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 |
---|---|---|---|---|---|---|---|---|---|---|---|
PCoA.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/pcoa/PCoA.java | /*
* PCoA.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.EigenvalueDecomposition;
import Jama.Matrix;
import jloda.util.CanceledException;
import jloda.util.Pair;
import jloda.util.StringUtils;
import jloda.util.progress.ProgressListener;
import megan.clusteranalysis.tree.Distances;
import megan.clusteranalysis.tree.Taxa;
import java.util.*;
/**
* does PCoA calculation
* Daniel Huson, 9.2012
*/
public class PCoA {
private final Taxa samples;
private final Matrix matrixD; // distances between samples
private final int rank;
private int numberOfPositiveEigenValues;
private double[] eigenValues;
private double[] percentExplained;
private final Map<String, double[]> sampleName2Point = new HashMap<>();
private final double[][] points;
private boolean done = false;
private final List<Pair<String, double[]>> loadingVectorsBiPlot = new LinkedList<>();
private final List<Pair<String, double[]>> loadingVectorsTriPlot = new LinkedList<>();
/**
* constructor
*
*/
public PCoA(Taxa samples, Distances distances) {
this.samples = samples;
rank = samples.size();
matrixD = new Matrix(rank, rank);
for (int i = 0; i < rank; i++) {
for (int j = 0; j < rank; j++) {
if (i == j)
matrixD.set(i, j, 0);
else {
double d = distances.get(i + 1, j + 1);
matrixD.set(i, j, d);
}
}
}
points = new double[rank][];
}
/**
* calculate the MDS analysis
*/
public void calculateClassicMDS(ProgressListener progress) throws CanceledException {
progress.setSubtask("Eigenvalue decomposition");
progress.setProgress(-1);
progress.setMaximum(-1);
loadingVectorsBiPlot.clear();
loadingVectorsTriPlot.clear();
// PrintWriter pw = new PrintWriter(System.err);
// System.err.println("distanceMatrix:");
//distanceMatrix.print(pw, rank, rank);
//pw.flush();
final Matrix centered = Utilities.computeDoubleCenteringOfSquaredMatrix(matrixD);
//System.err.println("centered:");
//centered.print(pw, rank, rank);
//pw.flush();
final EigenvalueDecomposition eigenValueDecomposition = centered.eig();
final Matrix eigenVectors = eigenValueDecomposition.getV();
//System.err.println("eigenVectors:");
//eigenVectors.print(pw, rank, rank);
//pw.flush();
numberOfPositiveEigenValues = 0;
final Matrix positiveEigenValues = eigenValueDecomposition.getD();
for (int i = 0; i < rank; i++) {
if (positiveEigenValues.get(i, i) > 0.000000001)
numberOfPositiveEigenValues++;
else
positiveEigenValues.set(i, i, 0);
}
//System.err.println("positiveEigenValues:");
//positiveEigenValues.print(pw, rank, rank);
//pw.flush();
// multiple eigenvectors by sqrt of eigenvalues
progress.setSubtask("Calculating PCoA");
progress.setProgress(0);
progress.setMaximum(2L * rank);
final Matrix scaledEigenVectors = (Matrix) eigenVectors.clone();
for (int i = 0; i < rank; i++) {
for (int j = 0; j < rank; j++) {
double v = scaledEigenVectors.get(i, j);
v = v * Math.sqrt(positiveEigenValues.get(j, j));
scaledEigenVectors.set(i, j, v);
}
progress.incrementProgress();
}
//System.err.println("scaledEigenVectors:");
//scaledEigenVectors.print(pw, rank, rank);
//pw.flush();
System.err.println("numberOfPositiveEigenValues: " + numberOfPositiveEigenValues);
// sort indices by eigenValues
int[] indices = Utilities.sortValues(positiveEigenValues);
/*
System.err.println("indices: " + Basic.toString(indices));
for(int i=0;i<indices.length;i++) {
System.err.println("positiveEigenValues.get(indices["+i+"],indices["+i+"])="+positiveEigenValues.get(indices[i], indices[i]));
}
*/
eigenValues = new double[numberOfPositiveEigenValues];
percentExplained = new double[numberOfPositiveEigenValues];
double total = 0;
for (int j = 0; j < numberOfPositiveEigenValues; j++) {
total += eigenValues[j] = positiveEigenValues.get(indices[j], indices[j]);
}
System.err.println("Positive eigenvalues:");
System.err.println(StringUtils.toString("%.8f", eigenValues, ", "));
if (total > 0) {
for (int j = 0; j < eigenValues.length; j++) {
percentExplained[j] = 100.0 * eigenValues[j] / total;
}
System.err.println("Percent explained:");
System.err.println(StringUtils.toString("%.1f%%", percentExplained, ", "));
}
for (int i = 0; i < rank; i++) {
String name = samples.getLabel(i + 1);
double[] vector = new double[numberOfPositiveEigenValues];
sampleName2Point.put(name, vector);
for (int j = 0; j < numberOfPositiveEigenValues; j++) {
vector[j] = scaledEigenVectors.get(i, indices[j]);
}
points[i] = vector;
progress.incrementProgress();
}
done = true;
}
public int getNumberOfPositiveEigenValues() {
return numberOfPositiveEigenValues;
}
/**
* given i-th, j-th and k-th coordinates for given name
*
* @return (i, j, k)
*/
public double[] getProjection(int i, int j, int k, String sampleName) {
double[] vector = sampleName2Point.get(sampleName);
return new double[]{i < numberOfPositiveEigenValues ? vector[i] : 0, j < numberOfPositiveEigenValues ? vector[j] : 0, k < numberOfPositiveEigenValues ? vector[k] : 0};
}
/**
* get rank
*
* @return rank
*/
public int getRank() {
return rank;
}
public boolean isDone() {
return done;
}
public double[] getEigenValues() {
return eigenValues;
}
/**
* computes the loading vectors as used in biplot
*
*/
public void computeLoadingVectorsBiPlot(final int numberOfSamples, final Map<String, float[]> class2counts) {
loadingVectorsBiPlot.clear();
final var numberOfClasses = (class2counts == null ? 0 : class2counts.size());
final var matrixM = new double[numberOfSamples][numberOfClasses]; // sample X class matrix
// setup classes
final String[] classNames;
if (class2counts != null) {
classNames = class2counts.keySet().toArray(new String[numberOfClasses]);
for (var classNumber = 0; classNumber < classNames.length; classNumber++) {
final var name = classNames[classNumber];
final var counts = class2counts.get(name);
if (counts != null) {
for (int sampleNumber = 0; sampleNumber < counts.length; sampleNumber++) {
matrixM[sampleNumber][classNumber] += counts[sampleNumber];
}
}
}
} else
classNames = new String[0];
// standardize points:
final var standardizedPoints = Utilities.centerAndScale(points);
final var S = Utilities.computeCovariance(matrixM, standardizedPoints, true);
final var values = eigenValues.clone();
Utilities.scalarMultiply(1.0 / (numberOfSamples - 1), values);
Utilities.sqrt(values);
Utilities.invertValues(values);
var diagonal = Utilities.diag(values);
var plotProjection = Utilities.multiply(S, diagonal);
for (var row : plotProjection)
Utilities.scalarMultiply(0.00001, row);
var nameAndLoadingVector = (Pair<String, double[]>[])new Pair[numberOfClasses];
for (var i = 0; i < numberOfClasses; i++) {
nameAndLoadingVector[i] = (new Pair<>(classNames[i], plotProjection[i]));
}
// sort by decreasing length of vector
Arrays.sort(nameAndLoadingVector, (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());
});
/*
for (int i = 0; i < nameAndLoadingVector.length; i++) {
Pair<String, double[]> pair = nameAndLoadingVector[i];
System.err.println(pair.getFirst() + ": "+Math.sqrt(Utilities.getSquaredLength(pair.getSecond())));
}
*/
loadingVectorsBiPlot.addAll(Arrays.asList(nameAndLoadingVector));
}
/**
* computes the loading vectors as used in biplot
*
*/
public void computeLoadingVectorsTriPlot(final int numberOfSamples, final Map<String, float[]> attribute2counts) {
loadingVectorsTriPlot.clear();
final var numberOfAttributes = (attribute2counts == null ? 0 : attribute2counts.size());
final var matrixM = new double[numberOfSamples][numberOfAttributes]; // sample X class matrix
// setup attributes
final String[] attributeNames;
if (attribute2counts != null) {
attributeNames = attribute2counts.keySet().toArray(new String[numberOfAttributes]);
for (var attributeNumber = 0; attributeNumber < attributeNames.length; attributeNumber++) {
final var name = attributeNames[attributeNumber];
final var counts = attribute2counts.get(name);
if (counts != null) {
for (var sampleNumber = 0; sampleNumber < counts.length; sampleNumber++) {
matrixM[sampleNumber][attributeNumber] += counts[sampleNumber];
}
}
}
} else
attributeNames = new String[0];
// standardize points:
final var standardizedPoints = Utilities.centerAndScale(points);
final var S = Utilities.computeCovariance(matrixM, standardizedPoints, true);
final var values = eigenValues.clone();
Utilities.scalarMultiply(1.0 / (numberOfSamples - 1), values);
Utilities.sqrt(values);
Utilities.invertValues(values);
var diagonal = Utilities.diag(values);
var projection = Utilities.multiply(S, diagonal);
for (var row : projection)
Utilities.scalarMultiply(0.00001, row);
var nameAndLoadingVector = ( Pair<String, double[]>[] )new Pair[numberOfAttributes];
for (var i = 0; i < numberOfAttributes; i++) {
nameAndLoadingVector[i] = (new Pair<>(attributeNames[i], projection[i]));
}
// sort by decreasing length of vector
Arrays.sort(nameAndLoadingVector, (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());
});
/*
for (int i = 0; i < nameAndLoadingVector.length; i++) {
Pair<String, double[]> pair = nameAndLoadingVector[i];
System.err.println(pair.getFirst() + ": "+Math.sqrt(Utilities.getSquaredLength(pair.getSecond())));
}
*/
loadingVectorsTriPlot.addAll(Arrays.asList(nameAndLoadingVector));
}
public List<Pair<String, double[]>> getLoadingVectorsBiPlot() {
return loadingVectorsBiPlot;
}
public List<Pair<String, double[]>> getLoadingVectorsTriPlot() {
return loadingVectorsTriPlot;
}
/**
* get percent explained for the given PC
*
* @return percent explained
*/
public double getPercentExplained(int pc) {
return percentExplained[pc];
}
public Taxa getSamples() {
return samples;
}
}
| 13,121 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
Ellipse.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/pcoa/Ellipse.java | /*
* Ellipse.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 jloda.swing.graphview.Transform;
import jloda.swing.util.Geometry;
import java.awt.*;
import java.awt.geom.AffineTransform;
/**
* ellipse
* Created by huson on 9/14/16.
*/
public class Ellipse {
private double centerX;
private double centerY;
private double lengthA;
private double lengthB;
private double angleInRadians;
private Color color;
/**
* default constructor
*/
public Ellipse() {
}
/**
* constructor
*
*/
public Ellipse(double centerX, double centerY, double lengthA, double lengthB, double angleInRadians) {
this.centerX = centerX;
this.centerY = centerY;
this.lengthA = lengthA;
this.lengthB = lengthB;
this.angleInRadians = angleInRadians;
}
/**
* paint the ellipse
*
*/
public void paint(Graphics g) {
final Graphics2D g2d = (Graphics2D) g;
final AffineTransform old = g2d.getTransform();
if (color != null)
g2d.setColor(color);
g2d.rotate(angleInRadians, centerX, centerY);
g2d.drawOval((int) Math.round(centerX - lengthA), (int) Math.round(centerY - lengthB),
(int) Math.round(2 * lengthA), (int) Math.round(2 * lengthB));
g2d.setTransform(old);
}
/**
* paint the ellipse
*
*/
public void paint(Graphics g, Transform trans) {
final Graphics2D g2d = (Graphics2D) g;
if (color != null)
g2d.setColor(color);
final Point center = trans.w2d(centerX, centerY);
final double lenX = Geometry.length(Geometry.diff(trans.w2d(lengthA, 0), trans.w2d(0, 0)));
final double lenY = Geometry.length(Geometry.diff(trans.w2d(0, lengthB), trans.w2d(0, 0)));
final AffineTransform old = g2d.getTransform();
g2d.rotate(angleInRadians, center.getX(), center.getY());
g2d.drawOval((int) Math.round(center.getX() - lenX), (int) Math.round(center.getY() - lenY),
(int) Math.round(2 * lenX), (int) Math.round(2 * lenY));
g2d.setTransform(old);
}
public double getCenterX() {
return centerX;
}
public void setCenterX(double centerX) {
this.centerX = centerX;
}
public double getCenterY() {
return centerY;
}
public void setCenterY(double centerY) {
this.centerY = centerY;
}
public double getLengthA() {
return lengthA;
}
public void setLengthA(double lengthA) {
this.lengthA = lengthA;
}
public double getLengthB() {
return lengthB;
}
public void setLengthB(double lengthB) {
this.lengthB = lengthB;
}
public double getAngleInRadians() {
return angleInRadians;
}
public void setAngleInRadians(double angleInRadians) {
this.angleInRadians = angleInRadians;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
}
| 3,848 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ComputeEllipse.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/pcoa/ComputeEllipse.java | /*
* ComputeEllipse.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.EigenvalueDecomposition;
import Jama.Matrix;
import jloda.swing.util.Geometry;
import jloda.util.APoint2D;
import java.awt.geom.Point2D;
import java.util.ArrayList;
public class ComputeEllipse {
/**
* Direct ellipse fit, proposed in article
* A. W. Fitzgibbon, M. Pilu, R. B. Fisher "Direct Least Squares Fitting of Ellipses" IEEE Trans. PAMI, Vol. 21, pages 476-480 (1999)
* <p>
* This is a java reimplementation of the mathlab function provided in
* http://de.mathworks.com/matlabcentral/fileexchange/22684-ellipse-fit--direct-method-/content/EllipseDirectFit.m
* <p>
* This code is based on a numerically stable version
* of this fit published by R. Halir and J. Flusser
* <p>
* Input: points) is the array of 2D coordinates of n points
* <p>
* Output: A = [a b c d e f]' is the vector of algebraic
* parameters of the fitting ellipse:
* ax^2 + bxy + cy^2 +dx + ey + f = 0
* the vector A is normed, so that ||A||=1
* <p>
* This is a fast non-iterative ellipse fit.
* <p>
* It returns ellipses only, even if points are
* better approximated by a hyperbola.
* It is somewhat biased toward smaller ellipses.
*
* @param points input 2D points
* @return algebraic parameters of the fitting ellipse
*/
private static double[] apply(final double[][] points) {
final int nPoints = points.length;
final double[] centroid = getMean(points);
final double xCenter = centroid[0];
final double yCenter = centroid[1];
final double[][] d1 = new double[nPoints][3];
for (int i = 0; i < nPoints; i++) {
final double xixC = points[i][0] - xCenter;
final double yiyC = points[i][1] - yCenter;
d1[i][0] = xixC * xixC;
d1[i][1] = xixC * yiyC;
d1[i][2] = yiyC * yiyC;
}
final Matrix D1 = new Matrix(d1);
final double[][] d2 = new double[nPoints][3];
for (int i = 0; i < nPoints; i++) {
d2[i][0] = points[i][0] - xCenter;
d2[i][1] = points[i][1] - yCenter;
d2[i][2] = 1;
}
final Matrix D2 = new Matrix(d2);
final Matrix S1 = D1.transpose().times(D1);
final Matrix S2 = D1.transpose().times(D2);
final Matrix S3 = D2.transpose().times(D2);
final Matrix T = (S3.inverse().times(-1)).times(S2.transpose());
final Matrix M = S1.plus(S2.times(T));
final double[][] m = M.getArray();
final double[][] n = {{m[2][0] / 2, m[2][1] / 2, m[2][2] / 2}, {-m[1][0], -m[1][1], -m[1][2]},
{m[0][0] / 2, m[0][1] / 2, m[0][2] / 2}};
final Matrix N = new Matrix(n);
final EigenvalueDecomposition E = N.eig();
final Matrix eVec = E.getV();
final Matrix R1 = eVec.getMatrix(0, 0, 0, 2);
final Matrix R2 = eVec.getMatrix(1, 1, 0, 2);
final Matrix R3 = eVec.getMatrix(2, 2, 0, 2);
final Matrix cond = (R1.times(4)).arrayTimes(R3).minus(R2.arrayTimes(R2));
int firstPositiveIndex = 0;
for (int i = 0; i < 3; i++) {
if (cond.get(0, i) > 0) {
firstPositiveIndex = i;
break;
}
}
final Matrix A1 = eVec.getMatrix(0, 2, firstPositiveIndex, firstPositiveIndex);
final Matrix A = new Matrix(6, 1);
A.setMatrix(0, 2, 0, 0, A1);
A.setMatrix(3, 5, 0, 0, T.times(A1));
final double[] a = A.getColumnPackedCopy();
final double a4 = a[3] - 2 * a[0] * xCenter - a[1] * yCenter;
final double a5 = a[4] - 2 * a[2] * yCenter - a[1] * xCenter;
final double a6 = a[5] + a[0] * xCenter * xCenter + a[2] * yCenter * yCenter + a[1] * xCenter * yCenter - a[3] * xCenter - a[4] * yCenter;
A.set(3, 0, a4);
A.set(4, 0, a5);
A.set(5, 0, a6);
final Matrix Anorm = A.times(1 / A.normF());
return Anorm.getColumnPackedCopy();
}
/**
* compute the mean coordinate of a set of points
*
* @return mean
*/
private static double[] getMean(final double[][] points) {
final int dim = points[0].length;
final double[] result = new double[dim];
for (double[] point : points) {
for (int i = 0; i < dim; i++) {
result[i] += point[i];
}
}
for (int i = 0; i < dim; i++) {
result[i] /= points.length;
}
return result;
}
/**
* converts variable description of ellipse to dimensions
* Based on http://mathworld.wolfram.com/Ellipse.html
*
* @return dimensions centerX,centerY,lengthAxisA,lengthAxisB,angle
*/
private static double[] convertVariablesToDimension(final double[] variables) {
final double a = variables[0];
final double b = variables[1] / 2;
final double c = variables[2];
final double d = variables[3] / 2;
final double f = variables[4] / 2;
final double g = variables[5];
final double centerX = (c * d - b * f) / (b * b - a * c);
final double centerY = (a * f - b * d) / (b * b - a * c);
final double numerator = 2 * (a * f * f + c * d * d + g * b * b - 2 * b * d * f - a * c * g);
final double lengthAxisA = Math.sqrt((numerator) / ((b * b - a * c) * (Math.sqrt((a - c) * (a - c) + 4 * b * b) - (a + c))));
final double lengthAxisB = Math.sqrt((numerator) / ((b * b - a * c) * (-Math.sqrt((a - c) * (a - c) + 4 * b * b) - (a + c))));
double phi = 0;
if (b == 0) {
if (a <= c)
phi = 0;
else if (a > c)
phi = Math.PI / 2;
} else {
if (a < c)
phi = Math.atan(2 * b / (a - c)) / 2;
else if (a > c)
phi = Math.atan(2 * b / (a - c)) / 2 + Math.PI / 2;
}
return new double[]{centerX, centerY, lengthAxisA, lengthAxisB, phi};
}
/**
* compute an ellipse
*
* @return ellipse
*/
public static Ellipse computeEllipse(ArrayList<Point2D> points) {
final double[][] array = new double[points.size()][2];
int i = 0;
for (Point2D aPoint : points) {
array[i][0] = aPoint.getX();
array[i++][1] = aPoint.getY();
}
final double[] dimensions = convertVariablesToDimension(apply(array));
return new Ellipse(dimensions[0], dimensions[1], dimensions[2], dimensions[3], dimensions[4]);
}
/**
* compute an ellipse
*
* @return ellipse
*/
public static javafx.scene.shape.Ellipse computeEllipseFX(ArrayList<APoint2D> points) {
final double[][] array = new double[points.size()][2];
int i = 0;
for (APoint2D aPoint : points) {
array[i][0] = aPoint.getX();
array[i++][1] = aPoint.getY();
}
final double[] dimensions = convertVariablesToDimension(apply(array));
javafx.scene.shape.Ellipse ellipse = new javafx.scene.shape.Ellipse(dimensions[0], dimensions[1], dimensions[2], dimensions[3]);
ellipse.setRotate(Geometry.rad2deg(dimensions[4]));
return ellipse;
}
} | 8,120 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
VectorN.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/pcoa/geom3d/VectorN.java | /*
* VectorN.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.geom3d;
/**
* Nd vector
* Original code by Ken Perlin
* Created by huson on 9/16/14.
*/
public class VectorN {
final double[] v;
/**
* constructor
*
*/
public VectorN(int n) {
v = new double[n];
}
/**
* constructor
*
*/
public VectorN(VectorN vector) {
v = new double[vector.v.length];
System.arraycopy(vector.v, 0, v, 0, v.length);
}
/**
* get dimension
*
* @return size
*/
private int size() {
return v.length;
}
/**
* get component
*
* @return j-th component
*/
public double get(int j) {
return v[j];
}
/**
* set j-th component
*
*/
public void set(int j, double f) {
v[j] = f;
}
/**
* set
*
*/
public void set(VectorN vector) {
for (int j = 0; j < size(); j++)
set(j, vector.get(j));
}
/**
* get string
*
* @return string
*/
public String toString() {
StringBuilder s = new StringBuilder("{");
for (int j = 0; j < size(); j++)
s.append(j == 0 ? "" : ",").append(get(j));
return s + "}";
}
/**
* multiple by given matrix
*
*/
public void transform(MatrixN mat) {
final VectorN tmp = new VectorN(size());
for (int i = 0; i < size(); i++) {
double f = 0d;
for (int j = 0; j < size(); j++)
f += mat.get(i, j) * get(j);
tmp.set(i, f);
}
set(tmp);
}
/**
* compute euclidean distance to given vector
*
* @return distance
*/
public double distance(VectorN vector) {
double d = 0d;
for (int i = 0; i < size(); i++) {
double x = vector.get(0) - get(0);
double y = vector.get(1) - get(1);
d += x * x + y * y;
}
return Math.sqrt(d);
}
}
| 2,791 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
Matrix3D.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/pcoa/geom3d/Matrix3D.java | /*
* Matrix3D.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.geom3d;
/**
* 3D matrix
* Original code by Ken Perlin
* Created by huson on 9/16/14.
*/
public class Matrix3D extends MatrixN {
/**
* constructor
*/
public Matrix3D() {
super(4);
identity();
}
/**
* rotate transformation about the X axis
*
*/
public void rotateX(double theta) {
Matrix3D tmp = new Matrix3D();
double c = Math.cos(theta);
double s = Math.sin(theta);
tmp.set(1, 1, c);
tmp.set(1, 2, -s);
tmp.set(2, 1, s);
tmp.set(2, 2, c);
preMultiply(tmp);
}
/**
* rotate transformation about the X axis
*
*/
public void rotateY(double theta) {
Matrix3D tmp = new Matrix3D();
double c = Math.cos(theta);
double s = Math.sin(theta);
tmp.set(2, 2, c);
tmp.set(2, 0, -s);
tmp.set(0, 2, s);
tmp.set(0, 0, c);
preMultiply(tmp);
}
/**
* rotate transformation about the Z axis
*
*/
public void rotateZ(double theta) {
Matrix3D tmp = new Matrix3D();
double c = Math.cos(theta);
double s = Math.sin(theta);
tmp.set(0, 0, c);
tmp.set(0, 1, -s);
tmp.set(1, 0, s);
tmp.set(1, 1, c);
preMultiply(tmp);
}
/**
* translate
*
*/
private void translate(double a, double b, double c) {
Matrix3D tmp = new Matrix3D();
tmp.set(0, 3, a);
tmp.set(1, 3, b);
tmp.set(2, 3, c);
preMultiply(tmp);
}
public void translate(Vector3D v) {
translate(v.get(0), v.get(1), v.get(2));
}
/**
* scale uniformly
*
*/
void scale(double s) {
Matrix3D tmp = new Matrix3D();
tmp.set(0, 0, s);
tmp.set(1, 1, s);
tmp.set(2, 2, s);
preMultiply(tmp);
}
/**
* scale non-uniformly
*
*/
private void scale(double r, double s, double t) {
Matrix3D tmp = new Matrix3D();
tmp.set(0, 0, r);
tmp.set(1, 1, s);
tmp.set(2, 2, t);
preMultiply(tmp);
}
/**
* scale non-uniformly
*
*/
public void scale(Vector3D v) {
scale(v.get(0), v.get(1), v.get(2));
}
}
| 3,110 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
Vector3D.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/pcoa/geom3d/Vector3D.java | /*
* Vector3D.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.geom3d;
/**
* 3D vector
* Original code by Ken Perlin
* Created by huson on 9/16/14.
*/
public class Vector3D extends VectorN {
/**
* constructor
*/
public Vector3D() {
super(4);
}
/**
* constructor
*
*/
public Vector3D(double x, double y, double z) {
super(4);
set(x, y, z);
}
/**
* constructor
*
*/
public Vector3D(double x, double y, double z, double w) {
super(4);
set(x, y, z, w);
}
/**
* constructor
*
*/
public Vector3D(Vector3D vector) {
super(vector);
}
/**
* set values
*
*/
private void set(double x, double y, double z, double w) {
set(0, x);
set(1, y);
set(2, z);
set(3, w);
}
/**
* set values
*
*/
private void set(double x, double y, double z) {
set(x, y, z, 1);
}
}
| 1,762 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
MatrixN.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/pcoa/geom3d/MatrixN.java | /*
* MatrixN.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.geom3d;
/**
* ND matrix
* Original code by Ken Perlin
* Created by huson on 9/16/14.
*/
public class MatrixN {
private final VectorN[] v;
/**
* constructor
*
*/
public MatrixN(int n) {
v = new VectorN[n];
for (int i = 0; i < n; i++)
v[i] = new VectorN(n);
}
/**
* get dimension
*
* @return size
*/
private int size() {
return v.length;
}
/**
* get component (i,j)
*
*/
public double get(int i, int j) {
return get(i).get(j);
}
/**
* set component (i,j)
*
*/
void set(int i, int j, double f) {
v[i].set(j, f);
}
/**
* get one row
*
*/
private VectorN get(int i) {
return v[i];
}
private void set(int i, VectorN vec) {
v[i].set(vec);
}
private void set(MatrixN mat) {
for (int i = 0; i < size(); i++)
set(i, mat.get(i));
}
public String toString() {
StringBuilder s = new StringBuilder("{");
for (int i = 0; i < size(); i++)
s.append(i == 0 ? "" : ",").append(get(i));
return s + "}";
}
/**
* set to identity matrix
*/
public void identity() {
for (int j = 0; j < size(); j++)
for (int i = 0; i < size(); i++)
set(i, j, (i == j ? 1 : 0));
}
/**
* pre multiple mat x this
*
*/
void preMultiply(MatrixN mat) {
final MatrixN tmp = new MatrixN(size());
for (int j = 0; j < size(); j++)
for (int i = 0; i < size(); i++) {
double f = 0.;
for (int k = 0; k < size(); k++)
f += mat.get(i, k) * get(k, j);
tmp.set(i, j, f);
}
set(tmp);
}
/**
* post multiple this x mat
*
*/
public void postMultiply(MatrixN mat) {
final MatrixN tmp = new MatrixN(size());
for (int j = 0; j < size(); j++)
for (int i = 0; i < size(); i++) {
double f = 0.;
for (int k = 0; k < size(); k++)
f += get(i, k) * mat.get(k, j);
tmp.set(i, j, f);
}
set(tmp);
}
/**
* determines whether this is the identity matrix
*
* @return true, if identity
*/
public boolean isIdentity() {
for (int i = 0; i < v.length; i++) {
for (int j = 0; j < v.length; j++) {
if (i == j) {
if (v[i].v[j] != 1)
return false;
} else if (v[i].v[j] != 0)
return false;
}
}
return true;
}
}
| 3,573 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SplitCardinalityComparator.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/nnet/SplitCardinalityComparator.java | /*
* SplitCardinalityComparator.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.nnet;
import java.util.Comparator;
/**
* compares two splits first by their cardinality, then by their id.
*/
public class SplitCardinalityComparator implements Comparator {
private int splitID;
private int cardinality;
public SplitCardinalityComparator() {
}
public SplitCardinalityComparator(int splitID, int cardinality) {
this.splitID = splitID;
this.cardinality = cardinality;
}
public int compare(Object obj1, Object obj2) throws ClassCastException {
SplitCardinalityComparator scc1 = (SplitCardinalityComparator) obj1;
SplitCardinalityComparator scc2 = (SplitCardinalityComparator) obj2;
if (scc1.cardinality < scc2.cardinality)
return -1;
else if (scc1.cardinality > scc2.cardinality)
return 1;
if (scc1.splitID < scc2.splitID)
return -1;
else if (scc1.splitID > scc2.splitID)
return 1;
return 0;
}
public int getSplitID() {
return splitID;
}
public void setSplitID(int splitID) {
this.splitID = splitID;
}
public int getCardinality() {
return cardinality;
}
public void setCardinality(int cardinality) {
this.cardinality = cardinality;
}
}
| 2,131 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
NeighborNet.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/nnet/NeighborNet.java | /*
* NeighborNet.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.nnet;
import jloda.util.CanceledException;
import jloda.util.progress.ProgressListener;
import megan.clusteranalysis.tree.Distances;
import megan.clusteranalysis.tree.Taxa;
import java.util.Objects;
import java.util.Stack;
/**
* the neighbor-net algorithm
* Dave Bryant and Daniel Huson, 9.2007
*/
public class NeighborNet {
private int[] ordering;
/**
* run neighbor-net
*
* @return splits
*/
public SplitSystem apply(ProgressListener progressListener, Taxa taxa, Distances distances) throws CanceledException {
progressListener.setTasks("Computing clustering", "Neighbor-Net");
System.err.println("Bryant and Moulton (2004)");
ordering = new int[taxa.size() + 1];
if (taxa.size() > 3)
runNeighborNet(progressListener, taxa.size(), setupMatrix(distances), ordering);
else
return new SplitSystem();
return CircularSplitWeights.compute(ordering, distances, true, 0.0001f);
}
/**
* gets the circular ordering
*/
public int[] getOrdering() {
return ordering;
}
/**
* Sets up the working matrix. The original distance matrix is enlarged to
* handle the maximum number of nodes
*
* @param dist Distance block
* @return a working matrix of appropriate cardinality
*/
private static double[][] setupMatrix(Distances dist) {
final int ntax = dist.getNtax();
final int max_num_nodes = Math.max(3, 3 * ntax - 5);
final double[][] mat = new double[max_num_nodes][max_num_nodes];
/* Copy the distance matrix into a larger, scratch distance matrix */
for (int i = 1; i <= ntax; i++) {
for (int j = 1; j <= ntax; j++)
mat[i][j] = dist.get(i, j);
}
return mat;
}
/**
* Run the neighbor net algorithm
*/
private void runNeighborNet(ProgressListener progressListener, int ntax, double[][] mat, int[] ordering) throws CanceledException {
NetNode netNodes = new NetNode();
/* Nodes are stored in a doubly linked list that we set up here */
for (int i = ntax; i >= 1; i--) /* Initially, all singleton nodes are active */ {
NetNode taxNode = new NetNode();
taxNode.id = i;
taxNode.next = netNodes.next;
netNodes.next = taxNode;
}
for (NetNode taxNode = netNodes; taxNode.next != null; taxNode = taxNode.next)
/* Set up links in other direction */
taxNode.next.prev = taxNode;
/* Perform the agglomeration step */
final Stack<NetNode> joins =joinNodes(progressListener, mat, netNodes, ntax);
expandNodes(progressListener, joins, netNodes, ordering);
}
/**
* Agglomerates the nodes
*/
private Stack<NetNode> joinNodes (ProgressListener progressListener, double[][] mat, NetNode netNodes, int num_nodes) throws CanceledException {
//System.err.println("joinNodes");
final Stack<NetNode> joins=new Stack<>();
int num_active = num_nodes;
int num_clusters = num_nodes;
while (num_active > 3) {
/* Special case
If we let this one go then we get a divide by zero when computing Qpq */
if (num_active == 4 && num_clusters == 2) {
final NetNode p = netNodes.next;
final NetNode q;
if (p.next != p.nbr)
q = p.next;
else
q = p.next.next;
if (mat[p.id][q.id] + mat[p.nbr.id][q.nbr.id] < mat[p.id][q.nbr.id] + mat[p.nbr.id][q.id]) {
join3way(p, q, q.nbr, joins, mat, netNodes, num_nodes);
} else {
join3way(p, q.nbr, q, joins, mat, netNodes, num_nodes);
}
break;
}
/* Compute the "averaged" sums s_i from each cluster to every other cluster.
To Do: 2x speedup by using symmetry*/
for (NetNode p = netNodes.next; p != null; p = p.next)
p.Sx = 0.0;
for (NetNode p = netNodes.next; p != null; p = p.next) {
if (p.nbr == null || p.nbr.id > p.id) {
for (NetNode q = p.next; q != null; q = q.next) {
if (q.nbr == null || (q.nbr.id > q.id) && (q.nbr != p)) {
final double dpq;
if ((p.nbr == null) && (q.nbr == null))
dpq = mat[p.id][q.id];
else if ((p.nbr != null) && (q.nbr == null))
dpq = (mat[p.id][q.id] + mat[p.nbr.id][q.id]) / 2.0;
else if (p.nbr == null)
dpq = (mat[p.id][q.id] + mat[p.id][q.nbr.id]) / 2.0;
else
dpq = (mat[p.id][q.id] + mat[p.id][q.nbr.id] + mat[p.nbr.id][q.id] + mat[p.nbr.id][q.nbr.id]) / 4.0;
p.Sx += dpq;
if (p.nbr != null)
p.nbr.Sx += dpq;
q.Sx += dpq;
if (q.nbr != null)
q.nbr.Sx += dpq;
}
}
if (progressListener != null)
progressListener.checkForCancel();
}
}
NetNode Cx=null;
NetNode Cy = null;
/* Now minimize (m-2) D[C_i,C_k] - Sx - Sy */
double best = 0;
for (NetNode p = netNodes.next; p != null; p = p.next) {
if ((p.nbr != null) && (p.nbr.id < p.id)) /* We only evaluate one node per cluster */
continue;
for (NetNode q = netNodes.next; q != p; q = q.next) {
if ((q.nbr != null) && (q.nbr.id < q.id)) /* We only evaluate one node per cluster */
continue;
if (q.nbr == p) /* We only evaluate nodes in different clusters */
continue;
final double Dpq;
if ((p.nbr == null) && (q.nbr == null))
Dpq = mat[p.id][q.id];
else if ((p.nbr != null) && (q.nbr == null))
Dpq = (mat[p.id][q.id] + mat[p.nbr.id][q.id]) / 2.0;
else if (p.nbr == null)
Dpq = (mat[p.id][q.id] + mat[p.id][q.nbr.id]) / 2.0;
else
Dpq = (mat[p.id][q.id] + mat[p.id][q.nbr.id] + mat[p.nbr.id][q.id] + mat[p.nbr.id][q.nbr.id]) / 4.0;
final double Qpq = ((double) num_clusters - 2.0) * Dpq - p.Sx - q.Sx;
/* Check if this is the best so far */
if ((Cx == null || (Qpq < best)) && (p.nbr != q)) {
Cx = p;
Cy = q;
best = Qpq;
}
}
}
/* Find the node in each cluster */
NetNode x = Cx;
NetNode y = Cy;
if (Objects.requireNonNull(Cx).nbr != null || Objects.requireNonNull(Cy).nbr != null) {
Cx.Rx = ComputeRx(Cx, Cx, Cy, mat, netNodes);
if (Cx.nbr != null)
Cx.nbr.Rx = ComputeRx(Cx.nbr, Cx, Cy, mat, netNodes);
Objects.requireNonNull(Cy).Rx = ComputeRx(Cy, Cx, Cy, mat, netNodes);
if (Cy.nbr != null)
Cy.nbr.Rx = ComputeRx(Cy.nbr, Cx, Cy, mat, netNodes);
}
int m = num_clusters;
if (Cx.nbr != null)
m++;
if (Cy.nbr != null)
m++;
best = ((double) m - 2.0) * mat[Cx.id][Cy.id] - Cx.Rx - Cy.Rx;
if (Cx.nbr != null) {
final double Qpq = ((double) m - 2.0) * mat[Cx.nbr.id][Cy.id] - Cx.nbr.Rx - Cy.Rx;
if (Qpq < best) {
x = Cx.nbr;
y = Cy;
best = Qpq;
}
}
if (Cy.nbr != null) {
final double Qpq = ((double) m - 2.0) * mat[Cx.id][Cy.nbr.id] - Cx.Rx - Cy.nbr.Rx;
if (Qpq < best) {
x = Cx;
y = Cy.nbr;
best = Qpq;
}
}
if ((Cx.nbr != null) && (Cy.nbr != null)) {
final double Qpq = ((double) m - 2.0) * mat[Cx.nbr.id][Cy.nbr.id] - Cx.nbr.Rx - Cy.nbr.Rx;
if (Qpq < best) {
x = Cx.nbr;
y = Cy.nbr;
}
}
/* We perform an agglomeration... one of three types */
if ((null == Objects.requireNonNull(x).nbr) && (null == Objects.requireNonNull(y).nbr)) { /* Both vertices are isolated...add edge {x,y} */
join2way(x, y);
num_clusters--;
} else if (null == x.nbr) { /* X is isolated, Y is not isolated*/
join3way(x, y, y.nbr, joins, mat, netNodes, num_nodes);
num_nodes += 2;
num_active--;
num_clusters--;
} else if ((null == Objects.requireNonNull(y).nbr) || (num_active == 4)) { /* Y is isolated, X is not isolated
OR theres only four active nodes and none are isolated */
join3way(y, x, x.nbr, joins, mat, netNodes, num_nodes);
num_nodes += 2;
num_active--;
num_clusters--;
} else { /* Both nodes are connected to others and there are more than 4 active nodes */
num_nodes = join4way(x.nbr, x, y, y.nbr, joins, mat, netNodes, num_nodes);
num_active -= 2;
num_clusters--;
}
}
return joins;
}
/**
* agglomerate 2 nodes
*
* @param x one node
* @param y other node
*/
private void join2way(NetNode x, NetNode y) {
x.nbr = y;
y.nbr = x;
}
/**
* agglomerate 3 nodes.
* Note that this version doesn't rescan num_nodes, you need to
* num_nodes+=2 after calling this!
*
* @param x one node
* @param y other node
* @param z other node
* @return one of the new nodes
*/
private NetNode join3way(NetNode x, NetNode y, NetNode z, Stack<NetNode> joins, double[][] mat, NetNode netNodes, int num_nodes) {
/* Agglomerate x,y, and z to give TWO new nodes, u and v */
/* In terms of the linked list: we replace x and z
by u and v and remove y from the linked list.
and replace y with the new node z
Returns a pointer to the node u */
//printf("Three way: %d, %d, and %d\n",x.id,y.id,z.id);
NetNode u = new NetNode();
u.id = num_nodes + 1;
u.ch1 = x;
u.ch2 = y;
NetNode v = new NetNode();
v.id = num_nodes + 2;
v.ch1 = y;
v.ch2 = z;
/* Replace x by u in the linked list */
u.next = x.next;
u.prev = x.prev;
if (u.next != null)
u.next.prev = u;
if (u.prev != null)
u.prev.next = u;
/* Replace z by v in the linked list */
v.next = z.next;
v.prev = z.prev;
if (v.next != null)
v.next.prev = v;
if (v.prev != null)
v.prev.next = v;
/* Remove y from the linked list */
if (y.next != null)
y.next.prev = y.prev;
if (y.prev != null)
y.prev.next = y.next;
/* Add an edge between u and v, and add u into the list of amalgamations */
u.nbr = v;
v.nbr = u;
/* Update distance matrix */
for (NetNode p = netNodes.next; p != null; p = p.next) {
mat[u.id][p.id] = mat[p.id][u.id] = (2.0 / 3.0) * mat[x.id][p.id] + mat[y.id][p.id] / 3.0;
mat[v.id][p.id] = mat[p.id][v.id] = (2.0 / 3.0) * mat[z.id][p.id] + mat[y.id][p.id] / 3.0;
}
mat[u.id][u.id] = mat[v.id][v.id] = 0.0;
joins.push(u);
return u;
}
/**
* Agglomerate four nodes
*
* @param x2 a node
* @param x a node
* @param y a node
* @param y2 a node
* @return the new number of nodes
*/
private int join4way(NetNode x2, NetNode x, NetNode y, NetNode y2, Stack<NetNode> joins, double[][] mat, NetNode netNodes, int num_nodes) {
/* Replace x2,x,y,y2 by with two vertices... performed using two
3 way amalgamations */
NetNode u;
u = join3way(x2, x, y, joins, mat, netNodes, num_nodes); /* Replace x2,x,y by two nodes, equalOverShorterOfBoth to x2_prev.next and y_prev.next. */
num_nodes += 2;
join3way(u, u.nbr, y2, joins, mat, netNodes, num_nodes); /* z = y_prev . next */
num_nodes += 2;
return num_nodes;
}
/**
* Computes the Rx
*
* @param z a node
* @param Cx a node
* @param Cy a node
* @param mat the distances
* @param netNodes the net nodes
* @return the Rx value
*/
private double ComputeRx(NetNode z, NetNode Cx, NetNode Cy, double[][] mat, NetNode netNodes) {
double Rx = 0.0;
for (NetNode p = netNodes.next; p != null; p = p.next) {
if (p == Cx || p == Cx.nbr || p == Cy || p == Cy.nbr || p.nbr == null)
Rx += mat[z.id][p.id];
else /* p.nbr != null */
Rx += mat[z.id][p.id] / 2.0; /* We take the average of the distances */
}
return Rx;
}
/**
* Expands the net nodes to obtain the ordering, quickly
* @param joins stack of amalagations
* @param netNodes the net nodes
* @param ordering the ordering
*/
private void expandNodes(ProgressListener progressListener, Stack<NetNode> joins, NetNode netNodes, int[] ordering) throws CanceledException {
//System.err.println("expandNodes");
/* Set up the circular order for the first three nodes */
NetNode x = netNodes.next;
NetNode y = x.next;
NetNode z = y.next;
z.next = x;
x.prev = z;
/* Now do the rest of the expansions */
while (!joins.empty()) {
/* Find the three elements replacing u and v. Swap u and v around if v comes before u in the
circular ordering being built up */
NetNode u = (joins.pop());
// System.err.println("POP: u="+u);
NetNode v = u.nbr;
x = u.ch1;
y = u.ch2;
z = v.ch2;
if (v != u.next) {
NetNode tmp = u;
u = v;
v = tmp;
tmp = x;
x = z;
z = tmp;
}
/* Insert x,y,z into the circular order */
x.prev = u.prev;
x.prev.next = x;
x.next = y;
y.prev = x;
y.next = z;
z.prev = y;
z.next = v.next;
z.next.prev = z;
if (progressListener != null)
progressListener.checkForCancel();
}
/* When we exit, we know that the point x points to a node in the circular order */
/* We loop through until we find the node after taxa zero */
while (x.id != 1) {
x = x.next;
}
/* extract the ordering */
NetNode a = x;
int t = 0;
do {
// System.err.println("a="+a);
ordering[++t] = a.id;
a = a.next;
} while (a != x);
}
}
/* A node in the net */
class NetNode {
int id = 0;
NetNode nbr = null; // adjacent node
NetNode ch1 = null; // first child
NetNode ch2 = null; // second child
NetNode next = null; // next in list of active nodes
NetNode prev = null; // prev in list of active nodes
double Rx = 0;
double Sx = 0;
public String toString() {
String str = "[id=" + id;
str += " nbr=" + (nbr == null ? "null" : ("" + nbr.id));
str += " ch1=" + (ch1 == null ? "null" : ("" + ch1.id));
str += " ch2=" + (ch2 == null ? "null" : ("" + ch2.id));
str += " prev=" + (prev == null ? "null" : ("" + prev.id));
str += " next=" + (next == null ? "null" : ("" + next.id));
str += " Rx=" + Rx;
str += " Sx=" + Sx;
str += "]";
return str;
}
}
| 17,460 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
Outline.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/nnet/Outline.java | /*
* Outline.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.nnet;
import javafx.geometry.Point2D;
import jloda.fx.util.GeometryUtilsFX;
import jloda.graph.Edge;
import jloda.graph.Node;
import jloda.graph.NodeArray;
import jloda.phylo.PhyloSplitsGraph;
import jloda.swing.graphview.PhyloTreeView;
import jloda.util.BitSetUtils;
import megan.clusteranalysis.tree.Taxa;
import java.util.*;
import java.util.function.Function;
/**
* the outline algorithm for computing a phylogenetic outline
* Daniel Huson, 1.2021
*/
public class Outline {
private int ntax;
/**
* computes the graph and graph view
*
*/
public void createNetwork(int[] cycle0, Taxa taxa, SplitSystem splits, PhyloTreeView view) {
final boolean useWeights = true;
ntax = taxa.getBits().cardinality();
final PhyloSplitsGraph graph = (PhyloSplitsGraph) view.getGraph();
graph.clear();
final int[] cycle = normalizeCycle(cycle0);
splits.addAllTrivial(taxa);
for (int i = 1; i <= ntax; i++)
graph.setTaxon2Cycle(cycle[i], i);
final double[] split2angle = assignAnglesToSplits(ntax, splits, cycle, 360);
final ArrayList<Event> events;
{
final ArrayList<Event> outbound = new ArrayList<>();
final ArrayList<Event> inbound = new ArrayList<>();
for (int s = 1; s <= splits.size(); s++) {
final Split split = splits.getSplit(s);
if (true) {
outbound.add(new Event(Event.Type.outbound, s, cycle, split));
inbound.add(new Event(Event.Type.inbound, s, cycle, split));
}
}
events = Event.radixSort(ntax, outbound, inbound);
}
final BitSet currentSplits = new BitSet();
Point2D location = new Point2D(0, 0);
final Node start = graph.newNode();
view.setLocation(start,new java.awt.geom.Point2D.Double(0,0));
final NodeArray<Point2D> node2point=new NodeArray<>(graph);
node2point.put(start, new Point2D(location.getX(), location.getY()));
final Map<BitSet,Node> splits2node=new HashMap<>();
splits2node.put(new BitSet(), start);
Event previousEvent = null;
// System.err.println("Algorithm:");
// System.err.println("Start: " + start.getId());
final BitSet taxaFound = new BitSet();
Node previousNode = start;
for (Event event : events) {
// System.err.println(event);
if (event.isStart()) {
currentSplits.set(event.getS(), true);
location = GeometryUtilsFX.translateByAngle(location, split2angle[event.getS()], useWeights ? event.getWeight() : 1);
} else {
currentSplits.set(event.getS(), false);
location = GeometryUtilsFX.translateByAngle(location, split2angle[event.getS()] + 180, useWeights ? event.getWeight() : 1);
}
final boolean mustCreateNode = (splits2node.get(currentSplits) == null);
final Node v;
if (mustCreateNode) {
v = graph.newNode();
splits2node.put(BitSetUtils.copy(currentSplits), v);
node2point.put(v, new Point2D(location.getX(), location.getY()));
view.setLocation(v, new java.awt.geom.Point2D.Double(location.getX(), location.getY()));
} else {
v = splits2node.get(currentSplits);
location = node2point.get(v);
}
// System.err.println("Node: " + v.getId());
if (!v.isAdjacent(previousNode)) {
final Edge e = graph.newEdge(previousNode, v);
graph.setSplit(e, event.getS());
graph.setWeight(e, useWeights ? event.getWeight() : 1);
graph.setAngle(e, split2angle[event.getS()]);
if (!mustCreateNode) // just closed loop
{
// loops.add(createLoop(v, e));
}
}
if (previousEvent != null) {
if (event.getS() == previousEvent.getS()) {
for (int t : BitSetUtils.members(splits.getSplit(event.getS()).getPartNotContaining(cycle[1]))) {
graph.addTaxon(previousNode, t);
taxaFound.set(t);
graph.setLabel(previousNode,taxa.getLabel(t));
}
}
}
previousNode = v;
previousEvent = event;
}
for (int t = 1; t <= ntax; t++) {
if (!taxaFound.get(t)) {
graph.addTaxon(start, t);
graph.setLabel(start, taxa.getLabel(t));
}
}
if (false) {
for (Node v : graph.nodes()) {
// if (graph.getLabel(v) != null)
System.err.println("Node " + v.getId() + " " + graph.getLabel(v) + " point: " + node2point.get(v));
}
for (Edge e : graph.edges()) {
System.err.println("Edge " + e.getSource().getId() + " - " + e.getTarget().getId() + " split: " + graph.getSplit(e));
}
}
view.resetViews();
}
/**
* normalizes cycle so that cycle[1]=1
*
* @return normalized cycle
*/
private int[] normalizeCycle(int[] cycle) {
int[] result = new int[cycle.length];
int i = 1;
while (cycle[i] != 1)
i++;
int j = 1;
while (i < cycle.length) {
result[j] = cycle[i];
i++;
j++;
}
i = 1;
while (j < result.length) {
result[j] = cycle[i];
i++;
j++;
}
return result;
}
/**
* assigns angles to all edges in the graph
*
*/
public static double[] assignAnglesToSplits(int ntaxa, SplitSystem splits, int[] cycle, double totalAngle) {
//We create the list of angles representing the positions on a circle.
double[] angles = new double[ntaxa + 1];
for (int t = 1; t <= ntaxa; t++) {
angles[t] = (totalAngle * (t - 1) / (double) ntaxa) + 270 - 0.5 * totalAngle;
}
double[] split2angle = new double[splits.size() + 1];
assignAnglesToSplits(ntaxa, angles, split2angle, splits, cycle);
return split2angle;
}
/**
* assigns angles to the splits in the graph, considering that they are located exactly "in the middle" of two taxa
* so we fill split2angle using TaxaAngles.
*
* @param angles for each taxa, its angle
* @param split2angle for each split, its angle
*/
private static void assignAnglesToSplits(int ntaxa, double[] angles, double[] split2angle, SplitSystem splits, int[] cycle) {
for (int s = 1; s <= splits.size(); s++) {
final Split split= splits.getSplit(s);
int xp = 0; // first position of split part not containing taxon cycle[1]
int xq = 0; // last position of split part not containing taxon cycle[1]
final BitSet part = split.getPartNotContaining(cycle[1]);
for (int i = 2; i <= ntaxa; i++) {
int t = cycle[i];
if (part.get(t)) {
if (xp == 0)
xp = i;
xq = i;
}
}
split2angle[s] = GeometryUtilsFX.modulo360(0.5 * (angles[xp] + angles[xq]));
//System.out.println("split from "+xp+","+xpneighbour+" ("+TaxaAngleP+") to "+xq+","+xqneighbour+" ("+TaxaAngleQ+") -> "+split2angle[s]+" $ "+(180 * (xp + xq)) / (double) ntaxa);s
}
}
static class Event {
enum Type {outbound, inbound}
private final double weight;
private int iPos;
private int jPos;
private final int s;
private final Type type;
public Event(Type type, int s, int[] cycle, Split split) {
this.type = type;
this.s = s;
this.weight = split.getWeight();
int firstInCycle = cycle[1];
iPos = Integer.MAX_VALUE;
jPos = Integer.MIN_VALUE;
final BitSet farSide = split.getPartNotContaining(firstInCycle);
for (int i = 0; i < cycle.length; i++) {
final int t = cycle[i];
if (t > 0 && farSide.get(t)) {
iPos = Math.min(iPos, i);
jPos = Math.max(jPos, i);
}
}
}
public int getS() {
return s;
}
private int getIPos() {
return iPos;
}
private int getJPos() {
return jPos;
}
public double getWeight() {
return weight;
}
public boolean isStart() {
return type == Type.outbound;
}
public boolean isEnd() {
return type == Type.inbound;
}
public String toString() {
return type.name() + " S" + s + " (" + iPos + "-" + jPos + ")"; //: " + Basic.toString(split.getPartNotContaining(firstInCycle), ",");
}
public static ArrayList<Event> radixSort(int ntax, ArrayList<Event> outbound, ArrayList<Event> inbound) {
countingSort(outbound, ntax, a -> ntax - a.getJPos());
countingSort(outbound, ntax, Event::getIPos);
countingSort(inbound, ntax, a -> ntax - a.getIPos());
countingSort(inbound, ntax, Event::getJPos);
return merge(outbound, inbound);
}
private static void countingSort(ArrayList<Event> events, int maxKey, Function<Event, Integer> key) {
if (events.size() > 1) {
final int[] key2pos = new int[maxKey + 1];
// count keys
for (Event event : events) {
final int value = key.apply(event);
key2pos[value]++;
}
// set positions
{
int pos = 0;
for (int i = 0; i < key2pos.length; i++) {
final int add = key2pos[i];
key2pos[i] = pos;
pos += add;
}
}
final Event[] other = new Event[events.size()];
// insert at positions:
for (Event event : events) {
final int k = key.apply(event);
final int pos = key2pos[k]++;
other[pos] = event;
}
// copy to result:
events.clear();
Collections.addAll(events, other);
}
}
private static ArrayList<Event> merge(ArrayList<Event> outbound, ArrayList<Event> inbound) {
final ArrayList<Event> events = new ArrayList<>(outbound.size() + inbound.size());
int ob = 0;
int ib = 0;
while (ob < outbound.size() && ib < inbound.size()) {
if (outbound.get(ob).getIPos() < inbound.get(ib).getJPos() + 1) {
events.add(outbound.get(ob++));
} else {
events.add(inbound.get(ib++));
}
}
while (ob < outbound.size())
events.add(outbound.get(ob++));
while (ib < inbound.size())
events.add(inbound.get(ib++));
return events;
}
}
}
| 12,385 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SplitSystem.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/nnet/SplitSystem.java | /*
* SplitSystem.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.nnet;
import jloda.graph.Edge;
import jloda.graph.Node;
import jloda.graph.NodeArray;
import jloda.phylo.PhyloTree;
import jloda.util.BitSetUtils;
import megan.clusteranalysis.tree.Taxa;
import java.util.*;
/**
* a collection of splits
* Daniel Huson, 6.2007
*/
public class SplitSystem {
private int nsplits;
private final Map<Integer,Split> index2split;
private final Map<Split,Integer> split2index;
/**
* constructor
*/
public SplitSystem() {
nsplits = 0;
index2split = new HashMap<>();
split2index = new HashMap<>();
}
/**
* constructs a set of splits from a tree
*
*/
public SplitSystem(Taxa allTaxa, PhyloTree tree) {
this();
splitsFromTreeRec(tree.getRoot(), tree, allTaxa, allTaxa.getBits(), new NodeArray<>(tree), this);
}
/**
* get size
*
* @return number of splits
*/
public int size() {
return nsplits;
}
/**
* add a split
*
*/
public void addSplit(Split split) {
nsplits++;
index2split.put(nsplits, split);
split2index.put(split, nsplits);
}
/**
* gets a split
*
* @return split with given index
*/
public Split getSplit(int index) {
return index2split.get(index);
}
/**
* gets the index of the split, if present, otherwise -1
*
* @return index or -1
*/
public int indexOf(Split split) {
Integer index = split2index.get(split);
return Objects.requireNonNullElse(index, -1);
}
/**
* determines whether given split is already contained in the system
*
* @return true, if contained
*/
private boolean contains(Split split) {
return split2index.containsKey(split);
}
/**
* gets a string representation
*
* @return string
*/
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append("Splits (").append(nsplits).append("):\n");
for (var it = iterator(); it.hasNext(); ) {
Split split = it.next();
buf.append(split).append("\n");
}
return buf.toString();
}
/**
* erase
*/
public void clear() {
nsplits = 0;
index2split.clear();
split2index.clear();
}
/**
* gets an iterator over all splits
*
* @return getLetterCodeIterator
*/
private Iterator<Split> iterator() {
return split2index.keySet().iterator();
}
/**
* given a phylogenetic tree and a set of taxa, returns all splits found in the tree.
* Assumes the last taxon is an outgroup
*
* @return splits
*/
public static SplitSystem getSplitsFromTree(Taxa allTaxa, BitSet activeTaxa, PhyloTree tree) {
SplitSystem splits = new SplitSystem();
splitsFromTreeRec(tree.getRoot(), tree, allTaxa, activeTaxa, new NodeArray<>(tree), splits);
return splits;
}
/**
* recursively extract splits from tree. Also works for cluster networks.
*
* @return taxa
*/
private static BitSet splitsFromTreeRec(Node v, PhyloTree tree,
Taxa allTaxa, BitSet activeTaxa, NodeArray<BitSet> reticulateNode2Taxa, SplitSystem splits) {
BitSet e_taxa = new BitSet();
int taxon = allTaxa.indexOf(tree.getLabel(v));
if (taxon > -1)
e_taxa.set(taxon);
for (Edge f = v.getFirstOutEdge(); f != null; f = v.getNextOutEdge(f)) {
Node w = f.getTarget();
BitSet f_taxa;
if (!tree.isReticulateEdge(f) || reticulateNode2Taxa.get(w) == null)
f_taxa = splitsFromTreeRec(w, tree, allTaxa, activeTaxa, reticulateNode2Taxa, splits);
else
f_taxa = reticulateNode2Taxa.get(w);
if (!tree.isReticulateEdge(f)) {
BitSet complement = (BitSet) activeTaxa.clone();
complement.andNot(f_taxa);
Split split = new Split(f_taxa, complement, tree.getWeight(f));
if (!splits.contains(split))
splits.addSplit(split);
else if (v == tree.getRoot() && v.getOutDegree() == 2) // is root split
{
Split prevSplit = splits.get(split);
if (prevSplit != null)
prevSplit.setWeight(prevSplit.getWeight() + split.getWeight());
}
} else
reticulateNode2Taxa.put(w, f_taxa);
e_taxa.or(f_taxa);
}
return e_taxa;
}
/**
* inserts a split into a tree
*
*/
private void processSplit(Node v, NodeArray<BitSet> node2taxa, int outGroupTaxonId, Split split, PhyloTree tree) {
BitSet partB = split.getPartNotContaining(outGroupTaxonId);
double weight = split.getWeight();
boolean done = false;
while (!done) {
var edgesToPush = new LinkedList<Edge>();
for (Edge f = v.getFirstOutEdge(); f != null; f = v.getNextOutEdge(f)) {
Node w = f.getTarget();
BitSet nodeSet = node2taxa.get(w);
if (nodeSet.intersects(partB))
edgesToPush.add(f);
}
if (edgesToPush.size() == 1) // need to move down tree
{
Edge f = edgesToPush.get(0);
v = f.getTarget();
} else if (edgesToPush.size() > 1) { // more than one subtree contains taxa from the set, time to split
Node u = tree.newNode();
node2taxa.put(u, partB);
Edge h = tree.newEdge(v, u);
tree.setWeight(h, weight);
for (Edge anEdgesToPush1 : edgesToPush) {
Edge f = anEdgesToPush1;
Node w = f.getTarget();
Edge g = tree.newEdge(u, w);
tree.setWeight(g, tree.getWeight(f));
}
for (Edge anEdgesToPush : edgesToPush) {
Edge f = anEdgesToPush;
tree.deleteEdge(f);
}
done = true;
} else {
throw new RuntimeException("0 taxa in splitsToTreeRec");
}
}
}
/**
* returns a trivial split separating index from all other taxa, if it exists
*
* @return trivial split, if it exists
*/
private Split getTrivial(int taxonIndex) {
for (var it = iterator(); it.hasNext(); ) {
Split split = it.next();
if (split.getA().cardinality() == 1 && split.getA().get(taxonIndex)
|| split.getB().cardinality() == 1 && split.getB().get(taxonIndex))
return split;
}
return null;
}
/**
* add all given splits that are not already present (as splits, ignoring weights etc)
*
* @return number actually added
*/
public int addAll(SplitSystem splits) {
int count = 0;
for (var it = splits.iterator(); it.hasNext(); ) {
Split split = it.next();
if (!split2index.containsKey(split)) {
addSplit(split);
count++;
}
}
return count;
}
/**
* get all splits in a new list
*
* @return list of splits
*/
public List<Split> asList() {
List<Split> result = new LinkedList<>();
for (var it = iterator(); it.hasNext(); ) {
result.add(it.next());
}
return result;
}
/**
* returns the splits as an array
*
* @return array of splits
*/
public Split[] asArray() {
Split[] result = new Split[size()];
int count = 0;
for (var it = iterator(); it.hasNext(); ) {
result[count++] = it.next();
}
return result;
}
/**
* if the given split A|B is contained in this split system, return it.
* This is useful because A|B might have a weight etc in the split system
*
* @return split
*/
private Split get(Split split) {
Integer index = split2index.get(split);
if (index != null)
return getSplit(index);
else
return null;
}
/**
* determines whether these splits contains a pair with all four intersections
*
*/
public boolean containsPairWithAllFourIntersections() {
for (int s = 1; s <= size(); s++) {
Split S = getSplit(s);
for (int t = s + 1; t <= size(); t++) {
Split T = getSplit(t);
if (S.getA().intersects(T.getA()) && S.getA().intersects(T.getB())
&& S.getB().intersects(T.getA()) && S.getB().intersects(T.getB()))
return true;
}
}
return false;
}
/**
* returns true, if all splits contain all taxa
*
* @return true, if full splits
*/
public boolean isFullSplitSystem(Taxa taxa) {
BitSet bits = taxa.getBits();
for (var it = iterator(); it.hasNext(); ) {
Split split = it.next();
if (!split.getTaxa().equals(bits))
return false;
}
return true;
}
/**
* gets the splits as binary sequences in fastA format
*
* @return splits in fastA format
*/
public String toStringAsBinarySequences(Taxa taxa) {
StringBuilder buf = new StringBuilder();
for (var it = taxa.iterator(); it.hasNext(); ) {
String name = (String) it.next();
int t = taxa.indexOf(name);
buf.append("> ").append(name).append("\n");
for (int s = 1; s <= size(); s++) {
Split split = getSplit(s);
if (split.getA().get(t))
buf.append("1");
else
buf.append("0");
}
buf.append("\n");
}
return buf.toString();
}
/**
* returns the heaviest trivial split or null
*
* @return heaviest trivial split
*/
public Split getHeaviestTrivialSplit() {
Split result = null;
for (int s = 1; s <= size(); s++) {
Split split = getSplit(s);
if (split.getSplitSize() == 1) {
if (result == null)
result = split;
else if (split.getWeight() > result.getWeight())
result = split;
}
}
return result;
}
/**
* delete all taxa listed
*
* @param taxa taxa are removed from here
* @return split set with taxa delated
*/
public SplitSystem deleteTaxa(List<String> labels, Taxa taxa) {
for (String label1 : labels) {
String label = label1;
taxa.remove(label);
}
SplitSystem result = new SplitSystem();
for (var it = iterator(); it.hasNext(); ) {
Split split = it.next();
Split induced = split.getInduced(taxa.getBits());
if (result.contains(induced)) {
Split other = result.get(induced);
if (other != null)
other.setWeight(other.getWeight() + induced.getWeight());
} else if (induced.getSplitSize() > 0) // make sure that is a proper split
result.addSplit(induced);
}
return result;
}
public void addAllTrivial(Taxa taxa) {
for(int t:taxa.members()) {
if(getTrivial(t)==null)
addSplit(new Split(BitSetUtils.asBitSet(t),BitSetUtils.minus(taxa.getBits(),BitSetUtils.asBitSet(t)),0));
}
}
}
| 12,479 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
Split.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/nnet/Split.java | /*
* Split.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.nnet;
import java.util.BitSet;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
/**
* a weighted split
* Daniel Huson, 6.2007
*/
public class Split implements Comparable, Comparator {
private final BitSet A;
private final BitSet B;
private double weight;
private final List weightList; // list of weights assigned to this split in different trees
private double confidence; // confidence in this split?
/**
* constructor
*/
public Split() {
this(null, null, 1, 1);
}
/**
* constructor
*
*/
public Split(BitSet A, BitSet B) {
this(A, B, 1, 1);
}
/**
* constructor
*
*/
public Split(BitSet A, BitSet B, double weight) {
this(A, B, weight, 1);
}
/**
* constructor
*
*/
public Split(BitSet A, BitSet B, double weight, double confidence) {
this.A = (A != null ? (BitSet) A.clone() : new BitSet());
this.B = (B != null ? (BitSet) B.clone() : new BitSet());
this.weight = weight;
this.weightList = new LinkedList();
this.confidence = confidence;
}
/**
* clone this split
*
* @return a clone of this split
*/
public Object clone() {
Split result = new Split();
result.copy(this);
return result;
}
/**
* copy a split
*
*/
private void copy(Split split) {
setA(split.getA());
setB(split.getB());
setWeight(split.getWeight());
weightList.addAll(split.weightList);
}
/**
* get the A part
*
* @return A part
*/
public BitSet getA() {
return A;
}
/**
* get the B part
*
* @return B part
*/
public BitSet getB() {
return B;
}
/**
* does A part contain taxon?
*
* @return true if contains taxon
*/
public boolean isAcontains(int taxon) {
return A.get(taxon);
}
/**
* does B part containt taxon?
*
* @return true if contains taxon
*/
public boolean isBcontains(int taxon) {
return B.get(taxon);
}
/**
* does A part contain set H?
*
* @return true if contains H
*/
public boolean isAcontains(BitSet H) {
BitSet M = ((BitSet) A.clone());
M.and(H);
return M.cardinality() == H.cardinality();
}
/**
* does B part contain set H?
*
* @return true if contains H
*/
public boolean isBcontains(BitSet H) {
BitSet M = ((BitSet) B.clone());
M.and(H);
return M.cardinality() == H.cardinality();
}
/**
* does A part intersect set H?
*
* @return true if intersects H
*/
public boolean isAintersects(BitSet H) {
return A.intersects(H);
}
/**
* does B part intersect set H?
*
* @return true if intersects H
*/
public boolean isBintersects(BitSet H) {
return B.intersects(H);
}
/**
* gets the split part containing taxon
*
* @return split part containing taxon, or null
*/
public BitSet getPartContaining(int taxon) {
if (A.get(taxon))
return A;
else if (B.get(taxon))
return B;
else
return null;
}
/**
* gets the first split part not containing taxon
*
* @return split part containing taxon, or null
*/
public BitSet getPartNotContaining(int taxon) {
if (!A.get(taxon))
return A;
else if (!B.get(taxon))
return B;
else
return null;
}
/**
* does the split split the given taxa?
*
* @return true, if both A and B intersects taxa
*/
public boolean splitsTaxa(BitSet taxa) {
return A.intersects(taxa) && B.intersects(taxa);
}
/**
* returns true, if split separates taxa a and b
*
* @return true, if separates
*/
public boolean separates(int a, int b) {
return A.get(a) && B.get(b) || A.get(b) && B.get(a);
}
/**
* returns true, if split separates the given set of taxa
*
* @return true, if separates
*/
public boolean separates(BitSet H) {
return A.intersects(H) && B.intersects(H);
}
/**
* gets the weight of split, or 1, of not set
*
* @return weight
*/
public double getWeight() {
return weight;
}
/**
* set the weight
*
*/
public void setWeight(double weight) {
this.weight = weight;
}
/**
* sets the A part of the split
*
*/
private void setA(BitSet A) {
this.A.clear();
this.A.or(A);
}
/**
* sets the B part of the split
*
*/
private void setB(BitSet B) {
this.B.clear();
this.B.or(B);
}
/**
* sets the split to A | B with weight 1
*
*/
public void set(BitSet A, BitSet B) {
set(A, B, 1);
}
/**
* sets the split to A |B with given weight
*
*/
private void set(BitSet A, BitSet B, double weight) {
this.A.clear();
this.A.or(A);
this.B.clear();
this.B.or(B);
this.weight = weight;
}
/**
* are the two splits equalOverShorterOfBoth as set bipartitionings (ignoring weights)
*
* @return true, if equalOverShorterOfBoth
*/
public boolean equals(Object object) {
return object instanceof Split && equals((Split) object);
}
/**
* are the two splits equalOverShorterOfBoth as set bipartitionings (ignoring weights)
*
* @return true, if equalOverShorterOfBoth
*/
private boolean equals(Split split) {
return (A.equals(split.A) && B.equals(split.B)) || (A.equals(split.B) && B.equals(split.A));
}
/**
* compare to a split object
*
* @return -1, 0 or 1, depending on relation
*/
public int compareTo(Object o) {
Split split = (Split) o;
BitSet P = getFirstPart();
BitSet Q = split.getFirstPart();
int a = P.nextSetBit(0);
int b = Q.nextSetBit(0);
while (a > -1 && b > -1) {
if (a < b)
return -1;
else if (a > b)
return 1;
a = P.nextSetBit(a + 1);
b = Q.nextSetBit(b + 1);
}
if (a < b)
return -1;
else if (a > b)
return 1;
P = getSecondPart();
Q = split.getSecondPart();
a = P.nextSetBit(0);
b = Q.nextSetBit(0);
while (a > -1 && b > -1) {
if (a < b)
return -1;
else if (a > b)
return 1;
a = P.nextSetBit(a + 1);
b = Q.nextSetBit(b + 1);
}
return Integer.compare(a, b);
}
/**
* compares two splits
*
* @return comparison
*/
public int compare(Object o1, Object o2) {
Split split1 = (Split) o1;
return split1.compareTo(o2);
}
/**
* gets the lexicographic first part
*
* @return first part
*/
private BitSet getFirstPart() {
if (A.nextSetBit(0) < B.nextSetBit(0))
return A;
else
return B;
}
/**
* gets the lexicographic second part
*
* @return first part
*/
private BitSet getSecondPart() {
if (A.nextSetBit(0) >= B.nextSetBit(0))
return A;
else
return B;
}
/**
* gets the hash code
*
* @return hash code
*/
public int hashCode() {
if (A.nextSetBit(0) < B.nextSetBit(0))
return A.hashCode() + 37 * B.hashCode();
else
return B.hashCode() + 37 * A.hashCode();
}
/**
* gets the split size, i.e. the cardinality of the smaller split part
*
* @return split size
*/
public int getSplitSize() {
return Math.min(A.cardinality(), B.cardinality());
}
/**
* gets the cardinality of the total set of both parts
*
* @return cardinality of union
*/
public int getCardinality() {
return A.cardinality() + B.cardinality();
}
public double getConfidence() {
return confidence;
}
public void setConfidence(double confidence) {
this.confidence = confidence;
}
/**
* add weight to list of weights
*
*/
public void addToWeightList(double weight) {
weightList.add(weight);
}
/**
* get the weight list
*
* @return weight list
*/
public List getWeightList() {
return weightList;
}
/**
* gets a string representation
*
* @return string
*/
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append(" taxa=").append(A.cardinality() + B.cardinality());
buf.append(" weight=").append((float) weight);
buf.append(" confidence=").append((float) confidence);
buf.append(":");
for (int a = A.nextSetBit(0); a != -1; a = A.nextSetBit(a + 1))
buf.append(" ").append(a);
buf.append(" |");
for (int b = B.nextSetBit(0); b != -1; b = B.nextSetBit(b + 1))
buf.append(" ").append(b);
return buf.toString();
}
/**
* is this split compatible with the given one?
*
* @return true, if compatible
*/
public boolean isCompatible(Split split) {
return !(getA().intersects(split.getA()) && getA().intersects(split.getB())
&& getB().intersects(split.getA()) && getB().intersects(split.getB()));
}
/**
* is split trivial?
*
* @return true, if trivial
*/
public boolean isTrivial() {
return getA().size() == 1 || getB().size() == 1;
}
/**
* gets all taxa mentioned in this split
*
* @return taxa
*/
public BitSet getTaxa() {
BitSet result = (BitSet) getA().clone();
result.or(getB());
return result;
}
/**
* gets the number of taxa in this split
*
* @return number of taxa
*/
public int getNumberOfTaxa() {
return getA().cardinality() + getB().cardinality();
}
/**
* gets the split induced by the given taxa set, or null, if result is not a proper split
*
* @return split or null
*/
public Split getInduced(BitSet taxa) {
Split result = (Split) clone();
result.getA().and(taxa);
result.getB().and(taxa);
if (result.getA().cardinality() > 0 && result.getB().cardinality() > 0)
return result;
else
return null;
}
/**
* get a comparator that compares splits by decreasing weight
*
* @return weight-based comparator
*/
public static Comparator createWeightComparator() {
return (o1, o2) -> {
Split split1 = (Split) o1;
Split split2 = (Split) o2;
if (split1.getWeight() > split2.getWeight())
return -1;
else if (split1.getWeight() < split2.getWeight())
return 1;
else
return split1.compareTo(split2);
};
}
/**
* get the A side (i=0) or B side (else) of the split
*
* @return A or B side of split
*/
public BitSet getSide(int i) {
if (i % 2 == 0)
return getA();
else
return getB();
}
/**
* set the split to A vs complement of A
*
*/
public void set(BitSet A, int ntax, double weight) {
BitSet B = new BitSet();
for (int i = 1; i <= ntax; i++)
if (!A.get(i))
B.set(i);
set(A, B, weight);
}
}
| 12,723 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CircularSplitWeights.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/nnet/CircularSplitWeights.java | /*
* CircularSplitWeights.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.nnet;
import megan.clusteranalysis.tree.Distances;
import java.util.Arrays;
import java.util.BitSet;
/**
* Given a circular ordering and a distance matrix,
* computes the unconstrained or constrained least square weighted splits
* <p/>
* For all vectors, the canonical ordering of pairs is (0,1),(0,2),...,(0,n-1),(1,2),(1,3),...,(1,n-1), ...,(n-1,n)
* <p/>
* (i,j) -> (2n - i -3)i/2 + j-1 .
* <p/>
* Increase i -> increase index by n-i-2
* Decrease i -> decrease index by n-i-1.
* <p/>
* <p/>
* x[i][j] is the split {i+1,i+2,...,j} | -------
*/
class CircularSplitWeights {
/* Epsilon constant for the conjugate gradient algorithm */
private static final double CG_EPSILON = 0.0001;
static public SplitSystem compute(int[] ordering, Distances dist, boolean constrained, double cutoff) {
final int ntax = dist.getNtax();
final int npairs = (ntax * (ntax - 1)) / 2;
//Handle n=1,2 separately.
if (ntax == 1)
return new SplitSystem();
if (ntax == 2) {
SplitSystem smallSplits = new SplitSystem();
float d_ij = (float) dist.get(ordering[1], ordering[2]);
if (d_ij > 0.0) {
BitSet A = new BitSet();
A.set(ordering[1]);
Split split = new Split();
split.set(A, ntax, d_ij);
smallSplits.addSplit(split);
}
return smallSplits;
}
/* Re-order taxa so that the ordering is 0,1,2,...,n-1 */
final double[] d = setupD(dist, ordering);
final double[] x = new double[npairs];
if (!constrained)
CircularSplitWeights.runUnconstrainedLS(ntax, d, x);
else // do constrained optimization
{
final double[] W = setupW(dist.getNtax());
/* Find the constrained optimal values for x */
runActiveConjugate(ntax, d, W, x);
}
/* Construct the splits with the appropriate weights */
SplitSystem splits = new SplitSystem();
int index = 0;
for (int i = 0; i < ntax; i++) {
BitSet A = new BitSet();
for (int j = i + 1; j < ntax; j++) {
A.set(ordering[j + 1]);
if (x[index] > cutoff) {
Split split = new Split();
split.set(A, ntax, (float) (x[index]));
splits.addSplit(split);
}
index++;
}
}
return splits;
}
/**
* setup working distance so that ordering is trivial.
* Note the the code assumes that taxa are labeled 0..ntax-1 and
* we do the transition here. It is undone when extracting the splits
*
* @param dist Distances block
* @param ordering circular ordering
* @return double[] distances stored as a vector
*/
static private double[] setupD(Distances dist, int[] ordering) {
final int ntax = dist.getNtax();
final int npairs = ((ntax - 1) * ntax) / 2;
double[] d = new double[npairs];
int index = 0;
for (int i = 0; i < ntax; i++)
for (int j = i + 1; j < ntax; j++)
d[index++] = dist.get(ordering[i + 1], ordering[j + 1]);
return d;
}
static private double[] setupW(int ntax) {
final int npairs = ((ntax - 1) * ntax) / 2;
double[] v = new double[npairs];
int index = 0;
for (int i = 0; i < ntax; i++)
for (int j = i + 1; j < ntax; j++) {
v[index] = 1.0;
index++;
}
return v;
}
/**
* Compute the branch lengths for unconstrained least squares using
* the formula of Chepoi and Fichet (this takes O(N^2) time only!).
*
* @param n the number of taxa
* @param d the distance matrix
* @param x the split weights
*/
static private void runUnconstrainedLS(int n, double[] d, double[] x) {
int index = 0;
for (int i = 0; i <= n - 3; i++) {
//index = (i,i+1)
//x[i,i+1] = (d[i][i+1] + d[i+1][i+2] - d[i,i+2])/2
x[index] = (d[index] + d[index + (n - i - 2) + 1] - d[index + 1]) / 2.0;
index++;
for (int j = i + 2; j <= n - 2; j++) {
//x[i][j] = ( d[i,j] + d[i+1,j+1] - d[i,j+1] - d[i+1][j])
x[index] = (d[index] + d[index + (n - i - 2) + 1] - d[index + 1] - d[index + (n - i - 2)]) / 2.0;
index++;
}
//index = (i,n-1)
if (i == 0) //(0,n-1)
x[index] = (d[0] + d[n - 2] - d[2 * n - 4]) / 2.0; //(d[0,1] + d[0,n-1] - d[1,n-1])/2
else
//x[i][n-1] == (d[i,n-1] + d[i+1,0] - d[i,0] - d[i+1,n-1])
x[index] = (d[index] + d[i] - d[i - 1] - d[index + (n - i - 2)]) / 2.0;
index++;
}
//index = (n-2,n-1)
x[index] = (d[index] + d[n - 2] - d[n - 3]) / 2.0;
}
/**
* Returns the array indices for the smallest propKept proportion of negative values in x.
* In the case of ties, priority is given to the earliest entries.
* Size of resulting array will be propKept * (number of negative entries) rounded up.
*
* @param x returns an array
* @param propKept the
* @return int[] array of indices
*/
static private int[] worstIndices(double[] x, double propKept) {
if (propKept == 0)
return null;
int n = x.length;
int numNeg = 0;
for (double aX1 : x)
if (aX1 < 0.0)
numNeg++;
if (numNeg == 0)
return null;
double[] xcopy = new double[numNeg];
int j = 0;
for (double aX : x)
if (aX < 0.0)
xcopy[j++] = aX;
Arrays.sort(xcopy);
int nkept = (int) Math.ceil(propKept * numNeg);
double cutoff = xcopy[nkept - 1];
int[] result = new int[nkept];
int front = 0, back = nkept - 1;
for (int i = 0; i < n; i++) {
if (x[i] < cutoff)
result[front++] = i;
else if (x[i] == cutoff) {
if (back >= front)
result[back--] = i;
}
}
return result;
}
/**
* Uses an active set method with the conjugate gradient algorithm to find x that minimises
* <p/>
* (Ax - d)W(Ax-d)
* <p/>
* Here, A is the design matrix for the set of cyclic splits with ordering 0,1,2,...,n-1
* d is the distance vector, with pairs in order (0,1),(0,2),...,(0,n-1),(1,2),(1,3),...,(1,n-1), ...,(n-1,n)
* W is a vector of variances for d, with pairs in same order as d.
* x is a vector of split weights, with pairs in same order as d. The split (i,j), for i<j, is {i,i+1,...,j-1}| rest
*
* @param ntax The number of taxa
* @param d the distance matrix
* @param W the weight matrix
* @param x the split weights
*/
static private void runActiveConjugate(int ntax, double[] d, double[] W, double[] x) {
int npairs = d.length;
if (W.length != npairs || x.length != npairs)
throw new IllegalArgumentException("Vectors d,W,x have different dimensions");
CircularSplitWeights.runUnconstrainedLS(ntax, d, x);
boolean all_positive = true;
for (int k = 0; k < npairs; k++)
if (x[k] < 0.0) {
all_positive = false;
break;
}
if (all_positive)
return;
final boolean[] active = new boolean[npairs];
double[] y = new double[npairs];
double[] AtWd = new double[npairs];
for (int k = 0; k < npairs; k++)
y[k] = W[k] * d[k];
CircularSplitWeights.calculateAtx(ntax, y, AtWd);
final double[] r = new double[npairs];
final double[] w = new double[npairs];
final double[] p = new double[npairs];
final double[] old_x = new double[npairs];
Arrays.fill(old_x, 1.0);
boolean first_pass = true;
while (true) {
while (true) {
if(first_pass)
first_pass=false;
else
CircularSplitWeights.circularConjugateGrads(ntax, npairs, r, w, p, y, W, AtWd, active, x);
final int[] entriesToContract = worstIndices(x, 0.6);
if (entriesToContract != null) {
for (int index : entriesToContract) {
x[index] = 0.0;
active[index] = true;
}
CircularSplitWeights.circularConjugateGrads(ntax, npairs, r, w, p, y, W, AtWd, active, x);
}
int min_i = -1;
double min_xi = -1.0;
for (int i = 0; i < npairs; i++) {
if (x[i] < 0.0) {
double xi = (old_x[i]) / (old_x[i] - x[i]);
if ((min_i == -1) || (xi < min_xi)) {
min_i = i;
min_xi = xi;
}
}
}
if (min_i == -1)
break;
else {
for (int i = 0; i < npairs; i++) {
if (!active[i])
old_x[i] += min_xi * (x[i] - old_x[i]);
}
active[min_i] = true;
x[min_i] = 0.0;
}
}
calculateAb(ntax, x, y);
for (int i = 0; i < npairs; i++)
y[i] *= W[i];
calculateAtx(ntax, y, r); /* r = AtWAx */
int min_i = -1;
double min_grad = 1.0;
for (int i = 0; i < npairs; i++) {
r[i] -= AtWd[i];
r[i] *= 2.0;
if (active[i]) {
double grad_ij = r[i];
if ((min_i == -1) || (grad_ij < min_grad)) {
min_i = i;
min_grad = grad_ij;
}
}
}
if ((min_i == -1) || (min_grad > -0.0001))
return;
else
active[min_i] = false;
}
}
/* Compute the row sum in d. */
static private double rowSum(int n, double[] d, int k) {
double r = 0;
int index = 0;
if (k > 0) {
index = k - 1;
for (int i = 0; i < k; i++) {
r += d[index];
index += (n - i - 2);
}
index++;
}
for (int j = k + 1; j < n; j++)
r += d[index++];
return r;
}
/**
* Computes p = A^Td, where A is the topological matrix for the
* splits with circular ordering 0,1,2,....,ntax-1
* *
*
* @param n number of taxa
* @param d distance matrix
* @param p the result
*/
static private void calculateAtx(int n, double[] d, double[] p) {
int index = 0;
for (int i = 0; i < n - 1; i++) {
p[index] = rowSum(n, d, i + 1);
index += (n - i - 1);
}
index = 1;
for (int i = 0; i < n - 2; i++) {
p[index] = p[index - 1] + p[index + (n - i - 2)] - 2 * d[index + (n - i - 2)];
index += (n - i - 2) + 1;
}
for (int k = 3; k <= n - 1; k++) {
index = k - 1;
for (int i = 0; i < n - k; i++) {
p[index] = p[index - 1] + p[index + n - i - 2] - p[index + n - i - 3] - 2.0 * d[index + n - i - 2];
index += (n - i - 2) + 1;
}
}
}
/**
* Computes d = Ab, where A is the topological matrix for the
* splits with circular ordering 0,1,2,....,ntax-1
*
* @param n number of taxa
* @param b split weights
* @param d pairwise distances from split weights
*/
static private void calculateAb(int n, double[] b, double[] d) {
{
int dindex = 0;
for (int i = 0; i < n - 1; i++) {
double d_ij = 0.0;
int index = i - 1;
for (int k = 0; k < i; k++) {
d_ij += b[index];
index += (n - k - 2);
}
index++;
for (int k = i + 1; k < n ; k++)
d_ij += b[index++];
d[dindex] = d_ij;
dindex += (n - i - 2) + 1;
}
}
{
int index = 1;
for (int i = 0; i <= n - 3; i++) {
d[index] = d[index - 1] + d[index + (n - i - 2)] - 2 * b[index - 1];
index += 1 + (n - i - 2);
}
}
for (int k = 3; k <n ; k++) {
int index = k - 1;
for (int i = 0; i < n - k; i++) {
d[index] = d[index - 1] + d[index + (n - i - 2)] - d[index + (n - i - 2) - 1] - 2.0 * b[index - 1];
index += 1 + (n - i - 2);
}
}
}
/**
* Computes sum of squares of the lower triangle of the matrix x
*
* @param x the matrix
* @return sum of squares of the lower triangle
*/
static private double norm(double[] x) {
double norm = 0.0;
for (double v : x) {
norm += v * v;
}
return norm;
}
/**
* Conjugate gradient algorithm solving A^tWA x = b (where b = AtWd)
* such that all x[i][j] for which active[i][j] = true are set to zero.
* We assume that x[i][j] is zero for all active i,j, and use the given
* values for x as our starting vector.
*
* @param ntax the number of taxa
* @param npairs dimension of b and x
* @param r stratch matrix
* @param w stratch matrix
* @param p stratch matrix
* @param y stratch matrix
* @param W the W matrix
* @param b the b matrix
* @param active the active constraints
* @param x the x matrix
*/
static private void circularConjugateGrads(int ntax, int npairs,
double[] r, double[] w, double[] p, double[] y,
double[] W, double[] b,
boolean[] active, double[] x) {
int kmax = ntax * (ntax - 1) / 2;
calculateAb(ntax, x, y);
for (int k = 0; k < npairs; k++)
y[k] = W[k] * y[k];
calculateAtx(ntax, y, r);
for (int k = 0; k < npairs; k++)
if (!active[k])
r[k] = b[k] - r[k];
else
r[k] = 0.0;
double rho = norm(r);
double rho_old = 0;
double e_0 = CG_EPSILON * Math.sqrt(norm(b));
int k = 0;
while ((rho > e_0 * e_0) && (k < kmax)) {
k = k + 1;
if (k == 1) {
System.arraycopy(r, 0, p, 0, npairs);
} else {
double beta = rho / rho_old;
for (int i = 0; i < npairs; i++)
p[i] = r[i] + beta * p[i];
}
calculateAb(ntax, p, y);
for (int i = 0; i < npairs; i++)
y[i] *= W[i];
calculateAtx(ntax, y, w);
for (int i = 0; i < npairs; i++)
if (active[i])
w[i] = 0.0;
double alpha = 0.0;
for (int i = 0; i < npairs; i++)
alpha += p[i] * w[i];
alpha = rho / alpha;
for (int i = 0; i < npairs; i++) {
x[i] += alpha * p[i];
r[i] -= alpha * w[i];
}
rho_old = rho;
rho = norm(r);
}
}
}
| 16,790 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
EcologicalIndexChiSquareCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/EcologicalIndexChiSquareCommand.java | /*
* EcologicalIndexChiSquareCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.indices.ChiSquareDistance;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* method=ChiSquare command
* Daniel Huson, 6.2010
*/
public class EcologicalIndexChiSquareCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getEcologicalIndex().equalsIgnoreCase(ChiSquareDistance.NAME);
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Use Chi-Square";
}
/**
* get description to be used as a tool-tip
*
* @return description
*/
public String getDescription() {
return "Use ChiSquare ecological index (Lebart et al, 1979)";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set index=" + ChiSquareDistance.NAME + ";");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getViewer().getParentViewer() != null && getViewer().getParentViewer().hasComparableData()
&& getViewer().getParentViewer().getSelectedNodes().size() > 0;
}
/**
* 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;
}
/**
* parses the given command and executes it
*/
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
public String getSyntax() {
return null;
}
}
| 3,407 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
EcologicalIndexKulczynskiCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/EcologicalIndexKulczynskiCommand.java | /*
* EcologicalIndexKulczynskiCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.indices.KulczynskiDistance;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* method=Kulczynski command
* Daniel Huson, 6.2010
*/
public class EcologicalIndexKulczynskiCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getEcologicalIndex().equalsIgnoreCase(KulczynskiDistance.NAME);
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Use Kulczynski";
}
/**
* get description to be used as a tool-tip
*
* @return description
*/
public String getDescription() {
return "Use Kulczynski ecological index (Odum, 1950)";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set index=" + KulczynskiDistance.NAME + ";");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getViewer().getParentViewer() != null && getViewer().getParentViewer().hasComparableData()
&& getViewer().getParentViewer().getSelectedNodes().size() > 0;
}
/**
* 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;
}
/**
* parses the given command and executes it
*/
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
public String getSyntax() {
return null;
}
}
| 3,406 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowNetworkTabCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/ShowNetworkTabCommand.java | /*
* ShowNetworkTabCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* choose network tab
* Daniel Huson, 7.2010
*/
public class ShowNetworkTabCommand extends CommandBase implements ICheckBoxCommand {
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Network";
}
public String getAltName() {
return "Network Tab";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Open the network tab";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
public boolean isSelected() {
return getViewer().getSelectedComponent() == getViewer().getNnetTab();
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
getViewer().selectComponent(getViewer().getNnetTab());
}
}
| 2,897 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CopyImageCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/CopyImageCommand.java | /*
* CopyImageCommand.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.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.export.TransferableGraphic;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* copy command
* Daniel Huson, 7.2010
*/
public class CopyImageCommand extends CommandBase implements ICommand {
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Copy Image";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Copy the current data as an image";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Copy16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | java.awt.event.InputEvent.SHIFT_DOWN_MASK);
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("copyImage;");
ClusterViewer viewer = getViewer();
JPanel panel = viewer.getPanel();
JScrollPane scrollPane = viewer.getSelectedScrollPane();
TransferableGraphic tg = new TransferableGraphic(panel, scrollPane);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(tg, tg);
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "copyImage;";
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute("copyImage;");
}
}
| 3,386 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowNJTreeTabCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/ShowNJTreeTabCommand.java | /*
* ShowNJTreeTabCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* choose nj tab
* Daniel Huson, 7.2010
*/
public class ShowNJTreeTabCommand extends CommandBase implements ICheckBoxCommand {
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "NJ Tree";
}
public String getAltName() {
return "NJ Tree Tab";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Open the NJ tree tab";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
public boolean isSelected() {
return getViewer().getSelectedComponent() == getViewer().getNJTab();
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
getViewer().selectComponent(getViewer().getNJTab());
}
}
| 2,887 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetGroupColorCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/SetGroupColorCommand.java | /*
* SetGroupColorCommand.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.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseColorLineWidthDialog;
import jloda.util.Pair;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.gui.PCoATab;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* set group color
* Daniel Huson, 10.2017
*/
public class SetGroupColorCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
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().getSelectedComponent() == getViewer().getPcoaTab();
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Set Groups Linewidth and Color...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Set group line-width and color";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
final PCoATab pCoATab = getViewer().getPcoaTab();
final Pair<Integer, Color> pair = ChooseColorLineWidthDialog.showDialog(getViewer().getFrame(), "Choose group line-width and color",
pCoATab.getGroupLineWidth(), pCoATab.getGroupsColor());
if (pair != null) {
final int lineWidth = pair.getFirst();
final Color color = pair.getSecond();
if (lineWidth != pCoATab.getGroupLineWidth() || !color.equals(pCoATab.getGroupsColor())) {
executeImmediately("setColor target=groups color=" + color.getRed() + " " + color.getGreen() + " " + color.getBlue() + " lineWidth=" + lineWidth + ";");
}
}
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,684 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetPC1vsPC2Command.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/SetPC1vsPC2Command.java | /*
* SetPC1vsPC2Command.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* PC1 vs PC2
* Daniel Huson, 9.2012
*/
public class SetPC1vsPC2Command extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getPcoaTab() != null
&& viewer.getPcoaTab().getFirstPC() == 0 && viewer.getPcoaTab().getSecondPC() == 1 && !viewer.getPcoaTab().isIs3dMode();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* 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().getTabbedIndex() == ClusterViewer.PCoA_TAB_INDEX;
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "PC1 vs PC2";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Set principle components to use";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("PC1vPC2_16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_1, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set pc1=1 pc2=2;");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,492 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
FlipHCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/FlipHCommand.java | /*
* FlipHCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.Basic;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* flip horizontally
* Daniel Huson, 3.2013
*/
public class FlipHCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
return isApplicable() && getViewer().getPcoaTab() != null && getViewer().getPcoaTab().isFlipH();
}
/**
* parses the given command and executes it
*/
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set flipH=");
boolean flip = np.getBoolean();
np.matchIgnoreCase(";");
getViewer().getPcoaTab().setFlipH(flip);
try {
getViewer().getGraphView().getGraph().clear();
getViewer().updateGraph();
} catch (Exception ex) {
Basic.caught(ex);
}
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set flipH={false|true};";
}
/**
* 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().getSelectedComponent() == getViewer().getPcoaTab();
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Flip Horizontally";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Flip horizontally";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set flipH=" + (!isSelected()) + ";");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,517 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetPC1vsPC3Command.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/SetPC1vsPC3Command.java | /*
* SetPC1vsPC3Command.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* PC1 vs PC3
* Daniel Huson, 9.2012
*/
public class SetPC1vsPC3Command extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getPcoaTab() != null && viewer.getPcoaTab().getFirstPC() == 0 && viewer.getPcoaTab().getSecondPC() == 2 && !viewer.getPcoaTab().isIs3dMode();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* 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().getTabbedIndex() == ClusterViewer.PCoA_TAB_INDEX;
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "PC1 vs PC3";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Set principle components to use";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("PC1vPC3_16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_2, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set pc1=1 pc2=3;");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,476 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
WeightedTaxonomicUniFracCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/WeightedTaxonomicUniFracCommand.java | /*
* WeightedTaxonomicUniFracCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.indices.UniFrac;
import megan.viewer.MainViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* UnweightedTaxonomicUniFrac command
* Daniel Huson, 11.2017
*/
public class WeightedTaxonomicUniFracCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getEcologicalIndex().equalsIgnoreCase(UniFrac.WeightedUniformUniFrac);
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Use Weighted Uniform UniFrac";
}
/**
* get description to be used as a tool-tip
*
* @return description
*/
public String getDescription() {
return "Use the weighted uniform UniFrac metric.\n" +
"For any two samples, this is the sum of absolute differences of summarized counts over all ranked nodes, normalized (Lozupone and Knight, 2005)";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set index=" + UniFrac.WeightedUniformUniFrac + ";");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
@Override
public void apply(NexusStreamParser np) {
}
@Override
public String getSyntax() {
return null;
}
@Override
public boolean isCritical() {
return true;
}
@Override
public boolean isApplicable() {
return getViewer().getParentViewer() != null && getViewer().getParentViewer() instanceof MainViewer
&& getViewer().getParentViewer().getSelectedNodes().size() > 0;
}
}
| 3,233 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowGroupsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/ShowGroupsCommand.java | /*
* ShowGroupsCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.director.IDirector;
import jloda.util.Basic;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* show groups as ellipses
* Daniel Huson, 9.2016
*/
public class ShowGroupsCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getPcoaTab() != null && viewer.getPcoaTab().isShowGroupsAsEllipses();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set showGroups=");
final boolean show = np.getBoolean();
final String style;
if (np.peekMatchIgnoreCase("style")) {
np.matchIgnoreCase("style=");
style = np.getWordMatchesIgnoringCase("ellipses convexHulls");
} else
style = "ellipses";
np.matchIgnoreCase(";");
final ClusterViewer viewer = getViewer();
if (style.equalsIgnoreCase("ellipses"))
viewer.getPcoaTab().setShowGroupsAsEllipses(show);
else
viewer.getPcoaTab().setShowGroupsAsConvexHulls(show);
try {
if (show)
viewer.getPcoaTab().computeConvexHullsAndEllipsesForGroups(viewer.getGroup2Nodes());
viewer.updateView(IDirector.ENABLE_STATE);
} catch (Exception ex) {
Basic.caught(ex);
}
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set showGroups={false|true} [style={ellipses|convexHulls}];";
}
/**
* 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().isPCoATab();
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Show Groups";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Show groups";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null; //ResourceManager.getIcon("PC1vPC2_16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
executeImmediately("set showGroups=" + (!isSelected()) + " style=ellipses;");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 4,244 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
UpdateGraphCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/UpdateGraphCommand.java | /*
* UpdateGraphCommand.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.commands;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* update current graph
* Daniel Huson, 7.2016
*/
public class UpdateGraphCommand extends CommandBase implements ICommand {
public UpdateGraphCommand() {
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return null;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Update the current graph";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
final ClusterViewer viewer = getViewer();
viewer.updateGraph();
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "updateGraph;"; // not a command-line command
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
}
}
| 2,887 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
TriangulationTestCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/TriangulationTestCommand.java | /*
* TriangulationTestCommand.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.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.TriangulationTest;
import megan.commands.CommandBase;
import megan.core.Document;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
/**
* apply the triangulation test
* Daniel Huson, 11.2015
*/
public class TriangulationTestCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "triangulationTest attribute=<name>;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("triangulationTest attribute=");
final String attribute = np.getLabelRespectCase();
np.matchIgnoreCase(";");
final ClusterViewer viewer = (ClusterViewer) getViewer();
final Document doc = viewer.getDocument();
if (TriangulationTest.isSuitableAttribute(doc.getSampleAttributeTable(), attribute)) {
TriangulationTest triangulationTest = new TriangulationTest();
boolean rejectedH0 = triangulationTest.apply(viewer, attribute);
if (rejectedH0) {
NotificationsInSwing.showInformation(viewer.getFrame(), "Triangulation test REJECTS null hypothesis that samples come from same distribution (alpha=0.05, attribute='" + attribute + "')");
} else {
NotificationsInSwing.showInformation(viewer.getFrame(), "Triangulation test FAILS to reject null hypothesis that samples come from same distribution (attribute='" + attribute + "')");
}
} else
NotificationsInSwing.showWarning(viewer.getFrame(), "Triangulation test not applicable to attribute '" + attribute + "': doesn't have at least two samples per value");
}
public void actionPerformed(ActionEvent event) {
final ClusterViewer viewer = (ClusterViewer) getViewer();
final Document doc = viewer.getDocument();
List<String> attributes = doc.getSampleAttributeTable().getAttributeOrder();
ArrayList<String> choices = new ArrayList<>(attributes.size());
for (String attribute : attributes) {
if (TriangulationTest.isSuitableAttribute(doc.getSampleAttributeTable(), attribute))
choices.add(attribute);
}
if (choices.size() > 0) {
String choice = ProgramProperties.get("TriangulationTestChoice", choices.get(0));
if (!choices.contains(choice))
choice = choices.get(0);
final String[] array = choices.toArray(new String[0]);
choice = (String) JOptionPane.showInputDialog(getViewer().getFrame(), "Attribute that defines biological replicates:",
"Setup triangulation test", JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon(), array, choice);
if (choice != null) {
ProgramProperties.put("TriangulationTestChoice", choice);
execute("triangulationTest attribute='" + choice + "';");
}
} else {
NotificationsInSwing.showWarning("Triangulation test not applicable: no attribute that defines biological replicates, with at least two samples per value");
}
}
public boolean isCritical() {
return true;
}
public boolean isApplicable() {
return getViewer() instanceof ClusterViewer && ((ClusterViewer) getViewer()).getDocument().getSampleAttributeTable().getNumberOfAttributes() > 0;
}
public String getName() {
return "Apply Triangulation Test...";
}
public ImageIcon getIcon() {
return null;
}
public String getDescription() {
return "Applies the triangulation test to determine whether biological samples have same distribution, based on multiple technical replicates per sample";
}
}
| 4,861 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetPC2vsPC3Command.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/SetPC2vsPC3Command.java | /*
* SetPC2vsPC3Command.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* PC2 vs PC3
* Daniel Huson, 9.2012
*/
public class SetPC2vsPC3Command extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getPcoaTab() != null && viewer.getPcoaTab().getFirstPC() == 1 && viewer.getPcoaTab().getSecondPC() == 2 && !viewer.getPcoaTab().isIs3dMode();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* 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().getTabbedIndex() == ClusterViewer.PCoA_TAB_INDEX;
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "PC2 vs PC3";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Set principle components to use";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("PC2vPC3_16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_3, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set pc1=2 pc2=3;");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,476 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CommandBase.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/CommandBase.java | /*
* CommandBase.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.clusteranalysis.commands;
import megan.clusteranalysis.ClusterViewer;
/**
* base class for NetworkViewer commands
* Daniel Huson, 6.2010
*/
public abstract class CommandBase extends jloda.swing.commands.CommandBase {
public ClusterViewer getViewer() {
return (ClusterViewer) super.getViewer();
}
}
| 1,140 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
PasteCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/PasteCommand.java | /*
* PasteCommand.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.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import javax.swing.text.DefaultEditorKit;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* paste command
* Daniel Huson, 7.2010
*/
public class PasteCommand extends CommandBase implements ICommand {
private final Action action;
public PasteCommand() {
action = findAction(new DefaultEditorKit(), DefaultEditorKit.cutAction);
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Paste";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Paste the current data";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Paste16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null; // not a command-line command
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return false;
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
action.actionPerformed(ev);
}
private Action findAction(DefaultEditorKit kit, String name) {
Action[] actions = kit.getActions();
for (int i = 0; i < kit.getActions().length; i++) {
Action action = actions[i];
if (action.getValue(AbstractAction.NAME).equals(name))
return action;
}
return null;
}
}
| 3,433 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SyncCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/SyncCommand.java | /*
* SyncCommand.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.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* close the window
* Daniel Huson, 6.2010
*/
public class SyncCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "sync;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
final ClusterViewer viewer = getViewer();
viewer.updateDistances();
viewer.updateGraph();
}
public void actionPerformed(ActionEvent event) {
execute(getSyntax());
}
public boolean isApplicable() {
return getViewer().getParentViewer() != null && getViewer().getParentViewer().hasComparableData()
&& getViewer().getParentViewer().getSelectedNodes().size() > 0;
}
public String getName() {
return "Sync";
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
public String getDescription() {
return "Sync view of data";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Refresh16.gif");
}
public boolean isCritical() {
return true;
}
}
| 2,316 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowPCoATabCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/ShowPCoATabCommand.java | /*
* ShowPCoATabCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* choose mds tab
* Daniel Huson, 7.2010
*/
public class ShowPCoATabCommand extends CommandBase implements ICheckBoxCommand {
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "PCoA";
}
public String getAltName() {
return "PCoA Tab";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Open the PCoA tab";
}
/**
* 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;
}
public boolean isSelected() {
return getViewer().getSelectedComponent() == getViewer().getPcoaTab();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
getViewer().selectComponent(getViewer().getPcoaTab());
}
}
| 2,878 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetBiPlotColorCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/SetBiPlotColorCommand.java | /*
* SetBiPlotColorCommand.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.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseColorLineWidthDialog;
import jloda.util.Pair;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.gui.PCoATab;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* set biplot color
* Daniel Huson, 10.2017
*/
public class SetBiPlotColorCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
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().getSelectedComponent() == getViewer().getPcoaTab();
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Set BiPlot Linewidth and Color...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Set bi-plot line-width and color";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
final PCoATab pCoATab = getViewer().getPcoaTab();
final Pair<Integer, Color> pair = ChooseColorLineWidthDialog.showDialog(getViewer().getFrame(), "Choose bi-plot line-width and color", pCoATab.getBiPlotLineWidth(), pCoATab.getBiPlotColor());
if (pair != null) {
final int lineWidth = pair.getFirst();
final Color color = pair.getSecond();
if (lineWidth != pCoATab.getBiPlotLineWidth() || !color.equals(pCoATab.getBiPlotColor())) {
executeImmediately("setColor target=biPlot color=" + color.getRed() + " " + color.getGreen() + " " + color.getBlue() + " lineWidth=" + lineWidth + ";");
}
}
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,677 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetPCIvsPCJvsPCkCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/SetPCIvsPCJvsPCkCommand.java | /*
* SetPCIvsPCJvsPCkCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.gui.PCoATab;
import megan.clusteranalysis.pcoa.PCoA;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* PC2 vs PC3
* Daniel Huson, 9.2012
*/
public class SetPCIvsPCJvsPCkCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getPcoaTab() != null && viewer.getPcoaTab().getPCoA() != null && viewer.getPcoaTab().getPCoA().getNumberOfPositiveEigenValues() > 3
&& !(viewer.getPcoaTab().getFirstPC() == 0 && viewer.getPcoaTab().getSecondPC() == 1 && viewer.getPcoaTab().getThirdPC() == 2)
&& viewer.getPcoaTab().isIs3dMode();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* 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().isPCoATab();
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "PCi PCj PCk...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Display three principle components";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("PCIvPCJvsPCK_16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_6, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
PCoATab tab = getViewer().getPcoaTab();
PCoA PCoA = tab.getPCoA();
int numberOfPCs = PCoA.getNumberOfPositiveEigenValues();
String value = (tab.getFirstPC() + 1) + " x " + (tab.getSecondPC() + 1) + " x " + (tab.getThirdPC() + 1);
value = JOptionPane.showInputDialog(getViewer().getFrame(), "Enter PCs (range 1-" + numberOfPCs + "):", value);
if (value != null) {
try {
String[] tokens = value.split("x");
int pc1 = Integer.parseInt(tokens[0].trim());
int pc2 = Integer.parseInt(tokens[1].trim());
int pc3 = Integer.parseInt(tokens[2].trim());
execute("set pc1=" + pc1 + " pc2=" + pc2 + " pc3=" + pc3 + ";");
} catch (Exception ex) {
NotificationsInSwing.showError(getViewer().getFrame(), "Expected 'pc1 x pc2 xpc3', got: " + value);
}
}
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 4,668 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectInvertedCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/SelectInvertedCommand.java | /*
* SelectInvertedCommand.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.commands;
import jloda.swing.commands.ICommand;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* select all nodes
* Daniel Huson, 6.2010
*/
public class SelectInvertedCommand extends SelectCommand implements ICommand {
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Invert";
}
/**
* get an alternative name used to identify this command
*
* @return name
*/
@Override
public String getAltName() {
return "Invert Selection";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Invert selection of nodes";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
executeImmediately("select=invert;");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getViewer().getTabbedIndex() != ClusterViewer.MATRIX_TAB_INDEX;
}
}
| 2,575 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
EcologicalIndexEuclideanCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/EcologicalIndexEuclideanCommand.java | /*
* EcologicalIndexEuclideanCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.indices.EuclideanDistance;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* method=Euclidean command
* Daniel Huson, 6.2010
*/
public class EcologicalIndexEuclideanCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getEcologicalIndex().equalsIgnoreCase(EuclideanDistance.NAME);
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Use Euclidean";
}
/**
* get description to be used as a tool-tip
*
* @return description
*/
public String getDescription() {
return "Use Euclidean ecological index";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set index=" + EuclideanDistance.NAME + ";");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getViewer().getParentViewer() != null && getViewer().getParentViewer().hasComparableData()
&& getViewer().getParentViewer().getSelectedNodes().size() > 0;
}
/**
* 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;
}
/**
* parses the given command and executes it
*/
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
public String getSyntax() {
return null;
}
}
| 3,385 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
MatrixTabCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/MatrixTabCommand.java | /*
* MatrixTabCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* choose mds tab
* Daniel Huson, 7.2010
*/
public class MatrixTabCommand extends CommandBase implements ICheckBoxCommand {
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Matrix";
}
public String getAltName() {
return "Matrix Tab";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Open the matrix tab";
}
/**
* 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;
}
public boolean isSelected() {
return getViewer().getSelectedComponent() == getViewer().getMatrixTab();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
getViewer().selectComponent(getViewer().getMatrixTab());
}
}
| 2,886 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowUPGMATreeTabCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/ShowUPGMATreeTabCommand.java | /*
* ShowUPGMATreeTabCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* choose nj tab
* Daniel Huson, 7.2010
*/
public class ShowUPGMATreeTabCommand extends CommandBase implements ICheckBoxCommand {
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "UPGMA Tree";
}
public String getAltName() {
return "UPGMA Tree Tab";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Open the UPGMA tree tab";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
public boolean isSelected() {
return getViewer().getSelectedComponent() == getViewer().getUpgmaTab();
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* parses the given command and executes it
*
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
getViewer().selectComponent(getViewer().getUpgmaTab());
}
}
| 2,912 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
DataSeedCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/DataSeedCommand.java | /*
* DataSeedCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import megan.clusteranalysis.ClusterViewer;
import megan.core.ClassificationType;
import megan.core.Director;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* data=seed command
* Daniel Huson, 6.2010
*/
public class DataSeedCommand extends DataCommand implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getDataType().equalsIgnoreCase("SEED");
}
/**
* set the selected status of this command
*
*/
public void setSelected(boolean selected) {
ClusterViewer viewer = getViewer();
viewer.setDataType("SEED");
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Use SEED";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Use SEED as basis of comparison";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set networkdata=" + ClassificationType.SEED + ";");
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
ClassificationViewer viewer = (ClassificationViewer) ((Director) getDir()).getViewerByClassName("SEED");
return viewer != null && viewer.hasComparableData();
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,048 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetTriPlotScaleFactorCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/SetTriPlotScaleFactorCommand.java | /*
* SetTriplotSizeCommand.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
* MERCHANTATRILITY 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.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.NumberUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* set scale factor
* Daniel Huson, 1.2023
*/
public class SetTriPlotScaleFactorCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
var viewer = getViewer();
np.matchIgnoreCase("set triPlotScaleFactor=");
var number = np.getDouble(0.001, 100.0);
np.matchIgnoreCase(";");
viewer.getPcoaTab().setTriPlotScaleFactor(number);
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set triPlotScaleFactor=<num>;";
}
/**
* 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() {
try {
return getViewer().isPCoATab() && getViewer().getPcoaTab().getPCoA().getEigenValues() != null;
} catch (Exception ex) {
return false;
}
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Set TriPlot Scale Factor...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Scale factor for TriPlot arrows";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
final var viewer = getViewer();
var result = JOptionPane.showInputDialog(viewer.getFrame(), "Set TriPlot scale factor: ", StringUtils.removeTrailingZerosAfterDot(viewer.getPcoaTab().getTriPlotScaleFactor()));
if (result != null && NumberUtils.isDouble(result)) {
var value = NumberUtils.parseDouble(result);
if (value <= 0.001 || value > 100.0)
NotificationsInSwing.showError(viewer.getFrame(), "Input '" + value + "' out of range: 0.001 -- 100");
else
executeImmediately("set triPlotScaleFactor=" + value + ";");
}
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,904 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
DataCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/DataCommand.java | /*
* DataCommand.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.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.core.ClassificationType;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* `
* Daniel Huson, 6.2010
*/
public class DataCommand extends CommandBase implements ICommand {
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Choose Data...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Choose data for basis of comparison";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set networkData=");
String dataType = np.getWordMatchesIgnoringCase(ClassificationType.Taxonomy + " " + ClassificationType.SEED + " " + ClassificationType.KEGG + " " + ClassificationType.COG);
np.matchIgnoreCase(";");
ClusterViewer viewer = getViewer();
viewer.setDataType(dataType);
viewer.updateDistances();
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
String[] methods = new String[]{ClassificationType.Taxonomy.toString(), "SEED", "KEGG"};
ClusterViewer viewer = getViewer();
String data = (String) JOptionPane.showInputDialog(getViewer().getFrame(), "Set Data", "Set Data", JOptionPane.QUESTION_MESSAGE,
ProgramProperties.getProgramIcon(), methods, viewer.getDataType());
if (data != null)
execute("set networkData=" + data + ";");
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set networkData=<data-name>;";
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,750 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
FlipVCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/FlipVCommand.java | /*
* FlipVCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.Basic;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* flip vertically
* Daniel Huson, 3.2013
*/
public class FlipVCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
return getViewer() != null && getViewer().getPcoaTab() != null && getViewer().getPcoaTab().isFlipV();
}
/**
* parses the given command and executes it
*/
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set flipV=");
boolean flip = np.getBoolean();
np.matchIgnoreCase(";");
getViewer().getPcoaTab().setFlipV(flip);
try {
getViewer().getGraphView().getGraph().clear();
getViewer().updateGraph();
} catch (Exception ex) {
Basic.caught(ex);
}
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set flipV={false|true};";
}
/**
* 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().getSelectedComponent() == getViewer().getPcoaTab();
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Flip Vertically";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Flip vertically";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set flipV=" + (!isSelected()) + ";");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,516 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
DataKeggCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/DataKeggCommand.java | /*
* DataKeggCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import megan.clusteranalysis.ClusterViewer;
import megan.core.ClassificationType;
import megan.core.Director;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* data=kegg command
* Daniel Huson, 6.2010
*/
public class DataKeggCommand extends DataCommand implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getDataType().equalsIgnoreCase("KEGG");
}
/**
* set the selected status of this command
*
*/
public void setSelected(boolean selected) {
ClusterViewer viewer = getViewer();
viewer.setDataType("KEGG");
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Use KEGG";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Use KEGG as basis of comparison";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set networkData=" + ClassificationType.KEGG + ";");
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
ClassificationViewer viewer = (ClassificationViewer) ((Director) getDir()).getViewerByClassName("KEGG");
return viewer != null && viewer.hasComparableData();
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,048 | 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/clusteranalysis/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.clusteranalysis.commands;
import jloda.swing.commands.ICommand;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
/**
* select all nodes
* Daniel Huson, 6.2010
*/
public class SelectNoneCommand extends SelectCommand implements ICommand {
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "None";
}
/**
* get an alternative name used to identify this command
*
* @return name
*/
@Override
public String getAltName() {
return "Select None";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "De-select nodes";
}
/**
* 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_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | InputEvent.SHIFT_DOWN_MASK);
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
executeImmediately("select=none;");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 2,434 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetNodeRadiusCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/SetNodeRadiusCommand.java | /*
* SetNodeRadiusCommand.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.commands;
import jloda.graph.Node;
import jloda.swing.commands.ICommand;
import jloda.util.NumberUtils;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* set node radius
* Daniel Huson, 9.2012
*/
public class SetNodeRadiusCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set nodeRadius=");
int radius = np.getInt(0, 100);
np.matchIgnoreCase(";");
ClusterViewer viewer = getViewer();
for (Node v = viewer.getGraphView().getGraph().getFirstNode(); v != null; v = v.getNext()) {
viewer.getGraphView().getNV(v).setHeight(radius);
viewer.getGraphView().getNV(v).setWidth(radius);
}
viewer.setNodeRadius(radius);
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set nodeRadius=<non-negative-integer>;";
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Set Node Radius...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Set node radius";
}
/**
* 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_K, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
String radius = "" + getViewer().getNodeRadius();
radius = JOptionPane.showInputDialog(getViewer().getFrame(), "Enter node radius (0-100)", radius);
if (radius != null && NumberUtils.isInteger(radius) && Integer.parseInt(radius) >= 0)
execute("set nodeRadius=" + radius + ";");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,820 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
UnweightedTaxonomicUniFracCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/UnweightedTaxonomicUniFracCommand.java | /*
* UnweightedTaxonomicUniFracCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.indices.UniFrac;
import megan.viewer.MainViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* UnweightedTaxonomicUniFrac command
* Daniel Huson, 11.2017
*/
public class UnweightedTaxonomicUniFracCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getEcologicalIndex().equalsIgnoreCase(UniFrac.UnweightedUniformUniFrac);
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Use Unweighted Uniform UniFrac";
}
/**
* get description to be used as a tool-tip
*
* @return description
*/
public String getDescription() {
return "Use the unweighted uniform UniFrac metric.\n" +
"For any two samples, this is the proportion of ranked taxonomic nodes on which exactly one sample has a zero count (Lozupone and Knight, 2005)";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set index=" + UniFrac.UnweightedUniformUniFrac + ";");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
@Override
public void apply(NexusStreamParser np) {
}
@Override
public String getSyntax() {
return null;
}
@Override
public boolean isCritical() {
return true;
}
@Override
public boolean isApplicable() {
return getViewer().getParentViewer() != null && getViewer().getParentViewer() instanceof MainViewer
&& getViewer().getParentViewer().getSelectedNodes().size() > 0;
}
}
| 3,244 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetTriplotSizeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/SetTriplotSizeCommand.java | /*
* SetTriplotSizeCommand.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.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.NumberUtils;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* choose number of triplot vectors
* Daniel Huson, 4.2015
*/
public class SetTriplotSizeCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
final ClusterViewer viewer = getViewer();
int max = viewer.getDir().getDocument().getSampleAttributeTable().getNumericalAttributes(null).size();
np.matchIgnoreCase("set triplotSize=");
int number = np.getInt(0, max);
np.matchIgnoreCase(";");
viewer.getPcoaTab().setTriplotSize(number);
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set triplotSize=<num>;";
}
/**
* 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() {
try {
return getViewer().isPCoATab() && getViewer().getPcoaTab().getPCoA().getEigenValues() != null;
} catch (Exception ex) {
return false;
}
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "TriPlot Size...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Set the number of tri-plot vectors to show";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
final ClusterViewer viewer = getViewer();
int max = viewer.getDir().getDocument().getSampleAttributeTable().getNumericalAttributes(null).size();
int number = Math.min(max, viewer.getPcoaTab().getTriplotSize());
String result = JOptionPane.showInputDialog(viewer.getFrame(), "Number of tri-plot vectors (0-" + max + "): ", number);
if (result != null && NumberUtils.isInteger(result)) {
final int value = NumberUtils.parseInt(result);
if (value < 0 || value > max)
NotificationsInSwing.showError(viewer.getFrame(), "Input '" + value + "' out of range: 0 -- " + max);
else executeImmediately("set triplotSize=" + value + ";");
}
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 4,083 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportPointsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/ExportPointsCommand.java | /*
* ExportDistancesCommand.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.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.*;
import jloda.util.FileUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.core.Director;
import megan.main.MeganProperties;
import javax.swing.*;
import javax.swing.table.TableModel;
import java.awt.event.ActionEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* export points command
* Daniel Huson, 5.2023
*/
public class ExportPointsCommand extends CommandBase implements ICommand {
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Export Points...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Export the points";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws IOException {
var viewer = getViewer();
np.matchIgnoreCase("export data=points file=");
var fileName = np.getAbsoluteFileName();
var replace = false;
if (np.peekMatchIgnoreCase("replace")) {
np.matchIgnoreCase("replace=");
replace = np.getBoolean();
}
np.matchIgnoreCase(";");
if (!replace && (new File(fileName)).exists())
throw new IOException("File exists: " + fileName + ", use REPLACE=true to overwrite");
try (var w = new BufferedWriter(FileUtils.getOutputWriterPossiblyZIPorGZIP(fileName))) {
w.write("# Computed by applying " + viewer.getEcologicalIndex() + " to " + viewer.getDataType() + " data\n");
if(viewer.getPcoaTab().isIs3dMode()) {
w.write("# PC1=%d PC2=%d PC3=%d%n".formatted(viewer.getPcoaTab().getFirstPC()+1,viewer.getPcoaTab().getSecondPC()+1,viewer.getPcoaTab().getThirdPC()+1));
} else {
w.write("# PC1=%d PC2=%d%n".formatted(viewer.getPcoaTab().getFirstPC()+1,viewer.getPcoaTab().getSecondPC()+1));
}
for(var item:viewer.getPcoaTab().getPoints()) {
var name=item.getFirst();
var point=item.getSecond();
if(viewer.getPcoaTab().isIs3dMode()) {
w.write("%s\t%s\t%s\t%s%n".formatted(name, StringUtils.removeTrailingZerosAfterDot("%.8f", point[0]),
StringUtils.removeTrailingZerosAfterDot("%.8f", point[1]),
StringUtils.removeTrailingZerosAfterDot("%.8f", point[2])));
}
else {
w.write("%s\t%s\t%s%n".formatted(name, StringUtils.removeTrailingZerosAfterDot("%.8f", point[0]),
StringUtils.removeTrailingZerosAfterDot("%.8f", point[1])));
}
}
} catch (IOException ex) {
throw ex;
} catch (Exception ex) {
throw new IOException(ex);
}
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
ClusterViewer viewer = getViewer();
String name = FileUtils.replaceFileSuffix(((Director) getDir()).getDocument().getMeganFile().getName(), ".txt");
File lastOpenFile = new File(name);
String lastDir = ProgramProperties.get(MeganProperties.NETWORK_DIRECTORY, "");
if (lastDir.length() > 0) {
lastOpenFile = new File(lastDir, lastOpenFile.getName());
}
getDir().notifyLockInput();
File file = ChooseFileDialog.chooseFileToSave(viewer.getFrame(), lastOpenFile, new TextFileFilter(), new NexusFileFilter(), ev, "Save as points file", ".txt");
getDir().notifyUnlockInput();
if (file != null) {
execute("export data=points file='" + file.getPath() + "' replace=true;");
ProgramProperties.put(MeganProperties.NETWORK_DIRECTORY, file.getParent());
}
}
/**
* 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() {
ClusterViewer viewer = getViewer();
if (viewer.getMatrixTab() != null) {
TableModel model = viewer.getMatrixTab().getTable().getModel();
return model.getRowCount() > 1;
}
return false;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "export data=points file=<filename> [replace=bool];";
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 6,330 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/SelectCommand.java | /*
* SelectCommand.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.commands;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
/**
* select all nodes
* Daniel Huson, 6.2010
*/
abstract class SelectCommand extends CommandBase {
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
ClusterViewer viewer = getViewer();
np.matchIgnoreCase("select=");
String target = np.getWordMatchesIgnoringCase("all none invert");
if (target.equalsIgnoreCase("all"))
viewer.selectAll(true);
else if (target.equalsIgnoreCase("invert"))
viewer.selectInverted();
else
viewer.selectAll(false);
np.matchIgnoreCase(";");
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "select=<target>;";
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 2,711 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowTriplotCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/ShowTriplotCommand.java | /*
* ShowTriplotCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.director.IDirector;
import jloda.util.Basic;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* show triplot
* Daniel Huson, 7.2014
*/
public class ShowTriplotCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getPcoaTab() != null && viewer.getPcoaTab().isShowTriPlot();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set showTriPlot=");
final boolean show = np.getBoolean();
np.matchIgnoreCase(";");
final ClusterViewer viewer = getViewer();
viewer.getPcoaTab().setShowTriPlot(show);
try {
viewer.updateView(IDirector.ENABLE_STATE);
} catch (Exception ex) {
Basic.caught(ex);
}
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set showTriPlot={false|true};";
}
/**
* 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().isPCoATab() && getViewer().getDir().getDocument().getSampleAttributeTable().getNumericalAttributes(null).size() > 0;
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Show TriPlot";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Show tri-plot loading vectors";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null; //ResourceManager.getIcon("PC1vPC2_16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_T, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
executeImmediately("set showTriPlot=" + (!isSelected()) + ";");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,944 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
PrintCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/PrintCommand.java | /*
* PrintCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.clusteranalysis.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.Basic;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.print.PageFormat;
import java.awt.print.PrinterJob;
/**
* print command
* Daniel Huson, 6.2010
*/
public class PrintCommand extends CommandBase implements ICommand {
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Print...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Print the network";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Print16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_P, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | InputEvent.SHIFT_DOWN_MASK);
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("print;");
// todo: implement
System.err.println("Print command: not implemented");
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
ClusterViewer viewer = getViewer();
PageFormat pageFormat = ProgramProperties.getPageFormat();
// todo: make it work for other tabs as well
PrinterJob job = PrinterJob.getPrinterJob();
if (pageFormat != null)
job.setPrintable(viewer, pageFormat);
else
job.setPrintable(viewer);
// Put up the dialog box
if (job.printDialog()) {
// Print the job if the user didn't cancel printing
try {
job.print();
} catch (Exception ex) {
Basic.caught(ex);
NotificationsInSwing.showError(viewer.getFrame(), "Print failed: " + ex);
}
}
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "print;";
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 4,122 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportDistancesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/ExportDistancesCommand.java | /*
* ExportDistancesCommand.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.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.*;
import jloda.util.FileUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.core.Director;
import megan.main.MeganProperties;
import javax.swing.*;
import javax.swing.table.TableModel;
import java.awt.event.ActionEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* export data command
* Daniel Huson, 6.2010
*/
public class ExportDistancesCommand extends CommandBase implements ICommand {
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Export Distances...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Export the distances to a Nexus file for SplitsTree";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws IOException {
ClusterViewer viewer = getViewer();
np.matchIgnoreCase("export data=distances file=");
String fileName = np.getAbsoluteFileName();
boolean replace = false;
if (np.peekMatchIgnoreCase("replace")) {
np.matchIgnoreCase("replace=");
replace = np.getBoolean();
}
np.matchIgnoreCase(";");
if (!replace && (new File(fileName)).exists())
throw new IOException("File exists: " + fileName + ", use REPLACE=true to overwrite");
try (BufferedWriter w = new BufferedWriter(FileUtils.getOutputWriterPossiblyZIPorGZIP(fileName))) {
w.write("#NEXUS [generated by MEGAN]\n");
w.write("[! Computed using " + viewer.getEcologicalIndex() + " applied to " + viewer.getDataType() + " data]\n");
TableModel model = viewer.getMatrixTab().getTable().getModel();
w.write("begin taxa;\ndimensions ntax=" + model.getRowCount() + ";\n taxlabels\n");
for (int r = 0; r < model.getRowCount(); r++) {
w.write("'" + StringUtils.toCleanName(model.getValueAt(r, 0).toString()) + "'\n");
}
w.write(";\n");
w.write("end;\n");
w.write("begin distances;\ndimensions ntax=" + model.getRowCount() + ";\n");
w.write("format triangle=both diagonal labels;\nmatrix\n");
for (int r = 0; r < model.getRowCount(); r++) {
w.write("'" + StringUtils.toCleanName(model.getValueAt(r, 0).toString()) + "'");
for (int c = 1; c < model.getColumnCount(); c++) {
w.write(" " + model.getValueAt(r, c));
}
w.write("\n");
}
w.write(";\n");
w.write("end;\n");
} catch (IOException ex) {
throw ex;
} catch (Exception ex) {
throw new IOException(ex);
}
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
ClusterViewer viewer = getViewer();
String name = FileUtils.replaceFileSuffix(((Director) getDir()).getDocument().getMeganFile().getName(), ".nex");
File lastOpenFile = new File(name);
String lastDir = ProgramProperties.get(MeganProperties.NETWORK_DIRECTORY, "");
if (lastDir.length() > 0) {
lastOpenFile = new File(lastDir, lastOpenFile.getName());
}
getDir().notifyLockInput();
File file = ChooseFileDialog.chooseFileToSave(viewer.getFrame(), lastOpenFile, new TextFileFilter(), new NexusFileFilter(), ev, "Save as Nexus file", ".nexus");
getDir().notifyUnlockInput();
if (file != null) {
execute("export data=distances file='" + file.getPath() + "' replace=true;");
ProgramProperties.put(MeganProperties.NETWORK_DIRECTORY, file.getParent());
}
}
/**
* 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() {
ClusterViewer viewer = getViewer();
if (viewer.getMatrixTab() != null) {
TableModel model = viewer.getMatrixTab().getTable().getModel();
return model.getRowCount() > 1;
}
return false;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "export data=distances file=<filename> [replace=bool];";
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 6,244 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
UseColorsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/UseColorsCommand.java | /*
* UseColorsCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* use colors
* Daniel Huson, 6.2010
*/
public class UseColorsCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.isUseColors();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set useColors=");
boolean useColors = np.getBoolean();
np.matchIgnoreCase(";");
ClusterViewer viewer = getViewer();
viewer.setUseColors(useColors);
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set useColors={false|true};";
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Use Colors";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Use colors";
}
/**
* 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_K, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set useColors=" + (!isSelected()) + ";");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,464 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetPCIvsPCJCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/SetPCIvsPCJCommand.java | /*
* SetPCIvsPCJCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.gui.PCoATab;
import megan.clusteranalysis.pcoa.PCoA;
import megan.clusteranalysis.tree.Taxa;
import megan.core.Director;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
/**
* PC2 vs PC3
* Daniel Huson, 9.2012
*/
public class SetPCIvsPCJCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getPcoaTab() != null && viewer.getPcoaTab().getPCoA() != null && viewer.getPcoaTab().getPCoA().getNumberOfPositiveEigenValues() > 3
&& !(viewer.getPcoaTab().getFirstPC() == 0 && viewer.getPcoaTab().getSecondPC() == 1)
&& !(viewer.getPcoaTab().getFirstPC() == 0 && viewer.getPcoaTab().getSecondPC() == 2)
&& !(viewer.getPcoaTab().getFirstPC() == 1 && viewer.getPcoaTab().getSecondPC() == 2) && !viewer.getPcoaTab().isIs3dMode();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
final ClusterViewer viewer = getViewer();
int maxPC = viewer.getPcoaTab().getPCoA().getNumberOfPositiveEigenValues();
np.matchIgnoreCase("set pc1=");
int pc1 = np.getInt(1, maxPC);
np.matchIgnoreCase("pc2=");
int pc2 = np.getInt(1, maxPC);
int pc3 = Math.max(pc1, pc2) + 1;
if (np.peekMatchIgnoreCase(";")) {
viewer.getPcoaTab().set3dMode(false);
} else {
np.matchIgnoreCase("pc3=");
pc3 = np.getInt(1, maxPC);
viewer.getPcoaTab().set3dMode(true);
}
np.matchIgnoreCase(";");
if (pc1 == pc2)
throw new IOException("pc1==pc2");
if (pc1 == pc3)
throw new IOException("pc1==pc3");
if (pc2 == pc3)
throw new IOException("pc2==pc3");
{
viewer.getPcoaTab().setFirstPC(pc1 - 1);
viewer.getPcoaTab().setSecondPC(pc2 - 1);
viewer.getPcoaTab().setThirdPC(pc3 - 1);
final Taxa taxa = new Taxa();
java.util.List<String> pids = ((Director) getDir()).getDocument().getSampleNames();
for (String name : pids) {
taxa.add(name);
}
viewer.getPcoaTab().setData(taxa, null);
viewer.updateConvexHulls = true;
viewer.addFormatting(viewer.getPcoaTab().getGraphView());
}
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set pc1=<number> pc2=<number> [pc3=<number>];";
}
/**
* 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().getTabbedIndex() == ClusterViewer.PCoA_TAB_INDEX;
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "PCi vs PCj...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Set principle components to use";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("PCIvPCJ_16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_4, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
PCoATab tab = getViewer().getPcoaTab();
PCoA PCoA = tab.getPCoA();
int numberOfPCs = PCoA.getNumberOfPositiveEigenValues();
String value = (tab.getFirstPC() + 1) + " x " + (tab.getSecondPC() + 1);
value = JOptionPane.showInputDialog(getViewer().getFrame(), "Enter PCs (range 1-" + numberOfPCs + "):", value);
if (value != null) {
try {
String[] tokens = value.split("x");
int pc1 = Integer.parseInt(tokens[0].trim());
int pc2 = Integer.parseInt(tokens[1].trim());
execute("set pc1=" + pc1 + " pc2=" + pc2 + ";");
} catch (Exception ex) {
NotificationsInSwing.showError(getViewer().getFrame(), "Expected 'pc1 x pc2', got: " + value);
}
}
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 6,271 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CopyCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/CopyCommand.java | /*
* CopyCommand.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.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Collection;
/**
* copy command
* Daniel Huson, 7.2010
*/
public class CopyCommand extends CommandBase implements ICommand {
public CopyCommand() {
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Copy";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Copy the current data";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Copy16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("copy what=clusterViewer;");
ClusterViewer viewer = getViewer();
StringBuilder buf = new StringBuilder();
int i = viewer.getTabbedIndex();
if (i == ClusterViewer.UPGMA_TAB_INDEX) {
Collection<String> labels = viewer.getUpgmaTab().getGraphView().getSelectedNodeLabels(true);
for (String label : labels) {
if (buf.length() > 0)
buf.append("\t");
buf.append(label);
}
} else if (i == ClusterViewer.NNET_TAB_INDEX) {
Collection<String> labels = viewer.getNnetTab().getGraphView().getSelectedNodeLabels(true);
for (String label : labels) {
if (buf.length() > 0)
buf.append("\t");
buf.append(label);
}
} else if (i == ClusterViewer.PCoA_TAB_INDEX) {
Collection<String> labels = viewer.getPcoaTab().getGraphView().getSelectedNodeLabels(false);
for (String label : labels) {
if (buf.length() > 0)
buf.append("\t");
buf.append(label);
}
} else if (i == ClusterViewer.MATRIX_TAB_INDEX) {
JTable table = viewer.getMatrixTab().getTable();
for (int row = 0; row < table.getRowCount(); row++) {
boolean first = true;
for (int col = 0; col < table.getColumnCount(); col++) {
if (!table.getSelectionModel().isSelectionEmpty() || table.isCellSelected(row, col)) {
if (first)
first = false;
else
buf.append("\t");
buf.append(table.getValueAt(row, col));
}
}
buf.append("\n");
}
}
/*
if(buf.length()==0 && viewer.getGraph().getNumberOfNodes()>0) {
StringWriter w = new StringWriter();
w.write("#NEXUS [generated by MEGAN]\n");
w.write("[! Computed using " + viewer.getEcologicalIndex() + " applied to " + viewer.getDataType() + "data]\n");
TableModel model = viewer.getMatrixTab().getTable().getModel();
w.write("begin taxa;\ndimensions ntax=" + model.getRowCount() + ";\n taxlabels\n");
for (int r = 0; r < model.getRowCount(); r++) {
w.write("'" + Basic.toCleanName(model.getValueAt(r, 0).toString()) + "'\n");
}
w.write(";\n");
w.write("end;\n");
w.write("begin distances;\ndimensions ntax=" + model.getRowCount() + ";\n");
w.write("format triangle=both diagonal labels;\nmatrix\n");
for (int r = 0; r < model.getRowCount(); r++) {
w.write("'" + Basic.toCleanName(model.getValueAt(r, 0).toString()) + "'");
for (int c = 1; c < model.getColumnCount(); c++) {
w.write(" " + model.getValueAt(r, c));
}
w.write("\n");
}
w.write(";\n");
w.write("end;\n");
buf.append(w.toString());
}
*/
if (buf.length() > 0) {
StringSelection stringSelection = new StringSelection(buf.toString());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, stringSelection);
}
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "copy what=<clusterViewer>;"; // not a command-line command
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
/*
NetworkViewer networkViewer = (NetworkViewer) getViewer();
return (networkViewer.getTabbedIndex() == 0 && networkViewer.getSelectedNodes().size() > 0)
|| (networkViewer.getTabbedIndex() == 1 && networkViewer.getPlotTab().getGraphView().getSelectedNodes().size() > 0)
|| (networkViewer.getTabbedIndex() == 2);
*/
return true;
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
executeImmediately("copy what=clusterViewer;");
}
}
| 7,095 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
EcologicalIndexHellingerCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/EcologicalIndexHellingerCommand.java | /*
* EcologicalIndexHellingerCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.indices.HellingerDistance;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* method=Hellinger command
* Daniel Huson, 6.2010
*/
public class EcologicalIndexHellingerCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getEcologicalIndex().equalsIgnoreCase(HellingerDistance.NAME);
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Use Hellinger";
}
/**
* get description to be used as a tool-tip
*
* @return description
*/
public String getDescription() {
return "Use Hellinger ecological index (Rao 1995)";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set index=" + HellingerDistance.NAME + ";");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getViewer().getParentViewer() != null && getViewer().getParentViewer().hasComparableData()
&& getViewer().getParentViewer().getSelectedNodes().size() > 0;
}
/**
* 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;
}
/**
* parses the given command and executes it
*/
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
public String getSyntax() {
return null;
}
}
| 3,396 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowAxesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/ShowAxesCommand.java | /*
* ShowAxesCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* show axes
* Daniel Huson, 1.2016
*/
public class ShowAxesCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getPcoaTab() != null && viewer.getPcoaTab().isShowAxes();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set showAxes=");
boolean show = np.getBoolean();
np.matchIgnoreCase(";");
final ClusterViewer viewer = getViewer();
viewer.getPcoaTab().setShowAxes(show);
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set showAxes={true|false};";
}
/**
* 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().isPCoATab();
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Show Axes";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Show axes in PCoA plot";
}
/**
* 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_D, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
executeImmediately("set showAxes=" + (!isSelected()) + ";");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,550 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
DataTaxonomyCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/DataTaxonomyCommand.java | /*
* DataTaxonomyCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import megan.clusteranalysis.ClusterViewer;
import megan.core.ClassificationType;
import megan.viewer.MainViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* data=taxonomy command
* Daniel Huson, 6.2010
*/
public class DataTaxonomyCommand extends DataCommand implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getDataType().equalsIgnoreCase(ClassificationType.Taxonomy.toString());
}
/**
* set the selected status of this command
*
*/
public void setSelected(boolean selected) {
ClusterViewer viewer = getViewer();
viewer.setDataType(ClassificationType.Taxonomy.toString());
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Use Taxonomy";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Use taxonomy as basis of comparison";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set networkdata=" + ClassificationType.Taxonomy + ";");
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
MainViewer mainViewer = (MainViewer) getDir().getViewerByClass(MainViewer.class);
return mainViewer != null && mainViewer.hasComparableData();
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,084 | 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/clusteranalysis/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.clusteranalysis.commands;
import jloda.swing.commands.ICommand;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* select all nodes
* Daniel Huson, 6.2010
*/
public class SelectAllCommand extends SelectCommand implements ICommand {
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "All";
}
/**
* get an alternative name used to identify this command
*
* @return name
*/
@Override
public String getAltName() {
return "Select All";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Select all nodes";
}
/**
* 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_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
executeImmediately("select=all;");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 2,366 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetPC1vsPC2vsPC3Command.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/SetPC1vsPC2vsPC3Command.java | /*
* SetPC1vsPC2vsPC3Command.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* PC1 vs PC3
* Daniel Huson, 9.2012
*/
public class SetPC1vsPC2vsPC3Command extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getPcoaTab() != null && viewer.getPcoaTab().getFirstPC() == 0 && viewer.getPcoaTab().getSecondPC() == 1 && viewer.getPcoaTab().getThirdPC() == 2 && viewer.getPcoaTab().isIs3dMode();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* 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().isPCoATab();
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "PC1 PC2 PC3";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Display first three principle components";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("PC1vPC2vsPC3_16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_5, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set pc1=1 pc2=2 pc3=3;");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,510 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowBiplotCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/ShowBiplotCommand.java | /*
* ShowBiplotCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.director.IDirector;
import jloda.util.Basic;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* show biplot
* Daniel Huson, 7.2014
*/
public class ShowBiplotCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getPcoaTab() != null && viewer.getPcoaTab().isShowBiPlot();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set showBiPlot=");
boolean show = np.getBoolean();
np.matchIgnoreCase(";");
ClusterViewer viewer = getViewer();
viewer.getPcoaTab().setShowBiPlot(show);
try {
viewer.updateView(IDirector.ENABLE_STATE);
} catch (Exception ex) {
Basic.caught(ex);
}
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set showBiPlot={false|true};";
}
/**
* 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().isPCoATab();
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Show BiPlot";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Show biplot loading vectors";
}
/**
* 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_B, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
executeImmediately("set showBiPlot=" + (!isSelected()) + ";");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,772 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowGroupsAsConvexHullsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/ShowGroupsAsConvexHullsCommand.java | /*
* ShowGroupsAsConvexHullsCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* show groups
* Daniel Huson, 7.2014
*/
public class ShowGroupsAsConvexHullsCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getPcoaTab() != null && viewer.getPcoaTab().isShowGroupsAsConvexHulls();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* 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().isPCoATab();
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Show Groups As Convex Hulls";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Show groups as convex hulls";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null; //ResourceManager.getIcon("PC1vPC2_16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
executeImmediately("set showGroups=" + (!isSelected()) + " style=convexHulls;");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,287 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
EcologicalIndexBrayCurtisCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/EcologicalIndexBrayCurtisCommand.java | /*
* EcologicalIndexBrayCurtisCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.indices.BrayCurtisDissimilarity;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* method=ChiSquare command
* Daniel Huson, 6.2010
*/
public class EcologicalIndexBrayCurtisCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getEcologicalIndex().equalsIgnoreCase(BrayCurtisDissimilarity.NAME);
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Use Bray-Curtis";
}
/**
* get description to be used as a tool-tip
*
* @return description
*/
public String getDescription() {
return "Use Bray-Curtis ecological index (Bray and Curtis, 1957)";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set index=" + BrayCurtisDissimilarity.NAME + ";");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getViewer().getParentViewer() != null && getViewer().getParentViewer().hasComparableData()
&& getViewer().getParentViewer().getSelectedNodes().size() > 0;
}
/**
* 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;
}
/**
* parses the given command and executes it
*/
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
public String getSyntax() {
return null;
}
}
| 3,432 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
EditNodeLabelCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/EditNodeLabelCommand.java | /*
* EditNodeLabelCommand.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.commands;
import jloda.graph.Node;
import jloda.swing.commands.ICommand;
import jloda.swing.graphview.GraphView;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class EditNodeLabelCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
final GraphView graphView = getViewer().getGraphView();
int numToEdit = graphView.getSelectedNodes().size();
boolean changed = false;
for (Node v : graphView.getSelectedNodes()) {
if (numToEdit > 5) {
int result = JOptionPane.showConfirmDialog(graphView.getFrame(), "There are " + numToEdit +
" more selected labels, edit next?", "Question", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.NO_OPTION)
break;
}
numToEdit--;
String label = graphView.getLabel(v);
label = JOptionPane.showInputDialog(graphView.getFrame(), "Edit Node Label:", label);
if (label != null && !label.equals(graphView.getLabel(v))) {
if (label.length() > 0)
graphView.setLabel(v, label);
else
graphView.setLabel(v, null);
changed = true;
}
}
if (changed)
graphView.repaint();
}
public boolean isApplicable() {
final GraphView graphView = getViewer().getGraphView();
return graphView != null && graphView.getSelectedNodes().size() > 0;
}
public String getName() {
return "Edit Node Label";
}
public String getDescription() {
return "Edit the node label";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Command16.gif");
}
public boolean isCritical() {
return true;
}
@Override
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 3,000 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowLabelsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/ShowLabelsCommand.java | /*
* ShowLabelsCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.clusteranalysis.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* select all nodes
* Daniel Huson, 6.2010
*/
public class ShowLabelsCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.isShowLabels();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set showLabels=");
boolean showLabels = np.getBoolean();
np.matchIgnoreCase(";");
ClusterViewer viewer = getViewer();
viewer.setShowLabels(showLabels);
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set showLabels={false|true};";
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Show Labels";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Show node labels";
}
/**
* 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_L, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | java.awt.event.InputEvent.SHIFT_DOWN_MASK);
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set showLabels=" + (!isSelected()) + ";");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,530 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetTriPlotColorCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/SetTriPlotColorCommand.java | /*
* SetTriPlotColorCommand.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.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseColorLineWidthDialog;
import jloda.util.Pair;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.gui.PCoATab;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* set biplot color
* Daniel Huson, 10.2017
*/
public class SetTriPlotColorCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
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().getSelectedComponent() == getViewer().getPcoaTab();
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Set TriPlot Linewidth and Color...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Set tri-plot color";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
final PCoATab pCoATab = getViewer().getPcoaTab();
final Pair<Integer, Color> pair = ChooseColorLineWidthDialog.showDialog(getViewer().getFrame(), "Choose tri-plot line-width and color",
pCoATab.getTriPlotLineWidth(), pCoATab.getTriPlotColor());
if (pair != null) {
final int lineWidth = pair.getFirst();
final Color color = pair.getSecond();
if (lineWidth != pCoATab.getTriPlotLineWidth() || !color.equals(pCoATab.getTriPlotColor())) {
executeImmediately("setColor target=triPlot color=" + color.getRed() + " " + color.getGreen() + " " + color.getBlue() + " lineWidth=" + lineWidth + ";");
}
}
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,688 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
EcologicalIndexGoodallCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/EcologicalIndexGoodallCommand.java | /*
* EcologicalIndexGoodallCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.indices.GoodallsDistance;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* method=Goodall command
* Daniel Huson, 6.2010
*/
public class EcologicalIndexGoodallCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getEcologicalIndex().equalsIgnoreCase(GoodallsDistance.NAME);
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Use Goodall";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Use Goodall's ecological index (Goodall 1964, 1966)";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set index=" + GoodallsDistance.NAME + ";");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getViewer().getParentViewer() != null && getViewer().getParentViewer().hasComparableData()
&& getViewer().getParentViewer().getSelectedNodes().size() > 0;
}
/**
* 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;
}
/**
* parses the given command and executes it
*/
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
public String getSyntax() {
return null;
}
}
| 3,393 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CorrelateClassToAttributeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/CorrelateClassToAttributeCommand.java | /*
* CorrelateClassToAttributeCommand.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.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.commands.CommandBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.Collection;
public class CorrelateClassToAttributeCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
Collection<String> list = getDoc().getSampleAttributeTable().getNumericalAttributes();
ClusterViewer viewer = (ClusterViewer) getViewer();
Collection<Integer> ids = viewer.getSelectedClassIds();
if (ids.size() > 0 && list.size() > 0) {
final String[] choices = list.toArray(new String[0]);
String choice = ProgramProperties.get("CorrelateToAttribute", choices[0]);
if (!list.contains(choice))
choice = choices[0];
choice = (String) JOptionPane.showInputDialog(getViewer().getFrame(), "Choose attribute to correlate to:",
"Compute Correlation Coefficient", JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon(), choices, choice);
if (choice != null) {
ProgramProperties.put("CorrelateToAttribute", choice);
StringBuilder buf = new StringBuilder();
buf.append("correlate class=");
for (Integer id : ids) {
buf.append(" ").append(id);
}
buf.append("' classification='").append(((ClusterViewer) getViewer()).getParentViewer().getClassName())
.append("' attribute='").append(choice).append("';");
executeImmediately("show window=message;");
execute(buf.toString());
}
}
}
public boolean isApplicable() {
return getViewer() instanceof ClusterViewer && ((ClusterViewer) getViewer()).getSelectedClassIds().size() > 0 && getDoc().getSampleAttributeTable().getNumberOfAttributes() > 0;
}
public String getName() {
return "Correlate To Attributes...";
}
public String getDescription() {
return "Correlate assigned (or summarized) counts for nodes with a selected attribute";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
}
| 3,396 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
JensensShannonDivergenceCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/JensensShannonDivergenceCommand.java | /*
* JensensShannonDivergenceCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.indices.JensenShannonDivergence;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* JensensShannonDivergenceCommand
* Daniel Huson, 7.2014
*/
public class JensensShannonDivergenceCommand extends CommandBase implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getEcologicalIndex().equalsIgnoreCase(JensenShannonDivergence.NAME);
}
private static final String NAME = "Use JSD";
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return NAME;
}
/**
* get description to be used as a tool-tip
*
* @return description
*/
public String getDescription() {
return "Use square root of Jensen-Shannon divergence (see Arumugam et al. 2011)";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set index=" + JensenShannonDivergence.NAME + ";");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
@Override
public boolean isApplicable() {
return getViewer().getParentViewer() != null && getViewer().getParentViewer().hasComparableData()
&& getViewer().getParentViewer().getSelectedNodes().size() > 0;
}
@Override
public void apply(NexusStreamParser np) {
}
@Override
public String getSyntax() {
return null;
}
@Override
public boolean isCritical() {
return true;
}
}
| 3,097 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetBiplotScaleFactorCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/SetBiplotScaleFactorCommand.java | /*
* SetBiplotSizeCommand.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.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.NumberUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* set scale factor
* Daniel Huson, 1.2023
*/
public class SetBiplotScaleFactorCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
final ClusterViewer viewer = getViewer();
np.matchIgnoreCase("set biPlotScaleFactor=");
var number = np.getDouble(0.001, 100.0);
np.matchIgnoreCase(";");
viewer.getPcoaTab().setBiPlotScaleFactor(number);
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set biPlotScaleFactor=<num>;";
}
/**
* 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() {
try {
return getViewer().isPCoATab() && getViewer().getPcoaTab().getPCoA().getEigenValues() != null;
} catch (Exception ex) {
return false;
}
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Set BiPlot Scale Factor...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Scale factor for BiPlot arrows";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null; //ResourceManager.getIcon("PC1vPC2_16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
final var viewer = getViewer();
var result = JOptionPane.showInputDialog(viewer.getFrame(), "Set BiPlot scale factor: ", StringUtils.removeTrailingZerosAfterDot(viewer.getPcoaTab().getBiPlotScaleFactor()));
if (result != null && NumberUtils.isDouble(result)) {
var value = NumberUtils.parseDouble(result);
if (value <= 0.001 || value > 100.0)
NotificationsInSwing.showError(viewer.getFrame(), "Input '" + value + "' out of range: 0.001 -- 100");
else
executeImmediately("set biPlotScaleFactor=" + value + ";");
}
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,955 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetAxisColorCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/SetAxisColorCommand.java | /*
* SetAxisColorCommand.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.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseColorLineWidthDialog;
import jloda.swing.util.ColorUtilsSwing;
import jloda.swing.util.ProgramProperties;
import jloda.util.Pair;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.gui.PCoATab;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* set axes color
* Daniel Huson, 10.2017
*/
public class SetAxisColorCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*
*/
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("setColor target=");
final String target = np.getWordMatchesIgnoringCase("axes biplot triplot groups");
np.matchIgnoreCase("color=");
Color color = ColorUtilsSwing.convert(np.getColor());
final byte lineWidth;
if (np.peekMatchIgnoreCase("lineWidth")) {
np.matchIgnoreCase("lineWidth=");
lineWidth = (byte) Math.min(127, np.getInt());
} else
lineWidth = 1;
np.matchIgnoreCase(";");
final PCoATab pCoATab = getViewer().getPcoaTab();
switch (target) {
case "axes" -> {
pCoATab.setAxesColor(color);
ProgramProperties.put("PCoAAxesColor", color);
pCoATab.setAxesLineWidth(lineWidth);
ProgramProperties.put("PCoAAxesLineWidth", lineWidth);
}
case "biplot" -> {
pCoATab.setBiPlotColor(color);
ProgramProperties.put("PCoABiPlotColor", color);
pCoATab.setBiPlotLineWidth(lineWidth);
ProgramProperties.put("PCoABiPlotLineWidth", lineWidth);
}
case "triplot" -> {
pCoATab.setTriPlotColor(color);
ProgramProperties.put("PCoATriPlotColor", color);
pCoATab.setTriPlotLineWidth(lineWidth);
ProgramProperties.put("PCoATriPlotLineWidth", lineWidth);
}
case "groups" -> {
pCoATab.setGroupsColor(color);
ProgramProperties.put("PCoAGroupColor", color);
pCoATab.setGroupLineWidth(lineWidth);
ProgramProperties.put("PCoAGroupLineWidth", lineWidth);
}
}
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "setColor target={axes|biplot|triplot} color=<color>;";
}
/**
* 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().getSelectedComponent() == getViewer().getPcoaTab();
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Set Axes Linewidth and Color...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Set axes color";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
final PCoATab pCoATab = getViewer().getPcoaTab();
final Pair<Integer, Color> pair = ChooseColorLineWidthDialog.showDialog(getViewer().getFrame(), "Choose axes line-width and color", pCoATab.getAxesLineWidth(), pCoATab.getAxesColor());
if (pair != null) {
final int lineWidth = pair.getFirst();
final Color color = pair.getSecond();
if (lineWidth != pCoATab.getAxesLineWidth() || !color.equals(pCoATab.getAxesColor())) {
execute("setColor target=axes color=" + color.getRed() + " " + color.getGreen() + " " + color.getBlue() + " lineWidth=" + lineWidth + ";");
}
}
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 5,498 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
PearsonsCorrelationsDistanceCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/PearsonsCorrelationsDistanceCommand.java | /*
* PearsonsCorrelationsDistanceCommand.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.commands;
import jloda.swing.commands.ICheckBoxCommand;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.indices.PearsonDistance;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* PearsonsCorrelationsDistanceCommand command
* Daniel Huson, 7.2010
*/
public class PearsonsCorrelationsDistanceCommand extends EcologicalIndexCommand implements ICheckBoxCommand {
/**
* this is currently selected?
*
* @return selected
*/
public boolean isSelected() {
ClusterViewer viewer = getViewer();
return viewer.getEcologicalIndex().equalsIgnoreCase(PearsonDistance.NAME);
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Use Pearson";
}
/**
* get description to be used as a tool-tip
*
* @return description
*/
public String getDescription() {
return "Use Pearson's correlation distance";
}
/**
* 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;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("set index=" + PearsonDistance.NAME + ";");
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 2,521 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
EcologicalIndexCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/EcologicalIndexCommand.java | /*
* EcologicalIndexCommand.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.commands;
import jloda.swing.util.ProgramProperties;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.indices.DistancesManager;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* the ecological index
* Daniel Huson, 6.2010
*/
abstract class EcologicalIndexCommand extends CommandBase {
/**
* parses the given command and executes it
*/
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set index=");
String method = np.getWordMatchesIgnoringCase(DistancesManager.getAllNames());
np.matchIgnoreCase(";");
ClusterViewer viewer = getViewer();
viewer.setEcologicalIndex(method);
executeImmediately("sync;");
}
/**
* get Command Syntax.... First two tokens are used to identify the command
*
* @return usage
*/
public String getSyntax() {
return "set index=<index-name>;";
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
final ClusterViewer viewer = getViewer();
final String method = (String) JOptionPane.showInputDialog(getViewer().getFrame(), "Set Ecological Index", "Set Ecological Index", JOptionPane.QUESTION_MESSAGE,
ProgramProperties.getProgramIcon(), DistancesManager.getAllNames(), viewer.getEcologicalIndex());
if (method != null)
executeImmediately("set index=" + method + ";");
}
/**
* 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().getParentViewer() != null && getViewer().getParentViewer().hasComparableData()
&& getViewer().getParentViewer().getSelectedNodes().size() > 0;
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 3,128 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CopyNodeLabelCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/CopyNodeLabelCommand.java | /*
* CopyNodeLabelCommand.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.commands;
import jloda.graph.Node;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.commands.CommandBase;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
public class CopyNodeLabelCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
ClusterViewer viewer = (ClusterViewer) getViewer();
StringBuilder buf = new StringBuilder();
boolean first = true;
for (Node v : viewer.getGraphView().getSelectedNodes()) {
String label = viewer.getGraphView().getLabel(v);
if (label != null) {
if (first)
first = false;
else
buf.append(" ");
buf.append(label);
}
}
if (buf.toString().length() > 0) {
StringSelection selection = new StringSelection(buf.toString());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, null);
}
}
public boolean isApplicable() {
return ((ClusterViewer) getViewer()).getGraphView() != null && ((ClusterViewer) getViewer()).getGraphView().getSelectedNodes().size() > 0;
}
public String getName() {
return "Copy Node Label";
}
public String getDescription() {
return "Copy the node label";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Copy16.gif");
}
public boolean isCritical() {
return false;
}
}
| 2,663 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetBiplotSizeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/SetBiplotSizeCommand.java | /*
* SetBiplotSizeCommand.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.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.NumberUtils;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* choose number of biplot vectors
* Daniel Huson, 7.2014
*/
public class SetBiplotSizeCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
final ClusterViewer viewer = getViewer();
int max = viewer.getPcoaTab().getPCoA().getLoadingVectorsBiPlot().size();
np.matchIgnoreCase("set biplotSize=");
int number = np.getInt(0, max);
np.matchIgnoreCase(";");
viewer.getPcoaTab().setBiplotSize(number);
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set biplotSize=<num>;";
}
/**
* 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() {
try {
return getViewer().isPCoATab() && getViewer().getPcoaTab().getPCoA().getEigenValues() != null;
} catch (Exception ex) {
return false;
}
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "BiPlot Size...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Set the number of bi-plot vectors to show";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null; //ResourceManager.getIcon("PC1vPC2_16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
final ClusterViewer viewer = getViewer();
int max = viewer.getPcoaTab().getPCoA().getLoadingVectorsBiPlot().size();
int number = Math.min(max, viewer.getPcoaTab().getBiplotSize());
String result = JOptionPane.showInputDialog(viewer.getFrame(), "Number of biplot vectors (0-" + max + "): ", number);
if (result != null && NumberUtils.isInteger(result)) {
final int value = NumberUtils.parseInt(result);
if (value < 0 || value > max)
NotificationsInSwing.showError(viewer.getFrame(), "Input '" + value + "' out of range: 0 -- " + max);
else
executeImmediately("set biplotSize=" + value + ";");
}
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
}
| 4,062 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
RotateDownCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/geom3d/RotateDownCommand.java | /*
* RotateDownCommand.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.commands.geom3d;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.commands.CommandBase;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* rotate command
*/
public class RotateDownCommand extends CommandBase implements ICommand {
/**
* 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_DOWN, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
@Override
public void actionPerformed(ActionEvent ev) {
double angle = 0.05 * Math.PI;
executeImmediately("rotate axis=x angle=" + angle + ";");
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getViewer().getTabbedIndex() == ClusterViewer.PCoA_TAB_INDEX && getViewer().getPcoaTab().isIs3dMode();
}
public String getName() {
return "Rotate Down";
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
@Override
public String getDescription() {
return "Rotate 3D PCoA plot down";
}
}
| 2,987 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
RotateRightCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/geom3d/RotateRightCommand.java | /*
* RotateRightCommand.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.commands.geom3d;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.commands.CommandBase;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* rotate command
*/
public class RotateRightCommand extends CommandBase implements ICommand {
/**
* 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_RIGHT, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
@Override
public void actionPerformed(ActionEvent ev) {
double angle = -0.05 * Math.PI;
executeImmediately("rotate axis=y angle=" + angle + ";");
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getViewer().getTabbedIndex() == ClusterViewer.PCoA_TAB_INDEX && getViewer().getPcoaTab().isIs3dMode();
}
public String getName() {
return "Rotate Right";
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
@Override
public String getDescription() {
return "Rotate 3D PCoA plot right";
}
}
| 2,993 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
RotateUpCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/geom3d/RotateUpCommand.java | /*
* RotateUpCommand.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.commands.geom3d;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.commands.CommandBase;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* rotate command
*/
public class RotateUpCommand extends CommandBase implements ICommand {
/**
* 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_UP, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
@Override
public void actionPerformed(ActionEvent ev) {
double angle = -0.05 * Math.PI;
executeImmediately("rotate axis=x angle=" + angle + ";");
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getViewer().getTabbedIndex() == ClusterViewer.PCoA_TAB_INDEX && getViewer().getPcoaTab().isIs3dMode();
}
public String getName() {
return "Rotate Up";
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
@Override
public String getDescription() {
return "Rotate 3D PCoA plot up";
}
}
| 2,978 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
RotateLeftCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/geom3d/RotateLeftCommand.java | /*
* RotateLeftCommand.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.commands.geom3d;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.commands.CommandBase;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* rotate command
*/
public class RotateLeftCommand extends CommandBase implements ICommand {
/**
* 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_LEFT, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
@Override
public void actionPerformed(ActionEvent ev) {
double angle = 0.05 * Math.PI;
executeImmediately("rotate axis=y angle=" + angle + ";");
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getViewer().getTabbedIndex() == ClusterViewer.PCoA_TAB_INDEX && getViewer().getPcoaTab().isIs3dMode();
}
public String getName() {
return "Rotate Left";
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
@Override
public String getDescription() {
return "Rotate 3D PCoA plot left";
}
}
| 2,988 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
RotateCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/geom3d/RotateCommand.java | /*
* RotateCommand.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.commands.geom3d;
import jloda.swing.commands.ICommand;
import jloda.util.NumberUtils;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.commands.CommandBase;
import megan.clusteranalysis.pcoa.geom3d.Matrix3D;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* rotate command
*/
public class RotateCommand extends CommandBase implements ICommand {
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
ClusterViewer viewer = getViewer();
np.matchIgnoreCase("rotate axis=");
String axis = np.getWordMatchesIgnoringCase("x y z");
np.matchIgnoreCase("angle=");
double angle = np.getDouble();
Matrix3D matrix = viewer.getPcoaTab().getTransformation3D();
if (axis.equalsIgnoreCase("x")) {
matrix.rotateX(angle);
} else if (axis.equalsIgnoreCase("y")) {
matrix.rotateY(angle);
} else if (axis.equalsIgnoreCase("z")) {
matrix.rotateZ(angle);
}
viewer.getPcoaTab().updateTransform(true);
if (viewer.getPcoaTab().isShowGroupsAsConvexHulls())
viewer.getPcoaTab().computeConvexHullsAndEllipsesForGroups(viewer.getGroup2Nodes());
np.matchIgnoreCase(";");
}
@Override
public void actionPerformed(ActionEvent ev) {
String input = JOptionPane.showInputDialog(getViewer().getFrame(), "Enter axis and angle");
if (input != null) {
char axis = input.charAt(0);
double angle = NumberUtils.parseDouble(input.substring(1));
executeImmediately("rotate axis=" + axis + " angle=" + angle + ";");
}
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "rotate axis={x|y|z} angle=<number>;";
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
public String getName() {
return "Rotate...";
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
@Override
public String getDescription() {
return "Three-dimensional rotation";
}
}
| 3,872 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ZoomToFullCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/zoom/ZoomToFullCommand.java | /*
* ZoomToFullCommand.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.commands.zoom;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ZoomToFullCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void actionPerformed(ActionEvent event) {
executeImmediately("zoom what=full;");
}
public String getName() {
return "Fully Expand";
}
public String getDescription() {
return "Expand tree vertically";
}
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 null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
@Override
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
@Override
public boolean isApplicable() {
return true;
}
}
| 2,353 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ZoomToSelectionCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/zoom/ZoomToSelectionCommand.java | /*
* ZoomToSelectionCommand.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.commands.zoom;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ZoomToSelectionCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void actionPerformed(ActionEvent event) {
executeImmediately(getSyntax());
}
public boolean isApplicable() {
return getViewer() != null && ((ClusterViewer) getViewer()).getGraphView().getSelectedNodes().size() > 0;
}
public String getName() {
return "Zoom To Selection";
}
public String getDescription() {
return "Zoom to the selection";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/AlignCenter16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
execute("zoom what=selected;");
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
@Override
public boolean isCritical() {
return true;
}
}
| 2,365 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExpandHorizontalCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/zoom/ExpandHorizontalCommand.java | /*
* ExpandHorizontalCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.clusteranalysis.commands.zoom;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.graphview.ScrollPaneAdjuster;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ExpandHorizontalCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "expand horizontal;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
ViewerBase viewer = (ViewerBase) ((ClusterViewer) getViewer()).getGraphView();
if (viewer != null) {
double scale = 1.2 * viewer.trans.getScaleX();
if (scale < 10000) {
ScrollPaneAdjuster spa = new ScrollPaneAdjuster(viewer.getScrollPane(), viewer.trans);
if (viewer.trans.getLockXYScale()) {
viewer.trans.composeScale(1.2, 1.2);
spa.adjust(true, true);
} else {
viewer.trans.composeScale(1.2, 1);
spa.adjust(true, false);
}
}
}
}
public void actionPerformed(ActionEvent event) {
executeImmediately(getSyntax());
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Expand Horizontal";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("ExpandHorizontal16.gif");
}
public String getDescription() {
return "Expand view horizontally";
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,783 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ContractHorizontalCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/zoom/ContractHorizontalCommand.java | /*
* ContractHorizontalCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.clusteranalysis.commands.zoom;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.graphview.ScrollPaneAdjuster;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ContractHorizontalCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "contract horizontal;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
ViewerBase viewer = (ViewerBase) ((ClusterViewer) getViewer()).getGraphView();
if (viewer != null) {
double scale = 1.2 * viewer.trans.getScaleX();
if (scale >= 0.0001) {
ScrollPaneAdjuster spa = new ScrollPaneAdjuster(viewer.getScrollPane(), viewer.trans);
if (viewer.trans.getLockXYScale()) {
viewer.trans.composeScale(1 / 1.2, 1 / 1.2);
spa.adjust(true, true);
} else {
viewer.trans.composeScale(1 / 1.2, 1);
spa.adjust(true, false);
}
}
}
}
public void actionPerformed(ActionEvent event) {
executeImmediately(getSyntax());
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Contract Horizontal";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("ContractHorizontal16.gif");
}
public String getDescription() {
return "Contract view horizontally";
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,809 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ContractVerticalCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/zoom/ContractVerticalCommand.java | /*
* ContractVerticalCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.clusteranalysis.commands.zoom;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.graphview.ScrollPaneAdjuster;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ContractVerticalCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "contract vertical;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
ViewerBase viewer = (ViewerBase) ((ClusterViewer) getViewer()).getGraphView();
if (viewer != null) {
double scale = 1.2 * viewer.trans.getScaleY();
if (scale >= 0.0001) {
ScrollPaneAdjuster spa = new ScrollPaneAdjuster(viewer.getScrollPane(), viewer.trans);
if (viewer.trans.getLockXYScale()) {
viewer.trans.composeScale(1 / 1.2, 1 / 1.2);
spa.adjust(true, true);
} else {
viewer.trans.composeScale(1, 1 / 1.2);
spa.adjust(false, true);
}
}
}
}
public void actionPerformed(ActionEvent event) {
executeImmediately(getSyntax());
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Contract Vertical";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("ContractVertical16.gif");
}
public String getDescription() {
return "Contract view vertically";
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,797 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetScaleCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/zoom/SetScaleCommand.java | /*
* SetScaleCommand.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.commands.zoom;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.graphview.GraphView;
import jloda.swing.util.ResourceManager;
import jloda.util.NumberUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.gui.ITab;
import megan.clusteranalysis.gui.PCoATab;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* Set scale command
* Daniel Huson, 6.2010
*/
public class SetScaleCommand extends CommandBase implements ICommand {
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set scaleFactor=<number>;";
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set scaleFactor=");
double scale = np.getDouble(0.000001, 100000);
np.matchIgnoreCase(";");
final ClusterViewer viewer = (ClusterViewer) getViewer();
if (viewer.getSelectedComponent() instanceof ITab) {
if (viewer.getSelectedComponent() instanceof PCoATab)
scale /= PCoATab.COORDINATES_SCALE_FACTOR;
GraphView graphView = viewer.getGraphView();
graphView.centerGraph();
graphView.trans.setScale(scale, scale);
}
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Set Scale...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Set the scale factor";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/AlignCenter16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
final ClusterViewer viewer = (ClusterViewer) getViewer();
if (viewer.getSelectedComponent() instanceof ITab) {
final GraphView graphView = viewer.getGraphView();
double scale = graphView.trans.getScaleX();
if (viewer.getSelectedComponent() instanceof PCoATab)
scale *= PCoATab.COORDINATES_SCALE_FACTOR;
final String result = JOptionPane.showInputDialog(viewer.getFrame(), "Set scale", StringUtils.removeTrailingZerosAfterDot(String.format("%.4f", scale)));
if (result != null && NumberUtils.isDouble(result) && NumberUtils.parseDouble(result) > 0) {
execute("set scaleFactor=" + NumberUtils.parseDouble(result) + ";");
}
}
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getViewer() instanceof ClusterViewer && ((ClusterViewer) getViewer()).getSelectedComponent() instanceof ITab;
}
public boolean isCritical() {
return true;
}
}
| 4,172 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ZoomToFitCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/zoom/ZoomToFitCommand.java | /*
* ZoomToFitCommand.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.commands.zoom;
import jloda.swing.commands.ICommand;
import jloda.swing.graphview.GraphView;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.clusteranalysis.commands.CommandBase;
import megan.clusteranalysis.gui.ITab;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* zoom to fit
* Daniel Huson, 6.2010
*/
public class ZoomToFitCommand extends CommandBase implements ICommand {
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "zoom what=<{fit|full|selection}>;";
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("zoom what=");
String what = np.getWordMatchesIgnoringCase("fit full selection");
np.matchIgnoreCase(";");
ClusterViewer viewer = getViewer();
if (viewer.getSelectedComponent() instanceof ITab) {
ITab tab = ((ITab) viewer.getSelectedComponent());
if (what.equalsIgnoreCase("fit"))
tab.zoomToFit();
else if (what.equalsIgnoreCase("selection")) {
tab.zoomToSelection();
} else if (what.equalsIgnoreCase("full")) { // doesn't work for PCoA3D
GraphView graphView = viewer.getGraphView();
graphView.fitGraphToWindow();
graphView.trans.setScaleY(1);
}
}
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Zoom to Fit";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Zoom";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/AlignCenter16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
execute("zoom what=fit;");
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
/**
* gets the command needed to undo this command
*
* @return undo command
*/
public String getUndo() {
return null;
}
public boolean isCritical() {
return true;
}
}
| 3,842 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExpandVerticalCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/clusteranalysis/commands/zoom/ExpandVerticalCommand.java | /*
* ExpandVerticalCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.clusteranalysis.commands.zoom;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.graphview.ScrollPaneAdjuster;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;
import megan.viewer.ViewerBase;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ExpandVerticalCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "expand vertical;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
ViewerBase viewer = (ViewerBase) ((ClusterViewer) getViewer()).getGraphView();
if (viewer != null) {
double scale = 2 * viewer.trans.getScaleY();
if (scale < 10000) {
ScrollPaneAdjuster spa = new ScrollPaneAdjuster(viewer.getScrollPane(), viewer.trans);
if (viewer.trans.getLockXYScale()) {
viewer.trans.composeScale(1.2, 1.2);
spa.adjust(true, true);
} else {
viewer.trans.composeScale(1, 1.2);
spa.adjust(false, true);
}
}
}
}
public void actionPerformed(ActionEvent event) {
executeImmediately(getSyntax());
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Expand Vertical";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("ExpandVertical16.gif");
}
public String getDescription() {
return "Expand view vertically";
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,769 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
TestMyTableView.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/xtra/TestMyTableView.java | /*
* TestMyTableView.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.xtra;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import jloda.fx.control.table.MyTableView;
import jloda.fx.control.table.MyTableViewSearcher;
import jloda.fx.find.FindToolBar;
import jloda.fx.util.ResourceManagerFX;
import jloda.util.CollectionUtils;
import jloda.util.StringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class TestMyTableView extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
final BorderPane root = new BorderPane();
final MyTableView tableView = new MyTableView();
tableView.setAllowDeleteCol(true);
tableView.setAllowAddCol(true);
tableView.setAllowRenameCol(true);
tableView.setAllAddRow(true);
tableView.setAllowDeleteRow(true);
tableView.setAllowRenameRow(true);
root.setCenter(tableView);
final MyTableViewSearcher searcher = new MyTableViewSearcher(tableView);
final FindToolBar findToolBar = new FindToolBar(null, searcher);
root.setTop(findToolBar);
tableView.setAdditionColHeaderMenuItems(col -> Collections.singletonList(new MenuItem("Color samples by attribute '" + col + "'")));
tableView.setAdditionRowHeaderMenuItems(rows -> {
final MenuItem moveSamplesUp = new MenuItem("Move Samples Up");
moveSamplesUp.setOnAction((e) ->
{
final ArrayList<String> list = new ArrayList<>(tableView.getSelectedRows());
System.err.println("Moving up: " + StringUtils.toString(list, " "));
for (String sample : list) {
final int oldPos = tableView.getRowIndex(sample);
final int newPos = oldPos - 1;
System.err.println(sample + ": " + oldPos + " -> " + newPos);
if (newPos >= 0 && newPos < tableView.getRowCount())
tableView.swapRows(oldPos, newPos);
}
});
final MenuItem moveSamplesDown = new MenuItem("Move Samples Down");
moveSamplesDown.setOnAction((e) ->
{
final ArrayList<String> list = CollectionUtils.reverse(tableView.getSelectedRows());
System.err.println("Moving down:" + StringUtils.toString(list, " "));
for (String sample : list) {
final int oldPos = tableView.getRowIndex(sample);
final int newPos = oldPos + 1;
System.err.println(sample + ": " + oldPos + " -> " + newPos);
if (newPos >= 0 && newPos < tableView.getRowCount())
tableView.swapRows(oldPos, newPos);
}
});
return Arrays.asList(moveSamplesUp, moveSamplesDown);
});
final ToggleButton findButton = new ToggleButton("Find");
findButton.selectedProperty().addListener((c, o, n) -> findToolBar.setShowFindToolBar(n));
final ToggleButton editableButton = new ToggleButton("Editable");
tableView.editableProperty().bind(editableButton.selectedProperty());
final Button scrollToTopButton = new Button("Scroll to top");
scrollToTopButton.setOnAction((e) -> tableView.scrollToRow(0));
Button copyButton = new Button("Copy");
copyButton.setOnAction((e) -> tableView.copyToClipboard());
copyButton.disableProperty().bind(Bindings.isEmpty(tableView.getSelectedCells()));
Button listButton = new Button("List");
listButton.setOnAction((e) -> System.err.println(tableView));
final Label updateLabel = new Label();
updateLabel.textProperty().bind(tableView.updateProperty().asString());
root.setBottom(new ToolBar(findButton, editableButton, copyButton, scrollToTopButton, listButton, updateLabel));
final Label selectedRowCount = new Label();
selectedRowCount.textProperty().bind(Bindings.concat("Selected rows: ", tableView.countSelectedRowsProperty().asString(), " "));
final Label selectedColCount = new Label();
selectedColCount.textProperty().bind(Bindings.concat("Selected cols: ", tableView.countSelectedColsProperty().asString(), " "));
root.setRight(new VBox(selectedRowCount, selectedColCount));
tableView.addCol("name");
tableView.addCol("age");
tableView.addCol("height");
for (int i = 0; i < 3; i++) {
tableView.addRow("first-first" + i, "cindy", 5, 5.0);
tableView.addRow("second" + i, "bob", 10, 25.0);
tableView.addRow("third" + i, "alice", 15, 125.0);
tableView.addRow("four" + i, "elke", 15, 125.0);
tableView.addRow("five" + i, "joe", 15, 125.0);
tableView.addRow("sixz" + i, "dave", 150, 225.0);
}
final ImageView imageView = new ImageView(ResourceManagerFX.getIcon("Algorithm16.gif"));
imageView.setPreserveRatio(true);
imageView.setFitWidth(16);
root.setLeft(new VBox(imageView));
Scene scene = new Scene(root, 600, 600);
primaryStage.setScene(scene);
primaryStage.setTitle("my table");
primaryStage.sizeToScene();
primaryStage.show();
}
}
| 6,350 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
RMA2Formatter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma2/RMA2Formatter.java | /*
* RMA2Formatter.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.rma2;
/**
* reads and writes the read block fixed part
* Daniel Huson, 3.2011
*/
public class RMA2Formatter {
private final ReadBlockRMA2Formatter readBlockFormatter;
private final MatchBlockRMA2Formatter matchBlockFormatter;
private boolean wantLocationData = false; // in the special case that we are parsing an RMA file for submission to a database, we want the ReadBlock.read method to return a readblock with location data
/**
* Constructor
*
*/
public RMA2Formatter(String readBlockFormatString, String matchBlockFormatString) {
readBlockFormatter = new ReadBlockRMA2Formatter(readBlockFormatString);
matchBlockFormatter = new MatchBlockRMA2Formatter(matchBlockFormatString);
}
/**
* get the read block formatter
*
* @return readBlockFormatter
*/
public ReadBlockRMA2Formatter getReadBlockRMA2Formatter() {
return readBlockFormatter;
}
public MatchBlockRMA2Formatter getMatchBlockRMA2Formatter() {
return matchBlockFormatter;
}
public void setWantLocationData(boolean wantLocationData) {
this.wantLocationData = wantLocationData;
}
public boolean isWantLocationData() {
return wantLocationData;
}
}
| 2,077 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ReadBlockRMA2Formatter.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma2/ReadBlockRMA2Formatter.java | /*
* ReadBlockRMA2Formatter.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.rma2;
import megan.io.ByteByteInt;
import megan.io.IInputReader;
import megan.io.IOutputWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.StringTokenizer;
/**
* formatting for readblock
* Daniel Huson, 4.2011
*/
public class ReadBlockRMA2Formatter {
static public final String DEFAULT_RMA2_0 = "MateUId:long;MateType:byte;ReadLength:int;NumberOfMatches:int;";
static public final String DEFAULT_RMA2_1 = "MateUId:long;MateType:byte;ReadLength:int;Complexity:float;NumberOfMatches:int;";
static public final String DEFAULT_RMA2_2 = "ReadWeight:int;MateUId:long;MateType:byte;ReadLength:int;Complexity:float;NumberOfMatches:int;";
static public final String DEFAULT_RMA2_5 = "ReadWeight:int;MateUId:long;MateType:byte;ReadLength:int;Complexity:float;NumberOfMatches:int;"; // MEGAN5
private final String format;
private int numberOfBytes = 0;
// access to commonly used ones:
private Object[] readWeight;
private Object[] mateUId;
private Object[] mateType;
private Object[] readLength;
private Object[] complexity;
private Object[] numberOfMatches;
private Object[][] data;
private final HashMap<String, Object[]> name2data = new HashMap<>();
/**
* constructs an instance and sets to the given format
*
*/
public ReadBlockRMA2Formatter(String format) {
this.format = format;
decode(format);
}
private void decode(String format) {
LinkedList<Object[]> list = new LinkedList<>();
StringTokenizer tokenizer = new StringTokenizer(format, ";");
int index = 0;
while (tokenizer.hasMoreElements()) {
String[] split = tokenizer.nextToken().split(":");
String name = split[0];
String type = split[1];
Object[] object = new Object[]{name, type.charAt(0), null};
switch (type.charAt(0)) {
case 'i', 'f' -> numberOfBytes += 4;
case 'l' -> numberOfBytes += 8;
case 'b' -> numberOfBytes += 1;
case 'B' -> numberOfBytes += 6;
case 'c' -> numberOfBytes += 2;
}
name2data.put(name, object);
list.add(object);
}
data = list.toArray(new Object[list.size()][]);
// access to standard items set here:
readWeight = name2data.get("ReadWeight");
mateUId = name2data.get("MateUId");
mateType = name2data.get("MateType");
readLength = name2data.get("ReadLength");
complexity = name2data.get("Complexity");
numberOfMatches = name2data.get("NumberOfMatches");
}
/**
* read the fixed part of the reads block
*
*/
public void read(IInputReader dataIndexReader) throws IOException {
for (Object[] dataRecord : data) {
switch ((Character) dataRecord[1]) {
case 'i' -> dataRecord[2] = dataIndexReader.readInt();
case 'f' -> dataRecord[2] = dataIndexReader.readFloat();
case 'l' -> dataRecord[2] = dataIndexReader.readLong();
case 'b' -> dataRecord[2] = (byte) dataIndexReader.read();
case 'B' -> dataRecord[2] = dataIndexReader.readByteByteInt();
case 'c' -> dataRecord[2] = dataIndexReader.readChar();
}
// System.err.println("Read (read): "+ Basic.toString(dataRecord, ","));
}
}
/**
* write the fixed part of the reads block
*
*/
public void write(IOutputWriter indexWriter) throws IOException {
for (Object[] dataRecord : data) {
switch ((Character) dataRecord[1]) {
case 'i' -> indexWriter.writeInt((Integer) dataRecord[2]);
case 'f' -> indexWriter.writeFloat((Float) dataRecord[2]);
case 'l' -> indexWriter.writeLong((Long) dataRecord[2]);
case 'b' -> indexWriter.write((Byte) dataRecord[2]);
case 'B' -> indexWriter.writeByteByteInt((ByteByteInt) dataRecord[2]);
case 'c' -> indexWriter.writeChar((Character) dataRecord[2]);
}
// System.err.println("Wrote (read): "+ Basic.toString(dataRecord,","));
}
}
/**
* get the value for a name
*
* @return value
*/
public Object get(String name) {
return name2data.get(name)[2];
}
/**
* set the value for a name. Does not check that value is of correct type!
*
*/
public void put(String name, Object value) {
name2data.get(name)[2] = value;
}
public boolean hasReadWeight() {
return readWeight != null;
}
public Integer getReadWeight() {
return (Integer) readWeight[2];
}
public void setReadWeight(Integer value) {
if (readWeight != null)
readWeight[2] = value;
}
public boolean hasMateUId() {
return mateUId != null;
}
public Long getMateUId() {
return (Long) mateUId[2];
}
public void setMateUId(Long value) {
mateUId[2] = value;
}
public boolean hasMateType() {
return mateType != null;
}
public byte getMateType() {
return (Byte) mateType[2];
}
public void setMateType(Byte value) {
mateType[2] = value;
}
public boolean hasReadLength() {
return readLength != null;
}
public int getReadLength() {
return (Integer) readLength[2];
}
public void setReadLength(Integer value) {
readLength[2] = value;
}
public boolean hasComplexity() {
return complexity != null;
}
public float getComplexity() {
if (complexity != null)
return (Float) complexity[2];
else
return 0;
}
public void setComplexity(Float value) {
if (complexity != null)
complexity[2] = value;
}
public boolean hasNumberOfMatches() {
return numberOfMatches != null;
}
public int getNumberOfMatches() {
return (Integer) numberOfMatches[2];
}
public void setNumberOfMatches(Integer value) {
numberOfMatches[2] = value;
}
public int getNumberOfBytes() {
return numberOfBytes;
}
/**
* gets the format string
*
* @return format string
*/
public String toString() {
return format;
}
}
| 7,286 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
RMA2File.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma2/RMA2File.java | /*
* RMA2File.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.rma2;
import jloda.util.FileUtils;
import megan.core.SampleAttributeTable;
import megan.data.LocationManager;
import megan.data.TextStoragePolicy;
import megan.io.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* rma2 file
* Daniel Huson, 10.2010
*/
public class RMA2File {
public final static int MAGIC_NUMBER = ('R' << 3) | ('M' << 2) | ('A' << 1) | ('R');
public static final byte CHECK_BYTE = (byte) 255;
private final File file;
private final InfoSection infoSection;
private String creator = "MEGAN";
/**
* constructor
*
*/
public RMA2File(File file) {
this.file = file;
infoSection = new InfoSection();
}
/**
* gets the version of the RMA file
*
* @return RMA version number or 0, if not an RMA file
*/
static public int getRMAVersion(File file) {
try {
try (InputReader r = new InputReader(file, null, null, true)) {
int magicNumber = r.readInt();
if (magicNumber != MAGIC_NUMBER)
throw new IOException("Not an RMA file");
return r.readInt(); // version
}
} catch (IOException e) {
return 0;
}
}
/**
* get the info section. When opening a file, first call loadInfoSection()
*
* @return info section
*/
public InfoSection getInfoSection() {
return infoSection;
}
/**
* load the info section
*
*/
public InfoSection loadInfoSection() throws IOException {
try (InputReader reader = new InputReader(getFile(), null, null, true)) {
readHeader(reader);
infoSection.read(reader);
}
// System.err.println("Loaded---------\n"+infoSection.toString());
return infoSection;
}
/**
* store the infosection
*
*/
private void storeInfoSection() throws IOException {
try (InputOutputReaderWriter io = new InputOutputReaderWriter(file, "rw")) {
if (infoSection.getInfoSectionStart() <= 0)
throw new IOException("getInfoSectionStart(), illegal value: " + infoSection.getInfoSectionStart());
io.seek(infoSection.getInfoSectionStart());
infoSection.write(io);
io.setLength(io.getPosition());
}
}
/**
* opens a writer to the main file
*
*/
public OutputWriter getFileWriter() throws IOException {
OutputWriter w = new OutputWriter(file);
writeHeader(w);
return w;
}
/**
* opens a writer to the named dump file
*
* @return writer
*/
public OutputWriter getDataDumpWriter(File file) throws IOException {
OutputWriter w = new OutputWriter(file);
writeHeader(w);
return w;
}
/**
* gets a append for the
*
*/
public InputOutputReaderWriter getFileAppender() throws IOException {
InputOutputReaderWriter io = new InputOutputReaderWriter(getFile(), "rw");
io.seek(io.length());
return io;
}
/**
* get the data index readerWriter
*
* @return data index readerWriter
*/
public InputReader getDataIndexReader() throws IOException {
loadInfoSection();
boolean useRelativeFilePositions = (infoSection.getTextStoragePolicy() == TextStoragePolicy.Embed);
InputReader r = new InputReader(getFile(), infoSection.getDataIndexSectionStart(), infoSection.getDataIndexSectionEnd(), !useRelativeFilePositions);
if (useRelativeFilePositions)
r.seek(0);
else
r.seek(infoSection.getDataIndexSectionStart());
check((byte) r.read(), CHECK_BYTE);
return r;
}
/**
* get data index readerWriter-writer. Use only to modify existing index, not to create a new one
*
* @return readerWriter-writer
*/
public InputOutputReaderWriter getDataIndexModifier() throws IOException {
loadInfoSection();
InputOutputReaderWriter io = new InputOutputReaderWriter(getFile(), "rw");
if (infoSection.getTextStoragePolicy() == TextStoragePolicy.Embed) {
// this is dirty: when using text_onboard policy, the data index is first written to a separate file
// and then copied to the main file. In this case, the file positions have be to offset
io.setOffset(infoSection.getDataIndexSectionStart()); // need to do this because readUids are locations relative to dataindexstart
io.seek(0);
} else
io.seek(infoSection.getDataIndexSectionStart());
check((byte) io.read(), CHECK_BYTE);
return io;
}
public InputReader getClassificationIndexReader(String classificationName) throws IOException {
loadInfoSection();
int id = infoSection.getClassificationNumber(classificationName);
return new InputReader(getFile(), infoSection.getClassificationIndexSectionStart(id), infoSection.getClassificationIndexSectionEnd(id), true);
}
public InputReader getClassificationDumpReader(String classificationName) throws IOException {
loadInfoSection();
int id = infoSection.getClassificationNumber(classificationName);
return new InputReader(getFile(), infoSection.getClassificationDumpSectionStart(id), infoSection.getClassificationDumpSectionEnd(id), true);
}
/**
* gets the temporary readerWriter
*
*/
public OutputWriter getTmpIndexFileWriter() throws IOException {
OutputWriter w = new OutputWriter(getIndexTmpFile());
w.write(CHECK_BYTE);
return w;
}
public InputReader getTmpIndexFileReader() throws IOException {
InputReader r = new InputReader(getIndexTmpFile(), null, null, true);
check((byte) r.read(), CHECK_BYTE);
return r;
}
private void writeHeader(IOutputWriter w) throws IOException {
w.writeInt(MAGIC_NUMBER);
w.writeInt(2); // version 2
w.writeString(creator);
}
private void readHeader(IInputReader r) throws IOException {
int magicNumber = r.readInt();
if (magicNumber != MAGIC_NUMBER)
throw new IOException("Not a RMA2 file");
int version = r.readInt();
if (version != 2)
throw new IOException("Not a RMA2 file, wrong version: " + version);
creator = r.readString();
}
/**
* check whether value read is the same as the value expected
*
*/
static public void check(long got, long expected) throws IOException {
if (expected != got)
throw new IOException("RMA2 file corrupt? Expected: " + expected + ", got: " + got);
}
private File getFile() {
return file;
}
public File getIndexTmpFile() {
File tmpFile = new File(file.getParent(), FileUtils.replaceFileSuffix(file.getName(), ".tmp0"));
tmpFile.deleteOnExit();
return tmpFile;
}
public File getClassificationIndexTmpFile() {
File tmpFile = new File(file.getParent(), FileUtils.replaceFileSuffix(file.getName(), ".tmp1"));
tmpFile.deleteOnExit();
return tmpFile;
}
/**
* gets the creation date of this dataset
*
* @return date
*/
public long getCreationDate() throws IOException {
loadInfoSection();
return infoSection.getCreationDate();
}
/**
* gets the list of classification names
*
* @return names
*/
public String[] getClassificationNames() throws IOException {
loadInfoSection();
return infoSection.getClassificationNames();
}
public int getClassificationSize(String classificationName) throws IOException {
loadInfoSection();
int id = infoSection.getClassificationNumber(classificationName);
if (id < 0)
return 0;
else
return infoSection.getClassificationSize(id);
}
/**
* gets the number of reads
*
* @return reads
*/
public int getNumberOfReads() throws IOException {
loadInfoSection();
return infoSection.getNumberOfReads();
}
/**
* gets the number of matches
*
* @return matches
*/
public int getNumberOfMatches() throws IOException {
loadInfoSection();
return infoSection.getNumberOfMatches();
}
public void setNumberOfReads(int numberOfReads) throws IOException {
loadInfoSection();
infoSection.setNumberOfReads(numberOfReads);
storeInfoSection();
}
public void setNumberOfMatches(int numberOfMatches) throws IOException {
loadInfoSection();
infoSection.setNumberOfMatches(numberOfMatches);
storeInfoSection();
}
/**
* replace the auxiliary data associated with the dataset
*
*/
public void replaceAuxiliaryData(Map<String, byte[]> label2data) throws IOException {
loadInfoSection();
try (InputOutputReaderWriter io = new InputOutputReaderWriter(new FileRandomAccessReadWriteAdapter(file.getPath(), "rw"))) {
long newPos = infoSection.getAuxiliaryDataStart();
if (newPos == 0)
newPos = infoSection.getInfoSectionStart();
io.seek(newPos);
infoSection.setAuxiliaryDataStart(newPos);
StringBuilder buf = new StringBuilder();
for (String label : label2data.keySet()) {
byte[] bytes = label2data.get(label);
if (bytes != null) {
buf.append("<<<").append(label).append(">>>").append(new String(bytes));
}
}
io.write(buf.toString().getBytes());
infoSection.setAuxiliaryDataEnd(io.getPosition());
infoSection.write(io);
io.setLength(io.getPosition());
}
// System.err.println("Saved summary:\n" + Basic.toString(auxiliaryData));
}
/**
* gets the summary section of the file
*
*/
public Map<String, byte[]> getAuxiliaryData() throws IOException {
loadInfoSection();
Map<String, byte[]> result = new HashMap<>();
if (infoSection.isHasAuxiliaryMap()) {
String auxiliaryDataString;
try (InputReader r = new InputReader(getFile(), infoSection.getAuxiliaryDataStart(), infoSection.getAuxiliaryDataEnd(), false)) {
int size = (int) r.length();
byte[] bytes = new byte[size];
r.read(bytes, 0, size);
auxiliaryDataString = new String(bytes);
}
String prevLabel = null;
int prevDataStart = 0;
for (int startPos = auxiliaryDataString.indexOf("<<<"); startPos != -1; startPos = auxiliaryDataString.indexOf("<<<", startPos + 1)) {
if (prevLabel != null) {
String data = auxiliaryDataString.substring(prevDataStart, startPos);
result.put(prevLabel, data.getBytes());
prevLabel = null;
}
int endPos = auxiliaryDataString.indexOf(">>>", startPos + 1);
if (startPos < endPos) {
prevLabel = auxiliaryDataString.substring(startPos + 3, endPos);
prevDataStart = endPos + 3;
}
}
if (prevLabel != null) {
String data = auxiliaryDataString.substring(prevDataStart);
result.put(prevLabel, data.getBytes());
}
} else {
String auxiliaryDataString;
try (InputReader r = new InputReader(getFile(), infoSection.getAuxiliaryDataStart(), infoSection.getAuxiliaryDataEnd(), false)) {
int size = (int) r.length();
byte[] bytes = new byte[size];
r.read(bytes, 0, size);
auxiliaryDataString = new String(bytes);
}
int pos = auxiliaryDataString.indexOf("BEGIN_METADATA_TABLE");
if (pos != -1) {
byte[] bytes = auxiliaryDataString.substring(0, pos).getBytes();
result.put(SampleAttributeTable.USER_STATE, bytes);
pos += "BEGIN_METADATA_TABLE".length();
bytes = auxiliaryDataString.substring(pos).getBytes();
result.put(SampleAttributeTable.SAMPLE_ATTRIBUTES, bytes);
} else
result.put(SampleAttributeTable.USER_STATE, auxiliaryDataString.getBytes());
}
return result;
}
/**
* gets a classification block
*
*/
public ClassificationBlockRMA2 getClassificationBlock(String classificationName) throws IOException {
ClassificationBlockRMA2 classificationBlock = new ClassificationBlockRMA2(classificationName);
classificationBlock.load(getClassificationIndexReader(classificationName));
return classificationBlock;
}
/**
* get the location manager associated with this file
*
* @return locationManager
*/
public LocationManager getLocationManager() throws IOException {
InfoSection infoSection = loadInfoSection();
return infoSection.getLocationManager(getFile());
}
/**
* replace the location manager by a new one
*
*/
public void replaceLocationManager(LocationManager locationManager) throws IOException {
InfoSection infoSection = loadInfoSection();
infoSection.syncLocationManager2InfoSection(locationManager);
storeInfoSection();
}
}
| 14,427 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
RMA2Modifier.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma2/RMA2Modifier.java | /*
* RMA2Modifier.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.rma2;
import megan.io.InputOutputReaderWriter;
import megan.io.InputReader;
import megan.io.OutputWriter;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* classed used to rescan classifications in RMA2 file
* Daniel Huson, 10.2010
*/
public class RMA2Modifier {
private final RMA2File rma2File;
private final InfoSection infoSection;
private final InputOutputReaderWriter io;
private String currentName;
private OutputWriter classificationIndexTmpFileWriter;
private int numberOfClasses;
private long dumpStart;
/**
* construct a new RMA2Modifier that can be used to rewrite all classifications. The summary section ist lost
*
*/
public RMA2Modifier(File file) throws IOException {
rma2File = new RMA2File(file);
infoSection = rma2File.loadInfoSection();
io = rma2File.getFileAppender();
infoSection.read(io);
// erase summary section:
infoSection.setAuxiliaryDataStart(0);
infoSection.setAuxiliaryDataEnd(0);
infoSection.setNumberOfClassifications(0);
// go to end of data section and remove all classifications, summary and info
io.seek(infoSection.getDataIndexSectionEnd());
io.setLength(infoSection.getDataIndexSectionEnd());
}
/**
* start a new classification
*
*/
public void startClassificationSection(String name) throws IOException {
currentName = name;
dumpStart = io.getPosition();
classificationIndexTmpFileWriter = new OutputWriter(rma2File.getClassificationIndexTmpFile());
numberOfClasses = 0;
}
/**
* add an entry to the classification
*
*/
public void addToClassification(Integer classId, float weight, List<Long> positions) throws IOException {
numberOfClasses++;
classificationIndexTmpFileWriter.writeInt(classId);
if (weight == positions.size())
classificationIndexTmpFileWriter.writeInt((int) weight);
else {
classificationIndexTmpFileWriter.writeInt(-(int) weight);
classificationIndexTmpFileWriter.writeInt(positions.size());
}
// System.err.println("classId: "+classId+" size: "+size+" dumpPos: "+io.getPosition()+" readPos: "+ Basic.toString(positions,","));
if (positions.size() > 0) {
classificationIndexTmpFileWriter.writeLong(io.getPosition());
for (Long pos : positions) {
io.writeLong(pos);
}
} else // no elements, write -1
{
classificationIndexTmpFileWriter.writeLong(-1);
}
}
/**
* finish a classification. The temporary file is closed, appended to the main file and then deleted
*
*/
public void finishClassificationSection() throws IOException {
long dumpEnd = io.getPosition();
// copy index:
long indexStart = io.getPosition();
if (classificationIndexTmpFileWriter != null && classificationIndexTmpFileWriter.length() > 0) {
// System.err.println("Position at close: " + classificationIndexTmpFileWriter.getPosition());
// System.err.println("Size at close: " + classificationIndexTmpFileWriter.length());
classificationIndexTmpFileWriter.close();
// System.err.println("File size: " + rma2File.getClassificationIndexTmpFile().length());
try (InputReader r = new InputReader(rma2File.getClassificationIndexTmpFile(), null, null, true)) {
// System.err.println("Channel: " + r.getChannel().size());
final int bufferSize = 1000000;
long length = r.length();
int blocks = (int) (length / bufferSize);
byte[] buffer = new byte[bufferSize];
long total = 0;
for (int i = 0; i < blocks; i++) {
if (r.read(buffer, 0, bufferSize) < bufferSize)
throw new IOException("Buffer underflow");
io.write(buffer, 0, bufferSize);
total += bufferSize;
}
int remainder = (int) (length - bufferSize * blocks);
if (remainder > 0) {
if (r.read(buffer, 0, remainder) < remainder)
throw new IOException("Buffer underflow");
io.write(buffer, 0, remainder);
}
//System.err.println("Copied: " + total);
io.seekToEnd();
}
}
long indexEnd = io.getPosition();
rma2File.getClassificationIndexTmpFile().delete();
infoSection.addClassification(currentName, numberOfClasses, dumpStart, dumpEnd, indexStart, indexEnd);
}
/**
* append the info section to the main file and then close it
*
*/
public void close() throws IOException {
infoSection.updateModificationDate();
infoSection.write(io);
}
}
| 5,830 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
RMA2Connector.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma2/RMA2Connector.java | /*
* RMA2Connector.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.rma2;
import jloda.util.Single;
import jloda.util.progress.ProgressListener;
import megan.data.*;
import java.io.File;
import java.io.IOException;
import java.util.*;
/**
* connector for an RMA2 file
* Daniel Huson, 9.2010
*/
public class RMA2Connector implements IConnector {
private File file;
/**
* constructor
*
*/
public RMA2Connector(String fileName) throws IOException {
setFile(fileName);
}
@Override
public String getFilename() {
return file.getPath();
}
/**
* set the file name of interest. Only one file can be used.
*
*/
public void setFile(String filename) {
file = new File(filename);
}
/**
* is connected document readonly?
*
* @return true, if read only
*/
public boolean isReadOnly() {
return file == null || !file.canWrite();
}
/**
* gets the unique identifier for the given filename.
* This method is also used to test whether dataset exists and can be connected to
*
* @return unique id
*/
public long getUId() throws IOException {
return (new RMA2File(file)).getCreationDate();
}
/**
* get all reads with specified matches.
*
* @param wantReadSequence @param wantMatches specifies what data to return in ReadBlock
* @return getLetterCodeIterator over all reads
*/
public IReadBlockIterator getAllReadsIterator(float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException {
return new AllReadsIterator(getReadBlockGetter(minScore, maxExpected, wantReadSequence, wantMatches));
}
/**
* get getLetterCodeIterator over all reads for given classification and classId.
*
* @param wantReadSequence @param wantMatches specifies what data to return in ReadBlock
* @return getLetterCodeIterator over reads in class
*/
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);
}
/**
* get getLetterCodeIterator over all reads for given classification and a collection of classids. If minScore=0 no filtering
*
* @param wantReadSequence @param wantMatches
* @return getLetterCodeIterator over reads filtered by given parameters
*/
public IReadBlockIterator getReadsIteratorForListOfClassIds(String classification, Collection<Integer> classIds, float minScore,
float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException {
return new ReadBlockIteratorRMA2(classification, classIds, wantReadSequence, wantMatches, wantMatches, minScore, maxExpected, file);
}
/**
* gets a read block accessor
*
* @param wantReadSequence @param wantMatches
* @return read block accessor
*/
public IReadBlockGetter getReadBlockGetter(float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException {
return new ReadBlockGetterRMA2(file, minScore, maxExpected, wantReadSequence, wantMatches, wantMatches);
}
/**
* get array of all classification names associated with this file or db
*
* @return classifications
*/
public String[] getAllClassificationNames() throws IOException {
return (new RMA2File(file)).getClassificationNames();
}
/**
* gets the number of classes in the named classification
*
* @return number of classes
*/
public int getClassificationSize(String classificationName) throws IOException {
return (new RMA2File(file)).getClassificationSize(classificationName);
}
/**
* gets the number of reads in a given class
*
* @return number of reads
*/
public int getClassSize(String classificationName, int classId) throws IOException {
ClassificationBlockRMA2 classificationBlock = (new RMA2File(file)).getClassificationBlock(classificationName);
// todo: this is very wasteful, better to read in the block once and then keep it...
return classificationBlock.getSum(classId);
}
/**
* gets the named classification block
*
* @return classification block
*/
public IClassificationBlock getClassificationBlock(String classificationName) throws IOException {
return (new RMA2File(file)).getClassificationBlock(classificationName);
}
/**
* updates the classId values for a collection of reads
*
* @param names names of classifications in the order that their values will appear in
* @param updateItemList list of rescan items
*/
public void updateClassifications(String[] names, List<UpdateItem> updateItemList, ProgressListener progressListener) throws IOException {
UpdateItemList updateItems = (UpdateItemList) updateItemList;
final int numClassifications = names.length;
long maxProgress = 0;
for (int i = 0; i < numClassifications; i++) {
maxProgress += updateItems.getClassIds(i).size();
}
progressListener.setMaximum(maxProgress);
final RMA2Modifier rma2Modifier = new RMA2Modifier(file);
for (int i = 0; i < numClassifications; i++) {
rma2Modifier.startClassificationSection(names[i]);
try {
for (Integer classId : updateItems.getClassIds(i)) {
float weight = updateItems.getWeight(i, classId);
final List<Long> positions = new ArrayList<>();
if (updateItems.getWeight(i, classId) > 0) {
for (UpdateItem item = updateItems.getFirst(i, classId); item != null; item = item.getNextInClassification(i)) {
positions.add(item.getReadUId());
}
}
rma2Modifier.addToClassification(classId, weight, positions);
progressListener.incrementProgress();
}
} finally {
rma2Modifier.finishClassificationSection();
}
}
rma2Modifier.close();
}
/**
* get all reads that match the given expression
*
* @param findSelection where to search for matches
* @return getLetterCodeIterator over reads that match
*/
public IReadBlockIterator getFindAllReadsIterator(String regEx, FindSelection findSelection, Single<Boolean> canceled) throws IOException {
return new FindAllReadsIterator(regEx, findSelection, getAllReadsIterator(0, 10, true, true), canceled);
}
/**
* gets the number of reads
*
* @return number of reads
*/
public int getNumberOfReads() throws IOException {
return (new RMA2File(file)).getNumberOfReads();
}
/**
* get the total number of matches
*
* @return number of matches
*/
public int getNumberOfMatches() throws IOException {
return (new RMA2File(file)).getNumberOfMatches();
}
/**
* sets the number of reads. Note that the logical number of reads may differ from
* the actual number of reads stored, so this needs to be stored explicitly
*
*/
public void setNumberOfReads(int numberOfReads) throws IOException {
(new RMA2File(file)).setNumberOfReads(numberOfReads);
}
/**
* puts the MEGAN auxiliary data associated with the dataset
*
*/
public void putAuxiliaryData(Map<String, byte[]> label2data) throws IOException {
(new RMA2File(file)).replaceAuxiliaryData(label2data);
}
/**
* gets the MEGAN auxiliary data associated with the dataset
*
* @return auxiliaryData
*/
public Map<String, byte[]> getAuxiliaryData() throws IOException {
return (new RMA2File(file)).getAuxiliaryData();
}
}
| 8,941 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
InfoSection.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma2/InfoSection.java | /*
* InfoSection.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.rma2;
import megan.data.LocationManager;
import megan.data.TextStoragePolicy;
import megan.io.IInputReader;
import megan.io.IOutputWriter;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Date;
import java.util.Objects;
/**
* info section of RMA2 file
* Daniel Huson, 10.2010
*/
public class InfoSection {
static private final byte VERSION_RMA2_0 = (byte) 255; // original RMA2 format
static private final byte VERSION_RMA2_1 = (byte) 254; // RMA2 format with READ and MATCH fixed-part formatting
private byte version;
private final byte AUXILIARY_DATA_AS_MAP_BYTE = (byte) 254;
private long creationDate;
private long modificationDate;
private int numberOfReads;
private int numberOfMatches;
private TextStoragePolicy textStoragePolicy;
private String[] textFileNames;
private Long[] textFileSizes;
private RMA2Formatter rma2Formatter;
// text sections if textLocationType==ONBOARD
private long dataDumpSectionStart;
private long dataDumpSectionEnd; // first position after datasection
private long dataIndexSectionStart;
private long dataIndexSectionEnd;
private String[] classificationNames = new String[0];
private Integer[] classificationSizes = new Integer[0];
private Long[] classificationDumpSectionStart = new Long[0];
private Long[] classificationDumpSectionEnd = new Long[0];
private Long[] classificationIndexSectionStart = new Long[0];
private Long[] classificationIndexSectionEnd = new Long[0];
private long auxiliaryDataStart;
private long auxiliaryDataEnd;
private boolean hasAuxiliaryMap;
private long infoSectionStart;
/**
* constructor
*/
public InfoSection() {
creationDate = System.currentTimeMillis();
modificationDate = creationDate;
version = VERSION_RMA2_1;
rma2Formatter = new RMA2Formatter(ReadBlockRMA2Formatter.DEFAULT_RMA2_5, MatchBlockRMA2Formatter.DEFAULT_RMA2_5);
}
/**
* write to end of file
*
*/
public void write(IOutputWriter w) throws IOException {
infoSectionStart = w.getPosition();
w.write(version);
w.writeLong(creationDate);
w.writeLong(modificationDate);
w.writeInt(numberOfReads);
w.writeInt(numberOfMatches);
if (version != VERSION_RMA2_0) {
w.writeString(rma2Formatter.getReadBlockRMA2Formatter().toString());
w.writeString(rma2Formatter.getMatchBlockRMA2Formatter().toString());
}
w.write(TextStoragePolicy.getId(textStoragePolicy));
switch (textStoragePolicy) {
case Embed -> {
w.writeLong(dataDumpSectionStart);
w.writeLong(dataDumpSectionEnd);
}
case InRMAZ, Reference -> {
w.writeInt(textFileNames.length);
for (String textFileName : textFileNames) {
w.writeString(Objects.requireNonNullElse(textFileName, ""));
}
if (textFileSizes == null)
w.writeInt(0);
else {
w.writeInt(textFileSizes.length);
for (Long textFileSize : textFileSizes) {
w.writeLong(Objects.requireNonNullElse(textFileSize, -1L));
}
}
}
default -> throw new IOException("Unknown textStoragePolicy: " + textStoragePolicy);
}
w.writeLong(dataIndexSectionStart);
w.writeLong(dataIndexSectionEnd);
w.writeInt(classificationNames.length);
for (String name : classificationNames)
w.writeString(name);
for (int size : classificationSizes)
w.writeInt(size);
for (long pos : classificationIndexSectionStart)
w.writeLong(pos);
for (long pos : classificationIndexSectionEnd)
w.writeLong(pos);
for (long pos : classificationDumpSectionStart)
w.writeLong(pos);
for (long pos : classificationDumpSectionEnd)
w.writeLong(pos);
w.writeLong(auxiliaryDataStart);
w.writeLong(auxiliaryDataEnd);
w.write(AUXILIARY_DATA_AS_MAP_BYTE);
w.write(RMA2File.CHECK_BYTE);
w.writeLong(infoSectionStart);
}
/**
* read from end of file
*
*/
public void read(IInputReader r) throws IOException {
r.seek(r.length() - 9);
RMA2File.check((byte) r.read(), RMA2File.CHECK_BYTE);
infoSectionStart = r.readLong();
r.seek(infoSectionStart);
version = (byte) r.read();
if (!(version == VERSION_RMA2_0 || version == VERSION_RMA2_1))
throw new IOException("Unsupported subversion of RMA2 format (MEGAN version too old?)");
setCreationDate(r.readLong());
if (getCreationDate() < 1292313486909L) // 14.Dec 2010
throw new IOException("RMA2 file generated by alpha version, too old, please regenerate");
setModificationDate(r.readLong());
setNumberOfReads(r.readInt());
setNumberOfMatches(r.readInt());
if (version == VERSION_RMA2_0) {
rma2Formatter = new RMA2Formatter(ReadBlockRMA2Formatter.DEFAULT_RMA2_0, MatchBlockRMA2Formatter.DEFAULT_RMA2_0);
} else // later versions have explicit format strings for reads and matches
{
rma2Formatter = new RMA2Formatter(r.readString(), r.readString());
}
setTextStoragePolicy(TextStoragePolicy.fromId((byte) r.read()));
if (getTextStoragePolicy() == TextStoragePolicy.Embed) {
setDataDumpSectionStart(r.readLong());
setDataDumpSectionEnd(r.readLong());
textFileNames = new String[0];
textFileSizes = new Long[0];
} else if (getTextStoragePolicy() == TextStoragePolicy.Reference || getTextStoragePolicy() == TextStoragePolicy.InRMAZ) {
int length = r.readInt();
textFileNames = new String[length];
for (int i = 0; i < textFileNames.length; i++) {
textFileNames[i] = r.readString();
}
length = r.readInt();
textFileSizes = new Long[length];
for (int i = 0; i < textFileSizes.length; i++) {
textFileSizes[i] = r.readLong();
}
setDataDumpSectionStart(0);
setDataDumpSectionEnd(0);
} else
throw new IOException("Unknown textStoragePolicy: " + textStoragePolicy);
setDataIndexSectionStart(r.readLong());
setDataIndexSectionEnd(r.readLong());
setNumberOfClassifications(r.readInt());
for (int i = 0; i < getNumberOfClassifications(); i++)
setClassificationName(i, r.readString());
for (int i = 0; i < getNumberOfClassifications(); i++)
setClassificationSize(i, r.readInt());
for (int i = 0; i < getNumberOfClassifications(); i++)
setClassificationIndexSectionStart(i, r.readLong());
for (int i = 0; i < getNumberOfClassifications(); i++)
setClassificationIndexSectionEnd(i, r.readLong());
for (int i = 0; i < getNumberOfClassifications(); i++)
setClassificationDumpSectionStart(i, r.readLong());
for (int i = 0; i < getNumberOfClassifications(); i++)
setClassificationDumpSectionEnd(i, r.readLong());
setAuxiliaryDataStart(r.readLong());
setAuxiliaryDataEnd(r.readLong());
byte aByte = (byte) r.read();
if (aByte == AUXILIARY_DATA_AS_MAP_BYTE) {
setHasAuxiliaryMap(true);
RMA2File.check((byte) r.read(), RMA2File.CHECK_BYTE);
} else {
setHasAuxiliaryMap(false);
RMA2File.check(aByte, RMA2File.CHECK_BYTE);
}
RMA2File.check(r.readLong(), infoSectionStart);
}
/**
* write in human readable form
*
* @return string
*/
public String toString() {
StringWriter w = new StringWriter();
if (version == VERSION_RMA2_0)
w.write("RMA file version: 2.0\n");
else if (version == VERSION_RMA2_1)
w.write("RMA file version: 2.1\n");
else
w.write("RMA file version: 2.* (" + version + ")\n");
w.write("creationDate: " + new Date(getCreationDate()) + "\n");
w.write("modificationDate: " + new Date(getModificationDate()) + "\n");
w.write("numberOfReads: " + getNumberOfReads() + "\n");
w.write("numberOfMatches: " + getNumberOfMatches() + "\n");
w.write("textStoragePolicy: " + getTextStoragePolicy() + "(" + TextStoragePolicy.getDescription(getTextStoragePolicy()) + ")\n");
if (getTextFileNames() != null) {
w.write("Source text files:\n");
for (int i = 0; i < getTextFileNames().length; i++) {
w.write("\t" + getTextFileNames()[i]);
if (i < getTextFileSizes().length)
w.write("\t" + getTextFileSizes()[i]);
w.write("\n");
}
}
w.write("Reads format: " + rma2Formatter.getReadBlockRMA2Formatter().toString() + "\n");
w.write("Matches format: " + rma2Formatter.getMatchBlockRMA2Formatter().toString() + "\n");
w.write("dataDumpSectionStart: " + getDataDumpSectionStart() + "\n");
w.write("dataDumpSectionEnd: " + getDataDumpSectionEnd() + "\n");
w.write("dataIndexSectionStart: " + getDataIndexSectionStart() + "\n");
w.write("dataIndexSectionEnd: " + getDataIndexSectionEnd() + "\n");
w.write("Number of classifications: " + getClassificationNames().length + "\n");
w.write("classificationNames:");
for (String name : getClassificationNames())
w.write(" " + name);
w.write("\n");
w.write("classificationSizes:");
for (int size : classificationSizes)
w.write(" " + size);
w.write("\n");
w.write("classificationIndexSectionStart:");
for (long pos : classificationIndexSectionStart)
w.write(" " + pos);
w.write("\n");
w.write("classificationIndexSectionEnd:");
for (long pos : classificationIndexSectionEnd)
w.write(" " + pos);
w.write("\n");
w.write("classificationDumpSectionStart:");
for (long pos : classificationDumpSectionStart)
w.write(" " + pos);
w.write("\n");
w.write("classificationDumpSectionEnd:");
for (long pos : classificationDumpSectionEnd)
w.write(" " + pos);
w.write("\n");
w.write("hasAuxiliaryMap: " + hasAuxiliaryMap + "\n");
w.write("userStateSectionStart: " + getAuxiliaryDataStart() + "\n");
w.write("userStateSectionEnd: " + getAuxiliaryDataEnd() + "\n");
w.write("infoSectionStart: " + getInfoSectionStart() + "\n");
return w.toString();
}
public long getCreationDate() {
return creationDate;
}
private void setCreationDate(long creationDate) {
this.creationDate = creationDate;
}
private long getModificationDate() {
return modificationDate;
}
private void setModificationDate(long modificationDate) {
this.modificationDate = modificationDate;
}
public void updateModificationDate() {
modificationDate = System.currentTimeMillis();
}
public int getNumberOfReads() {
return numberOfReads;
}
public void setNumberOfReads(int numberOfReads) {
this.numberOfReads = numberOfReads;
}
public int getNumberOfMatches() {
return numberOfMatches;
}
public void setNumberOfMatches(int numberOfMatches) {
this.numberOfMatches = numberOfMatches;
}
public int getClassificationSize(int i) {
return classificationSizes[i];
}
private void setClassificationSize(int i, int size) {
this.classificationSizes[i] = size;
}
private long getDataDumpSectionStart() {
return dataDumpSectionStart;
}
public void setDataDumpSectionStart(long dataDumpSectionStart) {
this.dataDumpSectionStart = dataDumpSectionStart;
}
private long getDataDumpSectionEnd() {
return dataDumpSectionEnd;
}
public void setDataDumpSectionEnd(long dataDumpSectionEnd) {
this.dataDumpSectionEnd = dataDumpSectionEnd;
}
public long getDataIndexSectionStart() {
return dataIndexSectionStart;
}
public void setDataIndexSectionStart(long dataIndexSectionStart) {
this.dataIndexSectionStart = dataIndexSectionStart;
}
public long getDataIndexSectionEnd() {
return dataIndexSectionEnd;
}
public void setDataIndexSectionEnd(long dataIndexSectionEnd) {
this.dataIndexSectionEnd = dataIndexSectionEnd;
}
public void setNumberOfClassifications(int numberOfClassifications) {
classificationIndexSectionStart = new Long[numberOfClassifications];
classificationIndexSectionEnd = new Long[numberOfClassifications];
classificationDumpSectionStart = new Long[numberOfClassifications];
classificationDumpSectionEnd = new Long[numberOfClassifications];
classificationNames = new String[numberOfClassifications];
classificationSizes = new Integer[numberOfClassifications];
}
public long getClassificationIndexSectionStart(int i) {
return classificationIndexSectionStart[i];
}
private void setClassificationIndexSectionStart(int i, long classificationSectionStart) {
this.classificationIndexSectionStart[i] = classificationSectionStart;
}
public long getClassificationIndexSectionEnd(int i) {
return classificationIndexSectionEnd[i];
}
private void setClassificationIndexSectionEnd(int i, long classificationSectionEnd) {
this.classificationIndexSectionEnd[i] = classificationSectionEnd;
}
public long getClassificationDumpSectionStart(int i) {
return classificationDumpSectionStart[i];
}
private void setClassificationDumpSectionStart(int i, long classificationSectionStart) {
this.classificationDumpSectionStart[i] = classificationSectionStart;
}
public long getClassificationDumpSectionEnd(int i) {
return classificationDumpSectionEnd[i];
}
private void setClassificationDumpSectionEnd(int i, long classificationSectionEnd) {
this.classificationDumpSectionEnd[i] = classificationSectionEnd;
}
private int getNumberOfClassifications() {
return classificationNames.length;
}
public String[] getClassificationNames() {
return classificationNames;
}
public String[] getClassificationName(int i) {
return classificationNames;
}
private void setClassificationName(int i, String classificationName) {
this.classificationNames[i] = classificationName;
}
public long getAuxiliaryDataStart() {
return auxiliaryDataStart;
}
public void setAuxiliaryDataStart(long auxiliaryDataStart) {
this.auxiliaryDataStart = auxiliaryDataStart;
}
public long getAuxiliaryDataEnd() {
return auxiliaryDataEnd;
}
public void setAuxiliaryDataEnd(long auxiliaryDataEnd) {
this.auxiliaryDataEnd = auxiliaryDataEnd;
}
public boolean isHasAuxiliaryMap() {
return hasAuxiliaryMap;
}
private void setHasAuxiliaryMap(boolean hasAuxiliaryMap) {
this.hasAuxiliaryMap = hasAuxiliaryMap;
}
public TextStoragePolicy getTextStoragePolicy() {
return textStoragePolicy;
}
public void setTextStoragePolicy(TextStoragePolicy textStoragePolicy) {
this.textStoragePolicy = textStoragePolicy;
}
private String[] getTextFileNames() {
return textFileNames;
}
public void setTextFileNames(String[] textFileNames) {
this.textFileNames = textFileNames;
}
private Long[] getTextFileSizes() {
return textFileSizes;
}
public void setTextFileSizes(Long[] textFileSizes) {
this.textFileSizes = textFileSizes;
}
public long getInfoSectionStart() {
return infoSectionStart;
}
/**
* gets the index of the given classification
*
* @return index or -1
*/
public int getClassificationNumber(String classificationName) {
for (int i = 0; i < classificationNames.length; i++)
if (classificationName.equals(classificationNames[i]))
return i;
return -1;
}
/**
* add a new classification
*
*/
public void addClassification(String name, int size, long dumpStart, long dumpEnd, long indexStart, long indexEnd) {
classificationNames = extend(classificationNames, name);
classificationSizes = extend(classificationSizes, size);
classificationDumpSectionStart = extend(classificationDumpSectionStart, dumpStart);
classificationDumpSectionEnd = extend(classificationDumpSectionEnd, dumpEnd);
classificationIndexSectionStart = extend(classificationIndexSectionStart, indexStart);
classificationIndexSectionEnd = extend(classificationIndexSectionEnd, indexEnd);
}
private static String[] extend(String[] array, String add) {
String[] newArray = new String[array.length + 1];
System.arraycopy(array, 0, newArray, 0, array.length);
newArray[newArray.length - 1] = add;
return newArray;
}
private static Long[] extend(Long[] array, Long add) {
Long[] newArray = new Long[array.length + 1];
System.arraycopy(array, 0, newArray, 0, array.length);
newArray[newArray.length - 1] = add;
return newArray;
}
private static Integer[] extend(Integer[] array, Integer add) {
Integer[] newArray = new Integer[array.length + 1];
System.arraycopy(array, 0, newArray, 0, array.length);
newArray[newArray.length - 1] = add;
return newArray;
}
/**
* gets the location manager stored in this info section
*
* @return location manager
*/
public LocationManager getLocationManager(File onboardFile) {
LocationManager locationManager = new LocationManager(textStoragePolicy);
if (getTextStoragePolicy() == TextStoragePolicy.Embed)
locationManager.addFile(onboardFile);
else {
for (int i = 0; i < textFileNames.length; i++) {
if (i < textFileSizes.length)
locationManager.addFile(new File(textFileNames[i]), textFileSizes[i]);
else
locationManager.addFile(new File(textFileNames[i]));
}
}
return locationManager;
}
/**
* set the location manager
*
*/
public void syncLocationManager2InfoSection(LocationManager locationManager) throws IOException {
if (textStoragePolicy != locationManager.getTextStoragePolicy())
throw new IOException("setLocationManager(): attempting to change textStoragePolicy from " +
textStoragePolicy + " to " + locationManager.getTextStoragePolicy());
textStoragePolicy = locationManager.getTextStoragePolicy();
textFileNames = locationManager.getFileNames();
textFileSizes = locationManager.getFileSizes();
}
/**
* gets the formatter associated with the file
*
* @return formatter
*/
public RMA2Formatter getRMA2Formatter() {
return rma2Formatter;
}
}
| 20,480 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ReadBlockIteratorAllRMA2.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma2/ReadBlockIteratorAllRMA2.java | /*
* ReadBlockIteratorAllRMA2.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.rma2;
import jloda.util.Basic;
import megan.data.IReadBlock;
import megan.data.IReadBlockIterator;
import megan.data.TextStorageReader;
import megan.io.IInputReader;
import java.io.File;
import java.io.IOException;
/**
* readblock getLetterCodeIterator over all reads, containing location information
* Daniel Huson, 3.2012
*/
public class ReadBlockIteratorAllRMA2 implements IReadBlockIterator {
private final TextStorageReader textStorageReader;
private final IInputReader dataIndexReader;
private final RMA2Formatter rma2Formatter;
private final boolean wantReadText;
private final boolean wantMatchData;
private final boolean wantMatchText;
private final float minScore;
private final float maxExpected;
private int countReads = 0;
private boolean error = false;
/**
* constructor
*
*/
public ReadBlockIteratorAllRMA2(boolean wantReadText, boolean wantMatchData, boolean wantMatchText, float minScore, float maxExpected, File file) throws IOException {
this.wantReadText = wantReadText;
this.wantMatchData = wantMatchData;
this.wantMatchText = wantMatchText;
this.minScore = minScore;
this.maxExpected = maxExpected;
RMA2File rma2File = new RMA2File(file);
dataIndexReader = rma2File.getDataIndexReader();
InfoSection infoSection = rma2File.loadInfoSection();
rma2Formatter = infoSection.getRMA2Formatter();
if (wantReadText || wantMatchText) {
textStorageReader = new TextStorageReader(infoSection.getLocationManager(file));
} else
textStorageReader = null;
}
/**
* get a string reporting stats
*
* @return stats string
*/
public String getStats() {
return "Reads: " + countReads;
}
/**
* close associated file or database
*/
public void close() {
try {
if (textStorageReader != null)
textStorageReader.closeAllFiles();
if (dataIndexReader != null)
dataIndexReader.close();
} catch (IOException e) {
Basic.caught(e);
}
}
/**
* gets the maximum progress value
*
* @return maximum progress value
*/
public long getMaximumProgress() {
try {
return dataIndexReader.length();
} catch (IOException e) {
Basic.caught(e);
return -1;
}
}
/**
* gets the current progress value
*
* @return current progress value
*/
public long getProgress() {
try {
return dataIndexReader.getPosition();
} catch (IOException e) {
Basic.caught(e);
return -1;
}
}
/**
* Returns <tt>true</tt> if the iteration has more elements. (In other
* words, returns <tt>true</tt> if <tt>next</tt> would return an element
* rather than throwing an exception.)
*
* @return <tt>true</tt> if the getLetterCodeIterator has more elements.
*/
public boolean hasNext() {
try {
return !error && dataIndexReader.getPosition() < dataIndexReader.length();
} catch (IOException e) {
Basic.caught(e);
return false;
}
}
/**
* Returns the next element in the iteration.
*
* @return the next element in the iteration.
* @throws java.util.NoSuchElementException iteration has no more elements.
*/
public IReadBlock next() {
try {
countReads++;
return ReadBlockRMA2.read(rma2Formatter, -1, wantReadText, wantMatchData, wantMatchText, minScore, maxExpected, textStorageReader, dataIndexReader);
} catch (IOException e) {
Basic.caught(e);
error = true;
return null;
}
}
/**
* not implemented
*/
public void remove() {
}
public void setWantLocationData(boolean wantLocationData) {
rma2Formatter.setWantLocationData(wantLocationData);
}
}
| 4,909 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ReadBlockRMA2.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma2/ReadBlockRMA2.java | /*
* ReadBlockRMA2.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.rma2;
import jloda.util.Pair;
import jloda.util.StringUtils;
import megan.data.*;
import megan.io.IInputReader;
import megan.io.IOutputWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedList;
import java.util.List;
import java.util.SortedSet;
/**
* a simple read block
* Daniel Huson, 9.2010
*/
public class ReadBlockRMA2 implements IReadBlock {
private long uid;
private String readHeader;
private String readSequence;
private int readWeight;
private long mateReadUId;
private byte mateType;
private int readLength;
private float complexity;
private int numberOfMatches;
private IMatchBlock[] matchBlocks = new MatchBlockRMA2[0];
/**
* erase the block (for reuse)
*/
public void clear() {
uid = 0;
readHeader = null;
readSequence = null;
readWeight = 1;
mateReadUId = 0;
mateType = 0;
readLength = 0;
complexity = 0;
numberOfMatches = 0;
matchBlocks = new MatchBlockRMA2[0];
}
/**
* get the unique identifier for this read (unique within a dataset).
* In an RMA file, this is always the file position for the read
*
* @return uid
*/
public long getUId() {
return uid;
}
public void setUId(long uid) {
this.uid = uid;
}
/**
* get the name of the read (first word in header)
*
* @return name
*/
public String getReadName() {
if (readHeader != null) {
String name = StringUtils.getFirstWord(readHeader);
if (name.startsWith(">"))
return name.substring(1).trim();
else
return name;
}
return null;
}
/**
* get the fastA header for the read
*
* @return fastA header
*/
public String getReadHeader() {
return readHeader;
}
public void setReadHeader(String readHeader) {
this.readHeader = readHeader;
}
/**
* get the sequence of the read
*
* @return sequence
*/
public String getReadSequence() {
return readSequence;
}
/**
* set the read sequence
*
*/
public void setReadSequence(String readSequence) {
this.readSequence = readSequence;
}
/**
* gets the uid of the mated read
*
* @return uid of mate or 0
*/
public long getMateUId() {
return mateReadUId;
}
public void setMateUId(long mateReadUId) {
this.mateReadUId = mateReadUId;
}
/**
* get the mate type
* Possible values: FIRST_MATE, SECOND_MATE
*
* @return mate type
*/
public byte getMateType() {
return mateType;
}
public void setMateType(byte type) {
this.mateType = type;
}
/**
* set the read length
*
*/
public void setReadLength(int readLength) {
this.readLength = readLength;
}
public int getReadLength() {
return readLength;
}
public int getReadWeight() {
return readWeight;
}
public void setReadWeight(int readWeight) {
this.readWeight = readWeight;
}
/**
* get the complexity
*
*/
public void setComplexity(float complexity) {
this.complexity = complexity;
}
public float getComplexity() {
return complexity;
}
/**
* get the original number of matches
*
* @return number of matches
*/
public int getNumberOfMatches() {
return numberOfMatches;
}
public void setNumberOfMatches(int numberOfMatches) {
this.numberOfMatches = numberOfMatches;
}
/**
* gets the current number of matches available
*
*/
public int getNumberOfAvailableMatchBlocks() {
if (matchBlocks != null)
return matchBlocks.length;
else
return 0;
}
/**
* get the matches. May be less than the original number of matches (when filtering matches)
*
*/
public IMatchBlock[] getMatchBlocks() {
return matchBlocks;
}
public void setMatchBlocks(IMatchBlock[] matchBlocks) {
this.matchBlocks = matchBlocks;
if (numberOfMatches == 0)
setNumberOfMatches(matchBlocks.length);
}
/**
* get the i-th match block
*
* @return match block
*/
public IMatchBlock getMatchBlock(int i) {
if (matchBlocks != null)
return matchBlocks[i];
else
return null;
}
/**
* read a read block from an RMA file
*
* @param uid seek to this position, unless -1
* @return readblock
*/
public static ReadBlockRMA2 read(RMA2Formatter rma2Formatter, long uid, boolean wantReadText, boolean wantMatchData,
boolean wantMatchText, float minScore, float maxExpected, TextStorageReader textReader, IInputReader dataIndexReader) throws IOException {
ReadBlockRMA2 readBlock = rma2Formatter.isWantLocationData() ? new ReadBlockFromBlast() : new ReadBlockRMA2();
if (uid == -1)
uid = dataIndexReader.getPosition();
else
dataIndexReader.seek(uid);
readBlock.setUId(uid);
ReadBlockRMA2Formatter readBlockFormatter = rma2Formatter.getReadBlockRMA2Formatter();
readBlockFormatter.read(dataIndexReader);
readBlock.setReadWeight(readBlockFormatter.hasReadWeight() ? readBlockFormatter.getReadWeight() : 1);
readBlock.setMateUId(readBlockFormatter.getMateUId());
readBlock.setMateType(readBlockFormatter.getMateType());
readBlock.setReadLength(readBlockFormatter.getReadLength());
readBlock.setComplexity(readBlockFormatter.getComplexity());
readBlock.setNumberOfMatches(readBlockFormatter.getNumberOfMatches());
// System.err.println("Number of matches: "+readBlock.getTotalMatches());
Location location = new Location(dataIndexReader.readChar(), dataIndexReader.readLong(), dataIndexReader.readInt());
if (wantReadText) {
Pair<String, String> headerSequence = textReader.getHeaderAndSequence(location);
if (rma2Formatter.isWantLocationData()) {
((ReadBlockFromBlast) readBlock).setTextLocation(location);
}
readBlock.setReadHeader(headerSequence.getFirst());
readBlock.setReadSequence(headerSequence.getSecond());
}
if (wantMatchData || wantMatchText) {
List<IMatchBlock> matchBlocks = new LinkedList<>();
int skippedMatches = 0;
for (int i = 0; i < readBlock.getNumberOfMatches(); i++) {
// System.err.println("Reading match " + i + " : " + dataIndexReader.getPosition());
MatchBlockRMA2 matchBlock = MatchBlockRMA2.read(rma2Formatter, -1, wantMatchData, wantMatchText, minScore, maxExpected, textReader, dataIndexReader);
if (matchBlock == null) // bitscore too low
{
skippedMatches = (readBlock.getNumberOfMatches() - (i + 1));
break;
}
matchBlocks.add(matchBlock);
}
readBlock.setMatchBlocks(matchBlocks.toArray(new IMatchBlock[0]));
if (skippedMatches > 0) {
// need to skip the rest of the bits:
dataIndexReader.skipBytes(skippedMatches * MatchBlockRMA2.getBytesInIndexFile(rma2Formatter.getMatchBlockRMA2Formatter()));
}
} else // skip all matches
dataIndexReader.skipBytes(readBlock.getNumberOfMatches() * MatchBlockRMA2.getBytesInIndexFile(rma2Formatter.getMatchBlockRMA2Formatter()));
return readBlock;
}
/**
* write a given read block to a RMA file
*
*/
public static void write(RMA2Formatter rma2Formatter, IReadBlockWithLocation readBlock, IOutputWriter dumpWriter, IOutputWriter indexWriter) throws IOException {
readBlock.setUId(indexWriter.getPosition()); // uid is position in index file
Location location = readBlock.getTextLocation();
if (dumpWriter != null) // need to write text to dump file and set location
{
long dataDumpPos = dumpWriter.getPosition();
if (readBlock.getReadSequence() != null)
dumpWriter.writeString(readBlock.getReadHeader() + "\n" + readBlock.getReadSequence());
else
dumpWriter.writeString(readBlock.getReadHeader() + "\n");
if (location == null) {
location = new Location();
readBlock.setTextLocation(location);
}
location.setFileId(0);
location.setPosition(dataDumpPos);
location.setSize((int) (dumpWriter.getPosition() - dataDumpPos));
}
// write read to dataindex:
// System.err.println("Writing read " + readBlock.getReadName() + ": " + indexWriter.getPosition());
// don't write uid!
ReadBlockRMA2Formatter readBlockFormatter = rma2Formatter.getReadBlockRMA2Formatter();
readBlockFormatter.setReadWeight(readBlock.getReadWeight());
readBlockFormatter.setMateUId(readBlock.getMateUId());
readBlockFormatter.setMateType(readBlock.getMateType());
readBlockFormatter.setReadLength(readBlock.getReadLength());
readBlockFormatter.setComplexity(readBlock.getComplexity());
readBlockFormatter.setNumberOfMatches(readBlock.getNumberOfMatches());
readBlockFormatter.write(indexWriter);
if (location != null) {
indexWriter.writeChar((char) location.getFileId());
indexWriter.writeLong(location.getPosition());
indexWriter.writeInt(location.getSize());
} else {
indexWriter.writeChar((char) -1);
indexWriter.writeLong(-1);
indexWriter.writeInt(-1);
}
for (int i = 0; i < readBlock.getNumberOfMatches(); i++) {
IMatchBlockWithLocation matchBlock = readBlock.getMatchBlock(i);
// System.err.println("Writing match " + i + ": " + dataIndexWriter.getPosition());
MatchBlockRMA2.write(rma2Formatter, matchBlock, dumpWriter, indexWriter);
}
//System.err.println(readBlock.toString());
}
public String toString() {
StringWriter w = new StringWriter();
w.write("Read uid: " + uid + "----------------------\n");
if (readHeader != null)
w.write("readHeader: " + readHeader + "\n");
if (readSequence != null)
w.write("readSequence: " + readSequence + "\n");
if (readWeight != 1)
w.write("readWeight: " + readWeight + "\n");
if (mateReadUId != 0)
w.write("mateReadUId: " + mateReadUId + "\n");
if (readLength != 0)
w.write("readLength: " + readLength + "\n");
if (complexity != 0)
w.write("complexity: " + complexity + "\n");
w.write("numberOfMatches: " + numberOfMatches + "\n");
for (IMatchBlock matchBlock : matchBlocks) w.write(matchBlock.toString());
return w.toString();
}
/**
* add the matchblocks to the readblock
*
*/
public void addMatchBlocks(SortedSet<IMatchBlock> matchBlocks) {
setMatchBlocks(matchBlocks.toArray(new IMatchBlock[0]));
}
}
| 12,278 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ClassificationBlockRMA2.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma2/ClassificationBlockRMA2.java | /*
* ClassificationBlockRMA2.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.rma2;
import jloda.util.Pair;
import megan.data.IClassificationBlock;
import megan.io.IInputReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* classification representation of RMA2
* Daniel Huson, 9.2010
*/
public class ClassificationBlockRMA2 implements IClassificationBlock {
private final String classificationName;
private final Map<Integer, Pair<Integer, Long>> id2SumAndPos = new HashMap<>();
private final Map<Integer, Integer> id2WeightedSum = new HashMap<>();
/**
* constructor
*
*/
public ClassificationBlockRMA2(String classificationName) {
this.classificationName = classificationName;
}
/**
* get the number associated with a key
*
* @return number
*/
public int getSum(Integer key) {
Pair<Integer, Long> pair = id2SumAndPos.get(key);
if (pair == null)
return 0;
else
return pair.getFirst();
}
/**
* get the number associated with a key
*
* @return number
*/
public float getWeightedSum(Integer key) {
Integer value = id2WeightedSum.get(key);
return Objects.requireNonNullElse(value, 0);
}
/**
* set the weighted sum
*
*/
public void setWeightedSum(Integer key, float sum) {
//throw new RuntimeException("Not implemented");
}
/**
* set the number associated with a key -> just set not written to disk
*
*/
public void setSum(Integer key, int sum) {
Pair<Integer, Long> pair = id2SumAndPos.get(key);
if (pair == null) {
pair = new Pair<>();
id2SumAndPos.put(key, pair);
}
pair.setFirst(sum);
}
public long getPos(Integer key) {
Pair<Integer, Long> pair = id2SumAndPos.get(key);
if (pair == null)
return 0;
else
return pair.getSecond();
}
public void setPos(Integer key, long pos) {
Pair<Integer, Long> pair = id2SumAndPos.get(key);
if (pair == null) {
pair = new Pair<>();
id2SumAndPos.put(key, pair);
}
pair.setSecond(pos);
}
private void setSumAndPos(Integer key, int sum, long pos) {
id2SumAndPos.put(key, new Pair<>(sum, pos));
}
/**
* get the name of this classification
*
* @return name
*/
public String getName() {
return classificationName;
}
/**
* set the name of this classification
*
*/
public void setName(String name) {
}
public Set<Integer> getKeySet() {
return id2SumAndPos.keySet();
}
/**
* read in the classification block from a file
*
*/
public void load(IInputReader r) throws IOException {
id2SumAndPos.clear();
try (r) {
int numberOfClasses = 0;
while (r.getPosition() < r.length()) {
int classId = r.readInt();
int count = r.readInt();
if (count < 0) {
setWeightedSum(classId, -count);
count = r.readInt();
} else
setWeightedSum(classId, count);
long pos = r.readLong();
setSumAndPos(classId, count, pos);
numberOfClasses++;
}
// System.err.println("Loaded:\n"+toString());
}
}
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append("Classification ").append(getName()).append(":\n");
for (Integer key : id2SumAndPos.keySet()) {
buf.append(key).append(" -> ").append(id2SumAndPos.get(key)).append("\n");
}
return buf.toString();
}
/**
* gets the count and pos for the given class in the given classification
*
* @return (count, pos) or null
*/
public static Pair<Integer, Long> getCountAndPos(RMA2File rma2File, String classification, int classId) throws IOException {
try (IInputReader r = rma2File.getClassificationIndexReader(classification)) {
int size = rma2File.getClassificationSize(classification);
for (int i = 0; i < size; i++) {
int id = r.readInt();
int count = r.readInt();
if (count < 0) {
count = r.readInt();
}
long pos = r.readLong();
if (id == classId)
return new Pair<>(count, pos);
}
return null;
}
}
/**
* gets the count and pos map for the classification
*
* @return (count, pos) or null
*/
public static Map<Integer, Pair<Integer, Long>> getCountAndPos(RMA2File rma2File, String classification) throws IOException {
Map<Integer, Pair<Integer, Long>> map = new HashMap<>();
try (IInputReader r = rma2File.getClassificationIndexReader(classification)) {
int size = rma2File.getClassificationSize(classification);
for (int i = 0; i < size; i++) {
int id = r.readInt();
int count = r.readInt();
if (count < 0) {
count = r.readInt();
}
long pos = r.readLong();
map.put(id, new Pair<>(count, pos));
}
}
return map;
}
}
| 6,313 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ReadBlockGetterRMA2.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma2/ReadBlockGetterRMA2.java | /*
* ReadBlockGetterRMA2.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.rma2;
import jloda.util.Basic;
import megan.data.IReadBlock;
import megan.data.IReadBlockGetter;
import megan.data.TextStorageReader;
import megan.io.IInputReader;
import java.io.File;
import java.io.IOException;
/**
* RMA2 implementation of read block accessor
* Daniel Huson, 10.2010
*/
public class ReadBlockGetterRMA2 implements IReadBlockGetter {
private final float minScore;
private final float maxExpected;
private final TextStorageReader textStorageReader;
private final IInputReader dataIndexReader;
private final RMA2Formatter rma2Formatter;
private final boolean wantReadText;
private final boolean wantMatchText;
private final boolean wantMatchData;
private final long numberOfReads;
/**
* constructor
*
*/
public ReadBlockGetterRMA2(File file, float minScore, float maxExpected, boolean wantReadText, boolean wantMatchData, boolean wantMatchText) throws IOException {
this.minScore = minScore;
this.maxExpected = maxExpected;
this.wantReadText = wantReadText;
this.wantMatchText = wantMatchText;
this.wantMatchData = wantMatchData;
RMA2File rma2File = new RMA2File(file);
dataIndexReader = rma2File.getDataIndexReader();
InfoSection infoSection = rma2File.loadInfoSection();
rma2Formatter = infoSection.getRMA2Formatter();
if (wantReadText || wantMatchText) {
textStorageReader = new TextStorageReader(infoSection.getLocationManager(file));
} else
textStorageReader = null;
numberOfReads = rma2File.getNumberOfReads();
}
/**
* gets the read block associated with the given uid
*
* @return read block or null
*/
public IReadBlock getReadBlock(long uid) throws IOException {
return ReadBlockRMA2.read(rma2Formatter, uid, wantReadText, wantMatchData, wantMatchText, minScore, maxExpected, textStorageReader, dataIndexReader);
}
/**
* closes the accessor
*
*/
public void close() {
if (textStorageReader != null)
textStorageReader.closeAllFiles();
if (dataIndexReader != null)
try {
dataIndexReader.close();
} catch (IOException e) {
Basic.caught(e);
}
}
/**
* get total number of reads
*
* @return total number of reads
*/
@Override
public long getCount() {
return numberOfReads;
}
}
| 3,320 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ReadBlockIteratorRMA2.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma2/ReadBlockIteratorRMA2.java | /*
* ReadBlockIteratorRMA2.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.rma2;
import jloda.util.Basic;
import jloda.util.Pair;
import megan.data.IReadBlock;
import megan.data.IReadBlockIterator;
import megan.data.TextStorageReader;
import megan.io.IInputReader;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* readblock getLetterCodeIterator over all reads in a given class
* Daniel Huson, 9.2010
*/
public class ReadBlockIteratorRMA2 implements IReadBlockIterator {
private final TextStorageReader textStorageReader;
private final IInputReader dataIndexReader;
private final IInputReader classDumpReader;
private final RMA2Formatter rma2Formatter;
private final boolean wantReadText;
private final boolean wantMatchData;
private final boolean wantMatchText;
private final float minScore;
private final float maxExpected;
private boolean error = false;
private final List<Pair<Integer, Long>> classes = new LinkedList<>();
private Pair<Integer, Long> currentClass;
private int currentCount = 0;
private long totalReads;
private long countReads = 0;
/**
* constructor
*
*/
public ReadBlockIteratorRMA2(String classification, Collection<Integer> classIds, boolean wantReadText, boolean wantMatchData, boolean wantMatchText, float minScore, float maxExpected, File file) throws IOException {
this.wantReadText = wantReadText;
this.wantMatchData = wantMatchData;
this.wantMatchText = wantMatchText;
this.minScore = minScore;
this.maxExpected = maxExpected;
RMA2File rma2File = new RMA2File(file);
dataIndexReader = rma2File.getDataIndexReader();
InfoSection infoSection = rma2File.loadInfoSection();
rma2Formatter = infoSection.getRMA2Formatter();
if (wantReadText || wantMatchText)
textStorageReader = new TextStorageReader(infoSection.getLocationManager(file));
else
textStorageReader = null;
Map<Integer, Pair<Integer, Long>> map = ClassificationBlockRMA2.getCountAndPos(rma2File, classification);
for (Integer classId : classIds) {
Pair<Integer, Long> pair = map.get(classId);
if (pair != null && pair.getSecond() >= 0) {
classes.add(pair);
totalReads += pair.getFirst();
}
}
// if(pair!=null)
// System.err.println("classId: "+classId+" size: "+pair.getFirst()+" dumpPos: "+pair.getSecond());
if (totalReads > 0) {
currentClass = classes.remove(0);
currentCount = 0;
classDumpReader = rma2File.getClassificationDumpReader(classification);
classDumpReader.seek(currentClass.getSecond());
} else
classDumpReader = null;
}
/**
* get a string reporting stats
*
* @return stats string
*/
public String getStats() {
return "Reads: " + countReads;
}
/**
* close associated file or database
*/
public void close() {
try {
if (textStorageReader != null)
textStorageReader.closeAllFiles();
if (dataIndexReader != null)
dataIndexReader.close();
if (classDumpReader != null)
classDumpReader.close();
} catch (IOException e) {
Basic.caught(e);
}
}
/**
* gets the maximum progress value
*
* @return maximum progress value
*/
public long getMaximumProgress() {
return totalReads;
}
/**
* gets the current progress value
*
* @return current progress value
*/
public long getProgress() {
return countReads;
}
/**
* Returns <tt>true</tt> if the iteration has more elements. (In other
* words, returns <tt>true</tt> if <tt>next</tt> would return an element
* rather than throwing an exception.)
*
* @return <tt>true</tt> if the getLetterCodeIterator has more elements.
*/
public boolean hasNext() {
if (error || currentClass == null)
return false;
if (currentCount < currentClass.getFirst())
return true;
currentClass = null;
while (classes.size() > 0) {
currentCount = 0;
Pair<Integer, Long> next = classes.remove(0);
if (next != null && next.getFirst() > 0 && next.getSecond() >= 0) {
try {
classDumpReader.seek(next.getSecond());
} catch (IOException e) {
Basic.caught(e);
return false;
}
currentClass = next;
return true;
}
}
return false;
}
/**
* Returns the next element in the iteration.
*
* @return the next element in the iteration.
* @throws java.util.NoSuchElementException iteration has no more elements.
*/
public IReadBlock next() {
try {
currentCount++;
countReads++;
return ReadBlockRMA2.read(rma2Formatter, classDumpReader.readLong(), wantReadText, wantMatchData, wantMatchText, minScore, maxExpected, textStorageReader, dataIndexReader);
} catch (IOException e) {
Basic.caught(e);
error = true;
return null;
}
}
/**
* not implemented
*/
public void remove() {
}
}
| 6,357 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ClassReadIdIteratorRMA2.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma2/ClassReadIdIteratorRMA2.java | /*
* ClassReadIdIteratorRMA2.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.rma2;
import jloda.util.Basic;
import jloda.util.Pair;
import megan.io.IInputReader;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* readblock getLetterCodeIterator over all reads in a given class
* Daniel Huson, 9.2010
*/
public class ClassReadIdIteratorRMA2 implements Iterator<Pair<Integer, List<Long>>> {
private final IInputReader classDumpReader;
private final ClassificationBlockRMA2 classificationBlockRMA2;
private final Iterator<Integer> iterator; // keys
private final int numberOfClasses;
private int classesProcessed = 0;
private boolean error = false;
/**
* constructor
*
*/
public ClassReadIdIteratorRMA2(String classification, File file) throws IOException {
RMA2File rma2File = new RMA2File(file);
classificationBlockRMA2 = new ClassificationBlockRMA2(classification);
classificationBlockRMA2.load(rma2File.getClassificationIndexReader(classification));
numberOfClasses = classificationBlockRMA2.getKeySet().size();
iterator = classificationBlockRMA2.getKeySet().iterator();
classDumpReader = rma2File.getClassificationDumpReader(classification);
}
/**
* get a string reporting stats
*
* @return stats string
*/
public String getStats() {
return "Classes: " + numberOfClasses;
}
/**
* close associated file or database
*/
public void close() throws IOException {
if (classDumpReader != null)
classDumpReader.close();
}
/**
* gets the maximum progress value
*
* @return maximum progress value
*/
public int getMaximumProgress() {
return numberOfClasses;
}
/**
* gets the current progress value
*
* @return current progress value
*/
public int getProgress() {
return classesProcessed;
}
/**
* Returns <tt>true</tt> if the iteration has more elements. (In other
* words, returns <tt>true</tt> if <tt>next</tt> would return an element
* rather than throwing an exception.)
*
* @return <tt>true</tt> if the getLetterCodeIterator has more elements.
*/
public boolean hasNext() {
return !error && iterator.hasNext();
}
/**
* Returns the next element in the iteration.
*
* @return the next element in the iteration.
* @throws java.util.NoSuchElementException iteration has no more elements.
*/
public Pair<Integer, List<Long>> next() {
try {
classesProcessed++;
Integer key = iterator.next();
long pos = classificationBlockRMA2.getPos(key);
int count = classificationBlockRMA2.getSum(key);
classDumpReader.seek(pos);
List<Long> list = new LinkedList<>();
for (int i = 0; i < count; i++)
list.add(classDumpReader.readLong());
return new Pair<>(key, list);
} catch (Exception e) {
Basic.caught(e);
error = true;
return null;
}
}
/**
* not implemented
*/
public void remove() {
}
}
| 4,065 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.