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
CSVSummaryParser.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/CSVSummaryParser.java
/* * CSVSummaryParser.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.parsers; import jloda.swing.window.NotificationsInSwing; import jloda.util.*; import megan.classification.Classification; import megan.classification.ClassificationManager; import megan.classification.IdMapper; import megan.classification.IdParser; import megan.core.ClassificationType; import megan.core.DataTable; import megan.core.Document; import megan.core.SampleAttributeTable; import megan.viewer.MainViewer; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.*; /** * parses a CVS file containing a summary of one or multiple taxonomic dataset * Daniel Huson, 9.2010 */ public class CSVSummaryParser { /** * apply the importer parser to the named file. * Format should be: taxid,count[,count,...] * If the first line contains non-number tokens, then these are interpreted as the names of the datasets * */ static public void apply(String fileName, Document doc, String[] cNames, boolean tabSeparator, long multiplier) throws IOException { String separator = (tabSeparator ? "\t" : ","); System.err.println("Importing summary of " + StringUtils.toString(cNames, ", ") + " assignments from CSV file"); System.err.println("Specified line format: classname" + separator + "count{" + separator + "count" + separator + "count...}"); DataTable table = doc.getDataTable(); table.clear(); table.setCreator(ProgramProperties.getProgramName()); table.setCreationDate((new Date()).toString()); table.setAlgorithm(ClassificationType.Taxonomy.toString(), "Summary"); doc.getActiveViewers().clear(); doc.getActiveViewers().addAll(Arrays.asList(cNames)); final Set<Integer>[] knownIds = new HashSet[cNames.length]; for (int i = 0; i < cNames.length; i++) { knownIds[i] = new HashSet<>(); knownIds[i].addAll(ClassificationManager.get(cNames[i], true).getName2IdMap().getIds()); } IdParser[] idParsers = new IdParser[cNames.length]; int taxonomyIndex = -1; for (int i = 0; i < cNames.length; i++) { String cName = cNames[i]; idParsers[i] = ClassificationManager.get(cName, true).getIdMapper().createIdParser(); if (!cName.equals(Classification.Taxonomy)) { ClassificationManager.ensureTreeIsLoaded(cName); doc.getActiveViewers().add(cName); } else { taxonomyIndex = i; } idParsers[i].setUseTextParsing(true); } String[] names = null; final Map<Integer, float[]>[] class2counts = new HashMap[cNames.length]; Arrays.fill(class2counts, new HashMap<>()); float[][] total = new float[cNames.length][]; int[] add = null; int numberOfColumns = -1; int numberOfErrors = 0; boolean first = true; int warningUnrecognizedName = 0; int[] warnings = new int[cNames.length]; int numberOfLines = 0; try (FileLineIterator it = new FileLineIterator(fileName)) { while (it.hasNext()) { numberOfLines++; var aLine = it.next().trim(); if (aLine.isEmpty() || (!first && aLine.startsWith("#"))) continue; try { String[] tokens = aLine.split(separator); if (numberOfColumns == -1) { numberOfColumns = tokens.length; } else if (tokens.length != numberOfColumns) throw new IOException("Line " + it.getLineNumber() + ": incorrect number of columns, expected " + numberOfColumns + ", got: " + tokens.length + " (" + aLine + ")"); if (first) { if (tokens.length < 2) throw new IOException("Line " + it.getLineNumber() + ": incorrect number of columns, expected at least 2, got: " + tokens.length + " (" + aLine + ")"); boolean headerLinePresent = (StringUtils.getIndexIgnoreCase(tokens[0], "name", "names", "samples", "SampleId", SampleAttributeTable.SAMPLE_ID, "Dataset", "Datasets") != -1); if (!headerLinePresent) { // check other tokens: unless all are numbers, assume the first line is header line for (int i = 1; i < tokens.length; i++) { if (!NumberUtils.isFloat(tokens[i])) { headerLinePresent = true; break; } } } if (!headerLinePresent && tokens[0].startsWith("#")) { System.err.println("Skipping comment line: " + StringUtils.abbreviateDotDotDot(aLine, 80)); continue; } first = false; if (headerLinePresent) { names = new String[tokens.length - 1]; System.arraycopy(tokens, 1, names, 0, names.length); table.setSamples(names, null, null, null); } else if (tokens.length == 2) { names = new String[]{FileUtils.getFileBaseName((new File(fileName)).getName())}; } else { names = new String[tokens.length - 1]; for (int i = 0; i < names.length; i++) names[i] = "Sample" + (i + 1); } Arrays.fill(total, new float[names.length]); if (headerLinePresent) continue; // don't try to parse numbers from header line } // first if (add == null) add = new int[names.length]; for (int i = 1; i < tokens.length; i++) { String number = tokens[i].trim(); if (number.length() == 0) add[i - 1] = 0; else if (NumberUtils.isInteger(number)) add[i - 1] = (int) (multiplier * Integer.parseInt(number)); else add[i - 1] = (int) (multiplier * Double.parseDouble(number)); } boolean found = false; for (int i = 0; i < idParsers.length; i++) { int id; if ((i == taxonomyIndex || taxonomyIndex == -1) && NumberUtils.isInteger(tokens[0])) id = NumberUtils.parseInt(tokens[0]); else id = idParsers[i].getName2IdMap().get(tokens[0]); if (id == 0) id = idParsers[i].getIdFromHeaderLine(tokens[0]); if (id != 0) { found = true; if (knownIds[i].contains(id)) { float[] counts = getOrCreate(class2counts[i], id, names.length); addToArray(counts, add); addToArray(total[i], add); /* if(id>0) { System.err.println(tokens[0]+" -> "+id); } */ } else { if (warnings[i] < 50) { System.err.println("Warning: " + cNames[i] + " Unclassified item: " + tokens[0]); warnings[i]++; if (warnings[i] == 50) System.err.println("No further warnings"); } } } } if (!found) { if (warningUnrecognizedName < 50) { System.err.println("Unrecognized name: " + tokens[0]); warningUnrecognizedName++; if (warningUnrecognizedName == 50) System.err.println("No further warnings"); } for (int i = 0; i < idParsers.length; i++) { float[] counts = getOrCreate(class2counts[i], IdMapper.UNASSIGNED_ID, names.length); addToArray(counts, add); addToArray(total[i], add); } } } catch (Exception ex) { System.err.println("Error: " + ex + ", skipping"); numberOfErrors++; if(numberOfErrors>1000) throw new IOException("Too many errors"); } } } float[] sizes = new float[Objects.requireNonNull(names).length]; if (taxonomyIndex == -1) { System.arraycopy(total[0], 0, sizes, 0, sizes.length); final Map<Integer, float[]> unassigned = new HashMap<>(); unassigned.put(IdMapper.UNASSIGNED_ID, sizes); doc.getActiveViewers().add(Classification.Taxonomy); table.getClassification2Class2Counts().put(Classification.Taxonomy, unassigned); } else System.arraycopy(total[taxonomyIndex], 0, sizes, 0, sizes.length); table.setSamples(names, null, sizes, null); for (int i = 0; i < cNames.length; i++) { table.getClassification2Class2Counts().put(cNames[i], class2counts[i]); } doc.getSampleAttributeTable().setSampleOrder(Arrays.asList(names)); long totalReads = 0; for (float size : sizes) { totalReads += size; } table.setTotalReads(totalReads); doc.setNumberReads(totalReads); System.err.println("Number of lines read: " + numberOfLines); if (numberOfErrors > 0) NotificationsInSwing.showWarning(MainViewer.getLastActiveFrame(), "Number of lines skipped during import: " + numberOfErrors); for (int i = 0; i < cNames.length; i++) { System.err.println("Different " + (cNames[i].length() <= 4 ? cNames[i] : cNames[i].substring(0, 3) + ".") + " classes identified: " + class2counts[i].size()); } System.err.println("done (" + totalReads + " reads)"); } /** * get the entry, if it exists, otherwise create it and initialize to zeros * * @return entry */ private static float[] getOrCreate(Map<Integer, float[]> map, Integer id, int size) { float[] result = map.computeIfAbsent(id, k -> new float[size]); return result; } /** * add all values to sum * */ private static void addToArray(float[] sum, int[] add) { for (int i = 0; i < add.length; i++) { sum[i] += add[i]; } } /** * get the number of tokens per line in the file * * @return tokens per line or 0 */ public static int getTokensPerLine(File file, String separator) { int result = 0; BufferedReader r = null; try { r = new BufferedReader(new FileReader(file)); String aLine = r.readLine(); while (aLine != null && (aLine.trim().length() == 0 || aLine.trim().startsWith("#"))) aLine = r.readLine().trim(); if (aLine == null) return 0; else result = aLine.split(separator).length; } catch (Exception ignored) { } finally { if (r != null) try { r.close(); } catch (IOException ignored) { } } return result; } /** * guess whether the given file uses tab as the separator * * @return true, if first line contains tabs */ public static boolean guessTabSeparator(File file) { BufferedReader r = null; try { r = new BufferedReader(new FileReader(file)); String aLine = r.readLine(); while (aLine != null && (aLine.trim().length() == 0 || aLine.trim().startsWith("#"))) aLine = r.readLine().trim(); if (aLine != null) return aLine.contains("\t"); } catch (Exception ignored) { } finally { if (r != null) try { r.close(); } catch (IOException ignored) { } } return false; } }
13,089
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MAFSorter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/maf/MAFSorter.java
/* * MAFSorter.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.parsers.maf; import jloda.util.*; import jloda.util.progress.ProgressListener; import jloda.util.progress.ProgressPercentage; import java.io.*; import java.util.ArrayList; /** * sorts a MAF file, if necessary * Daniel Huson, October 2017 * todo: unfortunately, this doesn't work because alignments for a given read do not appear consecutively even within batches... */ public class MAFSorter { private static final Pair<String, String[]> start = new Pair<>("", new String[0]); private static final Pair<String, String[]> done = new Pair<>("", new String[0]); private static final String SORTED = "# Sorted"; private static final String BATCH = "# batch"; /** * apply the sorter * * @return name of temporary file containing all sorted alignments */ private static String apply(File readsFile, File mafFile, ProgressListener progress) throws IOException, CanceledException { if (isUnsorted(mafFile)) { String header = getHeaderLines(mafFile); return createSortedFile(header, readsFile, mafFile, progress); } else // is already sorted, so return this file return mafFile.getPath(); } /** * create a sorted file * * @return original file or new sorted file */ private static String createSortedFile(String fileHeader, File readsFile, File mafFile, ProgressListener progress) throws IOException, CanceledException { final ArrayList<Long> batchPositions = getBatchStartPositions(mafFile, progress); final int numberOfBatches = batchPositions.size(); if (numberOfBatches == 1) return mafFile.toString(); else System.err.println("Batches in MAF file: " + numberOfBatches); final ArrayList<BufferedReader> readers = getReaders(mafFile, batchPositions); final ArrayList<Pair<String, String[]>> nextMaf = new ArrayList<>(); for (int i = 0; i < numberOfBatches; i++) nextMaf.add(start); final File outputFile = new File(mafFile.getParent(), FileUtils.replaceFileSuffix(mafFile.getName(), "-sorted.maf.gz")); try (BufferedWriter w = new BufferedWriter(new OutputStreamWriter(FileUtils.getOutputStreamPossiblyZIPorGZIP(outputFile.getPath())))) { w.write(fileHeader); try { progress.setSubtask("Processing batches:"); progress.setProgress(0); try (FileLineIterator it = new FileLineIterator(readsFile)) { progress.setProgress(it.getMaximumProgress()); while (it.hasNext()) { final String line = it.next(); if (line.startsWith(">")) { final String name = StringUtils.getFirstWord(line.substring(1)); for (int i = 0; i < numberOfBatches; i++) { if (nextMaf.get(i) == start) { nextMaf.set(i, readNextMafRecord(readers.get(i))); } while (nextMaf.get(i).getFirst().equals(name)) { w.write("\n"); w.write(StringUtils.toString(nextMaf.get(i).getSecond(), "\n")); w.write("\n"); nextMaf.set(i, readNextMafRecord(readers.get(i))); } } } progress.setProgress(it.getProgress()); } } if (progress instanceof ProgressPercentage) { progress.reportTaskCompleted(); } for (int i = 0; i < nextMaf.size(); i++) { final Pair<String, String[]> pair = nextMaf.get(i); if (pair != done) { System.err.println("Error: not all MAF records in batch " + i + " processed, e.g:\n" + StringUtils.toString(pair.getSecond(), "\n")); } } } finally { for (BufferedReader r : readers) { try { r.close(); } catch (IOException ex) { Basic.caught(ex); } } } } return outputFile.getPath(); } /** * gets the next MAF record * Format: * a score=159 EG2=1e-08 E=4.3e-17 * s WP_005682092.1 18 33 + 516 SAEANENERRWNDDKIDRKNQDSTNNYDKTRMK * s HISEQ:457:C5366ACXX:2:1101:2641:2226 1 99 + 100 TAEANENERHWNDDKIERKNQDPTNHYDKSRMR * * * */ private static Pair<String, String[]> readNextMafRecord(BufferedReader r) throws IOException { String aLine; while ((aLine = r.readLine()) != null) { if (aLine.startsWith("a")) { String s2 = r.readLine(); String s3 = r.readLine(); String name = StringUtils.getFirstWord(s3.substring((2))); return new Pair<>(name, new String[]{aLine, s2, s3}); } else if (aLine.startsWith(BATCH)) break; } return done; } /** * get the header lines from a maf file * * @return header lines */ private static String getHeaderLines(File mafFile) throws IOException { final StringBuilder buf = new StringBuilder(); try (FileLineIterator it = new FileLineIterator(mafFile)) { while (it.hasNext()) { final String aLine = it.next(); if (aLine.startsWith("#")) { if (!aLine.startsWith(BATCH)) buf.append(aLine).append("\n"); } else break; } } buf.append(SORTED).append("\n"); return buf.toString(); } /** * determines whether this is an unsorted file * * @return true, if not sorted */ private static boolean isUnsorted(File mafFile) throws IOException { try (FileLineIterator it = new FileLineIterator(mafFile)) { while (it.hasNext()) { String line = it.next(); if (line.startsWith("#")) { if (line.equals(SORTED)) return false; if (line.startsWith(BATCH)) return true; // is unsorted } else return false; } } return true; } /** * locate all batch start positions * */ private static ArrayList<Long> getBatchStartPositions(File mafFile, ProgressListener progress) throws IOException, CanceledException { progress.setSubtask("Determining batches in MAF file"); final ArrayList<Long> batchStartPositions = new ArrayList<>(); try (FileLineIterator it = new FileLineIterator(mafFile)) { progress.setMaximum(it.getMaximumProgress()); progress.setProgress(0); while (it.hasNext()) { String aLine = it.next(); if (aLine.startsWith(BATCH)) batchStartPositions.add(it.getPosition() + BATCH.length()); progress.setProgress(it.getProgress()); } } if (progress instanceof ProgressPercentage) { progress.reportTaskCompleted(); } return batchStartPositions; } /** * get a reader for each given position * * @return readers */ private static ArrayList<BufferedReader> getReaders(File mafFile, ArrayList<Long> positions) throws IOException { final ArrayList<BufferedReader> readers = new ArrayList<>(positions.size()); for (Long position : positions) { FileInputStream ins = new FileInputStream(mafFile); long skipped = 0; while (skipped < position) { skipped += ins.skip(position - skipped); } readers.add(new BufferedReader(new InputStreamReader(ins))); } return readers; } public static void main(String[] args) throws Exception { String mafFile = "/Users/huson/data/long-reads/nus-march2017/Anammox-R4-MinION.maf"; String readsFile = "/Users/huson/data/long-reads/nus-march2017/Anammox-R4-MinION.fasta"; String result = apply(new File(readsFile), new File(mafFile), new ProgressPercentage()); System.err.println("Result: " + result); } }
9,137
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ISAMIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/ISAMIterator.java
/* * ISAMIterator.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.parsers.blast; import java.io.IOException; /** * iterator for SAM format * Daniel Huson 4.2015 */ public interface ISAMIterator { /** * gets the next matches * * @return number of matches */ int next(); /** * is there more data? * * @return true, if more data available */ boolean hasNext(); /** * gets the matches text * * @return matches text */ byte[] getMatchesText(); byte[] getQueryText(); /** * length of matches text * * @return length of text */ int getMatchesTextLength(); long getMaximumProgress(); long getProgress(); void close() throws IOException; /** * are we parsing long reads? * */ void setParseLongReads(boolean longReads); boolean isParseLongReads(); }
1,662
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
LastMAF2SAMIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/LastMAF2SAMIterator.java
/* * LastMAF2SAMIterator.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.parsers.blast; import jloda.seq.BlastMode; import jloda.swing.window.NotificationsInSwing; import jloda.util.NumberUtils; import jloda.util.Pair; import jloda.util.StringUtils; import jloda.util.interval.Interval; import jloda.util.interval.IntervalTree; import megan.util.LastMAFFileFilter; import java.io.IOException; import java.util.TreeSet; /** * parses a LAST MAF files into SAM format * Daniel Huson, 2.2017 */ public class LastMAF2SAMIterator extends SAMIteratorBase implements ISAMIterator { private final Pair<byte[], Integer> matchesTextAndLength = new Pair<>(new byte[10000], 0); private final BlastMode blastMode; private final TreeSet<Match> matches = new TreeSet<>(new Match()); private final IntervalTree<Match> matchesIntervalTree = new IntervalTree<>(); private double lambda = -1; private double K = -1; private final String[] mafMatch = new String[3]; /** * constructor * */ protected LastMAF2SAMIterator(String fileName, int maxNumberOfMatchesPerRead, BlastMode blastMode) throws IOException { super(fileName, maxNumberOfMatchesPerRead); this.blastMode = blastMode; if (!LastMAFFileFilter.getInstance().accept(fileName)) { NotificationsInSwing.showWarning("Might not be a LAST file in MAF format: " + fileName); } while (hasNextLine()) { String line = nextLine(); String str = getNextToken(line, "lambda="); if (NumberUtils.isDouble(str)) { lambda = NumberUtils.parseDouble(str); str = getNextToken(line, "K="); K = NumberUtils.parseDouble(str); break; } } if (lambda == -1 || K == -1) throw new IOException("Failed to parse lambda and K"); moveToNextMAFMatch(); } /** * is there more data? * * @return true, if more data available */ @Override public boolean hasNext() { return mafMatch[0] != null; } /** * gets the next matches * * @return number of matches */ public int next() { if (mafMatch[0] == null) return -1; // at end of file final String firstQueryName; { firstQueryName = getNextToken(mafMatch[2], "s").trim(); } int matchId = 0; // used to distinguish between matches when sorting matches.clear(); matchesTextAndLength.setSecond(0); matchesIntervalTree.clear(); // get all matches for given query: try { while (true) { if (mafMatch[2] != null && getNextToken(mafMatch[2], "s").trim().equals(firstQueryName)) { final String[] queryTokens = StringUtils.splitOnWhiteSpace(mafMatch[2]); /* a score=159 EG2=1e-08 E=4.3e-17 s WP_005682092.1 18 33 + 516 SAEANENERRWNDDKIDRKNQDSTNNYDKTRMK s HISEQ:457:C5366ACXX:2:1101:2641:2226 1 99 + 100 TAEANENERHWNDDKIERKNQDPTNHYDKSRMR */ final String queryAligned = queryTokens[6]; int queryStart = NumberUtils.parseInt(queryTokens[2]) + 1; final int queryAlignmentLength = NumberUtils.parseInt(queryTokens[3]); final boolean queryReversed = !queryTokens[4].equals("+"); final int queryLength = NumberUtils.parseInt(queryTokens[5]); int queryEnd; final int frame = (queryReversed ? -1 : 1) * ((queryStart - 1) % 3 + 1); // do this before changing start to reflect reversed sequence if (queryReversed) { queryStart = queryLength - queryStart + 1; queryEnd = queryStart - queryAlignmentLength + 1; } else { queryEnd = queryStart + queryAlignmentLength - 1; } final String scoreLine = mafMatch[0]; final int rawScore = NumberUtils.parseInt(getNextToken(scoreLine, "score=")); final double expect = NumberUtils.parseDouble(getNextToken(scoreLine, "E=")); final float bitScore = (float) ((lambda * rawScore - Math.log(K)) / Math.log(2)); final String[] subjTokens = StringUtils.splitOnWhiteSpace(mafMatch[1]); final String subjName = subjTokens[1]; final String subjAligned = subjTokens[6]; int subjStart = NumberUtils.parseInt(subjTokens[2]) + 1; final int subjAlignmentLength = NumberUtils.parseInt(subjTokens[3]); final boolean subjReversed = !subjTokens[4].equals("+"); final int subjLength = NumberUtils.parseInt(subjTokens[5]); int subjEnd; if (subjReversed) { subjStart = subjLength - subjStart; subjEnd = subjStart - subjAlignmentLength + 1; } else { subjEnd = subjStart + subjAlignmentLength - 1; } final float percentIdentities; { final int nCompared = Math.min(queryAligned.length(), subjAligned.length()); if (nCompared > 0) { int same = 0; for (int i = 0; i < nCompared; i++) if (queryAligned.charAt(i) == subjAligned.charAt(i)) same++; percentIdentities = (float) same / (float) nCompared; } else percentIdentities = 0; } if (isParseLongReads()) { // when parsing long reads we keep alignments based on local critera Match match = new Match(); match.bitScore = bitScore; match.id = matchId++; if (blastMode == BlastMode.BlastN) match.samLine = BlastN2SAMIterator.makeSAM(firstQueryName, queryReversed ? "Minus" : "Plus", subjName, subjLength, subjReversed ? "Minus" : "Plus", bitScore, (float) expect, rawScore, percentIdentities, queryStart, queryEnd, subjStart, subjEnd, queryAligned, subjAligned); else match.samLine = BlastX2SAMIterator.makeSAM(firstQueryName, subjName, subjLength, bitScore, (float) expect, rawScore, percentIdentities, frame, queryStart, queryEnd, subjStart, subjEnd, queryAligned, subjAligned); matchesIntervalTree.add(new Interval<>(queryStart, queryEnd, match)); } else { if (matches.size() < getMaxNumberOfMatchesPerRead() || bitScore > matches.last().bitScore) { Match match = new Match(); match.bitScore = bitScore; match.id = matchId++; if (blastMode == BlastMode.BlastN) match.samLine = BlastN2SAMIterator.makeSAM(firstQueryName, queryReversed ? "Minus" : "Plus", subjName, subjLength, subjReversed ? "Minus" : "Plus", bitScore, (float) expect, rawScore, percentIdentities, queryStart, queryEnd, subjStart, subjEnd, queryAligned, subjAligned); else match.samLine = BlastX2SAMIterator.makeSAM(firstQueryName, subjName, subjLength, bitScore, (float) expect, rawScore, percentIdentities, frame, queryStart, queryEnd, subjStart, subjEnd, queryAligned, subjAligned); matches.add(match); if (matches.size() > getMaxNumberOfMatchesPerRead()) matches.remove(matches.last()); } } moveToNextMAFMatch(); } else // new query or last alignment, in either case return { break; } } } catch (Exception ex) { System.err.println("Error parsing file near line: " + getLineNumber() + ": " + ex.getMessage()); if (incrementNumberOfErrors() >= getMaxNumberOfErrors()) throw new RuntimeException("Too many errors"); } return getPostProcessMatches().apply(firstQueryName, matchesTextAndLength, isParseLongReads(), matchesIntervalTree, matches, null); } /** * move to the next MAF match */ private void moveToNextMAFMatch() { mafMatch[0] = getNextLineStartsWith("a "); if (mafMatch[0] != null) { mafMatch[1] = getNextLineStartsWith("s "); if (mafMatch[1] != null) mafMatch[2] = getNextLineStartsWith("s "); } if (mafMatch[0] == null || mafMatch[1] == null || mafMatch[2] == null) { mafMatch[0] = mafMatch[1] = mafMatch[2] = null; } } /** * gets the matches text * * @return matches text */ @Override public byte[] getMatchesText() { return matchesTextAndLength.getFirst(); } /** * length of matches text * * @return length of text */ @Override public int getMatchesTextLength() { return matchesTextAndLength.getSecond(); } }
10,406
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BlastModeUtils.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/BlastModeUtils.java
/* * BlastModeUtils.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.parsers.blast; import jloda.seq.BlastMode; import jloda.swing.util.FastaFileFilter; import jloda.swing.util.ProgramProperties; import jloda.util.Basic; import jloda.util.FileLineIterator; import megan.daa.io.DAAParser; import megan.util.*; import javax.swing.*; import java.awt.*; import java.io.IOException; /** * possible blast modes * Daniel Huson, 1.2014 */ public class BlastModeUtils { /** * gets the value of a label ignoring case * * @return value or null */ private static BlastMode valueOfIgnoreCase(String label) { for (BlastMode type : BlastMode.values()) if (label.equalsIgnoreCase(type.toString())) return type; return null; } /** * gets the blast mode for a given file * * @return blast mode or null */ public static BlastMode getBlastMode(String fileName) { if (SAMFileFilter.getInstance().accept(fileName)) return determineBlastModeSAMFile(fileName); else if (DAAFileFilter.getInstance().accept(fileName)) return DAAParser.getBlastMode(fileName); else if (BlastXTextFileFilter.getInstance().accept(fileName)) return BlastMode.BlastX; else if (BlastNTextFileFilter.getInstance().accept(fileName)) return BlastMode.BlastN; else if (BlastPTextFileFilter.getInstance().accept(fileName)) return BlastMode.BlastP; else if (BlastTabFileFilter.getInstance().accept(fileName)) return BlastMode.Unknown; if (LastMAFFileFilter.getInstance().accept(fileName)) return BlastMode.Unknown; else if (BlastXMLFileFilter.getInstance().accept(fileName)) return determineBlastModeXMLFile(fileName); else if (RAPSearch2AlnFileFilter.getInstance().accept(fileName)) return BlastMode.BlastX; else if (RDPAssignmentDetailsFileFilter.getInstance().accept(fileName)) return BlastMode.Classifier; else if (IlluminaReporterFileFilter.getInstance().accept(fileName)) return BlastMode.Classifier; else if (RDPStandaloneFileFilter.getInstance().accept(fileName)) return BlastMode.Classifier; else if (FastaFileFilter.getInstance().accept(fileName)) return BlastMode.Classifier; else if (MothurFileFilter.getInstance().accept(fileName)) return BlastMode.Classifier; else return BlastMode.Unknown; } /** * Determine the alignment mode * * @return file format or null */ public static BlastMode detectMode(Component owner, String filename, boolean ask) throws IOException { BlastMode mode = getBlastMode(filename); if (mode == BlastMode.Unknown && ask) { if (!ProgramProperties.isUseGUI()) throw new IOException("Couldn't detect BLAST mode, please specify"); mode = (BlastMode) JOptionPane.showInputDialog(owner, "Cannot determine mode, please choose:", "Question: Which mode?", JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon(), BlastMode.values(), BlastMode.BlastX); } return mode; } /** * determine blast mode of a SAM file * * @return blast mode */ public static BlastMode determineBlastModeSAMFile(String samFile) { try (final FileLineIterator it = new FileLineIterator(samFile)) { for (int i = 0; i < 50; i++) { // expect to figure out blast mode within the first 50 lines if (it.hasNext()) { String aLine = it.next().trim(); if (aLine.startsWith("@PG")) { String[] tokens = aLine.split("\t"); for (String token : tokens) { if (token.startsWith("DS:") && token.length() > 3) { BlastMode mode = valueOfIgnoreCase(token.substring(3)); if (mode != null) return mode; } } } // this is for backward compatibility: if (aLine.startsWith("@mm")) { String[] tokens = aLine.split("\t"); if (tokens.length >= 2) { BlastMode mode = valueOfIgnoreCase(tokens[1]); if (mode != null) return mode; } } } } } catch (Exception ex) { Basic.caught(ex); } return BlastMode.BlastN; } /** * determine the blast mode for an XML file * * @return blast mode */ private static BlastMode determineBlastModeXMLFile(String xmlFile) { try (final FileLineIterator it = new FileLineIterator(xmlFile)) { for (int i = 0; i < 50; i++) { // expect to figure out blast mode within the first 50 lines if (it.hasNext()) { String line = it.next().trim().toLowerCase(); if (line.startsWith("<blastoutput_program>") || line.startsWith("<blastoutput_version>")) { if (line.contains("blastn")) return BlastMode.BlastN; else if (line.contains("blastx")) return BlastMode.BlastX; else if (line.contains("blastp")) return BlastMode.BlastP; } } } } catch (Exception ex) { Basic.caught(ex); } return BlastMode.Unknown; } /** * gets the value ignoring case * * @return value or null */ public static BlastMode valueOfIgnoringCase(String formatName) { if (formatName != null) { for (BlastMode format : BlastMode.values()) { if (format.toString().equalsIgnoreCase(formatName)) return format; } } return null; } /** * set of all values except 'Unknown' * */ public static BlastMode[] valuesExceptUnknown() { BlastMode[] array = new BlastMode[BlastMode.values().length - 1]; int i = -0; for (BlastMode value : BlastMode.values()) { if (value != BlastMode.Unknown) array[i++] = value; } return array; } }
6,543
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IteratorManager.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/IteratorManager.java
/* * IteratorManager.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.parsers.blast; import jloda.seq.BlastMode; import megan.daa.io.DAA2SAMIterator; import java.io.IOException; /** * manages the alignment file iterators * Daniel Huson, 4.2015 */ public class IteratorManager { /** * gets the iterator for the given file, format and blastMode * * @return iterator */ public static ISAMIterator getIterator(String blastFile, BlastFileFormat format, BlastMode blastMode, int maxMatchesPerRead, boolean longReads) throws IOException { final ISAMIterator iterator; if (format == BlastFileFormat.SAM) iterator = new SAM2SAMIterator(blastFile, maxMatchesPerRead, blastMode); else if (format == BlastFileFormat.DAA) { iterator = new DAA2SAMIterator(blastFile, maxMatchesPerRead, longReads); } else if (format == BlastFileFormat.BlastText && blastMode == BlastMode.BlastX) iterator = new BlastX2SAMIterator(blastFile, maxMatchesPerRead); else if (format == BlastFileFormat.BlastText && blastMode == BlastMode.BlastP) iterator = new BlastP2SAMIterator(blastFile, maxMatchesPerRead); else if (format == BlastFileFormat.BlastText && blastMode == BlastMode.BlastN) iterator = new BlastN2SAMIterator(blastFile, maxMatchesPerRead); else if (format == BlastFileFormat.BlastXML) iterator = new BlastXML2SAMIterator(blastFile, maxMatchesPerRead); else if (format == BlastFileFormat.BlastTab) iterator = new BlastTab2SAMIterator(blastFile, maxMatchesPerRead); else if (format == BlastFileFormat.LastMAF) iterator = new LastMAF2SAMIterator(blastFile, maxMatchesPerRead, blastMode); else if (format == BlastFileFormat.RapSearch2Aln && blastMode == BlastMode.BlastX) iterator = new RAPSearchAln2SAMIterator(blastFile, maxMatchesPerRead); else if (format == BlastFileFormat.RDPAssignmentDetails) iterator = new RDPAssignmentDetails2SAMIterator(blastFile, maxMatchesPerRead); else if (format == BlastFileFormat.IlluminaReporter) iterator = new IlluminaReporter2SAMIterator(blastFile, maxMatchesPerRead); else if (format == BlastFileFormat.RDPStandalone) iterator = new RDPStandalone2SAMIterator(blastFile, maxMatchesPerRead); else if (format == BlastFileFormat.References_as_FastA) iterator = new Fasta2SAMIterator(blastFile, maxMatchesPerRead); else if (format == BlastFileFormat.Mothur) iterator = new Mothur2SAMIterator(blastFile, maxMatchesPerRead); else throw new IOException("Unsupported combination of file format: " + format + " and alignment mode: " + blastMode); iterator.setParseLongReads(longReads); return iterator; } }
3,624
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
PostProcessMatches.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/PostProcessMatches.java
/* * PostProcessMatches.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.parsers.blast; import jloda.swing.util.ProgramProperties; import jloda.util.Basic; import jloda.util.Pair; import jloda.util.interval.Interval; import jloda.util.interval.IntervalTree; import java.util.List; import java.util.Set; /** * post process set of parsed matches * Daniel Huson, Feb 2017 */ public class PostProcessMatches { private final static float defaultMinPercentToCoverToStronglyDominate = 90f; private final static float defaultTopPercentScoreToStronglyDominate = 90f; private float minProportionCoverToStronglyDominate = Math.min(1f, (float) ProgramProperties.get("MinPercentCoverToStronglyDominate", defaultMinPercentToCoverToStronglyDominate) / 100.0f); private float topProportionScoreToStronglyDominate = Math.min(1f, (float) ProgramProperties.get("TopPercentScoreToStronglyDominate", defaultTopPercentScoreToStronglyDominate) / 100.0f); private boolean parseLongReads = false; /** * constructor */ public PostProcessMatches() { } /** * post process set of parsed matches * * @return number of matches returned */ public int apply(String queryName, Pair<byte[], Integer> matchesTextAndLength, boolean parseLongReads, IntervalTree<Match> matchesIntervalTree, Set<Match> matches, List<Match> listOfMatches) { if (listOfMatches != null && listOfMatches.size() > 0) // this overrides all other considerations { byte[] matchesText = matchesTextAndLength.getFirst(); int matchesTextLength = 0; for (Match match : listOfMatches) { byte[] bytes = match.samLine.getBytes(); if (matchesTextLength + bytes.length + 1 >= matchesText.length) { byte[] tmp = new byte[2 * (matchesTextLength + bytes.length + 1)]; System.arraycopy(matchesText, 0, tmp, 0, matchesTextLength); matchesText = tmp; } System.arraycopy(bytes, 0, matchesText, matchesTextLength, bytes.length); matchesTextLength += bytes.length; matchesText[matchesTextLength++] = '\n'; } matchesTextAndLength.set(matchesText, matchesTextLength); //System.err.println("Match: "+ Basic.toString(matchesText,0,matchesTextAndLength.getSecond())); return matches.size(); } if (parseLongReads && matchesIntervalTree != null) { matches.clear(); for (Interval<Match> interval : matchesIntervalTree) { final Match match = interval.getData(); boolean covered = false; for (Interval<Match> other : matchesIntervalTree.getIntervals(interval)) { final Match otherMatch = other.getData(); if (other.overlap(interval) > minProportionCoverToStronglyDominate * interval.length() && topProportionScoreToStronglyDominate * otherMatch.bitScore > match.bitScore) { covered = true; break; } } if (!covered) matches.add(interval.getData()); } } byte[] matchesText = matchesTextAndLength.getFirst(); int matchesTextLength = 0; if (matches.size() == 0) { // no matches, so return query name only if (queryName.length() > matchesTextAndLength.getFirst().length) { matchesTextAndLength.setFirst(new byte[2 * queryName.length()]); } for (int i = 0; i < queryName.length(); i++) { matchesTextAndLength.getFirst()[matchesTextLength++] = (byte) queryName.charAt(i); } matchesTextAndLength.getFirst()[matchesTextLength++] = '\n'; matchesTextAndLength.set(matchesText, matchesTextLength); return 0; } else { // short reads for (Match match : matches) { final byte[] bytes = match.samLine.getBytes(); final long newLength=matchesTextLength + bytes.length + 1L; if (newLength >= matchesText.length) { if (newLength>Basic.MAX_ARRAY_SIZE) throw new RuntimeException("Data record size exceeds max array size: "+newLength); final byte[] tmp = new byte[(int)(Math.min(Basic.MAX_ARRAY_SIZE,2L * newLength))]; System.arraycopy(matchesText, 0, tmp, 0, matchesTextLength); matchesText = tmp; } System.arraycopy(bytes, 0, matchesText, matchesTextLength, bytes.length); matchesTextLength += bytes.length; matchesText[matchesTextLength++] = '\n'; } matchesTextAndLength.set(matchesText, matchesTextLength); //System.err.println("Match: "+ Basic.toString(matchesText,0,matchesTextAndLength.getSecond())); return matches.size(); } } public float getMinProportionCoverToStronglyDominate() { return minProportionCoverToStronglyDominate; } public float getTopProportionScoreToStronglyDominate() { return topProportionScoreToStronglyDominate; } public boolean isParseLongReads() { return parseLongReads; } public void setParseLongReads(boolean parseLongReads) { this.parseLongReads = parseLongReads; if (parseLongReads) { final float minPercentCoverToStronglyDominate = (float) ProgramProperties.get("MinPercentCoverToStronglyDominate", defaultMinPercentToCoverToStronglyDominate); if (minPercentCoverToStronglyDominate != defaultMinPercentToCoverToStronglyDominate) System.err.println("Using MinPercentCoverToStonglyDominate=" + minPercentCoverToStronglyDominate); minProportionCoverToStronglyDominate = minPercentCoverToStronglyDominate / 100.0f; final float topPercentScoreToStronglyDominate = (float) ProgramProperties.get("TopPercentScoreToStronglyDominate", defaultTopPercentScoreToStronglyDominate); if (topPercentScoreToStronglyDominate != defaultTopPercentScoreToStronglyDominate) System.err.println("Using TopPercentScoreToStronglyDominate=" + topPercentScoreToStronglyDominate); topProportionScoreToStronglyDominate = topPercentScoreToStronglyDominate / 100.0f; System.err.printf("Input domination filter: MinPercentCoverToStronglyDominate=%.1f and TopPercentScoreToStronglyDominate=%.1f%n", minPercentCoverToStronglyDominate, topPercentScoreToStronglyDominate); } } }
7,471
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Match.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/Match.java
/* * Match.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.parsers.blast; import java.util.Comparator; /** * use this to sort matches * Daniel Huson, 2016 */ public class Match implements Comparator<Match> { float bitScore; int id; String samLine; @Override public int compare(Match a, Match b) { if (a.bitScore > b.bitScore) return -1; else if (a.bitScore < b.bitScore) return 1; else return Integer.compare(a.id, b.id); } public float getBitScore() { return bitScore; } public void setBitScore(float bitScore) { this.bitScore = bitScore; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getSamLine() { return samLine; } public void setSamLine(String samLine) { this.samLine = samLine; } }
1,673
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IlluminaReporter2SAMIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/IlluminaReporter2SAMIterator.java
/* * IlluminaReporter2SAMIterator.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.parsers.blast; import jloda.swing.window.NotificationsInSwing; import jloda.util.NumberUtils; import jloda.util.Pair; import jloda.util.StringUtils; import megan.util.IlluminaReporterFileFilter; import java.io.IOException; import java.util.TreeSet; /** * parses a Illumina reporter output into SAM format * <p> * Format: * >M03141:11:000000000-AKT4M:1:1101:8857:1086 * Bacteria;1.00;Bacteroidetes;1.00;Bacteroidia;1.00;Bacteroidales;1.00;Bacteroidaceae;1.00;Bacteroides;1.00;stercorirosoris;0.98 * >M03141:11:000000000-AKT4M:1:1101:10834:1096 * Bacteria;1.00;Firmicutes;1.00;Clostridia;1.00;Clostridiales;1.00;;1.00;;1.00;;0.98 * <p> * Daniel Huson, 1.2016 */ public class IlluminaReporter2SAMIterator extends SAMIteratorBase implements ISAMIterator { private final TreeSet<Match> matches = new TreeSet<>(new Match()); private final Pair<byte[], Integer> matchesTextAndLength = new Pair<>(new byte[10000], 0); /** * constructor * */ public IlluminaReporter2SAMIterator(String fileName, int maxNumberOfMatchesPerRead) throws IOException { super(fileName, maxNumberOfMatchesPerRead); if (!IlluminaReporterFileFilter.getInstance().accept(fileName)) { NotificationsInSwing.showWarning("Might not be in Illumina reporter format: " + fileName); } } /** * is there more data? * * @return true, if more data available */ @Override public boolean hasNext() { return hasNextLine(); } /** * gets the next matches * * @return number of matches */ public int next() { if (!hasNextLine()) return -1; matchesTextAndLength.setSecond(0); String line = nextLine(); while (hasNextLine() && !line.startsWith(">")) { line = nextLine(); } if (line == null || !line.startsWith(">")) return -1; final String queryName = StringUtils.getReadName(line); if (!hasNextLine()) return -1; line = nextLine(); final String[] tokens = StringUtils.split(line, ';'); int matchId = 0; // used to distinguish between matches when sorting matches.clear(); StringBuilder path = new StringBuilder(); // add one match block for each percentage given: try { path.append("root").append(";"); int whichToken = 0; while (whichToken < tokens.length && tokens[whichToken].length() > 0) { String name = tokens[whichToken++]; if (whichToken >= 2 && Character.isLowerCase(name.charAt(0)) && whichToken == tokens.length - 1) name = tokens[whichToken - 3] + " " + name; // make binomial name if (!name.equalsIgnoreCase("root")) path.append(name).append(";"); String ref = StringUtils.toString(tokens, 0, whichToken, ";") + ";"; String scoreString = tokens[whichToken++]; float bitScore = 100 * NumberUtils.parseFloat(scoreString); if (matches.size() < getMaxNumberOfMatchesPerRead() || bitScore > matches.last().bitScore) { Match match = new Match(); match.bitScore = bitScore; match.id = matchId++; match.samLine = makeSAM(queryName, path.toString(), bitScore, ref); matches.add(match); if (matches.size() > getMaxNumberOfMatchesPerRead()) matches.remove(matches.last()); } } } catch (Exception ex) { System.err.println("Error parsing file near line: " + getLineNumber()); if (incrementNumberOfErrors() >= getMaxNumberOfErrors()) throw new RuntimeException("Too many errors"); } return getPostProcessMatches().apply(queryName, matchesTextAndLength, isParseLongReads(), null, matches, null); } /** * gets the matches text * * @return matches text */ @Override public byte[] getMatchesText() { return matchesTextAndLength.getFirst(); } /** * length of matches text * * @return length of text */ @Override public int getMatchesTextLength() { return matchesTextAndLength.getSecond(); } /** * make a SAM line */ private String makeSAM(String queryName, String refName, float bitScore, String line) { return String.format("%s\t0\t%s\t0\t255\t*\t*\t0\t0\t*\t*\tAS:i:%d\t", queryName, refName, Math.round(bitScore)) + String.format("AL:Z:%s\t", StringUtils.replaceSpaces(line, ' ')); } }
5,507
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
RAPSearchAln2SAMIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/RAPSearchAln2SAMIterator.java
/* * RAPSearchAln2SAMIterator.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.parsers.blast; import jloda.swing.window.NotificationsInSwing; import jloda.util.NumberUtils; import jloda.util.Pair; import jloda.util.StringUtils; import jloda.util.interval.Interval; import jloda.util.interval.IntervalTree; import megan.util.RAPSearch2AlnFileFilter; import java.io.IOException; import java.util.TreeSet; /** * parses a RAPSearch2 ALN files into SAM format * Daniel Huson, 4.2015 */ public class RAPSearchAln2SAMIterator extends SAMIteratorBase implements ISAMIterator { private final static String vsString = " vs "; private final Pair<byte[], Integer> matchesTextAndLength = new Pair<>(new byte[10000], 0); private final TreeSet<Match> matches = new TreeSet<>(new Match()); private final IntervalTree<Match> matchesIntervalTree = new IntervalTree<>(); /** * constructor * */ public RAPSearchAln2SAMIterator(String fileName, int maxNumberOfMatchesPerRead) throws IOException { super(fileName, maxNumberOfMatchesPerRead); if (!RAPSearch2AlnFileFilter.getInstance().accept(fileName)) { NotificationsInSwing.showWarning("Might not be a RapSearch2 .aln file: " + fileName); } } /** * is there more data? * * @return true, if more data available */ @Override public boolean hasNext() { return hasNextLine(); } /** * gets the next matches * * @return number of matches */ public int next() { String queryLine = getNextLineContains(vsString); if (queryLine == null) return -1; // at end of file final String queryName = StringUtils.swallowLeadingGreaterSign(StringUtils.getFirstWord(queryLine)); pushBackLine(queryLine); int matchId = 0; // used to distinguish between matches when sorting matches.clear(); matchesTextAndLength.setSecond(0); matchesIntervalTree.clear(); // get all matches for given query: try { while (hasNextLine()) { queryLine = getNextLineContains(vsString); if (queryLine == null) break; // end of file String currentQueryName = StringUtils.swallowLeadingGreaterSign(StringUtils.getFirstWord(queryLine)); if (!currentQueryName.equals(queryName)) { pushBackLine(queryLine); // start of next query break; } final RapSearchMatch match = new RapSearchMatch(); match.parseHeader(queryLine); match.parseLines(nextLine(), nextLine(), nextLine()); if (isParseLongReads()) { // when parsing long reads we keep alignments based on local critera match.samLine = makeSAM(queryName, match.referenceName, -1, match.bitScore, match.expected, 0, match.identity, match.frame, match.queryStart, match.queryEnd, match.refStart, match.refEnd, match.querySequence, match.refSequence); matchesIntervalTree.add(new Interval<>(match.queryStart, match.queryEnd, match)); } else { if (matches.size() < getMaxNumberOfMatchesPerRead() || match.bitScore > matches.last().bitScore) { match.id = matchId++; match.samLine = makeSAM(queryName, match.referenceName, -1, match.bitScore, match.expected, 0, match.identity, match.frame, match.queryStart, match.queryEnd, match.refStart, match.refEnd, match.querySequence, match.refSequence); matches.add(match); if (matches.size() > getMaxNumberOfMatchesPerRead()) matches.remove(matches.last()); } } } } catch (Exception ex) { System.err.println("Error parsing file near line: " + getLineNumber()); if (incrementNumberOfErrors() >= getMaxNumberOfErrors()) throw new RuntimeException("Too many errors"); } return getPostProcessMatches().apply(queryName, matchesTextAndLength, isParseLongReads(), matchesIntervalTree, matches, null); } /** * /** * gets the matches text * * @return matches text */ @Override public byte[] getMatchesText() { return matchesTextAndLength.getFirst(); } /** * length of matches text * * @return length of text */ @Override public int getMatchesTextLength() { return matchesTextAndLength.getSecond(); } /** * make a SAM line */ private String makeSAM(String queryName, String refName, int referenceLength, float bitScore, float expect, int rawScore, float percentIdentity, int frame, int queryStart, int queryEnd, int referenceStart, int referenceEnd, String alignedQuery, String alignedReference) { if (alignedQuery.contains(".")) alignedQuery = alignedQuery.replaceAll("\\.", "X"); // if(alignedReference.contains(".")) // alignedReference=alignedReference.replaceAll("\\.","-"); final StringBuilder buffer = new StringBuilder(); buffer.append(queryName).append("\t"); buffer.append(0); buffer.append("\t"); buffer.append(refName).append("\t"); buffer.append(referenceStart).append("\t"); buffer.append("255\t"); Utilities.appendCigar(alignedQuery, alignedReference, buffer); buffer.append("\t"); buffer.append("*\t"); buffer.append("0\t"); buffer.append("0\t"); buffer.append(alignedQuery.replaceAll("-", "")).append("\t"); buffer.append("*\t"); buffer.append(String.format("AS:i:%d\t", Math.round(bitScore))); buffer.append(String.format("NM:i:%d\t", Utilities.computeEditDistance(alignedQuery, alignedReference))); buffer.append(String.format("ZL:i:%d\t", referenceLength)); buffer.append(String.format("ZR:i:%d\t", rawScore)); buffer.append(String.format("ZE:f:%g\t", expect)); buffer.append(String.format("ZI:i:%d\t", Math.round(percentIdentity))); buffer.append(String.format("ZF:i:%d\t", frame)); buffer.append(String.format("ZS:i:%s\t", queryStart)); Utilities.appendMDString(alignedQuery, alignedReference, buffer); return buffer.toString(); } /** * a rapsearch match */ static class RapSearchMatch extends Match { String readName; String referenceName; String referenceLine; int queryStart; int queryEnd; String querySequence; int refStart; int refEnd; String refSequence; float bitScore; float expected; int frame; int length; float identity; boolean isNoHit = false; final static String Query = "Query:"; final static String Subject = "Sbjct:"; final static String noHitString = "NO HIT"; final static String bitsString = "bits="; final static String evalueString = "log(E-value)="; final static String evalueStringAlt = "log(Evalue)="; final static String identityString = "identity="; final static String lengthString = "aln-len="; final static String lengthStringAlt = "alnlen="; final static String frameString = "nFrame="; /** * parses the header line. * */ void parseHeader(String aLine) throws IOException { referenceLine = aLine; int index = aLine.indexOf(vsString); if (index <= 0) { index = aLine.indexOf(noHitString); if (index <= 0) throw new IOException("Token 'vs' or 'NO HIT' not found in line: " + aLine); else isNoHit = true; } readName = aLine.substring(aLine.charAt(0) == '>' ? 1 : 0, index).trim(); if (isNoHit) return; String suffix = aLine.substring(index + vsString.length()).trim(); index = suffix.indexOf(" "); if (index <= 0) throw new IOException("Token ' ' not found after ' vs ' in line: " + aLine); referenceName = suffix.substring(0, index).trim(); suffix = suffix.substring(index + 1).trim(); String[] tokens = suffix.split(" "); if (tokens[0].startsWith(bitsString) && NumberUtils.isFloat(tokens[0].substring(bitsString.length()))) bitScore = Float.parseFloat(tokens[0].substring(bitsString.length())); else throw new IOException("Failed to parse '" + bitsString + "' in: " + aLine); if (tokens[1].startsWith(evalueString) && NumberUtils.isFloat(tokens[1].substring(evalueString.length()))) expected = (float) Math.pow(10, Float.parseFloat(tokens[1].substring(evalueString.length()))); else if (tokens[1].startsWith(evalueStringAlt) && NumberUtils.isFloat(tokens[1].substring(evalueStringAlt.length()))) expected = (float) Math.pow(10, Float.parseFloat(tokens[1].substring(evalueStringAlt.length()))); else throw new IOException("Failed to parse '" + evalueString + "' or '" + evalueStringAlt + "' in: " + aLine); if (tokens[2].startsWith(identityString) && NumberUtils.isFloat(tokens[2].substring(identityString.length(), tokens[2].length() - 1))) identity = Float.parseFloat(tokens[2].substring(identityString.length(), tokens[2].length() - 1)); else throw new IOException("Failed to parse '" + identityString + "' in: " + aLine); if (tokens[3].startsWith(lengthString) && NumberUtils.isInteger(tokens[3].substring(lengthString.length()))) length = Integer.parseInt(tokens[3].substring(lengthString.length())); else if (tokens[3].startsWith(lengthStringAlt) && NumberUtils.isInteger(tokens[3].substring(lengthStringAlt.length()))) length = Integer.parseInt(tokens[3].substring(lengthStringAlt.length())); else throw new IOException("Failed to parse '" + lengthString + "' or '" + lengthStringAlt + "' in: " + aLine); if (tokens[6].startsWith(frameString) && NumberUtils.isInteger(tokens[6].substring(frameString.length()))) { int f = Integer.parseInt(tokens[6].substring(frameString.length())); if (f < 3) frame = f + 1; // 0,1,2->1,2,3 else frame = f - 6; // 3,4,5-> -3, -2, -1 } else throw new IOException("Failed to parse '" + frameString + "' in: " + aLine); } /** * parse the lines containing the match * */ void parseLines(String queryLine, String midLine, String subjectLine) throws IOException { if (!queryLine.startsWith(Query)) throw new IOException("Token '" + Query + "' not found in line: " + queryLine); String[] queryTokens = queryLine.split("\\s+"); if (queryTokens.length != 4) throw new IOException("Wrong number of tokens: " + queryTokens.length + " in query line: " + queryLine); queryStart = NumberUtils.parseInt(queryTokens[1]); querySequence = queryTokens[2]; queryEnd = NumberUtils.parseInt(queryTokens[3]); if (!subjectLine.startsWith(Subject)) throw new IOException("Token '" + Subject + "' not found in line: " + midLine); String[] subjTokens = subjectLine.split("\\s+"); if (subjTokens.length != 4) throw new IOException("Wrong number of tokens: " + subjTokens.length + " in subject line: " + subjectLine); refStart = NumberUtils.parseInt(subjTokens[1]); refSequence = subjTokens[2]; refEnd = NumberUtils.parseInt(subjTokens[3]); } } }
12,865
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Utilities.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/Utilities.java
/* * Utilities.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.parsers.blast; /** * some utilities * Daniel Huson, 4.2016 */ public class Utilities { /** * append the cigar string * */ public static void appendCigar(String alignedQuery, String alignedReference, StringBuilder buffer) { char cigarState = 'M'; // M in match, D deletion, I insertion int count = 0; for (int i = 0; i < alignedQuery.length(); i++) { if (alignedQuery.charAt(i) == '-') { if (cigarState == 'D') { count++; } else if (count > 0) { buffer.append(count).append(cigarState); cigarState = 'D'; count = 1; } } else if (alignedReference.charAt(i) == '-') { if (cigarState == 'I') { count++; } else if (count > 0) { buffer.append(count).append(cigarState); cigarState = 'I'; count = 1; } } else { // match or mismatch if (cigarState == 'M') { count++; } else if (count > 0) { buffer.append(count).append(cigarState); cigarState = 'M'; count = 1; } } } if (count > 0) { buffer.append(count).append(cigarState); } } /** * append the MD string * */ public static void appendMDString(final String alignedQuery, final String alignedReference, final StringBuilder buffer) { buffer.append("MD:Z:"); int countMatches = 0; boolean inDeletion = false; for (int i = 0; i < alignedQuery.length(); i++) { final char qChar = alignedQuery.charAt(i); final char rChar = alignedReference.charAt(i); if (qChar == '-') { // gap in query if (countMatches > 0) { buffer.append(countMatches); countMatches = 0; } if (!inDeletion) { buffer.append("^"); inDeletion = true; } buffer.append(rChar); } else if (rChar != '-') { // match or mismatch if (qChar == rChar) { countMatches++; } else { if (inDeletion) buffer.append("0"); if (countMatches > 0) { buffer.append(countMatches); countMatches = 0; } buffer.append(rChar); } if (inDeletion) inDeletion = false; } // else alignedReference[i] == '-': this has no effect } if (countMatches > 0) buffer.append(countMatches); else if (inDeletion) buffer.append(0); } /** * compute edit distance from alignment * * @return edit distance */ public static int computeEditDistance(String alignedQuery, String alignedReference) { int distance = 0; for (int i = 0; i < alignedQuery.length(); i++) { if (alignedQuery.charAt(i) == '-' || alignedReference.charAt(i) == '-' || alignedQuery.charAt(i) != alignedReference.charAt(i)) distance++; } return distance; } }
4,312
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BlastXML2SAMIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/BlastXML2SAMIterator.java
/* * BlastXML2SAMIterator.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.parsers.blast; import jloda.swing.window.NotificationsInSwing; import jloda.util.Basic; import megan.parsers.blast.blastxml.BlastXMLParser; import megan.parsers.blast.blastxml.MatchesText; import megan.util.BlastXMLFileFilter; import java.io.File; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * parses a BlastXML files into SAM format * Daniel Huson, 4.2015 */ public class BlastXML2SAMIterator implements ISAMIterator { private final ExecutorService executorService; private final BlastXMLParser blastXMLParser; private final BlockingQueue<MatchesText> queue; private MatchesText currentMatches; private MatchesText nextMatches; private final MatchesText sentinel; private boolean done = false; private boolean parseLongReads; /** * constructor * */ public BlastXML2SAMIterator(String fileName, int maxNumberOfMatchesPerRead) { if (!BlastXMLFileFilter.getInstance().accept(fileName)) { NotificationsInSwing.showWarning("Might not be a BLAST file in XML format: " + fileName); } queue = new ArrayBlockingQueue<>(10000); sentinel = new MatchesText(); currentMatches = null; nextMatches = null; blastXMLParser = new BlastXMLParser(new File(fileName), queue, maxNumberOfMatchesPerRead); executorService = Executors.newSingleThreadExecutor(); executorService.execute(() -> { try { blastXMLParser.apply(); } catch (Exception e) { Basic.caught(e); NotificationsInSwing.showError(Basic.getShortName(e.getClass()) + ": " + e.getMessage()); } finally { try { queue.put(sentinel); } catch (InterruptedException e) { done = true; Basic.caught(e); } executorService.shutdownNow(); } }); } private MatchesText getNext() { if (!done) { try { return queue.take(); } catch (InterruptedException e) { done = true; e.printStackTrace(); } } return null; } /** * is there more data? * * @return true, if more data available */ @Override public boolean hasNext() { if (done) return false; if (nextMatches == null) nextMatches = getNext(); if (nextMatches == sentinel) { done = true; nextMatches = null; } return !done; } /** * gets the next matches * * @return number of matches */ public int next() { if (hasNext()) { currentMatches = nextMatches; nextMatches = null; return currentMatches.getNumberOfMatches(); } return -1; } /** * gets the current matches text * * @return matches text */ @Override public byte[] getMatchesText() { return currentMatches.getText(); } /** * get length of current matches text * * @return length of text */ @Override public int getMatchesTextLength() { return currentMatches.getLengthOfText(); } @Override public long getMaximumProgress() { return blastXMLParser.getMaximumProgress(); } @Override public long getProgress() { return blastXMLParser.getProgress(); } @Override public void close() { } @Override public byte[] getQueryText() { return null; } @Override public void setParseLongReads(boolean longReads) { this.parseLongReads = longReads; } @Override public boolean isParseLongReads() { return parseLongReads; } }
4,825
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BlastTab2SAMIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/BlastTab2SAMIterator.java
/* * BlastTab2SAMIterator.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.parsers.blast; import jloda.swing.window.NotificationsInSwing; import jloda.util.FileUtils; import jloda.util.NumberUtils; import jloda.util.Pair; import jloda.util.StringUtils; import jloda.util.interval.Interval; import jloda.util.interval.IntervalTree; import java.io.File; import java.io.IOException; import java.util.TreeSet; /** * parses a blast Tab file into SAM format * Daniel Huson, 4.2015 */ public class BlastTab2SAMIterator extends SAMIteratorBase implements ISAMIterator { private final Pair<byte[], Integer> matchesTextAndLength = new Pair<>(new byte[10000], 0); private final TreeSet<Match> matches = new TreeSet<>(new Match()); private final IntervalTree<Match> matchesIntervalTree = new IntervalTree<>(); /** * constructor * */ public BlastTab2SAMIterator(String fileName, int maxNumberOfMatchesPerRead) throws IOException { super(fileName, maxNumberOfMatchesPerRead); setSkipCommentLines(true); final String line = FileUtils.getFirstLineFromFile(new File(fileName), "#", 1000); if (line != null && line.split("\t").length < 12) { NotificationsInSwing.showWarning("Might not be a BLAST file in TAB format: " + fileName); } } /** * is there more data? * * @return true, if more data available */ @Override public boolean hasNext() { return hasNextLine(); } /** * gets the next matches * * @return number of matches */ public int next() { if (!hasNextLine()) return -1; String line = nextLine(); final String queryName = StringUtils.getReadName(line); pushBackLine(line); int matchId = 0; // used to distinguish between matches when sorting matches.clear(); matchesTextAndLength.setSecond(0); matchesIntervalTree.clear(); // get all matches for given query: try { while (hasNextLine()) { // expected format: // queryId, subjectId, percIdentity, alnLength, mismatchCount, gapOpenCount, queryStart, queryEnd, // subjectStart, subjectEnd, eVal, bitScore // move to next match or next query: line = nextLine(); if (line == null)// at end of file break; if (line.startsWith("# ")) continue; // is a comment line if (line.startsWith("@") || line.startsWith((">"))) line = line.substring(1); if (!(line.startsWith(queryName) && Character.isWhitespace(line.charAt(queryName.length())))) { // at start of next query pushBackLine(line); break; } String[] tokens = StringUtils.split(line, '\t'); if (tokens.length == 1) continue; final String refName = tokens[1]; // subjectId if (!NumberUtils.isFloat(tokens[2])) // percIdentity throw new IOException("Expected float (percent identity), got: " + tokens[2]); if (NumberUtils.parseFloat(tokens[2]) > 100) throw new IOException("Expected percent identity, got: " + tokens[2]); float identity = (Float.parseFloat(tokens[2])); if (!NumberUtils.isInteger(tokens[3])) // alnLength throw new IOException("Expected integer (length), got: " + tokens[3]); int alignmentLength = (Integer.parseInt(tokens[3])); if (!NumberUtils.isInteger(tokens[4])) // mismatchCount throw new IOException("Expected integer (mismatches), got: " + tokens[4]); int mismatches = (Integer.parseInt(tokens[4])); if (!NumberUtils.isInteger(tokens[5])) // gapOpenCount throw new IOException("Expected integer (gap openings), got: " + tokens[5]); int gapOpenings = (Integer.parseInt(tokens[5])); if (!NumberUtils.isInteger(tokens[6])) // queryStart throw new IOException("Expected integer (query start), got: " + tokens[6]); int queryStart = (Integer.parseInt(tokens[6])); if (!NumberUtils.isInteger(tokens[7])) // queryEnd throw new IOException("Expected integer (query end), got: " + tokens[7]); int queryEnd = (Integer.parseInt(tokens[7])); if (!NumberUtils.isInteger(tokens[8])) // subjectStart throw new IOException("Expected integer (subject start), got: " + tokens[8]); int subjStart = (Integer.parseInt(tokens[8])); if (!NumberUtils.isInteger(tokens[9])) // subjectEnd throw new IOException("Expected integer (subject end), got: " + tokens[9]); int subjEnd = (Integer.parseInt(tokens[9])); if (!NumberUtils.isFloat(tokens[10])) // eVal throw new IOException("Expected float (expected), got: " + tokens[10]); float expect = (Float.parseFloat(tokens[10])); if (!NumberUtils.isFloat(tokens[11])) // bitScore throw new IOException("Expected float (bit score), got: " + tokens[11]); float bitScore = (Float.parseFloat(tokens[11])); if (isParseLongReads()) { // when parsing long reads we keep alignments based on local critera Match match = new Match(); match.bitScore = bitScore; match.id = matchId++; match.samLine = makeSAM(queryName, refName, bitScore, expect, identity, queryStart, queryEnd, subjStart, subjEnd, line); matchesIntervalTree.add(new Interval<>(queryStart, queryEnd, match)); } else { if (matches.size() < getMaxNumberOfMatchesPerRead() || bitScore > matches.last().bitScore) { Match match = new Match(); match.bitScore = bitScore; match.id = matchId++; match.samLine = makeSAM(queryName, refName, bitScore, expect, identity, queryStart, queryEnd, subjStart, subjEnd, line); matches.add(match); if (matches.size() > getMaxNumberOfMatchesPerRead()) matches.remove(matches.last()); } } } } catch (Exception ex) { System.err.println("Error parsing file near line: " + getLineNumber() + ": " + ex.getMessage()); if (incrementNumberOfErrors() >= getMaxNumberOfErrors()) throw new RuntimeException("Too many errors"); } return getPostProcessMatches().apply(queryName, matchesTextAndLength, isParseLongReads(), matchesIntervalTree, matches, null); } /** * gets the matches text * * @return matches text */ @Override public byte[] getMatchesText() { return matchesTextAndLength.getFirst(); } /** * length of matches text * * @return length of text */ @Override public int getMatchesTextLength() { return matchesTextAndLength.getSecond(); } /** * make a SAM line */ private String makeSAM(String queryName, String refName, float bitScore, float expect, float percentIdentity, int queryStart, int queryEnd, int referenceStart, int referenceEnd, String line) { final StringBuilder buffer = new StringBuilder(); buffer.append(queryName).append("\t"); boolean reverseComplemented = (referenceStart > referenceEnd); if (reverseComplemented) { buffer.append(0x10); // SEQ is reverse complemented } else buffer.append(0); buffer.append("\t"); buffer.append(refName).append("\t"); if (reverseComplemented) buffer.append(referenceEnd).append("\t"); else buffer.append(referenceStart).append("\t"); buffer.append("255\t"); buffer.append("*\t"); buffer.append("*\t"); buffer.append("0\t"); buffer.append("0\t"); buffer.append("*\t"); buffer.append("*\t"); buffer.append(String.format("AS:i:%d\t", Math.round(bitScore))); buffer.append(String.format("ZE:f:%g\t", expect)); buffer.append(String.format("ZI:i:%d\t", Math.round(percentIdentity))); buffer.append(String.format("ZS:i:%s\t", queryStart)); buffer.append(String.format("ZQ:i:%s\t", queryEnd)); buffer.append(String.format("AL:Z:%s\t", StringUtils.replaceSpaces(line, ' '))); return buffer.toString(); } }
9,628
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BlastP2SAMIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/BlastP2SAMIterator.java
/* * BlastP2SAMIterator.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.parsers.blast; import jloda.swing.window.NotificationsInSwing; import megan.util.BlastPTextFileFilter; import java.io.IOException; /** * parses a blastp files into SAM format * Daniel Huson, 4.2015 */ public class BlastP2SAMIterator extends BlastX2SAMIterator implements ISAMIterator { /** * constructor * */ public BlastP2SAMIterator(String fileName, int maxNumberOfMatchesPerRead) throws IOException { super(fileName, maxNumberOfMatchesPerRead, true); if (!BlastPTextFileFilter.getInstance().accept(fileName)) { NotificationsInSwing.showWarning("Might not be a BLASTP file in TEXT format: " + fileName); } } }
1,507
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BlastFileFormat.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/BlastFileFormat.java
/* * BlastFileFormat.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.parsers.blast; import jloda.swing.util.FastaFileFilter; import jloda.swing.util.ProgramProperties; import megan.util.*; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.IOException; /** * alignment file formats * Daniel Huson. 4.2015 */ public enum BlastFileFormat { Unknown, DAA, BlastText, BlastXML, BlastTab, LastMAF, RapSearch2Aln, IlluminaReporter, RDPAssignmentDetails, RDPStandalone, Mothur, SAM, References_as_FastA; /** * Determine the file format of an alignment file * * @return file format or null */ public static BlastFileFormat detectFormat(Component owner, String fileName, boolean ask) throws IOException { BlastFileFormat result = null; if (!(new File(fileName)).canRead() || (new File(fileName).isDirectory())) throw new IOException("Can't open file to read: " + fileName); if (SAMFileFilter.getInstance().accept(fileName)) result = SAM; else if (DAAFileFilter.getInstance().accept(fileName)) result = DAA; else if (BlastXTextFileFilter.getInstance().accept(fileName)) result = BlastText; else if (BlastNTextFileFilter.getInstance().accept(fileName)) result = BlastText; else if (BlastPTextFileFilter.getInstance().accept(fileName)) result = BlastText; else if (BlastTabFileFilter.getInstance().accept(fileName)) result = BlastTab; else if (BlastXMLFileFilter.getInstance().accept(fileName)) result = BlastXML; else if (LastMAFFileFilter.getInstance().accept(fileName)) result = LastMAF; else if (RAPSearch2AlnFileFilter.getInstance().accept(fileName)) result = RapSearch2Aln; else if (RDPAssignmentDetailsFileFilter.getInstance().accept(fileName)) result = RDPAssignmentDetails; else if (IlluminaReporterFileFilter.getInstance().accept(fileName)) result = IlluminaReporter; else if (RDPStandaloneFileFilter.getInstance().accept(fileName)) result = RDPStandalone; else if (FastaFileFilter.getInstance().accept(fileName)) result = References_as_FastA; else if (MothurFileFilter.getInstance().accept(fileName)) result = Mothur; if (result == null && ProgramProperties.isUseGUI() && ask) { result = (BlastFileFormat) JOptionPane.showInputDialog(owner, "Cannot determine format, please choose:", "Question: Which input format?", JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon(), valuesExceptUnknown(), BlastText); } if (result == null) { throw new IOException("Failed to determine BLAST format"); } return result; } /** * gets the value ignoring case * * @return value or null */ public static BlastFileFormat valueOfIgnoreCase(String formatName) { if (formatName != null) { for (BlastFileFormat format : values()) { if (format.toString().equalsIgnoreCase(formatName)) return format; } } return null; } /** * set of all values except 'Unknown' * */ public static BlastFileFormat[] valuesExceptUnknown() { BlastFileFormat[] array = new BlastFileFormat[values().length - 1]; int i = -0; for (BlastFileFormat value : values()) { if (value != Unknown) array[i++] = value; } return array; } }
4,418
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
RDPAssignmentDetails2SAMIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/RDPAssignmentDetails2SAMIterator.java
/* * RDPAssignmentDetails2SAMIterator.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.parsers.blast; import jloda.swing.window.NotificationsInSwing; import jloda.util.NumberUtils; import jloda.util.Pair; import jloda.util.StringUtils; import megan.util.RDPAssignmentDetailsFileFilter; import java.io.IOException; import java.util.TreeSet; /** * parses a RDP assignment details file into SAM format * Daniel Huson, 4.2015 */ public class RDPAssignmentDetails2SAMIterator extends SAMIteratorBase implements ISAMIterator { private final TreeSet<Match> matches = new TreeSet<>(new Match()); private final Pair<byte[], Integer> matchesTextAndLength = new Pair<>(new byte[10000], 0); /** * constructor * */ public RDPAssignmentDetails2SAMIterator(String fileName, int maxNumberOfMatchesPerRead) throws IOException { super(fileName, maxNumberOfMatchesPerRead); if (!RDPAssignmentDetailsFileFilter.getInstance().accept(fileName)) { NotificationsInSwing.showWarning("Might not be a 'RDP assignment details' file: " + fileName); } // skip all header lines: while (hasNextLine()) { if (nextLine().length() == 0) break; } } /** * is there more data? * * @return true, if more data available */ @Override public boolean hasNext() { return hasNextLine(); } /** * gets the next matches * * @return number of matches */ public int next() { if (!hasNextLine()) return -1; matchesTextAndLength.setSecond(0); final var line = nextLine(); try { var containsSemiColons = line.contains(";"); var containsTabs = line.contains("\t"); if (containsSemiColons) { final String[] tokens = StringUtils.split(line, ';'); int matchId = 0; // used to distinguish between matches when sorting matches.clear(); int whichToken = 0; final String queryName = tokens[whichToken++].trim(); final String direction = tokens[whichToken++]; final StringBuilder path = new StringBuilder(); // add one match block for each percentage given: while (whichToken < tokens.length) { String name = tokens[whichToken++]; if (name.equals("Root")) name = "root"; path.append(name).append(";"); String scoreString = tokens[whichToken++]; if (!scoreString.endsWith("%")) { System.err.println("Expected percentage in: " + line); break; } float bitScore = NumberUtils.parseFloat(scoreString); final Match match = new Match(); match.bitScore = bitScore; match.id = matchId++; final String ref = StringUtils.toString(tokens, 0, whichToken, ";") + ";"; match.samLine = makeSAM(queryName, path.toString(), bitScore, ref); matches.add(match); } return getPostProcessMatches().apply(queryName, matchesTextAndLength, isParseLongReads(), null, matches, null); } else if (containsTabs) { final String[] tokens = StringUtils.split(line, '\t'); int matchId = 0; // used to distinguish between matches when sorting matches.clear(); int whichToken = 0; final String queryName = tokens[whichToken++].trim(); var path = new StringBuilder(); var foundRoot = false; // add one match block for each percentage given: while (whichToken < tokens.length) { String name = tokens[whichToken++]; if (name.equals("Root")) { name = "root"; foundRoot = true; } if (!foundRoot) continue; path.append(name).append(";"); String scoreString = tokens[whichToken++]; if (!scoreString.endsWith("%")) { System.err.println("Expected percentage in: " + line); break; } var bitScore = NumberUtils.parseFloat(scoreString.substring(0, scoreString.length() - 1)); var match = new Match(); match.bitScore = bitScore; match.id = matchId++; final String ref = StringUtils.toString(tokens, 0, whichToken, ";") + ";"; match.samLine = makeSAM(queryName, path.toString(), bitScore, ref); matches.add(match); } return getPostProcessMatches().apply(queryName, matchesTextAndLength, isParseLongReads(), null, matches, null); } } catch (Exception ex) { System.err.println("Error parsing file near line: " + getLineNumber()); if (incrementNumberOfErrors() >= getMaxNumberOfErrors()) throw new RuntimeException("Too many errors"); } return 0; } /** * gets the matches text * * @return matches text */ @Override public byte[] getMatchesText() { return matchesTextAndLength.getFirst(); } /** * length of matches text * * @return length of text */ @Override public int getMatchesTextLength() { return matchesTextAndLength.getSecond(); } /** * make a SAM line */ private String makeSAM(String queryName, String refName, float bitScore, String line) { return String.format("%s\t0\t%s\t0\t255\t*\t*\t0\t0\t*\t*\tAS:i:%d\t", queryName, refName, Math.round(bitScore)) + String.format("AL:Z:%s\t", StringUtils.replaceSpaces(line, ' ')); } }
6,805
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SAM2SAMIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/SAM2SAMIterator.java
/* * SAM2SAMIterator.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.parsers.blast; import jloda.seq.BlastMode; import jloda.swing.window.NotificationsInSwing; import jloda.util.NumberUtils; import jloda.util.Pair; import jloda.util.StringUtils; import jloda.util.interval.Interval; import jloda.util.interval.IntervalTree; import megan.parsers.sam.SAMMatch; import megan.util.SAMFileFilter; import java.io.IOException; import java.util.TreeSet; /** * parses a SAM File in SAM format * Daniel Huson, 2.2017 */ public class SAM2SAMIterator extends SAMIteratorBase implements ISAMIterator { private final Pair<byte[], Integer> matchesTextAndLength = new Pair<>(new byte[10000000], 0); private final TreeSet<Match> matches = new TreeSet<>(new Match()); private final IntervalTree<Match> matchesIntervalTree = new IntervalTree<>(); private String currentMatchLine = null; private final SAMMatch samMatch; /** * constructor * */ protected SAM2SAMIterator(String fileName, int maxNumberOfMatchesPerRead, BlastMode blastMode) throws IOException { super(fileName, maxNumberOfMatchesPerRead); samMatch = new SAMMatch(blastMode); if (!SAMFileFilter.getInstance().accept(fileName)) { NotificationsInSwing.showWarning("Might not be a SAM file: " + fileName); } // skip header lines while (hasNextLine()) { String line = nextLine(); if (!line.startsWith("@")) { pushBackLine(line); break; } } moveToNextSAMLine(); } /** * is there more data? * * @return true, if more data available */ @Override public boolean hasNext() { return currentMatchLine != null; } /** * gets the next matches * * @return number of matches */ public int next() { if (currentMatchLine == null) return -1; // at end of file final String firstQuery = currentMatchLine; int matchId = 0; // used to distinguish between matches when sorting matches.clear(); matchesTextAndLength.setSecond(0); matchesIntervalTree.clear(); // get all matches for given query: try { while (true) { if (currentMatchLine != null && sameQuery(currentMatchLine, firstQuery)) { samMatch.parse(currentMatchLine); if (samMatch.isMatch()) { final Match match = new Match(); match.bitScore = samMatch.getBitScore(); match.id = matchId++; match.samLine = currentMatchLine; if (isParseLongReads()) { // when parsing long reads we keep alignments based on local critera matchesIntervalTree.add(new Interval<>(samMatch.getAlignedQueryStart(), samMatch.getAlignedQueryEnd(), match)); } else { if (matches.size() < getMaxNumberOfMatchesPerRead() || samMatch.getBitScore() > matches.last().bitScore) { matches.add(match); if (matches.size() > getMaxNumberOfMatchesPerRead()) matches.remove(matches.last()); } } } moveToNextSAMLine(); } else // new query or last alignment, in either case return { break; } } } catch (Exception ex) { System.err.println("Error parsing file near line: " + getLineNumber() + ": " + ex.getMessage()); if (incrementNumberOfErrors() >= getMaxNumberOfErrors()) throw new RuntimeException("Too many errors"); } return getPostProcessMatches().apply(firstQuery, matchesTextAndLength, isParseLongReads(), matchesIntervalTree, matches, null); } /** * move to the next match */ private void moveToNextSAMLine() { if (hasNextLine()) { currentMatchLine = nextLine(); // this skips over any empty lines: while (currentMatchLine != null && currentMatchLine.trim().length() == 0) { if (hasNextLine()) currentMatchLine = nextLine(); else currentMatchLine = null; } } else { currentMatchLine = null; } } /** * gets the matches text * * @return matches text */ @Override public byte[] getMatchesText() { return matchesTextAndLength.getFirst(); } /** * length of matches text * * @return length of text */ @Override public int getMatchesTextLength() { return matchesTextAndLength.getSecond(); } /** * do these two SAM lines refer to the same query sequence? * * @return true, if same query */ private boolean sameQuery(String samA, String samB) { String[] tokensA = StringUtils.split(samA, '\t', 2); String[] tokensB = StringUtils.split(samB, '\t', 2); // not the same name, return false if (tokensA.length >= 1 && tokensB.length >= 1 && !tokensA[0].equals(tokensB[0])) return false; // check whether they are different "templates", that is, first and last of a read pair try { final int flagA = NumberUtils.parseInt(tokensA[1]); final int flagB = NumberUtils.parseInt(tokensB[1]); return (flagA & 192) == (flagB & 192); // second token is 'flag', must have same 7th and 8th bit for same query } catch (Exception ex) { return true; } } }
6,578
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BlastX2SAMIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/BlastX2SAMIterator.java
/* * BlastX2SAMIterator.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.parsers.blast; import jloda.swing.window.NotificationsInSwing; import jloda.util.NumberUtils; import jloda.util.Pair; import jloda.util.StringUtils; import jloda.util.interval.Interval; import jloda.util.interval.IntervalTree; import megan.util.BlastXTextFileFilter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.TreeSet; /** * parses a blastx files into SAM format * Daniel Huson, 4.2015 */ public class BlastX2SAMIterator extends SAMIteratorBase implements ISAMIterator { private final static String NEW_QUERY = "Query="; private final static String NEW_MATCH = ">"; private final static String QUERY = "Query"; private final static String SUBJECT = "Sbjct"; private final static String SCORE = "Score"; private final static String EXPECT = "Expect"; private final static String LENGTH = "Length"; private final static String IDENTITIES = "Identities"; private final static String FRAME = "Frame"; private final static String EQUALS = "="; private final Pair<byte[], Integer> matchesTextAndLength = new Pair<>(new byte[10000], 0); private final boolean blastPMode; private final ArrayList<String> refHeaderLines = new ArrayList<>(1000); private final TreeSet<Match> matches = new TreeSet<>(new Match()); private final IntervalTree<Match> matchesIntervalTree = new IntervalTree<>(); private List<Match> listOfMatches = null; // if we want to iterate over all matches in the order they were obtained, then must set this to non-null private long numberOfReads = 0; /** * constructor * */ public BlastX2SAMIterator(String fileName, int maxNumberOfMatchesPerRead) throws IOException { this(fileName, maxNumberOfMatchesPerRead, false); if (!BlastXTextFileFilter.getInstance().accept(fileName)) { NotificationsInSwing.showWarning("Might not be a BLASTX file in TEXT format: " + fileName); } } /** * constructor * */ protected BlastX2SAMIterator(String fileName, int maxNumberOfMatchesPerRead, boolean blastPMode) throws IOException { super(fileName, maxNumberOfMatchesPerRead); this.blastPMode = blastPMode; } /** * is there more data? * * @return true, if more data available */ @Override public boolean hasNext() { return hasNextLine(); } /** * gets the next matches * * @return number of matches */ public int next() { String queryLine = getNextLineStartsWith(NEW_QUERY); if (queryLine == null) return -1; // at end of file final String queryName; { numberOfReads++; final String name = getNextToken(queryLine, NEW_QUERY).trim(); queryName = (name.length() == 0 ? "Read" + numberOfReads : name); } matches.clear(); matchesIntervalTree.clear(); if (listOfMatches != null) listOfMatches.clear(); matchesTextAndLength.setSecond(0); int matchId = 0; // used to distinguish between matches when sorting // get all matches for given query: try { while (hasNextLine()) { // move to next match or next query: String line = getNextLineStartsWith(NEW_QUERY, NEW_MATCH); if (line == null)// at end of file break; if (line.startsWith(NEW_QUERY)) { // at start of next query pushBackLine(line); break; } // line is at start of new match // collect all the reference header lines: refHeaderLines.clear(); while (true) { if (startsWith(line, LENGTH)) break; else refHeaderLines.add(line.replaceAll("\\s+", " ")); line = nextLine().trim(); } final int referenceLength = NumberUtils.parseInt(getNextToken(line, LENGTH, EQUALS)); final String refName = StringUtils.swallowLeadingGreaterSign(StringUtils.toString(refHeaderLines, " ")); // Blast text downloaded from NBCI might have some text before the alignment starts: do { line = skipEmptyLines(); if (line.startsWith("Score =")) break; else line = nextLine().trim(); } while (hasNext()); boolean hasAnotherAlignmentAgainstReference = true; while (hasAnotherAlignmentAgainstReference) { hasAnotherAlignmentAgainstReference = false; float bitScore = NumberUtils.parseFloat(getNextToken(line, SCORE, EQUALS)); int rawScore = NumberUtils.parseInt(getNextToken(line, "(")); float expect = NumberUtils.parseFloat(getNextToken(line, EXPECT, EQUALS)); // usually Expect = but can also be Expect(2)= line = nextLine(); float percentIdentities = NumberUtils.parseFloat(getNextToken(line, IDENTITIES, "(")); int frame; if (blastPMode) { frame = 0; } else { line = nextLine(); frame = NumberUtils.parseInt(getNextToken(line, FRAME, EQUALS)); } String[] queryLineTokens = getNextLineStartsWith(QUERY).split("\\s+"); // split on white space int queryStart = NumberUtils.parseInt(queryLineTokens[1]); StringBuilder queryBuf = new StringBuilder(); queryBuf.append(queryLineTokens[2]); int queryEnd = NumberUtils.parseInt(queryLineTokens[3]); if (!hasNextLine()) break; nextLine(); // skip middle line String[] subjectLineTokens = getNextLineStartsWith(SUBJECT).split("\\s+"); int subjStart = NumberUtils.parseInt(subjectLineTokens[1]); StringBuilder subjBuf = new StringBuilder(); subjBuf.append(subjectLineTokens[2]); int subjEnd = NumberUtils.parseInt(subjectLineTokens[3]); // if match is broken over multiple lines, collect all parts of match while (hasNextLine()) { line = skipEmptyLines(); if (line == null) break; // at EOF... if (line.startsWith(NEW_QUERY)) { // at new query pushBackLine(line); break; } else if (line.startsWith(NEW_MATCH)) { // start of new match pushBackLine(line); break; } else if (line.startsWith(SCORE)) { // there is another match of query to the same reference if (isParseLongReads()) { hasAnotherAlignmentAgainstReference = true; // also report other matches to same reference break; } else pushBackLine(getNextLineStartsWith(NEW_QUERY, NEW_MATCH)); // skip other matches to same query } else if (line.startsWith(QUERY)) { // match continues... queryLineTokens = line.split("\\s+"); queryBuf.append(queryLineTokens[2]); queryEnd = NumberUtils.parseInt(queryLineTokens[3]); subjectLineTokens = getNextLineStartsWith(SUBJECT).split("\\s+"); subjBuf.append(subjectLineTokens[2]); subjEnd = NumberUtils.parseInt(subjectLineTokens[3]); } } final Match match = new Match(); match.bitScore = bitScore; match.id = matchId++; match.samLine = makeSAM(queryName, refName, referenceLength, bitScore, expect, rawScore, percentIdentities, frame, queryStart, queryEnd, subjStart, subjEnd, queryBuf.toString(), subjBuf.toString()); if (listOfMatches != null) listOfMatches.add(match); else if (isParseLongReads()) { // when parsing long reads we keep alignments based on local critera matchesIntervalTree.add(new Interval<>(queryStart, queryEnd, match)); } else if (matches.size() < getMaxNumberOfMatchesPerRead() || bitScore > matches.last().bitScore) { matches.add(match); if (matches.size() > getMaxNumberOfMatchesPerRead()) matches.remove(matches.last()); } } } } catch (Exception ex) { System.err.println("Error parsing file near line: " + getLineNumber() + ": " + ex.getMessage()); if (incrementNumberOfErrors() >= getMaxNumberOfErrors()) throw new RuntimeException("Too many errors"); } return getPostProcessMatches().apply(queryName, matchesTextAndLength, isParseLongReads(), matchesIntervalTree, matches, listOfMatches); } /** * gets the matches text * * @return matches text */ @Override public byte[] getMatchesText() { return matchesTextAndLength.getFirst(); } /** * length of matches text * * @return length of text */ @Override public int getMatchesTextLength() { return matchesTextAndLength.getSecond(); } /** * make a SAM line */ public static String makeSAM(String queryName, String refName, int referenceLength, float bitScore, float expect, int rawScore, float percentIdentity, int frame, int queryStart, int queryEnd, int referenceStart, int referenceEnd, String alignedQuery, String alignedReference) { final StringBuilder buffer = new StringBuilder(); buffer.append(queryName).append("\t"); buffer.append(0); buffer.append("\t"); buffer.append(refName).append("\t"); buffer.append(referenceStart).append("\t"); buffer.append("255\t"); Utilities.appendCigar(alignedQuery, alignedReference, buffer); buffer.append("\t"); buffer.append("*\t"); buffer.append("0\t"); buffer.append("0\t"); buffer.append(alignedQuery.replaceAll("-", "")).append("\t"); buffer.append("*\t"); buffer.append(String.format("AS:i:%d\t", Math.round(bitScore))); buffer.append(String.format("NM:i:%d\t", Utilities.computeEditDistance(alignedQuery, alignedReference))); buffer.append(String.format("ZL:i:%d\t", referenceLength)); buffer.append(String.format("ZR:i:%d\t", rawScore)); buffer.append(String.format("ZE:f:%g\t", expect)); buffer.append(String.format("ZI:i:%d\t", Math.round(percentIdentity))); if (frame != 0) buffer.append(String.format("ZF:i:%d\t", frame)); buffer.append(String.format("ZS:i:%s\t", queryStart)); Utilities.appendMDString(alignedQuery, alignedReference, buffer); return buffer.toString(); } public void setReportAllMatchesInOriginalOrder(boolean report) { listOfMatches = (report ? new ArrayList<>() : null); } public boolean isReportAllMatchesInOriginalOrder() { return listOfMatches != null; } }
12,248
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BlastN2SAMIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/BlastN2SAMIterator.java
/* * BlastN2SAMIterator.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.parsers.blast; import jloda.seq.SequenceUtils; import jloda.swing.window.NotificationsInSwing; import jloda.util.NumberUtils; import jloda.util.Pair; import jloda.util.StringUtils; import jloda.util.interval.Interval; import jloda.util.interval.IntervalTree; import megan.util.BlastNTextFileFilter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.TreeSet; /** * parses a blastn files into SAM format * Daniel Huson, 4.2015 */ public class BlastN2SAMIterator extends SAMIteratorBase implements ISAMIterator { private final static String NEW_QUERY = "Query="; private final static String NEW_MATCH = ">"; private final static String QUERY = "Query"; private final static String SUBJECT = "Sbjct"; private final static String SCORE = "Score"; private final static String EXPECT = "Expect"; private final static String LENGTH = "Length"; private final static String IDENTITIES = "Identities"; private final static String STRAND = "Strand"; private final static String EQUALS = "="; private final Pair<byte[], Integer> matchesTextAndLength = new Pair<>(new byte[10000], 0); private final ArrayList<String> refHeaderLines = new ArrayList<>(1000); private final TreeSet<Match> matches = new TreeSet<>(new Match()); private final IntervalTree<Match> matchesIntervalTree = new IntervalTree<>(); private List<Match> listOfMatches = null; // if we want to iterate over all matches in the order they were obtained, then must set this to non-null private long numberOfReads = 0; /** * constructor * */ public BlastN2SAMIterator(String fileName, int maxNumberOfMatchesPerRead) throws IOException { super(fileName, maxNumberOfMatchesPerRead); if (!BlastNTextFileFilter.getInstance().accept(fileName)) { NotificationsInSwing.showWarning("Might not be a BLASTN file in TEXT format: " + fileName); } } /** * is there more data? * * @return true, if more data available */ @Override public boolean hasNext() { return hasNextLine(); } /** * gets the next matches * * @return number of matches */ public int next() { String queryLine = getNextLineStartsWith(NEW_QUERY); if (queryLine == null) return -1; // at end of file final String queryName; { numberOfReads++; final String name = getNextToken(queryLine, NEW_QUERY).trim(); queryName = (name.length() == 0 ? "Read" + numberOfReads : name); } matchesTextAndLength.setSecond(0); matches.clear(); if (listOfMatches != null) listOfMatches.clear(); matchesIntervalTree.clear(); int matchId = 0; // used to distinguish between matches when sorting // get all matches for given query: try { while (hasNextLine()) { // move to next match or next query: String line = getNextLineStartsWith(NEW_QUERY, NEW_MATCH); if (line == null)// at end of file break; if (line.startsWith(NEW_QUERY)) { // at start of next query pushBackLine(line); break; } // line is at start of new match // collect all the reference header lines: refHeaderLines.clear(); while (true) { if (startsWith(line, LENGTH)) break; else refHeaderLines.add(line.replaceAll("\\s+", " ")); line = nextLine().trim(); } final int referenceLength = NumberUtils.parseInt(getNextToken(line, LENGTH, EQUALS)); final String refName = StringUtils.swallowLeadingGreaterSign(StringUtils.toString(refHeaderLines, " ")); // Blast text downloaded from NBCI might have some text before the alignment starts: do { line = skipEmptyLines(); if (line.startsWith("Score =")) break; else line = nextLine().trim(); } while (hasNext()); boolean hasAnotherAlignmentAgainstReference = true; while (hasAnotherAlignmentAgainstReference) { hasAnotherAlignmentAgainstReference = false; final float bitScore = NumberUtils.parseFloat(getNextToken(line, SCORE, EQUALS)); final int rawScore = NumberUtils.parseInt(getNextToken(line, "(")); final float expect = NumberUtils.parseFloat(getNextToken(line, EXPECT, EQUALS)); // usually Expect = but can also be Expect(2)= line = nextLine(); final float percentIdentities = NumberUtils.parseFloat(getNextToken(line, IDENTITIES, "(")); line = nextLine(); final String queryDirection = getNextLetters(line, STRAND, "="); final String refDirection = getNextToken(line, "/"); // skip line containing Strand String[] queryLineTokens = getNextLineStartsWith(QUERY).split("\\s+"); // split on white space int queryStart = NumberUtils.parseInt(queryLineTokens[1]); StringBuilder queryBuf = new StringBuilder(); queryBuf.append(queryLineTokens[2]); int queryEnd = NumberUtils.parseInt(queryLineTokens[3]); if (!hasNextLine()) break; nextLine(); // skip middle line String[] subjectLineTokens = getNextLineStartsWith(SUBJECT).split("\\s+"); int subjStart = NumberUtils.parseInt(subjectLineTokens[1]); StringBuilder subjBuf = new StringBuilder(); subjBuf.append(subjectLineTokens[2]); int subjEnd = NumberUtils.parseInt(subjectLineTokens[3]); // if match is broken over multiple lines, collect all parts of match: while (hasNextLine()) { line = skipEmptyLines(); if (line == null) break; // at EOF... if (line.startsWith(NEW_QUERY)) { // at new query pushBackLine(line); break; } else if (line.startsWith(NEW_MATCH)) { // start of new match pushBackLine(line); break; } else if (line.startsWith(SCORE)) { // there is another match to the same reference if (isParseLongReads()) { hasAnotherAlignmentAgainstReference = true; // also report other matches to same reference break; } else pushBackLine(getNextLineStartsWith(NEW_QUERY, NEW_MATCH)); // skip other matches to same query } else if (line.startsWith(QUERY)) { // match continues... queryLineTokens = line.split("\\s+"); queryBuf.append(queryLineTokens[2]); queryEnd = NumberUtils.parseInt(queryLineTokens[3]); subjectLineTokens = getNextLineStartsWith(SUBJECT).split("\\s+"); subjBuf.append(subjectLineTokens[2]); subjEnd = NumberUtils.parseInt(subjectLineTokens[3]); } } if (isParseLongReads()) { // when parsing long reads we keep alignments based on local critera Match match = new Match(); match.bitScore = bitScore; match.id = matchId++; match.samLine = makeSAM(queryName, queryDirection, refName, referenceLength, refDirection, bitScore, expect, rawScore, percentIdentities, queryStart, queryEnd, subjStart, subjEnd, queryBuf.toString(), subjBuf.toString()); matchesIntervalTree.add(new Interval<>(queryStart, queryEnd, match)); } else { if (matches.size() < getMaxNumberOfMatchesPerRead() || bitScore > matches.last().bitScore) { Match match = new Match(); match.bitScore = bitScore; match.id = matchId++; match.samLine = makeSAM(queryName, queryDirection, refName, referenceLength, refDirection, bitScore, expect, rawScore, percentIdentities, queryStart, queryEnd, subjStart, subjEnd, queryBuf.toString(), subjBuf.toString()); matches.add(match); if (matches.size() > getMaxNumberOfMatchesPerRead()) matches.remove(matches.last()); } } } } } catch (Exception ex) { System.err.println("Error parsing file near line: " + getLineNumber() + ": " + ex.getMessage()); if (incrementNumberOfErrors() >= getMaxNumberOfErrors()) throw new RuntimeException("Too many errors"); } return getPostProcessMatches().apply(queryName, matchesTextAndLength, isParseLongReads(), matchesIntervalTree, matches, listOfMatches); } /** * gets the matches text * * @return matches text */ @Override public byte[] getMatchesText() { return matchesTextAndLength.getFirst(); } /** * length of matches text * * @return length of text */ @Override public int getMatchesTextLength() { return matchesTextAndLength.getSecond(); } /** * make a SAM line */ public static String makeSAM(String queryName, String queryDirection, String refName, int referenceLength, String refDirection, float bitScore, float expect, int rawScore, float percentIdentity, int queryStart, int queryEnd, int referenceStart, int referenceEnd, String alignedQuery, String alignedReference) throws IOException { final boolean reverseComplemented; if (queryDirection.equals("Plus")) { if (refDirection.equals("Minus")) { alignedQuery = SequenceUtils.getReverseComplement(alignedQuery); alignedReference = SequenceUtils.getReverseComplement(alignedReference); reverseComplemented = true; } else reverseComplemented = false; } else { if (refDirection.equals("Minus")) // query minus, ref minus throw new IOException("Can't parse match with Strand = Minus / Minus"); else { // query minus, ref plus int tmp = queryStart; queryStart = queryEnd; tmp = referenceStart; referenceStart = referenceEnd; referenceEnd = tmp; reverseComplemented = true; } } final StringBuilder buffer = new StringBuilder(); buffer.append(queryName).append("\t"); if (reverseComplemented) buffer.append(0x10); // SEQ is reverse complemented else buffer.append(0); buffer.append("\t"); buffer.append(refName).append("\t"); if (reverseComplemented) buffer.append(referenceEnd).append("\t"); else buffer.append(referenceStart).append("\t"); buffer.append("255\t"); Utilities.appendCigar(alignedQuery, alignedReference, buffer); buffer.append("\t"); buffer.append("*\t"); buffer.append("0\t"); buffer.append("0\t"); buffer.append(alignedQuery.replaceAll("-", "")).append("\t"); buffer.append("*\t"); buffer.append(String.format("AS:i:%d\t", Math.round(bitScore))); buffer.append(String.format("NM:i:%d\t", Utilities.computeEditDistance(alignedQuery, alignedReference))); buffer.append(String.format("ZL:i:%d\t", referenceLength)); buffer.append(String.format("ZR:i:%d\t", rawScore)); buffer.append(String.format("ZE:f:%g\t", expect)); buffer.append(String.format("ZI:i:%d\t", Math.round(percentIdentity))); buffer.append(String.format("ZS:i:%s\t", queryStart)); Utilities.appendMDString(alignedQuery, alignedReference, buffer); return buffer.toString(); } public void setReportAllMatchesInOriginalOrder(boolean report) { listOfMatches = (report ? new ArrayList<>() : null); } public boolean isReportAllMatchesInOriginalOrder() { return listOfMatches != null; } }
13,904
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SAMIteratorBase.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/SAMIteratorBase.java
/* * SAMIteratorBase.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.parsers.blast; import jloda.util.FileLineIterator; import java.io.IOException; /** * base class * <p/> * Daniel Huson, 4.2015 */ public class SAMIteratorBase { private final FileLineIterator iterator; private final int maxNumberOfMatchesPerRead; private int maxNumberOfErrors = 1000; private int numberOfErrors = 0; private String pushedBackLine; private boolean parseLongReads; private final PostProcessMatches postProcessMatches; /** * constructor * */ public SAMIteratorBase(String fileName, int maxNumberOfMatchesPerRead) throws IOException { iterator = new FileLineIterator(fileName); this.maxNumberOfMatchesPerRead = maxNumberOfMatchesPerRead; postProcessMatches = new PostProcessMatches(); } /** * does string start with the given tag (allowing spaces inside tag to be missing in string) * */ static boolean startsWith(String string, String tag) { return string.startsWith(tag) || (tag.contains(" ") && string.startsWith(tag.replaceAll(" ", ""))); } /** * gets the next token following tag in aLine. Treats spaces in tag as match 0 or 1 spaces... * * @return next token after tag */ static String getNextToken(String aLine, String tag) { int a = endOfTagMatch(aLine, tag); if (a >= 0) { while (a < aLine.length() && Character.isWhitespace(aLine.charAt(a))) a++; int b = a; while (b < aLine.length() && !Character.isWhitespace(aLine.charAt(b))) b++; return aLine.substring(a, b); } return ""; } /** * gets the next token following tag1 and then tag2 in aLine. Treats spaces in tag as match 0 or 1 spaces... * * @return next token after tag */ static String getNextToken(String aLine, String tag1, String tag2) { int a = endOfTagMatch(aLine, tag1); if (a >= 0) { a = endOfTagMatch(aLine, a, tag2); while (a < aLine.length() && Character.isWhitespace(aLine.charAt(a))) a++; int b = a; while (b < aLine.length() && !Character.isWhitespace(aLine.charAt(b))) b++; return aLine.substring(a, b); } return ""; } /** * gets the next token consisting only of letters, following tag1 and then tag2 in aLine. Treats spaces in tag as match 0 or 1 spaces... * * @return next token after tag */ static String getNextLetters(String aLine, String tag1, String tag2) { int a = endOfTagMatch(aLine, tag1); if (a >= 0) { a = endOfTagMatch(aLine, a, tag2); while (a < aLine.length() && Character.isWhitespace(aLine.charAt(a))) a++; int b = a; while (b < aLine.length() && Character.isLetter(aLine.charAt(b))) b++; return aLine.substring(a, b); } return ""; } /** * matches tag to string (allowing spaces inside tag to be missing in string) * * @return position after match and all trailing white space, or -1 */ private static int endOfTagMatch(String string, String tag) { return endOfTagMatch(string, 0, tag); } /** * matches tag to string (allowing spaces inside tag to be missing in string) * * @param fromIndex starting index in string * @return position after match and all trailing white space, or -1 */ private static int endOfTagMatch(String string, int fromIndex, String tag) { int pos = string.indexOf(tag, fromIndex); if (pos != -1) { while (pos < string.length() && Character.isWhitespace(string.charAt(pos))) pos++; return pos + tag.length(); } if (tag.contains(" ")) { tag = tag.replaceAll(" ", ""); pos = string.indexOf(tag); if (pos != -1) { while (pos < string.length() && Character.isWhitespace(string.charAt(pos))) pos++; return pos + tag.length(); } } return -1; } public long getMaximumProgress() { return iterator.getMaximumProgress(); } public long getProgress() { return iterator.getProgress(); } /** * close the iterator * */ public void close() throws IOException { iterator.close(); } /** * is there a next line? * * @return true, if next line available */ boolean hasNextLine() { return pushedBackLine != null || iterator.hasNext(); } /** * gets the next line * * @return next line */ String nextLine() { if (pushedBackLine != null) { final String result = pushedBackLine; pushedBackLine = null; return result; } else return iterator.next(); } /** * move to next line that starts with the given prefix * * @return line or null */ String getNextLineStartsWith(String prefix) { while (hasNextLine()) { final String line = nextLine(); if (line.startsWith(prefix)) return line; } return null; } /** * move to next line that contains given infix * * @return line or null */ String getNextLineContains(String infix) { while (hasNextLine()) { final String line = nextLine(); if (line.contains(infix)) return line; } return null; } /** * moves to next query that starts with either of the given prefixes * * @return next line or null */ String getNextLineStartsWith(String prefix1, String prefix2) { while (hasNextLine()) { final String line = nextLine(); if (line.startsWith(prefix1) || line.startsWith(prefix2)) return line; } return null; } /** * skips empty lines and returns the next non-empty one or null * * @return next line or null */ String skipEmptyLines() { while (true) { if (hasNextLine()) { final String next = nextLine().trim(); if (next.length() > 0) return next; } else return null; } } /** * push back a line * */ void pushBackLine(String line) { if (pushedBackLine != null) System.err.println("Error: Push back line, but buffer not empty"); pushedBackLine = line; } long getLineNumber() { return iterator.getLineNumber(); } int getMaxNumberOfMatchesPerRead() { return maxNumberOfMatchesPerRead; } int getMaxNumberOfErrors() { return maxNumberOfErrors; } public void setMaxNumberOfErrors(int maxNumberOfErrors) { this.maxNumberOfErrors = maxNumberOfErrors; } public int incrementNumberOfErrors() { return ++numberOfErrors; } /** * skip lines starting with #? * */ public void setSkipCommentLines(boolean skip) { iterator.setSkipCommentLines(skip); } /** * skip lines starting with #? * */ public boolean isSkipCommentLines() { return iterator.isSkipCommentLines(); } public byte[] getQueryText() { return null; } public boolean isParseLongReads() { return parseLongReads; } public void setParseLongReads(boolean parseLongReads) { this.parseLongReads = parseLongReads; postProcessMatches.setParseLongReads(parseLongReads); } public PostProcessMatches getPostProcessMatches() { return postProcessMatches; } }
8,718
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
RDPStandalone2SAMIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/RDPStandalone2SAMIterator.java
/* * RDPStandalone2SAMIterator.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.parsers.blast; import jloda.swing.window.NotificationsInSwing; import jloda.util.NumberUtils; import jloda.util.Pair; import jloda.util.StringUtils; import megan.util.RDPStandaloneFileFilter; import java.io.IOException; import java.util.TreeSet; /** * parses a RDP assignment details file into SAM format * Daniel Huson, 4.2015 */ public class RDPStandalone2SAMIterator extends SAMIteratorBase implements ISAMIterator { private final TreeSet<Match> matches = new TreeSet<>(new Match()); private final Pair<byte[], Integer> matchesTextAndLength = new Pair<>(new byte[10000], 0); /** * constructor * */ public RDPStandalone2SAMIterator(String fileName, int maxNumberOfMatchesPerRead) throws IOException { super(fileName, maxNumberOfMatchesPerRead); if (!RDPStandaloneFileFilter.getInstance().accept(fileName)) { NotificationsInSwing.showWarning("Might not be a 'RDP standalone' file: " + fileName); } } /** * is there more data? * * @return true, if more data available */ @Override public boolean hasNext() { return hasNextLine(); } /** * gets the next matches * * @return number of matches */ public int next() { if (!hasNextLine()) return -1; matchesTextAndLength.setSecond(0); String line = nextLine(); while (hasNextLine() && line.startsWith("#")) { line = nextLine(); } if (line == null) return -1; final String[] tokens = line.replaceAll("\t\t", "\t").split("\t"); if (tokens.length < 4) { System.err.println("Too few tokens in line: " + line); throw new RuntimeException("Too many errors"); } int whichToken = 0; final String queryName = tokens[whichToken++]; int matchId = 0; // used to distinguish between matches when sorting matches.clear(); final StringBuilder path = new StringBuilder(); // add one match block for each percentage given: try { while (whichToken < tokens.length) { String name = tokens[whichToken++]; if (name.startsWith("\"")) name = name.substring(1, name.length() - 1); if (name.equals("Root")) name = "root"; path.append(name).append(";"); final String rank = tokens[whichToken++]; // rank ignored... final String scoreString = tokens[whichToken++]; float bitScore = 100 * NumberUtils.parseFloat(scoreString); final Match match = new Match(); match.bitScore = bitScore; match.id = matchId++; final String ref = StringUtils.toString(tokens, 0, whichToken, ";") + ";"; match.samLine = makeSAM(queryName, path.toString(), bitScore, ref); matches.add(match); } } catch (Exception ex) { System.err.println("Error parsing file near line: " + getLineNumber()); if (incrementNumberOfErrors() >= getMaxNumberOfErrors()) throw new RuntimeException("Too many errors"); } return getPostProcessMatches().apply(queryName, matchesTextAndLength, isParseLongReads(), null, matches, null); } /** * gets the matches text * * @return matches text */ @Override public byte[] getMatchesText() { return matchesTextAndLength.getFirst(); } /** * length of matches text * * @return length of text */ @Override public int getMatchesTextLength() { return matchesTextAndLength.getSecond(); } /** * make a SAM line */ private String makeSAM(String queryName, String refName, float bitScore, String line) { return String.format("%s\t0\t%s\t0\t255\t*\t*\t0\t0\t*\t*\tAS:i:%d\t", queryName, refName, Math.round(bitScore)) + String.format("AL:Z:%s\t", StringUtils.replaceSpaces(line, ' ')); } }
4,920
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Fasta2SAMIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/Fasta2SAMIterator.java
/* * Fasta2SAMIterator.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.parsers.blast; import jloda.swing.util.FastaFileFilter; import jloda.swing.window.NotificationsInSwing; import jloda.util.StringUtils; import java.io.IOException; /** * parses a FastA file into SAM format. This is used to partition a database such as NR by taxonomic or other assignment * Daniel Huson, 4.2015 */ public class Fasta2SAMIterator extends SAMIteratorBase implements ISAMIterator { private byte[] matchesText = new byte[0]; /** * constructor * */ public Fasta2SAMIterator(String fileName, int maxNumberOfMatchesPerRead) throws IOException { super(fileName, maxNumberOfMatchesPerRead); if (!FastaFileFilter.accept(fileName, true)) { NotificationsInSwing.showWarning("Might not be FastA format: " + fileName); } } /** * is there more data? * * @return true, if more data available */ @Override public boolean hasNext() { return hasNextLine(); } /** * gets the next matches * * @return number of matches */ public int next() { if (!hasNextLine()) return -1; String line = nextLine(); if (line == null || !line.startsWith(">")) return -1; final String queryName = StringUtils.getReadName(line); matchesText = makeSAM(queryName, StringUtils.replaceSpaces(line, ' ')).getBytes(); while (hasNextLine()) { line = nextLine(); if (line.startsWith(">")) { pushBackLine(line); break; } } return 1; } /** * gets the matches text * * @return matches text */ @Override public byte[] getMatchesText() { return matchesText; } /** * length of matches text * * @return length of text */ @Override public int getMatchesTextLength() { return matchesText.length; } /** * make a SAM line */ private String makeSAM(String queryName, String referenceLine) { return queryName + "\t0\t" + referenceLine + "\t0\t255\t*\t*\t0\t0\t*\t*\tAS:i:100\t\n"; } }
2,986
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Mothur2SAMIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/Mothur2SAMIterator.java
/* * Mothur2SAMIterator.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.parsers.blast; import jloda.swing.window.NotificationsInSwing; import jloda.util.NumberUtils; import jloda.util.Pair; import jloda.util.StringUtils; import megan.util.MothurFileFilter; import java.io.IOException; import java.util.TreeSet; /** * parses a mothur file into SAM format * Daniel Huson, 4.2015 */ public class Mothur2SAMIterator extends SAMIteratorBase implements ISAMIterator { private final TreeSet<Match> matches = new TreeSet<>(new Match()); private final Pair<byte[], Integer> matchesTextAndLength = new Pair<>(new byte[10000], 0); /** * constructor * */ public Mothur2SAMIterator(String fileName, int maxNumberOfMatchesPerRead) throws IOException { super(fileName, maxNumberOfMatchesPerRead); if (!MothurFileFilter.getInstance().accept(fileName)) { NotificationsInSwing.showWarning("Might not be a MOTHUR analysis file: " + fileName); } } /** * is there more data? * * @return true, if more data available */ @Override public boolean hasNext() { return hasNextLine(); } /** * gets the next matches * * @return number of matches */ public int next() { if (!hasNextLine()) return -1; matchesTextAndLength.setSecond(0); // Format: ASF360\tBacteria(100);Firmicutes(100);Bacilli(100);Lactobacillales(100);Lactobacillaceae(100);Lactobacillus(100); String line = nextLine(); boolean found = false; while (line != null && !found) { if (StringUtils.countOccurrences(line, '\t') == 1) found = true; else if (hasNext()) line = nextLine(); else line = null; } if (line == null) return -1; int matchId = 0; // used to distinguish between matches when sorting matches.clear(); final String[] lines = StringUtils.split(line, '\t'); final String queryName = lines[0]; final String[] tokens = StringUtils.split(lines[1], ';'); StringBuilder path = new StringBuilder(); // add one match block for each percentage given: try { int whichToken = 0; while (whichToken < tokens.length) { String name = tokens[whichToken++]; if (name.equals("Root")) name = "root"; path.append(name).append(";"); String scoreString = tokens[whichToken++]; if (!scoreString.endsWith(")")) { System.err.println("Expected (number) in: " + line); break; } float bitScore = NumberUtils.parseFloat(scoreString); if (matches.size() < getMaxNumberOfMatchesPerRead() || bitScore > matches.last().bitScore) { Match match = new Match(); match.bitScore = bitScore; match.id = matchId++; String ref = StringUtils.toString(tokens, 0, whichToken, ";") + ";"; match.samLine = makeSAM(queryName, path.toString(), bitScore, ref); matches.add(match); if (matches.size() > getMaxNumberOfMatchesPerRead()) matches.remove(matches.last()); } } } catch (Exception ex) { System.err.println("Error parsing file near line: " + getLineNumber()); if (incrementNumberOfErrors() >= getMaxNumberOfErrors()) throw new RuntimeException("Too many errors"); } return getPostProcessMatches().apply(queryName, matchesTextAndLength, isParseLongReads(), null, matches, null); } /** * gets the matches text * * @return matches text */ @Override public byte[] getMatchesText() { return matchesTextAndLength.getFirst(); } /** * length of matches text * * @return length of text */ @Override public int getMatchesTextLength() { return matchesTextAndLength.getSecond(); } /** * make a SAM line */ private String makeSAM(String queryName, String refName, float bitScore, String line) { return String.format("%s\t0\t%s\t0\t255\t*\t*\t0\t0\t*\t*\tAS:i:%d\t", queryName, refName, Math.round(bitScore)) + String.format("AL:Z:%s\t", StringUtils.replaceSpaces(line, ' ')); } }
5,211
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MatchesText.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/blastxml/MatchesText.java
/* * MatchesText.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.parsers.blast.blastxml; /** * Matches in SAM format * Daniel Huson, 4.2015 */ public class MatchesText { private int numberOfMatches; private byte[] text; private int lengthOfText; public int getNumberOfMatches() { return numberOfMatches; } public void setNumberOfMatches(int numberOfMatches) { this.numberOfMatches = numberOfMatches; } public byte[] getText() { return text; } public void setText(byte[] text) { this.text = text; } public int getLengthOfText() { return lengthOfText; } public void setLengthOfText(int lengthOfText) { this.lengthOfText = lengthOfText; } }
1,512
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
InfoBlock.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/blastxml/InfoBlock.java
/* * InfoBlock.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.parsers.blast.blastxml; import jloda.util.NumberUtils; import jloda.util.Pair; import java.io.StringWriter; import java.util.LinkedList; import java.util.List; /** * a block information * Daniel Huson, 2.11 */ public class InfoBlock { private final String name; private final List<Pair<String, Object>> list = new LinkedList<>(); public InfoBlock(String name) { this.name = name; } public void add(String name, String value) { list.add(new Pair<>(name, value)); } public void addInt(String name, String value) { list.add(new Pair<>(name, NumberUtils.parseInt(value))); } public void addLong(String name, String value) { list.add(new Pair<>(name, NumberUtils.parseLong(value))); } public void addFloat(String name, String value) { list.add(new Pair<>(name, NumberUtils.parseFloat(value))); } public void addDouble(String name, String value) { list.add(new Pair<>(name, NumberUtils.parseDouble(value))); } public String toString() { StringWriter w = new StringWriter(); w.write(name + ":\n"); for (Pair<String, Object> pair : list) { w.write(pair.getFirst() + ": " + pair.getSecond() + "\n"); } return w.toString(); } public Object getValue(String name) { for (Pair<String, Object> pair : list) { if (pair.getFirst().equals(name)) return pair.getSecond(); } return null; } }
2,306
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BlastXMLParser.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/blastxml/BlastXMLParser.java
/* * BlastXMLParser.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.parsers.blast.blastxml; import jloda.util.CanceledException; import jloda.util.FileUtils; import jloda.util.NumberUtils; import megan.parsers.blast.Match; import megan.parsers.blast.Utilities; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.util.LinkedList; import java.util.List; import java.util.TreeSet; import java.util.concurrent.BlockingQueue; /** * parser for BLAST XML files. Matches are posted to the given Queue * Daniel Huson, 2.2011, 4.2015 */ public class BlastXMLParser extends DefaultHandler { static private final long AVERAGE_CHARACTERS_PER_READ = 10000L; // guess used in progress bar static private SAXParserFactory saxParserFactory; // stuff we need to access: private final File blastFile; private final BlockingQueue<MatchesText> blockQueue; private final int maxMatchesPerRead; // general info obtained from the file: private final InfoBlock preamble = new InfoBlock("Preamble"); private final InfoBlock parameters = new InfoBlock("Parameters"); private final InfoBlock stats = new InfoBlock("Stats"); private StringBuilder elementText; private int numberOfReads = 0; private int totalMatches = 0; private int totalDiscardedMatches = 0; private Iteration iteration; private Hit hit; private HSP hsp; private final List<Hit> iterationHits = new LinkedList<>(); private final TreeSet<Match> matches = new TreeSet<>(new Match()); // set of matches found for a given query private final long maximumProgress; /** * constructor * */ public BlastXMLParser(File blastFile, BlockingQueue<MatchesText> blockQueue, int maxMatchesPerRead) { this.blastFile = blastFile; this.blockQueue = blockQueue; this.maxMatchesPerRead = maxMatchesPerRead; maximumProgress = (FileUtils.isZIPorGZIPFile(blastFile.getPath()) ? blastFile.length() / (10 * AVERAGE_CHARACTERS_PER_READ) : blastFile.length() / AVERAGE_CHARACTERS_PER_READ); } /** * apply the parser * */ public void apply() throws CanceledException, IOException, ParserConfigurationException, SAXException { if (saxParserFactory == null) saxParserFactory = SAXParserFactory.newInstance(); SAXParser saxParser = saxParserFactory.newSAXParser(); saxParser.parse(FileUtils.getInputStreamPossiblyZIPorGZIP(blastFile.getPath()), this); } /** * start the document * */ @Override public void startDocument() throws SAXException { super.startDocument(); } /** * end the document * */ @Override public void endDocument() throws SAXException { super.endDocument(); } /** * start an element * */ @Override public void startElement(String uri, String localName, String qName, Attributes attributes) { elementText = new StringBuilder(); switch (qName) { case "Iteration": iteration = new Iteration(); iterationHits.clear(); break; case "Iteration_stat": break; case "Iteration_hits": iterationHits.clear(); break; case "Hit": hit = new Hit(); break; case "Hsp": hsp = new HSP(); break; } } /** * end an element * */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { switch (qName) { case "BlastOutput_program": preamble.add(qName, getElementText()); break; // else if (qName.equals("BlastOutput_query-ID")) // preamble.add(qName, getElementText()); case "BlastOutput_query-def": preamble.add(qName, getElementText()); break; case "BlastOutput_query-len": preamble.add(qName, getElementText()); break; case "BlastOutput_db": preamble.add(qName, getElementText()); break; case "Parameters_matrix": parameters.add(qName, getElementText()); break; case "Parameters_expect": parameters.addDouble(qName, getElementText()); break; case "Parameters_gap-open": parameters.addInt(qName, getElementText()); break; case "Parameters_gap-extend": parameters.addInt(qName, getElementText()); break; case "Parameters_filter": parameters.add(qName, getElementText()); break; case "Iteration": // ending an iteration, write it out numberOfReads++; MatchesText matchesText = new MatchesText(); if (iterationHits.size() == 0) { matchesText.setNumberOfMatches(0); matchesText.setText(iteration.queryDef.getBytes()); matchesText.setLengthOfText(matchesText.getText().length); } else { int numberOfMatches = 0; matches.clear(); for (Hit hit : iterationHits) { if (matches.size() < getMaxMatchesPerRead() || hit.hsp.bitScore > matches.last().getBitScore()) { final Match match = new Match(); final HSP hsp = hit.hsp; match.setBitScore(hsp.bitScore); match.setId(numberOfMatches++); int queryStart = (int) (hsp.queryFrame >= 0 ? hsp.queryFrom : hsp.queryTo); int queryEnd = (int) (hsp.queryFrame >= 0 ? hsp.queryTo : hsp.queryFrom); final StringBuilder buf = new StringBuilder(); if (hit.def != null) buf.append(hit.def); if (hit.id != null) { if (buf.length() > 0) buf.append(" "); buf.append(hit.id).append(" "); } if (hit.accession != null) { if (buf.length() > 0) buf.append(" "); buf.append("acc|").append(hit.accession); } if (buf.length() > 0) buf.append(" "); match.setSamLine(makeSAM(iteration.queryDef, buf.toString().replaceAll("\\s+", " "), hit.len, hsp.bitScore, (float) hsp.eValue, (int) hsp.score, hsp.identity, hsp.queryFrame, queryStart, queryEnd, (int) hsp.hitFrom, (int) hsp.hitTo, hsp.qSeq, hsp.hSeq)); matches.add(match); if (matches.size() > maxMatchesPerRead) matches.remove(matches.last()); } } StringBuilder buf = new StringBuilder(); for (Match match : matches) { buf.append(match.getSamLine()).append("\n"); } matchesText.setText(buf.toString().getBytes()); matchesText.setLengthOfText(matchesText.getText().length); matchesText.setNumberOfMatches(matches.size()); totalMatches += iterationHits.size(); totalDiscardedMatches += (iterationHits.size() - matchesText.getNumberOfMatches()); } try { blockQueue.put(matchesText); } catch (InterruptedException e) { throw new SAXException("Interrupted"); } break; case "Iteration_iter-num": iteration.iterNum = NumberUtils.parseLong(getElementText()); break; // else if (qName.equals("Iteration_query-ID")) // iteration.queryID = getElementText(); case "Iteration_query-def": iteration.queryDef = getElementText(); break; case "Iteration_query-len": iteration.queryLen = NumberUtils.parseInt(getElementText()); break; case "Hit_def": hit.def = getElementText(); break; case "Hit_accession": hit.accession = getElementText(); break; case "Hit_id": hit.id = getElementText(); break; case "Hit_len": hit.len = NumberUtils.parseInt(getElementText()); break; case "Hsp": // todo: a hit can have more than one HSP but we only keep the first one, for now if (hit.hsp == null || hsp.bitScore > hit.hsp.bitScore) hit.hsp = hsp; break; case "Hit": iterationHits.add(hit); break; case "Hsp_bit-score": hsp.bitScore = NumberUtils.parseFloat(getElementText()); break; case "Hsp_score": hsp.score = NumberUtils.parseFloat(getElementText()); break; case "Hsp_evalue": hsp.eValue = NumberUtils.parseDouble(getElementText()); break; case "Hsp_query-from": hsp.queryFrom = Long.parseLong(getElementText()); break; case "Hsp_query-to": hsp.queryTo = NumberUtils.parseLong(getElementText()); break; case "Hsp_hit-from": hsp.hitFrom = NumberUtils.parseLong(getElementText()); break; case "Hsp_hit-to": hsp.hitTo = NumberUtils.parseLong(getElementText()); break; case "Hsp_hit-frame": hsp.hitFrame = NumberUtils.parseInt(getElementText()); break; case "Hsp_query-frame": hsp.queryFrame = NumberUtils.parseInt(getElementText()); break; case "Hsp_identity": hsp.identity = NumberUtils.parseInt(getElementText()); break; case "Hsp_positive": hsp.positive = NumberUtils.parseInt(getElementText()); break; case "Hsp_gaps": hsp.gaps = NumberUtils.parseInt(getElementText()); break; case "Hsp_align-len": hsp.alignLength = NumberUtils.parseInt(getElementText()); break; case "Hsp_density": hsp.density = NumberUtils.parseInt(getElementText()); break; case "Hsp_qseq": hsp.qSeq = getElementText(); break; case "Hsp_hseq": hsp.hSeq = getElementText(); break; case "Hsp_midline": hsp.midLine = getElementText(); break; case "Statistics_db-num": stats.addLong(qName, getElementText()); break; case "Statistics_db-len": stats.addLong(qName, getElementText()); break; case "Statistics_hsp-len": stats.addLong(qName, getElementText()); break; case "Statistics_eff-space": stats.addDouble(qName, getElementText()); break; case "Statistics_kappa": stats.addFloat(qName, getElementText()); break; case "Statistics_lambda": stats.addFloat(qName, getElementText()); break; case "Statistics_entropy": stats.addFloat(qName, getElementText()); break; } } /** * resolve an entity * */ @Override public InputSource resolveEntity(String publicId, String systemId) { return new InputSource(new StringReader("")); } /** * build current element text * */ @Override public void characters(char[] chars, int start, int length) { elementText.append(chars, start, length); } /** * get the text of the current element * * @return text */ private String getElementText() { return elementText.toString(); } public int getNumberOfReads() { return numberOfReads; } public int getTotalMatches() { return totalMatches; } public int getTotalDiscardedMatches() { return totalDiscardedMatches; } private int getMaxMatchesPerRead() { return maxMatchesPerRead; } public long getMaximumProgress() { return maximumProgress; } public long getProgress() { return numberOfReads * AVERAGE_CHARACTERS_PER_READ; } /** * make a SAM line */ private String makeSAM(String queryName, String refName, int referenceLength, float bitScore, float expect, int rawScore, float percentIdentity, int frame, int queryStart, int queryEnd, int referenceStart, int referenceEnd, String alignedQuery, String alignedReference) { final StringBuilder buffer = new StringBuilder(); buffer.append(queryName).append("\t"); buffer.append(0); buffer.append("\t"); buffer.append(refName).append("\t"); buffer.append(referenceStart).append("\t"); buffer.append("255\t"); Utilities.appendCigar(alignedQuery, alignedReference, buffer); buffer.append("\t"); buffer.append("*\t"); buffer.append("0\t"); buffer.append("0\t"); buffer.append(alignedQuery.replaceAll("-", "")).append("\t"); buffer.append("*\t"); buffer.append(String.format("AS:i:%d\t", Math.round(bitScore))); buffer.append(String.format("NM:i:%d\t", Utilities.computeEditDistance(alignedQuery, alignedReference))); buffer.append(String.format("ZL:i:%d\t", referenceLength)); buffer.append(String.format("ZR:i:%d\t", rawScore)); buffer.append(String.format("ZE:f:%g\t", expect)); buffer.append(String.format("ZI:i:%d\t", Math.round(percentIdentity))); if (frame != 0) buffer.append(String.format("ZF:i:%d\t", frame)); buffer.append(String.format("ZS:i:%s\t", queryStart)); Utilities.appendMDString(alignedQuery, alignedReference, buffer); return buffer.toString(); } /** * blast iteration */ static class Iteration { long iterNum; // public String queryID; String queryDef; int queryLen; } /** * a hit as retrieved in XML file */ static class Hit { String def; String accession; String id; int len; HSP hsp; } }
16,215
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
HSP.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/blast/blastxml/HSP.java
/* * HSP.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.parsers.blast.blastxml; import jloda.util.StringUtils; /** * Blast HSP * Daniel Huson, 2.2011, 4.2015 */ public class HSP { public float bitScore; public float score; public double eValue; public long queryFrom; public long queryTo; public long hitFrom; public long hitTo; public int queryFrame; public int hitFrame; public int identity; public int positive; public int gaps; public int alignLength; public int density; public String qSeq; public String hSeq; public String midLine; /** * return human readable string representation * * @return string */ public String toString(String hitDef, int hitLen) { StringBuilder buffer = new StringBuilder(); buffer.append(String.format(">%s\n\tLength = %d\n", StringUtils.fold(hitDef, 100), hitLen)); buffer.append(String.format(" Score = %.1f bits (%.1f), Expect= %e\n", bitScore, score, eValue)); buffer.append(String.format(" Identities = %d/%d (%d%%), Positives = %d/%d (%d%%), Gaps = %d/%d (%d%%)\n", identity, alignLength, Math.round(100 * identity / alignLength), positive, alignLength, 100 * positive / alignLength, gaps, alignLength, 100 * gaps / alignLength)); if (queryFrame != 0) buffer.append(String.format(" Frame = %+d\n", queryFrame)); if (qSeq != null && hSeq != null) { long a = (queryFrame >= 0 ? queryFrom : queryTo); long b = (queryFrame >= 0 ? queryTo : queryFrom); buffer.append(String.format("\nQuery:%9d %s %d\n", a, qSeq, b)); if (midLine != null) buffer.append(String.format(" %s\n", midLine)); buffer.append(String.format("Sbjct:%9d %s %d\n", hitFrom, hSeq, hitTo)); } else buffer.append("[No alignment given]\n"); return buffer.toString(); } }
2,710
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SAMMatch.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/sam/SAMMatch.java
/* * SAMMatch.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.parsers.sam; import jloda.seq.BlastMode; import jloda.seq.SequenceUtils; import jloda.util.NumberUtils; import jloda.util.Single; import jloda.util.StringUtils; import megan.util.BlosumMatrix; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * a match in SAM format * Daniel Huson, 3.2011 */ public class SAMMatch implements megan.rma3.IMatch { private static final int ALIGNMENT_FOLD = 120; private final String pairedReadSuffix1; private final String pairedReadSuffix2; private final BlastMode mode; public static final boolean warnAboutProblems = true; private String[] tokens = new String[12]; /* 0 QNAME String 1 FLAG Int 2 RNAME String 3 POS Int 4 MAPQ Int 5 CIGAR String 6 RNEXT String 7 PNEXT Int 8 TLEN Int 9 SEQ String 10 QUAL String Regexp/Range [!-?A-~]{1,255} [0,216 -1] \*|[!-()+-<>-~][!-~]* [0,229 -1][0,28 -1] \*|([0-9]+[MIDNSHPX=])+ \*|=|[!-()+-<>-~][!-~]* [0,229 -1] [-229 +1,229 -1] \*|[A-Za-z=.]+ [!-~]+ Brief description Query template NAME bitwise FLAG Reference sequence NAME 1-based leftmost mapping POSition MAPping Quality CIGAR string Ref. name of the mate/next fragment Position of the mate/next fragment observed Template LENgth fragment SEQuence ASCII of Phred-scaled base QUALity+33 */ private String queryName; private int alignedQueryStart; private int alignedQueryEnd; private int flag; private String refName; private int pos; private int mapQuality; private String cigarString; private String RNext; private int PNext; private int TLength; private String sequence; private String quality; private final Map<String, Object> optionalFields = new HashMap<>(); private Cigar cigar; /** * constructor */ public SAMMatch(BlastMode mode) { this(mode, null, null); } /** * constructor * */ public SAMMatch(BlastMode mode, String pairedReadSuffix1, String pairedReadSuffix2) { this.mode = mode; this.pairedReadSuffix1 = pairedReadSuffix1; this.pairedReadSuffix2 = pairedReadSuffix2; } /** * erase the match */ @Override public void clear() { queryName = null; alignedQueryStart = 0; alignedQueryEnd = 0; flag = 0; refName = null; pos = 0; mapQuality = 0; cigarString = null; RNext = null; PNext = 0; TLength = 0; sequence = null; quality = null; optionalFields.clear(); cigar = null; } /** * parse a line of SAM format * */ public void parse(byte[] aLine, int length) throws IOException { int numberOfTokens = 0; int start = 0; while (start < length) { int end = start; while (aLine[end] != '\t' && end < length) end++; if (numberOfTokens == tokens.length) { String[] tmp = new String[2 * tokens.length]; System.arraycopy(tokens, 0, tmp, 0, tokens.length); tokens = tmp; } tokens[numberOfTokens++] = StringUtils.toString(aLine, start, end - start); start = end + 1; } parse(tokens, numberOfTokens); } /** * parse a line of SAM format * */ @Override public void parse(String aLine) throws IOException { String[] tokens = aLine.trim().split("\t"); parse(tokens, tokens.length); /* int numberOfTokens = 0; int start = 0; while (start < aLine.length()) { int end = aLine.indexOf('\t', start); if (end == -1) end = aLine.length(); if (numberOfTokens == tokens.length) { String[] tmp = new String[2 * tokens.length]; System.arraycopy(tokens, 0, tmp, 0, tokens.length); tokens = tmp; } tokens[numberOfTokens++] = aLine.substring(start, end); start = end + 1; } parse(tokens, numberOfTokens); */ } /** * parse a line of SAM format * */ public void parse(String[] tokens, int numberOfTokens) throws IOException { if (numberOfTokens < 11) { throw new IOException("Too few tokens in line: " + numberOfTokens); } setQueryName(tokens[0]); setFlag(NumberUtils.parseInt(tokens[1])); setRefName(tokens[2]); setPos(NumberUtils.parseInt(tokens[3])); setMapQuality(NumberUtils.parseInt(tokens[4])); setCigarString(tokens[5]); setRNext(tokens[6]); setPNext(NumberUtils.parseInt(tokens[7])); setTLength(Math.abs(NumberUtils.parseInt(tokens[8]))); //setSequence(isReverseComplemented() ? SequenceUtils.getReverseComplement(tokens[9]) : tokens[9]); setSequence(tokens[9].toUpperCase()); setQuality(tokens[10]); for (int i = 11; i < numberOfTokens; i++) { final String word = tokens[i]; int pos1 = word.indexOf(':'); int pos2 = word.indexOf(':', pos1 + 1); if (pos2 == -1) throw new IOException("Failed to parse: " + word); final String[] three = new String[]{word.substring(0, pos1), word.substring(pos1 + 1, pos2), word.substring(pos2 + 1)}; final Object object = switch (three[1].charAt(0)) { case 'A' -> //character three[2].charAt(0); case 'i' -> // integer NumberUtils.parseInt(three[2]); case 'f' -> // float NumberUtils.parseFloat(three[2]); case 'Z' -> //string three[2]; case 'H' -> // hex string Integer.valueOf(three[2]); default -> throw new IOException("Failed to parse: " + word); }; optionalFields.put(three[0], object); } Flag theFlag = new Flag(flag); if (pairedReadSuffix1 != null && !theFlag.isFirstFragment() && !getQueryName().endsWith(pairedReadSuffix1)) setQueryName(getQueryName() + pairedReadSuffix1); if (pairedReadSuffix2 != null && !theFlag.isLastFragment() && !getQueryName().endsWith(pairedReadSuffix2)) setQueryName(getQueryName() + pairedReadSuffix2); alignedQueryStart = determineQueryStart(); alignedQueryEnd = determineQueryEnd(alignedQueryStart); } /** * determine the query start position * * @return query start */ private int determineQueryStart() { int queryStart = 1; Object obj = optionalFields.get("ZS"); if (obj instanceof Integer) { queryStart = (Integer) obj; } else { // first need to trim: if (mode != BlastMode.BlastX) { if (getCigar().getCigarElements().size() > 0) { CigarElement element = getCigar().getCigarElement(0); if (element.getOperator() == CigarOperator.S || element.getOperator() == CigarOperator.H) { queryStart = element.getLength() + 1; } } } else { if (getCigar().getCigarElements().size() > 0) { CigarElement element = getCigar().getCigarElement(0); if (element.getOperator() == CigarOperator.S || element.getOperator() == CigarOperator.H) { queryStart = 3 * element.getLength() + 1; } } } } return queryStart; } /** * determine the query end position * * @return query end */ private int determineQueryEnd(int alignedQueryStart) { final Object zq = optionalFields.get("ZQ"); if (zq instanceof Integer) { return (Integer) zq; } int alignedQueryLength = computeAlignedQuerySegmentLength(getSequence()); if (mode == BlastMode.BlastX) { final Object df = optionalFields.get("ZF"); final boolean reverse = (df instanceof Integer && ((Integer) df) < 0); if (reverse) return alignedQueryStart - alignedQueryLength + 1; } return alignedQueryStart + alignedQueryLength - 1; } /** * return string representation * * @return as string */ public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append(getQueryName()).append("\t"); buffer.append(getFlag()).append("\t"); buffer.append(getRefName()).append("\t"); buffer.append(getPos()).append("\t"); buffer.append(getMapQuality()).append("\t"); buffer.append(getCigarString()).append("\t"); buffer.append(getRNext()).append("\t"); buffer.append(getPNext()).append("\t"); buffer.append(getTLength()).append("\t"); buffer.append(getSequence()).append("\t"); buffer.append(getQuality()); for (String a : getOptionalFields().keySet()) { Object value = getOptionalFields().get(a); buffer.append("\t").append(a).append(":").append(getType(value)).append(":").append(value); } return buffer.toString(); } /** * gets the type code for a value * * @return type */ private char getType(Object value) { if (value instanceof Integer) return 'i'; else if (value instanceof Float) return 'f'; else if (value instanceof Character) return 'A'; else if (value instanceof String) return 'Z'; else return '?'; } /** * gets match as blast alignment text * * @return blast alignment text */ public String getBlastAlignmentText() { return getBlastAlignmentText(null); } /** * gets match as blast alignment text * * @param percentIdentity variable to save percent identity to in the case of a blastN match * @return blast alignment text */ public String getBlastAlignmentText(final Single<Float> percentIdentity) { return switch (mode) { case BlastX -> getBlastXAlignment(percentIdentity); case BlastP -> getBlastPAlignment(percentIdentity); case BlastN -> getBlastNAlignment(percentIdentity); default -> ""; }; } /** * return a BlastNText alignment * */ private String getBlastNAlignment(final Single<Float> percentIdentity) { final int editDistance = getEditDistance(); final String query = getSequence(); final String[] aligned = computeAlignment(query); if (aligned[0].equals("No alignment")) { return shortDescription(); } if (isReverseComplemented()) { aligned[0] = SequenceUtils.getReverseComplement(aligned[0]); aligned[1] = SequenceUtils.getReverse(aligned[1]); aligned[2] = SequenceUtils.getReverseComplement(aligned[2]); } int identities = 0; for (int i = 0; i < aligned[1].length(); i++) { if (aligned[1].charAt(i) == '|') identities++; } int alignmentLength = aligned[1].length(); String alignedQuery = getUngappedSequence(aligned[0]); int queryLength = alignedQuery.length(); int refLength = getUngappedLength(aligned[2]); int gaps = 2 * aligned[0].length() - queryLength - getUngappedLength(aligned[2]); StringBuilder buffer = new StringBuilder(); buffer.append(String.format(">%s\n", StringUtils.fold(refName, ALIGNMENT_FOLD))); { final int len = getRefLength(); if (len >= refLength) buffer.append(String.format("\tLength = %d\n\n", len)); else buffer.append(String.format("\tLength >= %d\n\n", (getPos() + refLength - 1))); } if (optionalFields.get("AS") != null && optionalFields.get("AS") instanceof Integer) { if (optionalFields.get("ZR") != null && optionalFields.get("ZR") instanceof Integer && optionalFields.get("ZE") != null && optionalFields.get("ZE") instanceof Float) { int bitScore = getBitScore(); int rawScore = getRawScore(); float expect = getExpected(); if (expect == 0) buffer.append(String.format(" Score = %d bits (%d), Expect = 0\n", bitScore, rawScore)); else buffer.append(String.format(" Score = %d bits (%d), Expect = %.1g\n", bitScore, rawScore, expect)); } else { buffer.append(String.format(" Score = %d\n", optionalFields.get("AS"))); } } else buffer.append(String.format("MapQuality = %d EditDistance=%d\n", getMapQuality(), editDistance)); float pIdentity = 100f * identities / alignmentLength; if (percentIdentity != null) percentIdentity.set(pIdentity); buffer.append(String.format(" Identities = %d/%d (%d%%), Gaps = %d/%d (%d%%)\n", identities, alignmentLength, Math.round(pIdentity), gaps, alignmentLength, Math.round(100.0 * gaps / queryLength))); buffer.append(" Strand = Plus / ").append(isReverseComplemented() ? "Minus" : "Plus").append("\n"); int qStart = getAlignedQueryStart(); int qEnd = 0; int sStart = !isReverseComplemented() ? getPos() : (getPos() + refLength - 1); int sEnd = 0; for (int pos = 0; pos < Objects.requireNonNull(aligned[0]).length(); pos += ALIGNMENT_FOLD) { if (getSequence() != null && aligned[0] != null) { int qAdd = Math.min(ALIGNMENT_FOLD, aligned[0].length() - pos); String qPart = aligned[0].substring(pos, pos + qAdd); int qGaps = countGapsDashDotStar(qPart); qEnd = qStart + (qAdd - qGaps) - 1; buffer.append(String.format("\nQuery:%9d %s %d\n", qStart, qPart, qEnd)); qStart = qEnd + 1; } if (aligned[1] != null) { int mAdd = Math.min(ALIGNMENT_FOLD, aligned[1].length() - pos); String mPart = aligned[1].substring(pos, pos + mAdd); buffer.append(String.format(" %s\n", mPart)); } if (aligned[2] != null) { int sAdd = Math.min(ALIGNMENT_FOLD, aligned[2].length() - pos); String sPart = aligned[2].substring(pos, pos + sAdd).toUpperCase(); int sGaps = countGapsDashDotStar(sPart); if (!isReverseComplemented()) sEnd = sStart + (sAdd - sGaps) - 1; else sEnd = sStart - (sAdd - sGaps) + 1; buffer.append(String.format("Sbjct:%9d %s %d\n", sStart, sPart, sEnd)); if (!isReverseComplemented()) sStart = sEnd + 1; else sStart = sEnd - 1; } } if (qEnd > 0 && qEnd != getAlignedQueryStart() + queryLength - 1 && warnAboutProblems) System.err.println("Internal error writing BLAST format: qEnd=" + qEnd + ", should be: " + (getAlignedQueryStart() + queryLength - 1)); if (aligned[2] != null) { int sEndShouldBe = (!isReverseComplemented() ? (getPos() + refLength - 1) : getPos()); if (sEnd > 0 && sEnd != sEndShouldBe && warnAboutProblems) System.err.println("Internal error writing BLAST format: sEnd=" + sEnd + ", should be: " + sEndShouldBe); } return buffer.toString(); } /** * return a BlastPText alignment * */ private String getBlastPAlignment(final Single<Float> percentIdentity) { final int editDistance = getEditDistance(); final String query = getSequence(); final String[] aligned = computeAlignment(query); if (aligned[0].equals("No alignment")) { return shortDescription(); } int identities = 0; for (int i = 0; i < aligned[1].length(); i++) { if (aligned[1].charAt(i) != '+' && aligned[1].charAt(i) != ' ') identities++; } int alignmentLength = aligned[1].length(); String alignedQuery = getUngappedSequence(aligned[0]); int queryLength = alignedQuery.length(); int refLength = getUngappedLength(aligned[2]); int gaps = 2 * aligned[0].length() - queryLength - getUngappedLength(aligned[2]); StringBuilder buffer = new StringBuilder(); buffer.append(String.format(">%s\n", StringUtils.fold(refName, ALIGNMENT_FOLD))); { final int len = getRefLength(); if (len >= refLength) buffer.append(String.format("\tLength = %d\n\n", len)); else buffer.append(String.format("\tLength >= %d\n\n", (getPos() + refLength - 1))); } if (optionalFields.get("AS") != null && optionalFields.get("AS") instanceof Integer) { if (optionalFields.get("ZR") != null && optionalFields.get("ZR") instanceof Integer && optionalFields.get("ZE") != null && optionalFields.get("ZE") instanceof Float) { int bitScore = getBitScore(); int rawScore = getRawScore(); float expect = getExpected(); if (expect == 0) buffer.append(String.format(" Score = %d bits (%d), Expect = 0\n", bitScore, rawScore)); else buffer.append(String.format(" Score = %d bits (%d), Expect = %.1g\n", bitScore, rawScore, expect)); } else { buffer.append(String.format(" Score = %d\n", optionalFields.get("AS"))); } } else buffer.append(String.format("MapQuality = %d EditDistance=%d\n", getMapQuality(), editDistance)); int numberOfPositives = alignmentLength - StringUtils.countOccurrences(aligned[1], ' '); float pIdentity = 100f * identities / alignmentLength; if (percentIdentity != null) percentIdentity.set(pIdentity); buffer.append(String.format(" Identities = %d/%d (%d%%), Positives = %d/%d (%.0f%%), Gaps = %d/%d (%d%%)\n", identities, alignmentLength, Math.round(pIdentity), numberOfPositives, alignmentLength, (100.0 * (numberOfPositives) / alignmentLength), gaps, alignmentLength, Math.round(100.0 * gaps / queryLength))); int qStart = getAlignedQueryStart(); int qEnd = 0; int sStart = getPos(); int sEnd = 0; for (int pos = 0; pos < Objects.requireNonNull(aligned[0]).length(); pos += ALIGNMENT_FOLD) { if (getSequence() != null && aligned[0] != null) { int qAdd = Math.min(ALIGNMENT_FOLD, aligned[0].length() - pos); String qPart = aligned[0].substring(pos, pos + qAdd); int qGaps = countGapsDashDot(qPart); qEnd = qStart + (qAdd - qGaps) - 1; buffer.append(String.format("\nQuery:%9d %s %d\n", qStart, qPart, qEnd)); qStart = qEnd + 1; } if (aligned[1] != null) { int mAdd = Math.min(ALIGNMENT_FOLD, aligned[1].length() - pos); String mPart = aligned[1].substring(pos, pos + mAdd); buffer.append(String.format(" %s\n", mPart)); } if (aligned[2] != null) { int sAdd = Math.min(ALIGNMENT_FOLD, aligned[2].length() - pos); String sPart = aligned[2].substring(pos, pos + sAdd).toUpperCase(); int sGaps = countGapsDashDot(sPart); sEnd = sStart + (sAdd - sGaps) - 1; buffer.append(String.format("Sbjct:%9d %s %d\n", sStart, sPart, sEnd)); sStart = sEnd + 1; } } if (qEnd > 0 && qEnd != getAlignedQueryStart() + queryLength - 1 && warnAboutProblems) System.err.println("Internal error writing BLAST format: qEnd=" + qEnd + ", should be: " + (getAlignedQueryStart() + queryLength - 1)); if (aligned[2] != null) { int sEndShouldBe = (getPos() + refLength - 1); if (sEnd > 0 && sEnd != sEndShouldBe && warnAboutProblems) System.err.println("Internal error writing BLAST format: sEnd=" + sEnd + ", should be: " + sEndShouldBe); } return buffer.toString(); } /** * return a BlastText alignment * */ private String getBlastXAlignment(final Single<Float> percentIdentity) { final int editDistance = getEditDistance(); final String query = getSequence(); final String[] aligned = computeAlignment(query); if (aligned[0].equals("No alignment")) { return shortDescription(); } int identities = 0; for (int i = 0; i < aligned[1].length(); i++) { if (aligned[1].charAt(i) != '+' && aligned[1].charAt(i) != ' ') identities++; } final int alignmentLength = aligned[1].length(); final int queryLengthForGapCalculation = getUngappedSequence(aligned[0]).length(); // query length as required for gaps calculation, this differs from actual length that must take frame shifts into account final int refLength = getUngappedLength(aligned[2]); final int gaps = 2 * aligned[0].length() - queryLengthForGapCalculation - getUngappedLength(aligned[2]); final StringBuilder buffer = new StringBuilder(); buffer.append(String.format(">%s\n", StringUtils.fold(refName, ALIGNMENT_FOLD))); { final int len = getRefLength(); if (len >= refLength) buffer.append(String.format("\tLength = %d\n\n", len)); else buffer.append(String.format("\tLength >= %d\n\n", (getPos() + refLength - 1))); } // get query frame: final int qFrame; { final Object obj = optionalFields.get("ZF"); if (obj instanceof Integer) { qFrame = (Integer) obj; } else qFrame = 0; } final int qJump = (qFrame >= 0 ? 3 : -3); if (optionalFields.get("AS") != null && optionalFields.get("AS") instanceof Integer) { if (optionalFields.get("ZR") != null && optionalFields.get("ZR") instanceof Integer && optionalFields.get("ZE") != null && optionalFields.get("ZE") instanceof Float) { int bitScore = getBitScore(); int rawScore = getRawScore(); float expect = getExpected(); if (expect == 0) buffer.append(String.format(" Score = %d bits (%d), Expect = 0\n", bitScore, rawScore)); else buffer.append(String.format(" Score = %d bits (%d), Expect = %.1g\n", bitScore, rawScore, expect)); } else { buffer.append(String.format(" Score = %d\n", optionalFields.get("AS"))); } } else buffer.append(String.format("MapQuality = %d EditDistance=%d\n", getMapQuality(), editDistance)); int numberOfPositives = alignmentLength - StringUtils.countOccurrences(aligned[1], ' '); float pIdentity = 100f * identities / alignmentLength; if (percentIdentity != null) percentIdentity.set(pIdentity); buffer.append(String.format(" Identities = %d/%d (%d%%), Positives = %d/%d (%.0f%%), Gaps = %d/%d (%d%%)\n", identities, alignmentLength, Math.round(pIdentity), numberOfPositives, alignmentLength, (100.0 * (numberOfPositives) / alignmentLength), gaps, alignmentLength, Math.round((100.0 * gaps / queryLengthForGapCalculation)))); if (qFrame != 0) buffer.append(String.format(" Frame = %+d\n", qFrame)); int qEnd = 0; final int sStart = !isReverseComplemented() ? getPos() : (getPos() + refLength - 1); int sStartPart = sStart; int sEnd = 0; int qStartPart = determineQueryStart(); for (int pos = 0; pos < Objects.requireNonNull(aligned[0]).length(); pos += ALIGNMENT_FOLD) { if (getSequence() != null && aligned[0] != null) { int qAdd = Math.min(ALIGNMENT_FOLD, aligned[0].length() - pos); String qPart = aligned[0].substring(pos, pos + qAdd); int qGaps = countGapsDashDot(qPart); int qFrameShiftChange = countFrameShiftChange(qPart); qEnd = qStartPart + qJump * (qAdd - qGaps) + (qFrame > 0 ? qFrameShiftChange : -qFrameShiftChange) + (qFrame > 0 ? -1 : 1); buffer.append(String.format("\nQuery:%9d %s %d\n", qStartPart, qPart, qEnd)); qStartPart = qEnd + (qFrame < 0 ? -1 : 1); } if (aligned[1] != null) { int mAdd = Math.min(ALIGNMENT_FOLD, aligned[1].length() - pos); String mPart = aligned[1].substring(pos, pos + mAdd); buffer.append(String.format(" %s\n", mPart)); } if (aligned[2] != null) { int sAdd = Math.min(ALIGNMENT_FOLD, aligned[2].length() - pos); String sPart = aligned[2].substring(pos, pos + sAdd).toUpperCase(); int sGaps = countGapsDashDot(sPart); if (!isReverseComplemented()) sEnd = sStartPart + (sAdd - sGaps) - 1; else sEnd = sStartPart - (sAdd - sGaps) + 1; buffer.append(String.format("Sbjct:%9d %s %d\n", sStartPart, sPart, sEnd)); if (!isReverseComplemented()) sStartPart = sEnd + 1; else sStartPart = sEnd - 1; } } if (qEnd > 0 && qEnd != alignedQueryEnd && warnAboutProblems) { // System.err.println(buffer.toString()); System.err.println("Internal error writing BLAST format: query length is incorrect"); } if (aligned[2] != null) { int sEndShouldBe = (!isReverseComplemented() ? (getPos() + refLength - 1) : getPos()); if (sEnd > 0 && sEnd != sEndShouldBe && warnAboutProblems) System.err.println("Internal error writing BLAST format: sEnd=" + sEnd + ", should be: " + sEndShouldBe); } return buffer.toString(); } private int countFrameShiftChange(String qPart) { int count = 0; for (int i = 0; i < qPart.length(); i++) { if (qPart.charAt(i) == '\\') // forward shift count -= 2; else if (qPart.charAt(i) == '/') // reverse shift count -= 4; } return count; } /** * gets a short description of a match * This is used for BlastTab and similar incomplete formats * * @return short description */ private String shortDescription() { StringBuilder buffer = new StringBuilder(); if (refName.length() > 0) buffer.append(String.format(">%s\n", StringUtils.fold(refName, ALIGNMENT_FOLD))); { if (getRefLength() > 9) buffer.append(String.format("\tLength = %d\n\n", getRefLength())); else buffer.append("\n"); } { boolean hasFirst = false; boolean hasSecond = false; if (optionalFields.get("AS") != null && optionalFields.get("AS") instanceof Integer) { buffer.append(String.format(" Score = %d", getBitScore())); if (optionalFields.get("ZR") != null && optionalFields.get("ZR") instanceof Integer) { buffer.append(String.format(" bits (%d)", getRawScore())); } hasFirst = true; } if (optionalFields.get("ZE") != null && optionalFields.get("ZE") instanceof Float) { if (hasFirst) buffer.append(","); if (getExpected() == 0) buffer.append(" Expect = 0"); else buffer.append(String.format(" Expect = %.1g", getExpected())); hasSecond = true; } if (hasFirst || hasSecond) buffer.append("\n"); } { if (optionalFields.get("AL") != null) buffer.append(optionalFields.get("AL").toString()).append("\n"); } return buffer.toString(); } private String getUngappedSequence(String s) { StringBuilder buffer = new StringBuilder(); for (int i = 0; i < s.length(); i++) if (!isGap(s.charAt(i))) buffer.append(s.charAt(i)); return buffer.toString(); } /** * get the ungapped length of a gapped string * * @return ungapped length */ private int getUngappedLength(String s) { int count = 0; for (int i = 0; i < s.length(); i++) if (!isGap(s.charAt(i))) count++; return count; } /** * get the edit distance * * @return edit distance */ private int getEditDistance() { Integer value = (Integer) getOptionalFields().get("NM"); return value != null ? value : 0; } @Override public int getBitScore() { try { return (Integer) optionalFields.get("AS"); } catch (Exception ex) { return 0; } } private int getRawScore() { try { return (Integer) optionalFields.get("ZR"); } catch (Exception ex) { return 0; } } @Override public float getExpected() { try { return (Float) optionalFields.get("ZE"); } catch (Exception ex) { return 0; } } @Override public int getPercentIdentity() { try { return (Integer) optionalFields.get("ZI"); } catch (Exception ex) { return 0; } } /** * count the number of gaps ('-', '.', '*') in a sequence * * @return number of gaps */ private static int countGapsDashDotStar(String sequence) { int count = 0; for (int i = 0; i < sequence.length(); i++) { int a = sequence.charAt(i); if (a == '-' || a == '.' || a == '*') count++; } return count; } /** * count the number of gaps ('-', '.') in a sequence * * @return number of gaps */ private static int countGapsDashDot(String sequence) { int count = 0; for (int i = 0; i < sequence.length(); i++) { int a = sequence.charAt(i); if (a == '-' || a == '.') count++; } return count; } /** * compute three line description of alignment (query, midline, subject) * * @param query trimmed query string * @return alignment */ private String[] computeAlignment(String query) { if (getCigar().getCigarElements().size() == 0) // not available { return new String[]{"No alignment", "mapQ=0 (not uniquely mapped)", ""}; } if (getCigar().hasFrameShift()) { return new String[]{"No alignment", "Contains frame-shift, not supported", ""}; } final String[] pair = computeAlignmentPair(query); if (pair[0].equals("No alignment")) return pair; final String gappedQuerySequence = pair[0]; final String gappedReferenceSequence = pair[1]; final StringBuilder midBuffer = new StringBuilder(); int top = Math.min(gappedQuerySequence.length(), gappedReferenceSequence.length()); switch (mode) { case BlastX: case BlastP: for (int i = 0; i < top; i++) { byte a = (byte) Character.toUpperCase(gappedQuerySequence.charAt(i)); byte b = (byte) Character.toUpperCase(gappedReferenceSequence.charAt(i)); if (Character.isLetter(a) && Character.isLetter(b)) { if (a == b) midBuffer.append((char) a); else if (BlosumMatrix.getBlosum62().getScore(a, b) > 0) midBuffer.append('+'); else midBuffer.append(' '); } else midBuffer.append(" "); } break; default: case BlastN: for (int i = 0; i < top; i++) { if (Character.isLetter(gappedQuerySequence.charAt(i)) && gappedQuerySequence.charAt(i) == gappedReferenceSequence.charAt(i)) midBuffer.append("|"); else if (isGap(gappedQuerySequence.charAt(i)) || isGap(gappedReferenceSequence.charAt(i))) midBuffer.append(" "); else midBuffer.append(" "); } } return new String[]{gappedQuerySequence, midBuffer.toString(), gappedReferenceSequence}; } /** * compute two line description of alignment (query, subject) * * @param query trimmed query string * @return alignment */ private String[] computeAlignmentPair(String query) { if (getCigar().getCigarElements().size() == 0) // not available { return new String[]{"No alignment", "mapQ=0 (not uniquely mapped)", ""}; } if (query.equals("*") || query.length() == 0) return new String[]{"No alignment", "no string stored"}; boolean hardClippedPositionsHaveBeenInserted = (query.charAt(0) == 0); // hard clipped positions have been inserted into query string as 0's, must advance position when parsing leading hard clip final StringBuilder gappedQueryBuffer = new StringBuilder(); final StringBuilder gappedReferenceBuffer = new StringBuilder(); int posQuery = 0; for (CigarElement element : getCigar().getCigarElements()) { for (int i = 0; i < element.getLength(); i++) { final char queryChar = (posQuery < query.length() ? query.charAt(posQuery) : 0); // todo: should not need to check whether posQuery is in range, but minimap produces files that cause this problem switch (element.getOperator()) { case D: gappedQueryBuffer.append("-"); gappedReferenceBuffer.append("?"); break; case M: gappedQueryBuffer.append(queryChar); gappedReferenceBuffer.append("?"); posQuery++; break; case I: gappedQueryBuffer.append(queryChar); gappedReferenceBuffer.append("-"); posQuery++; break; case N: gappedQueryBuffer.append("."); gappedReferenceBuffer.append("?"); break; case S: if (!hardClippedPositionsHaveBeenInserted) posQuery++; break; case H: if (hardClippedPositionsHaveBeenInserted) posQuery++; //hard clipped positions have been inserted into query string (as 0's), must advance position break; case P: gappedQueryBuffer.append("*"); gappedReferenceBuffer.append("*"); break; case EQ: gappedQueryBuffer.append(queryChar); gappedReferenceBuffer.append(queryChar); posQuery++; break; case FF: gappedQueryBuffer.append("/"); gappedReferenceBuffer.append("-"); break; case FR: gappedQueryBuffer.append("\\"); gappedReferenceBuffer.append("-"); break; case X: gappedQueryBuffer.append(queryChar); gappedReferenceBuffer.append("?"); break; } } } final String gappedQuerySequence = gappedQueryBuffer.toString(); final String gappedReferenceSequence; String mdString = (String) getOptionalFields().get("MD"); if (mdString == null) mdString = (String) getOptionalFields().get("md"); if (mdString != null) { gappedReferenceSequence = Diff.getReference(mdString, gappedQuerySequence, gappedReferenceBuffer.toString()); } else gappedReferenceSequence = gappedReferenceBuffer.toString(); return new String[]{gappedQuerySequence, gappedReferenceSequence}; } /** * compute the aligned query segment length * * @param query query sequence * @return aligned query length */ private int computeAlignedQuerySegmentLength(String query) { if (query.equals("*") || query.length() == 0) return 0; int length = 0; for (CigarElement element : getCigar().getCigarElements()) { for (int i = 0; i < element.getLength(); i++) { switch (element.getOperator()) { case D: break; case M: length++; break; case I: length++; break; case N: break; case S: break; case H: break; case P: break; case EQ: length++; break; case X: length++; break; } } } if (mode == BlastMode.BlastX) { length *= 3; for (int i = 0; i < query.length(); i++) { char ch = query.charAt(i); if (ch == '/') // reverse shift by 1 length -= 4; // single letter is counted above as 3 nucleotides, but this is a reverse shift by 1, so above we overcounted by 4 else if (ch == '\\') // forward shift by 1 length -= 2; // a single letter is counted above as 3 nucleotides, but this is only a forward shift by 1, so above we overcounted by 2 } } return length; } private boolean isGap(char c) { return c == '.' || c == '-'; } @Override public String getQueryName() { return queryName; } private void setQueryName(String queryName) { this.queryName = queryName; } private int getFlag() { return flag; } private void setFlag(int flag) { this.flag = flag; } @Override public String getRefName() { return refName; } private void setRefName(String refName) { this.refName = refName; } private int getPos() { return pos; } private void setPos(int pos) { this.pos = pos; } private int getMapQuality() { return mapQuality; } private void setMapQuality(int mapQuality) { this.mapQuality = mapQuality; } private String getCigarString() { return cigarString; } private void setCigarString(String cigarString) { this.cigarString = cigarString; setCigar(TextCigarCodec.getSingleton().decode(cigarString)); } private String getRNext() { return RNext; } private void setRNext(String RNext) { this.RNext = RNext; } private int getPNext() { return PNext; } private void setPNext(int PNext) { this.PNext = PNext; } public int getTLength() { return TLength; } private void setTLength(int TLength) { this.TLength = TLength; } private String getSequence() { return sequence; } private void setSequence(String sequence) { this.sequence = sequence; } private String getQuality() { return quality; } private void setQuality(String quality) { this.quality = quality; } private Map<String, Object> getOptionalFields() { return optionalFields; } private Cigar getCigar() { return cigar; } private void setCigar(Cigar cigar) { this.cigar = cigar; } private boolean isReverseComplemented() { return (getFlag() & 0x10) != 0; } /** * returns true, if is match * * @return true if match */ public boolean isMatch() { return !(refName == null || refName.equals("*")); } public int getAlignedQueryStart() { return alignedQueryStart; } public int getAlignedQueryEnd() { return alignedQueryEnd; } public int getRefLength() { Object obj = optionalFields.get("ZL"); if (obj instanceof Integer) return (Integer) optionalFields.get("ZL"); else return 0; } }
42,971
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Diff.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/sam/Diff.java
/* * Diff.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.parsers.sam; import jloda.util.NumberUtils; import java.util.LinkedList; import java.util.List; /** * use this to reconstruct the ref sequence from the query sequence * Daniel Huson, 3.2011 */ public class Diff { enum Type { MATCH, REPLACE, INSERT } /** * reconstruct the reference string from the query, a template of the ref and the diff * * @param gappedReferenceSequenceTemplate aligned reference sequence with ?'s for unknown bases * @return reference */ public static String getReference(String diff, String gappedQuerySequence, String gappedReferenceSequenceTemplate) { if (diff == null) return gappedQuerySequence; final List<DiffElement> differences = decode(diff); StringBuilder buffer = new StringBuilder(); int posQuery = 0; int posRef = 0; for (DiffElement element : differences) { // skip gaps in reference sequence: while (isGap(gappedReferenceSequenceTemplate.charAt(posRef))) { buffer.append(gappedReferenceSequenceTemplate.charAt(posRef)); posQuery++; posRef++; } switch (element.type) { case MATCH -> { for (int i = 0; i < element.count; i++) { while (isGap(gappedReferenceSequenceTemplate.charAt(posRef))) { buffer.append(gappedReferenceSequenceTemplate.charAt(posRef)); posQuery++; posRef++; } buffer.append(gappedQuerySequence.charAt(posQuery)); posQuery++; posRef++; } } case REPLACE -> { final String what = element.what.toLowerCase(); buffer.append(what); posQuery++; posRef++; } case INSERT -> { final String what = element.what.toLowerCase(); buffer.append(what); posQuery += what.length(); posRef += what.length(); } default -> System.err.println("Unknown Diff element: " + element); } } if (differences.size() > 0 && buffer.length() < gappedQuerySequence.length()) { // todo: added this in an attempt to deal with the fact that the cigar and MD fields may not match in length if (SAMMatch.warnAboutProblems) { System.err.println("\n(Problem parsing SAM format, alignment may be incorrect: buffer.length=" + buffer.length() + ", gappedQuery.length=" + gappedQuerySequence.length() + ")"); } while (buffer.length() < gappedQuerySequence.length()) { buffer.append(gappedQuerySequence.charAt(posQuery++)); } } return buffer.toString(); } /** * decode a string of differences * * @return list of difference elements */ private static List<DiffElement> decode(final String diff) { /* The MD field aims to achieve SNP/indel calling without looking at the reference. For example, a string �10A5^AC6� means from the leftmost reference base in the alignment, there are 10 matches followed by an A on the reference which is different from the aligned read base; the next 5 reference bases are matches followed by a 2bp deletion from the reference; the deleted sequence is AC; the last 6 bases are matches. The MD field ought to match the CIGAR string. */ final List<DiffElement> differences = new LinkedList<>(); int pos = 0; while (pos < diff.length()) { int ch = diff.charAt(pos); if (Character.isDigit(ch)) { int a = pos; while (pos < diff.length() && Character.isDigit(diff.charAt(pos))) pos++; int i = NumberUtils.parseInt(diff.substring(a, pos)); DiffElement element = new DiffElement(); element.type = Type.MATCH; element.count = i; differences.add(element); } else if (isLetterOrStartOrFrameShift(ch) || ch == '.') { DiffElement element = new DiffElement(); element.type = Type.REPLACE; element.what = "" + (char) ch; differences.add(element); pos++; } else if (ch == '^') { pos++; int a = pos; while (pos < diff.length() && (isLetterOrStartOrFrameShift(diff.charAt(pos)) || diff.charAt(pos) == '.')) pos++; DiffElement element = new DiffElement(); element.type = Type.INSERT; element.what = diff.substring(a, pos); differences.add(element); if (pos < diff.length() && diff.charAt(pos) == '0') pos++; // consume 0 that was used to indicate end of insert } else { if (!Character.isWhitespace(diff.charAt(pos))) System.err.println("Warning: illegal char in diff string: '" + diff.charAt(pos) + "' (code: " + (int) diff.charAt(pos) + ")"); pos++; } } return differences; } static class DiffElement { Type type; int count; String what; } private static boolean isLetterOrStartOrFrameShift(int c) { return Character.isLetter(c) || c == '*' || c == '\\' || c == '/'; } private static boolean isGap(char c) { return c == '*' || c == '.' || c == '-'; } public static String getLongestContainedPrefix(String reconstructedReference, String reference) { for (int i = reconstructedReference.length(); i >= 0; i--) { int pos = reference.indexOf(reconstructedReference.substring(0, i)); if (pos >= 0) { return "Reconstr.: " + reconstructedReference.substring(0, i) + "|" + reconstructedReference.substring(i) + "\n" + "Reference: " + reference.substring(pos, pos + i) + "|" + reference.substring(pos + i) + "\n"; } } return "No prefix contained"; } }
7,178
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
CigarOperator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/sam/CigarOperator.java
/* * CigarOperator.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.parsers.sam; /** * The operators that can appear in a cigar string, and information about their disk representations. */ public enum CigarOperator { /** * Match or mismatch */ M(true, true, 'M'), /** * Insertion vs. the reference. */ I(true, false, 'I'), /** * Deletion vs. the reference. */ D(false, true, 'D'), /** * Skipped region from the reference. */ N(false, true, 'N'), /** * Soft clip. */ S(true, false, 'S'), /** * Hard clip. */ H(false, false, 'H'), /** * Padding. */ P(false, false, 'P'), /** * Matches the reference. */ EQ(true, true, '='), /** * Mismatches the reference. */ X(true, true, 'X'), /** * reverse frame shift */ FF(true, false, '/'), /** * forward frame shift */ FR(false, true, '\\'); private final boolean consumesReadBases; private final boolean consumesReferenceBases; private final byte character; private final String string; // Readable synonyms of the above enums public static final CigarOperator MATCH_OR_MISMATCH = M; public static final CigarOperator INSERTION = I; public static final CigarOperator DELETION = D; public static final CigarOperator SKIPPED_REGION = N; public static final CigarOperator SOFT_CLIP = S; public static final CigarOperator HARD_CLIP = H; public static final CigarOperator PADDING = P; /** * Default constructor. */ CigarOperator(boolean consumesReadBases, boolean consumesReferenceBases, char character) { this.consumesReadBases = consumesReadBases; this.consumesReferenceBases = consumesReferenceBases; this.character = (byte) character; this.string = String.valueOf(character).intern(); } /** * If true, represents that this cigar operator "consumes" bases from the read bases. */ public boolean consumesReadBases() { return consumesReadBases; } /** * If true, represents that this cigar operator "consumes" bases from the reference sequence. */ public boolean consumesReferenceBases() { return consumesReferenceBases; } /** * @param b CIGAR operator in character form as appears in a text CIGAR string * @return CigarOperator enum value corresponding to the given character. */ public static CigarOperator characterToEnum(final int b) { return switch (b) { case 'M' -> M; case 'I' -> I; case 'D' -> D; case 'N' -> N; case 'S' -> S; case 'H' -> H; case 'P' -> P; case '=' -> EQ; case 'X' -> X; case '/' -> FF; case '\\' -> FR; default -> throw new IllegalArgumentException("Unrecognized CigarOperator: " + (char) b); }; } /** * Returns the character that should be used within a SAM file. */ public static byte enumToCharacter(final CigarOperator e) { return e.character; } /** * Returns the cigar operator as it would be seen in a SAM file. */ @Override public String toString() { return this.string; } }
4,119
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SAMValidationError.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/sam/SAMValidationError.java
/* * SAMValidationError.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.parsers.sam; /** * Class that encapsulates a validation error message as well as a type code so that * errors can be aggregated by type. * * @author Doug Voet */ public class SAMValidationError { public enum Severity { WARNING, ERROR } public enum Type { /** * proper pair flag set for unpaired read */ INVALID_FLAG_PROPER_PAIR, /** * mate unmapped flag set when mate is mapped or not set when mate is not mapped */ INVALID_FLAG_MATE_UNMAPPED, /** * mate unmapped flag does not match read unmapped flag of mate */ MISMATCH_FLAG_MATE_UNMAPPED, /** * mate negative strand flag set for unpaired read */ INVALID_FLAG_MATE_NEG_STRAND, /** * mate negative strand flag does not match read negative strand flag of mate */ MISMATCH_FLAG_MATE_NEG_STRAND, /** * first of pair flag set for unpaired read */ INVALID_FLAG_FIRST_OF_PAIR, /** * second of pair flag set for unpaired read */ INVALID_FLAG_SECOND_OF_PAIR, /** * pair flag set but not marked as first or second of pair */ PAIRED_READ_NOT_MARKED_AS_FIRST_OR_SECOND(Severity.WARNING), /** * not primary alignment flag set for unmapped read */ INVALID_FLAG_NOT_PRIM_ALIGNMENT, /** * mapped read flat not set for mapped read */ INVALID_FLAG_READ_UNMAPPED, /** * inferred insert size is out of range */ INVALID_INSERT_SIZE, /** * mapping quality set for unmapped read or is >= 256 */ INVALID_MAPPING_QUALITY, /** * CIGAR string is empty for mapped read or not empty of unmapped read, or other CIGAR badness. */ INVALID_CIGAR, /** * CIGAR string contains I followed by D, or vice versa, with no intervening M */ ADJACENCT_INDEL_IN_CIGAR(Severity.WARNING), /** * mate reference index (MRNM) set for unpaired read */ INVALID_MATE_REF_INDEX, /** * mate reference index (MRNM) does not match reference index of mate */ MISMATCH_MATE_REF_INDEX, /** * reference index not found in sequence dictionary */ INVALID_REFERENCE_INDEX, /** * alignment start is can not be correct */ INVALID_ALIGNMENT_START, /** * mate alignment does not match alignment start of mate */ MISMATCH_MATE_ALIGNMENT_START, /** * the record's mate fields do not match the corresponding fields of the mate */ MATE_FIELD_MISMATCH, /** * the NM tag (nucleotide differences) is incorrect */ INVALID_TAG_NM, /** * the NM tag (nucleotide differences) is missing */ MISSING_TAG_NM(Severity.WARNING), /** * the sam/bam file is missing the header */ MISSING_HEADER, /** * there is no sequence dictionary in the header */ MISSING_SEQUENCE_DICTIONARY, /** * the header is missing read group information */ MISSING_READ_GROUP, /** * the record is out of order */ RECORD_OUT_OF_ORDER, /** * A read group ID on a SAMRecord is not found in the header */ READ_GROUP_NOT_FOUND, /** * Indexing bin set on SAMRecord does not agree with computed value. */ INVALID_INDEXING_BIN, MISSING_VERSION_NUMBER, INVALID_VERSION_NUMBER, TRUNCATED_FILE, MISMATCH_READ_LENGTH_AND_QUALS_LENGTH, EMPTY_READ, /** * Bases corresponding to M operator in CIGAR are beyond the end of the reference. */ CIGAR_MAPS_OFF_REFERENCE, /** * Length of E2 (secondary base calls) and U2 (secondary base quals) tag values should match read length */ MISMATCH_READ_LENGTH_AND_E2_LENGTH, MISMATCH_READ_LENGTH_AND_U2_LENGTH, /** * Secondary base calls should not be the same as primary, unless one or the other is N */ E2_BASE_EQUALS_PRIMARY_BASE(Severity.WARNING), /** * BAM appears to be healthy, but is an older file so doesn't have terminator block. */ BAM_FILE_MISSING_TERMINATOR_BLOCK(Severity.WARNING), /** * Header record is not one of the standard types */ UNRECOGNIZED_HEADER_TYPE, /** * Header tag does not have colon */ POORLY_FORMATTED_HEADER_TAG, /** * Header tag appears more than once in header line with different value */ HEADER_TAG_MULTIPLY_DEFINED, HEADER_RECORD_MISSING_REQUIRED_TAG, /** * Date string is not ISO-8601 */ INVALID_DATE_STRING(Severity.WARNING), /** * Unsigned integer tag value is deprecated in BAM. */ TAG_VALUE_TOO_LARGE, /** * Invalide virtualFilePointer in index */ INVALID_INDEX_FILE_POINTER, /** * PI tag value is not numeric. */ INVALID_PREDICTED_MEDIAN_INSERT_SIZE, /** * Same read group id appears more than once */ DUPLICATE_READ_GROUP_ID, /** * Same program group id appears more than once */ DUPLICATE_PROGRAM_GROUP_ID, /** * Read is marked as paired, but its pair was not found. */ MATE_NOT_FOUND; final Severity severity; Type() { this.severity = Severity.ERROR; } Type(final Severity severity) { this.severity = severity; } /** * @return Format for writing to histogram summary output. */ public String getHistogramString() { return this.severity.name() + ":" + this.name(); } } private final Type type; private final String message; private final String readName; private long recordNumber = -1; private String source; /** * Construct a SAMValidationError with unknown record number. * * @param readName May be null if readName is not known. */ public SAMValidationError(final Type type, final String message, final String readName) { this.type = type; this.message = message; this.readName = readName; } /** * Construct a SAMValidationError with possibly-known record number. * * @param readName May be null if readName is not known. * @param recordNumber Position of the record in the SAM file it has been read from. -1 if not known. */ public SAMValidationError(final Type type, final String message, final String readName, final long recordNumber) { this(type, message, readName); this.recordNumber = recordNumber; } public String toString() { final StringBuilder builder = new StringBuilder(); builder.append(type.severity.toString()); builder.append(": "); if (source != null) { builder.append("File ").append(source).append(", "); } if (recordNumber > 0) { builder.append("Record ").append(recordNumber).append(", "); } if (readName != null) { builder.append("Read name ").append(readName).append(", "); } return builder.append(message).toString(); } public Type getType() { return type; } public String getMessage() { return message; } /** * may be null */ public String getReadName() { return readName; } /** * 1-based. -1 if not known. */ public long getRecordNumber() { return recordNumber; } public void setRecordNumber(final long recordNumber) { this.recordNumber = recordNumber; } public String getSource() { return source; } public void setSource(final String source) { this.source = source; } }
9,236
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
TextCigarCodec.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/sam/TextCigarCodec.java
/* * TextCigarCodec.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.parsers.sam; /** * Convert between String and Cigar class representations of CIGAR. */ public class TextCigarCodec { private static final byte ZERO_BYTE = "0".getBytes()[0]; private static final byte NINE_BYTE = "9".getBytes()[0]; private static final TextCigarCodec singleton = new TextCigarCodec(); /** * It is not necessary to get the singleton but it is preferable to use the same one * over and over vs. creating a new object for each BAMRecord. There is no state in this * class so this is thread-safe. * * @return A singleton TextCigarCodec useful for converting Cigar classes to and from strings */ public static TextCigarCodec getSingleton() { return singleton; } /** * Convert from Cigar class representation to String. * * @param cigar in Cigar class format * @return CIGAR in String form ala SAM text file. "*" means empty CIGAR. */ public String encode(final Cigar cigar) { if (cigar.isEmpty()) { return "*"; } final StringBuilder ret = new StringBuilder(); for (final CigarElement cigarElement : cigar.getCigarElements()) { ret.append(cigarElement.getLength()); ret.append(cigarElement.getOperator()); } return ret.toString(); } /** * Convert from String CIGAR representation to Cigar class representation. Does not * do validation beyond the most basic CIGAR string well-formedness, i.e. each operator is * valid, and preceded by a decimal length. * * @param textCigar CIGAR in String form ala SAM text file. "*" means empty CIGAR. * @return cigar in Cigar class format * @throws RuntimeException if textCigar is invalid at the most basic level. */ public Cigar decode(final String textCigar) { if ("*".equals(textCigar)) { return new Cigar(); } final Cigar ret = new Cigar(); final byte[] cigarBytes = textCigar.getBytes(); for (int i = 0; i < cigarBytes.length; ++i) { if (!isDigit(cigarBytes[i])) { throw new IllegalArgumentException("Malformed CIGAR string: " + textCigar); } int length = (cigarBytes[i] - ZERO_BYTE); for (++i; isDigit(cigarBytes[i]); ++i) { length = (length * 10) + cigarBytes[i] - ZERO_BYTE; } final CigarOperator operator = CigarOperator.characterToEnum(cigarBytes[i]); ret.add(new CigarElement(length, operator)); } return ret; } private boolean isDigit(final byte c) { return c >= ZERO_BYTE && c <= NINE_BYTE; } }
3,528
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Flag.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/sam/Flag.java
/* * Flag.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.parsers.sam; /** * SAM alignment flag * Daniel Huson, DATE */ public class Flag { private final int value; /* 0x1 template having multiple fragments in sequencing 0x2 each fragment properly aligned according to the aligner 0x4 fragment unmapped 0x8 next fragment in the template unmapped 0x10 SEQ being reverse complemented 0x20 SEQ of the next fragment in the template being reversed 0x40 the first fragment in the template 0x80 the last fragment in the template 0x100 secondary alignment 0x200 not passing quality controls 0x400 PCR or optical duplicate */ public Flag(int value) { this.value = value; } public boolean isHasMate() { return (value & 0x1) != 0; } public boolean isUnmapped() { return (value & 0x4) != 0; } public boolean isReverseComplemented() { return (value & 0x10) != 0; } public boolean isFirstFragment() { return (value & 0x40) != 0; } public boolean isLastFragment() { return (value & 0x80) != 0; } public boolean isSecondaryAlignment() { return (value & 0x100) != 0; } public boolean isNotPassedQualityControl() { return (value & 0x200) != 0; } }
2,043
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
CigarElement.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/sam/CigarElement.java
/* * CigarElement.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.parsers.sam; /** * One component of a cigar string. The component comprises the operator, and the number of bases to which * the operator applies. */ public class CigarElement { private final int length; private final CigarOperator operator; public CigarElement(final int length, final CigarOperator operator) { this.length = length; this.operator = operator; } public int getLength() { return length; } public CigarOperator getOperator() { return operator; } @Override public boolean equals(final Object o) { if (this == o) return true; if (!(o instanceof CigarElement)) return false; final CigarElement that = (CigarElement) o; return length == that.length && operator == that.operator; } @Override public int hashCode() { int result = length; result = 31 * result + (operator != null ? operator.hashCode() : 0); return result; } }
1,814
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Cigar.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/sam/Cigar.java
/* * Cigar.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.parsers.sam; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * A list of CigarElements, which describes how a read aligns with the reference. * E.g. the Cigar string 10M1D25M means * * match or mismatch for 10 bases * * deletion of 1 base * * match or mismatch for 25 bases * <p/> * c.f. http://samtools.sourceforge.net/SAM1.pdf for complete CIGAR specification. */ public class Cigar { private final List<CigarElement> cigarElements = new ArrayList<>(); public Cigar() { } public Cigar(final List<CigarElement> cigarElements) { this.cigarElements.addAll(cigarElements); } public List<CigarElement> getCigarElements() { return Collections.unmodifiableList(cigarElements); } public CigarElement getCigarElement(final int i) { return cigarElements.get(i); } public void add(final CigarElement cigarElement) { cigarElements.add(cigarElement); } public int numCigarElements() { return cigarElements.size(); } public boolean isEmpty() { return cigarElements.isEmpty(); } /** * @return The number of reference bases that the read covers, excluding padding. */ public int getReferenceLength() { int length = 0; for (final CigarElement element : cigarElements) { switch (element.getOperator()) { case M, D, N, EQ, X -> length += element.getLength(); } } return length; } /** * @return The number of reference bases that the read covers, including padding. */ public int getPaddedReferenceLength() { int length = 0; for (final CigarElement element : cigarElements) { switch (element.getOperator()) { case M, D, N, EQ, X, P -> length += element.getLength(); } } return length; } /** * @return The number of read bases that the read covers. */ public int getReadLength() { return getReadLength(cigarElements); } /** * @return The number of read bases that the read covers. */ private static int getReadLength(final List<CigarElement> cigarElements) { int length = 0; for (final CigarElement element : cigarElements) { if (element.getOperator().consumesReadBases()) { length += element.getLength(); } } return length; } /** * Exhaustive validation of CIGAR. * Note that this method deliberately returns null rather than Collections.emptyList() if there * are no validation errors, because callers tend to assume that if a non-null list is returned, it is modifiable. * * @param readName For error reporting only. May be null if not known. * @param recordNumber For error reporting only. May be -1 if not known. * @return List of validation errors, or null if no errors. */ public List<SAMValidationError> isValid(final String readName, final long recordNumber) { if (this.isEmpty()) { return null; } List<SAMValidationError> ret = null; boolean seenRealOperator = false; for (int i = 0; i < cigarElements.size(); ++i) { final CigarElement element = cigarElements.get(i); // clipping operator can only be at start or end of CIGAR final CigarOperator op = element.getOperator(); if (isClippingOperator(op)) { if (op == CigarOperator.H) { if (i != 0 && i != cigarElements.size() - 1) { if (ret == null) ret = new ArrayList<>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_CIGAR, "Hard clipping operator not at start or end of CIGAR", readName, recordNumber)); } } else { if (op != CigarOperator.S) throw new IllegalStateException("Should never happen: " + op.name()); if (i == 0 || i == cigarElements.size() - 1) { // Soft clip at either end is fine } else if (i == 1) { if (cigarElements.size() == 3 && cigarElements.get(2).getOperator() == CigarOperator.H) { // Handle funky special case in which S operator is both one from the beginning and one // from the end. } else if (cigarElements.get(0).getOperator() != CigarOperator.H) { if (ret == null) ret = new ArrayList<>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_CIGAR, "Soft clipping CIGAR operator can only be inside of hard clipping operator", readName, recordNumber)); } } else if (i == cigarElements.size() - 2) { if (cigarElements.get(cigarElements.size() - 1).getOperator() != CigarOperator.H) { if (ret == null) ret = new ArrayList<>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_CIGAR, "Soft clipping CIGAR operator can only be inside of hard clipping operator", readName, recordNumber)); } } else { if (ret == null) ret = new ArrayList<>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_CIGAR, "Soft clipping CIGAR operator can at start or end of read, or be inside of hard clipping operator", readName, recordNumber)); } } } else if (isRealOperator(op)) { // Must be at least one real operator (MIDN) seenRealOperator = true; // There should be an M or P operator between any pair of IDN operators if (isInDelOperator(op)) { for (int j = i + 1; j < cigarElements.size(); ++j) { final CigarOperator nextOperator = cigarElements.get(j).getOperator(); // Allow if ((isRealOperator(nextOperator) && !isInDelOperator(nextOperator)) || isPaddingOperator(nextOperator)) { break; } if (isInDelOperator(nextOperator) && op == nextOperator) { if (ret == null) ret = new ArrayList<>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_CIGAR, "No M or N operator between pair of " + op.name() + " operators in CIGAR", readName, recordNumber)); } } } } else if (isPaddingOperator(op)) { if (i == 0 || i == cigarElements.size() - 1) { if (ret == null) ret = new ArrayList<>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_CIGAR, "Padding operator not valid at start or end of CIGAR", readName, recordNumber)); } else if (!isRealOperator(cigarElements.get(i - 1).getOperator()) || !isRealOperator(cigarElements.get(i + 1).getOperator())) { if (ret == null) ret = new ArrayList<>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_CIGAR, "Padding operator not between real operators in CIGAR", readName, recordNumber)); } } } if (!seenRealOperator) { if (ret == null) ret = new ArrayList<>(); ret.add(new SAMValidationError(SAMValidationError.Type.INVALID_CIGAR, "No real operator (M|I|D|N) in CIGAR", readName, recordNumber)); } return ret; } private static boolean isRealOperator(final CigarOperator op) { return op == CigarOperator.M || op == CigarOperator.EQ || op == CigarOperator.X || op == CigarOperator.I || op == CigarOperator.D || op == CigarOperator.N; } private static boolean isInDelOperator(final CigarOperator op) { return op == CigarOperator.I || op == CigarOperator.D; } private static boolean isClippingOperator(final CigarOperator op) { return op == CigarOperator.S || op == CigarOperator.H; } private static boolean isPaddingOperator(final CigarOperator op) { return op == CigarOperator.P; } @Override public boolean equals(final Object o) { if (this == o) return true; if (!(o instanceof Cigar)) return false; final Cigar cigar = (Cigar) o; return cigarElements.equals(cigar.cigarElements); } @Override public int hashCode() { return cigarElements.hashCode(); } public String toString() { return TextCigarCodec.getSingleton().encode(this); } public void clear() { cigarElements.clear(); } public boolean hasFrameShift() { for (CigarElement element : cigarElements) { if (element.getOperator() == CigarOperator.FR || element.getOperator() == CigarOperator.FF) return true; } return false; } }
10,433
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Resources.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/resources/Resources.java
/* * Resources.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.resources; /** * Resources class * Daniel Huson, 8.2019 */ public class Resources { }
910
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Utilities.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/Utilities.java
/* * Utilities.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.ms; import at.favre.lib.crypto.bcrypt.BCrypt; import megan.daa.connector.ClassificationBlockDAA; import megan.daa.io.ByteInputStream; import megan.daa.io.ByteOutputStream; import megan.daa.io.InputReaderLittleEndian; import megan.daa.io.OutputWriterLittleEndian; import megan.data.IClassificationBlock; import java.io.IOException; import java.util.Map; import java.util.TreeMap; /** * megan server utilities * Daniel Huson, 8.2020 */ public class Utilities { private static final byte[] SALT="7DFjUnE9p2uDeDu0".getBytes(); public static final String SERVER_ERROR = "401 Error:"; /** * construct classification block from bytes */ public static IClassificationBlock getClassificationBlockFromBytes(byte[] bytes) throws IOException { try (var ins = new InputReaderLittleEndian(new ByteInputStream(bytes, 0, bytes.length))) { final var classificationName = ins.readNullTerminatedBytes(); final var classificationBlock = new ClassificationBlockDAA(classificationName); final var numberOfClasses = ins.readInt(); for (var c = 0; c < numberOfClasses; c++) { int classId = ins.readInt(); classificationBlock.setWeightedSum(classId, ins.readInt()); classificationBlock.setSum(classId, ins.readInt()); } return classificationBlock; } } /** * save classification block to bytes */ public static byte[] writeClassificationBlockToBytes(IClassificationBlock classificationBlock) throws IOException { try (var stream = new ByteOutputStream(); var outs = new OutputWriterLittleEndian(stream)) { outs.writeNullTerminatedString(classificationBlock.getName().getBytes()); final var numberOfClasses = classificationBlock.getKeySet().size(); outs.writeInt(numberOfClasses); for (var classId : classificationBlock.getKeySet()) { outs.writeInt(classId); outs.writeInt((int) classificationBlock.getWeightedSum(classId)); outs.writeInt(classificationBlock.getSum(classId)); } return stream.getExactLengthCopy(); } } public static Map<String, byte[]> getAuxiliaryDataFromBytes(byte[] bytes) throws IOException { final var label2data = new TreeMap<String, byte[]>(); try (var ins = new InputReaderLittleEndian(new ByteInputStream(bytes, 0, bytes.length))) { final var numberOfLabels = ins.readInt(); for (var i = 0; i < numberOfLabels; i++) { final var label = ins.readNullTerminatedBytes(); final var size = ins.readInt(); final var data = new byte[size]; final var length = ins.read_available(data, 0, size); if (length < size) { final var tmp = new byte[length]; System.arraycopy(data, 0, tmp, 0, length); label2data.put(label, tmp); throw new IOException("buffer underflow"); } label2data.put(label, data); } } return label2data; } public static byte[] writeAuxiliaryDataToBytes(Map<String, byte[]> label2data) throws IOException { try (var stream = new ByteOutputStream(); var outs = new OutputWriterLittleEndian(stream)) { outs.writeInt(label2data.size()); for (var label : label2data.keySet()) { outs.writeNullTerminatedString(label.getBytes()); final var data = label2data.get(label); outs.writeInt(data.length); outs.write(data, 0, data.length); } return stream.getExactLengthCopy(); } } public static byte[] getBytesLittleEndian(int a) { return new byte[]{(byte) a, (byte) (a >> 8), (byte) (a >> 16), (byte) (a >> 24)}; } public static byte[] getBytesLittleEndian(long a) { return new byte[]{(byte) a, (byte) (a >> 8), (byte) (a >> 16), (byte) (a >> 24), (byte) (a >> 32), (byte) (a >> 40), (byte) (a >> 48), (byte) (a >> 56)}; } public static String computeBCryptHash(byte[] password) { return new String(BCrypt.withDefaults().hash(6, SALT, password)); } public static boolean verify (char[] password,String bcryptHash) { return BCrypt.verifyer().verify(password,bcryptHash).verified; } }
5,297
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ClientMS.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/client/ClientMS.java
/* * ClientMS.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.ms.client; import jloda.util.Basic; import jloda.util.NumberUtils; import jloda.util.StringUtils; import megan.ms.Utilities; import java.io.IOException; import java.net.*; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; import java.util.List; import java.util.stream.Collectors; /** * MeganServer client * Daniel Huson, 8.2020 */ public class ClientMS { private final String serverAndPrefix; private final int timeoutSeconds; private final HttpClient httpClient; private int pageSize = 100; private final char[] passwordHashChars; /** * constructor */ public ClientMS(String serverAndPrefix, String proxyName, int proxyPort, String user, String passwordHash, int timeoutSeconds) { this.serverAndPrefix = serverAndPrefix.replaceAll("/$", ""); this.timeoutSeconds = timeoutSeconds; this.passwordHashChars=passwordHash.toCharArray(); final var proxyAddress = (proxyName == null || proxyName.isBlank() ? null : new InetSocketAddress(proxyName, proxyPort)); httpClient = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(timeoutSeconds)) .authenticator(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, passwordHashChars); } } ) .version(HttpClient.Version.HTTP_2) .followRedirects(HttpClient.Redirect.NORMAL) .proxy(ProxySelector.of(proxyAddress)) .build(); } public List<String> getFiles() throws IOException { try { final var request = setupRequest("/list", false); var response = httpClient.send(request, HttpResponse.BodyHandlers.ofLines()); final var list = response.body().collect(Collectors.toList()); if (list.size() > 0 && list.get(0).startsWith(Utilities.SERVER_ERROR)) { System.err.println(list.get(0)); throw new IOException(list.get(0)); } else return list; } catch (InterruptedException e) { throw new IOException(e); } } public List<FileRecord> getFileRecords() throws IOException { try { final var request = setupRequest("/list?readCount=true&matchCount=true", false); final var response = httpClient.send(request, HttpResponse.BodyHandlers.ofLines()); final var list = response.body().toList(); if (list.size() > 0 && list.get(0).startsWith(Utilities.SERVER_ERROR)) { System.err.println(list.get(0)); throw new IOException(list.get(0)); } else { return list.stream().map(line -> StringUtils.split(line, '\t')) .filter(tokens -> tokens.length > 0) .map(tokens -> { var name = tokens[0]; var reads = (tokens.length > 1 ? NumberUtils.parseLong(tokens[1]) : 0); var matches = (tokens.length > 2 ? NumberUtils.parseLong(tokens[2]) : 0); return new FileRecord(name, reads, matches); }).collect(Collectors.toList()); } } catch (InterruptedException e) { throw new IOException(e); } } /** * gets as string */ public String getAsString(String command) throws IOException { try { final var request = setupRequest(command, false); var response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); final var result = response.body(); if (result.startsWith(Utilities.SERVER_ERROR)) { System.err.println(StringUtils.getFirstLine(result)); throw new IOException(StringUtils.getFirstLine(result)); } else return result; } catch (InterruptedException e) { throw new IOException(e); } } public byte[] getAsBytes(String command) throws IOException { try { final var request = setupRequest(command, true); final var response = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray()); final var result = response.body(); if (StringUtils.startsWith(result, Utilities.SERVER_ERROR)) { System.err.println(StringUtils.getFirstLine(result)); throw new IOException(StringUtils.getFirstLine(result)); } else return result; } catch (InterruptedException e) { throw new IOException(e); } } public HttpRequest setupRequest(String command, boolean binary) { final var uri = URI.create(serverAndPrefix + (command.startsWith("/") ? command : "/" + command)); if(Basic.getDebugMode()) System.err.println("Remote request: " +uri); return HttpRequest.newBuilder() .uri(uri) .timeout(Duration.ofSeconds(timeoutSeconds)) .header("Content-Type", binary ? "application/octet-stream" : "application/text") .build(); } public HttpClient getHttpClient() { return httpClient; } /** * gets as long */ public long getAsLong(String command) throws IOException { return NumberUtils.parseLong(StringUtils.getFirstWord(getAsString(command))); } /** * gets as long */ public int getAsInt(String command) throws IOException { return NumberUtils.parseInt(StringUtils.getFirstWord(getAsString(command))); } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public static class FileRecord { private final String name; private final long reads; private final long matches; private String description; public FileRecord(String name, long reads, long matches) { this.name = name; this.reads = reads; this.matches = matches; if(reads>0) { var description=String.format("reads=%,d",reads); if(matches>0) description+=String.format(", matches=%,d",matches); this.description = description; } else description=null; } public String getName() { return name; } public long getReads() { return reads; } public long getMatches() { return matches; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } }
7,673
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ReadBlockMS.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/client/connector/ReadBlockMS.java
/* * ReadBlockMS.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.ms.client.connector; import jloda.util.StringUtils; import megan.daa.io.ByteInputStream; import megan.daa.io.ByteOutputStream; import megan.daa.io.InputReaderLittleEndian; import megan.daa.io.OutputWriterLittleEndian; import megan.data.IMatchBlock; import megan.data.IReadBlock; import java.io.IOException; import java.util.ArrayList; public class ReadBlockMS implements IReadBlock { private long uid; private String readHeader; private String readSequence; private int readWeight; private long mateUid; private byte mateType; private int readLength; private float complexity; private int numberOfMatches; private IMatchBlock[] matchBlocks = new IMatchBlock[0]; public ReadBlockMS() { } @Override public long getUId() { return uid; } @Override public void setUId(long uid) { this.uid = uid; } @Override public String getReadName() { return StringUtils.getFirstWord(StringUtils.swallowLeadingGreaterOrAtSign(getReadHeader())); } @Override public String getReadHeader() { return readHeader; } @Override public void setReadHeader(String readHeader) { this.readHeader = readHeader; } @Override public String getReadSequence() { return readSequence; } @Override public void setReadSequence(String readSequence) { this.readSequence = readSequence; } @Override public int getReadWeight() { return readWeight; } @Override public void setReadWeight(int readWeight) { this.readWeight = readWeight; } @Override public long getMateUId() { return mateUid; } @Override public void setMateUId(long mateUid) { this.mateUid = mateUid; } @Override public byte getMateType() { return mateType; } @Override public void setMateType(byte mateType) { this.mateType = mateType; } @Override public int getReadLength() { return readLength; } @Override public void setReadLength(int readLength) { this.readLength = readLength; } @Override public float getComplexity() { return complexity; } @Override public void setComplexity(float complexity) { this.complexity = complexity; } @Override public int getNumberOfMatches() { return numberOfMatches; } @Override public void setNumberOfMatches(int numberOfMatches) { this.numberOfMatches = numberOfMatches; } @Override public int getNumberOfAvailableMatchBlocks() { return matchBlocks.length; } @Override public IMatchBlock getMatchBlock(int i) { return matchBlocks[i]; } @Override public IMatchBlock[] getMatchBlocks() { return matchBlocks; } @Override public void setMatchBlocks(IMatchBlock[] matchBlocks) { this.matchBlocks = matchBlocks; } public static String writeToString(IReadBlock readBlock, boolean includeUid, boolean includeHeader, boolean includeSequence, boolean includeMatches) { final ArrayList<String> list = new ArrayList<>(); if (includeUid) list.add(String.valueOf(readBlock.getUId())); if (includeHeader) list.add(">" + readBlock.getReadHeader()); if (includeSequence) list.add(readBlock.getReadSequence()); if (includeMatches) { list.add(""); for (int i = 0; i < readBlock.getNumberOfAvailableMatchBlocks(); i++) { list.add(readBlock.getMatchBlock(i).getText()); } } return StringUtils.toString(list, "\n"); } /** * write a match block to bytes */ public static byte[] writeToBytes(String[] cNames, IReadBlock readBlock, boolean includeSequences,boolean includeMatches) throws IOException { try (var stream = new ByteOutputStream(); var outs = new OutputWriterLittleEndian(stream)) { outs.writeLong(readBlock.getUId()); outs.writeNullTerminatedString(readBlock.getReadHeader().getBytes()); if(includeSequences) { var sequence=readBlock.getReadSequence(); if(sequence!=null) outs.writeNullTerminatedString(sequence.getBytes()); else outs.write((byte) 0); } else outs.write((byte) 0); outs.writeInt(readBlock.getReadWeight()); outs.writeLong(readBlock.getMateUId()); outs.writeInt(readBlock.getReadLength()); outs.writeFloat(readBlock.getComplexity()); outs.writeInt(readBlock.getNumberOfMatches()); if (includeMatches) { outs.writeInt(readBlock.getNumberOfMatches()); for (int m = 0; m < readBlock.getNumberOfMatches(); m++) { MatchBlockMS.writeToBytes(cNames, readBlock.getMatchBlock(m), outs); } } else outs.writeInt(0); return stream.getExactLengthCopy(); } } public static ReadBlockMS readFromBytes(String[] cNames, byte[] bytes) throws IOException { final ReadBlockMS readBlock = new ReadBlockMS(); try (InputReaderLittleEndian ins = new InputReaderLittleEndian(new ByteInputStream(bytes, 0, bytes.length))) { readBlock.uid = ins.readLong(); readBlock.readHeader = ins.readNullTerminatedBytes(); readBlock.readSequence = ins.readNullTerminatedBytes(); readBlock.readWeight = ins.readInt(); readBlock.mateUid = ins.readLong(); readBlock.readLength = ins.readInt(); readBlock.complexity = ins.readFloat(); readBlock.numberOfMatches = ins.readInt(); final int availableMatches = ins.readInt(); final MatchBlockMS[] matchBlocks = new MatchBlockMS[availableMatches]; for (int m = 0; m < availableMatches; m++) { matchBlocks[m] = MatchBlockMS.getFromBytes(cNames, ins); } readBlock.matchBlocks = matchBlocks; } return readBlock; } }
7,076
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MatchBlockMS.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/client/connector/MatchBlockMS.java
/* * MatchBlockMS.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.ms.client.connector; import jloda.util.StringUtils; import megan.daa.io.ByteInputStream; import megan.daa.io.ByteOutputStream; import megan.daa.io.InputReaderLittleEndian; import megan.daa.io.OutputWriterLittleEndian; import megan.data.IMatchBlock; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * matchblock for megan server * Daniel Huson, 8.2020 */ public class MatchBlockMS implements IMatchBlock { private long uid; private int taxonId; private float bitScore; private float percentIdentity; private String refSeqId; private float expected; private int length; private boolean ignore; private String text; private final Map<String, Integer> class2id = new HashMap<>(); private int alignedQueryStart; private int alignedQueryEnd; private int refLength; public MatchBlockMS() { } public long getUId() { return uid; } public void setUId(long uid) { this.uid = uid; } @Override public int getTaxonId() { return taxonId; } @Override public void setTaxonId(int taxonId) { this.taxonId = taxonId; } @Override public float getBitScore() { return bitScore; } @Override public void setBitScore(float bitScore) { this.bitScore = bitScore; } @Override public float getPercentIdentity() { return percentIdentity; } @Override public void setPercentIdentity(float percentIdentity) { this.percentIdentity = percentIdentity; } @Override public String getRefSeqId() { return refSeqId; } @Override public void setRefSeqId(String refSeqId) { this.refSeqId = refSeqId; } @Override public float getExpected() { return expected; } @Override public void setExpected(float expected) { this.expected = expected; } @Override public int getLength() { return length; } @Override public void setLength(int length) { this.length = length; } @Override public boolean isIgnore() { return ignore; } @Override public void setIgnore(boolean ignore) { this.ignore = ignore; } @Override public String getText() { return text; } @Override public String getTextFirstWord() { return StringUtils.getFirstWord(getText()); } public void setText(String text) { this.text = text; } @Override public int getId(String cName) { final Integer id = class2id.get(cName); return id == null ? 0 : id; } @Override public void setId(String cName, Integer id) { class2id.put(cName, id); } @Override public int[] getIds(String[] cNames) { return new int[0]; } @Override public int getAlignedQueryStart() { return alignedQueryStart; } @Override public int getAlignedQueryEnd() { return alignedQueryEnd; } @Override public int getRefLength() { return refLength; } public static byte[] writeToBytes(String[] cNames, IMatchBlock matchBlock) throws IOException { try (ByteOutputStream stream = new ByteOutputStream(); OutputWriterLittleEndian outs = new OutputWriterLittleEndian(stream)) { writeToBytes(cNames, matchBlock, outs); return stream.getExactLengthCopy(); } } public static void writeToBytes(String[] cNames, IMatchBlock matchBlock, OutputWriterLittleEndian outs) throws IOException { outs.writeLong(matchBlock.getUId()); outs.writeInt(matchBlock.getTaxonId()); outs.writeFloat(matchBlock.getBitScore()); outs.writeFloat(matchBlock.getPercentIdentity()); outs.writeFloat(matchBlock.getExpected()); outs.writeInt(matchBlock.getLength()); outs.writeNullTerminatedString(matchBlock.getText().getBytes()); final int[] ids = matchBlock.getIds(cNames); outs.writeInt(ids.length); for (int id : ids) { outs.writeInt(id); } outs.writeInt(matchBlock.getAlignedQueryStart()); outs.writeInt(matchBlock.getAlignedQueryEnd()); outs.writeInt(matchBlock.getRefLength()); } public static MatchBlockMS getFromBytes(String[] cNames, byte[] bytes) throws IOException { try (InputReaderLittleEndian ins = new InputReaderLittleEndian(new ByteInputStream(bytes, 0, bytes.length))) { return getFromBytes(cNames, ins); } } public static MatchBlockMS getFromBytes(String[] cNames, InputReaderLittleEndian ins) throws IOException { final MatchBlockMS matchBlock = new MatchBlockMS(); matchBlock.uid = ins.readLong(); matchBlock.taxonId = ins.readInt(); matchBlock.bitScore = ins.readFloat(); matchBlock.percentIdentity = ins.readFloat(); matchBlock.expected = ins.readFloat(); matchBlock.length = ins.readInt(); matchBlock.text = ins.readNullTerminatedBytes(); int count = ins.readInt(); for (int i = 0; i < count; i++) { matchBlock.setId(cNames[i], ins.readInt()); } matchBlock.alignedQueryStart = ins.readInt(); matchBlock.alignedQueryEnd = ins.readInt(); matchBlock.refLength = ins.readInt(); return matchBlock; } }
6,268
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MSConnector.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/client/connector/MSConnector.java
/* * MSConnector.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.ms.client.connector; import jloda.util.NumberUtils; import jloda.util.Single; import jloda.util.StringUtils; import jloda.util.progress.ProgressListener; import megan.core.Document; import megan.data.*; import megan.ms.Utilities; import megan.ms.client.ClientMS; import megan.ms.clientdialog.service.RemoteServiceManager; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; /** * MeganServer connector * Daniel Huson, 8.2020 */ public class MSConnector implements IConnector { private final ClientMS client; private String fileName; public MSConnector(String serverFileName) { RemoteServiceManager.ensureCredentialsHaveBeenLoadedFromProperties(); var parts = serverFileName.split("::"); var serverURL = parts[0]; var user = RemoteServiceManager.getUser(serverURL); var passwordHash = RemoteServiceManager.getPasswordHash(serverURL); var filePath = parts[1]; client = new ClientMS(serverURL, null, 0, user, passwordHash, 600); setFile(filePath); } @Override public void setFile(String filename) { this.fileName = filename; } @Override public String getFilename() { return fileName; } @Override public boolean isReadOnly() { return true; } @Override public long getUId() throws IOException { return client.getAsLong("fileUid?file=" + fileName); } @Override public IReadBlockIterator getAllReadsIterator(float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException { return new ReadBlockIteratorMS(client, fileName, minScore, maxExpected, wantReadSequence, wantMatches); } @Override public IReadBlockIterator getReadsIterator(String classification, int classId, float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException { return getReadsIteratorForListOfClassIds(classification, Collections.singletonList(classId), minScore, maxExpected, wantReadSequence, wantMatches); } @Override public IReadBlockIterator getReadsIteratorForListOfClassIds(String classification, Collection<Integer> classIds, float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException { return new ReadBlockIteratorMS(client, fileName, classification, classIds, minScore, maxExpected, wantReadSequence, wantMatches); } @Override public IReadBlockGetter getReadBlockGetter(float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException { return new ReadBlockGetterMS(client, fileName, wantReadSequence, wantMatches); } @Override public String[] getAllClassificationNames() throws IOException { return StringUtils.getLinesFromString(client.getAsString("getClassificationNames?file=" + fileName)).toArray(new String[0]); } @Override public int getClassificationSize(String classificationName) throws IOException { return NumberUtils.parseInt(client.getAsString("getClassificationSize?file=" + fileName + "&classification=" + classificationName)); } @Override public int getClassSize(String classificationName, int classId) throws IOException { return NumberUtils.parseInt(client.getAsString("getClassSize?file=" + fileName + "&classification=" + classificationName + "&sum=true&classId=" + classId)); } @Override public IClassificationBlock getClassificationBlock(String classificationName) throws IOException { return Utilities.getClassificationBlockFromBytes(client.getAsBytes("getClassificationBlock?file=" + fileName + "&classification=" + classificationName + "&binary=true")); } @Override public void updateClassifications(String[] classificationNames, List<UpdateItem> updateItems, ProgressListener progressListener) { System.err.println("updateClassifications: not implemented"); } @Override public IReadBlockIterator getFindAllReadsIterator(String regEx, FindSelection findSelection, Single<Boolean> canceled) throws IOException { return new FindAllReadsIterator(regEx, findSelection, getAllReadsIterator(0, 10, true, true), canceled); } @Override public int getNumberOfReads() throws IOException { return NumberUtils.parseInt(client.getAsString("getNumberOfReads?file=" + fileName)); } @Override public int getNumberOfMatches() throws IOException { return NumberUtils.parseInt(client.getAsString("getNumberOfMatches?file=" + fileName)); } @Override public void setNumberOfReads(int numberOfReads) { System.err.println("setNumberOfReads: not implemented"); } @Override public void putAuxiliaryData(Map<String, byte[]> label2data) { System.err.println("putAuxiliaryData: not implemented"); } @Override public Map<String, byte[]> getAuxiliaryData() throws IOException { return Utilities.getAuxiliaryDataFromBytes(client.getAsBytes("getAuxiliaryData?file=" + fileName + "&binary=true")); } /** * load the set megan summary file */ public void loadMeganSummaryFile(Document document) throws IOException { var fileContent = StringUtils.toString(getAuxiliaryData().get("FILE_CONTENT")); document.loadMeganSummary(new BufferedReader(new StringReader(fileContent))); } }
6,373
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ReadBlockGetterMS.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/client/connector/ReadBlockGetterMS.java
/* * ReadBlockGetterMS.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.ms.client.connector; import jloda.util.Basic; import jloda.util.StringUtils; import megan.data.IReadBlock; import megan.data.IReadBlockGetter; import megan.data.IReadBlockIterator; import megan.ms.client.ClientMS; import java.io.IOException; /** * read block getter * Daniel Huson, 8.2020 */ public class ReadBlockGetterMS implements IReadBlockGetter { private final ClientMS client; private final String fileName; private final int numberOfReads; private IReadBlockIterator iterator; private boolean iteratorHasBeenSet = false; private final boolean wantSequences; private final boolean wantMatches; private final String[] classifications; private static final String commandTemplate = "getRead?file=%s&readId=%d&binary=true&sequence=%b&matches=%b"; /** * constructor */ public ReadBlockGetterMS(ClientMS client, String fileName, boolean wantSequences, boolean wantMatches) throws IOException { this.client = client; this.fileName = fileName; this.wantSequences = wantSequences; this.wantMatches = wantMatches; this.numberOfReads = client.getAsInt("numberOfReads?file=" + fileName); this.classifications = StringUtils.getLinesFromString(client.getAsString("getClassificationNames?file=" + fileName), 1000).toArray(new String[0]); } @Override public IReadBlock getReadBlock(long uid) { // uid -1: stream if (uid == -1) // use next { if (!iteratorHasBeenSet) { iteratorHasBeenSet = true; try { iterator = new ReadBlockIteratorMS(client, fileName, 0, 10, wantSequences, wantMatches); } catch (IOException e) { Basic.caught(e); } } if (iterator != null && iterator.hasNext()) { return iterator.next(); } else return null; } try { if (false) // todo: for debugging { final String commandTemplate = "getRead?file=%s&readId=%d&binary=false&sequence=%b&matches=%b"; System.err.println(client.getAsString(String.format(commandTemplate, fileName, uid, wantSequences, wantMatches))); } final byte[] bytes = client.getAsBytes(String.format(commandTemplate, fileName, uid, wantSequences, wantMatches)); return ReadBlockMS.readFromBytes(classifications, bytes); } catch (Exception ignored) { return null; } } @Override public void close() { } @Override public long getCount() { return numberOfReads; } }
3,504
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ReadBlockIteratorMS.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/client/connector/ReadBlockIteratorMS.java
/* * ReadBlockIteratorMS.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.ms.client.connector; import jloda.util.StringUtils; import megan.daa.io.ByteInputStream; import megan.daa.io.InputReaderLittleEndian; import megan.data.IReadBlock; import megan.data.IReadBlockIterator; import megan.ms.client.ClientMS; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * read blocks iterator * Daniel Huson, 8.2020 */ public class ReadBlockIteratorMS implements IReadBlockIterator { private final static Map<ClientMS,String[]> clientClassificationsMap=new HashMap<>(); private final ClientMS client; private final String[] classifications; private final ArrayList<IReadBlock> reads = new ArrayList<>(); private int nextIndex = 0; private int count = 0; private long nextPageId = 0; /** * constructor */ public ReadBlockIteratorMS(ClientMS client, String fileName, float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException { this.client = client; this.classifications = StringUtils.getLinesFromString(client.getAsString("getClassificationNames?file=" + fileName), 1000).toArray(new String[0]); processBytes(client.getAsBytes("getReads?file=" + fileName + "&binary=true&sequences=" + wantReadSequence + "&matches=" + wantMatches + "&pageSize=" + client.getPageSize())); } /** * constructor */ public ReadBlockIteratorMS(ClientMS client, String fileName, String classification, Collection<Integer> classIds, float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException { var pageSize=client.getPageSize(); if(!wantReadSequence) pageSize*=10; if(!wantMatches) pageSize*=10; this.client = client; if(!clientClassificationsMap.containsKey(client)) { synchronized (clientClassificationsMap) { if(!clientClassificationsMap.containsKey(client)) { clientClassificationsMap.put(client,StringUtils.getLinesFromString(client.getAsString("getClassificationNames?file=" + fileName), 1000).toArray(new String[0])); } } } this.classifications =clientClassificationsMap.get(client); processBytes(client.getAsBytes("getReadsForClass?file=" + fileName + "&binary=true&classification=" + classification + "&classId=" + StringUtils.toString(classIds, ",") + "&sequences=" + wantReadSequence + "&matches=" + wantMatches + "&pageSize=" + pageSize)); } private void processBytes(byte[] bytes) throws IOException { reads.clear(); nextIndex = 0; try (InputReaderLittleEndian ins = new InputReaderLittleEndian(new ByteInputStream(bytes, 0, bytes.length))) { final int count = ins.readInt(); for (int i = 0; i < count; i++) { int size = ins.readInt(); reads.add(ReadBlockMS.readFromBytes(classifications, ins.readBytes(size))); } nextPageId = ins.readLong(); } } @Override public String getStats() { return "Count: " + count; } @Override public void close() { } @Override public long getMaximumProgress() { return reads.size(); // not current, as doesn't take number of pages into account } @Override public long getProgress() { return nextIndex; } @Override public boolean hasNext() { return nextIndex < reads.size(); } @Override public IReadBlock next() { if (hasNext()) { final IReadBlock result = reads.get(nextIndex++); if (nextIndex >= reads.size() && nextPageId > 0) { try { processBytes(client.getAsBytes("getNext?pageId=" + nextPageId + "&binary=true" + "&pageSize=" + client.getPageSize())); count++; } catch (IOException ignored) { } } return result; } return null; } }
4,897
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ServicePanel.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/clientdialog/ServicePanel.java
/* * ServicePanel.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.ms.clientdialog; import jloda.swing.director.IDirector; import jloda.swing.director.ProjectManager; import jloda.swing.find.ISearcher; import jloda.swing.message.MessageWindow; import jloda.swing.util.ProgramProperties; import megan.core.Director; import megan.ms.clientdialog.commands.*; import javax.swing.*; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.util.*; /** * A panel representing a service * Created by huson on 10/8/14. */ public class ServicePanel extends JPanel { private final RemoteServiceBrowser remoteServiceBrowser; private final IRemoteService service; private final JTree fileTree; private final Map<DefaultMutableTreeNode, String> treeNode2File; private final JMenuItem openMenuItem; private final JMenuItem compareMenuItem; private final JMenuItem aboutServerMenuItem; private final ISearcher jTreeSearcher; private final JMenuItem expandMenuItem; private final JMenuItem collapseMenuItem; public static String[] serviceButtonNames = {CompareSelectedFilesCommand.ALTNAME}; /** * constructor * */ public ServicePanel(IRemoteService service, final RemoteServiceBrowser remoteServiceBrowser) { this.remoteServiceBrowser = remoteServiceBrowser; this.service = service; setBorder(BorderFactory.createTitledBorder("Location: " + service.getServerURL())); setLayout(new BorderLayout()); treeNode2File = new HashMap<>(); fileTree = createFileTree(service); fileTree.setCellRenderer(new MyRenderer()); ToolTipManager.sharedInstance().registerComponent(fileTree); jTreeSearcher = new jloda.swing.find.JTreeSearcher(fileTree); fileTree.addTreeSelectionListener(e -> remoteServiceBrowser.updateView(IDirector.ENABLE_STATE)); fileTree.addTreeExpansionListener(new TreeExpansionListener() { @Override public void treeExpanded(TreeExpansionEvent event) { updateFonts(); } @Override public void treeCollapsed(TreeExpansionEvent event) { } }); add(new JScrollPane(fileTree), BorderLayout.CENTER); JPanel bottom = new JPanel(); bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS)); bottom.add(Box.createHorizontalGlue()); for (var name : serviceButtonNames) { final AbstractButton button = remoteServiceBrowser.getCommandManager().getButton(name); if (button != null) bottom.add(button); } bottom.add(Box.createHorizontalStrut(20)); bottom.add(remoteServiceBrowser.getCommandManager().getButton(OpenSelectedFilesCommand.ALTNAME)); openMenuItem = remoteServiceBrowser.getCommandManager().getJMenuItem(OpenSelectedFilesCommand.ALTNAME); compareMenuItem = remoteServiceBrowser.getCommandManager().getJMenuItem(CompareSelectedFilesCommand.ALTNAME); aboutServerMenuItem = remoteServiceBrowser.getCommandManager().getJMenuItem(ShowServerInfoCommand.NAME); expandMenuItem = remoteServiceBrowser.getCommandManager().getJMenuItem(ExpandNodesCommand.ALTNAME); collapseMenuItem = remoteServiceBrowser.getCommandManager().getJMenuItem(CollapseNodesCommand.ALTNAME); add(bottom, BorderLayout.SOUTH); } /** * get all selected files * * @return list of selected files, full remote names */ public Collection<String> getSelectedFiles() { Set<String> set = new HashSet<>(); TreePath[] paths = fileTree.getSelectionPaths(); if (paths != null) { for (TreePath path : paths) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); if (node != null) { String file = treeNode2File.get(node); if (file != null) { if(service.getAvailableFiles().contains(file)) { file = service.getServerAndFileName(file); if (file != null) set.add(file); } } } } } return set; } public IRemoteService getService() { return service; } /** * get all currently open remote files * * @return open remote files */ public Set<String> getCurrentlyOpenRemoteFiles() { Set<String> openFiles = new HashSet<>(); for (IDirector iDir : ProjectManager.getProjects()) { Director dir = (Director) iDir; if (dir.getDocument().getMeganFile().isMeganServerFile()) { String fileName = dir.getDocument().getMeganFile().getFileName(); openFiles.add(fileName); } } return openFiles; } private JTree createFileTree(final IRemoteService service) { final JTree tree = new JTree(); final DefaultTreeModel treeModel = new DefaultTreeModel(null); tree.setModel(treeModel); treeNode2File.clear(); final var path2node = new HashMap<String, DefaultMutableTreeNode>(); final var root = new DefaultMutableTreeNode(service.getServerURL(), true); treeModel.setRoot(root); treeNode2File.put(root,"."); var sortedSet = new TreeSet<>(service.getAvailableFiles()); for (var fileName : sortedSet) { var levels = fileName.split("/"); var path = ""; DefaultMutableTreeNode parent = root; for (var i = 0; i < levels.length; i++) { path += levels[i]; DefaultMutableTreeNode node = path2node.get(path); if (node == null) { boolean isLeaf = (i == levels.length - 1); node = new DefaultMutableTreeNode(levels[i], !isLeaf); if (isLeaf) { treeNode2File.put(node, fileName); node.setUserObject("<html><b>" + node.getUserObject() + "</b></html>"); } else treeNode2File.put(node,String.join("/", Arrays.copyOf(levels, i))); path2node.put(path, node); } parent.add(node); parent = node; } } tree.addMouseListener(new MyMouseListener()); treeModel.reload(); tree.validate(); return tree; } /** * open all currently selected files */ private void openSelectedFiles() { StringBuilder buf = new StringBuilder(); int count = 0; Set<String> openFiles = getCurrentlyOpenRemoteFiles(); for (String fileName : getSelectedFiles()) { if (openFiles.contains(fileName)) { buf.append("toFront file='").append(fileName).append("';"); } else { buf.append("open file='").append(fileName).append("' readOnly=true;"); count++; } } if (count > 10) { if (JOptionPane.showConfirmDialog(remoteServiceBrowser.getFrame(), "Do you really want to open " + count + " new files?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon()) == JOptionPane.NO_OPTION) return; } Director dir = remoteServiceBrowser.getDir(); dir.execute(buf.toString(), remoteServiceBrowser.getCommandManager()); } public String getURL() { return service.getServerURL(); } public ISearcher getjTreeSearcher() { return jTreeSearcher; } public JTree getFileTree() { return fileTree; } /** * expand the given node * */ public void expand(DefaultMutableTreeNode v) { if (v == null) v = (DefaultMutableTreeNode) fileTree.getModel().getRoot(); for (var descendants = v.breadthFirstEnumeration(); descendants.hasMoreElements(); ) { v = (DefaultMutableTreeNode) descendants.nextElement(); fileTree.expandPath(new TreePath(v.getPath())); } } /** * expand an array of paths * */ public void expand(TreePath[] paths) { for (TreePath path : paths) { expand((DefaultMutableTreeNode) path.getLastPathComponent()); } } /** * collapse the given node or root * */ public void collapse(DefaultMutableTreeNode v) { if (v == null) v = (DefaultMutableTreeNode) fileTree.getModel().getRoot(); for (var descendants = v.depthFirstEnumeration(); descendants.hasMoreElements(); ) { v = (DefaultMutableTreeNode) descendants.nextElement(); fileTree.collapsePath(new TreePath(v.getPath())); } } /** * collapse an array of paths * */ public void collapse(TreePath[] paths) { for (TreePath path : paths) { collapse((DefaultMutableTreeNode) path.getLastPathComponent()); } } /** * updates fonts used in tree */ public void updateFonts() { final Set<String> openFiles = getCurrentlyOpenRemoteFiles(); for (int i = 0; i < fileTree.getRowCount(); i++) { DefaultMutableTreeNode v = (DefaultMutableTreeNode) fileTree.getPathForRow(i).getLastPathComponent(); String file = treeNode2File.get(v); if (file != null) { if (openFiles.contains(service.getServerAndFileName(file))) { int pos = file.lastIndexOf(File.separator); if (pos == -1) v.setUserObject(file); else v.setUserObject(file.substring(pos + 1)); } else { String user = v.getUserObject().toString(); if (!user.startsWith("<html>")) v.setUserObject("<html><b>" + user + "</b></html>"); } } } } public void selectAll(boolean select) { // todo: select only leaves if (select) fileTree.setSelectionInterval(0, fileTree.getRowCount()); else fileTree.setSelectionInterval(0, 0); } class MyMouseListener extends MouseAdapter { public void mouseClicked(MouseEvent e) { if(e.getClickCount()==1) { var path=fileTree.getPathForLocation(e.getX(), e.getY()); if(path!=null) { var node = (DefaultMutableTreeNode)path.getLastPathComponent(); final String fileName = treeNode2File.get(node); if (fileName != null) { var about=service.getDescription(fileName); if(about!=null && !about.isBlank()) { MessageWindow.getInstance().getFrame().setVisible(true); MessageWindow.getInstance().getFrame().toFront(); System.err.println("\n"+node.toString().replaceAll("<.*?>", "") +":\n"+about.trim()); System.err.flush(); } } } } else if (e.getClickCount() == 2) { int selRow = fileTree.getRowForLocation(e.getX(), e.getY()); TreePath path = fileTree.getPathForLocation(e.getX(), e.getY()); if (selRow != -1 && path != null) { fileTree.setSelectionRow(selRow); } remoteServiceBrowser.updateView(IDirector.ENABLE_STATE); if (openMenuItem.isEnabled()) openSelectedFiles(); } } public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { showPopupMenu(e); } } public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { showPopupMenu(e); } } } private void showPopupMenu(MouseEvent e) { int selRow = fileTree.getRowForLocation(e.getX(), e.getY()); TreePath path = fileTree.getPathForLocation(e.getX(), e.getY()); if (selRow != -1 && path != null) { fileTree.setSelectionRow(selRow); } remoteServiceBrowser.updateView(IDirector.ENABLE_STATE); JPopupMenu popupMenu = new JPopupMenu(); popupMenu.add(openMenuItem); popupMenu.add(compareMenuItem); popupMenu.addSeparator(); popupMenu.add(expandMenuItem); popupMenu.add(collapseMenuItem); popupMenu.addSeparator(); popupMenu.add(aboutServerMenuItem); popupMenu.show(fileTree, e.getX(), e.getY()); } private class MyRenderer extends DefaultTreeCellRenderer { public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { setToolTipText(null); try { final DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getPathForRow(row).getLastPathComponent(); final String fileName = treeNode2File.get(node); if (fileName != null) { setToolTipText(service.getDescription(fileName)); } } catch (Exception ignored) { } return super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); } } }
14,834
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IRemoteService.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/clientdialog/IRemoteService.java
/* * IRemoteService.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.ms.clientdialog; import java.util.Collection; /** * Represents a (remote) MEGAN server * <p/> * Daniel Huson on 12/2014 */ public interface IRemoteService { /** * get the remote server URL and directory path, e.g. www.megan.de/data/files * * @return file specification */ String getServerURL(); /** * is service available * */ boolean isAvailable(); /** * get a list of available files (relative names) * * @return list of available files */ Collection<String> getAvailableFiles(); /** * gets the server and file name * * @return server and file */ String getServerAndFileName(String file); /** * gets the info string for a server * * @return info in html */ String getInfo(); /** * get the description associated with a given file name * * @return description */ String getDescription(String fileName); }
1,803
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
GUIConfiguration.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/clientdialog/GUIConfiguration.java
/* * GUIConfiguration.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.ms.clientdialog; import jloda.swing.window.MenuConfiguration; /** * configuration for menu and toolbar * Daniel Huson, 7.2010 */ class GUIConfiguration { /** * get the menu configuration * * @return menu configuration */ public static MenuConfiguration getMenuConfiguration() { MenuConfiguration menuConfig = new MenuConfiguration(); menuConfig.defineMenuBar("File;Edit;Options;Layout;Window;Help;"); menuConfig.defineMenu("File", "New...;|;Open Selected Files;@Open Recent;|;Open From URL...;|;Compare Selected Files;|;Import From BLAST...;@Import;Meganize DAA File...;|;Close;|;Quit;"); menuConfig.defineMenu("Open Recent", ";"); menuConfig.defineMenu("Edit", "Cut;Copy;Paste;|;Select All;Select None;|;Find...;Find Again;"); menuConfig.defineMenu("Options", "Open Server...;Close Remote Server...;"); menuConfig.defineMenu("Layout", "Expand Remote Browser Nodes;Collapse Remote Browser Nodes;"); menuConfig.defineMenu("Window", "Close All Other Windows...;|;Reset Window Location;Set Window Size...;|;Message Window...;|;"); menuConfig.defineMenu("Help", "About...;How to Cite...;|;Community Website...;Reference Manual...;|;Check For Updates...;"); return menuConfig; } /** * gets the toolbar configuration * * @return toolbar configuration */ public static String getToolBarConfiguration() { return "Open Selected Files;|;Find...;|;Expand Remote Browser Nodes;Collapse Remote Browser Nodes;|;Server Info...;Close Remote Server...;"; } }
2,435
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
RemoteServiceBrowser.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/clientdialog/RemoteServiceBrowser.java
/* * RemoteServiceBrowser.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.ms.clientdialog; import jloda.swing.commands.CommandManager; import jloda.swing.director.IDirectableViewer; import jloda.swing.director.IDirector; import jloda.swing.director.IViewerWithFindToolBar; import jloda.swing.director.ProjectManager; import jloda.swing.find.EmptySearcher; import jloda.swing.find.FindToolBar; import jloda.swing.find.SearchManager; import jloda.swing.util.ProgramProperties; import jloda.swing.util.RememberingComboBox; import jloda.swing.util.StatusBar; import jloda.swing.util.ToolBar; import jloda.swing.window.MenuBar; import megan.core.Director; import megan.core.Document; import megan.main.MeganProperties; import megan.ms.Utilities; import megan.ms.clientdialog.commands.OpenRemoteServerCommand; import megan.ms.clientdialog.service.RemoteServiceManager; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; import java.awt.*; import java.awt.event.ItemListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.ArrayList; /** * Remote services browser * <p/> * Daniel Huson, 10.2014 */ public class RemoteServiceBrowser extends JFrame implements IDirectableViewer, IViewerWithFindToolBar { private final Director dir; private boolean uptoDate; private boolean locked = false; private final JPanel mainPanel; private final MenuBar menuBar; private boolean showFindToolBar = false; private final SearchManager searchManager; private final JTabbedPane tabbedPane; private final CommandManager commandManager; private RememberingComboBox urlComboBox; private final JTextField userTextField = new JTextField(30); private final JPasswordField passwordTextField = new JPasswordField(30); private boolean passwordHash = false; //private JTextField passwordTextField = new JTextField(30); private final JCheckBox saveCredentialsCBox = new JCheckBox(); private final StatusBar statusBar; public static String[] commandSources = {"megan.commands", "megan.ms.clientdialog.commands"}; public static String[] additionalItems = {}; /** * constructor */ public RemoteServiceBrowser(JFrame parent) { this.dir = new Director(new Document()); dir.getDocument().setDirty(true); // prevent opening in this document dir.addViewer(this); commandManager = new CommandManager(dir, this, commandSources, !ProgramProperties.isUseGUI()); setTitle(); setSize(700, 400); setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); setIconImages(ProgramProperties.getProgramIconImages()); menuBar = new MenuBar(this, GUIConfiguration.getMenuConfiguration(), commandManager); setJMenuBar(menuBar); MeganProperties.addPropertiesListListener(menuBar.getRecentFilesListener()); MeganProperties.notifyListChange(ProgramProperties.RECENTFILES); ProjectManager.addAnotherWindowWithWindowMenu(dir, menuBar.getWindowMenu()); mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); final ToolBar toolBar = new ToolBar(this, GUIConfiguration.getToolBarConfiguration(), commandManager); getContentPane().setLayout(new BorderLayout()); getContentPane().add(toolBar, BorderLayout.NORTH); statusBar = new StatusBar(); statusBar.setToolTipText("Status bar"); getContentPane().add(statusBar, BorderLayout.SOUTH); searchManager = new SearchManager(dir, this, new EmptySearcher(), false, true); tabbedPane = new JTabbedPane(); tabbedPane.addChangeListener(e -> updateView(IDirector.ENABLE_STATE)); tabbedPane.add("Add Server", createOpenRemoteServerPanel()); tabbedPane.setSelectedIndex(0); mainPanel.add(tabbedPane, BorderLayout.CENTER); getContentPane().add(mainPanel, BorderLayout.CENTER); getContentPane().validate(); commandManager.updateEnableState(); getFrame().setLocationRelativeTo(parent); } /** * create the open remote server panel * * @return open remote panel */ private JPanel createOpenRemoteServerPanel() { RemoteServiceManager.ensureCredentialsHaveBeenLoadedFromProperties(); final JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder("Open Server")); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.add(new JLabel(" ")); urlComboBox = new RememberingComboBox(); urlComboBox.setBorder(BorderFactory.createBevelBorder(1)); // ((JTextComponent) urlComboBox.getEditor().getEditorComponent()).getDocument().addDocumentListener(createDocumentListener()); final ItemListener itemListener = e -> { final String selected = e.getItem().toString(); final String user = RemoteServiceManager.getUser(selected); userTextField.setText(user != null ? user : ""); final String password = RemoteServiceManager.getPasswordHash(selected); passwordTextField.setText(password != null ? password : ""); setPasswordHash(password != null); commandManager.updateEnableState(); }; urlComboBox.addItemListener(itemListener); { var items = new ArrayList<>(RemoteServiceManager.getServers()); items.remove(RemoteServiceManager.DEFAULT_MEGAN_SERVER); if(items.size()==0) items.add(RemoteServiceManager.DEFAULT_MEGAN_SERVER); else items.set(0, RemoteServiceManager.DEFAULT_MEGAN_SERVER); urlComboBox.addItems(items); } urlComboBox.setMaximumSize(new Dimension(2000, 25)); urlComboBox.setPreferredSize(new Dimension(600, 25)); urlComboBox.setToolTipText("MEGAN server URL"); if(urlComboBox.getItemCount()>0) urlComboBox.setSelectedIndex(0); final JPanel aRow = new JPanel(); aRow.setLayout(new BoxLayout(aRow, BoxLayout.X_AXIS)); //aRow.add(Box.createHorizontalGlue()); aRow.add(new JLabel("Server: ")); aRow.add(urlComboBox); panel.add(aRow); panel.add(Box.createVerticalStrut(4)); userTextField.setMaximumSize(new Dimension(2000, 25)); userTextField.setPreferredSize(new Dimension(600, 20)); userTextField.setToolTipText("User id required by server."); final JPanel bRow = new JPanel(); bRow.setLayout(new BoxLayout(bRow, BoxLayout.X_AXIS)); bRow.add(new JLabel("User: ")); bRow.add(userTextField); panel.add(bRow); panel.add(Box.createVerticalStrut(4)); passwordTextField.setMaximumSize(new Dimension(2000, 25)); passwordTextField.setPreferredSize(new Dimension(600, 20)); passwordTextField.setToolTipText("Password required by server."); passwordTextField.addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { setPasswordHash(false); } }); final JPanel cRow = new JPanel(); cRow.setLayout(new BoxLayout(cRow, BoxLayout.X_AXIS)); //cRow.add(Box.createHorizontalGlue()); cRow.add(new JLabel("Password: ")); cRow.add(passwordTextField); panel.add(cRow); panel.add(new JLabel(" ")); final JPanel dRow = new JPanel(); dRow.setLayout(new BoxLayout(dRow, BoxLayout.X_AXIS)); dRow.add(Box.createHorizontalGlue()); dRow.add(commandManager.getButton(OpenRemoteServerCommand.ALT_NAME)); panel.add(dRow); final JPanel outside = new JPanel(); outside.setLayout(new BoxLayout(outside, BoxLayout.Y_AXIS)); outside.add(Box.createVerticalGlue()); outside.add(panel, BorderLayout.NORTH); outside.add(Box.createVerticalGlue()); for (var item : additionalItems) { final AbstractButton button = commandManager.getButton(item); if (button != null) { final JPanel aLine = new JPanel(); aLine.setLayout(new BoxLayout(aLine, BoxLayout.LINE_AXIS)); aLine.add(button); aLine.add(Box.createHorizontalGlue()); outside.add(aLine); } } { final JPanel aLine = new JPanel(); aLine.setLayout(new BoxLayout(aLine, BoxLayout.LINE_AXIS)); aLine.add(Box.createHorizontalGlue()); aLine.add(new JLabel("Save credentials")); aLine.add(saveCredentialsCBox); saveCredentialsCBox.addActionListener(e -> ProgramProperties.put("SaveRemoteCredentials", saveCredentialsCBox.isSelected())); saveCredentialsCBox.setToolTipText("Save MeganServer credentials"); outside.add(aLine); } urlComboBox.setSelectedIndex(0); return outside; } @Override public boolean isShowFindToolBar() { return showFindToolBar; } @Override public void setShowFindToolBar(boolean show) { this.showFindToolBar = show; updateView(IDirector.ENABLE_STATE); } @Override public SearchManager getSearchManager() { return searchManager; } public boolean isUptoDate() { return uptoDate; } public JFrame getFrame() { return this; } public void updateView(String what) { uptoDate = false; setTitle(); saveCredentialsCBox.setSelected(ProgramProperties.get("SaveRemoteCredentials", true)); commandManager.updateEnableState(); if (tabbedPane.getSelectedComponent() instanceof ServicePanel) { final ServicePanel servicePanel = (ServicePanel) tabbedPane.getSelectedComponent(); searchManager.setSearcher(servicePanel.getjTreeSearcher()); statusBar.setText2("Number of files: " + servicePanel.getService().getAvailableFiles().size()); statusBar.setToolTipText(servicePanel.getToolTipText() + (servicePanel.getSelectedFiles().size() > 0 ? " (" + servicePanel.getSelectedFiles().size() + " selected)" : "")); servicePanel.updateFonts(); } else { searchManager.setSearcher(new EmptySearcher()); statusBar.setText2(""); statusBar.setToolTipText(""); } final FindToolBar findToolBar = searchManager.getFindDialogAsToolBar(); if (findToolBar.isClosing()) { showFindToolBar = false; findToolBar.setClosing(false); } if (!findToolBar.isEnabled() && showFindToolBar) { mainPanel.add(findToolBar, BorderLayout.NORTH); findToolBar.setEnabled(true); getContentPane().validate(); getCommandManager().updateEnableState(); } else if (findToolBar.isEnabled() && !showFindToolBar) { mainPanel.remove(findToolBar); findToolBar.setEnabled(false); getContentPane().validate(); getCommandManager().updateEnableState(); } if (findToolBar.isEnabled()) findToolBar.clearMessage(); uptoDate = true; } public void lockUserInput() { locked = true; commandManager.setEnableCritical(false); searchManager.getFindDialogAsToolBar().setEnableCritical(false); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); urlComboBox.setEnabled(false); userTextField.setEnabled(false); passwordTextField.setEnabled(false); saveCredentialsCBox.setEnabled(false); menuBar.setEnableRecentFileMenuItems(false); } public void unlockUserInput() { commandManager.setEnableCritical(true); searchManager.getFindDialogAsToolBar().setEnableCritical(true); setCursor(Cursor.getDefaultCursor()); urlComboBox.setEnabled(true); userTextField.setEnabled(true); passwordTextField.setEnabled(true); saveCredentialsCBox.setEnabled(true); menuBar.setEnableRecentFileMenuItems(true); locked = false; } /** * is viewer currently locked? * * @return true, if locked */ public boolean isLocked() { return locked; } /** * destroy the view. todo: this does not get called at present */ public void destroyView() { MeganProperties.removePropertiesListListener(menuBar.getRecentFilesListener()); dir.removeViewer(this); searchManager.getFindDialogAsToolBar().close(); if (!ProgramProperties.get("SaveRemoteCredentials", false)) ProgramProperties.put("MeganServers", new String[0]); dispose(); } public void setUptoDate(boolean flag) { uptoDate = flag; } /** * set the title of the window */ private void setTitle() { setTitle("Remote MEGAN Files"); } public CommandManager getCommandManager() { return commandManager; } /** * add a remote file service * */ public void addService(final IRemoteService service) { final ServicePanel servicePanel = new ServicePanel(service, this); servicePanel.setToolTipText(service.getServerURL()); tabbedPane.add(servicePanel, 0); tabbedPane.setTitleAt(0, abbreviateName(service.getServerURL())); tabbedPane.setSelectedIndex(0); } /** * abbreviate name * * @return name of length <=18 */ private String abbreviateName(String name) { name = name.replace("http://", "").replace(":8080", "").replaceAll("/megan6server$", ""); if (name.length() <= 18) return name; return "..." + name.substring(name.length() - 15); } /** * get the URL of a service * * @return URL */ public String getURL() { Component component = tabbedPane.getSelectedComponent(); if (isServiceSelected()) { return ((ServicePanel) component).getURL(); } else { String url = urlComboBox.getCurrentText(false); if (url != null) return url.trim(); else return ""; } } public void setURL(String URL) { urlComboBox.setSelectedItem(URL); } public String getUser() { return userTextField.getText().trim(); } public void setUser(String user) { userTextField.setText(user); } public String getPasswordHash() { if(isPasswordHash()) return String.valueOf(passwordTextField.getPassword()); else { return Utilities.computeBCryptHash(new String(passwordTextField.getPassword()).getBytes()); } } /** * get name for this type of viewer * * @return name */ public String getClassName() { return "RemoteBrowser"; } /** * get the number of currently chosen documents * * @return currently chosen documents */ public int getNumberOfChosenDocuments() { return 0; } public Director getDir() { return dir; } public DocumentListener createDocumentListener() { return new DocumentListener() { public void insertUpdate(DocumentEvent e) { changedUpdate(e); } public void removeUpdate(DocumentEvent e) { changedUpdate(e); } public void changedUpdate(DocumentEvent e) { try { final String shortServerName = e.getDocument().getText(0, e.getDocument().getLength()).replace("http://", "").replaceAll("/$", "") + "::"; final String user = RemoteServiceManager.getUser(shortServerName); userTextField.setText(user != null ? user : ""); final String password = RemoteServiceManager.getPasswordHash(shortServerName); passwordTextField.setText(password != null ? password : ""); } catch (BadLocationException ignored) { } updateView(IDirector.ENABLE_STATE); } }; } /** * save the current configuation */ public void saveConfig() { urlComboBox.getCurrentText(true); } /** * close the named service * * @return true, if service found and closed */ public boolean closeRemoteService(String url) { url = url.replace(".*://", ""); for (int i = 0; i < tabbedPane.getTabCount(); i++) { if (tabbedPane.getComponentAt(i) instanceof ServicePanel) { final ServicePanel panel = (ServicePanel) tabbedPane.getComponentAt(i); if (panel.getService().getServerURL().equalsIgnoreCase(url)) { { RemoteServiceManager.removeNode(url); tabbedPane.remove(panel); return true; } } } } return false; } /** * is the currently selected panel a service panel? * * @return true if service panel currently selected */ public boolean isServiceSelected() { return tabbedPane != null && tabbedPane.getSelectedComponent() != null && tabbedPane.getSelectedComponent() instanceof ServicePanel; } /** * select the given service tab, if present * */ public boolean selectServiceTab(String url) { url = url.replaceAll(".*://", ""); for (int i = 0; i < tabbedPane.getTabCount(); i++) { if (tabbedPane.getTitleAt(i).equalsIgnoreCase(url)) { tabbedPane.setSelectedIndex(i); return true; } } return false; } public MenuBar getMenu() { return menuBar; } public ServicePanel getServicePanel() { if (tabbedPane != null && tabbedPane.getSelectedComponent() instanceof ServicePanel) return (ServicePanel) tabbedPane.getSelectedComponent(); else return null; } public boolean isPasswordHash() { return passwordHash; } public void setPasswordHash(boolean passwordHash) { this.passwordHash = passwordHash; } public void clearUser() { userTextField.setText(""); } public void clearPassword() { passwordTextField.setText(""); } }
19,428
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
RemoteService.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/clientdialog/service/RemoteService.java
/* * RemoteService.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.ms.clientdialog.service; import megan.ms.client.ClientMS; import megan.ms.clientdialog.IRemoteService; import megan.ms.server.MeganServer; import java.io.IOException; import java.util.*; /** * implements a remote service * <p/> * Created by huson on 10/3/14, 7.2021 */ public class RemoteService implements IRemoteService { private final String serverURL; private final ClientMS clientMS; private final Set<String> files=new TreeSet<>(); private final boolean serverSupportsGetDescription; private final String about; private final Map<String, String> fileName2Description = new HashMap<>(); /** * constructor * * @path path to root directory */ public RemoteService(String serverURL, String user, String passwordHash) throws IOException { serverURL = serverURL.replaceAll("/$", ""); if(serverURL.endsWith("/help")) serverURL=serverURL.substring(0,serverURL.length()-4); // remove help if (!serverURL.contains(("/"))) serverURL += "/megan6server"; this.serverURL = serverURL; clientMS = new ClientMS(this.serverURL, null, 0, user, passwordHash, 600); final String remoteVersion = clientMS.getAsString("version"); if (!remoteVersion.startsWith("MeganServer")) throw new IOException("Failed to confirm MeganServer at remote site"); if (!remoteVersion.equals(MeganServer.Version)) throw new IOException("Incompatible version numbers: client=" + MeganServer.Version + " server=" + remoteVersion); about = clientMS.getAsString("about"); serverSupportsGetDescription =clientMS.getAsString("help").contains("getDescription"); System.err.println(about); var directories=new HashSet<String>(); directories.add("."); for(var fileRecord:clientMS.getFileRecords()) { var name=fileRecord.getName(); files.add(name); if(serverSupportsGetDescription) { try { var description = clientMS.getAsString("getDescription?file=" + fileRecord.getName()); if (!description.isBlank()) fileRecord.setDescription(description); } catch (IOException ignored) { } } fileName2Description.put(name, fileRecord.getDescription()); if(name.contains("/")) directories.add(name.substring(0,name.lastIndexOf("/"))); } if(serverSupportsGetDescription) { for (var directory : directories) { fileName2Description.put(directory, directory); try { var description = clientMS.getAsString("getDescription?file=" + directory); if (!description.isBlank()) fileName2Description.put(directory, description); } catch (IOException ignored) { } } } System.err.println("Server: " + serverURL + ", number of available files: " + getAvailableFiles().size()); } /** * is this node available? * * @return availability */ @Override public boolean isAvailable() { return true; // todo: fix } /** * get a list of available files and their unique ids * * @return list of available files in format path,id */ @Override public Collection<String> getAvailableFiles() { return files; } /** * get the server URL * * @return server URL */ @Override public String getServerURL() { return serverURL; } /** * gets the server and file name * * @return server and file */ @Override public String getServerAndFileName(String file) { return serverURL + "::" + file; } /** * gets the info string for a server * * @return info in html */ @Override public String getInfo() { try { return clientMS.getAsString("about"); } catch (IOException ignored) { } return ""; } /** * get the description associated with a given file name * * @return description */ public String getDescription(String fileName) { return fileName2Description.get(fileName); } public ClientMS getClientMS() { return clientMS; } public String getAbout() { return about; } }
5,342
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IService.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/clientdialog/service/IService.java
/* * IService.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.ms.clientdialog.service; import java.io.FileFilter; import java.util.List; /** * Represents a directory system of files, can be local or on a server * <p/> * Created by huson on 10/3/14. */ interface IService { /** * get URL of remote server * * @return url */ String getRemoteURL(); /** * get the local name of this node * * @return local name */ String getNodeName(); /** * set the file filter * */ void setFileFilter(FileFilter fileFilter); /** * is this node currently available? * * @return availability */ boolean isAvailable(); /** * get a list of available files and their unique ids * * @return list of available files in format path,id */ List<String> getAvailableFiles(); /** * gets the file length for the given file * * @return file length */ long getFileLength(int fileId); /** * opens the specified file for reading * * @return handle id */ int openFile(String name); /** * seek * */ void seek(int handleId, long pos); /** * read the specified number of bytes * * @param handleId value returned by openFile * @return number of bytes read */ int read(int handleId, byte[] buffer, int offset, int length); /** * close the file associated with the given handle * */ void closeFile(int handleId); /** * gets the last time that the content of this node was updated * * @return last rescan time */ long getLastUpdateTime(); /** * get the file id for a name * * @return file id */ Integer getId(String name); /** * get current position in file * * @return current position */ long getPosition(int handleId); }
2,699
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
RemoteServiceManager.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/clientdialog/service/RemoteServiceManager.java
/* * RemoteServiceManager.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.ms.clientdialog.service; import jloda.swing.util.ProgramProperties; import jloda.util.Pair; import megan.ms.Utilities; import megan.ms.clientdialog.IRemoteService; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; /** * remote service manager * <p/> * Daniel Huson, 2014, 10.2020 */ public class RemoteServiceManager { public static final String LOCAL = "Local::"; public static final String DEFAULT_MEGAN_SERVER = "http://maira.cs.uni-tuebingen.de:8001/megan6server"; private static final Map<String, IRemoteService> url2node = new HashMap<>(); private static final Map<String, Pair<String, String>> server2Credentials = new HashMap<>(); private static boolean loaded = false; // have the credentials been loaded from the properties file? /** * create a new node * * @return node or null */ public static IRemoteService createService(String remoteURL, String user, String password) throws IOException { final IRemoteService clientNode; if (remoteURL.startsWith(LOCAL)) { clientNode = new LocalService(remoteURL.replaceAll(LOCAL, ""), ".rma", ".rma6", ".daa", ".megan", "megan.gz"); } else clientNode = new RemoteService(remoteURL, user, password); if (url2node.containsKey(clientNode.getServerURL())) System.err.println("Server is already open: " + clientNode.getServerURL()); url2node.put(clientNode.getServerURL(), clientNode); if (ProgramProperties.get("SaveRemoteCredentials", true)) saveCredentials(clientNode.getServerURL(), user, password); return clientNode; } /** * remove the node * */ public static void removeNode(String url) { url2node.remove(url); } /** * does node for this URL exist * * @return true, if node for URL exists */ public static boolean hasNode(String url) { return url2node.containsKey(url); } /** * get the client node * * @return node */ public static IRemoteService get(String url) { return url2node.get(url); } /** * get the server URL * * @return full file URL as required by connector */ public static String getServerURL(String serverFileName) { var pos = serverFileName.indexOf(("::")); if (pos > 0) return serverFileName.substring(0, pos); else return serverFileName; } /** * get the remote file path * * @return remote file path */ public static String getFilePath(String serverFileName) { if (isRemoteFile(serverFileName)) { var pos = serverFileName.indexOf("::"); return serverFileName.substring(pos + "::".length()); } else return null; } /** * get the remote user * * @return remote user */ public static String getUser(String serviceName) { var credentials = getCredentials(serviceName); if (credentials != null) return credentials.getFirst(); else return "guest"; } /** * get remote password * * @return password */ public static String getPasswordHash(String serviceName) { final Pair<String, String> credentials = getCredentials(serviceName); if (credentials != null) return credentials.getSecond(); else return "guest"; } /** * does this file name have the syntax of a remote file? * * @return true, if local name of a remote file */ private static boolean isRemoteFile(String fileName) { return !fileName.startsWith(LOCAL) && fileName.contains("::"); } /** * get credentials for given server, if known * * @return credentials */ public static Pair<String, String> getCredentials(String serviceName) { return server2Credentials.get(serviceName); } /** * save credentials for given server * */ public static void saveCredentials(String serviceName, String user, String passwordHash) { server2Credentials.put(serviceName, new Pair<>(user, passwordHash)); saveCredentialsToProperties(); } /** * load all saved credentials from properties */ public static void ensureCredentialsHaveBeenLoadedFromProperties() { if (!loaded) { final var credentials = ProgramProperties.get("MeganServers", new String[0]); for (var line : credentials) { var tokens = line.split("::"); if (tokens.length > 0) { server2Credentials.put(tokens[0], new Pair<>(tokens.length > 1 ? tokens[1] : "", (tokens.length > 2 ? tokens[2] : ""))); } } loaded = true; } } /** * save all credentials to properties */ private static void saveCredentialsToProperties() { final var list = new LinkedList<String>(); var toDelete=new ArrayList<String>(); for (var server : server2Credentials.keySet()) { if (server.toLowerCase().contains("informatik.uni-tuebingen.de")) { System.err.println("Removed defunct server address: " + server); toDelete.add(server); } } toDelete.forEach(server2Credentials.keySet()::remove); for (var server : server2Credentials.keySet()) { var pair = server2Credentials.get(server); list.add(server + "::" + pair.getFirst() + "::" + pair.getSecond()); } ProgramProperties.put("MeganServers", list.toArray(new String[0])); } /** * remove credentials for given URL * */ public static void removeCredentials(String url) { server2Credentials.remove(url); } public static Collection<String> getServers() { ensureCredentialsHaveBeenLoadedFromProperties(); return server2Credentials.keySet(); } public static void ensureDefaultService() { var user = "guest"; var passwordHash = Utilities.computeBCryptHash("guest".getBytes()); saveCredentials(DEFAULT_MEGAN_SERVER, user, passwordHash); } }
7,130
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
LocalService.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/clientdialog/service/LocalService.java
/* * LocalService.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.ms.clientdialog.service; import jloda.util.CanceledException; import jloda.util.FileUtils; import jloda.util.progress.ProgressListener; import megan.core.DataTable; import megan.core.Document; import megan.core.SampleAttributeTable; import megan.core.SyncArchiveAndDataTable; import megan.ms.clientdialog.IRemoteService; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.*; import java.util.concurrent.locks.ReentrantLock; /** * implements a local directory service * <p/> * Daniel Huson, 2014, 2021 */ public class LocalService implements IRemoteService { private final String[] fileExtensions; private final String fullServerDirectory; private File rootDirectory; private final List<String> files; private final Map<String, String> fileName2Description = new HashMap<>(); private final ReentrantLock lock = new ReentrantLock(); // need to look when rescanning directory /** * constructor */ public LocalService(String rootDirectory, String... fileExtensions) throws IOException { fullServerDirectory = "Local::" + rootDirectory; files = new LinkedList<>(); this.fileExtensions = fileExtensions; setRootDirectory(new File(rootDirectory)); } /** * is this service available? * * @return true, if data present */ @Override public boolean isAvailable() { return files.size() > 0; } /** * get a list of available files and their unique ids * * @return list of available files in format path,id */ @Override public Collection<String> getAvailableFiles() { return files; } /** * get the remote server URL and directory path, e.g. www.megan.de/data/files * * @return file specification */ @Override public String getServerURL() { return fullServerDirectory; } /** * set the root directory. All files must be below this directory */ private void setRootDirectory(File rootDirectory) throws IOException { if (rootDirectory != null) { rootDirectory = rootDirectory.getAbsoluteFile(); if (!rootDirectory.isDirectory()) throw new IOException("Not a directory: " + rootDirectory); if (!rootDirectory.exists()) throw new IOException("Directory not found: " + rootDirectory); if (!rootDirectory.canRead()) throw new IOException("Cannot read: " + rootDirectory); } System.err.println("Set root directory to: " + rootDirectory); this.rootDirectory = rootDirectory; } /** * rescan root directory and rescan contents */ public void rescan(ProgressListener progress) { progress.setSubtask("Scanning..."); lock.lock(); try { files.clear(); final var files = FileUtils.getAllFilesInDirectory(rootDirectory, true, fileExtensions); var directories = new HashSet<File>(); for (var file : files) { try { directories.add(file.getParentFile()); final var relative = FileUtils.getRelativeFile(file, rootDirectory).getPath(); final var doc = new Document(); doc.getMeganFile().setFileFromExistingFile(file.getPath(), true); if (doc.getMeganFile().hasDataConnector()) { final var connector = doc.getMeganFile().getConnector(); final var dataTable = new DataTable(); SampleAttributeTable sampleAttributeTable = new SampleAttributeTable(); SyncArchiveAndDataTable.syncArchive2Summary(null, doc.getMeganFile().getFileName(), connector, dataTable, sampleAttributeTable); this.files.add(relative); fileName2Description.put(relative, String.format("reads: %,d, matches: %,d", connector.getNumberOfReads(), connector.getNumberOfMatches())); } else if (doc.getMeganFile().isMeganSummaryFile()) { this.files.add(relative); fileName2Description.put(relative, String.format("reads: %,d", doc.getNumberOfReads())); } if (FileUtils.fileExistsAndIsNonEmpty(FileUtils.replaceFileSuffix(file, ".txt"))) fileName2Description.put(relative, Files.readString(FileUtils.replaceFileSuffix(file, ".txt").toPath())); progress.checkForCancel(); } catch (CanceledException ex) { break; } catch (IOException ignored) { } } for(var directory:directories) { var aboutFile=new File(directory,"About.txt"); if(aboutFile.exists()) { try { fileName2Description.put(directory.getPath(),Files.readString(aboutFile.toPath())); } catch (IOException ignored) { } } } } finally { lock.unlock(); } } /** * get the full absolute file path */ private String getAbsoluteFilePath(String localFileName) { return rootDirectory + File.separator + localFileName; } /** * gets the server and file name */ @Override public String getServerAndFileName(String file) { return getAbsoluteFilePath(file); } public String getInfo() { return String.format("Number of files: %,d", fileName2Description.size()); } /** * get the description associated with a given file name */ public String getDescription(String fileName) { return fileName2Description.get(fileName); } }
6,452
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ExpandNodesCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/clientdialog/commands/ExpandNodesCommand.java
/* * ExpandNodesCommand.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.ms.clientdialog.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.ms.clientdialog.RemoteServiceBrowser; import megan.ms.clientdialog.ServicePanel; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; /** * command * Daniel Huson, 11.2010 */ public class ExpandNodesCommand extends CommandBase implements ICommand { /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); ServicePanel servicePanel = ((RemoteServiceBrowser) getViewer()).getServicePanel(); if (servicePanel != null) { TreePath[] paths = servicePanel.getFileTree().getSelectionPaths(); if (paths != null) servicePanel.expand(paths); else servicePanel.expand((DefaultMutableTreeNode) servicePanel.getFileTree().getModel().getRoot()); } } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "expand;"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { executeImmediately(getSyntax()); } public String getName() { return "Expand"; } public static final String ALTNAME = "Expand Remote Browser Nodes"; public String getAltName() { return ALTNAME; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Expand the selected nodes, or all, if none selected"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("sun/AlignJustifyVertical16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_J, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } /** * 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() { RemoteServiceBrowser remoteServiceBrowser = (RemoteServiceBrowser) getViewer(); return remoteServiceBrowser != null && remoteServiceBrowser.getServicePanel() != null && remoteServiceBrowser.getServicePanel().getFileTree().getModel().getRoot() != null && remoteServiceBrowser.getServicePanel().getFileTree().getModel().getChildCount(remoteServiceBrowser.getServicePanel().getFileTree().getModel().getRoot()) > 0; } }
4,072
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
OpenSelectedFilesCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/clientdialog/commands/OpenSelectedFilesCommand.java
/* * OpenSelectedFilesCommand.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.ms.clientdialog.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.ms.clientdialog.RemoteServiceBrowser; import megan.ms.clientdialog.ServicePanel; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.Collection; import java.util.Set; /** * command * Daniel Huson, 11.2010 */ public class OpenSelectedFilesCommand extends CommandBase implements ICommand { /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); ServicePanel servicePanel = ((RemoteServiceBrowser) getViewer()).getServicePanel(); if (servicePanel != null) { TreePath[] paths = servicePanel.getFileTree().getSelectionPaths(); if (paths != null) servicePanel.collapse(paths); else servicePanel.collapse((DefaultMutableTreeNode) servicePanel.getFileTree().getModel().getRoot()); } } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "openSelectedFiles;"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { final RemoteServiceBrowser remoteServiceBrowser = (RemoteServiceBrowser) getViewer(); final ServicePanel servicePanel = remoteServiceBrowser.getServicePanel(); if (servicePanel != null) { final Collection<String> selectedFiles = remoteServiceBrowser.getServicePanel().getSelectedFiles(); final StringBuilder buf = new StringBuilder(); int count = 0; Set<String> openFiles = servicePanel.getCurrentlyOpenRemoteFiles(); for (String fileName : selectedFiles) { if (openFiles.contains(fileName)) { buf.append("toFront file='").append(fileName).append("';"); } else { buf.append("open file='").append(fileName).append("' readOnly=true;"); count++; } } if (count > 10) { if (JOptionPane.showConfirmDialog(remoteServiceBrowser.getFrame(), "Do you really want to open " + count + " new files?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon()) == JOptionPane.NO_OPTION) return; } execute(buf.toString()); } } public String getName() { return "Open"; } public static final String ALTNAME = "Open Selected Files"; public String getAltName() { return ALTNAME; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Open all selected files"; } /** * 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()); } /** * 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() { RemoteServiceBrowser remoteServiceBrowser = (RemoteServiceBrowser) getViewer(); return remoteServiceBrowser != null && remoteServiceBrowser.getServicePanel() != null && remoteServiceBrowser.getServicePanel().getSelectedFiles().size() > 0; } }
5,175
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SelectNoneCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/clientdialog/commands/SelectNoneCommand.java
/* * SelectNoneCommand.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.ms.clientdialog.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; /** * * selection command * * Daniel Huson, 11.2010 */ public class SelectNoneCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { execute("select samples=none;"); } public boolean isApplicable() { return true; } public String getName() { return "Select None"; } public String getDescription() { return "Deselect all"; } public ImageIcon getIcon() { return ResourceManager.getIcon("Empty16.gif"); } public boolean isCritical() { return true; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | InputEvent.SHIFT_DOWN_MASK); } }
2,244
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
CollapseNodesCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/clientdialog/commands/CollapseNodesCommand.java
/* * CollapseNodesCommand.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.ms.clientdialog.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.ms.clientdialog.RemoteServiceBrowser; import megan.ms.clientdialog.ServicePanel; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; /** * command * Daniel Huson, 11.2010 */ public class CollapseNodesCommand extends CommandBase implements ICommand { /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); ServicePanel servicePanel = ((RemoteServiceBrowser) getViewer()).getServicePanel(); if (servicePanel != null) { TreePath[] paths = servicePanel.getFileTree().getSelectionPaths(); if (paths != null) servicePanel.collapse(paths); else servicePanel.collapse((DefaultMutableTreeNode) servicePanel.getFileTree().getModel().getRoot()); } } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "collapse;"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { executeImmediately(getSyntax()); } public String getName() { return "Collapse"; } public static final String ALTNAME = "Collapse Remote Browser Nodes"; public String getAltName() { return ALTNAME; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Collapse the selected nodes, or all, if none selected"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("sun/AlignJustifyHorizontal16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_K, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } /** * 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() { RemoteServiceBrowser remoteServiceBrowser = (RemoteServiceBrowser) getViewer(); return remoteServiceBrowser != null && remoteServiceBrowser.getServicePanel() != null && remoteServiceBrowser.getServicePanel().getFileTree().getModel().getRoot() != null && remoteServiceBrowser.getServicePanel().getFileTree().getModel().getChildCount(remoteServiceBrowser.getServicePanel().getFileTree().getModel().getRoot()) > 0; } }
4,090
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SelectAllCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/clientdialog/commands/SelectAllCommand.java
/* * SelectAllCommand.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.ms.clientdialog.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.ms.clientdialog.RemoteServiceBrowser; import megan.ms.clientdialog.ServicePanel; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; /** * * selection command * * Daniel Huson, 11.2010 */ public class SelectAllCommand extends CommandBase implements ICommand { public String getSyntax() { return "select samples={all|none};"; } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { ServicePanel servicePanel = ((RemoteServiceBrowser) getViewer()).getServicePanel(); np.matchIgnoreCase("select samples="); String what = np.getWordMatchesIgnoringCase("all none"); if (what.equalsIgnoreCase("all")) servicePanel.selectAll(true); else if (what.equals("none")) servicePanel.selectAll(false); np.matchRespectCase(";"); System.err.println("Number of nodes selected: " + servicePanel.getSelectedFiles().size()); } public void actionPerformed(ActionEvent event) { executeImmediately("select samples=all;"); } public boolean isApplicable() { return true; } public String getName() { return "Select All"; } public String getDescription() { return "Select"; } public ImageIcon getIcon() { return ResourceManager.getIcon("Empty16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } }
2,714
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
OpenRemoteServerCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/clientdialog/commands/OpenRemoteServerCommand.java
/* * OpenRemoteServerCommand.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.ms.clientdialog.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.core.Director; import megan.ms.clientdialog.IRemoteService; import megan.ms.clientdialog.RemoteServiceBrowser; import megan.ms.clientdialog.service.LocalService; import megan.ms.clientdialog.service.RemoteServiceManager; import javax.swing.*; import java.awt.event.ActionEvent; /** * command * Daniel Huson, 12.2014 */ public class OpenRemoteServerCommand extends CommandBase implements ICommand { private static String hiddenPassword; private static final String HIDDEN_PASSWORD = "******"; private static final Object syncObject = new Object(); /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("openServer url="); final String url = np.getWordFileNamePunctuation(); String user = ""; if (np.peekMatchIgnoreCase("user")) { np.matchIgnoreCase("user="); user = np.getWordRespectCase(); } String password = ""; if (np.peekMatchIgnoreCase("password")) { np.matchIgnoreCase("password="); password = np.getWordRespectCase(); synchronized (syncObject) { if (password.equals(HIDDEN_PASSWORD) && hiddenPassword != null) password = hiddenPassword; hiddenPassword = null; } } np.matchIgnoreCase(";"); if (!((RemoteServiceBrowser) getViewer()).selectServiceTab(url)) { IRemoteService service = RemoteServiceManager.createService(url, user, password); if (service instanceof LocalService) { ((LocalService) service).rescan(((Director) getDir()).getDocument().getProgressListener()); } if (service.isAvailable()) { ((RemoteServiceBrowser) getViewer()).addService(service); ((RemoteServiceBrowser) getViewer()).saveConfig(); } } } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "openServer url=<url> [user=<user>] [password=<hiddenPassword>];"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { final RemoteServiceBrowser remoteServiceBrowser = (RemoteServiceBrowser) getViewer(); if (remoteServiceBrowser != null) { String url = remoteServiceBrowser.getURL(); String user = remoteServiceBrowser.getUser(); String passwordHash = remoteServiceBrowser.getPasswordHash(); String command = "openServer url='" + url + "'"; if (user.length() > 0) command += " user='" + user + "'"; if (passwordHash.length() > 0) { synchronized (syncObject) { OpenRemoteServerCommand.hiddenPassword = passwordHash; } command += " password='" + HIDDEN_PASSWORD + "'"; } command += ";"; if (url.length() > 0) { execute(command); } } } private static final String NAME = "Open"; public String getName() { return NAME; } public static final String ALT_NAME = "Open Server..."; public String getAltName() { return ALT_NAME; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Open a remote server"; } /** * 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() { if (getViewer() == null || !(getViewer() instanceof RemoteServiceBrowser)) return false; final RemoteServiceBrowser remoteServiceBrowser = (RemoteServiceBrowser) getViewer(); return !remoteServiceBrowser.isServiceSelected() && remoteServiceBrowser.getURL().length() > 0; } }
5,621
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
CloseRemoteServerCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/clientdialog/commands/CloseRemoteServerCommand.java
/* * CloseRemoteServerCommand.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.ms.clientdialog.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.swing.window.NotificationsInSwing; import jloda.util.parse.NexusStreamParser; import megan.ms.clientdialog.RemoteServiceBrowser; import javax.swing.*; import java.awt.event.ActionEvent; /** * close remote server connection * Daniel Huson, 10.2014 */ public class CloseRemoteServerCommand extends CommandBase implements ICommand { /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("detach remoteServer="); final String url = np.getWordFileNamePunctuation(); np.matchIgnoreCase(";"); if (((RemoteServiceBrowser) getViewer()).closeRemoteService(url)) System.err.println("Service closed: " + url); else NotificationsInSwing.showError(getViewer().getFrame(), "Failed to close service: " + url); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "detach remoteServer=<url>;"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { final RemoteServiceBrowser remoteServiceBrowser = (RemoteServiceBrowser) getViewer(); if (remoteServiceBrowser != null) { String url = remoteServiceBrowser.getURL(); if (url.length() > 0) { execute("detach remoteServer=" + url + ";"); } } } private static final String NAME = "Close"; public String getName() { return NAME; } private static final String ALT_NAME = "Close Remote Server..."; public String getAltName() { return ALT_NAME; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Close remote server"; } /** * 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 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() != null && getViewer() instanceof RemoteServiceBrowser && ((RemoteServiceBrowser) getViewer()).isServiceSelected(); } }
3,822
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ShowServerInfoCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/clientdialog/commands/ShowServerInfoCommand.java
/* * ShowServerInfoCommand.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.ms.clientdialog.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.Message; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.ms.clientdialog.RemoteServiceBrowser; import megan.ms.clientdialog.ServicePanel; import javax.swing.*; import java.awt.event.ActionEvent; /** * command * Daniel Huson, 11.2010 */ public class ShowServerInfoCommand extends CommandBase implements ICommand { /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); ServicePanel servicePanel = ((RemoteServiceBrowser) getViewer()).getServicePanel(); if (servicePanel != null) { Message.show(getViewer().getFrame(), servicePanel.getService().getInfo()); } } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "showServerInfo;"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { executeImmediately(getSyntax()); } final static public String NAME = "Server Info..."; public String getName() { return NAME; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Show remote server info page"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("sun/About16.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() { RemoteServiceBrowser remoteServiceBrowser = (RemoteServiceBrowser) getViewer(); return remoteServiceBrowser != null && remoteServiceBrowser.getServicePanel() != null; } }
3,335
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
CompareSelectedFilesCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/clientdialog/commands/CompareSelectedFilesCommand.java
/* * CompareSelectedFilesCommand.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.ms.clientdialog.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.dialogs.compare.CompareWindow; import megan.ms.clientdialog.RemoteServiceBrowser; import megan.ms.clientdialog.ServicePanel; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.Collection; /** * compare command * Daniel Huson, 11.2010 */ public class CompareSelectedFilesCommand extends CommandBase implements ICommand { /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase(getSyntax()); final RemoteServiceBrowser remoteServiceBrowser = (RemoteServiceBrowser) getViewer(); final ServicePanel servicePanel = remoteServiceBrowser.getServicePanel(); if (servicePanel != null) { final Collection<String> selectedFiles = remoteServiceBrowser.getServicePanel().getSelectedFiles(); if (selectedFiles.size() > 1) { CompareWindow compareWindow = new CompareWindow(getViewer().getFrame(), remoteServiceBrowser.getDir(), selectedFiles); if (!compareWindow.isCanceled()) { final Director newDir = Director.newProject(); newDir.getMainViewer().getFrame().setVisible(true); newDir.getMainViewer().setDoReInduce(true); newDir.getMainViewer().setDoReset(true); final String command = compareWindow.getCommand(); if (command != null) newDir.execute(command, newDir.getCommandManager()); } } } } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "compare;"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { execute(getSyntax()); } /** * get id of open file * */ private int getPID(String fileName) { for (final IDirector iDir : ProjectManager.getProjects()) { Director dir = (Director) iDir; if (dir.getDocument().getMeganFile().getFileName().equals(fileName)) return dir.getID(); } return -1; } public String getName() { return "Compare"; } public static final String ALTNAME = "Compare Selected Files"; public String getAltName() { return ALTNAME; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Open all selected files in a comparison document"; } /** * 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 KeyStroke.getKeyStroke(KeyEvent.VK_M, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } /** * 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() { RemoteServiceBrowser remoteServiceBrowser = (RemoteServiceBrowser) getViewer(); return remoteServiceBrowser != null && remoteServiceBrowser.getServicePanel() != null && remoteServiceBrowser.getServicePanel().getSelectedFiles().size() > 1; } }
4,900
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
HttpHandlerMS.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/server/HttpHandlerMS.java
/* * HttpHandlerMS.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.ms.server; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import jloda.util.Basic; import jloda.util.StringUtils; import java.io.IOException; import java.util.concurrent.atomic.AtomicLong; /** * handles an HTTP request * Daniel Huson, 8.2020 */ public class HttpHandlerMS implements HttpHandler { private final RequestHandler requestHandler; private static final AtomicLong numberOfRequests = new AtomicLong(0L); public HttpHandlerMS() { this(RequestHandler.getDefault()); } public HttpHandlerMS(RequestHandler requestHandler) { this.requestHandler = requestHandler; } @Override public void handle(HttpExchange httpExchange) throws IOException { try { final String[] parameters; if ("GET".equals(httpExchange.getRequestMethod())) { parameters = getGETParameters(httpExchange); } else if ("POST".equals(httpExchange.getRequestMethod())) { parameters = getPOSTParameters(httpExchange); } else parameters = null; respond(httpExchange, parameters); numberOfRequests.incrementAndGet(); } catch (Exception ex) { Basic.caught(ex); throw ex; } } private String[] getGETParameters(HttpExchange httpExchange) { final var uri = httpExchange.getRequestURI().toString(); final var posQuestionMark = uri.indexOf('?'); if (posQuestionMark > 0 && posQuestionMark < uri.length() - 1) { final var parameters = uri.substring(posQuestionMark + 1); if (parameters.contains("&")) { return StringUtils.split(parameters, '&'); } else return new String[]{parameters}; } return new String[0]; } private String[] getPOSTParameters(HttpExchange httpExchange) { return new String[0]; // not implemented } public void respond(HttpExchange httpExchange, String[] parameters) throws IOException { final var bytes = requestHandler.handle(httpExchange.getHttpContext().getPath(), parameters); try (var outputStream = httpExchange.getResponseBody()) { httpExchange.sendResponseHeaders(200, bytes.length); outputStream.write(bytes); outputStream.flush(); } } public static AtomicLong getNumberOfRequests() { return numberOfRequests; } }
3,302
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ReadsOutputFormat.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/server/ReadsOutputFormat.java
/* * ReadsOutputFormat.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.ms.server; /** * read output format * Daniel Huson, 10.2020 */ public class ReadsOutputFormat { private final boolean readIds; private final boolean headers; private final boolean sequences; private final boolean matches; public ReadsOutputFormat(boolean readIds, boolean headers, boolean sequences, boolean matches) { this.readIds = readIds; this.headers = headers; this.sequences = sequences; this.matches = matches; } public boolean isReadIds() { return readIds; } public boolean isHeaders() { return headers; } public boolean isSequences() { return sequences; } public boolean isMatches() { return matches; } }
1,572
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Parameters.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/server/Parameters.java
/* * Parameters.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.ms.server; import jloda.util.CollectionUtils; import jloda.util.NumberUtils; import jloda.util.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Parameters { public static boolean matchIgnoreCase(String[] parameters, String key, String value) { for (String param : parameters) { final String[] tokens = StringUtils.split(param, '='); if (tokens.length == 2 && tokens[0].equalsIgnoreCase(key) && CollectionUtils.contains(StringUtils.split(tokens[1].toLowerCase(), ','), value.toLowerCase())) return true; } return false; } public static String getValue(String[] parameters, String key) { for (String param : parameters) { final String[] tokens = StringUtils.split(param, '='); if (tokens.length == 2 && tokens[0].equalsIgnoreCase(key)) return tokens[1]; } return null; } public static boolean getValue(String[] parameters, String key, boolean defaultValue) { for (String param : parameters) { final String[] tokens = StringUtils.split(param, '='); if (tokens.length == 2 && tokens[0].equalsIgnoreCase(key) && NumberUtils.isBoolean(tokens[1])) return NumberUtils.parseBoolean(tokens[1]); } return defaultValue; } public static int getValue(String[] parameters, String key, int defaultValue) { for (String param : parameters) { final String[] tokens = StringUtils.split(param, '='); if (tokens.length == 2 && tokens[0].equalsIgnoreCase(key) && NumberUtils.isInteger(tokens[1])) return NumberUtils.parseInt(tokens[1]); } return defaultValue; } public static long getValue(String[] parameters, String key, long defaultValue) { for (String param : parameters) { final String[] tokens = StringUtils.split(param, '='); if (tokens.length == 2 && tokens[0].equalsIgnoreCase(key) && NumberUtils.isLong(tokens[1])) return NumberUtils.parseLong(tokens[1]); } return defaultValue; } public static double getValue(String[] parameters, String key, double defaultValue) { for (String param : parameters) { final String[] tokens = StringUtils.split(param, '='); if (tokens.length == 2 && tokens[0].equalsIgnoreCase(key) && NumberUtils.isDouble(tokens[1])) return NumberUtils.parseDouble(tokens[1]); } return defaultValue; } public static String[] getValues(String[] parameters, String key) { final ArrayList<String> values = new ArrayList<>(); for (String param : parameters) { final String[] tokens = StringUtils.split(param, '='); if (tokens.length == 2 && tokens[0].equalsIgnoreCase(key)) { values.addAll(Arrays.asList(StringUtils.split(tokens[1], ','))); } } return values.toArray(new String[0]); } public static boolean hasKey(String[] parameters, String key) { for (String param : parameters) { final String[] tokens = StringUtils.split(param, '='); if (tokens.length == 2 && tokens[0].equalsIgnoreCase(key)) return true; } return false; } public static List<Integer> getIntValues(String[] parameters, String key) { final ArrayList<Integer> list = new ArrayList<>(); final String[] values = getValues(parameters, key); for (String value : values) { if (NumberUtils.isInteger(value)) list.add(NumberUtils.parseInt(value)); } return list; } }
4,340
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
UserManager.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/server/UserManager.java
/* * UserManager.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.ms.server; import com.sun.net.httpserver.BasicAuthenticator; import jloda.util.FileUtils; import jloda.util.StringUtils; import megan.ms.Utilities; import java.io.*; import java.util.*; import java.util.stream.Collectors; /** * manages Megan server users * Daniel Huson, 10.2020 */ public class UserManager { public static final String ADMIN="admin"; private final String fileName; private final Map<String, String> user2passwordHash = new TreeMap<>(); private final Map<String,Set<String>> user2roles =new TreeMap<>(); private final MyAuthenticator authenticator = createAuthenticator(null); private final MyAuthenticator adminAuthenticator = createAuthenticator(ADMIN); public UserManager(String fileName) throws IOException { this.fileName = fileName; readFile(); } public List<String> listAllUsers() { return user2passwordHash.keySet().stream().map(user -> user + " " + StringUtils.toString(user2roles.get(user), ",")).collect(Collectors.toList()); } public void readFile() throws IOException { if (FileUtils.fileExistsAndIsNonEmpty(fileName)) { if (true) { if (FileUtils.getLinesFromFile(fileName).stream().filter(line -> line.startsWith("#")).anyMatch(line -> line.contains("password-md5"))) { throw new IOException("Users file '" + fileName + "' contains md5 hashes, no longer supported, please delete and setup new file"); } } FileUtils.getLinesFromFile(fileName).stream().filter(line -> line.length() > 0 && !line.startsWith("#")) .map(line -> line.contains("\t") ? line : line.replaceAll("\\s+", "\t")) .map(line -> StringUtils.split(line, '\t')) .filter(tokens -> tokens.length >= 2 && tokens[0].length() > 0 && tokens[1].length() > 0) .forEach(tokens -> { user2passwordHash.put(tokens[0], tokens[1]); final Set<String> roles=new TreeSet<>(); user2roles.put(tokens[0],roles); if (tokens.length == 3 && tokens[2].length()>0) roles.addAll(Arrays.asList(StringUtils.split(tokens[2], ','))); }); } } public void writeFile() throws IOException { System.err.println("Updating file: " + fileName); try (var w = new OutputStreamWriter(FileUtils.getOutputStreamPossiblyZIPorGZIP(fileName))) { w.write("#MeganServer registered users\n"); w.write("#Name\tpassword-hash\troles\n"); for (var entry : user2passwordHash.entrySet()) w.write(String.format("%s\t%s\t%s\n", entry.getKey(), entry.getValue(), StringUtils.toString(user2roles.get(entry.getKey()), ","))); } } public void addUser(String name, String password, boolean allowReplace, String... roles) throws IOException { if (!allowReplace && user2passwordHash.containsKey(name)) throw new IOException("User exists: " + name); user2passwordHash.put(name, Utilities.computeBCryptHash(password.getBytes())); user2roles.put(name,new TreeSet<>()); final List<String> nonNullRoles = Arrays.stream(roles).filter(Objects::nonNull).map(String::trim).filter(r -> r.length() > 0).toList(); if(nonNullRoles.size()>0) user2roles.get(name).addAll(nonNullRoles); writeFile(); } public void removeUser(String name) throws IOException { if (!user2passwordHash.containsKey(name)) throw new IOException("No such user: " + name); user2passwordHash.remove(name); user2roles.remove(name); writeFile(); } public void addRoles(String user, String... roles) throws IOException { if(roles.length>0) { if(!user2roles.containsKey(user)) throw new IOException("No such user: " + user); user2roles.get(user).addAll(Arrays.asList(roles)); writeFile(); } } public void removeRoles(String user, String... roles) throws IOException { if(roles.length>0) { if(!user2roles.containsKey(user)) throw new IOException("No such user: " + user); Arrays.asList(roles).forEach(user2roles.get(user)::remove); writeFile(); } } public boolean userExists(String name) { return user2passwordHash.containsKey(name); } public int size() { return user2passwordHash.size(); } public boolean hasAdmin() { for(var roles:user2roles.values()) { if (roles.contains(ADMIN)) return true; } return false; } public void askForAdminPassword() throws IOException { System.err.println(); final Console console = System.console(); if (console == null) System.err.printf("ATTENTION: No admin defined in list of users, enter password for special user 'admin':%n"); else console.printf("ATTENTION: No admin defined in list of users, enter password for special user 'admin':%n"); String password; while (true) { if (console == null) { password = (new BufferedReader(new InputStreamReader(System.in)).readLine()); } else { password = new String(console.readPassword()); } if (password == null || password.length() == 0) break; else if (password.length() < 8) System.err.println("Too short, enter a longer password (at least 8 characters):"); else if (password.contains("\t")) System.err.println("Contains a tab, enter a password that doesn't contain a tab:"); else break; } if (password == null || password.length() == 0) throw new IOException("Failed to input admin password"); addUser(ADMIN, password, true, UserManager.ADMIN); } public boolean checkCredentials(String requiredRole, String user, String passwordHash) { boolean result= user2passwordHash.containsKey(user) && passwordHash.equals(user2passwordHash.get(user)) && (requiredRole==null || user2roles.get(user).contains(requiredRole) || user2roles.get(user).contains(ADMIN) ); if(!result && requiredRole!=null && requiredRole.contains("/") && requiredRole.replaceAll(".*/","").length()>0) { return checkCredentials(requiredRole.replaceAll(".*/",""),user,passwordHash); } else return result; } public MyAuthenticator getAuthenticator() { return authenticator; } public MyAuthenticator getAdminAuthenticator() { return adminAuthenticator; } public MyAuthenticator createAuthenticator(String role) { return new MyAuthenticator(role); } public class MyAuthenticator extends BasicAuthenticator { private final String role; MyAuthenticator(String role) { super("get"); this.role=role; } @Override public boolean checkCredentials(String username, String password) { return UserManager.this.checkCredentials(role, username, password) || UserManager.this.checkCredentials(role, username, Utilities.computeBCryptHash(password.getBytes())); } } }
8,124
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
RequestHandler.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/server/RequestHandler.java
/* * RequestHandler.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.ms.server; import jloda.swing.util.ResourceManager; import jloda.util.CollectionUtils; import jloda.util.StringUtils; import megan.daa.connector.ClassificationBlockDAA; import megan.data.IClassificationBlock; import megan.data.IReadBlock; import megan.ms.Utilities; import megan.ms.client.connector.ReadBlockMS; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * MeganServer request handler for data requests * Daniel Huson, 8.2020 */ public interface RequestHandler { byte[] handle(String context, String[] parameters) throws IOException; static RequestHandler getDefault() { return (c, p) -> ("<html>\n" + "<body>\n" + "<b> Not implemented: " + c + " " + StringUtils.toString(p, ", ") + "</b>\n" + "</body>\n" + "</html>\n").getBytes(); } static RequestHandler getAbout(HttpServerMS server) { return (c, p) -> { checkKnownParameters(p); return server.getAbout().getBytes(); }; } static RequestHandler getHelp(String url) { return (c, p) -> { try { checkKnownParameters(p); try (InputStream ins = ResourceManager.getFileAsStream("ms/help.html")) { if (ins != null) { return StringUtils.toString(ins.readAllBytes()).replaceAll("ServiceURL",url).getBytes(); } } throw new IOException("Resource not found: ms/help.html"); } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } static RequestHandler getVersion() { return (c, p) -> { try { checkKnownParameters(p); return MeganServer.Version.getBytes(); } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } static RequestHandler getListDataset(Database database) { return (c, p) -> { try { checkKnownParameters(p, "readCount","matchCount","metadata"); final boolean readCount = Parameters.getValue(p, "readCount", false); final boolean matchCount = Parameters.getValue(p, "matchCount", false); final boolean includeMetadata = Parameters.getValue(p, "metadata", false); final var list = new ArrayList<>(); for (String fileName : database.getFileNames()) { final StringBuilder buf = new StringBuilder(); buf.append(fileName); if (readCount) buf.append("\t").append(database.getRecord(fileName).getNumberOfReads()); if (matchCount) buf.append("\t").append(database.getRecord(fileName).getNumberOfReads()); if (includeMetadata) buf.append("\t").append(database.getMetadata(fileName).replaceAll("\t",",")); list.add(buf.toString()); } return StringUtils.toString(list, "\n").getBytes(); } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } static RequestHandler getNumberOfReads(Database database) { return (c, p) -> { try { checkKnownParameters(p, "file"); checkRequiredParameters(p, "file"); final ArrayList<Long> list = new ArrayList<>(); for (String fileName : Parameters.getValues(p, "file")) { list.add(database.getRecord(fileName).getNumberOfReads()); } return StringUtils.toString(list, " ").getBytes(); } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } static RequestHandler getNumberOfMatches(Database database) { return (c, p) -> { try { checkKnownParameters(p, "file"); checkRequiredParameters(p, "file"); final ArrayList<Long> list = new ArrayList<>(); for (String fileName : Parameters.getValues(p, "file")) { list.add(database.getRecord(fileName).getNumberOfMatches()); } return StringUtils.toString(list, " ").getBytes(); } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } static RequestHandler getClassifications(Database database) { return (c, p) -> { try { checkKnownParameters(p, "file"); checkRequiredParameters(p, "file"); final ArrayList<String> list = new ArrayList<>(); for (String fileName : Parameters.getValues(p, "file")) { list.add(StringUtils.toString(database.getClassifications(fileName), "\n") + "\n"); } return StringUtils.toString(list, "\n").getBytes(); } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } static RequestHandler getAuxiliaryData(Database database) { return (c, p) -> { try { checkKnownParameters(p, "file", "binary"); checkRequiredParameters(p, "file"); final boolean binary = Parameters.getValue(p, "binary", false); final String fileName = Parameters.getValue(p, "file"); final ArrayList<String> list = new ArrayList<>(); Database.FileRecord fileRecord = database.getRecord(fileName); if (fileRecord != null && fileRecord.getAuxiliaryData() != null) { if (binary) { return Utilities.writeAuxiliaryDataToBytes(fileRecord.getAuxiliaryData()); } else { for (String key : fileRecord.getAuxiliaryData().keySet()) { list.add(key + ":\n" + StringUtils.toString(fileRecord.getAuxiliaryData().get(key))); } } } return StringUtils.toString(list, "\n").getBytes(); } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } static RequestHandler getDescription(Database database) { return (c, p) -> { checkKnownParameters(p,"file"); final String fileName = Parameters.getValue(p, "file"); var description=database.getFileDescription(fileName); return description!=null?description.getBytes():new byte[0]; }; } static RequestHandler getFileUid(Database database) { return (c, p) -> { try { checkKnownParameters(p, "file"); checkRequiredParameters(p, "file"); final ArrayList<String> list = new ArrayList<>(); for (String fileName : Parameters.getValues(p, "file")) { final Integer fileId = database.getFileName2Id().get(fileName); list.add(fileId != null ? String.valueOf(fileId) : "File not found: " + fileName); } return StringUtils.toString(list, "\n").getBytes(); } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } static RequestHandler getClassificationBlock(Database database) { return (c, p) -> { try { checkKnownParameters(p, "file", "classification", "binary"); checkRequiredParameters(p, "file", "classification"); final String fileName = Parameters.getValue(p, "file"); final String classification = Parameters.getValue(p, "classification"); final boolean binary = Parameters.getValue(p, "binary", false); IClassificationBlock classificationBlock = database.getClassificationBlock(fileName, classification); if(classificationBlock==null) classificationBlock=new ClassificationBlockDAA(classification); if (binary) { return Utilities.writeClassificationBlockToBytes(classificationBlock); } else { final ArrayList<String> list = new ArrayList<>(classificationBlock.getKeySet().size()); list.add(classification); list.add(String.valueOf(classificationBlock.getKeySet().size())); for (Integer id : classificationBlock.getKeySet()) { list.add(id + "\t" + classificationBlock.getWeightedSum(id) + "\t" + classificationBlock.getSum(id)); } return StringUtils.toString(list, "\n").getBytes(); } } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } static RequestHandler getClassSize(Database database) { return (c, p) -> { try { checkKnownParameters(p, "file", "classification", "classId", "sum"); checkRequiredParameters(p, "file", "classification", "classId"); final String fileName = Parameters.getValue(p, "file"); final String classification = Parameters.getValue(p, "classification"); final List<Integer> classIds = Parameters.getIntValues(p, "classId"); final boolean wantSum = Parameters.getValue(p, "sum", false); final IClassificationBlock classificationBlock = database.getClassificationBlock(fileName, classification); final ArrayList<String> list = new ArrayList<>(classificationBlock.getKeySet().size()); if (wantSum) { int sum = 0; for (Integer id : classIds) { sum += classificationBlock.getSum(id); } list.add(String.valueOf(sum)); } else { for (Integer id : classIds) { list.add(id + "\t" + classificationBlock.getSum(id)); } } return StringUtils.toString(list, "\n").getBytes(); } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } static RequestHandler getRead(Database database) { return (c, p) -> { try { checkKnownParameters(p, "file", "readId", "header", "sequence", "matches", "binary"); checkRequiredParameters(p, "file", "readId"); final String fileName = Parameters.getValue(p, "file"); final ReadsOutputFormat format = new ReadsOutputFormat( false, Parameters.getValue(p, "header", true), Parameters.getValue(p, "sequence", true), Parameters.getValue(p, "matches", true)); final long readId = Parameters.getValue(p, "readId", -1L); if(readId==-1) throw new IOException("readId: expected internally assigned long, got: "+Parameters.getValue(p,"readId")); final boolean binary = Parameters.getValue(p, "binary", true); if (binary) { final String[] cNames = database.getClassifications(fileName).toArray(new String[0]); return ReadBlockMS.writeToBytes(cNames, database.getRead(fileName, readId, format.isMatches()), format.isSequences(),format.isMatches()); } else { return ReadBlockMS.writeToString(database.getRead(fileName, readId, format.isMatches()), format.isReadIds(), format.isHeaders(), format.isSequences(), format.isMatches()).getBytes(); } } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } static RequestHandler getReads(Database database,int defaultReadsPerPage) { return (c, p) -> { try { checkKnownParameters(p, "pageSize", "file", "readIds", "headers", "sequences", "matches", "binary"); checkRequiredParameters(p, "file"); var pageSize = Parameters.getValue(p, "pageSize", defaultReadsPerPage); final var fileName = Parameters.getValue(p, "file"); if(database.getRecord(fileName)==null) return reportError(c, p, "File not found: "+fileName); if (pageSize == 100) { // older versions of MEGAN always request 100 reads per page, reduce to 1 for long reads // set page size depending on whether long reads or not pageSize = database.getRecord(fileName).isLongReads() ? 1 : 100; } final ReadsOutputFormat format = new ReadsOutputFormat( Parameters.getValue(p, "readIds", true), Parameters.getValue(p, "headers", true), Parameters.getValue(p, "sequences", true), Parameters.getValue(p, "matches", true)); final boolean binary = Parameters.getValue(p, "binary", true); final ReadIteratorPagination.Page page = database.getReads(fileName, format, pageSize); return getReads(c, binary, page); } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } static RequestHandler getReadsForMultipleClassIdsIterator(Database database,int defaultReadsPerPage) { return (c, p) -> { try { checkKnownParameters(p, "file", "classification", "classId", "readIds", "headers", "sequences", "matches", "binary", "pageSize"); checkRequiredParameters(p, "file", "classification", "classId"); final int pageSize = Parameters.getValue(p, "pageSize", defaultReadsPerPage); final String fileName = Parameters.getValue(p, "file"); final String classification = Parameters.getValue(p, "classification"); final List<Integer> classIds = Parameters.getIntValues(p, "classId"); final ReadsOutputFormat format = new ReadsOutputFormat( Parameters.getValue(p, "readIds", true), Parameters.getValue(p, "headers", true), Parameters.getValue(p, "sequences", true), Parameters.getValue(p, "matches", true)); final boolean binary = Parameters.getValue(p, "binary", true); final ReadIteratorPagination.Page page = database.getReadsForMultipleClassIds(fileName, classification, classIds, format, pageSize); return getReads(c, binary, page); } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } static RequestHandler getNextPage(Database database) { return (c, p) -> { try { checkKnownParameters(p, "pageId", "binary", "pageSize"); checkRequiredParameters(p, "pageId"); final int pageId = Parameters.getValue(p, "pageId", 0); final int pageSize = Parameters.getValue(p, "pageSize", -1); // -1: use what was initially set final boolean binary = Parameters.getValue(p, "binary", false); final ReadIteratorPagination.Page page = database.getNextPage(pageId, pageSize); return getReads(c, binary, page); } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } private static byte[] getReads(String c, boolean binary, ReadIteratorPagination.Page page) throws IOException { if (page != null) { final long nextPageId = page.getNextPage(); if (binary) { final ArrayList<byte[]> list = new ArrayList<>(); list.add(Utilities.getBytesLittleEndian(page.getReads().size())); for (IReadBlock readBlock : page.getReads()) { final byte[] bytes = ReadBlockMS.writeToBytes(page.getCNames(), readBlock, page.getFormat().isSequences(),page.getFormat().isMatches()); list.add(Utilities.getBytesLittleEndian(bytes.length)); list.add(bytes); } list.add(Utilities.getBytesLittleEndian(page.getNextPage())); return StringUtils.concatenate(list); } else { final ArrayList<String> list = new ArrayList<>(); for (IReadBlock readBlock : page.getReads()) { addReadToList(readBlock, page.getFormat(), list); } if (nextPageId != 0) list.add("Next pageId=" + nextPageId); else list.add("done"); return StringUtils.toString(list, "\n").getBytes(); } } else return reportError(c, new String[0], "failed"); } private static void addReadToList(IReadBlock readBlock, ReadsOutputFormat format, ArrayList<String> list) { if (format.isReadIds()) list.add(String.valueOf(readBlock.getUId())); if (format.isHeaders()) list.add(">" + readBlock.getReadHeader()); if (format.isSequences()) list.add(readBlock.getReadSequence()); if (format.isMatches()) { for (int i = 0; i < readBlock.getNumberOfAvailableMatchBlocks(); i++) { list.add(readBlock.getMatchBlock(i).getText()); } } } static byte[] reportError(String content, String[] parameters, String message) { final String error = (Utilities.SERVER_ERROR + content + "?" + StringUtils.toString(parameters, "&") + ": " + message); System.err.println(error); return error.getBytes(); } static void checkKnownParameters(String[] parameters, String... known) throws IOException { final List<String> parameterNames = Arrays.stream(parameters).sequential().map(parameter -> { if (parameter.contains("=")) return parameter.substring(0, parameter.indexOf("=")); else return parameter; }).toList(); for (String name : parameterNames) { if (!CollectionUtils.contains(known, name)) throw new IOException("Unknown parameter: '" + name + "'"); } } static void checkRequiredParameters(String[] parameters, String... required) throws IOException { final List<String> parameterNames = Arrays.stream(parameters).sequential().map(parameter -> { if (parameter.contains("=")) return parameter.substring(0, parameter.indexOf("=")); else return parameter; }).toList(); for (String name : required) { if (!parameterNames.contains(name)) throw new IOException("Missing parameter: '" + name + "'"); } } }
20,047
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ReadIteratorPagination.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/server/ReadIteratorPagination.java
/* * ReadIteratorPagination.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.ms.server; import megan.data.IReadBlock; import megan.data.IReadBlockIterator; import java.io.IOException; import java.util.ArrayList; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicLong; /** * this implements pagination of read iterators * Daniel Huson, 8.2020 */ public class ReadIteratorPagination { private static int timeoutSeconds = 10000; private static final AtomicLong mostRecentPageId = new AtomicLong(0); private final static Map<Long, PagingJob> pageId2Job = new TreeMap<>(); public static Long createPagination(IReadBlockIterator iterator, String[] cNames, ReadsOutputFormat format, int pageSize) { final long pageId = mostRecentPageId.addAndGet(1); final PagingJob pagingJob = new PagingJob(pageId, cNames, format, iterator, pageSize); synchronized (pageId2Job) { pageId2Job.put(pageId, pagingJob); } return pageId; } public static Page getNextPage(long pageId, int pageSize) { final PagingJob pagingJob = pageId2Job.get(pageId); if (pagingJob != null && pagingJob.hasNext()) { ArrayList<IReadBlock> data = pagingJob.nextPage(pageSize > 0 ? pageSize : pagingJob.getPageSize()); final long newPageId; if (pagingJob.hasNext()) { newPageId = mostRecentPageId.addAndGet(1); synchronized (pageId2Job) { pageId2Job.remove(pageId); pageId2Job.put(newPageId, pagingJob); } } else newPageId = 0; // no further pages return new Page(data, pagingJob.getCNames(), pagingJob.getFormat(), newPageId); } else return Page.createEmptyPage(); } private static void purgeStale() { synchronized (pageId2Job) { final long time = System.currentTimeMillis(); final ArrayList<Long> toDelete = new ArrayList<>(); for (PagingJob job : pageId2Job.values()) { if (!job.iterator.hasNext() || time - job.getLastAccess() > 1000L * timeoutSeconds) { try { job.iterator.close(); } catch (IOException ignored) { } toDelete.add(job.getJobId()); } } toDelete.forEach(pageId2Job.keySet()::remove); } } public static int getTimeoutSeconds() { return timeoutSeconds; } public static void setTimeoutSeconds(int timeoutSeconds) { ReadIteratorPagination.timeoutSeconds = timeoutSeconds; } private static class PagingJob { private final long jobId; private final String[] cNames; private final ReadsOutputFormat format; private final IReadBlockIterator iterator; private long lastAccess; private final int pageSize; public PagingJob(long jobId, String[] cNames, ReadsOutputFormat format, IReadBlockIterator iterator, int pageSize) { this.jobId = jobId; this.cNames = cNames; this.format = format; this.iterator = iterator; this.lastAccess = System.currentTimeMillis(); this.pageSize = pageSize; } public long getJobId() { return jobId; } public String[] getCNames() { return cNames; } public ReadsOutputFormat getFormat() { return format; } public IReadBlockIterator getIterator() { return iterator; } public long getLastAccess() { return lastAccess; } public void setLastAccess(long lastAccess) { this.lastAccess = lastAccess; } public boolean hasNext() { return iterator.hasNext(); } public int getPageSize() { return pageSize; } public ArrayList<IReadBlock> nextPage(int pageSize) { setLastAccess(System.currentTimeMillis()); final ArrayList<IReadBlock> list = new ArrayList<>(pageSize); while (iterator.hasNext() && list.size() < pageSize) { list.add(iterator.next()); } setLastAccess(System.currentTimeMillis()); purgeStale(); return list; } } public static class Page { private final ArrayList<IReadBlock> reads; private final String[] cNames; private final ReadsOutputFormat format; private final long nextPage; public Page(ArrayList<IReadBlock> reads, String[] cNames, ReadsOutputFormat format, long nextPage) { this.reads = reads; this.cNames = cNames; this.format = format; this.nextPage = nextPage; } public static Page createEmptyPage() { return new Page(new ArrayList<>(),new String[0],new ReadsOutputFormat(false,false,false,false),-1); } public ArrayList<IReadBlock> getReads() { return reads; } public String[] getCNames() { return cNames; } public ReadsOutputFormat getFormat() { return format; } public long getNextPage() { return nextPage; } } }
6,201
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Database.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/server/Database.java
/* * Database.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.ms.server; import jloda.util.*; import jloda.util.progress.ProgressPercentage; import megan.core.Document; import megan.core.MeganFile; import megan.core.SampleAttributeTable; import megan.daa.connector.ClassificationBlockDAA; import megan.data.*; import java.io.*; import java.nio.file.Files; import java.util.*; /** * Megan Server database * Daniel Huson, 8.2020 */ public class Database { private final File rootDirectory; private final boolean recursive; private final String[] fileExtensions; private final Map<String, Integer> fileName2Id = new TreeMap<>(); private final Map<Integer, FileRecord> id2Record = new HashMap<>(); private final Map<String,File> file2DescriptionFile =new HashMap<>(); private long lastRebuild = 0; /** * constructor * */ public Database(File rootDirectory, String[] fileExtensions, boolean recursive) throws IOException { if (!rootDirectory.isDirectory()) throw new IOException("Not a directory: " + rootDirectory); if (!rootDirectory.canRead()) throw new IOException("Not readable: " + rootDirectory); this.rootDirectory = rootDirectory; this.fileExtensions =fileExtensions; this.recursive = recursive; } /** * rebuild the database * * @return message */ public String rebuild() { fileName2Id.clear(); id2Record.clear(); file2DescriptionFile.clear(); final var files = FileUtils.getAllFilesInDirectory(rootDirectory, recursive, fileExtensions); final var fileName2IdRebuilt = new HashMap<String, Integer>(); final var id2record = new HashMap<Integer, FileRecord>(); try (ProgressPercentage progress = new ProgressPercentage("Rebuilding database:", files.size())) { System.err.println(Basic.getDateString("yyyy-MM-dd hh:mm:ss")); for(var file:files) { try { if (FileUtils.fileExistsAndIsNonEmpty(FileUtils.replaceFileSuffix(file, ".txt"))) { file2DescriptionFile.put(FileUtils.getRelativeFile(file, rootDirectory).getPath(), FileUtils.replaceFileSuffix(file, ".txt")); } final var document = new Document(); final var meganFile = document.getMeganFile(); meganFile.setFileFromExistingFile(file.getPath(), true); if (meganFile.isMeganSummaryFile()) { try (var r = new BufferedReader(new InputStreamReader(FileUtils.getInputStreamPossiblyZIPorGZIP(file.getPath())))) { document.loadMeganSummary(r); final var numberOfReads = document.getNumberOfReads(); final var fileId = fileName2IdRebuilt.size() + 1; final String relativePath = FileUtils.getRelativeFile(file, rootDirectory).getPath(); fileName2IdRebuilt.put(relativePath, fileId); try (var w = new StringWriter()) { document.getDataTable().write(w); document.getSampleAttributeTable().write(w, false, true); final var data = new HashMap<String, byte[]>(); data.put("FILE_CONTENT", w.toString().getBytes()); id2record.put(fileId, new FileRecord(fileId, file, document.getClassificationNames(), data, numberOfReads, 0, document.isLongReads())); } } } else if (meganFile.hasDataConnector()) { final var connector = meganFile.getConnector(); document.loadMeganFile(); final var numberOfReads = connector.getNumberOfReads(); if (numberOfReads > 0) { final var numberOfMatches = connector.getNumberOfMatches(); final var fileId = fileName2IdRebuilt.size() + 1; final var relativePath = FileUtils.getRelativeFile(file, rootDirectory).getPath(); fileName2IdRebuilt.put(relativePath, fileId); id2record.put(fileId, new FileRecord(fileId, file, Arrays.asList(connector.getAllClassificationNames()), connector.getAuxiliaryData(), numberOfReads, numberOfMatches, document.isLongReads())); } } progress.incrementProgress(); } catch (IOException ignored) { } } } for (var aboutFile : FileUtils.getAllFilesInDirectory(rootDirectory, recursive, "About.txt")) { var relativePath = FileUtils.getRelativeFile(aboutFile.getParentFile(), rootDirectory).getPath(); file2DescriptionFile.put(relativePath, aboutFile); } this.fileName2Id.putAll(fileName2IdRebuilt); this.id2Record.putAll(id2record); System.err.printf("Files: %,d%n", id2record.size()); lastRebuild = System.currentTimeMillis(); return "Rebuild '"+rootDirectory.getName()+"' completed at " + (new Date(getLastRebuild()))+"\n"; } public FileRecord getRecord(String fileName) { final Integer fileId; if (NumberUtils.isInteger(fileName)) fileId = NumberUtils.parseInt(fileName); else fileId = fileName2Id.get(fileName); if (fileId != null) return id2Record.get(fileId); else return null; } public String getMetadata(String fileName) { final FileRecord fileRecord = getRecord(fileName); if (fileRecord != null && fileRecord.getAuxiliaryData() != null && fileRecord.getAuxiliaryData().containsKey(SampleAttributeTable.SAMPLE_ATTRIBUTES)) { return StringUtils.toString(fileRecord.getAuxiliaryData().get(SampleAttributeTable.SAMPLE_ATTRIBUTES)); } else return ""; } public String getInfo() { return String.format("directory %s, %,d files", rootDirectory, fileName2Id.size()); } public File getRootDirectory() { return rootDirectory; } public String[] getFileExtensions() { return fileExtensions; } public Map<String, Integer> getFileName2Id() { return fileName2Id; } public Collection<String> getFileNames() { return fileName2Id.keySet(); } public Map<Integer, FileRecord> getId2Record() { return id2Record; } public List<String> getClassifications(String fileName) { return getRecord(fileName).getClassifications(); } public IClassificationBlock getClassificationBlock(String fileName, String classification) throws IOException { final Document document = new Document(); final File file = getRecord(fileName).getFile(); document.getMeganFile().setFileFromExistingFile(file.getPath(), true); if (document.getMeganFile().hasDataConnector()) { final IConnector connector = document.getMeganFile().getConnector(); return connector.getClassificationBlock(classification); } else { document.loadMeganFile(); final ClassificationBlockDAA classificationBlock = new ClassificationBlockDAA(classification); if (document.getClassificationNames().contains(classification)) { final Map<Integer, float[]> class2count = document.getDataTable().getClass2Counts(classification); for (var classId : class2count.keySet()) { classificationBlock.setSum(classId, Math.round(CollectionUtils.getSum(class2count.get(classId)))); } } return classificationBlock; } } public IReadBlock getRead(String fileName, long readUid, boolean includeMatches) throws IOException { try (IReadBlockGetter getter = getConnector(fileName).getReadBlockGetter(0, 10, true, includeMatches)) { return getter.getReadBlock(readUid); } } public ReadIteratorPagination.Page getReads(String fileName, ReadsOutputFormat format, int pageSize) throws IOException { final IReadBlockIterator iterator = getConnector(fileName).getAllReadsIterator(0, 10, format.isSequences(), format.isMatches()); long pageId = ReadIteratorPagination.createPagination(iterator, getConnector(fileName).getAllClassificationNames(), format, pageSize); return getNextPage(pageId, -1); } public ReadIteratorPagination.Page getReadsForMultipleClassIds(String fileName, String classification, Collection<Integer> classIds, ReadsOutputFormat format, int pageSize) throws IOException { final IReadBlockIterator iterator = getConnector(fileName).getReadsIteratorForListOfClassIds(classification, classIds, 0, 10, format.isSequences(), format.isMatches()); long pageId = ReadIteratorPagination.createPagination(iterator, getConnector(fileName).getAllClassificationNames(), format, pageSize); return getNextPage(pageId, -1); } public ReadIteratorPagination.Page getNextPage(long pageId, int pageSize) { return ReadIteratorPagination.getNextPage(pageId, pageSize); } private IConnector getConnector(String fileName) throws IOException { final MeganFile meganFile = new MeganFile(); final File file = getRecord(fileName).getFile(); meganFile.setFileFromExistingFile(file.getPath(), true); return meganFile.getConnector(); } public long getLastRebuild() { return lastRebuild; } public String getFileDescription(String fileName) throws IOException { var file= file2DescriptionFile.get(fileName); if (FileUtils.fileExistsAndIsNonEmpty(file)) return Files.readString(file.toPath()); else return null; } public static class FileRecord { private final long fileId; private final File file; private final List<String> classifications; private final Map<String, byte[]> auxiliaryData; private final long numberOfReads; private final long numberOfMatches; private final boolean longReads; public FileRecord(long fileId, File file, List<String> classifications, Map<String, byte[]> auxiliaryData, long numberOfReads, long numberOfMatches, boolean longReads) { this.fileId = fileId; this.file = file; this.classifications = new ArrayList<>(classifications); this.auxiliaryData = auxiliaryData; this.numberOfReads = numberOfReads; this.numberOfMatches = numberOfMatches; this.longReads = longReads; } public long getFileId() { return fileId; } public File getFile() { return file; } public List<String> getClassifications() { return classifications; } public Map<String, byte[]> getAuxiliaryData() { return auxiliaryData; } public long getNumberOfReads() { return numberOfReads; } public long getNumberOfMatches() { return numberOfMatches; } public boolean isLongReads() { return longReads; } } }
11,502
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
RequestHandlerAdditional.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/server/RequestHandlerAdditional.java
/* * RequestHandlerAdditional.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.ms.server; import com.sun.net.httpserver.HttpExchange; import jloda.util.FileUtils; import jloda.util.StringUtils; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; /** * addition request handlers * Daniel Huson, 10.2020 */ public class RequestHandlerAdditional { private final static String DOWNLOAD_FILE_PREFIX = "DOWNLOAD-FILE:"; static RequestHandler getDownloadPage(Database database) { return (c, p) -> { try { RequestHandler.checkKnownParameters(p, "file"); RequestHandler.checkRequiredParameters(p, "file"); final var name = Parameters.getValue(p, "file"); final var file = database.getRecord(name).getFile(); return (DOWNLOAD_FILE_PREFIX + file).getBytes(); } catch (IOException ex) { return RequestHandler.reportError(c, p, ex.getMessage()); } }; } public static HttpHandlerMS getDownloadPageHandler(Database database) { final RequestHandler requestHandler = getDownloadPage(database); return new HttpHandlerMS(requestHandler) { public void respond(HttpExchange httpExchange, String[] parameters) throws IOException { final var bytes = requestHandler.handle(httpExchange.getHttpContext().getPath(), parameters); if (!StringUtils.startsWith(bytes, DOWNLOAD_FILE_PREFIX)) throw new IOException("invalid"); final var fileName = StringUtils.getTextAfter(DOWNLOAD_FILE_PREFIX, StringUtils.toString(bytes)); if (fileName == null) throw new IOException("No file name"); final var file = new File(fileName); if (!file.exists()) throw new IOException("No such file: " + file); httpExchange.getResponseHeaders().set("Content-Type", "application/octet-stream"); var headerKey = "Content-Disposition"; var headerValue = String.format("attachment; filename=\"%s\"", FileUtils.getFileNameWithoutPath(fileName)); httpExchange.getResponseHeaders().set(headerKey, headerValue); httpExchange.sendResponseHeaders(200, file.length()); try (var outs = httpExchange.getResponseBody(); var ins = new BufferedInputStream(new FileInputStream(fileName))) { var buf = new byte[8192]; int length; while ((length = ins.read(buf)) > 0) { outs.write(buf, 0, length); } } } }; } }
3,518
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
HttpServerMS.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/server/HttpServerMS.java
/* * HttpServerMS.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.ms.server; import com.sun.net.httpserver.BasicAuthenticator; import com.sun.net.httpserver.HttpContext; import com.sun.net.httpserver.HttpServer; import jloda.fx.util.ProgramExecutorService; import jloda.swing.util.ProgramProperties; import jloda.util.Basic; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Date; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; /** * HTTP server for megan server * Daniel Huson, 8.2020 */ public class HttpServerMS { private final InetAddress address; private final HttpServer httpServer; private final Map<String,Database> path2database =new TreeMap<>(); private final UserManager userManager; private final String defaultPath; private long started = 0L; private final int readsPerPage; private final ArrayList<HttpContext> contexts=new ArrayList<>(); public HttpServerMS(String path, int port, UserManager userManager, int backlog, int readsPerPage, int pageTimeout) throws IOException { if(!path.startsWith("/")) path="/"+path; this.defaultPath =path; this.userManager = userManager; this.readsPerPage = readsPerPage; ReadIteratorPagination.setTimeoutSeconds(pageTimeout); address = InetAddress.getLocalHost(); httpServer = HttpServer.create(new InetSocketAddress((InetAddress) null, port), backlog); final var adminAuthenticator = userManager.createAuthenticator(UserManager.ADMIN); // admin commands: createContext(path + "/admin/update", new HttpHandlerMS(RequestHandlerAdmin.update(path2database.values())),adminAuthenticator); createContext(path + "/admin/listUsers", new HttpHandlerMS(RequestHandlerAdmin.listUsers(userManager)),adminAuthenticator); createContext(path + "/admin/addUser", new HttpHandlerMS(RequestHandlerAdmin.addUser(userManager)),adminAuthenticator); createContext(path + "/admin/removeUser", new HttpHandlerMS(RequestHandlerAdmin.removeUser(userManager)),adminAuthenticator); createContext(path + "/admin/addRole", new HttpHandlerMS(RequestHandlerAdmin.addRole(userManager)),adminAuthenticator); createContext(path + "/admin/removeRole", new HttpHandlerMS(RequestHandlerAdmin.removeRole(userManager)),adminAuthenticator); createContext(path + "/admin/getLog", new HttpHandlerMS(RequestHandlerAdmin.getLog()),adminAuthenticator); createContext(path + "/admin/clearLog", new HttpHandlerMS(RequestHandlerAdmin.clearLog()),adminAuthenticator); createContext(path + "/admin/shutdown", new HttpHandlerMS(RequestHandlerAdmin.shutdown()),adminAuthenticator); final ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(ProgramExecutorService.getNumberOfCoresToUse()); httpServer.setExecutor(threadPoolExecutor); } public void addDatabase(String path, Database database, String role) { if(!path.startsWith("/")) path="/"+path; path2database.put(path,database); // general info: var url="http://" + getAddress().getHostAddress() + ":" + getSocketAddress().getPort() +path; createContext(path + "/help", new HttpHandlerMS(RequestHandler.getHelp(url)),null); // .setAuthenticator(authenticator); final var authenticator = userManager.createAuthenticator(role); // general info: createContext(path + "/version", new HttpHandlerMS(RequestHandler.getVersion()),authenticator); createContext(path + "/about", new HttpHandlerMS(RequestHandler.getAbout(this)),authenticator); createContext(path + "/isReadOnly", new HttpHandlerMS( (c, p) -> "true".getBytes()),authenticator); createContext(path + "/list", new HttpHandlerMS(RequestHandler.getListDataset(database)),authenticator); // file info: createContext(path + "/getFileUid", new HttpHandlerMS(RequestHandler.getFileUid(database)),authenticator); createContext(path + "/getAuxiliary", new HttpHandlerMS(RequestHandler.getAuxiliaryData(database)),authenticator); createContext(path + "/getNumberOfReads", new HttpHandlerMS(RequestHandler.getNumberOfReads(database)),authenticator); createContext(path + "/getNumberOfMatches", new HttpHandlerMS(RequestHandler.getNumberOfMatches(database)),authenticator); // for backward compatibility: createContext(path + "/numberOfReads", new HttpHandlerMS(RequestHandler.getNumberOfReads(database)),authenticator); createContext(path + "/numberOfMatches", new HttpHandlerMS(RequestHandler.getNumberOfMatches(database)),authenticator); createContext(path + "/getClassificationNames", new HttpHandlerMS(RequestHandler.getClassifications(database)),authenticator); // access reads and matches createContext(path + "/getRead", new HttpHandlerMS(RequestHandler.getRead(database)),authenticator); createContext(path + "/getReads", new HttpHandlerMS(RequestHandler.getReads(database, getReadsPerPage())),authenticator); createContext(path + "/getReadsForClass", new HttpHandlerMS(RequestHandler.getReadsForMultipleClassIdsIterator(database, getReadsPerPage())),authenticator); createContext(path + "/getFindAllReadsIterator", new HttpHandlerMS(),authenticator); createContext(path + "/getNext", new HttpHandlerMS(RequestHandler.getNextPage(database)),authenticator); // access classifications createContext(path + "/getClassificationBlock", new HttpHandlerMS(RequestHandler.getClassificationBlock(database)),authenticator); createContext(path + "/getClassSize", new HttpHandlerMS(RequestHandler.getClassSize(database)),authenticator); // download a file createContext(path + "/download", RequestHandlerAdditional.getDownloadPageHandler(database),authenticator); createContext(path + "/getDescription", new HttpHandlerMS(RequestHandler.getDescription(database)),authenticator); } private void createContext(String path, HttpHandlerMS handler, BasicAuthenticator authenticator) { final HttpContext context=httpServer.createContext(path,handler); if(authenticator!=null) context.setAuthenticator(authenticator); contexts.add(context); } public ArrayList<HttpContext> getContexts() { return contexts; } public void rebuildDatabases() { try { userManager.readFile(); } catch (IOException e) { Basic.caught(e); } for(var database:path2database.values()) database.rebuild(); } public long getStarted() { return started; } public void start() { started = System.currentTimeMillis(); httpServer.start(); } public void stop() { httpServer.stop(1); } public InetAddress getAddress() { return address; } public InetSocketAddress getSocketAddress() { return httpServer.getAddress(); } public HttpServer getHttpServer() { return httpServer; } public UserManager getUserManager() { return userManager; } public Map<String,Database> getPath2Database() { return path2database; } public int getReadsPerPage() { return readsPerPage; } public String getAbout() { return MeganServer.Version + "\n" + "Version: " + ProgramProperties.getProgramVersion() + "\n" + "Hostname: " + getAddress().getHostName() + "\n" + "IP address: " + getAddress().getHostAddress() + "\n" + "Port: " + getSocketAddress().getPort() + "\n" + "Known users: " + userManager.size() + "\n" + "Total requests: " + (HttpHandlerMS.getNumberOfRequests().get() + 1L) + "\n" + "Server started: " + (new Date(getStarted())) + "\n"; } }
8,811
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MeganServer.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/server/MeganServer.java
/* * MeganServer.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.ms.server; import jloda.fx.util.ProgramExecutorService; import jloda.swing.util.ArgsOptions; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.util.Basic; import jloda.util.PeakMemoryUsageMonitor; import jloda.util.UsageException; import megan.daa.connector.DAAConnector; import megan.rma6.RMA6Connector; import java.io.File; /** * Megan Server program * Daniel Huson, 8.2020 */ public class MeganServer { public static final String Version = "MeganServer0.1"; /** * * main */ public static void main(String[] args) { try { Basic.startCollectionStdErr(); ResourceManager.insertResourceRoot(megan.resources.Resources.class); ProgramProperties.setProgramName("MeganServer"); ProgramProperties.setProgramVersion(megan.main.Version.SHORT_DESCRIPTION); PeakMemoryUsageMonitor.start(); (new MeganServer()).run(args); System.exit(0); } catch (Exception ex) { Basic.caught(ex); System.exit(1); } } /** * run */ private void run(String[] args) throws Exception { // we keep references to read blocks, so must not reuse readblocks: RMA6Connector.reuseReadBlockInGetter=false; DAAConnector.reuseReadBlockInGetter=false; final ArgsOptions options = new ArgsOptions(args, this, "Serves MEGAN files over the web via HTTP"); options.setVersion(ProgramProperties.getProgramVersion()); options.setLicense("Copyright (C) 2024. This program comes with ABSOLUTELY NO WARRANTY."); options.setAuthors("Daniel H. Huson"); options.comment("Input"); final String inputDirectory = options.getOptionMandatory("-i", "input", "Input directory", ""); final boolean recursive = options.getOption("-r", "recurse", "Recursively visit all input subdirectories", true); final String[] inputFileExtensions = options.getOption("-x", "extensions", "Input file extensions", new String[]{".daa", ".rma", ".rma6", ".megan", ".megan.gz"}); options.comment("Server"); final String endpoint = options.getOption("-e", "endpoint", "Endpoint name", "megan6server"); final int port = options.getOption("-p", "port", "Server port", 8001); final boolean allowGuestLogin = options.getOption("-g", "allowGuest", "Allow guest login (name: guest, pwd: guest)", false); options.comment(ArgsOptions.OTHER); String defaultPreferenceFile; if (ProgramProperties.isMacOS()) defaultPreferenceFile = System.getProperty("user.home") + "/Library/Preferences/MeganServerUsers.def"; else defaultPreferenceFile = System.getProperty("user.home") + File.separator + ".MeganServerUsers.def"; final String usersFile = options.getOption("-u", "usersFile", "File containing list of users", defaultPreferenceFile); final int backlog = options.getOption("-bl", "backlog", "Set the socket backlog", 100); final int pageTimeout = options.getOption("-pt", "pageTimeout", "Number of seconds to keep pending pages alive", 10000); final int readsPerPage=options.getOption("-rpp","readsPerPage","Number of reads per page to serve",100); ProgramExecutorService.setNumberOfCoresToUse(options.getOption("-t", "threads", "Number of threads", 8)); Basic.setDebugMode(options.getOption("-d", "debug", "Debug mode", false)); options.done(); if(endpoint.length()==0) throw new UsageException("--endpoint: must have positive length"); final UserManager userManager = new UserManager(usersFile); if (!userManager.hasAdmin()) userManager.askForAdminPassword(); if (allowGuestLogin) { userManager.addUser("guest", "guest", true); System.err.println("Guests can login with name: guest and password: guest"); } final HttpServerMS server = new HttpServerMS(endpoint, port,userManager, backlog, readsPerPage,pageTimeout); final Database database = new Database(new File(inputDirectory), inputFileExtensions, recursive); server.addDatabase(endpoint,database,null); Runtime.getRuntime().addShutdownHook(new Thread(() -> { System.err.println("Stopping http server..."); System.err.println(server.getAbout()); server.stop(); System.err.println("Total time: " + PeakMemoryUsageMonitor.getSecondsSinceStartString()); System.err.println("Peak memory: " + PeakMemoryUsageMonitor.getPeakUsageString()); })); System.err.println("Starting http server..."); server.start(); System.err.println(server.getAbout()); System.err.println("Server address:"); System.err.println("http://" + server.getAddress().getHostAddress() + ":" + server.getSocketAddress().getPort() + "/"+endpoint); System.err.println("http://" + server.getAddress().getHostName() + ":" + server.getSocketAddress().getPort() +"/"+ endpoint); System.err.println("Help: http://" + server.getAddress().getHostAddress() + ":"+server.getSocketAddress().getPort() + endpoint + "/help"); System.err.println(); server.rebuildDatabases(); Thread.sleep(Long.MAX_VALUE); } }
6,196
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
RequestHandlerAdmin.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/ms/server/RequestHandlerAdmin.java
/* * RequestHandlerAdmin.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.ms.server; import jloda.util.Basic; import jloda.util.StringUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.atomic.AtomicBoolean; import static megan.ms.server.RequestHandler.*; /** * handles admin requests * Daniel Huson, 10.2020 */ public class RequestHandlerAdmin { public static final AtomicBoolean inUpdate = new AtomicBoolean(false); static RequestHandler listUsers(UserManager userManager) { return (c, p) -> (StringUtils.toString(userManager.listAllUsers(), "\n")).getBytes(); } static RequestHandler addUser(UserManager userManager) { return (c, p) -> { if (inUpdate.get()) return reportError(c, p, "Updating database"); try { checkKnownParameters(p, "name", "password", "role", "isAdmin", "replace"); checkRequiredParameters(p, "name", "password"); final String user = Parameters.getValue(p, "name"); final String password = Parameters.getValue(p, "password"); final boolean isAdmin = Parameters.getValue(p, "isAdmin", false); final String role = isAdmin ? "admin" : Parameters.getValue(p, "role"); final boolean allowReplace = Parameters.getValue(p, "replace", false); userManager.addUser(user, password, allowReplace, role); return ("User '" + user + "' added").getBytes(); } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } static RequestHandler addRole(UserManager userManager) { return (c, p) -> { if (inUpdate.get()) return reportError(c, p, "Updating database"); try { checkKnownParameters(p, "user", "role"); checkRequiredParameters(p, "user", "role"); final String user = Parameters.getValue(p, "user"); final String[] roles = StringUtils.split(Parameters.getValue(p, "role"), ','); if (!userManager.userExists(user)) throw new IOException("No such user: " + user); userManager.addRoles(user, roles); return ("User " + user + ": role " + StringUtils.toString(roles, ",") + " added").getBytes(); } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } static RequestHandler removeRole(UserManager userManager) { return (c, p) -> { if (inUpdate.get()) return reportError(c, p, "Updating database"); try { checkKnownParameters(p, "user", "role"); checkRequiredParameters(p, "user", "role"); final String user = Parameters.getValue(p, "name"); final String[] roles = StringUtils.split(Parameters.getValue(p, "role"), ','); if (!userManager.userExists(user)) throw new IOException("No such user: " + user); userManager.removeRoles(user, roles); return ("User " + user + ": role " + StringUtils.toString(roles, ",") + " removed").getBytes(); } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } static RequestHandler removeUser(UserManager userManager) { return (c, p) -> { if (inUpdate.get()) return reportError(c, p, "Updating database"); try { checkKnownParameters(p, "name"); checkRequiredParameters(p, "name"); final String user = Parameters.getValue(p, "name"); userManager.removeUser(user); return ("User '" + user + "' removed").getBytes(); } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } static RequestHandler update(Collection<Database> databases) { return (c, p) -> { synchronized (inUpdate) { if (inUpdate.get()) return reportError(c, p, "Updating database"); else inUpdate.set(true); } try { checkKnownParameters(p); final ArrayList<byte[]> list = new ArrayList<>(); for (var database : databases) list.add(database.rebuild().getBytes()); return StringUtils.concatenate(list); } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } finally { inUpdate.set(false); } }; } static RequestHandler shutdown() { return (c, p) -> { try { checkKnownParameters(p); System.exit(0); return "Shut down".getBytes(); } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } static RequestHandler getLog() { return (c, p) -> { if (inUpdate.get()) return reportError(c, p, "Updating database"); try { checkKnownParameters(p); return Basic.getCollected().getBytes(); } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } static RequestHandler clearLog() { return (c, p) -> { if (inUpdate.get()) return reportError(c, p, "Updating database"); try { checkKnownParameters(p); Basic.stopCollectingStdErr(); Basic.startCollectionStdErr(); return "Log cleared".getBytes(); } catch (IOException ex) { return reportError(c, p, ex.getMessage()); } }; } }
6,795
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ClusterAnalysisSearcher.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/ClusterAnalysisSearcher.java
/* * ClusterAnalysisSearcher.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.clusteranalysis; import jloda.swing.find.IObjectSearcher; import megan.clusteranalysis.gui.ITab; import megan.clusteranalysis.gui.MatrixTab; import javax.swing.*; import java.awt.*; import java.util.Collection; /** * network searcher * Daniel Huson, 7.2010 */ public class ClusterAnalysisSearcher implements IObjectSearcher { private static final String NAME = "Network"; private ClusterViewer clusterViewer; private IObjectSearcher currentSearcher; /** * empty constructor. Searcher doesn't work until setup has been called */ public ClusterAnalysisSearcher() { } /** * Constructor * * @param clusterViewer the go viewer */ public ClusterAnalysisSearcher(ClusterViewer clusterViewer) { setup(clusterViewer); updateCurrent(); } /** * setup the searcher * */ private void setup(ClusterViewer clusterViewer) { this.clusterViewer = clusterViewer; updateCurrent(); } /** * rescan the matrix searcher */ public void updateMatrixSearcher() { updateCurrent(); } public boolean gotoFirst() { updateCurrent(); return currentSearcher != null && currentSearcher.gotoFirst(); } public boolean gotoNext() { updateCurrent(); return currentSearcher != null && currentSearcher.gotoNext(); } public boolean gotoLast() { updateCurrent(); return currentSearcher != null && currentSearcher.gotoLast(); } public boolean gotoPrevious() { updateCurrent(); return currentSearcher != null && currentSearcher.gotoPrevious(); } public boolean isCurrentSet() { updateCurrent(); return currentSearcher != null && currentSearcher.isCurrentSet(); } public boolean isCurrentSelected() { updateCurrent(); return currentSearcher != null && currentSearcher.isCurrentSelected(); } public void setCurrentSelected(boolean select) { updateCurrent(); if (currentSearcher != null) currentSearcher.setCurrentSelected(select); } public String getCurrentLabel() { updateCurrent(); if (currentSearcher != null) return currentSearcher.getCurrentLabel(); else return null; } public void setCurrentLabel(String newLabel) { updateCurrent(); if (currentSearcher != null) currentSearcher.setCurrentLabel(newLabel); } public int numberOfObjects() { updateCurrent(); if (currentSearcher != null) return currentSearcher.numberOfObjects(); else return 0; } public String getName() { return NAME; } public boolean isGlobalFindable() { updateCurrent(); return currentSearcher != null && currentSearcher.isGlobalFindable(); } public boolean isSelectionFindable() { updateCurrent(); return currentSearcher != null && currentSearcher.isSelectionFindable(); } public void updateView() { if (currentSearcher != null) currentSearcher.updateView(); } public boolean canFindAll() { updateCurrent(); return currentSearcher != null && currentSearcher.canFindAll(); } public void selectAll(boolean select) { updateCurrent(); if (currentSearcher != null) currentSearcher.selectAll(select); } public Component getParent() { if (currentSearcher != null) return currentSearcher.getParent(); else return null; } private void updateCurrent() { if (clusterViewer.getSelectedComponent() instanceof ITab) currentSearcher = ((ITab) clusterViewer.getSelectedComponent()).getSearcher(); else if (clusterViewer.getSelectedComponent() instanceof MatrixTab) currentSearcher = ((MatrixTab) clusterViewer.getSelectedComponent()).getSearcher(); else currentSearcher = null; } @Override public Collection<AbstractButton> getAdditionalButtons() { return null; } }
5,010
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
TriangulationTest.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/TriangulationTest.java
/* * TriangulationTest.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.clusteranalysis; import jloda.util.Triplet; import megan.clusteranalysis.tree.Distances; import megan.clusteranalysis.tree.Taxa; import megan.core.SampleAttributeTable; import java.util.*; /** * performs the triangulation test */ public class TriangulationTest { /** * performs the triangulation test described in Huson et al, A statistical test for detecting taxonomic inhomogeneity in replicated metagenomic samples * * @return true, if the H0 "all samples from same taxon distribution" is rejected, false else * @throws IllegalArgumentException if sample doesn't have attribute value */ public boolean apply(ClusterViewer clusterViewer, String attributeThatDefinesBiologicalSamples) { final SampleAttributeTable sampleAttributeTable = clusterViewer.getDocument().getSampleAttributeTable(); final ArrayList<Triplet<String, String, String>> triangles = computeTriangluation(sampleAttributeTable, attributeThatDefinesBiologicalSamples); // first two of triplet always in same biological sample, third is from other System.err.println("Triangulation (" + triangles.size() + "):"); for (Triplet<String, String, String> triangle : triangles) { System.err.println(triangle.toString()); } final int minNumberOfNonConflictedTrianglesRequired = computeMinNumberOfNonConflictedTrianglesRequired(triangles.size()); System.err.println("Minimum number of non-conflicted triangles required to reject H0: " + minNumberOfNonConflictedTrianglesRequired); final Taxa taxa = clusterViewer.getTaxa(); final Distances distances = clusterViewer.getDistances(); int numberOfNonconflictedTriangles = 0; for (Triplet<String, String, String> triangle : triangles) { double ab = distances.get(taxa.indexOf(triangle.getFirst()), taxa.indexOf(triangle.getSecond())); double ac = distances.get(taxa.indexOf(triangle.getFirst()), taxa.indexOf(triangle.getThird())); double bc = distances.get(taxa.indexOf(triangle.getSecond()), taxa.indexOf(triangle.getThird())); if (ac < ab || bc < ab) { System.err.println("Conflicted triangle a=" + triangle.getFirst() + ",b=" + triangle.getSecond() + " vs c=" + triangle.getThird() + ", distances: " + String.format("ab=%.4f, ac=%.4f, bc=%.4f", ab, ac, bc)); } else numberOfNonconflictedTriangles++; } if (numberOfNonconflictedTriangles < minNumberOfNonConflictedTrianglesRequired) System.err.println("Insufficient number of non-conflicted triangles: " + numberOfNonconflictedTriangles + ", null hypothesis not rejected"); return numberOfNonconflictedTriangles >= minNumberOfNonConflictedTrianglesRequired; } /** * compute a triangulation * * @return triangulation */ private ArrayList<Triplet<String, String, String>> computeTriangluation(SampleAttributeTable sampleAttributeTable, String attributeThatDefinesBiologicalSamples) { final ArrayList<Triplet<String, String, String>> triangles = new ArrayList<>(); // first two of triplet always in same biological sample, third is from other for (int i = 0; i < 50; i++) { // try 50 times to compute a perfect triangulation triangles.clear(); final Map<Object, LinkedList<String>> key2set = new HashMap<>(); final Map<Object, Integer> key2pairs = new HashMap<>(); for (String sample : sampleAttributeTable.getSampleOrder()) { final Object key = sampleAttributeTable.get(sample, attributeThatDefinesBiologicalSamples); if (key == null) throw new IllegalArgumentException("No value for sample=" + sample + " and attribute=" + attributeThatDefinesBiologicalSamples); LinkedList<String> set = key2set.get(key); if (set == null) { set = new LinkedList<>(); key2set.put(key, set); key2pairs.put(key, 0); } set.add(sample); } for (LinkedList<String> set : key2set.values()) { if (set.size() < 2) throw new IllegalArgumentException("Too few samples for attribute=" + attributeThatDefinesBiologicalSamples + ": " + set.size()); } final List<Object> allKeys = new LinkedList<>(key2set.keySet()); final List<Object> allKeysForDoubletOrMoreSets = new LinkedList<>(key2set.keySet()); final List<Object> allKeysForSingletonSets = new LinkedList<>(); final Random random = new Random(); while (allKeysForDoubletOrMoreSets.size() > 0 && (2 * allKeysForDoubletOrMoreSets.size() + allKeysForSingletonSets.size()) > 2) { Object key1 = allKeys.get(random.nextInt(allKeys.size())); if (allKeysForSingletonSets.contains(key1)) { final Object key2 = allKeysForDoubletOrMoreSets.get(random.nextInt(allKeysForDoubletOrMoreSets.size())); // won't be key1 key2pairs.put(key2, key2pairs.get(key2) + 1); final String sample1 = key2set.get(key2).remove(random.nextInt(key2set.get(key2).size())); final String sample2 = key2set.get(key2).remove(random.nextInt(key2set.get(key2).size())); final String sample3 = key2set.get(key1).remove(0); // last one left in set triangles.add(new Triplet<>(sample1, sample2, sample3)); allKeysForSingletonSets.remove(key1); allKeys.remove(key1); if (key2set.get(key2).size() < 2) { allKeysForDoubletOrMoreSets.remove(key2); if (key2set.get(key2).size() == 1) allKeysForSingletonSets.add(key2); else allKeys.remove(key2); } } else // key1 points to set with at least two replicates available { Object key2; do { key2 = allKeys.get(random.nextInt(allKeys.size())); } while (key2 == key1); // there are at least two keys available, so this will end final boolean pair1 = (allKeysForSingletonSets.contains(key2) || key2pairs.get(key1) < key2pairs.get(key2) || (key2pairs.get(key1).equals(key2pairs.get(key2)) && random.nextBoolean())); if (!pair1) { // swap roles Object tmp = key1; key1 = key2; key2 = tmp; } final String sample1 = key2set.get(key1).remove(random.nextInt(key2set.get(key1).size())); final String sample2 = key2set.get(key1).remove(random.nextInt(key2set.get(key1).size())); final String sample3 = key2set.get(key2).remove(random.nextInt(key2set.get(key2).size())); triangles.add(new Triplet<>(sample1, sample2, sample3)); key2pairs.put(key1, key2pairs.get(key1) + 1); if (key2set.get(key1).size() < 2) { allKeysForDoubletOrMoreSets.remove(key1); if (key2set.get(key1).size() == 1 && !allKeysForSingletonSets.contains(key1)) allKeysForSingletonSets.add(key1); if (key2set.get(key1).size() == 0) { allKeysForSingletonSets.remove(key1); allKeys.remove(key1); } } if (key2set.get(key2).size() < 2) { allKeysForDoubletOrMoreSets.remove(key2); if (key2set.get(key2).size() == 1 && !allKeysForSingletonSets.contains(key2)) allKeysForSingletonSets.add(key2); if (key2set.get(key2).size() == 0) { allKeysForSingletonSets.remove(key2); allKeys.remove(key2); } } } } if ((allKeysForDoubletOrMoreSets.size() == 0 || key2set.get(allKeysForDoubletOrMoreSets.get(0)).size() < 3) && allKeysForSingletonSets.size() < 3) break; // no excess of remaining samples } return triangles; } /** * computes the minimum number of non-conflicted triangles required to reject H0 with alpha=0.05 * * @return max triangles allowed to be in conflict */ private int computeMinNumberOfNonConflictedTrianglesRequired(int totalTriangles) { double sum = 0; for (int k = totalTriangles; k >= 0; k--) { sum += binomial(totalTriangles, k) * Math.pow(1.0 / 3.0, k) * Math.pow(2.0 / 3.0, totalTriangles - k); if (sum > 0.05) return k + 1; } return 0; } /** * binomial * * @return n choose k */ private static long binomial(int n, int k) { if (k > n - k) k = n - k; long b = 1; for (int i = 1, m = n; i <= k; i++, m--) b = b * m / i; return b; } /** * test whether there are at least two samples for each attribute value * * @return true, if ok */ public static boolean isSuitableAttribute(SampleAttributeTable sampleAttributeTable, String attribute) { if (sampleAttributeTable.isSecretAttribute(attribute) || sampleAttributeTable.isHiddenAttribute(attribute)) return false; boolean ok = true; Map<Object, Integer> value2count = new HashMap<>(); for (String sample : sampleAttributeTable.getSampleOrder()) { Object value = sampleAttributeTable.get(sample, attribute); if (value == null) { ok = false; break; } else { value2count.merge(value, 1, Integer::sum); } } if (ok) { for (Integer count : value2count.values()) { if (count < 2) { ok = false; break; } } } return ok; } }
11,285
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
LegendPanel.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/LegendPanel.java
/* * LegendPanel.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.clusteranalysis; import jloda.swing.util.BasicSwing; import megan.core.Document; import megan.util.GraphicsUtilities; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; /** * legend panel for cluster viewer * Daniel Huson, 3.2013 */ public class LegendPanel extends JPanel { private final ClusterViewer viewer; private final Document doc; private Font font = Font.decode("Helvetica-NORMAL-11"); private Color fontColor = Color.BLACK; private JPopupMenu popupMenu = null; /** * constructor * */ public LegendPanel(ClusterViewer viewer) { this.viewer = viewer; doc = viewer.getDir().getDocument(); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent mouseEvent) { if (mouseEvent.isPopupTrigger() && popupMenu != null) popupMenu.show(LegendPanel.this, mouseEvent.getX(), mouseEvent.getY()); } public void mouseReleased(MouseEvent mouseEvent) { if (mouseEvent.isPopupTrigger() && popupMenu != null) popupMenu.show(LegendPanel.this, mouseEvent.getX(), mouseEvent.getY()); } }); } public void setPopupMenu(JPopupMenu popupMenu) { this.popupMenu = popupMenu; } /** * draw the legend * */ public void paint(Graphics graphics) { super.paint(graphics); Graphics2D gc = (Graphics2D) graphics; gc.setColor(Color.WHITE); gc.fill(getVisibleRect()); draw(gc, null); } /** * rescan the view */ public void updateView() { Graphics2D graphics = (Graphics2D) getGraphics(); if (graphics != null) { Dimension size = new Dimension(); draw(graphics, size); //setPreferredSize(new Dimension(getPreferredSize().width,size.height)); setPreferredSize(size); revalidate(); } } /** * draw a legend for sample colors * */ public void draw(Graphics2D gc, Dimension size) { if (doc.getNumberOfSamples() > 1) { boolean vertical = viewer.getShowLegend().equals("vertical"); gc.setFont(getFont()); boolean doDraw = (size == null); int yStart = 20; int x = 3; int maxX = x; if (doDraw) { String legend = "Legend:"; gc.setColor(Color.BLACK); gc.drawString(legend, x, yStart); Dimension labelSize = BasicSwing.getStringSize(gc, legend, gc.getFont()).getSize(); maxX = Math.max(maxX, labelSize.width); } int y = yStart + (int) (1.5 * gc.getFont().getSize()); if (viewer.getGraphView() != null) { for (String sampleName : doc.getSampleNames()) { String label = doc.getSampleLabelGetter().getLabel(sampleName); if (!label.equals(sampleName)) label += " (" + sampleName + ")"; final Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize(); int boxSize = labelSize.height - 2; if (x + boxSize + labelSize.width + 2 > getWidth() || vertical) { x = 3; y += 1.5 * gc.getFont().getSize(); } if (doDraw) { final Image image = GraphicsUtilities.makeSampleIconSwing(doc, sampleName, true, true, boxSize + 1); gc.drawImage(image, x, y - boxSize, this); gc.setColor(getFontColor()); gc.drawString(label, x + boxSize + 2, y); } maxX = Math.max(maxX, x); x += boxSize + 2 + labelSize.width + 10; if (vertical) maxX = Math.max(maxX, x); } if (size != null) size.setSize(maxX, y); } } } public void setFont(Font font) { this.font = font; } public Font getFont() { return font; } public void setFontColor(Color fontColor) { this.fontColor = fontColor; } private Color getFontColor() { return fontColor; } }
5,279
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
GUIConfiguration.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/GUIConfiguration.java
/* * GUIConfiguration.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.clusteranalysis; import jloda.swing.window.MenuConfiguration; import megan.classification.data.ClassificationCommandHelper; /** * configuration for menu and toolbar * Daniel Huson, 7.2010 */ public class GUIConfiguration { /** * get the menu configuration * * @return menu configuration */ public static MenuConfiguration getMenuConfiguration() { MenuConfiguration menuConfig = new MenuConfiguration(); menuConfig.defineMenuBar("File;Edit;Select;Layout;Options;PCoA;Window;Help;"); menuConfig.defineMenu("File", "New...;|;Open...;@Open Recent;|;Open From Server...;|;Compare...;|;Import From BLAST...;@Import;Meganize DAA File...;|;Save As...;|;" + "@Export;|;Page Setup...;Print...;|;Close;|;Quit;"); menuConfig.defineMenu("Open Recent", ";"); menuConfig.defineMenu("Import", "Import Text (CSV) Format...;Import BIOM Format...;|;Import Metadata...;"); menuConfig.defineMenu("Export", "Export Image...;Export Legend...;|;Export Distances...;Export Points...;"); menuConfig.defineMenu("Edit", "Copy;Copy Image;Copy Legend;Paste;|;Format...;Set Node Shape...;Set Color...;|;Set Axes Linewidth and Color...;Set BiPlot Linewidth and Color...;Set TriPlot Linewidth and Color...;Set Groups Linewidth and Color...;|;Group Nodes;Ungroup All;|;Find...;Find Again;|;Colors...;"); menuConfig.defineMenu("Node Shape", "Circle;Square;Triangle;Diamond;"); menuConfig.defineMenu("Select", "Select All;Select None;Invert Selection;|;From Previous Window;"); menuConfig.defineMenu("Layout", "Show Legend;|;Increase Font Size;Decrease Font Size;|;@Expand/Contract;|;Zoom to Fit;Set Scale...;|;Flip Horizontally;Flip Vertically;@Rotate;|;" + "Show Groups;Show Groups As Convex Hulls;|;Use Colors;Show Labels;Set Node Radius...;"); menuConfig.defineMenu("Rotate", "Rotate Left;Rotate Right;Rotate Up;Rotate Down;"); menuConfig.defineMenu("Expand/Contract", "Expand Horizontal;Contract Horizontal;Expand Vertical;Contract Vertical;"); menuConfig.defineMenu("Options", "Apply Triangulation Test...;|;PCoA Tab;UPGMA Tree Tab;NJ Tree Tab;Network Tab;Matrix Tab;|;Use JSD;Use Bray-Curtis;Use Euclidean;|;Use Unweighted Uniform UniFrac;Use Weighted Uniform UniFrac;|;Use Chi-Square;Use Kulczynski;Use Hellinger;Use Goodall;|;Sync;"); menuConfig.defineMenu("PCoA", "PCoA Tab;|;PC1 vs PC2;PC1 vs PC3;PC2 vs PC3;PCi vs PCj...;|;PC1 PC2 PC3;PCi PCj PCk...;|;Show Axes;|;Show BiPlot;BiPlot Size...;|;Show TriPlot;TriPlot Size...;|;@More;"); menuConfig.defineMenu("More","Set BiPlot Scale Factor...;Set TriPlot Scale Factor...;"); menuConfig.defineMenu("Window", "Message Window...;|;Samples Viewer...;Groups Viewer...;|;"); menuConfig.defineMenu("Help", "About...;How to Cite...;|;Community Website...;Reference Manual...;|;Check For Updates...;"); return menuConfig; } /** * gets the toolbar configuration * * @return toolbar configuration */ public static String getToolBarConfiguration() { return "Open...;Print...;Export Image...;|;Find...;|;Expand Vertical;Contract Vertical;Expand Horizontal;Contract Horizontal;|;Zoom to Fit;|;" + "PC1 vs PC2;PC1 vs PC3;PC2 vs PC3;PCi vs PCj...;|;PC1 PC2 PC3;PCi PCj PCk...;|;" + "Color Samples By Attribute;Shape Samples By Attribute;Label Samples By Attribute;Group Samples By Attribute;Ungroup All;|;" + "Main Viewer...;" + ClassificationCommandHelper.getOpenViewerMenuString() + "|;Samples Viewer...;|;Show Legend;|;Sync;"; } /** * get the configuration of the node popup menu * * @return config */ public static String getNodePopupConfiguration() { return "Correlate To Attributes...;|;Copy Node Label;Edit Node Label;|;Set Node Shape...;Set Color...;"; } /** * get the configuration of the edge popup menu * * @return config */ public static String getEdgePopupConfiguration() { return null; } /** * gets the canvas popup configuration * * @return config */ public static String getPanelPopupConfiguration() { return "Copy Image;Export Image...;"; } }
5,132
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ClusterViewer.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/ClusterViewer.java
/* * ClusterViewer.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.clusteranalysis; import jloda.graph.Edge; import jloda.graph.Node; import jloda.graph.NodeSet; import jloda.phylo.PhyloTree; import jloda.swing.commands.CommandManager; import jloda.swing.director.*; import jloda.swing.find.FindToolBar; import jloda.swing.find.SearchManager; import jloda.swing.format.Formatter; import jloda.swing.graphview.EdgeView; import jloda.swing.graphview.GraphView; import jloda.swing.graphview.NodeView; import jloda.swing.util.PopupMenu; import jloda.swing.util.ProgramProperties; import jloda.swing.util.StatusBar; import jloda.swing.util.ToolBar; import jloda.swing.window.MenuBar; import jloda.swing.window.NotificationsInSwing; import jloda.util.Basic; import jloda.util.NodeShape; import megan.classification.Classification; import megan.classification.ClassificationManager; import megan.clusteranalysis.gui.*; import megan.clusteranalysis.indices.BrayCurtisDissimilarity; import megan.clusteranalysis.indices.DistancesManager; import megan.clusteranalysis.tree.Distances; import megan.clusteranalysis.tree.Taxa; import megan.core.Director; import megan.core.Document; import megan.core.SelectionSet; import megan.dialogs.input.InputDialog; import megan.main.MeganProperties; import megan.viewer.ClassificationViewer; import megan.viewer.MainViewer; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.io.IOException; import java.util.*; import java.util.function.Consumer; /** * viewer for distance-based comparison of metagenome datasets * Daniel Huson, 5.2010 */ public class ClusterViewer extends JFrame implements IDirectableViewer, IViewerWithFindToolBar, IViewerWithLegend, Printable { public static int PCoA_TAB_INDEX = 0; public static int UPGMA_TAB_INDEX = 1; private static int NJ_TAB_INDEX = 2; public static int NNET_TAB_INDEX = 3; public static int MATRIX_TAB_INDEX = 4; private int currentTab = 0; private final Director dir; private final Document doc; private final JPanel mainPanel; private final StatusBar statusBar; private final JTabbedPane tabbedPane; private final MatrixTab matrixTab; private final UPGMATab upgmaTab; private final NJTab njTab; private final NNetTab nnetTab; private final PCoATab pcoaTab; private final LegendPanel legendPanel; private final JScrollPane legendScrollPane; private String showLegend = "none"; private final JSplitPane splitPane; private final MenuBar menuBar; private final CommandManager commandManager; private final SelectionSet.SelectionListener selectionListener; private String dataType; private String ecologicalIndex = BrayCurtisDissimilarity.NAME; private boolean locked = false; private boolean uptodate = true; private boolean showFindToolBar = false; private final SearchManager searchManager; private final ClusterAnalysisSearcher clusterAnalysisSearcher; private boolean useColors = true; private boolean showLabels = true; private int nodeRadius = 12; // default node radius private final HashMap<String, NodeShape> label2shape = new HashMap<>(); private final Map<String, LinkedList<Node>> group2Nodes = new HashMap<>(); // used in calc of convex hulls public boolean updateConvexHulls = false; private Taxa taxa; private Distances distances; private final ClassificationViewer parentViewer; public static Consumer<ClusterViewer> clusterViewerAddOn; /** * creates a new network viewer * */ public ClusterViewer(final Director dir, ClassificationViewer parentViewer, String dataType) { this.dataType = dataType; this.parentViewer = parentViewer; this.dir = dir; this.doc = dir.getDocument(); getContentPane().setLayout(new BorderLayout()); setSize(600, 600); setLocationRelativeTo(parentViewer.getFrame()); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); commandManager = new CommandManager(dir, this, new String[]{"megan.commands", "megan.clusteranalysis.commands"}, !ProgramProperties.isUseGUI()); menuBar = new MenuBar(this, GUIConfiguration.getMenuConfiguration(), getCommandManager()); setJMenuBar(menuBar); MeganProperties.addPropertiesListListener(menuBar.getRecentFilesListener()); MeganProperties.notifyListChange(ProgramProperties.RECENTFILES); ProjectManager.addAnotherWindowWithWindowMenu(dir, menuBar.getWindowMenu()); add(new ToolBar(this, GUIConfiguration.getToolBarConfiguration(), commandManager), BorderLayout.NORTH); setIconImages(ProgramProperties.getProgramIconImages()); statusBar = new StatusBar(); add(statusBar, BorderLayout.SOUTH); tabbedPane = new JTabbedPane(); mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); mainPanel.add(tabbedPane, BorderLayout.CENTER); legendPanel = new LegendPanel(this); legendScrollPane = new JScrollPane(legendPanel); splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, mainPanel, legendScrollPane); splitPane.setOneTouchExpandable(true); splitPane.setEnabled(true); splitPane.setResizeWeight(1.0); splitPane.setDividerLocation(1.0); splitPane.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent componentEvent) { if (getShowLegend().equals("none")) splitPane.setDividerLocation(1.0); legendPanel.updateView(); } }); getContentPane().add(splitPane, BorderLayout.CENTER); upgmaTab = new UPGMATab(this); njTab = new NJTab(this); njTab.getGraphView().trans.setLockXYScale(true); nnetTab = new NNetTab(this); nnetTab.getGraphView().trans.setLockXYScale(true); pcoaTab = new PCoATab(this); matrixTab = new MatrixTab(this.getFrame()); tabbedPane.add(pcoaTab.getLabel(), pcoaTab); tabbedPane.add(upgmaTab.getLabel(), upgmaTab); tabbedPane.add(njTab.getLabel(), njTab); tabbedPane.add(nnetTab.getLabel(), nnetTab); tabbedPane.add(matrixTab.getLabel(), matrixTab); tabbedPane.addChangeListener(changeEvent -> { int tabId = tabbedPane.getSelectedIndex(); if (tabId != currentTab) { if (tabbedPane.getComponentAt(currentTab) instanceof ITab) { ((ITab) tabbedPane.getComponentAt(currentTab)).deactivate(); } if (tabbedPane.getSelectedComponent() instanceof ITab && ((ITab) tabbedPane.getSelectedComponent()).needsUpdate()) { final ITab tab = ((ITab) tabbedPane.getSelectedComponent()); tab.activate(); dir.execute("sync;", getCommandManager()); } else { final GraphView prevView = getGraphViewForTabId(currentTab); final GraphView nextView = getGraphViewForTabId(tabId); if (prevView != null && nextView != null && prevView != nextView) // copy attributes from one labeled node to next { for (Node v = prevView.getGraph().getFirstNode(); v != null; v = v.getNext()) { if (prevView.getLabel(v) != null) { for (Node w = nextView.getGraph().getFirstNode(); w != null; w = w.getNext()) { if (nextView.getLabel(w) != null && prevView.getLabel(v).equals(nextView.getLabel(w))) { NodeView nw = nextView.getNV(w); NodeView nv = prevView.getNV(v); nw.setColor(nv.getColor()); nw.setFont(nv.getFont()); nw.setLabelColor(nv.getLabelColor()); nw.setBackgroundColor(nv.getBackgroundColor()); nw.setLabelBackgroundColor(nv.getLabelBackgroundColor()); nw.setHeight(nv.getHeight()); nw.setWidth(nv.getWidth()); nw.setShape(nv.getShape()); nw.setLineWidth((byte) nv.getLineWidth()); nextView.setSelected(w, prevView.getSelected(v)); } } } } } if (nextView != null) nextView.fitGraphToWindow(); } currentTab = tabId; } if (isActive() && Formatter.getInstance() != null) { Formatter.getInstance().setViewer(dir, getGraphView()); } // updateView(IDirector.ALL); }); this.setPreferredSize(new Dimension(0, 0)); clusterAnalysisSearcher = new ClusterAnalysisSearcher(this); searchManager = new SearchManager(dir, this, clusterAnalysisSearcher, false, true); addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent event) { MainViewer.setLastActiveFrame(ClusterViewer.this); updateView(IDirector.ENABLE_STATE); if (Formatter.getInstance() != null) { Formatter.getInstance().setViewer(dir, getGraphView()); } InputDialog inputDialog = InputDialog.getInstance(); if (inputDialog != null) inputDialog.setViewer(dir, ClusterViewer.this); } public void windowDeactivated(WindowEvent event) { if (tabbedPane.getComponentAt(currentTab) instanceof ITab) { ((ITab) tabbedPane.getComponentAt(currentTab)).deactivate(); } if (getGraphView() instanceof ViewerBase) { Collection<String> selectedLabels = ((ViewerBase) getGraphView()).getSelectedNodeLabels(false); if (selectedLabels.size() != 0) { ProjectManager.getPreviouslySelectedNodeLabels().clear(); ProjectManager.getPreviouslySelectedNodeLabels().addAll(selectedLabels); } } } public void windowClosing(WindowEvent e) { getDir().executeImmediately("close what=current;", getCommandManager()); if (dir.getDocument().getProgressListener() != null) dir.getDocument().getProgressListener().setUserCancelled(true); if (MainViewer.getLastActiveFrame() == ClusterViewer.this) MainViewer.setLastActiveFrame(null); } }); setTitle(); selectionListener = (labels, selected) -> selectByLabel(getTabbedIndex(), labels, selected); doc.getSampleSelection().addSampleSelectionListener(selectionListener); legendPanel.setPopupMenu(new PopupMenu(this, megan.chart.gui.GUIConfiguration.getLegendPanelPopupConfiguration(), commandManager)); setVisible(true); splitPane.setDividerLocation(1.0); SwingUtilities.invokeLater(() -> dir.execute("sync;", commandManager)); } /** * is viewer uptodate? * * @return uptodate */ public boolean isUptoDate() { return uptodate; } /** * return the frame associated with the viewer * * @return frame */ public JFrame getFrame() { return this; } private void setTitle() { String newTitle = dataType + " Cluster Analysis - " + doc.getTitle(); if (doc.getMeganFile().isMeganServerFile()) newTitle += " (remote file)"; if (doc.getMeganFile().isReadOnly()) newTitle += " (read-only)"; else if (doc.isDirty()) newTitle += "*"; if (dir.getID() == 1) newTitle += " - " + ProgramProperties.getProgramVersion(); else newTitle += " - [" + dir.getID() + "] - " + ProgramProperties.getProgramVersion(); if (!getTitle().equals(newTitle)) { setTitle(newTitle); ProjectManager.updateWindowMenus(); } } /** * ask view to update itself. This method is wrapped into a runnable object * and put in the swing event queue to avoid concurrent modifications. * * @param what what should be updated? Possible values: Director.ALL or Director.TITLE */ public void updateView(final String what) { for (String sample : doc.getSampleNames()) { String label = doc.getSampleAttributeTable().getSampleShape(sample); NodeShape shape; if (label == null || label.equalsIgnoreCase("circle")) shape = NodeShape.Oval; else shape = NodeShape.valueOfIgnoreCase(label); label2shape.put(sample, shape); } setFont(ProgramProperties.get(ProgramProperties.DEFAULT_FONT, getFont())); final GraphView graphView = getGraphViewForTabId(tabbedPane.getSelectedIndex()); setStatusLine(ClusterViewer.this); getCommandManager().updateEnableState(); setTitle(); if (what.equals(IDirector.ALL)) { if (graphView != null) { final PhyloTree graph = ((PhyloTree) graphView.getGraph()); group2Nodes.clear(); if (isPCoATab()) { // setup group 2 nodes in order that samples appear in table Map<String, Node> sample2node = new HashMap<>(); for (Node v = graph.getFirstNode(); v != null; v = v.getNext()) { sample2node.put(graph.getLabel(v), v); } for (String sample : getDir().getDocument().getSampleAttributeTable().getSampleOrder()) { String groupId = getDir().getDocument().getSampleAttributeTable().getGroupId(sample); if (groupId != null) { LinkedList<Node> nodes = group2Nodes.computeIfAbsent(groupId, k -> new LinkedList<>()); nodes.add(sample2node.get(sample)); } } } if (isActive()) graphView.requestFocusInWindow(); final Set<String> selectedLabels = doc.getSampleSelection().getAll(); final NodeSet toSelect = new NodeSet(graphView.getGraph()); for (Node v = graph.getFirstNode(); v != null; v = v.getNext()) { final NodeView nv = graphView.getNV(v); if (nv.getLabel() != null) { nv.setLabelVisible(showLabels); if (nv.getHeight() <= 3) nv.setHeight(nodeRadius); if (nv.getWidth() <= 3) nv.setWidth(nodeRadius); nv.setFixedSize(true); if (useColors) { String sample = graph.getLabel(v); Color color = dir.getDocument().getChartColorManager().getSampleColor(sample); if (nodeRadius > 1 || !showLabels) { nv.setBackgroundColor(color); nv.setLabelBackgroundColor(null); } else nv.setLabelBackgroundColor(color); } else nv.setBackgroundColor(null); if (selectedLabels.contains(nv.getLabel())) toSelect.add(v); } } addFormatting(upgmaTab.getGraphView()); addFormatting(njTab.getGraphView()); addFormatting(nnetTab.getGraphView()); if (pcoaTab.isShowGroupsAsEllipses() || pcoaTab.isShowGroupsAsConvexHulls()) pcoaTab.computeConvexHullsAndEllipsesForGroups(group2Nodes); addFormatting(pcoaTab.getGraphView()); graphView.setSelected(toSelect, true); } } if (graphView != null) graphView.repaint(); final FindToolBar findToolBar = searchManager.getFindDialogAsToolBar(); if (findToolBar.isClosing()) { showFindToolBar = false; findToolBar.setClosing(false); } if (!findToolBar.isEnabled() && showFindToolBar) { mainPanel.add(findToolBar, BorderLayout.NORTH); findToolBar.setEnabled(true); getContentPane().validate(); getCommandManager().updateEnableState(); } else if (findToolBar.isEnabled() && !showFindToolBar) { mainPanel.remove(findToolBar); findToolBar.setEnabled(false); getContentPane().validate(); getCommandManager().updateEnableState(); } if (tabbedPane.getSelectedComponent() instanceof ITab) { try { ((ITab) tabbedPane.getSelectedComponent()).updateView(what); } catch (Exception e) { Basic.caught(e); } } legendPanel.updateView(); if (doc.getNumberOfSamples() <= 1) splitPane.setDividerLocation(1.0); legendPanel.repaint(); // enable applicable tabs for (int i = 0; i < tabbedPane.getTabCount(); i++) { if (tabbedPane.getComponentAt(i) instanceof ITab) { ITab tab = (ITab) tabbedPane.getComponentAt(i); tabbedPane.setEnabledAt(i, tab.isApplicable()); } } } /** * update distances */ public void updateDistances() throws Exception { taxa = new Taxa(); java.util.List<String> pids = doc.getSampleNames(); for (String name : pids) { taxa.add(name); } if (taxa.size() < 4) throw new IOException("Too few samples: " + taxa.size()); distances = new Distances(taxa.size()); DistancesManager.apply(ecologicalIndex, getParentViewer(), distances); if (distances.replaceNaNByZero()) { NotificationsInSwing.showWarning(getFrame(), "Undefined distances detected, replaced by 0"); } getPcoaTab().clear(); getUpgmaTab().clear(); getNnetTab().clear(); getNJTab().clear(); matrixTab.setData(taxa, distances); } /** * update the graph */ public void updateGraph() throws Exception { if (tabbedPane.getSelectedComponent() instanceof ITab) { final ITab iTab = (ITab) tabbedPane.getSelectedComponent(); iTab.compute(taxa, distances); clusterAnalysisSearcher.updateMatrixSearcher(); } } /** * sets the status line */ private void setStatusLine(ClusterViewer clusterViewer) { statusBar.setText1("Samples=" + clusterViewer.getDir().getDocument().getNumberOfSamples()); String text2 = "Data=" + clusterViewer.getDataType(); text2 += " Matrix=" + clusterViewer.getEcologicalIndex(); Component pane = getSelectedComponent(); if (pane instanceof ITab) { text2 += " Method=" + ((ITab) pane).getMethod(); } statusBar.setText2(text2); } /** * get the graph viewer for the given id * * @return GraphView or null */ private GraphView getGraphViewForTabId(int tabId) { if (tabbedPane.getComponentAt(tabId) instanceof ITab) { return ((ITab) tabbedPane.getComponentAt(tabId)).getGraphView(); } else { return null; } } /** * ask view to prevent user input */ public void lockUserInput() { locked = true; tabbedPane.setEnabled(false); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); statusBar.setText2("Busy..."); getCommandManager().setEnableCritical(false); menuBar.setEnableRecentFileMenuItems(false); } /** * ask view to allow user input */ public void unlockUserInput() { locked = false; tabbedPane.setEnabled(true); setCursor(Cursor.getDefaultCursor()); getCommandManager().setEnableCritical(true); getCommandManager().updateEnableState(); menuBar.setEnableRecentFileMenuItems(true); } public boolean isLocked() { return locked; } /** * set the cursor for all tabs * */ public void setCursor(Cursor cursor) { super.setCursor(cursor); if (getPcoaTab() != null) getPcoaTab().getGraphView().setCursor(cursor); if (getNJTab() != null) getNJTab().getGraphView().setCursor(cursor); if (getNnetTab() != null) getNnetTab().getGraphView().setCursor(cursor); if (getUpgmaTab() != null) getUpgmaTab().getGraphView().setCursor(cursor); if (getMatrixTab() != null) getMatrixTab().setCursor(cursor); } /** * ask view to destroy itself */ public void destroyView() { searchManager.getFindDialogAsToolBar().close(); setVisible(false); doc.getSampleSelection().removeSampleSelectionListener(selectionListener); MeganProperties.removePropertiesListListener(menuBar.getRecentFilesListener()); dir.removeViewer(this); dispose(); } /** * set uptodate state * */ public void setUptoDate(boolean flag) { uptodate = flag; } public Director getDir() { return dir; } public String getDataType() { return dataType; } public String getEcologicalIndex() { return ecologicalIndex; } /** * add node and edge formatting * */ public void addFormatting(GraphView graphView) { try { final PhyloTree graph = ((PhyloTree) graphView.getGraph()); for (Node v = graph.getFirstNode(); v != null; v = v.getNext()) { final NodeView nv = graphView.getNV(v); final String label = graph.getLabel(v); boolean showThisLabel = showLabels; if (label != null) { if (graphView == pcoaTab.getGraphView()) { if (pcoaTab.isBiplotNode(v)) showThisLabel = pcoaTab.isShowBiPlot(); else if (pcoaTab.isTriplotNode(v)) showThisLabel = pcoaTab.isShowTriPlot(); } if (showThisLabel) { nv.setLabelVisible(true); if (nv.getHeight() <= 3) nv.setHeight(nodeRadius); if (nv.getWidth() <= 3) nv.setWidth(nodeRadius); nv.setFixedSize(true); NodeShape shape = label2shape.get(label); if (shape != null) { nv.setNodeShape(shape); } graphView.setLabel(v, doc.getSampleLabelGetter().getLabel(label)); if (useColors) { Color color = dir.getDocument().getChartColorManager().getSampleColor(label); if (nodeRadius > 1) { nv.setBackgroundColor(color); nv.setLabelBackgroundColor(null); } else nv.setLabelBackgroundColor(color); } else nv.setBackgroundColor(null); } } else showThisLabel=false; if(!showThisLabel) { nv.setLabelVisible(false); } } for (Edge e = graph.getFirstEdge(); e != null; e = e.getNext()) { if (graph.getInfo(e) != null && (Byte) graph.getInfo(e) == EdgeView.DIRECTED) graphView.setDirection(e, EdgeView.DIRECTED); else graphView.setDirection(e, EdgeView.UNDIRECTED); } } catch (Exception e) { Basic.caught(e); } } public void setEcologicalIndex(String ecologicalIndex) { this.ecologicalIndex = ecologicalIndex; } public CommandManager getCommandManager() { return commandManager; } public void setDataType(String dataType) { this.dataType = dataType; } /** * gets the index of the showing tab * * @return index */ public int getTabbedIndex() { return tabbedPane.getSelectedIndex(); } public boolean isPCoATab() { return tabbedPane.getSelectedComponent() instanceof ITab && ((ITab) tabbedPane.getSelectedComponent()).getLabel().contains("PCoA"); } public void selectAll(boolean select) { GraphView graphView = getGraphViewForTabId(getTabbedIndex()); if (graphView != null) { graphView.selectAllNodes(select); graphView.selectAllEdges(select); graphView.repaint(); } else { if (select) matrixTab.getTable().selectAll(); else matrixTab.getTable().clearSelection(); } } public void selectByLabel(int tabbedIndex, Collection<String> labels, boolean select) { GraphView graphView = getGraphViewForTabId(tabbedIndex); if (graphView != null) { PhyloTree graph = ((PhyloTree) graphView.getGraph()); NodeSet nodes = new NodeSet(graph); for (Node v = graph.getFirstNode(); v != null; v = v.getNext()) { String label = graph.getLabel(v); if (label != null && labels.contains(label) && graphView.getSelected(v) != select) nodes.add(v); } graphView.setSelected(nodes, select); } else if (tabbedIndex == MATRIX_TAB_INDEX) { matrixTab.getTable().selectAll(); } } public void selectInverted() { GraphView graphView = getGraphViewForTabId(getTabbedIndex()); if (graphView != null) { graphView.invertNodeSelection(); if (graphView.getSelectedEdges().size() > 0) graphView.invertEdgeSelection(); } else { matrixTab.getTable().selectAll(); } } public PCoATab getPcoaTab() { return pcoaTab; } public TreeTabBase getUpgmaTab() { return upgmaTab; } public TreeTabBase getNJTab() { return njTab; } public TreeTabBase getNnetTab() { return nnetTab; } public MatrixTab getMatrixTab() { return matrixTab; } public Taxa getTaxa() { return taxa; } public Distances getDistances() { return distances; } public int getNumberOfNodesUsed() { int numberOfNodesUsed = 0; return numberOfNodesUsed; } public Component getSelectedComponent() { if (tabbedPane != null) return tabbedPane.getSelectedComponent(); else return null; } public void selectComponent(Component component) { tabbedPane.setSelectedComponent(component); } /** * gets the current graphview * * @return graphview */ public GraphView getGraphView() { if (tabbedPane.getSelectedComponent() instanceof ITab) return ((ITab) tabbedPane.getSelectedComponent()).getGraphView(); else return null; } /** * gets the current data viewer (MainViewer, SeedViewer, KeggViewer) * * @return graphview */ public ClassificationViewer getParentViewer() { return parentViewer; } /** * Print the graph associated with this viewer. * * @param gc0 the graphics context. * @param format page format * @param pagenumber page index */ public int print(Graphics gc0, PageFormat format, int pagenumber) throws PrinterException { JPanel panel = getPanel(); if (panel != null && pagenumber == 0) { if (panel instanceof GraphView) { return ((GraphView) panel).print(gc0, format, pagenumber); } else { Graphics2D gc = ((Graphics2D) gc0); Dimension dim = panel.getSize(); int image_w = dim.width; int image_h = dim.height; double paper_x = format.getImageableX() + 1; double paper_y = format.getImageableY() + 1; double paper_w = format.getImageableWidth() - 2; double paper_h = format.getImageableHeight() - 2; double scale_x = paper_w / image_w; double scale_y = paper_h / image_h; double scale = Math.min(scale_x, scale_y); double shift_x = paper_x + (paper_w - scale * image_w) / 2.0; double shift_y = paper_y + (paper_h - scale * image_h) / 2.0; gc.translate(shift_x, shift_y); gc.scale(scale, scale); panel.print(gc0); return Printable.PAGE_EXISTS; } } return Printable.NO_SUCH_PAGE; } public JScrollPane getSelectedScrollPane() { Component tab = tabbedPane.getSelectedComponent(); if (tab instanceof TreeTabBase) { return ((TreeTabBase) tab).getGraphView().getScrollPane(); } if (tab instanceof PCoATab) { return ((PCoATab) tab).getGraphView().getScrollPane(); } if (tab instanceof MatrixTab) { return ((MatrixTab) tab).getScrollPane(); } return null; } public JPanel getPanel() { Component tab = tabbedPane.getSelectedComponent(); if (tab instanceof TreeTabBase) { return ((TreeTabBase) tab).getGraphView(); } if (tab instanceof PCoATab) { return ((PCoATab) tab).getGraphView(); } if (tab instanceof MatrixTab) { return ((MatrixTab) tab); } return (JPanel) tab; } public boolean isShowFindToolBar() { return showFindToolBar; } public void setShowFindToolBar(boolean showFindToolBar) { this.showFindToolBar = showFindToolBar; } public SearchManager getSearchManager() { return searchManager; } /** * get name for this type of viewer * * @return name */ public String getClassName() { return dataType.toUpperCase() + "ClusterViewer"; } public boolean isUseColors() { return useColors; } public void setUseColors(boolean useColors) { this.useColors = useColors; } public boolean isShowLabels() { return showLabels; } public void setShowLabels(boolean showLabels) { this.showLabels = showLabels; } public int getNodeRadius() { return nodeRadius; } public void setNodeRadius(int nodeRadius) { this.nodeRadius = nodeRadius; } public StatusBar getStatusBar() { return statusBar; } /** * show the legend horizontal, vertical or none * */ public void setShowLegend(String showLegend) { this.showLegend = showLegend; if (showLegend.equalsIgnoreCase("horizontal")) { splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); Dimension size = new Dimension(); splitPane.validate(); legendPanel.setSize(splitPane.getWidth(), 50); legendPanel.draw((Graphics2D) legendPanel.getGraphics(), size); int height = (int) size.getHeight() + 30; legendPanel.setPreferredSize(new Dimension(splitPane.getWidth(), height)); legendPanel.validate(); splitPane.setDividerLocation(splitPane.getSize().height - splitPane.getInsets().right - splitPane.getDividerSize() - height); } else if (showLegend.equalsIgnoreCase("vertical")) { splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT); Dimension size = new Dimension(); splitPane.validate(); legendPanel.setSize(20, splitPane.getHeight()); legendPanel.draw((Graphics2D) legendPanel.getGraphics(), size); int width = (int) size.getWidth() + 5; legendPanel.setPreferredSize(new Dimension(width, splitPane.getHeight())); legendPanel.validate(); splitPane.setDividerLocation(splitPane.getSize().width - splitPane.getInsets().right - splitPane.getDividerSize() - width); } else { splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); splitPane.setDividerLocation(1.0); } } public Document getDocument() { return dir.getDocument(); } public String getShowLegend() { return showLegend; } public LegendPanel getLegendPanel() { return legendPanel; } public JScrollPane getLegendScrollPane() { return legendScrollPane; } public Map<String, LinkedList<Node>> getGroup2Nodes() { return group2Nodes; } /** * add a tab at the indicated position * * @param tab must be instance of JPanel */ public void addTab(int index, ITab tab) { JPanel panel = (JPanel) tab; tabbedPane.insertTab(tab.getLabel(), null, panel, tab.getLabel(), index); if (PCoA_TAB_INDEX >= index) PCoA_TAB_INDEX++; if (NJ_TAB_INDEX >= index) NJ_TAB_INDEX++; if (NNET_TAB_INDEX >= index) NNET_TAB_INDEX++; if (UPGMA_TAB_INDEX >= index) UPGMA_TAB_INDEX++; if (MATRIX_TAB_INDEX >= index) MATRIX_TAB_INDEX++; } /** * gets the number of selected taxon or similar ids * * @return set of selected ids */ public Set<Integer> getSelectedClassIds() { Set<Integer> set = new HashSet<>(); Classification classification = ClassificationManager.get(parentViewer.getClassName(), false); if (getTabbedIndex() == PCoA_TAB_INDEX) { PCoATab tab = getPcoaTab(); GraphView graphView = getGraphView(); for (Node v : graphView.getSelectedNodes()) { if (tab.isBiplotNode(v)) { int id = classification.getName2IdMap().get(graphView.getLabel(v)); if (id != 0) set.add(id); } } } return set; } /** * is the currently selected tab a Swing panel? Needed for export image dialog * * @return true. if swing panel */ public boolean isSwingPanel() { return getSelectedComponent() == getPcoaTab() || getSelectedComponent() == getPcoaTab() || getSelectedComponent() == getNJTab() || getSelectedComponent() == getNnetTab() || getSelectedComponent() == getUpgmaTab(); } }
36,752
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
TaxonomyClusterViewer.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/TaxonomyClusterViewer.java
/* * TaxonomyClusterViewer.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.clusteranalysis; import megan.core.ClassificationType; import megan.viewer.MainViewer; /** * network viewer for taxonomy * Daniel Huson, 5.2011 */ public class TaxonomyClusterViewer extends ClusterViewer { /** * creates a new network viewer * */ public TaxonomyClusterViewer(final MainViewer viewer) { super(viewer.getDir(), viewer, ClassificationType.Taxonomy.toString()); } }
1,248
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SyncDataTableAndNetwork.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/SyncDataTableAndNetwork.java
/* * SyncDataTableAndNetwork.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.clusteranalysis; import megan.core.DataTable; /** * sync network formatting and summary * <p/> * Daniel Huson, 9.2010 */ class SyncDataTableAndNetwork { /** * sync network formatting to summary * */ public static void syncNetworkFormatting2Summary(ClusterViewer clusterViewer, DataTable megan4Table) { System.err.println("syncNetworkFormatting2Summary(): not implemented"); } /** * sync summary to network formatting * */ public static void syncSummary2NetworkFormatting(DataTable megan4Table, ClusterViewer clusterViewer) { System.err.println("syncSummary2NetworkFormatting(): not implemented"); } }
1,506
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Distances.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/tree/Distances.java
/* * Distances.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.clusteranalysis.tree; import java.util.Vector; /** * a simple distance matrix * Daniel Huson, 5.2010 */ public class Distances { private final double[][] matrix; public Distances(int ntax) { matrix = new double[ntax][ntax]; } /** * get the value * * @param i between 1 and ntax * @param j between 1 and ntax * @return value */ public double get(int i, int j) { return matrix[i - 1][j - 1]; } /** * set the value * * @param i between 1 and ntax * @param j between 1 and ntax */ public void set(int i, int j, double value) { matrix[i - 1][j - 1] = matrix[j - 1][i - 1] = value; } /** * increment the count * */ public void increment(int i, int j) { matrix[i - 1][j - 1]++; matrix[j - 1][i - 1]++; } /** * get the number of taxa * * @return number of taxa */ public int getNtax() { return matrix.length; } /** * sets the distances from an upper triangle representation of distances * */ public void setFromUpperTriangle(Vector<Vector<Double>> upperTriangle) { for (int i = 0; i < upperTriangle.size(); i++) { matrix[i][i] = 0; Vector<Double> row = upperTriangle.get(i); for (int count = 0; count < row.size(); count++) matrix[i][i + count + 1] = matrix[i + count + 1][i] = row.get(count); } } /** * get the matrix * * @return matrix */ public double[][] getMatrix() { return matrix; } /** * replace all NaN by zero */ public boolean replaceNaNByZero() { boolean changed = false; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix.length; j++) { if (Double.isNaN(matrix[i][j])) { matrix[i][j] = 0; changed = true; } } } return changed; } }
2,868
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
UPGMA.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/tree/UPGMA.java
/* * UPGMA.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.clusteranalysis.tree; import jloda.graph.Edge; import jloda.graph.Node; import jloda.phylo.PhyloTree; import jloda.swing.graphview.NodeView; import jloda.swing.graphview.PhyloTreeView; import java.awt.geom.Point2D; import java.util.LinkedList; /** * run the UPGMA algorithm and compute an embedding * Daniel Huson, 3.2011 (enroute Frankfurt - Washington D.C.) */ public class UPGMA { private static UPGMA instance; /** * apply the UPGMA algorithm * */ public static void apply(Taxa taxa, Distances distances, PhyloTreeView treeView) { if (instance == null) instance = new UPGMA(); instance.computeUPMATree(taxa, distances, treeView.getPhyloTree()); embedTree(treeView); } /** * run the UPGMA algorithm * */ private void computeUPMATree(Taxa taxa, Distances dist, PhyloTree tree) { tree.clear(); int ntax = dist.getNtax(); Node[] subtrees = new Node[ntax + 1]; int[] sizes = new int[ntax + 1]; double[] heights = new double[ntax + 1]; for (int i = 1; i <= ntax; i++) { subtrees[i] = tree.newNode(); tree.setLabel(subtrees[i], taxa.getLabel(i)); sizes[i] = 1; } double[][] d = new double[ntax + 1][ntax + 1];// distance matix //Initialise d //Compute the closest values for each taxa. for (int i = 1; i <= ntax; i++) { for (int j = i + 1; j <= ntax; j++) { double dij = (dist.get(i, j) + dist.get(j, i)) / 2.0;// distance matix h d[i][j] = d[j][i] = dij; } } for (int actual = ntax; actual > 2; actual--) { int i_min = 0, j_min = 0; //Find closest pair. double d_min = Double.MAX_VALUE; for (int i = 1; i <= actual; i++) { for (int j = i + 1; j <= actual; j++) { double dij = d[i][j]; if (i_min == 0 || dij < d_min) { i_min = i; j_min = j; d_min = dij; } } } double height = d_min / 2.0; Node v = tree.newNode(); Edge e = tree.newEdge(v, subtrees[i_min]); tree.setWeight(e, Math.max(height - heights[i_min], 0.0)); Edge f = tree.newEdge(v, subtrees[j_min]); tree.setWeight(f, Math.max(height - heights[j_min], 0.0)); subtrees[i_min] = v; subtrees[j_min] = null; heights[i_min] = height; int size_i = sizes[i_min]; int size_j = sizes[j_min]; sizes[i_min] = size_i + size_j; for (int k = 1; k <= ntax; k++) { if ((k == i_min) || k == j_min) continue; double dki = (d[k][i_min] * size_i + d[k][j_min] * size_j) / ((double) (size_i + size_j)); d[k][i_min] = d[i_min][k] = dki; } //Copy the top row of the matrix and arrays into the empty j_min row/column. if (j_min < actual) { for (int k = 1; k <= actual; k++) { d[j_min][k] = d[k][j_min] = d[actual][k]; } d[j_min][j_min] = 0.0; subtrees[j_min] = subtrees[actual]; sizes[j_min] = sizes[actual]; heights[j_min] = heights[actual]; } } int sister = 2; while (subtrees[sister] == null) sister++; Node root = tree.newNode(); tree.setRoot(root); double w1, w2; double delta = Math.abs(heights[1] - heights[sister]); double distance = d[1][sister] - delta; if (heights[1] <= heights[sister]) { w1 = 0.5 * distance + delta; w2 = 0.5 * distance; } else { w1 = 0.5 * distance; w2 = 0.5 * distance + delta; } Edge e1 = tree.newEdge(root, subtrees[1]); tree.setWeight(e1, w1); Edge e2 = tree.newEdge(root, subtrees[sister]); tree.setWeight(e2, w2); } /** * embed the tree * */ public static void embedTree(PhyloTreeView treeView) { treeView.removeAllInternalPoints(); Node root = treeView.getPhyloTree().getRoot(); if (root != null) computeEmbeddingRec(treeView, root, null, 0, 0, true); treeView.resetViews(); for (Node v = treeView.getPhyloTree().getFirstNode(); v != null; v = v.getNext()) { treeView.setLabel(v, treeView.getPhyloTree().getLabel(v)); treeView.setLabelLayout(v, NodeView.EAST); } treeView.trans.setCoordinateRect(treeView.getBBox()); treeView.fitGraphToWindow(); } /** * recursively compute the embedding * * @param hDistToRoot horizontal distance from node to root * @param leafNumber rank of leaf in vertical ordering * @return index of last leaf */ private static int computeEmbeddingRec(PhyloTreeView view, Node v, Edge e, double hDistToRoot, int leafNumber, boolean toScale) { if (v.getDegree() == 1 && e != null) // hit a leaf { view.setLocation(v, toScale ? hDistToRoot : 0, ++leafNumber); } else { Point2D first = null; Point2D last = null; double minX = Double.MAX_VALUE; for (Edge f = v.getFirstAdjacentEdge(); f != null; f = v.getNextAdjacentEdge(f)) { if (f != e) { Node w = f.getOpposite(v); leafNumber = computeEmbeddingRec(view, w, f, hDistToRoot + view.getPhyloTree().getWeight(f), leafNumber, toScale); if (first == null) first = view.getLocation(w); last = view.getLocation(w); if (last.getX() < minX) minX = last.getX(); } } if (first != null) // always true { double x; if (toScale) x = hDistToRoot; else x = minX - 1; double y = 0.5 * (last.getY() + first.getY()); view.setLocation(v, x, y); for (Edge f = v.getFirstAdjacentEdge(); f != null; f = v.getNextAdjacentEdge(f)) { if (f != e) { Node w = f.getOpposite(v); java.util.List<Point2D> list = new LinkedList<>(); Point2D p = new Point2D.Double(x, view.getLocation(w).getY()); list.add(p); view.setInternalPoints(f, list); } } } } return leafNumber; } }
7,695
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
NJ.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/tree/NJ.java
/* * NJ.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.clusteranalysis.tree; import jloda.graph.Edge; import jloda.graph.EdgeDoubleArray; import jloda.graph.Node; import jloda.graph.NodeSet; import jloda.phylo.PhyloTree; import jloda.swing.graphview.PhyloTreeView; import jloda.swing.util.Geometry; import jloda.util.Basic; import java.util.HashMap; import java.util.Random; /** * run the NJ algorithm and compute an embedding * Daniel Huson, 9.2012 */ public class NJ { private static NJ instance; public static void apply(Taxa taxa, Distances distances, PhyloTreeView treeView) { if (instance == null) instance = new NJ(); PhyloTree tree = (PhyloTree) treeView.getGraph(); instance.computeNJ(taxa, distances, tree); instance.computeEmbedding(treeView, tree); } /** * run the UPGMA algorithm * */ private void computeNJ(Taxa taxa, Distances dist, PhyloTree tree) { tree.clear(); try { HashMap<String, Node> TaxaHashMap = new HashMap<>(); int nbNtax = dist.getNtax(); StringBuffer[] tax = new StringBuffer[nbNtax + 1]; //Taxalabels are saved as a StringBuffer array for (int i = 1; i <= nbNtax; i++) { tax[i] = new StringBuffer(); tax[i].append(taxa.getLabel(i)); Node v = tree.newNode(); // create newNode for each Taxon tree.setLabel(v, tax[i].toString()); TaxaHashMap.put(tax[i].toString(), v); } double[][] h = new double[nbNtax + 1][nbNtax + 1];// distance matix double[] b = new double[nbNtax + 1];// the b variable in Neighbor Joining int i_min = 0, j_min = 0; // needed for manipulation of h and b double temp, dist_e, dist_f;//new edge weights StringBuilder tax_old_i; //labels of taxa that are being merged StringBuilder tax_old_j; Node v; Edge e, f; //from tax_old to new=merged edge for (int i = 0; i <= nbNtax; i++) { h[0][i] = 1.0; // with 1.0 marked columns indicate columns/rows h[i][0] = 1.0;// that haven't been deleted after merging } for (int i = 1; i <= nbNtax; i++) { for (int j = 1; j <= nbNtax; j++) { //fill up the if (i < j) h[i][j] = dist.get(i, j);// distance matix h else h[i][j] = dist.get(j, i); } } // calculate b: for (int i = 1; i <= nbNtax; i++) { for (int j = 1; j <= nbNtax; j++) { b[i] += h[i][j]; } } // recall: int i_min=0, j_min=0; // actual for (finding all nearest Neighbors) for (int actual = nbNtax; actual > 2; actual--) { // find: min D (h, b, b) double d_min = Double.MAX_VALUE; for (int i = 1; i < nbNtax; i++) { if (h[0][i] == 0.0) continue; for (int j = i + 1; j <= nbNtax; j++) { if (h[0][j] == 0.0) continue; if (h[i][j] - ((b[i] + b[j]) / (actual - 2)) < d_min) { d_min = h[i][j] - ((b[i] + b[j]) / (actual - 2)); i_min = i; j_min = j; } } } dist_e = 0.5 * (h[i_min][j_min] + b[i_min] / (actual - 2) - b[j_min] / (actual - 2)); dist_f = 0.5 * (h[i_min][j_min] + b[j_min] / (actual - 2) - b[i_min] / (actual - 2)); h[j_min][0] = 0.0;// marking h[0][j_min] = 0.0; // tax taxa rescan: tax_old_i = new StringBuilder(tax[i_min].toString()); tax_old_j = new StringBuilder(tax[j_min].toString()); tax[i_min].insert(0, "("); tax[i_min].append(","); tax[i_min].append(tax[j_min]); tax[i_min].append(")"); tax[j_min].delete(0, tax[j_min].length()); // b rescan: b[i_min] = 0.0; b[j_min] = 0.0; // fusion of h // double h_min = h[i_min][j_min]; for (int i = 1; i <= nbNtax; i++) { if (h[0][i] == 0.0) continue; //temp=(h[i][i_min] + h[i][j_min] - h_min)/2; This is incorrect temp = (h[i][i_min] + h[i][j_min] - dist_e - dist_f) / 2; // correct NJ if (i != i_min) { b[i] = b[i] - h[i][i_min] - h[i][j_min] + temp; } b[i_min] += temp; h[i][i_min] = temp; b[j_min] = 0.0; } for (int i = 0; i <= nbNtax; i++) { h[i_min][i] = h[i][i_min]; h[i][j_min] = 0.0; h[j_min][i] = 0.0; } // generate new Node for merged Taxa: v = tree.newNode(); TaxaHashMap.put(tax[i_min].toString(), v); // generate Edges from two Taxa that are merged to one: e = tree.newEdge(TaxaHashMap.get(tax_old_i.toString()), v); tree.setWeight(e, Math.max(dist_e, 0.0)); f = tree.newEdge(TaxaHashMap.get(tax_old_j.toString()), v); tree.setWeight(f, Math.max(dist_f, 0.0)); } // evaluating last two nodes: for (int i = 1; i <= nbNtax; i++) { if (h[0][i] == 1.0) { i_min = i; i++; for (; i <= nbNtax; i++) { if (h[0][i] == 1.0) { j_min = i; } } } } tax_old_i = new StringBuilder(tax[i_min].toString()); tax_old_j = new StringBuilder(tax[j_min].toString()); tax[i_min].insert(0, "("); tax[i_min].append(","); tax[i_min].append(tax[j_min]); tax[i_min].append(")"); tax[j_min].delete(0, tax[j_min].length()); //not neces. but sets content to NULL // generate new Node for merged Taxa: // generate Edges from two Taxa that are merged to one: e = tree.newEdge(TaxaHashMap.get (tax_old_i.toString()), TaxaHashMap.get(tax_old_j.toString())); tree.setWeight(e, Math.max(h[i_min][j_min], 0.0)); } catch (Exception ex) { Basic.caught(ex); } //System.err.println(tree.toString()); } /** * compute an embedding of the graph */ private void computeEmbedding(PhyloTreeView treeView, PhyloTree tree) { treeView.removeAllInternalPoints(); if (tree.getNumberOfNodes() == 0) return; treeView.removeAllInternalPoints(); // don't use setRoot to remember root Node root = tree.getFirstNode(); NodeSet leaves = new NodeSet(tree); for (Node v = tree.getFirstNode(); v != null; v = tree.getNextNode(v)) { if (tree.getDegree(v) == 1) leaves.add(v); if (tree.getDegree(v) > tree.getDegree(root)) root = v; } // recursively visit all nodes in the tree and determine the // angle 0-2PI of each edge. nodes are placed around the unit // circle at position // n=1,2,3,... and then an edge along which we visited nodes // k,k+1,...j-1,j is directed towards positions k,k+1,...,j EdgeDoubleArray angle = new EdgeDoubleArray(tree); // angle of edge Random rand = new Random(); rand.setSeed(1); int seen = setAnglesRec(tree, 0, root, null, leaves, angle, rand); if (seen != leaves.size()) System.err.println("Warning: Number of nodes seen: " + seen + " != Number of leaves: " + leaves.size()); // recursively compute node coordinates from edge angles: setCoordsRec(treeView, tree, root, null, angle); treeView.trans.setCoordinateRect(treeView.getBBox()); treeView.resetViews(); treeView.fitGraphToWindow(); } /** * Recursively determines the angle of every tree edge. * * @param num int * @param root Node * @param entry Edge * @param leaves NodeSet * @param angle EdgeDoubleArray * @param rand Random * @return b int */ private int setAnglesRec(PhyloTree tree, int num, Node root, Edge entry, NodeSet leaves, EdgeDoubleArray angle, Random rand) { if (leaves.contains(root)) return num + 1; else { // edges.permute(); // look at children in random order int a = num; // is number of nodes seen so far int b = 0; // number of nodes after visiting subtree for (Edge e : root.adjacentEdges()) { if (e != entry) { b = setAnglesRec(tree, a, tree.getOpposite(root, e), e, leaves, angle, rand); // point towards the segment of the unit circle a...b: angle.put(e, Math.PI * (a + 1 + b) / leaves.size()); a = b; } } if (b == 0) System.err.println("Warning: setAnglesRec: recursion failed"); return b; } } /** * recursively compute node coordinates from edge angles: * * @param root Node * @param entry Edge * @param angle EdgeDouble */ private void setCoordsRec(PhyloTreeView treeView, PhyloTree tree, Node root, Edge entry, EdgeDoubleArray angle) { for (Edge e : root.adjacentEdges()) { if (e != entry) { Node v = tree.getOpposite(root, e); // translate in the computed direction by the given amount treeView.setLocation(v, Geometry.translateByAngle(treeView.getLocation(root), angle.getDouble(e), tree.getWeight(e))); setCoordsRec(treeView, tree, v, e, angle); } } } }
11,373
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Taxa.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/tree/Taxa.java
/* * Taxa.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.clusteranalysis.tree; import java.util.*; /** * maintains the taxa associated with a tree or network * Daniel Huson, 6.2007 */ public class Taxa { private final Map<String, Integer> name2index; private final Map<Integer, String> index2name; private final BitSet bits; private int ntax; /** * constructor */ public Taxa() { name2index = new HashMap<>(); index2name = new HashMap<>(); bits = new BitSet(); ntax = 0; } /** * get the t-th taxon (numbered 1-size) * * @return name of t-th taxon */ public String getLabel(int t) { return index2name.get(t); } /** * index of the named taxon, or -1 * * @return index or -1 */ public int indexOf(String name) { Integer index = name2index.get(name); return Objects.requireNonNullElse(index, -1); } /** * add the named taxon * */ public void add(String name) { if (!name2index.containsKey(name)) { ntax++; bits.set(ntax); Integer index = ntax; index2name.put(index, name); name2index.put(name, index); } else { name2index.get(name); } } /** * does this taxa object contain the named taxon? * * @return true, if contained */ public boolean contains(String name) { return indexOf(name) != -1; } /** * get the number of taxa * * @return number of taxa */ public int size() { return bits.cardinality(); } /** * gets the maximal defined taxon id * * @return max id */ public int maxId() { int t = -1; while (true) { int s = bits.nextSetBit(t + 1); if (s == -1) return t; else t = s; } } /** * erase all taxa */ public void clear() { ntax = 0; bits.clear(); index2name.clear(); name2index.clear(); } /** * gets the complement to bit set A * * @return complement */ public BitSet getComplement(BitSet A) { BitSet result = new BitSet(); for (int t = 1; t <= ntax; t++) { if (!A.get(t)) result.set(t); } return result; } /** * add all taxa. * */ public void addAll(Taxa taxa) { for (Iterator it = taxa.iterator(); it.hasNext(); ) { String name = (String) it.next(); add(name); } } /** * gets string representation * * @return string */ public String toString() { StringBuilder buf = new StringBuilder(); buf.append("Taxa (").append(size()).append("):\n"); for (Iterator it = iterator(); it.hasNext(); ) { String name = (String) it.next(); buf.append(name).append("\n"); } return buf.toString(); } /** * gets an getLetterCodeIterator over all taxon names * * @return getLetterCodeIterator */ public Iterator iterator() { return name2index.keySet().iterator(); } /** * gets the bits of this set * * @return bits */ public BitSet getBits() { return bits; } /** * remove this taxon * */ public void remove(String name) { Integer tt = name2index.get(name); if (tt != null) { name2index.keySet().remove(name); index2name.remove(tt); ntax--; bits.set(tt, false); } } public Iterable<Integer> members() { return () -> new Iterator<>() { private int t = bits.nextSetBit(0); @Override public boolean hasNext() { return t != -1; } @Override public Integer next() { final int result = t; t = bits.nextSetBit(t + 1); return result; } }; } }
4,936
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
PearsonDistance.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/indices/PearsonDistance.java
/* * PearsonDistance.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.clusteranalysis.indices; import jloda.graph.Node; import megan.clusteranalysis.tree.Distances; import megan.viewer.ClassificationViewer; import java.util.HashSet; import java.util.LinkedList; /** * Pearson's correlation distance * Daniel Huson, 9.2012 */ public class PearsonDistance { public static final String NAME = "Pearsons-Correlation"; /** * apply the PearsonDistance computation to the given classification * * @return number of nodes used to compute value */ public static int apply(final ClassificationViewer viewer, final Distances distances) { System.err.println("Computing " + NAME + " distances"); double[][] vectors = computeVectors(viewer, distances.getNtax()); int rank = distances.getNtax(); computeCorrelationMatrix(rank, vectors, distances); convertCorrelationsToDistances(distances); return vectors.length; } /** * compute vectors for analysis * * @return vectors. First index is class, second is sample */ private static double[][] computeVectors(ClassificationViewer graphView, int numberOfSamples) { double[] total = new double[numberOfSamples]; HashSet<Integer> seen = new HashSet<>(); LinkedList<double[]> rows = new LinkedList<>(); for (Node v = graphView.getGraph().getFirstNode(); v != null; v = v.getNext()) { if (graphView.getSelected(v)) { if (!seen.contains(v.getInfo())) { seen.add((Integer) v.getInfo()); double[] row = new double[numberOfSamples]; final float[] values = (v.getOutDegree() == 0 ? graphView.getNodeData(v).getSummarized() : graphView.getNodeData(v).getAssigned()); for (int i = 0; i < values.length; i++) { row[i] = values[i]; total[i] += row[i]; } rows.add(row); } } } for (double[] row : rows) { for (int i = 0; i < row.length; i++) { if (total[i] > 0) row[i] /= total[i]; } } return rows.toArray(new double[rows.size()][]); } /** * computes the pearson distances * */ private static void computeCorrelationMatrix(int rank, double[][] vectors, Distances distances) { // compute mean for each row double[] mean = new double[rank]; for (double[] row : vectors) { for (int col = 0; col < rank; col++) { mean[col] += row[col]; } } for (int col = 0; col < rank; col++) { mean[col] /= vectors.length; } double[] stddev = new double[rank]; for (double[] row : vectors) { for (int col = 0; col < rank; col++) { stddev[col] += (row[col] - mean[col]) * (row[col] - mean[col]); } } for (int col = 0; col < rank; col++) { stddev[col] = Math.sqrt(stddev[col] / vectors.length); } for (int di = 0; di < rank; di++) { distances.set(di + 1, di + 1, 0); for (int dj = di + 1; dj < rank; dj++) { double cor = 0; for (double[] row : vectors) { cor += (row[di] - mean[di]) * (row[dj] - mean[dj]) / (stddev[di] * stddev[dj]); } cor /= vectors.length; distances.set(di + 1, dj + 1, cor); } } } /** * convert correlations into distances by subtracting from 1 and dividing by 2 * */ private static void convertCorrelationsToDistances(Distances distances) { for (int i = 1; i <= distances.getNtax(); i++) { for (int j = i + 1; j <= distances.getNtax(); j++) { distances.set(i, j, (1.0 - distances.get(i, j) * distances.get(i, j))); } } } }
4,818
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DistancesManager.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/indices/DistancesManager.java
/* * DistancesManager.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.clusteranalysis.indices; import jloda.util.CanceledException; import megan.clusteranalysis.tree.Distances; import megan.viewer.ClassificationViewer; import megan.viewer.MainViewer; import java.util.Arrays; public class DistancesManager { private static String[] names; /** * apply the named method * */ public static void apply(String method, final ClassificationViewer viewer, final Distances distances) throws CanceledException { if (method.equalsIgnoreCase(UniFrac.UnweightedUniformUniFrac)) { UniFrac.applyUnweightedUniformUniFrac((MainViewer) viewer, 1, distances); } else if (method.equalsIgnoreCase(UniFrac.WeightedUniformUniFrac)) { UniFrac.applyWeightedUniformUniFrac(viewer, distances); } else if (method.equalsIgnoreCase(JensenShannonDivergence.NAME)) { JensenShannonDivergence.apply(viewer, distances); } else if (method.equalsIgnoreCase(PearsonDistance.NAME)) { PearsonDistance.apply(viewer, distances); } else if (method.equalsIgnoreCase(EuclideanDistance.NAME)) { EuclideanDistance.apply(viewer, distances); } else if (method.equalsIgnoreCase(KulczynskiDistance.NAME)) { KulczynskiDistance.apply(viewer, distances); } else if (method.equalsIgnoreCase(ChiSquareDistance.NAME)) { ChiSquareDistance.apply(viewer, distances); } else if (method.equalsIgnoreCase(HellingerDistance.NAME)) { HellingerDistance.apply(viewer, distances); } else if (method.equalsIgnoreCase(GoodallsDistance.NAME)) { GoodallsDistance.apply(viewer, method, distances); } else // Bray-Curtis { BrayCurtisDissimilarity.apply(viewer, distances); } } /** * get names of all known distance calculations * * @return names */ public static String[] getAllNames() { if (names == null) { names = new String[]{ UniFrac.UnweightedUniformUniFrac, UniFrac.WeightedUniformUniFrac, JensenShannonDivergence.NAME, PearsonDistance.NAME, EuclideanDistance.NAME, KulczynskiDistance.NAME, ChiSquareDistance.NAME, HellingerDistance.NAME, GoodallsDistance.NAME, BrayCurtisDissimilarity.NAME}; Arrays.sort(names); } return names; } }
3,333
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ChiSquareDistance.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/indices/ChiSquareDistance.java
/* * ChiSquareDistance.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.clusteranalysis.indices; import jloda.graph.Node; import megan.clusteranalysis.tree.Distances; import megan.viewer.ClassificationViewer; /** * compute the ChiSquare metric between any two samples * Daniel Huson, 6.2018 */ public class ChiSquareDistance { public static final String NAME = "ChiSquare"; /** * compute the ChiSquare metric between any two samples * * @return number of nodes used to compute value */ public static int apply(final ClassificationViewer viewer, final Distances distances) { System.err.println("Computing " + NAME + " distances"); final int nTax = distances.getNtax(); final double[][] matrix = distances.getMatrix(); for (int s = 0; s < nTax; s++) { for (int t = s + 1; t < nTax; t++) { matrix[s][t] = 0; } } final double[] total = new double[nTax]; for (Node v : viewer.getSelectedNodes()) { final float[] count = (v.getOutDegree() == 0 ? viewer.getNodeData(v).getSummarized() : viewer.getNodeData(v).getAssigned()); for (int s = 0; s < nTax; s++) total[s] += count[s]; } for (Node v : viewer.getSelectedNodes()) { final float[] count = (v.getOutDegree() == 0 ? viewer.getNodeData(v).getSummarized() : viewer.getNodeData(v).getAssigned()); for (int s = 0; s < nTax; s++) { final double p = (total[s] > 0 ? count[s] / total[s] : 0); for (int t = s + 1; t < nTax; t++) { final double q = (total[t] > 0 ? count[t] / total[t] : 0); if (p + q > 0) { matrix[s][t] += Math.pow(p - q, 2) / (p + q); } } } } for (int s = 0; s < nTax; s++) { for (int t = s + 1; t < nTax; t++) { matrix[s][t] = matrix[t][s] = 2 * matrix[s][t]; } } return viewer.getSelectedNodes().size(); } }
2,862
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
GoodallsDistance.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/indices/GoodallsDistance.java
/* * GoodallsDistance.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.clusteranalysis.indices; import jloda.graph.Node; import megan.clusteranalysis.tree.Distances; import megan.viewer.ClassificationViewer; import java.util.HashSet; import java.util.Vector; /** * computes the ecological distances * Suparna Mitra, 2011 */ public class GoodallsDistance { public static final String NAME = "Goodall"; /** * apply the named computation * */ public static int apply(ClassificationViewer viewer, String method, Distances distances) { System.err.println("Computing " + method + " distances"); // setup input data: Vector<Double[]> input = new Vector<>(); double[] total = new double[viewer.getNumberOfDatasets()]; int countNodesUsed = 0; HashSet<Integer> seen = new HashSet<>(); for (Node v = viewer.getGraph().getFirstNode(); v != null; v = v.getNext()) { Integer id = (Integer) v.getInfo(); if (viewer.getSelected(v)) { if (!seen.contains(id)) { seen.add(id); countNodesUsed++; final float[] counts = (v.getOutDegree() == 0 ? viewer.getNodeData(v).getSummarized() : viewer.getNodeData(v).getAssigned()); final Double[] numbers = new Double[counts.length]; for (int i = 0; i < counts.length; i++) { numbers[i] = (double) counts[i]; total[i] += numbers[i]; } input.addElement(numbers); } } } for (Double[] numbers : input) { for (int i = 0; i < numbers.length; i++) { if (total[i] > 0) { numbers[i] /= total[i]; } } } System.err.println("Nodes used: " + seen.size()); distances.setFromUpperTriangle(getGoodallsDistance(input, true)); return countNodesUsed; } /* * evaluate range */ private static Vector<Double> getRange(Vector<Double[]> numbers) { Vector<Double> range = new Vector<>(); for (Double[] array : numbers) { double min = Double.POSITIVE_INFINITY; double max = Double.NEGATIVE_INFINITY; for (Double d : array) { if (!Double.isNaN(d)) { if (d < min) min = d; if (d > max) max = d; } } range.add(max - min); } return range; } /* * transpose vector with Double[] inside * species names excluded,so that type String is not to need * then normalize the values in each column */ private static Vector<Double[]> transpose(Vector<Double[]> numbers, boolean normalized) { int row_l = numbers.get(0).length; int col_l = numbers.size(); Vector<Double[]> res = new Vector<>(); for (int i = 0; i < row_l; i++) { Double[] d = new Double[col_l]; double sum = 0.0; // System.err.print(i + ". column of raw data "); for (int j = 0; j < col_l; j++) { d[j] = numbers.get(j)[i]; sum += d[j]; // System.err.print(Math.round(d[j]) + " "); } // System.err.println("sum=" + sum); /*normalize*/ if (normalized) { for (int c = 0; c < d.length; c++) { d[c] = d[c] * 4000 / sum; } /*printing*/ // System.err.print(i + ". column of normalized "); // for (double single : d) { // System.err.print(Math.round(single) + " "); // } // System.err.println(); } res.add(d); } return res; } /* * half diagonal table of GowerCoefficient * a Vector<Double[]> means one column of the table */ private static Vector<Vector<Double[]>> getGowerCoefficient(Vector<Double[]> numbers, Vector<Double> range) { Vector<Vector<Double[]>> res = new Vector<>(); for (int i = 0; i < numbers.size() - 1; i++) { Vector<Double[]> column = new Vector<>(); for (int j = i + 1; j < numbers.size(); j++) { Double[] d1 = numbers.get(i); Double[] d2 = numbers.get(j); int len = d1.length; Double[] s = new Double[len]; for (int k = 0; k < len; k++) { /* * calculate s value */ if (d1[k] == 0.0 && d2[k] == 0.0) s[k] = 0.0; else s[k] = 1.0 - Math.abs(d1[k] - d2[k]) / range.get(k); } column.add(s); } res.add(column); } return res; } /* * evaluate the pair ratio of one vector(one row) */ private static Double[] pairRatio(Double[] row) { Double[] res = new Double[row.length]; for (int i = 0; i < row.length; i++) { int count = 0; boolean existNaN = false; for (Double e : row) { if (!Double.isNaN(e)) { if (e >= row[i]) count++; } else existNaN = true; } if (!existNaN) res[i] = (count + 0.0) / row.length; else res[i] = Double.NaN; } return res; } /* * evaluate pair ratios of one table * in the result: * a array of Double means one row(values for a same spice) in table */ private static Vector<Double[]> getPairRatioMatrix(Vector<Double[]> gower) { Vector<Double[]> rowindouble = new Vector<>(); int len = gower.get(0).length; int size = gower.size(); for (int i = 0; i < len; i++) { Double[] row = new Double[size]; for (int j = 0; j < size; j++) { row[j] = gower.get(j)[i]; } rowindouble.add(row); } Vector<Double[]> res = new Vector<>(); for (int k = 0; k < len; k++) { res.add(pairRatio(rowindouble.get(k))); } return res; } private static Vector<Double> getSumOfLogVector(Vector<Double[]> pairRatioMatrix) { Vector<Double> res = new Vector<>(); int len = pairRatioMatrix.get(0).length; for (int i = 0; i < len; i++) { double sum = 0.0; for (Double[] darray : pairRatioMatrix) { if (!Double.isNaN(darray[i])) sum += Math.log10(darray[i]); } res.add(sum); } return res; } /* * evaluate site. sym. vector via pairRatio() */ private static Vector<Vector<Double>> getSiteSym(Vector<Double> productVector) { Vector<Vector<Double>> res = new Vector<>(); /*convert into array for application of pairRatio*/ Double[] toArray = new Double[productVector.size()]; for (int k = 0; k < productVector.size(); k++) { toArray[k] = productVector.get(k); } Double[] pairratio = pairRatio(toArray); /*num is the number of data sets * index is the pointer on the array * */ int num = (int) (1 + Math.sqrt(1 + 8 * productVector.size())) / 2; int index = 0; /*adding element in 2 dimension vector ,so that the * result looks like half triangle*/ for (int i = 0; i < num - 1; i++) { Vector<Double> newRow = new Vector<>(); for (int j = i + 1; j < num; j++) { newRow.add(pairratio[index++]); } res.add(newRow); } return res; } /* * return inverse of vector */ private static Vector<Vector<Double>> getSiteDist(Vector<Vector<Double>> siteSym) { Vector<Vector<Double>> res = new Vector<>(); for (Vector<Double> row : siteSym) { Vector<Double> newRow = new Vector<>(); for (Double pi : row) { Double inverse = 1.0 - pi; newRow.add(inverse); } res.add(newRow); } return res; } /** * computes Goodall's distance * * @return Goodall's */ private static Vector<Vector<Double>> getGoodallsDistance(Vector<Double[]> numbers, boolean normalized) { Vector<Double> range = getRange(numbers); Vector<Double[]> transpose = transpose(numbers, normalized); /* System.err.println("Range: " + range); System.err.println("tranposed:"); for (Double[] value : transpose) { for (Double v : value) System.err.print(v + ", "); System.err.println(); } */ Vector<Vector<Double[]>> gowercoeffi1 = getGowerCoefficient(transpose, range); //System.err.println("gowercoeffi done"); /*column-product vector*/ Vector<Double[]> gowercoeffi2 = new Vector<>(); for (Vector<Double[]> vectordarray : gowercoeffi1) { gowercoeffi2.addAll(vectordarray); } Vector<Double[]> pairratio = getPairRatioMatrix(gowercoeffi2); // System.err.println("pairratio done"); //Vector<Double> prod = obj.getProductVector(pairratio); Vector<Double> sum = getSumOfLogVector(pairratio); // System.err.println("Vector done"); /* System.err.println("Vector:"); for (Double value : sum) { System.err.println(value); } */ /*site.dist vector*/ //Vector<Vector<Double>> sitedist = obj.getSiteDist(obj.getSiteSym(prod)); return getSiteDist(getSiteSym(sum)); } }
10,661
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
UniFrac.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/indices/UniFrac.java
/* * UniFrac.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.clusteranalysis.indices; import jloda.graph.*; import jloda.phylo.PhyloTree; import jloda.util.CanceledException; import jloda.util.StringUtils; import jloda.util.progress.ProgressListener; import megan.clusteranalysis.tree.Distances; import megan.viewer.ClassificationViewer; import megan.viewer.MainViewer; import megan.viewer.TaxonomicLevels; import megan.viewer.TaxonomyData; /** * unweighted and weighted distance * Daniel Huson, 9.2012, 11.2017, 6.2018 */ public class UniFrac { public final static String UnweightedUniformUniFrac = "UnweightedUniformUniFrac"; public final static String WeightedUniformUniFrac = "WeightedUniformUniFrac"; /** * apply the unweighted taxonomic unifrac method * * @param distances for each pair of samples i and j, the proportion of ranked nodes in which either sample i or j has a none-zero count, but not both * @return number of nodes used to compute value */ public static int applyUnweightedUniformUniFrac(final MainViewer viewer, final int threshold, final Distances distances) throws CanceledException { System.err.println("Computing " + StringUtils.fromCamelCase(UnweightedUniformUniFrac) + " distances"); final int nTax = distances.getNtax(); int countNodesUsed = 0; final PhyloTree tree = viewer.getTree(); final NodeSet inducedNodes = new NodeSet(tree); inducedNodes.addAll(viewer.getSelectedNodes()); final NodeArray<float[]> summarized = new NodeArray<>(tree); computeSummarizedCountsOnInducedTreeRec(tree.getRoot(), inducedNodes, viewer, summarized, nTax); removeRootNodeAndNodesOnPathLeadingToIt(tree.getRoot(), inducedNodes); int[][] diff = new int[nTax][nTax]; final ProgressListener progress = viewer.getDocument().getProgressListener(); progress.setTasks("Computing", "Unweighted uniform UniFrac"); progress.setProgress(0); progress.setMaximum(inducedNodes.size()); for (Node v : inducedNodes) { final int taxonId = (Integer) v.getInfo(); if (taxonId > 0 && TaxonomicLevels.isMajorRank(TaxonomyData.getTaxonomicRank(taxonId))) // only use proper nodes { countNodesUsed++; final float[] counts = summarized.get(v); for (int s = 0; s < nTax; s++) { for (int t = s + 1; t < nTax; t++) { if ((counts[s] >= threshold) != (counts[t] >= threshold)) diff[s][t]++; } } } progress.incrementProgress(); } for (int s = 0; s < nTax; s++) { for (int t = s + 1; t < nTax; t++) { distances.set(s + 1, t + 1, (countNodesUsed > 0 ? (double) diff[s][t] / (double) countNodesUsed : 0)); } } System.err.println("Nodes used: " + countNodesUsed); return countNodesUsed; } /** * apply the named computation to the taxonomy * * @param distances for each pair of samples i and j, the sum of absolute differences of summarized counts (not assigned counts!) on each node, normalized * such that two identical profiles get distance 0 and two disjoint profiles get distance 1 * @return number of nodes used to compute value */ public static int applyWeightedUniformUniFrac(final ClassificationViewer viewer, final Distances distances) throws CanceledException { System.err.println("Computing " + StringUtils.fromCamelCase(WeightedUniformUniFrac) + " distances"); final int nTax = distances.getNtax(); int countNodesUsed = 0; final PhyloTree tree = viewer.getTree(); final NodeSet inducedNodes = new NodeSet(tree); inducedNodes.addAll(viewer.getSelectedNodes()); final NodeArray<float[]> summarized = new NodeArray<>(tree); computeSummarizedCountsOnInducedTreeRec(tree.getRoot(), inducedNodes, viewer, summarized, nTax); final ProgressListener progress = viewer.getDocument().getProgressListener(); progress.setTasks("Computing", "Weighted uniform UniFrac"); progress.setProgress(0); progress.setMaximum(2L * inducedNodes.size()); final Node root = removeRootNodeAndNodesOnPathLeadingToIt(tree.getRoot(), inducedNodes); // setup total number of reads in each sample summarized below the root final double[] total = new double[nTax]; { for (Edge e : root.outEdges()) { final Node w = e.getTarget(); if (inducedNodes.contains(w)) { for (int s = 0; s < nTax; s++) total[s] += summarized.get(w)[s]; } } } final double[][] diff = new double[nTax][nTax]; // difference between two samples final double[][] sum = new double[nTax][nTax]; // largest possible difference between two samples for (Node v : inducedNodes) { final int taxonId = (Integer) v.getInfo(); if (taxonId > 0 && TaxonomicLevels.isMajorRank(TaxonomyData.getTaxonomicRank(taxonId))) // only use proper nodes { countNodesUsed++; final float[] count = summarized.get(v); // total number of reads that "descend" from node v for (int s = 0; s < nTax; s++) { final double p = (total[s] > 0 ? count[s] / total[s] : 0); for (int t = s + 1; t < nTax; t++) { final double q = (total[t] > 0 ? count[t] / total[t] : 0); diff[s][t] += Math.abs(p - q); // normalized differences between datasets sum[s][t] += (p + q); } } } progress.incrementProgress(); } for (int s = 0; s < nTax; s++) { for (int t = s + 1; t < nTax; t++) { distances.set(s + 1, t + 1, (sum[s][t] > 0 ? diff[s][t] / sum[s][t] : 0)); } } return countNodesUsed; } /** * recursively compute the summarized counts for all nodes in tree induced by user selection * * @return true, if selected nodes on or below v */ private static boolean computeSummarizedCountsOnInducedTreeRec(Node v, NodeSet selected, ClassificationViewer viewer, NodeArray<float[]> summarized, int ntax) { float[] currentSummarized = null; for (Edge e : v.outEdges()) { if (computeSummarizedCountsOnInducedTreeRec(e.getTarget(), selected, viewer, summarized, ntax)) { if (currentSummarized == null) { currentSummarized = new float[ntax]; } final float[] childSummarized = summarized.get(e.getTarget()); for (int s = 0; s < ntax; s++) { currentSummarized[s] += childSummarized[s]; } } } final NodeData nodeData = viewer.getNodeData(v); if (currentSummarized != null) { // has selected below for (int s = 0; s < ntax; s++) // add counts for current node currentSummarized[s] += nodeData.getAssigned()[s]; summarized.put(v, currentSummarized); selected.add(v); return true; } else if (selected.contains(v)) { // nothing selected below, but this node is selected, so it is a selection leaf summarized.put(v, nodeData.getSummarized()); return true; } else return false; } /** * remove the root node and root path * * @return the root */ private static Node removeRootNodeAndNodesOnPathLeadingToIt(Node v, NodeSet induced) { while (true) { induced.remove(v); Node selectedChild = null; for (Edge e : v.outEdges()) { if (induced.contains(e.getTarget())) { if (selectedChild == null) selectedChild = e.getTarget(); else return v; // more than one selected child, done } } if (selectedChild == null) // no selected children below, then degenerate case... return v; else v = selectedChild; } } }
9,264
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
HellingerDistance.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/indices/HellingerDistance.java
/* * HellingerDistance.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.clusteranalysis.indices; import jloda.graph.Node; import megan.clusteranalysis.tree.Distances; import megan.viewer.ClassificationViewer; /** * compute the Hellinger metric between any two samples * Daniel Huson, 6.2018 */ public class HellingerDistance { public static final String NAME = "Hellinger"; /** * compute the Hellinger metric between any two samples * * @return number of nodes used to compute value */ public static int apply(final ClassificationViewer viewer, final Distances distances) { System.err.println("Computing " + NAME + " distances"); final int nTax = distances.getNtax(); final double[][] matrix = distances.getMatrix(); for (int s = 0; s < nTax; s++) { for (int t = s + 1; t < nTax; t++) { matrix[s][t] = 0; } } final double[] total = new double[nTax]; for (Node v : viewer.getSelectedNodes()) { final float[] count = (v.getOutDegree() == 0 ? viewer.getNodeData(v).getSummarized() : viewer.getNodeData(v).getAssigned()); for (int s = 0; s < nTax; s++) total[s] += count[s]; } for (Node v : viewer.getSelectedNodes()) { final float[] count = (v.getOutDegree() == 0 ? viewer.getNodeData(v).getSummarized() : viewer.getNodeData(v).getAssigned()); for (int s = 0; s < nTax; s++) { final double p = (total[s] > 0 ? count[s] / total[s] : 0); for (int t = s + 1; t < nTax; t++) { final double q = (total[t] > 0 ? count[t] / total[t] : 0); matrix[s][t] += Math.pow(Math.sqrt(p) - Math.sqrt(q), 2); } } } for (int s = 0; s < nTax; s++) { for (int t = s + 1; t < nTax; t++) { matrix[s][t] = matrix[t][s] = Math.sqrt(matrix[s][t]); } } return viewer.getSelectedNodes().size(); } }
2,818
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BrayCurtisDissimilarity.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/indices/BrayCurtisDissimilarity.java
/* * BrayCurtisDissimilarity.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.clusteranalysis.indices; import jloda.graph.Node; import megan.clusteranalysis.tree.Distances; import megan.viewer.ClassificationViewer; /** * compute the Bray Curtis dissimilarity * Daniel Huson, 6.2018 */ public class BrayCurtisDissimilarity { public static final String NAME = "Bray-Curtis"; /** * compute the Bray Curtis dissimilarity * * @return number of nodes used to compute value */ public static int apply(final ClassificationViewer viewer, final Distances distances) { System.err.println("Computing " + NAME + " distances"); final int nSamples = distances.getNtax(); final double[] total = new double[nSamples]; for (Node v : viewer.getSelectedNodes()) { final float[] count = (v.getOutDegree() == 0 ? viewer.getNodeData(v).getSummarized() : viewer.getNodeData(v).getAssigned()); for (int s = 0; s < nSamples; s++) total[s] += count[s]; } final float[][] lesser = new float[nSamples][nSamples]; final float[][] sum = new float[nSamples][nSamples]; for (Node v : viewer.getSelectedNodes()) { final float[] count = (v.getOutDegree() == 0 ? viewer.getNodeData(v).getSummarized() : viewer.getNodeData(v).getAssigned()); for (int s = 0; s < nSamples; s++) { final double p = (total[s] > 0 ? count[s] / total[s] : 0); for (int t = s + 1; t < nSamples; t++) { final double q = (total[t] > 0 ? count[t] / total[t] : 0); lesser[s][t] += Math.min(p, q); sum[s][t] += p + q; } } } for (int s = 0; s < nSamples; s++) { for (int t = s + 1; t < nSamples; t++) { if (sum[s][t] > 0) distances.set(s + 1, t + 1, 1 - 2 * lesser[s][t] / sum[s][t]); else distances.set(s + 1, t + 1, 0); } } return viewer.getSelectedNodes().size(); } }
2,884
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
KulczynskiDistance.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/indices/KulczynskiDistance.java
/* * KulczynskiDistance.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.clusteranalysis.indices; import jloda.graph.Node; import megan.clusteranalysis.tree.Distances; import megan.viewer.ClassificationViewer; /** * compute the Kulczynski metric between any two samples * Daniel Huson, 6.2018 */ public class KulczynskiDistance { public static final String NAME = "Kulczynski"; /** * compute the Kulczynski metric between any two samples * * @return number of nodes used to compute value */ public static int apply(final ClassificationViewer viewer, final Distances distances) { System.err.println("Computing " + NAME + " distances"); final int nSamples = distances.getNtax(); final double[] total = new double[nSamples]; for (Node v : viewer.getSelectedNodes()) { final float[] count = (v.getOutDegree() == 0 ? viewer.getNodeData(v).getSummarized() : viewer.getNodeData(v).getAssigned()); for (int s = 0; s < nSamples; s++) total[s] += count[s]; } final float[][] lesser = new float[nSamples][nSamples]; final float[] sum = new float[nSamples]; // normalized sum, not the same as total! for (Node v : viewer.getSelectedNodes()) { final float[] count = (v.getOutDegree() == 0 ? viewer.getNodeData(v).getSummarized() : viewer.getNodeData(v).getAssigned()); for (int s = 0; s < nSamples; s++) { final double p = (total[s] > 0 ? count[s] / total[s] : 0); sum[s] += p; for (int t = s + 1; t < nSamples; t++) { final double q = (total[t] > 0 ? count[t] / total[t] : 0); lesser[s][t] += Math.min(p, q); } } } for (int s = 0; s < nSamples; s++) { for (int t = s + 1; t < nSamples; t++) { if (total[s] > 0 && total[t] > 0) distances.set(s + 1, t + 1, 1 - 0.5 * (lesser[s][t] / sum[s] + lesser[s][t] / sum[t])); else distances.set(s + 1, t + 1, 0); } } return viewer.getSelectedNodes().size(); } }
2,966
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
JensenShannonDivergence.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/indices/JensenShannonDivergence.java
/* * JensenShannonDivergence.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.clusteranalysis.indices; import jloda.graph.Node; import jloda.util.StringUtils; import megan.clusteranalysis.tree.Distances; import megan.core.Document; import megan.viewer.ViewerBase; /** * Jensen shannon divergence * See: http://enterotype.embl.de/enterotypes.html * Daniel Huson, 9.2014 */ public class JensenShannonDivergence { public static final String NAME = "SqrtJensenShannonDivergence"; /** * apply the named computation to the taxonomy * * @return number of nodes used to compute value */ public static int apply(final ViewerBase viewer, final Distances distances) { System.err.println("Computing " + StringUtils.fromCamelCase(NAME) + " distances"); final double[][] profiles = computeProfiles(viewer.getDocument(), viewer); System.err.println("Samples: " + profiles.length + " classes: " + profiles[0].length); for (int x = 0; x < profiles.length; x++) { distances.set(x + 1, x + 1, 0); for (int y = x + 1; y < profiles.length; y++) { distances.set(x + 1, y + 1, Math.sqrt(computeJSD(profiles[x], profiles[y]))); distances.set(y + 1, x + 1, distances.get(x + 1, y + 1)); } } return profiles[0].length; } /** * compute the Jensen-Shannon divergence * */ private static double computeJSD(double[] px, double[] py) { double[] m = computeMean(px, py); return 0.5 * (computeKLD(px, m) + computeKLD(py, m)); } /** * compute the Kullback-Leibler divergence * */ private static double computeKLD(double[] px, double[] py) { double result = 0; for (int i = 0; i < px.length; i++) { double xi = Math.max(px[i], 0.0000000001); double yi = Math.max(py[i], 0.0000000001); result += xi * Math.log(xi / yi); } return result; } /** * return mean of two profiles * * @return mean */ private static double[] computeMean(double[] px, double[] py) { double[] m = new double[px.length]; for (int i = 0; i < px.length; i++) m[i] = 0.5 * (px[i] + py[i]); return m; } /** * compute profiles for analysis * * @return profiles. First index is sample, second is class */ private static double[][] computeProfiles(Document doc, ViewerBase graphView) { final int totalSamples = doc.getNumberOfSamples(); int totalClasses = 0; for (Node v = graphView.getGraph().getFirstNode(); v != null; v = v.getNext()) { if (graphView.getSelected(v)) { totalClasses++; } } double[][] profiles = new double[totalSamples][totalClasses]; int classCount = 0; for (Node v : graphView.getSelectedNodes()) { float[] counts = (v.getOutDegree() == 0 ? graphView.getNodeData(v).getSummarized() : graphView.getNodeData(v).getAssigned()); for (int sampleCount = 0; sampleCount < totalSamples; sampleCount++) { profiles[sampleCount][classCount] = counts[sampleCount]; } classCount++; } for (double[] profile : profiles) { double sum = 0; for (double value : profile) sum += value; //System.err.println("Sum: "+sum); if (sum > 0) { for (int i = 0; i < profile.length; i++) { profile[i] /= sum; } } } return profiles; } }
4,429
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
EuclideanDistance.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/indices/EuclideanDistance.java
/* * EuclideanDistance.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.clusteranalysis.indices; import jloda.graph.Node; import megan.clusteranalysis.tree.Distances; import megan.viewer.ClassificationViewer; /** * compute the euclidean distances between any two samples * Daniel Huson, 6.2018 */ public class EuclideanDistance { public static final String NAME = "Euclidean"; /** * compute the euclidean distances between any two samples * * @return number of nodes used to compute value */ public static int apply(final ClassificationViewer viewer, final Distances distances) { System.err.println("Computing " + NAME + " distances"); final int nTax = distances.getNtax(); final double[][] matrix = distances.getMatrix(); for (int s = 0; s < nTax; s++) { for (int t = s + 1; t < nTax; t++) { matrix[s][t] = 0; } } final double[] total = new double[nTax]; for (Node v : viewer.getSelectedNodes()) { final float[] count = (v.getOutDegree() == 0 ? viewer.getNodeData(v).getSummarized() : viewer.getNodeData(v).getAssigned()); for (int s = 0; s < nTax; s++) total[s] += count[s]; } for (Node v : viewer.getSelectedNodes()) { final float[] count = (v.getOutDegree() == 0 ? viewer.getNodeData(v).getSummarized() : viewer.getNodeData(v).getAssigned()); for (int s = 0; s < nTax; s++) { final double p = (total[s] > 0 ? count[s] / total[s] : 0); for (int t = s + 1; t < nTax; t++) { final double q = (total[t] > 0 ? count[t] / total[t] : 0); matrix[s][t] += (p - q) * (p - q); } } } for (int s = 0; s < nTax; s++) { for (int t = s + 1; t < nTax; t++) { matrix[s][t] = matrix[t][s] = Math.sqrt(matrix[s][t]); } } return viewer.getSelectedNodes().size(); } }
2,802
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
TreeTabBase.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/gui/TreeTabBase.java
/* * TreeTabBase.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.clusteranalysis.gui; import jloda.graph.Node; import jloda.graph.NodeSet; import jloda.phylo.PhyloTree; import jloda.swing.director.IDirector; import jloda.swing.find.IObjectSearcher; import jloda.swing.find.NodeLabelSearcher; import jloda.swing.find.SearchManager; import jloda.swing.graphview.NodeActionAdapter; import jloda.swing.graphview.NodeView; import jloda.swing.util.ProgramProperties; import jloda.util.Basic; import megan.clusteranalysis.ClusterViewer; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.lang.reflect.InvocationTargetException; import java.util.HashSet; import java.util.Set; /** * tab that shows a plot of the data * Daniel Huson, 5.2010 */ public class TreeTabBase extends JPanel { private final ViewerBase graphView; final ClusterViewer clusterViewer; private final IObjectSearcher searcher; /** * constructor * */ public TreeTabBase(final ClusterViewer clusterViewer) { this.clusterViewer = clusterViewer; graphView = new ViewerBase(clusterViewer.getDir(), new PhyloTree(), false) { private boolean showScaleBox = ProgramProperties.get("ShowScaleBox", true); public void setShowScaleBox(boolean showScaleBox) { this.showScaleBox = showScaleBox; } public boolean isShowScaleBox() { return showScaleBox; } public JFrame getFrame() { return null; } public void fitGraphToWindow() { Dimension size = getScrollPane().getSize(); if (size.getWidth() == 0 || size.getHeight() == 0) { try { Runnable runnable = () -> { TreeTabBase.this.validate(); getScrollPane().validate(); }; if (SwingUtilities.isEventDispatchThread()) runnable.run(); // already in the swing thread, just run else SwingUtilities.invokeAndWait(runnable); } catch (InterruptedException | InvocationTargetException e) { Basic.caught(e); } size = getScrollPane().getSize(); } if (getGraph().getNumberOfNodes() > 0) { // need more width than in GraphView trans.fitToSize(new Dimension(Math.max(100, size.width - 300), Math.max(50, size.height - 200))); } else trans.fitToSize(new Dimension(0, 0)); centerGraph(); } public void centerGraph() { JScrollBar hScrollBar = getScrollPane().getHorizontalScrollBar(); hScrollBar.setValue((hScrollBar.getMaximum() - hScrollBar.getModel().getExtent() + hScrollBar.getMinimum()) / 2); JScrollBar vScrollBar = getScrollPane().getVerticalScrollBar(); vScrollBar.setValue((vScrollBar.getMaximum() - vScrollBar.getModel().getExtent() + vScrollBar.getMinimum()) / 2); } public boolean isShowFindToolBar() { return clusterViewer.isShowFindToolBar(); } public void setShowFindToolBar(boolean showFindToolBar) { clusterViewer.setShowFindToolBar(showFindToolBar); } public java.util.Collection<Integer> getSelectedNodeIds() { return graphView.getSelectedNodeIds(); } public SearchManager getSearchManager() { return clusterViewer.getSearchManager(); } public void resetViews() { } }; graphView.setCanvasColor(Color.WHITE); graphView.trans.setLockXYScale(false); graphView.trans.setTopMargin(80); graphView.trans.setBottomMargin(80); graphView.trans.setLeftMargin(200); graphView.trans.setRightMargin(300); graphView.setDrawScaleBar(true); graphView.setFixedNodeSize(true); graphView.setAllowMoveInternalEdgePoints(false); graphView.setAllowMoveNodes(false); graphView.setAllowMoveInternalEdgePoints(false); graphView.setFixedNodeSize(true); graphView.setAutoLayoutLabels(false); graphView.setAllowEdit(false); setLayout(new BorderLayout()); add(graphView.getScrollPane(), BorderLayout.CENTER); this.setPreferredSize(new Dimension(0, 0)); graphView.getScrollPane().getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE); graphView.getScrollPane().setWheelScrollingEnabled(true); graphView.getScrollPane().setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); graphView.trans.removeAllChangeListeners(); graphView.trans.addChangeListener(trans -> graphView.recomputeMargins()); graphView.getScrollPane().addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent event) { { if (graphView.getScrollPane().getSize().getHeight() > 400 && graphView.getScrollPane().getSize().getWidth() > 400) graphView.fitGraphToWindow(); else graphView.trans.fireHasChanged(); } } }); graphView.addNodeActionListener(new NodeActionAdapter() { public void doMoveLabel(NodeSet nodes) { for (Node v = nodes.getFirstElement(); v != null; v = nodes.getNextElement(v)) { graphView.setLabelLayout(v, NodeView.USER); } } public void doSelect(NodeSet nodes) { Set<String> samples = new HashSet<>(); for (Node v : nodes) { String label = graphView.getTree().getLabel(v); if (label != null) samples.add(label); } graphView.getDocument().getSampleSelection().setSelected(samples, true); clusterViewer.updateView(IDirector.ENABLE_STATE); } public void doDeselect(NodeSet nodes) { Set<String> samples = new HashSet<>(); for (Node v : nodes) { String label = graphView.getTree().getLabel(v); if (label != null) samples.add(label); } graphView.getDocument().getSampleSelection().setSelected(samples, false); clusterViewer.updateView(IDirector.ENABLE_STATE); } }); searcher = new NodeLabelSearcher(clusterViewer.getFrame(), "PCoA", graphView); } /** * get the associated graph view * * @return graph view */ public ViewerBase getGraphView() { return graphView; } public void clear() { graphView.getGraph().deleteAllNodes(); } /** * this tab has been selected */ public void activate() { } /** * this tab has been deselected */ public void deactivate() { } public void updateView(String what) { } /** * zoom to fit */ public void zoomToFit() { graphView.fitGraphToWindow(); } /** * zoom to selection */ public void zoomToSelection() { graphView.zoomToSelection(); } /** * gets the searcher associated with this tab * * @return searcher */ public IObjectSearcher getSearcher() { return searcher; } public boolean isApplicable() { return true; } public boolean needsUpdate() { return graphView.getGraph().getNumberOfNodes() == 0; } }
8,805
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
NJTab.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/gui/NJTab.java
/* * NJTab.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.clusteranalysis.gui; import jloda.swing.util.GraphViewPopupListener; import jloda.swing.util.ProgramProperties; import megan.clusteranalysis.ClusterViewer; import megan.clusteranalysis.tree.Distances; import megan.clusteranalysis.tree.NJ; import megan.clusteranalysis.tree.Taxa; /** * Tab that displays a NJ tree * Daniel Huson, 9.2015 */ public class NJTab extends TreeTabBase implements ITab { /** * constructor * */ public NJTab(final ClusterViewer clusterViewer) { super(clusterViewer); getGraphView().setPopupListener(new GraphViewPopupListener(getGraphView(), megan.clusteranalysis.GUIConfiguration.getNodePopupConfiguration(), megan.clusteranalysis.GUIConfiguration.getEdgePopupConfiguration(), megan.clusteranalysis.GUIConfiguration.getPanelPopupConfiguration(), clusterViewer.getCommandManager())); } public String getLabel() { return "NJ Tree"; } public String getMethod() { return "Neighbor-joining"; } /** * sync * */ public void compute(Taxa taxa, Distances distances) { if (getGraphView().getGraph().getNumberOfNodes() == 0) { System.err.println("Computing " + getLabel()); getGraphView().setAutoLayoutLabels(true); NJ.apply(taxa, distances, getGraphView()); getGraphView().setFixedNodeSize(true); getGraphView().setFont(ProgramProperties.get(ProgramProperties.DEFAULT_FONT, clusterViewer.getFont())); clusterViewer.addFormatting(getGraphView()); } } }
2,425
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
NNetTab.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/gui/NNetTab.java
/* * NNetTab.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.clusteranalysis.gui; import jloda.swing.util.GraphViewPopupListener; import jloda.swing.util.ProgramProperties; import jloda.util.progress.ProgressCmdLine; import megan.clusteranalysis.ClusterViewer; import megan.clusteranalysis.nnet.NeighborNet; import megan.clusteranalysis.nnet.Outline; import megan.clusteranalysis.nnet.SplitSystem; import megan.clusteranalysis.tree.Distances; import megan.clusteranalysis.tree.Taxa; /** * Tab that displays a neighbor net * Daniel Huson, 9.2015 */ public class NNetTab extends TreeTabBase implements ITab { /** * constructor * */ public NNetTab(final ClusterViewer clusterViewer) { super(clusterViewer); getGraphView().setPopupListener(new GraphViewPopupListener(getGraphView(), megan.clusteranalysis.GUIConfiguration.getNodePopupConfiguration(), megan.clusteranalysis.GUIConfiguration.getEdgePopupConfiguration(), megan.clusteranalysis.GUIConfiguration.getPanelPopupConfiguration(), clusterViewer.getCommandManager())); } public String getLabel() { return "Outline"; } public String getMethod() { return "Outline"; } /** * sync * */ public void compute(Taxa taxa, Distances distances) throws Exception { if (getGraphView().getGraph().getNumberOfNodes() == 0) { System.err.println("Computing " + getLabel()); final NeighborNet neighborNet = new NeighborNet(); final SplitSystem splits = neighborNet.apply(new ProgressCmdLine(), taxa, distances); final int[] ordering = neighborNet.getOrdering(); getGraphView().setAutoLayoutLabels(true); final Outline outline = new Outline(); outline.createNetwork(ordering, taxa, splits, getGraphView()); getGraphView().setFixedNodeSize(true); getGraphView().resetViews(); getGraphView().trans.setCoordinateRect(getGraphView().getBBox()); getGraphView().getScrollPane().revalidate(); getGraphView().fitGraphToWindow(); getGraphView().setFont(ProgramProperties.get(ProgramProperties.DEFAULT_FONT, clusterViewer.getFont())); clusterViewer.addFormatting(getGraphView()); } } }
3,105
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
UPGMATab.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/gui/UPGMATab.java
/* * UPGMATab.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.clusteranalysis.gui; import jloda.swing.util.GraphViewPopupListener; import jloda.swing.util.ProgramProperties; import megan.clusteranalysis.ClusterViewer; import megan.clusteranalysis.tree.Distances; import megan.clusteranalysis.tree.Taxa; import megan.clusteranalysis.tree.UPGMA; /** * Tab that displays a UPGMA tree * Daniel Huson, 9.2015 */ public class UPGMATab extends TreeTabBase implements ITab { /** * constructor * */ public UPGMATab(final ClusterViewer clusterViewer) { super(clusterViewer); getGraphView().setPopupListener(new GraphViewPopupListener(getGraphView(), megan.clusteranalysis.GUIConfiguration.getNodePopupConfiguration(), megan.clusteranalysis.GUIConfiguration.getEdgePopupConfiguration(), megan.clusteranalysis.GUIConfiguration.getPanelPopupConfiguration(), clusterViewer.getCommandManager())); } public String getLabel() { return "UPGMA Tree"; } public String getMethod() { return "UPGMA"; } /** * sync * */ public void compute(Taxa taxa, Distances distances) { if (getGraphView().getGraph().getNumberOfNodes() == 0) { System.err.println("Computing " + getLabel()); getGraphView().setAutoLayoutLabels(false); UPGMA.apply(taxa, distances, getGraphView()); getGraphView().setFixedNodeSize(true); getGraphView().setFont(ProgramProperties.get(ProgramProperties.DEFAULT_FONT, clusterViewer.getFont())); clusterViewer.addFormatting(getGraphView()); } } }
2,435
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MatrixTab.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/gui/MatrixTab.java
/* * MatrixTab.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.clusteranalysis.gui; import jloda.swing.find.IObjectSearcher; import jloda.swing.find.TableSearcher; import megan.clusteranalysis.tree.Distances; import megan.clusteranalysis.tree.Taxa; import javax.swing.*; import javax.swing.table.AbstractTableModel; import java.awt.*; import java.util.Set; /** * tab that shows the data matrix * Daniel Huson, 5.2010 */ public class MatrixTab extends JPanel { private final JScrollPane scrollPane; private final JPanel contentPanel; private JTable table; private final IObjectSearcher searcher; public MatrixTab(JFrame frame) { setLayout(new BorderLayout()); contentPanel = new JPanel(); contentPanel.setLayout(new BorderLayout()); scrollPane = new JScrollPane(contentPanel); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); add(scrollPane, BorderLayout.CENTER); setData(null, null); // adds empty table to panel searcher = new TableSearcher(frame, "Matrix", getTable()); } /** * set the data * */ public void setData(Taxa taxa, Distances distances) { contentPanel.removeAll(); if (taxa != null && distances != null) table = new JTable(new MyTableModel(taxa, distances)); else table = new JTable(); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setGridColor(Color.LIGHT_GRAY); table.setShowGrid(true); table.setDragEnabled(false); table.removeEditor(); table.setCellSelectionEnabled(true); table.getTableHeader().setReorderingAllowed(false); contentPanel.add(table.getTableHeader(), BorderLayout.PAGE_START); contentPanel.add(table, BorderLayout.CENTER); scrollPane.revalidate(); } public void selectByLabels(Set<String> toSelect) { System.err.println("Select From Previous: not implemented for MatrixTab"); } static class MyTableModel extends AbstractTableModel { private final Taxa taxa; private final Distances distances; MyTableModel(Taxa taxa, Distances distances) { this.taxa = taxa; this.distances = distances; } public String getColumnName(int col) { if (col == 0) return "[Dataset]"; else return "[" + (col) + "] " + taxa.getLabel(col); } public int getRowCount() { return distances.getNtax(); } public int getColumnCount() { return distances.getNtax() + 1; } public Object getValueAt(int row, int col) { if (col == 0) return "[" + (row + 1) + "] " + taxa.getLabel(row + 1); else { return (float) distances.get(row + 1, col); } } public boolean isCellEditable(int row, int col) { return false; } public void setValueAt(Object value, int row, int col) { if (col > 0) { distances.set(row + 1, col, Double.parseDouble(value.toString())); fireTableCellUpdated(row, col); } } } public JTable getTable() { return table; } public JPanel getContentPanel() { return contentPanel; } public JScrollPane getScrollPane() { return scrollPane; } public String getLabel() { return "Matrix"; } public IObjectSearcher getSearcher() { return searcher; } }
4,384
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
PCoATab.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/gui/PCoATab.java
/* * PCoATab.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.clusteranalysis.gui; import javafx.geometry.Point3D; import jloda.graph.*; import jloda.phylo.PhyloGraph; import jloda.phylo.PhyloTree; import jloda.swing.director.IDirector; import jloda.swing.find.IObjectSearcher; import jloda.swing.find.NodeLabelSearcher; import jloda.swing.find.SearchManager; import jloda.swing.graphview.*; import jloda.swing.util.PopupMenu; import jloda.swing.util.ProgramProperties; import jloda.swing.util.*; import jloda.swing.window.NotificationsInSwing; import jloda.util.*; import jloda.util.progress.ProgressListener; import jloda.util.progress.ProgressSilent; import megan.clusteranalysis.ClusterViewer; import megan.clusteranalysis.GUIConfiguration; import megan.clusteranalysis.pcoa.ComputeEllipse; import megan.clusteranalysis.pcoa.Ellipse; import megan.clusteranalysis.pcoa.PCoA; import megan.clusteranalysis.pcoa.Utilities; import megan.clusteranalysis.pcoa.geom3d.Matrix3D; import megan.clusteranalysis.pcoa.geom3d.Vector3D; import megan.clusteranalysis.tree.Distances; import megan.clusteranalysis.tree.Taxa; import megan.viewer.MainViewer; import megan.viewer.ViewerBase; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.lang.reflect.InvocationTargetException; import java.text.DecimalFormat; import java.util.List; import java.util.*; /** * tab that shows a PCoA plot of the data * Daniel Huson, 5.2010, 4.2015 */ public class PCoATab extends JPanel implements ITab { public static final double COORDINATES_SCALE_FACTOR = 10000; private final ClusterViewer clusterViewer; private final ViewerBase graphView; private final PhyloGraph graph; private PCoA pcoa; private int firstPC = 0; private int secondPC = 1; private int thirdPC = 2; private boolean flipH = false; private boolean flipV = false; private boolean showAxes = ProgramProperties.get("ShowPCoAAxes", true); private boolean showBiPlot = ProgramProperties.get("ShowBiPlot", false); private double biPlotScaleFactor=ProgramProperties.get("BiPlotScaleFactor",1.0); private boolean showTriPlot = ProgramProperties.get("ShowTriPlot", false); private double triPlotScaleFactor =ProgramProperties.get("TriPlotScaleFactor",1.0); private boolean showGroupsAsEllipses = ProgramProperties.get("ShowGroups", true); private boolean showGroupsAsConvexHulls = ProgramProperties.get("ShowGroupsAsConvexHulls", true); private final NodeSet biplotNodes; private final EdgeSet biplotEdges; private final NodeSet triplotNodes; private final EdgeSet triplotEdges; private final NodeSet convexHullCenters; private final EdgeSet convexHullEdges; private final ArrayList<Ellipse> ellipses; private int biplotSize = ProgramProperties.get("BiplotSize", 3); private int triplotSize = ProgramProperties.get("TriplotSize", 3); private Pair<String, double[]>[] biplot; private Pair<String, double[]>[] triplot; private final NodeArray<Point3D> node2point3D; // for external use private Color axesColor = ProgramProperties.get("PCoAAxesColor", ColorUtilsSwing.convert(AColor.parseColor("lightgray"))); private byte axesLineWidth = (byte) ProgramProperties.get("PCoAAxesLineWidth", 1); private Color biPlotColor = ProgramProperties.get("PCoABiPlotColor", ColorUtilsSwing.convert(AColor.parseColor("darkseagreen"))); private byte biPlotLineWidth = (byte) ProgramProperties.get("PCoABiPlotLineWidth", 1); private Color triPlotColor = ProgramProperties.get("PCoATriPlotColor", ColorUtilsSwing.convert(AColor.parseColor("sandybrown"))); private byte triPlotLineWidth = (byte) ProgramProperties.get("PCoATriPlotLineWidth", 1); private Color groupsColor = ProgramProperties.get("PCoAGroupColor", ColorUtilsSwing.convert(AColor.parseColor("lightblue"))); private byte groupLineWidth = (byte) ProgramProperties.get("PCoAGroupLineWidth", 1); // 3D figure: private final Matrix3D transformation3D; private final NodeArray<Vector3D> node2vector; // used only in this class private boolean is3dMode = false; private final IObjectSearcher searcher; public long lastSynced = 0; /** * constructor * */ public PCoATab(final ClusterViewer parent) { this.clusterViewer = parent; graphView = new ViewerBase(parent.getDir(), new PhyloTree(), false) { private boolean showScaleBox = ProgramProperties.get("ShowScaleBox", true); public void setShowScaleBox(boolean showScaleBox) { this.showScaleBox = showScaleBox; } public boolean isShowScaleBox() { return showScaleBox; } public JFrame getFrame() { return null; } public boolean isShowFindToolBar() { return parent.isShowFindToolBar(); } public void setShowFindToolBar(boolean showFindToolBar) { parent.setShowFindToolBar(showFindToolBar); } public SearchManager getSearchManager() { return parent.getSearchManager(); } public void drawScaleBar(Graphics2D gc, Rectangle rect) { PCoATab.this.drawScaleBar(this, gc, rect); } public java.util.Collection<Integer> getSelectedNodeIds() { return super.getSelectedNodeIds(); } public void fitGraphToWindow() { Dimension size = getScrollPane().getSize(); if (size.getWidth() == 0 || size.getHeight() == 0) { try { Runnable runnable = () -> { PCoATab.this.validate(); getScrollPane().validate(); }; if (SwingUtilities.isEventDispatchThread()) { //System.err.println("RUN"); runnable.run(); // already in the swing thread, just run } else { //System.err.println("INVOKE"); SwingUtilities.invokeAndWait(runnable); } } catch (InterruptedException | InvocationTargetException e) { Basic.caught(e); } size = getScrollPane().getSize(); } if (getGraph().getNumberOfNodes() > 0) { // need more width than in GraphView trans.fitToSize(new Dimension(Math.max(100, size.width - 300), Math.max(50, size.height - 200))); } else { trans.fitToSize(new Dimension(0, 0)); } centerGraph(); } public void centerGraph() { final JScrollBar hScrollBar = getScrollPane().getHorizontalScrollBar(); final JScrollBar vScrollBar = getScrollPane().getVerticalScrollBar(); hScrollBar.setValue((hScrollBar.getMaximum() - hScrollBar.getModel().getExtent() + hScrollBar.getMinimum()) / 2); vScrollBar.setValue((vScrollBar.getMaximum() - vScrollBar.getModel().getExtent() + vScrollBar.getMinimum()) / 2); // weird, but the following two lines prevent the plot from sometimes appearing half a window too low in the window: todo: doesn't work hScrollBar.setValue(hScrollBar.getValue() + 1); vScrollBar.setValue(vScrollBar.getValue() + 1); } public void resetViews() { } public void paint(Graphics g) { super.paint(g); g.setColor(getGroupsColor()); ((Graphics2D) g).setStroke(new BasicStroke(getGroupLineWidth())); if (showGroupsAsEllipses) { for (Ellipse ellipse : ellipses) { ellipse.paint(g, trans); } } } }; graph = (PhyloGraph) graphView.getGraph(); graphView.setCanvasColor(Color.WHITE); graphView.trans.setLockXYScale(true); graphView.trans.setTopMargin(120); graphView.trans.setBottomMargin(120); graphView.trans.setLeftMargin(200); graphView.trans.setRightMargin(300); graphView.setFixedNodeSize(true); graphView.setAllowMoveInternalEdgePoints(false); graphView.setAllowMoveNodes(false); graphView.setAllowMoveInternalEdgePoints(false); graphView.setAllowRotation(false); graphView.setAutoLayoutLabels(true); graphView.setAllowEdit(false); biplotNodes = new NodeSet(graph); biplotEdges = new EdgeSet(graph); triplotNodes = new NodeSet(graph); triplotEdges = new EdgeSet(graph); convexHullCenters = new NodeSet(graph); convexHullEdges = new EdgeSet(graph); ellipses = new ArrayList<>(); transformation3D = new Matrix3D(); node2vector = new NodeArray<>(graph); node2point3D = new NodeArray<>(graph); setLayout(new BorderLayout()); add(graphView.getScrollPane(), BorderLayout.CENTER); this.setPreferredSize(new Dimension(0, 0)); graphView.getScrollPane().getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE); graphView.getScrollPane().setWheelScrollingEnabled(false); graphView.getScrollPane().setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); graphView.trans.removeAllChangeListeners(); graphView.trans.addChangeListener(trans -> graphView.recomputeMargins()); graphView.getScrollPane().addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent event) { if (graphView.getScrollPane().getSize().getHeight() > 400 && graphView.getScrollPane().getSize().getWidth() > 400) graphView.fitGraphToWindow(); else graphView.trans.fireHasChanged(); } }); graphView.addNodeActionListener(new NodeActionAdapter() { public void doMoveLabel(NodeSet nodes) { for (Node v = nodes.getFirstElement(); v != null; v = nodes.getNextElement(v)) { graphView.setLabelLayout(v, NodeView.USER); } } public void doSelect(NodeSet nodes) { Set<String> samples = new HashSet<>(); for (Node v : nodes) { if (!biplotNodes.contains(v) && !triplotNodes.contains(v)) { String label = graphView.getTree().getLabel(v); if (label != null) samples.add(label); } } final boolean allowMove = (graphView.getSelectedNodes().equals(graph.getUnhiddenSubset(biplotNodes)) || graphView.getSelectedNodes().equals(graph.getUnhiddenSubset(triplotNodes))) && !isIs3dMode(); graphView.setAllowMoveNodes(allowMove); graphView.getDocument().getSampleSelection().setSelected(samples, true); clusterViewer.updateView(IDirector.ENABLE_STATE); } public void doDeselect(NodeSet nodes) { Set<String> samples = new HashSet<>(); for (Node v : nodes) { if (!biplotNodes.contains(v) && !triplotNodes.contains(v)) { String label = graphView.getTree().getLabel(v); if (label != null) samples.add(label); } } final boolean allowMove = (graphView.getSelectedNodes().equals(graph.getUnhiddenSubset(biplotNodes)) || graphView.getSelectedNodes().equals(graph.getUnhiddenSubset(triplotNodes))); graphView.setAllowMoveNodes(allowMove); graphView.getDocument().getSampleSelection().setSelected(samples, false); clusterViewer.updateView(IDirector.ENABLE_STATE); } public void doClick(NodeSet nodes, int clicks) { if (clicks == 2 && nodes.size() > 0) { final NodeSet nodesToSelect = new NodeSet(graph); final boolean select = graphView.getSelected(nodes.getFirstElement()); if (clusterViewer.getGroup2Nodes().size() > 0) { // select all groups for (Node v : nodes) { final String joinId = graphView.getDocument().getSampleAttributeTable().getGroupId(graph.getLabel(v)); // todo: implement this } } graphView.setSelected(nodesToSelect, select); } } public void doClickLabel(NodeSet nodes, int clicks) { doClick(nodes, clicks); } }); final JPopupMenu panelPopupMenu = new PopupMenu(this, GUIConfiguration.getPanelPopupConfiguration(), parent.getCommandManager()); graphView.addPanelActionListener(mouseEvent -> { if (mouseEvent.isPopupTrigger()) { panelPopupMenu.show(PCoATab.this, mouseEvent.getX(), mouseEvent.getY()); } }); ((GraphViewListener) graphView.getGraphViewListener()).setAllowSelectConnectedComponent(true); final Single<Point> previousLocation = new Single<>(); graphView.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { super.mousePressed(e); previousLocation.set(e.getLocationOnScreen()); } public void mouseReleased(MouseEvent e) { super.mousePressed(e); if (previousLocation.get() != null) { if (showGroupsAsConvexHulls && !clusterViewer.isLocked()) { // computeConvexHullsAndEllipsesForGroups(clusterViewer.getGroup2Nodes()); updateTransform(is3dMode); } previousLocation.set(null); } } }); graphView.addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { super.mouseDragged(e); if (isIs3dMode() && !e.isShiftDown() && !e.isAltDown() && !e.isAltGraphDown()) { int h = e.getLocationOnScreen().x - previousLocation.get().x; int v = e.getLocationOnScreen().y - previousLocation.get().y; previousLocation.set(e.getLocationOnScreen()); if (h != 0) { transformation3D.rotateY(0.02 * h); } if (v != 0) { //if(false) transformation3D.rotateX(-0.02 * v); } if (h != 0 || v != 0) { updateTransform(is3dMode); if ((showGroupsAsConvexHulls || showGroupsAsEllipses) && !clusterViewer.isLocked()) { computeConvexHullsAndEllipsesForGroups(clusterViewer.getGroup2Nodes()); // updateConvexHullOfGroups(clusterViewer.getGroup2Nodes()); } } } } }); getGraphView().setPopupListener(new GraphViewPopupListener(getGraphView(), megan.clusteranalysis.GUIConfiguration.getNodePopupConfiguration(), megan.clusteranalysis.GUIConfiguration.getEdgePopupConfiguration(), megan.clusteranalysis.GUIConfiguration.getPanelPopupConfiguration(), clusterViewer.getCommandManager())); graphView.addKeyListener(new KeyAdapter() { /** * Invoked when a key has been pressed. * */ @Override public void keyPressed(KeyEvent e) { super.keyPressed(e); // System.err.println("PRESSED: " + e); } }); searcher = new NodeLabelSearcher(clusterViewer.getFrame(), "PCoA", graphView); } /** * get the associated graph view * * @return graph view */ public ViewerBase getGraphView() { return graphView; } /** * compute the plot and set the data * */ public void setData(Taxa samples, Distances distances) { graphView.setFont(ProgramProperties.get(ProgramProperties.DEFAULT_FONT, getFont())); transformation3D.identity(); graph.deleteAllEdges(); graph.deleteAllNodes(); biplotNodes.clear(); biplotEdges.clear(); triplotNodes.clear(); triplotEdges.clear(); try { if (distances != null) { // if distances given, rerun calculation, otherwise just rebuild graph (after replace of PCs) pcoa = new PCoA(samples, distances); runPCoA(pcoa); } if (!pcoa.isDone()) throw new Exception("PCoA computation: failed"); if (pcoa.getNumberOfPositiveEigenValues() < 2) throw new Exception("PCoA computation: too few positive eigenvalues"); { NodeSet selectedNodes = clusterViewer.getParentViewer().getSelectedNodes(); HashMap<String, float[]> class2counts = new HashMap<>(); for (Node v : selectedNodes) { String className = clusterViewer.getParentViewer().getLabel(v); // todo: need to get proper name NodeData nodeData = (NodeData) v.getData(); class2counts.put(className, nodeData.getSummarized()); } if (class2counts.size() >= 2) { pcoa.computeLoadingVectorsBiPlot(samples.size(), class2counts); } { List<String> sampleNames = new ArrayList<>(samples.size()); for (int t = 1; t <= samples.size(); t++) { String name = samples.getLabel(t); sampleNames.add(name); } HashMap<String, float[]> attribute2counts = clusterViewer.getDir().getDocument().getSampleAttributeTable().getNumericalAttributes(sampleNames); if (attribute2counts.size() > 0) { pcoa.computeLoadingVectorsTriPlot(samples.size(), attribute2counts); } } } // System.err.println("Stress (3D): " + stress3D); // firstVariationExplained=pcoa.getVariationExplained(firstPC); // System.err.println("Variation explained by PC"+(firstPC+1)+": "+firstVariationExplained); // secondVariationExplained=pcoa.getVariationExplained(secondPC); // System.err.println("Variation explained by PC"+(secondPC+1)+": "+secondVariationExplained); // compute points: for (int t = 1; t <= samples.size(); t++) { String name = samples.getLabel(t); double[] coordinates = pcoa.getProjection(firstPC, secondPC, thirdPC, name); final Node v = graph.newNode(); graph.setLabel(v, name); final NodeView nv = graphView.getNV(v); nv.setLabel(graphView.getDocument().getSampleLabelGetter().getLabel(name)); nv.setLabelVisible(clusterViewer.isShowLabels()); graphView.setLocation(v, (flipH ? -1 : 1) * COORDINATES_SCALE_FACTOR * coordinates[0], (flipV ? -1 : 1) * COORDINATES_SCALE_FACTOR * coordinates[1]); // nv.setLabelLayoutFromAngle(Geometry.computeAngle(nv.getLocation())); final double z = COORDINATES_SCALE_FACTOR * coordinates[2]; node2vector.put(v, new Vector3D(graphView.getLocation(v).getX(), graphView.getLocation(v).getY(), z)); node2point3D.put(v, new Point3D(graphView.getLocation(v).getX(), graphView.getLocation(v).getY(), z)); nv.setWidth(clusterViewer.getNodeRadius()); nv.setHeight(clusterViewer.getNodeRadius()); nv.setColor(Color.BLACK); nv.setBackgroundColor(Color.BLACK); nv.setNodeShape(NodeShape.Oval); } // compute biplot arrows: computeBiPlotVectors(getBiplotSize()); if (!isShowBiPlot()) setShowBiPlot(false); computeTriPlotVectors(getTriplotSize()); if (!isShowTriPlot()) setShowTriPlot(false); clusterViewer.getStatusBar().setText2(clusterViewer.getStatusBar().getText2() + " Eigenvalues: " + StringUtils.toString(pcoa.getEigenValues(), ",")); // System.err.println("" + item.get() + "=(" + 100 * item.get(0).floatValue() + "," + 100 * item.get(1).floatValue() + ")"); graphView.trans.setCoordinateRect(graphView.getBBox()); graphView.fitGraphToWindow(); graphView.getScrollPane().revalidate(); } catch (Exception ex) { NotificationsInSwing.showError(MainViewer.getLastActiveFrame(), "PCoA calculation failed: " + ex); } } public ArrayList<Pair<String,double[]>> getPoints() { var result=new ArrayList<Pair<String,double[]>>(); for (int t = 1; t <= pcoa.getSamples().size(); t++) { var name = pcoa.getSamples().getLabel(t); double[] coordinates = pcoa.getProjection(firstPC, secondPC, thirdPC, name); result.add(new Pair<>(name,coordinates)); } return result; } /** * run the MDS code * */ private void runPCoA(final PCoA pcoa) throws CanceledException { ProgressListener progressListener = clusterViewer.getDir().getDocument().getProgressListener(); if (progressListener == null) progressListener = new ProgressSilent(); pcoa.calculateClassicMDS(progressListener); } public PCoA getPCoA() { return pcoa; } public int getFirstPC() { return firstPC; } public void setFirstPC(int firstPC) { this.firstPC = firstPC; } public int getSecondPC() { return secondPC; } public void setSecondPC(int secondPC) { this.secondPC = secondPC; } public int getThirdPC() { return thirdPC; } public void setThirdPC(int thirdPC) { this.thirdPC = thirdPC; } public boolean isFlipH() { return flipH; } public void setFlipH(boolean flipH) { this.flipH = flipH; } public boolean isFlipV() { return flipV; } public void setFlipV(boolean flipV) { this.flipV = flipV; } public boolean isShowBiPlot() { return showBiPlot; } public void setShowBiPlot(boolean showBiPlot) { this.showBiPlot = showBiPlot; ProgramProperties.put("ShowBiPlot", showBiPlot); if (showBiPlot) computeBiPlotVectors(biplotSize); for (Node v : biplotNodes) { if (showBiPlot) { graph.setHidden(v, false); graphView.getNV(v).setLabelVisible(true); graphView.getNV(v).setShape(NodeView.OVAL_NODE); } else { graphView.getNV(v).setLabelVisible(false); graphView.getNV(v).setShape(NodeView.NONE_NODE); graph.setHidden(v, true); } } for (Edge e : biplotEdges) { if (!showBiPlot) { graphView.getEV(e).setLineWidth((byte) 0); } graph.setHidden(e, !showBiPlot); } } public boolean isShowTriPlot() { return showTriPlot; } public void setShowTriPlot(boolean showTriPlot) { this.showTriPlot = showTriPlot; ProgramProperties.put("ShowTriPlot", showTriPlot); if (showTriPlot) computeTriPlotVectors(triplotSize); for (Node v : triplotNodes) { if (showTriPlot) { graph.setHidden(v, false); graphView.getNV(v).setLabelVisible(true); graphView.getNV(v).setShape(NodeView.OVAL_NODE); } else { graphView.getNV(v).setLabelVisible(false); graphView.getNV(v).setShape(NodeView.NONE_NODE); graph.setHidden(v, true); } } for (Edge e : triplotEdges) { if (!showTriPlot) { graphView.getEV(e).setLineWidth((byte) 0); } graph.setHidden(e, !showTriPlot); } } public int getBiplotSize() { return biplotSize; } public void setBiplotSize(int biplotSize) { if (biplotSize > 0) showBiPlot = true; else { setShowBiPlot(false); return; } this.biplotSize = biplotSize; ProgramProperties.put("BiplotSize", biplotSize); computeBiPlotVectors(biplotSize); } public double getBiPlotScaleFactor() { return biPlotScaleFactor; } public void setBiPlotScaleFactor(double factor) { this.biPlotScaleFactor = factor; ProgramProperties.put("BiPlotScaleFactor", biPlotScaleFactor); computeBiPlotVectors(biplotSize); } public void setTriplotSize(int triplotSize) { if (triplotSize > 0) showTriPlot = true; else { setShowTriPlot(false); return; } this.triplotSize = triplotSize; ProgramProperties.put("TriplotSize", triplotSize); computeTriPlotVectors(triplotSize); } public int getTriplotSize() { return triplotSize; } public double getTriPlotScaleFactor() { return triPlotScaleFactor; } public void setTriPlotScaleFactor(double factor) { this.triPlotScaleFactor = factor; ProgramProperties.put("TriPlotScaleFactor", triPlotScaleFactor); computeTriPlotVectors(triplotSize); } public void setShowGroupsAsConvexHulls(boolean showGroupsAsConvexHulls) { this.showGroupsAsConvexHulls = showGroupsAsConvexHulls; ProgramProperties.put("ShowGroupsAsConvexHulls", showGroupsAsConvexHulls); for (Iterator<Edge> it = graph.edgeIteratorIncludingHidden(); it.hasNext(); ) { Edge e = it.next(); if (convexHullEdges.contains(e)) { graphView.getEV(e).setLineWidth(showGroupsAsConvexHulls ? (byte) 1 : (byte) 0); graph.setHidden(e, !showGroupsAsConvexHulls); // graph.setWeight(e,showGroupsAsConvexHulls?1:0); } } } public boolean isShowGroupsAsEllipses() { return showGroupsAsEllipses; } public void setShowGroupsAsEllipses(boolean showGroupsAsEllipses) { this.showGroupsAsEllipses = showGroupsAsEllipses; ProgramProperties.put("ShowGroups", showGroupsAsEllipses); } public boolean isShowGroupsAsConvexHulls() { return showGroupsAsConvexHulls; } /** * compute the scale factor to be used when drawing loadings * */ private double computeLoadingsScaleFactor(double[] vector) { if (vector.length >= 2) { final double length = Math.sqrt(Geometry.squaredDistance(0, 0, vector[0], vector[1])); if (length > 0) { final Rectangle2D bbox = graphView.getBBox(); return 0.2 * Math.min(bbox.getWidth(), bbox.getHeight()) / (length); } } return 1; } /** * computes the convex hulls and ellipses of all groups of nodes * */ public void computeConvexHullsAndEllipsesForGroups(final Map<String, LinkedList<Node>> group2Nodes) { synchronized (convexHullEdges) { { final Set<Edge> edgeToDelete = new HashSet<>(); for (final Iterator<Edge> it = graph.edgeIteratorIncludingHidden(); it.hasNext(); ) { Edge e = it.next(); if (convexHullEdges.contains(e)) { edgeToDelete.add(e); } } for (Edge e : edgeToDelete) { graph.deleteEdge(e); } for (Edge e = graph.getFirstEdge(); e != null; e = e.getNext()) { try { graph.checkOwner(e); } catch (NotOwnerException ex) { Basic.caught(ex); } } } convexHullEdges.clear(); ellipses.clear(); for (Node v : convexHullCenters) { graph.deleteNode(v); } convexHullCenters.clear(); for (String joinId : group2Nodes.keySet()) { final LinkedList<Node> nodes = group2Nodes.get(joinId); if (nodes.size() > 1) { ArrayList<APoint2D> points = new ArrayList<>(nodes.size()); for (Node v : nodes) { if (v == null) continue; points.add(new APoint2D<>(Math.round(graphView.getLocation(v).getX()), Math.round(graphView.getLocation(v).getY()), v)); } if (points.size() > 1) { final ArrayList<APoint2D> hull = ConvexHull.getInstance().quickHull(points); if (showGroupsAsEllipses) { final ArrayList<Point2D> points4 = new ArrayList<>(4 * points.size()); for (APoint2D p : points) { points4.add(new Point2D.Double(p.getX() - 32, p.getY() - 32)); points4.add(new Point2D.Double(p.getX() - 32, p.getY() + 32)); points4.add(new Point2D.Double(p.getX() + 32, p.getY() - 32)); points4.add(new Point2D.Double(p.getX() + 32, p.getY() + 32)); } final Ellipse ellipse = ComputeEllipse.computeEllipse(points4); ellipse.setColor(getGroupsColor()); ellipses.add(ellipse); } if (!showGroupsAsConvexHulls) continue; for (int i = 0; i < hull.size(); i++) { final Node v = (Node) hull.get(i > 0 ? i - 1 : hull.size() - 1).getUserData(); // prev node in polygon final Node w = (Node) hull.get(i).getUserData(); // current node in polygon if (v != w) { final Edge e = graph.newEdge(v, w, EdgeView.UNDIRECTED); graphView.setColor(e, getGroupsColor()); graphView.setDirection(e, EdgeView.UNDIRECTED); convexHullEdges.add(e); } } final Node center = graph.newNode(); convexHullCenters.add(center); graphView.setLocation(center, computeCenter(points)); node2vector.put(center, new Vector3D(graphView.getLocation(center).getX(), graphView.getLocation(center).getY(), 0)); graphView.setWidth(center, 0); graphView.setHeight(center, 0); for (Node v : nodes) { Edge e = graph.newEdge(center, v); graphView.setDirection(e, EdgeView.UNDIRECTED); graphView.setLineWidth(e, 0); graphView.setColor(e, null); convexHullEdges.add(e); } } } } } } /** * computes the center for a set of points * * @return center */ private Point2D computeCenter(ArrayList<APoint2D> points) { final Point center = new Point(0, 0); if (points.size() > 0) { for (APoint2D aPt : points) { center.x += (int) aPt.getX(); center.y += (int) aPt.getY(); } center.x /= points.size(); center.y /= points.size(); } return center; } /** * compute the given number of biplot vectors to show */ private void computeBiPlotVectors(int numberOfBiplotVectorsToShow) { // delete all existing biplot nodes: for (var v : biplotNodes) graph.deleteNode(v); biplotNodes.clear(); biplotEdges.clear(); biplot = null; // compute biplot arrows: var top = Math.min(numberOfBiplotVectorsToShow, getPCoA().getLoadingVectorsBiPlot().size()); if (top > 0) { final Node zero = graph.newNode(); graphView.setLocation(zero, 0, 0); graphView.setNodeShape(zero, NodeShape.None); biplotNodes.add(zero); biplot = new Pair[getPCoA().getLoadingVectorsBiPlot().size()]; for (int i = 0; i < getPCoA().getLoadingVectorsBiPlot().size(); i++) { final Pair<String, double[]> pair = getPCoA().getLoadingVectorsBiPlot().get(i); var x = pair.getSecond()[firstPC]; var y = pair.getSecond()[secondPC]; var z = (thirdPC < pair.getSecond().length ? pair.getSecond()[thirdPC] : 0); biplot[i] = new Pair<>(pair.getFirst(), new double[]{x, y, z}); } Arrays.sort(biplot, (a, b) -> { var aSquaredLength = Utilities.getSquaredLength(a.getSecond()); var bSquaredLength = Utilities.getSquaredLength(b.getSecond()); if (aSquaredLength > bSquaredLength) return -1; else if (aSquaredLength < bSquaredLength) return 1; else return a.getFirst().compareTo(b.getFirst()); }); var scaleFactor = computeLoadingsScaleFactor(biplot[0].getSecond())*biPlotScaleFactor; for (var i = 0; i < top; i++) { var pair = biplot[i]; var x = (flipH ? -1 : 1) * scaleFactor * pair.getSecond()[0]; var y = (flipV ? -1 : 1) * scaleFactor * pair.getSecond()[1]; var z = scaleFactor * pair.getSecond()[2]; var v = graph.newNode(); biplotNodes.add(v); graph.setLabel(v, pair.getFirst()); graphView.setLabel(v, pair.getFirst()); graphView.setLabelVisible(v, isShowBiPlot()); var nv = graphView.getNV(v); nv.setLocation(x, y); node2vector.put(v, new Vector3D(x, y, z)); nv.setLabelLayoutFromAngle(Geometry.computeAngle(nv.getLocation())); nv.setLabelColor(getBiPlotColor()); nv.setNodeShape(NodeShape.None); var e = graph.newEdge(zero, v); biplotEdges.add(e); var ev = graphView.getEV(e); ev.setDirection(EdgeView.DIRECTED); ev.setColor(getBiPlotColor()); ev.setLineWidth(getBiPlotLineWidth()); graph.setInfo(e, EdgeView.DIRECTED); } } updateTransform(is3dMode); // without this, start off at wrong locations... } /** * compute the given number of triplot vectors to show */ private void computeTriPlotVectors(int numberOfTriplotVectorsToShow) { // delete all existing triplot nodes: for (var v : triplotNodes) graph.deleteNode(v); triplotNodes.clear(); triplotEdges.clear(); triplot = null; // compute triplot arrows: var top = Math.min(numberOfTriplotVectorsToShow, getPCoA().getLoadingVectorsTriPlot().size()); if (top > 0) { var zero = graph.newNode(); graphView.setLocation(zero, 0, 0); graphView.setNodeShape(zero, NodeShape.None); triplotNodes.add(zero); triplot = new Pair[getPCoA().getLoadingVectorsTriPlot().size()]; for (int i = 0; i < getPCoA().getLoadingVectorsTriPlot().size(); i++) { var pair = getPCoA().getLoadingVectorsTriPlot().get(i); var x = pair.getSecond()[firstPC]; var y = pair.getSecond()[secondPC]; var z = (thirdPC < pair.getSecond().length ? pair.getSecond()[thirdPC] : 0); triplot[i] = new Pair<>(pair.getFirst(), new double[]{x, y, z}); } Arrays.sort(triplot, (a, b) -> { var aSquaredLength = Utilities.getSquaredLength(a.getSecond()); var bSquaredLength = Utilities.getSquaredLength(b.getSecond()); if (aSquaredLength > bSquaredLength) return -1; else if (aSquaredLength < bSquaredLength) return 1; else return a.getFirst().compareTo(b.getFirst()); }); var scaleFactor = computeLoadingsScaleFactor(triplot[0].getSecond()) * triPlotScaleFactor; for (var i = 0; i < top; i++) { var pair = triplot[i]; var x = (flipH ? -1 : 1) * scaleFactor * pair.getSecond()[0]; var y = (flipV ? -1 : 1) * scaleFactor * pair.getSecond()[1]; var z = scaleFactor * pair.getSecond()[2]; var v = graph.newNode(); triplotNodes.add(v); graph.setLabel(v, pair.getFirst()); graphView.setLabel(v, pair.getFirst()); graphView.setLabelVisible(v, isShowTriPlot()); var nv = graphView.getNV(v); nv.setLocation(x, y); node2vector.put(v, new Vector3D(x, y, z)); triplot[i].setSecond(new double[]{x, y, z}); nv.setLabelLayoutFromAngle(Geometry.computeAngle(nv.getLocation())); nv.setLabelColor(getTriPlotColor()); nv.setNodeShape(NodeShape.None); var e = graph.newEdge(zero, v); triplotEdges.add(e); var ev = graphView.getEV(e); ev.setDirection(EdgeView.DIRECTED); ev.setColor(getTriPlotColor()); ev.setLineWidth((byte) getTriPlotLineWidth()); graph.setInfo(e, EdgeView.DIRECTED); } } updateTransform(is3dMode); // without this, start off at wrong locations... } /** * apply 3d transformation matrix. If draw3D==true, modify colors etc to look 3D * */ public void updateTransform(boolean draw3D) { if (draw3D) { final SortedSet<Pair<Double, Node>> pairs = new TreeSet<>(new Pair<>()); for (Iterator<Node> it = graph.nodeIteratorIncludingHidden(); it.hasNext(); ) { final Node v = it.next(); Vector3D vector = node2vector.get(v); if (vector != null) { Vector3D newVector = new Vector3D(vector); newVector.transform(transformation3D); graphView.setLocation(v, newVector.get(0), newVector.get(1)); pairs.add(new Pair<>(newVector.get(2), v)); if (newVector.get(2) >= 0) { graphView.setColor(v, Color.BLACK); } else { graphView.setColor(v, Color.LIGHT_GRAY); } } else pairs.add(new Pair<>(0d, v)); } // this will make drawer draw graph from back to front List<Node> nodeOrder = new ArrayList<>(pairs.size()); for (Pair<Double, Node> pair : pairs) { nodeOrder.add(pair.getSecond()); } graph.reorderNodes(nodeOrder); } else // 2D { for (Iterator<Node> it = graph.nodeIteratorIncludingHidden(); it.hasNext(); ) { final Node v = it.next(); graphView.setColor(v, Color.BLACK); } } graphView.repaint(); } public Matrix3D getTransformation3D() { return transformation3D; } public boolean isIs3dMode() { return is3dMode; } public void set3dMode(boolean is3dMode) { this.is3dMode = is3dMode; if (!is3dMode) transformation3D.identity(); if (is3dMode) System.err.println("3D mode: Control-click-drag to rotate"); } /** * draws a centerAndScale bar */ private void drawScaleBar(GraphView graphView, Graphics2D gc, Rectangle rect) { final Font oldFont = gc.getFont(); try { if (pcoa.isDone() && pcoa.getNumberOfPositiveEigenValues() >= 2) { gc.setColor(getAxesColor()); gc.setStroke(new BasicStroke(getAxesLineWidth())); final Rectangle grid = new Rectangle(rect.x + 40, rect.y + 20, rect.width - 60, rect.height - 40); gc.setStroke(new BasicStroke(1)); if (!isIs3dMode()) { { gc.setFont(Font.decode("Dialog-PLAIN-12")); String label = getTitle2D(); Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize(); gc.drawString(label, grid.x + grid.width / 2 - labelSize.width / 2, grid.y - 4); } if (isShowAxes()) { gc.setFont(Font.decode("Dialog-PLAIN-11")); final Point zeroDC = graphView.trans.w2d(0, 0); final DecimalFormat tickNumberFormat = new DecimalFormat("#.####"); { final double factor = COORDINATES_SCALE_FACTOR / pcoa.getEigenValues()[firstPC]; double step = 0.0000001d; int jump = 5; while (step < 100000 && graphView.trans.w2d(step * factor, 0).getX() - zeroDC.getX() < 35) { step *= jump; if (jump == 5) jump = 2; else jump = 5; } for (Boolean top : Arrays.asList(true, false)) { final int v0; if (top) v0 = Math.round(grid.y); else v0 = Math.round(grid.y + grid.height); gc.drawLine(grid.x, v0, grid.x + grid.width, v0); for (Integer sign : Arrays.asList(-1, 1)) { for (int i = (sign == 1 ? 0 : 1); i < 1000; i++) { Point2D tickWC = new Point2D.Double(sign * i * step * factor, 0); Point tickDC = graphView.trans.w2d(tickWC); final String label = (i == 0 ? String.format("PC%d", firstPC + 1) : tickNumberFormat.format(sign * i * step)); final Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize(); if (tickDC.x - labelSize.width / 2 >= grid.x && tickDC.x + labelSize.width / 2 <= grid.x + grid.width) { gc.drawLine(tickDC.x, v0, tickDC.x, v0 + (top ? 2 : -2)); if (!top) gc.drawString(label, tickDC.x - labelSize.width / 2, v0 + labelSize.height); } if (sign == -1 && tickDC.x <= grid.x || sign == 1 && tickDC.x >= grid.x + grid.width) break; } } } } { final double factor = COORDINATES_SCALE_FACTOR / pcoa.getEigenValues()[secondPC]; double step = 0.0000001d; int jump = 5; while (step < 100000 && graphView.trans.w2d(0, step * factor).getY() - zeroDC.getY() < 25) { step *= jump; if (jump == 5) jump = 2; else jump = 5; } int yTickStart = grid.y; for (Boolean left : Arrays.asList(true, false)) { final int h0 = (left ? Math.round(grid.x) : Math.round(grid.x + grid.width)); gc.drawLine(h0, grid.y, h0, grid.y + grid.height); for (Integer sign : Arrays.asList(-1, 1)) { for (int i = (sign == 1 ? 0 : 1); i < 1000; i++) { final Point2D tickWC = new Point2D.Double(0, sign * i * step * factor); final Point tickDC = graphView.trans.w2d(tickWC); final String label = (i == 0 ? String.format("PC%d", secondPC + 1) : tickNumberFormat.format(sign * i * step)); final Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize(); if (tickDC.y - labelSize.height / 2 >= yTickStart && tickDC.y + labelSize.height / 2 <= grid.y + grid.height) { gc.drawLine(h0, tickDC.y, h0 + (left ? 2 : -2), tickDC.y); if (left) gc.drawString(label, h0 - labelSize.width - 2, tickDC.y + labelSize.height / 2); } if (sign == -1 && tickDC.y <= yTickStart || sign == 1 && tickDC.y >= grid.y + grid.height) break; } } } } } } else // three dimensional { { gc.setFont(Font.decode("Dialog-PLAIN-12")); String label = getTitle3D(); Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize(); gc.setColor(Color.DARK_GRAY); gc.drawString(label, grid.x + grid.width / 2 - labelSize.width / 2, grid.y - 4); } if (isShowAxes()) { gc.setFont(Font.decode("Dialog-PLAIN-11")); final Vector3D centerVector = new Vector3D(0, 0, 0); centerVector.transform(transformation3D); gc.setColor(getAxesColor()); final Point center = graphView.trans.w2d(centerVector.get(0), centerVector.get(1)); final int axisLength = 50; final Point2D worldOrig = graphView.trans.d2w(0, 0); final Point2D worldX = graphView.trans.d2w(axisLength, 0); { Vector3D v = new Vector3D(worldX.getX() - worldOrig.getX(), 0, 0); v.transform(transformation3D); final Point point = graphView.trans.w2d(v.get(0), v.get(1)); gc.drawLine(center.x, center.y, point.x, point.y); drawArrowHead(gc, center, point); String label = String.format("PC%d", firstPC + 1); gc.drawString(label, point.x, point.y); } { Vector3D v = new Vector3D(0, -(worldX.getX() - worldOrig.getX()), 0); v.transform(transformation3D); final Point point = graphView.trans.w2d(v.get(0), v.get(1)); gc.drawLine(center.x, center.y, point.x, point.y); drawArrowHead(gc, center, point); String label = String.format("PC%d", secondPC + 1); gc.drawString(label, point.x, point.y); } { Vector3D v = new Vector3D(0, 0, worldX.getX() - worldOrig.getX()); v.transform(transformation3D); final Point point = graphView.trans.w2d(v.get(0), v.get(1)); gc.drawLine(center.x, center.y, point.x, point.y); drawArrowHead(gc, center, point); String label = String.format("PC%d", thirdPC + 1); gc.drawString(label, point.x, point.y); } } } } } catch (Exception ex) { // ignore } gc.setFont(oldFont); } private String getTitle2D() { return String.format("PCoA of %s using %s: PC %d (%.1f%%) vs PC %d (%.1f%%)", clusterViewer.getDataType(), clusterViewer.getEcologicalIndex(), (firstPC + 1), pcoa.getPercentExplained(firstPC), (secondPC + 1), pcoa.getPercentExplained(secondPC)); } public String getTitle3D() { return String.format("PCoA of %s using %s: PC %d (%.1f%%) vs PC %d (%.1f%%) vs PC %d (%.1f%%)", clusterViewer.getDataType(), clusterViewer.getEcologicalIndex(), (firstPC + 1), pcoa.getPercentExplained(firstPC), (secondPC + 1), pcoa.getPercentExplained(secondPC), (thirdPC + 1), pcoa.getPercentExplained(thirdPC)); } /** * Draw an arrow head. * * @param gc Graphics * @param vp Point * @param wp Point */ private static void drawArrowHead(Graphics gc, Point vp, Point wp) { final Point diff = new Point(wp.x - vp.x, wp.y - vp.y); if (diff.x != 0 || diff.y != 0) { final int arrowLength = 5; final double arrowAngle = 2.2; double alpha = Geometry.computeAngle(diff); Point a = new Point(arrowLength, 0); a = Geometry.rotate(a, alpha + arrowAngle); a.translate(wp.x, wp.y); Point b = new Point(arrowLength, 0); b = Geometry.rotate(b, alpha - arrowAngle); b.translate(wp.x, wp.y); gc.drawLine(a.x, a.y, wp.x, wp.y); gc.drawLine(wp.x, wp.y, b.x, b.y); } } public String getLabel() { return "PCoA Plot"; } public String getMethod() { return "PCoA"; } /** * sync * */ public void compute(Taxa taxa, Distances distances) { if (graph.getNumberOfNodes() == 0) { System.err.println("Computing " + getLabel()); getGraphView().setAutoLayoutLabels(true); setData(taxa, distances); getGraphView().setFixedNodeSize(true); getGraphView().resetViews(); getGraphView().getScrollPane().revalidate(); getGraphView().fitGraphToWindow(); getGraphView().setFont(ProgramProperties.get(ProgramProperties.DEFAULT_FONT, getGraphView().getFont())); clusterViewer.addFormatting(getGraphView()); clusterViewer.updateConvexHulls = true; } } /** * this tab has been selected */ @Override public void activate() { } /** * this tab has been deselected */ @Override public void deactivate() { } public void clear() { lastSynced = System.currentTimeMillis(); graphView.getGraph().deleteAllNodes(); } public boolean isSampleNode(Node v) { final NodeView nv = graphView.getNV(v); return nv.getLabel() != null && !biplotNodes.contains(v) && !triplotNodes.contains(v) && nv.getLabel().length() > 0; } public boolean isBiplotNode(Node v) { return biplotNodes.contains(v); } public boolean isTriplotNode(Node v) { return triplotNodes.contains(v); } public Point3D getPoint3D(Node v) { return node2point3D.get(v); } public Pair<String, double[]>[] getBiplot() { return biplot; } public Pair<String, double[]>[] getTriplot() { return triplot; } @Override public void updateView(String what) { } /** * zoom to fit */ public void zoomToFit() { if (is3dMode) { getTransformation3D().identity(); updateTransform(is3dMode); } graphView.fitGraphToWindow(); } /** * zoom to selection */ public void zoomToSelection() { graphView.zoomToSelection(); } /** * gets the searcher associated with this tab * * @return searcher */ @Override public IObjectSearcher getSearcher() { return searcher; } public boolean isShowAxes() { return this.showAxes; } public void setShowAxes(boolean showAxes) { this.showAxes = showAxes; ProgramProperties.put("ShowPCoAAxes", showAxes); clusterViewer.updateView(IDirector.ENABLE_STATE); } public boolean isApplicable() { return true; } public boolean needsUpdate() { return graph.getNumberOfNodes() == 0; } static class PointNode extends Point2D.Double { private final Node v; public PointNode(double x, double y, Node v) { super(x, y); this.v = v; } public Node getNode() { return v; } } public Color getAxesColor() { return axesColor; } public void setAxesColor(Color axesColor) { this.axesColor = axesColor; } public int getAxesLineWidth() { return axesLineWidth; } public void setAxesLineWidth(byte axesLineWidth) { this.axesLineWidth = axesLineWidth; } public Color getBiPlotColor() { return biPlotColor; } public void setBiPlotColor(Color biPlotColor) { this.biPlotColor = biPlotColor; for (Edge e : biplotEdges) { graphView.getEV(e).setColor(biPlotColor); graphView.getNV(e.getTarget()).setLabelColor(biPlotColor); } } public Color getTriPlotColor() { return triPlotColor; } public void setTriPlotColor(Color triPlotColor) { this.triPlotColor = triPlotColor; for (Edge e : triplotEdges) { graphView.getEV(e).setColor(triPlotColor); graphView.getNV(e.getTarget()).setLabelColor(triPlotColor); } } public byte getBiPlotLineWidth() { return biPlotLineWidth; } public void setBiPlotLineWidth(byte biPlotLineWidth) { this.biPlotLineWidth = biPlotLineWidth; for (Edge e : biplotEdges) graphView.getEV(e).setLineWidth(biPlotLineWidth); } public int getTriPlotLineWidth() { return triPlotLineWidth; } public void setTriPlotLineWidth(byte triPlotLineWidth) { this.triPlotLineWidth = triPlotLineWidth; for (Edge e : triplotEdges) graphView.getEV(e).setLineWidth(triPlotLineWidth); } public Color getGroupsColor() { return groupsColor; } public void setGroupsColor(Color groupsColor) { this.groupsColor = groupsColor; for (Edge e : convexHullEdges) { if (!convexHullCenters.contains(e.getSource()) && !convexHullCenters.contains(e.getTarget())) graphView.getEV(e).setColor(groupsColor); } for (Ellipse ellipse : ellipses) { ellipse.setColor(groupsColor); } repaint(); } public byte getGroupLineWidth() { return groupLineWidth; } public void setGroupLineWidth(byte groupLineWidth) { this.groupLineWidth = groupLineWidth; for (Edge e : convexHullEdges) { if (!convexHullCenters.contains(e.getSource()) && !convexHullCenters.contains(e.getTarget())) graphView.getEV(e).setLineWidth(groupLineWidth); } repaint(); } }
58,449
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ITab.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/gui/ITab.java
/* * ITab.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.clusteranalysis.gui; import jloda.swing.find.IObjectSearcher; import jloda.swing.graphview.GraphView; import megan.clusteranalysis.tree.Distances; import megan.clusteranalysis.tree.Taxa; /** * basic tab interface * Daniel Huson, 9.2015 */ public interface ITab { /** * this tab has been selected */ void activate(); /** * this tab has been deselected */ void deactivate(); /** * compute the graphics * */ void compute(Taxa taxa, Distances distances) throws Exception; /** * get the label * */ String getLabel(); /** * get the method name * * @return method of computation */ String getMethod(); /** * update the view * */ void updateView(String what); /** * get the associated graphview * * @return graphview */ GraphView getGraphView(); /** * zoom to fit */ void zoomToFit(); /** * zoom to selection */ void zoomToSelection(); /** * gets the searcher associated with this tab * * @return searcher */ IObjectSearcher getSearcher(); /** * should this tab be enabled? * * @return true, if currently applicable */ boolean isApplicable(); /** * need update * * @return update */ boolean needsUpdate(); }
2,203
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Utilities.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/pcoa/Utilities.java
/* * Utilities.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.clusteranalysis.pcoa; import Jama.Matrix; import jloda.util.StringUtils; /** * Math utilities for computing PCoA and biplot. * Daniel Huson, 7.2014 */ public class Utilities { /** * compute centered inner product matrix * * @return new matrix */ public static Matrix computeDoubleCenteringOfSquaredMatrix(Matrix matrix) { final int size = matrix.getColumnDimension(); Matrix result = new Matrix(size, size); final double[] rowAverage = new double[size]; final double[] colAverage = new double[size]; double overallAverage = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { rowAverage[j] += matrix.get(i, j) * matrix.get(i, j); colAverage[i] += matrix.get(i, j) * matrix.get(i, j); overallAverage += matrix.get(i, j) * matrix.get(i, j); } } for (int i = 0; i < size; i++) { rowAverage[i] /= size; colAverage[i] /= size; } overallAverage /= (size * size); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { result.set(i, j, -0.5 * (Math.pow(matrix.get(i, j), 2) - rowAverage[j] - colAverage[i] + overallAverage)); } } return result; } /** * center and scale a given matrix. * Center means: subtract row-average from each col * Scale means: divide each column by square root of (sum-of-squares of column / (number of columns -1)) * See http://docs.tibco.com/pub/enterprise-runtime-for-R/1.1.0-november-2012/TERR_1.1.0_LanguageRef/base/scale.html * * @return new matrix */ public static double[][] centerAndScale(double[][] matrix) { final double[][] result = matrix.clone(); final int nRows = result.length; final int nCols = result[0].length; if (nRows < 2 || nCols == 0) // matrix to return result; // center: for (int col = 0; col < nCols; col++) { double rowAverage = 0; for (double[] aRow : result) { rowAverage += aRow[col]; } rowAverage /= nRows; for (double[] aRow : result) { aRow[col] -= rowAverage; } } // scale: for (int col = 0; col < nCols; col++) { double sumOfSquares = 0; for (double[] aRow : result) { sumOfSquares += aRow[col] * aRow[col]; } double value = Math.sqrt(sumOfSquares / (nRows - 1)); if (value != 0) { for (double[] aRow : result) { aRow[col] /= value; } } } return result; } /** * sort indices by values * * @return sorted indices * todo: replace by proper sorting */ public static int[] sortValues(Matrix m) { double[] v = new double[m.getColumnDimension()]; int[] index = new int[v.length]; for (int i = 0; i < v.length; i++) { v[i] = m.get(i, i); index[i] = i; } for (int i = 0; i < v.length; i++) { for (int j = i + 1; j < v.length; j++) { if (Math.abs(v[i]) < Math.abs(v[j])) { double tmpValue = v[j]; v[j] = v[i]; v[i] = tmpValue; int tmpIndex = index[j]; index[j] = index[i]; index[i] = tmpIndex; } } } return index; } /** * compute the covariance between the columns of two matrices * * @param biasCorrected (if true, multiples values by (nRows/(nRows-1)) * @return convariance */ public static double[][] computeCovariance(final double[][] x, final double[][] y, final boolean biasCorrected) { final int rowsX = x.length; final int colsX = x[0].length; final int rowsY = y.length; final int colsY = y[0].length; final double[][] cov = new double[colsX][colsY]; System.err.println("rowsCov: " + colsX + " colsCov: " + colsY); final double[] meanColX = new double[colsX]; for (int colX = 0; colX < colsX; colX++) { double mean = 0; for (double[] row : x) { mean += row[colX]; } meanColX[colX] = mean / rowsX; } final double[] meanColY = new double[colsY]; for (int colY = 0; colY < colsY; colY++) { double mean = 0; for (double[] row : y) { mean += row[colY]; } meanColY[colY] = mean / rowsY; } for (int colX = 0; colX < colsX; colX++) { for (int colY = 0; colY < colsY; colY++) { double result = 0; for (int row = 0; row < rowsX; row++) { final double xDev = x[row][colX] - meanColX[colX]; final double yDev = y[row][colY] - meanColY[colY]; result += (xDev * yDev - result) / (row + 1); } cov[colX][colY] = biasCorrected ? result * ((double) rowsX / (double) (rowsX - 1)) : result; } } return cov; } /** * matrix multiplication * * @return x*y */ public static double[][] multiply(double[][] x, double[][] y) { final int rowsX = x.length; final int colsX = x[0].length; final int rowsY = y.length; final int colsY = y[0].length; if (colsX != rowsY) throw new RuntimeException("multiply(x,y): incompatible dimensions"); final double[][] z = new double[rowsX][colsY]; for (int a = 0; a < rowsX; a++) { for (int b = 0; b < colsY; b++) { double value = 0; for (int c = 0; c < colsX; c++) { value += x[a][c] * y[c][b]; } z[a][b] = value; } } return z; } /** * creates a matrix whose diagonal contains the given values and all other entries are 0 * * @return matrix */ public static double[][] diag(double[] values) { final int dim = values.length; final double[][] matrix = new double[dim][dim]; for (int i = 0; i < dim; i++) { matrix[i][i] = values[i]; } return matrix; } public static void main(String[] args) { double[][] matrix = {{1, 3, 2}, {2, 6, 4}, {3, 9, 8}}; System.err.println(StringUtils.toString(matrix)); matrix = multiply(matrix, matrix); System.err.println(StringUtils.toString(matrix)); } public static void scalarMultiply(final double value, double[] vector) { for (int i = 0; i < vector.length; i++) vector[i] *= value; } public static void sqrt(double[] vector) { for (int i = 0; i < vector.length; i++) vector[i] = Math.sqrt(vector[i]); } public static void invertValues(double[] vector) { for (int i = 0; i < vector.length; i++) vector[i] = 1.0 / vector[i]; } /** * copy only first nCols of matrix * * @return copy with first nCols */ public static double[][] truncateRows(double[][] matrix, int nCols) { final int nRows = matrix.length; final double[][] result = new double[nRows][nCols]; for (int row = 0; row < nRows; row++) { System.arraycopy(matrix[row], 0, result[row], 0, nCols); } return result; } /** * gets squared length of a vector * * @return squared length */ public static double getSquaredLength(double[] vector) { double result = 0; for (double value : vector) result += value * value; return result; } }
8,820
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z