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 |
---|---|---|---|---|---|---|---|---|---|---|---|
ChartColorManager.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/ChartColorManager.java | /*
* ChartColorManager.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart;
import jloda.swing.util.ColorTable;
import jloda.swing.util.ColorTableManager;
import jloda.swing.util.ProgramProperties;
import jloda.util.Basic;
import jloda.util.NumberUtils;
import java.awt.*;
import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* default chart colors, based on hash code of label
* Daniel Huson, 5.2012
*/
public class ChartColorManager {
public static final String SAMPLE_ID = "#SampleID";
public static ChartColorManager programChartColorManager;
private final Map<String, Color> class2color = new HashMap<>(); // cache changes
private final Map<String, Color> attributeState2color = new HashMap<>(); // cache changes
private ColorTable colorTable;
private ColorTable colorTableHeatMap;
private boolean colorByPosition;
private ColorGetter seriesOverrideColorGetter = null;
private final Map<String,Integer> sample2Position=new HashMap<>();
private final Map<String, Integer> class2position = new HashMap<>(); // maps classes to their position in the order of things
private final Map<String, Integer> attributeState2position = new HashMap<>(); // maps attributes to their position in the order of things
/**
* constructor
*
*/
public ChartColorManager(ColorTable colorTable) {
this.colorTable = colorTable;
setColorByPosition(ProgramProperties.get("ColorByPosition", false));
}
/**
* initial the program-wide color table
*/
public static void initialize() {
if (programChartColorManager == null) {
programChartColorManager = new ChartColorManager(ColorTableManager.getDefaultColorTable());
programChartColorManager.setHeatMapTable(ColorTableManager.getDefaultColorTableHeatMap().getName());
programChartColorManager.loadColorEdits(ProgramProperties.get("ColorMap", ""));
}
}
/**
* save document edits, if they exist
*/
public static void store() {
if (programChartColorManager != null) {
ProgramProperties.put("ColorMap", programChartColorManager.getColorEdits());
}
}
/**
* get color for data set
*
* @return color
*/
public Color getSampleColor(String sample) {
Color color = null;
if (seriesOverrideColorGetter != null)
color = seriesOverrideColorGetter.get(sample);
if (color == null)
color = getAttributeStateColor(SAMPLE_ID, sample);
if (isColorByPosition()) {
Integer position = sample2Position.get(sample);
if (position != null) {
color=getColorTable().get(position);
}
}
if (color == null) {
if (sample == null || sample.equals("GRAY"))
color = Color.GRAY;
else {
int key = sample.hashCode();
color = colorTable.get(key);
}
}
return color;
}
/**
* get color for data set
*
* @return color
*/
public Color getSampleColorWithAlpha(String sample, int alpha) {
Color color = getSampleColor(sample);
if (color == null)
return null;
if (color.getAlpha() == alpha)
return color;
else
return new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha);
}
/**
* set the color for a sample
*
*/
public void setSampleColor(String sample, Color color) {
setAttributeStateColor(SAMPLE_ID, sample, color);
}
public void setSampleColorPositions(Collection<String> samples) {
sample2Position.clear();
int pos = 0;
for (String name : samples) {
if (!sample2Position.containsKey(name))
sample2Position.put(name, pos++);
}
}
/**
* get the color fo a specific chart and class
*
* @return color
*/
public Color getClassColor(String className) {
if (className == null)
return null;
if (className.equals("GRAY"))
return Color.GRAY;
if (class2color.containsKey(className))
return class2color.get(className);
if (isColorByPosition()) {
Integer position = class2position.get(className);
if (position == null) {
position = class2position.size();
class2position.put(className, position);
}
return colorTable.get(position);
} else {
return colorTable.get(className.hashCode());
}
}
/**
* get the color fo a specific chart and class
*
* @return color
*/
public Color getClassColor(String className, int alpha) {
Color color = getClassColor(className);
if (color == null)
return null;
if (color.getAlpha() == alpha)
return color;
else
return new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha);
}
/**
* set the color for a class
*
*/
public void setClassColor(String className, Color color) {
class2color.put(className, color);
}
public void setClassColorPositions(Collection<String> classNames) {
class2position.clear();
int pos = 0;
for (String name : classNames) {
if (!class2position.containsKey(name))
class2position.put(name, pos++);
}
}
public void setAttributeStateColorPositions(String attributeName, Collection<String> states) {
attributeState2position.clear();
int pos = 0;
for (String state : states) {
String attributeState = attributeName + "::" + state;
if (!attributeState2position.containsKey(attributeState))
attributeState2position.put(attributeState, pos++);
}
}
/**
* get the color fo a specific chart and attribute
*
* @return color
*/
public Color getAttributeStateColor(String attributeName, Object state) {
if (state == null || state.toString().equals("NA"))
return Color.GRAY;
final String attributeState = attributeName + "::" + state;
if (attributeState2color.containsKey(attributeState))
return attributeState2color.get(attributeState);
if (isColorByPosition()) {
Integer position = attributeState2position.get(attributeState);
if (position == null) {
position = attributeState2position.size();
attributeState2position.put(attributeState, position);
}
if (attributeState2position.size() >= colorTable.size()) {
return colorTable.get(position);
} else { // scale to color table
int index = (position * colorTable.size()) / attributeState2position.size();
//System.err.println("Position: "+position+" -> "+index);
return colorTable.get(index);
}
} else {
return colorTable.get(attributeState.hashCode());
}
}
/**
* set the color for an attribute
*
*/
public void setAttributeStateColor(String attributeName, String state, Color color) {
attributeState2color.put(attributeName + "::" + state, color);
}
/**
* are the any changed colors?
*
* @return true, if has changed colors
*/
public boolean hasChangedColors() {
return attributeState2color.size() > 0 || class2color.size() > 0;
}
/**
* clear all changed colors
*/
public void clearChangedColors() {
attributeState2color.clear();
class2color.clear();
}
/**
* load color edits
*
*/
public void loadColorEdits(String colorEdits) {
if (colorEdits != null && colorEdits.length() > 0) {
read(colorEdits.split(";"));
}
}
public String getColorEdits() {
try (StringWriter w = new StringWriter()) {
write(w, ";");
return w.toString();
} catch (IOException e) {
return null;
}
}
/**
* write color table
*
*/
public void write(Writer w) throws IOException {
write(w, "\n");
}
/**
* write color table
*
*/
private void write(Writer w, String separator) throws IOException {
for (Map.Entry<String, Color> entry : class2color.entrySet()) {
Color color = entry.getValue();
if (color != null)
w.write("C" + "\t" + entry.getKey() + "\t" + color.getRGB() + (color.getAlpha() < 255 ? "\t" + color.getAlpha() : "") + separator);
}
for (Map.Entry<String, Color> entry : attributeState2color.entrySet()) {
Color color = entry.getValue();
if (color != null)
w.write("A" + "\t" + entry.getKey() + "\t" + color.getRGB() + (color.getAlpha() < 255 ? "\t" + color.getAlpha() : "") + separator);
}
}
/**
* read color table
*
*/
public void read(Reader r0) throws IOException {
String[] tokens = Basic.getLines(r0);
read(tokens);
}
/**
* read color table
*
*/
private void read(String[] lines) {
for (String aLine : lines) {
aLine = aLine.trim();
if (aLine.length() > 0 && !aLine.startsWith("#")) {
String[] tokens = aLine.split("\t");
if (tokens.length >= 3 && NumberUtils.isInteger(tokens[2])) {
switch (tokens[0]) {
case "C" -> {
String className = tokens[1];
Color color = new Color(Integer.parseInt(tokens[2]));
if (tokens.length >= 4) {
int alpha = Integer.parseInt(tokens[3]);
color = new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha);
}
class2color.put(className, color);
}
case "A" -> {
String attribute = tokens[1];
Color color = new Color(Integer.parseInt(tokens[2]));
if (tokens.length >= 4) {
int alpha = Integer.parseInt(tokens[3]);
color = new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha);
}
attributeState2color.put(attribute, color);
}
}
}
}
}
}
/**
* gets a series color getter that overrides MEGAN-wide colors
*
* @return color getter
*/
public ColorGetter getSeriesOverrideColorGetter() {
return seriesOverrideColorGetter;
}
/**
* sets a series color getter that overrides MEGAN-wide colors. Is used to implement document-specific colors
*
*/
public void setSeriesOverrideColorGetter(ColorGetter seriesOverrideColorGetter) {
this.seriesOverrideColorGetter = seriesOverrideColorGetter;
}
public ColorGetter getSeriesColorGetter() {
return this::getSampleColor;
}
public ColorGetter getClassColorGetter() {
return this::getClassColor;
}
public ColorGetter getAttributeColorGetter() {
return label -> Color.WHITE;
}
public String getColorTableName() {
return colorTable.getName();
}
public interface ColorGetter {
Color get(String label);
}
public void setColorTable(String name) {
this.colorTable = ColorTableManager.getColorTable(name);
}
public void setColorTable(String name, boolean colorByPosition) {
this.colorTable = ColorTableManager.getColorTable(name);
setColorByPosition(colorByPosition);
}
public ColorTable getColorTable() {
return colorTable;
}
public boolean isColorByPosition() {
return colorByPosition;
}
public void setColorByPosition(boolean colorByPosition) {
this.colorByPosition = colorByPosition;
ProgramProperties.put("ColorByPosition", colorByPosition);
}
public void setHeatMapTable(String name) {
this.colorTableHeatMap = ColorTableManager.getColorTableHeatMap(name);
}
public ColorTable getHeatMapTable() {
return colorTableHeatMap;
}
public boolean isUsingProgramColors() {
return this == programChartColorManager;
}
}
| 13,593 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
TaxaChart.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/TaxaChart.java | /*
* TaxaChart.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart;
import jloda.graph.Node;
import jloda.graph.NodeData;
import jloda.graph.NodeSet;
import jloda.swing.util.ProgramProperties;
import jloda.util.Basic;
import jloda.util.CanceledException;
import megan.chart.data.DefaultChartData;
import megan.chart.data.IChartData;
import megan.chart.drawers.BarChartDrawer;
import megan.chart.gui.ChartViewer;
import megan.commands.OpenNCBIWebPageCommand;
import megan.commands.OpenWebPageCommand;
import megan.core.Director;
import megan.core.Document;
import megan.dialogs.input.InputDialog;
import megan.main.MeganProperties;
import megan.viewer.MainViewer;
import megan.viewer.TaxonomicLevels;
import megan.viewer.TaxonomyData;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.LinkedList;
/**
* a taxa chart
* Daniel Huson, 6.2012
*/
public class TaxaChart extends ChartViewer {
private NodeSet syncedNodes;
private boolean inSync = false;
private String colorByRank = null;
private final MainViewer mainViewer;
/**
* constructor
*
*/
public TaxaChart(final Director dir) {
super(dir.getMainViewer(), dir, dir.getDocument().getSampleLabelGetter(), new DefaultChartData(), ProgramProperties.isUseGUI());
this.mainViewer = dir.getMainViewer();
MeganProperties.addPropertiesListListener(getJMenuBar().getRecentFilesListener());
MeganProperties.notifyListChange(ProgramProperties.RECENTFILES);
getToolbar().addSeparator(new Dimension(5, 10));
getToolbar().add(getCommandManager().getButton("Sync"));
chooseDrawer(BarChartDrawer.NAME);
setChartTitle("Taxonomy profile for " + dir.getDocument().getTitle());
IChartData chartData = (IChartData) getChartData();
String name = dir.getDocument().getTitle();
if (name.length() > 20)
chartData.setDataSetName(name.substring(0, 20));
else
getChartData().setDataSetName(name);
setWindowTitle("Taxonomy Chart");
chartData.setSeriesLabel("Samples");
chartData.setClassesLabel("Taxa");
chartData.setCountsLabel(dir.getDocument().getReadAssignmentMode().getDisplayLabel());
setClassLabelAngle(Math.PI / 4);
//setShowLegend(true);
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent event) {
InputDialog inputDialog = InputDialog.getInstance();
if (inputDialog != null)
inputDialog.setViewer(dir, TaxaChart.this);
}
});
getClassesList().getPopupMenu().addSeparator();
{
final OpenWebPageCommand command = new OpenWebPageCommand();
command.setViewer(this);
Action action = new AbstractAction(OpenWebPageCommand.NAME) {
public void actionPerformed(ActionEvent actionEvent) {
java.util.Collection<String> selectedIds = getClassesList().getSelectedLabels();
if (selectedIds.size() > 0) {
if (selectedIds.size() >= 5 && JOptionPane.showConfirmDialog(getFrame(), "Do you really want to open " + selectedIds.size() +
" windows in your browser?", "Confirmation - MEGAN", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon()) != JOptionPane.YES_OPTION)
return;
for (String label : selectedIds) {
try {
command.apply("show webPage classification='Taxonomy' id='" + label + "';");
} catch (Exception e) {
Basic.caught(e);
}
}
}
}
};
action.putValue(AbstractAction.SMALL_ICON, command.getIcon());
getClassesList().getPopupMenu().add(action);
}
{
final OpenNCBIWebPageCommand command = new OpenNCBIWebPageCommand();
command.setViewer(this);
Action action = new AbstractAction(OpenNCBIWebPageCommand.NAME) {
public void actionPerformed(ActionEvent actionEvent) {
java.util.Collection<String> selectedIds = getClassesList().getSelectedLabels();
if (selectedIds.size() > 0) {
if (selectedIds.size() >= 5 && JOptionPane.showConfirmDialog(getFrame(), "Do you really want to open " + selectedIds.size() +
" windows in your browser?", "Confirmation - MEGAN", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon()) != JOptionPane.YES_OPTION)
return;
for (String label : selectedIds) {
try {
command.apply("show webPage taxon='" + label + "';");
} catch (Exception e) {
Basic.caught(e);
}
}
}
}
};
action.putValue(AbstractAction.SMALL_ICON, command.getIcon());
getClassesList().getPopupMenu().add(action);
}
try {
sync();
} catch (CanceledException e) {
Basic.caught(e);
}
int[] geometry = ProgramProperties.get(MeganProperties.TAXA_CHART_WINDOW_GEOMETRY, new int[]{100, 100, 800, 600});
setSize(geometry[2], geometry[3]);
getFrame().addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
ProgramProperties.put(MeganProperties.TAXA_CHART_WINDOW_GEOMETRY, new int[]{
getLocation().x, getLocation().y, getSize().width, getSize().height});
}
});
setVisible(true);
}
/**
* synchronize chart to reflect latest user selection in taxon chart
*/
public void sync() throws CanceledException {
if (!inSync) {
inSync = true;
final IChartData chartData = (IChartData) getChartData();
chartData.clear();
final Document doc = dir.getDocument();
setChartTitle("Taxonomy profile for " + doc.getTitle());
int numberOfSamples = doc.getNumberOfSamples();
if (numberOfSamples > 0) {
final MainViewer mainViewer = dir.getMainViewer();
if (mainViewer.getSelectedNodes().size() == 0) {
mainViewer.selectAllLeaves();
if (mainViewer.getPOWEREDBY() != null)
setChartTitle(getChartTitle() + " (rank=" + mainViewer.getPOWEREDBY() + ")");
}
chartData.setAllSeries(doc.getSampleNames());
final String[] names = doc.getSampleNames().toArray(new String[0]);
final float[] totalSizes = new float[doc.getSampleNames().size()];
syncedNodes = mainViewer.getSelectedNodes();
final LinkedList<String> taxonNames = new LinkedList<>();
for (Node v = mainViewer.getGraph().getFirstNode(); v != null; v = v.getNext()) {
if (syncedNodes.contains(v)) {
final String taxonName = TaxonomyData.getName2IdMap().get((Integer) v.getInfo());
taxonNames.add(taxonName);
if (numberOfSamples == 1) {
if (v.getOutDegree() == 0)
chartData.putValue(names[0], taxonName, ((NodeData) v.getData()).getCountSummarized());
else
chartData.putValue(names[0], taxonName, ((NodeData) v.getData()).getCountAssigned());
} else {
float[] values;
if (v.getOutDegree() == 0)
values = ((NodeData) v.getData()).getSummarized();
else
values = ((NodeData) v.getData()).getAssigned();
for (int i = 0; i < names.length; i++) {
chartData.putValue(names[i], taxonName, values[i]);
}
}
}
float[] values;
if (v.getOutDegree() == 0)
values = ((NodeData) v.getData()).getSummarized();
else
values = ((NodeData) v.getData()).getAssigned();
for (int i = 0; i < names.length; i++) {
totalSizes[i] += values[i];
}
}
chartData.setAllSeriesTotalSizes(totalSizes);
chartData.setClassNames(taxonNames);
}
updateColorByRank();
chartData.setTree(mainViewer.getInducedTree(TaxonomyData.getName2IdMap().getId2Name(), mainViewer.getSelectedNodes()));
super.sync();
updateView(Director.ALL);
inSync = false;
}
}
/**
* ask view to destroy itself
*/
public void destroyView() throws CanceledException {
MeganProperties.removePropertiesListListener(getJMenuBar().getRecentFilesListener());
super.destroyView();
}
public String getColorByRank() {
return colorByRank;
}
public void setColorByRank(String colorByRank) {
this.colorByRank = colorByRank;
}
public void updateColorByRank() {
String rank = getColorByRank();
getClass2HigherClassMapper().clear();
if (rank == null)
return;
int rankId = TaxonomicLevels.getId(rank);
if (rank.equals("None") || rankId == 0) {
getStatusbar().setText2("");
} else {
getStatusbar().setText2("Colored by rank=" + rank);
if (syncedNodes != null) {
for (Node v : syncedNodes) {
Node w = v;
String taxName = TaxonomyData.getName2IdMap().get((Integer) v.getInfo());
boolean ok = false;
while (true) {
Integer taxId = (Integer) w.getInfo();
int taxLevel = TaxonomyData.getTaxonomicRank(taxId);
if (taxLevel == rankId) {
getClass2HigherClassMapper().put(taxName, TaxonomyData.getName2IdMap().get(taxId));
ok = true;
break;
}
if (w.getInDegree() > 0)
w = w.getFirstInEdge().getSource();
else
break;
}
if (!ok)
getClass2HigherClassMapper().put(TaxonomyData.getName2IdMap().get((Integer) v.getInfo()), "GRAY"); // will be shown in gray
}
}
}
}
public NodeSet getSyncedNodes() {
return syncedNodes;
}
/**
* get name for this type of viewer
*
* @return name
*/
public String getClassName() {
return "TaxaChart";
}
}
| 12,353 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
RarefactionPlot.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/RarefactionPlot.java | /*
* RarefactionPlot.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart;
import jloda.graph.Edge;
import jloda.graph.Node;
import jloda.graph.NodeData;
import jloda.graph.NodeIntArray;
import jloda.phylo.PhyloTree;
import jloda.swing.util.ProgramProperties;
import jloda.util.CanceledException;
import jloda.util.Pair;
import jloda.util.progress.ProgressListener;
import megan.chart.data.DefaultPlot2DData;
import megan.chart.data.IPlot2DData;
import megan.chart.drawers.Plot2DDrawer;
import megan.chart.gui.ChartViewer;
import megan.core.Director;
import megan.core.Document;
import megan.dialogs.input.InputDialog;
import megan.main.MeganProperties;
import megan.viewer.ClassificationViewer;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.*;
/**
* Rarefaction plot
* Daniel Huson, 7.2012, 4.2015
*/
public class RarefactionPlot extends ChartViewer {
private final Document doc;
private final String cName;
private final ClassificationViewer viewer;
private boolean inSync = false;
/**
* constructor
*
*/
public RarefactionPlot(final Director dir, ClassificationViewer parent) throws CanceledException {
super(parent, dir, dir.getDocument().getSampleLabelGetter(), new DefaultPlot2DData(), ProgramProperties.isUseGUI());
viewer = parent;
this.cName = parent.getClassName();
doc = dir.getDocument();
getToolbar().addSeparator(new Dimension(5, 10));
getToolbar().add(getCommandManager().getButton("Sync"));
MeganProperties.addPropertiesListListener(getJMenuBar().getRecentFilesListener());
MeganProperties.notifyListChange(ProgramProperties.RECENTFILES);
chooseDrawer(Plot2DDrawer.NAME);
setChartTitle(cName + " rarefaction plot for " + doc.getTitle());
setWindowTitle(cName + " rarefaction");
getChartDrawer().setClassLabelAngle(0);
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent event) {
InputDialog inputDialog = InputDialog.getInstance();
if (inputDialog != null)
inputDialog.setViewer(dir, RarefactionPlot.this);
}
});
sync();
int[] geometry = ProgramProperties.get(cName + "RareFactionChartGeometry", new int[]{100, 100, 800, 600});
setSize(geometry[2], geometry[3]);
getFrame().addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
ProgramProperties.put(cName + "RareFactionChartGeometry", new int[]{
getLocation().x, getLocation().y, getSize().width, getSize().height});
}
});
}
/**
* synchronize chart to reflect latest user selection in taxon chart
*/
public void sync() throws CanceledException {
if (!inSync) {
inSync = true;
setChartTitle(cName + " rarefaction plot for " + doc.getTitle());
for (String name : doc.getSampleNames()) {
((Plot2DDrawer) getChartDrawer()).setShowLines(name, true);
((Plot2DDrawer) getChartDrawer()).setShowDots(name, true);
}
final Map<String, Collection<Pair<Number, Number>>> name2counts = computeCounts(doc, 1, viewer, doc.getProgressListener());
final IPlot2DData chartData = (IPlot2DData) getChartData();
chartData.clear();
chartData.setDataSetName(doc.getTitle());
for (String name : doc.getSampleNames())
chartData.setDataForSeries(name, name2counts.get(name));
getChartData().setSeriesLabel(doc.getReadAssignmentMode().getDisplayLabel() + " sampled from leaves");
getChartData().setCountsLabel("Number of leaves in " + cName + " tree");
super.sync();
inSync = false;
}
}
/**
* ask view to destroy itself
*/
public void destroyView() throws CanceledException {
MeganProperties.removePropertiesListListener(getJMenuBar().getRecentFilesListener());
super.destroyView();
}
/**
* do rarefaction analysis for parent
*
* @return values for 10-100 percent, for each dataset in the document
*/
private static Map<String, Collection<Pair<Number, Number>>> computeCounts(Document doc, int threshold, ClassificationViewer viewer, ProgressListener progressListener) throws CanceledException {
final String cName = viewer.getClassName();
final int numberOfPoints = ProgramProperties.get("NumberRareFactionDataPoints", 20);
final int numberOfReplicates = ProgramProperties.get("NumberRareFactionReplicates", 10);
progressListener.setTasks(cName + " rarefaction analysis", "Sampling from current leaves");
progressListener.setMaximum((long) numberOfPoints * numberOfReplicates * doc.getNumberOfSamples());
progressListener.setProgress(0);
Random rand = new Random(666);
final PhyloTree tree = viewer.getTree();
Map<String, Collection<Pair<Number, Number>>> name2counts = new HashMap<>();
for (int pid = 0; pid < doc.getNumberOfSamples(); pid++) {
NodeIntArray numbering = new NodeIntArray(tree);
int numberOfReads = computeCountRec(pid, tree.getRoot(), viewer, 0, numbering);
progressListener.incrementProgress();
Vector<Float> counts = new Vector<>();
counts.add(0f);
NodeIntArray[] node2count = new NodeIntArray[numberOfReplicates];
for (int r = 0; r < numberOfReplicates; r++)
node2count[r] = new NodeIntArray(tree);
Set<Node> nodes = new HashSet<>();
int batchSize = numberOfReads / numberOfPoints;
for (int p = 1; p <= numberOfPoints; p++) {
for (int r = 0; r < numberOfReplicates; r++) {
for (int i = 1; i <= batchSize; i++) {
int which = rand.nextInt(numberOfReads);
Node v = getIdRec(tree.getRoot(), which, numbering);
nodes.add(v);
node2count[r].set(v, node2count[r].getInt(v) + 1);
}
progressListener.incrementProgress();
}
int count = 0;
for (int r = 0; r < numberOfReplicates; r++) {
for (Node v : nodes) {
if (node2count[r].getInt(v) >= threshold)
count++;
}
}
counts.add((float) count / (float) numberOfReplicates);
}
ArrayList<Pair<Number, Number>> list = new ArrayList<>(counts.size());
int sampleSize = 0;
for (int p = 0; p <= numberOfPoints; p++) {
list.add(new Pair<>(sampleSize, counts.get(p)));
sampleSize += batchSize;
}
name2counts.put(doc.getSampleNames().get(pid), list);
}
return name2counts;
}
/**
* each node is numbered by the count of reads that come before it
*
* @return count for node
*/
private static int computeCountRec(int pid, Node v, ClassificationViewer viewer, int top, NodeIntArray numbering) {
for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) {
top = computeCountRec(pid, e.getTarget(), viewer, top, numbering);
}
if (v.getOutDegree() == 0) // sample from leaves only
{
NodeData data = viewer.getNodeData(v);
if (data != null && data.getSummarized() != null)
top += data.getSummarized()[pid];
}
numbering.set(v, top);
return top;
}
/**
* gets the node hit
*
*/
private static Node getIdRec(Node v, int which, NodeIntArray counts) {
for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) {
Node w = e.getTarget();
if (which <= counts.getInt(w)) {
return getIdRec(w, which, counts);
}
}
return v;
}
/**
* get name for this type of parent
*
* @return name
*/
public String getClassName() {
return getClassName(cName);
}
public static String getClassName(String cName) {
return cName + "RarefactionPlot";
}
}
| 9,349 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
FViewerChart.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/FViewerChart.java | /*
* FViewerChart.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart;
import jloda.swing.util.ProgramProperties;
import jloda.util.Basic;
import jloda.util.CanceledException;
import megan.chart.data.DefaultChartData;
import megan.chart.data.IChartData;
import megan.chart.drawers.BarChartDrawer;
import megan.chart.gui.ChartViewer;
import megan.commands.OpenWebPageCommand;
import megan.core.Director;
import megan.core.Document;
import megan.dialogs.input.InputDialog;
import megan.main.MeganProperties;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.LinkedList;
/**
* a Viewer chart
* Daniel Huson, 6.2012, 4.2015
*/
public class FViewerChart extends ChartViewer {
private boolean inSync = false;
private final String cName;
private final ClassificationViewer viewer;
/**
* constructor
*
*/
public FViewerChart(final Director dir, ClassificationViewer parent) {
super(parent, dir, dir.getDocument().getSampleLabelGetter(), new DefaultChartData(), ProgramProperties.isUseGUI());
viewer = parent;
cName = parent.getClassName();
MeganProperties.addPropertiesListListener(getJMenuBar().getRecentFilesListener());
MeganProperties.notifyListChange(ProgramProperties.RECENTFILES);
getToolbar().addSeparator(new Dimension(5, 10));
getToolbar().add(getCommandManager().getButton("Sync"));
chooseDrawer(BarChartDrawer.NAME);
setChartTitle(parent.getClassName() + " profile for " + dir.getDocument().getTitle());
IChartData chartData = (IChartData) getChartData();
String name = dir.getDocument().getTitle();
if (name.length() > 20) {
chartData.setDataSetName(name.substring(0, 20));
name = name.substring(0, 20) + "...";
}
getChartData().setDataSetName(name);
setWindowTitle(cName + " Chart");
chartData.setSeriesLabel("Samples");
chartData.setClassesLabel(cName);
chartData.setCountsLabel(dir.getDocument().getReadAssignmentMode().getDisplayLabel());
setClassLabelAngle(Math.PI / 4);
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent event) {
InputDialog inputDialog = InputDialog.getInstance();
if (inputDialog != null)
inputDialog.setViewer(dir, FViewerChart.this);
}
});
getClassesList().getPopupMenu().addSeparator();
{
final OpenWebPageCommand command = new OpenWebPageCommand();
command.setViewer(this);
Action action = new AbstractAction(OpenWebPageCommand.NAME) {
public void actionPerformed(ActionEvent actionEvent) {
java.util.Collection<String> selectedIds = getClassesList().getSelectedLabels();
if (selectedIds.size() > 0) {
if (selectedIds.size() >= 5 && JOptionPane.showConfirmDialog(getFrame(), "Do you really want to open " + selectedIds.size() +
" windows in your browser?", "Confirmation - MEGAN", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon()) != JOptionPane.YES_OPTION)
return;
for (String label : selectedIds) {
try {
command.apply("show webPage classification=" + cName + " id='" + label + "';");
} catch (Exception e) {
Basic.caught(e);
}
}
}
}
};
action.putValue(AbstractAction.SMALL_ICON, command.getIcon());
getClassesList().getPopupMenu().add(action);
}
try {
sync();
} catch (CanceledException e) {
Basic.caught(e);
}
int[] geometry = ProgramProperties.get(cName + "ChartGeometry", new int[]{100, 100, 800, 600});
setSize(geometry[2], geometry[3]);
setVisible(true);
getFrame().addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
ProgramProperties.put(cName + "ChartGeometry", new int[]{
getLocation().x, getLocation().y, getSize().width, getSize().height});
}
});
}
/**
* synchronize chart to reflect latest user selection in taxon chart
*/
public void sync() throws CanceledException {
if (!inSync) {
inSync = true;
IChartData chartData = (IChartData) getChartData();
chartData.clear();
Document doc = dir.getDocument();
setChartTitle(cName + " profile for " + doc.getTitle());
int numberOfSamples = doc.getNumberOfSamples();
if (numberOfSamples > 0) {
if (viewer.getSelectedNodes().size() == 0) {
viewer.selectAllLeaves();
}
chartData.setAllSeries(doc.getSampleNames());
String[] sampleNames = doc.getSampleNames().toArray(new String[0]);
java.util.Collection<Integer> ids = viewer.getSelectedNodeIds();
LinkedList<String> classNames = new LinkedList<>();
for (Integer id : ids) {
String className = viewer.getClassification().getName2IdMap().get(id);
classNames.add(className);
float[] summarized = viewer.getSummarized(id);
for (int i = 0; i < sampleNames.length; i++) {
chartData.putValue(sampleNames[i], className, summarized[i]);
}
}
chartData.setClassNames(classNames);
}
chartData.setTree(viewer.getInducedTree(viewer.getClassification().getName2IdMap().getId2Name(), viewer.getSelectedNodes()));
super.sync();
inSync = false;
}
}
/**
* ask view to destroy itself
*/
public void destroyView() throws CanceledException {
MeganProperties.removePropertiesListListener(getJMenuBar().getRecentFilesListener());
super.destroyView();
}
/**
* get name for this type of parent
*
* @return name
*/
public String getClassName() {
return getClassName(cName);
}
public String getCName() {
return cName;
}
public static String getClassName(String cName) {
return cName + "Chart";
}
}
| 7,522 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ComparisonPlot.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/ComparisonPlot.java | /*
* ComparisonPlot.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart;
import jloda.graph.Node;
import jloda.graph.NodeData;
import jloda.swing.util.ProgramProperties;
import jloda.util.CanceledException;
import jloda.util.Pair;
import jloda.util.progress.ProgressListener;
import megan.chart.data.DefaultPlot2DData;
import megan.chart.data.IPlot2DData;
import megan.chart.drawers.ChartDrawerBase;
import megan.chart.drawers.Plot2DDrawer;
import megan.chart.gui.ChartViewer;
import megan.core.Director;
import megan.core.Document;
import megan.dialogs.input.InputDialog;
import megan.main.MeganProperties;
import megan.util.ScalingType;
import megan.viewer.ClassificationViewer;
import megan.viewer.ViewerBase;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
/**
* comparison chart
* Daniel Huson, 2.2013
*/
public class ComparisonPlot extends ChartViewer {
private final String cName;
private final Document doc;
private boolean inSync = false;
private final ClassificationViewer viewer;
/**
* constructor
*
*/
public ComparisonPlot(final Director dir, ClassificationViewer parent) throws CanceledException {
super(parent, dir, dir.getDocument().getSampleLabelGetter(), new DefaultPlot2DData(), ProgramProperties.isUseGUI());
viewer = parent;
this.doc = dir.getDocument();
this.cName = parent.getClassName();
getToolbar().addSeparator(new Dimension(5, 10));
getToolbar().add(getCommandManager().getButton("Sync"));
MeganProperties.addPropertiesListListener(getJMenuBar().getRecentFilesListener());
MeganProperties.notifyListChange(ProgramProperties.RECENTFILES);
chooseDrawer(Plot2DDrawer.NAME);
((ChartDrawerBase) getChartDrawer()).setSupportedScalingTypes(ScalingType.LINEAR);
setChartTitle(cName + " vs " + cName + " plot for " + doc.getTitle());
setWindowTitle(cName + " vs " + cName);
getChartDrawer().setClassLabelAngle(0);
addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent event) {
InputDialog inputDialog = InputDialog.getInstance();
if (inputDialog != null)
inputDialog.setViewer(dir, ComparisonPlot.this);
}
});
sync();
}
/**
* synchronize chart to reflect latest user selection in taxon chart
*/
public void sync() throws CanceledException {
if (!inSync) {
inSync = true;
setChartTitle(cName + " vs " + cName + " plot for " + doc.getTitle());
String[] sampleNames = doc.getSampleNamesAsArray();
for (int i = 0; i < sampleNames.length; i++) {
String name1 = sampleNames[i];
for (int j = i + 1; j < sampleNames.length; j++) {
String name2 = sampleNames[j];
String name = name1 + " vs " + name2;
((Plot2DDrawer) getChartDrawer()).setShowDots(name, true);
((Plot2DDrawer) getChartDrawer()).setShowLines(name, false);
}
}
//setShowLegend(true);
Map<String, Collection<Pair<Number, Number>>> name2counts = computeCounts(doc, viewer, doc.getProgressListener());
IPlot2DData chartData = (IPlot2DData) getChartData();
chartData.clear();
chartData.setDataSetName(doc.getTitle());
for (String name : name2counts.keySet())
chartData.setDataForSeries(name, name2counts.get(name));
if (sampleNames.length == 2) {
getChartData().setSeriesLabel(sampleNames[0]);
getChartData().setCountsLabel(sampleNames[1]);
if (name2counts.values().size() > 0) {
Collection<Pair<Number, Number>> pairs = name2counts.values().iterator().next();
double correlationCoefficent = computePearsonsCorrelation(pairs);
System.err.println("Number of points: " + pairs.size() + ", Pearson's correlation: " + correlationCoefficent);
}
}
if (getChartDrawer() instanceof Plot2DDrawer) {
Plot2DDrawer drawer = (Plot2DDrawer) getChartDrawer();
for (String name : name2counts.keySet()) {
drawer.setUseJitter(name, true);
}
}
super.sync();
inSync = false;
}
}
/**
* ask view to destroy itself
*/
public void destroyView() throws CanceledException {
super.destroyView();
}
/**
* compute sample vs sample data
*
* @return values for 10-100 percent, for each dataset in the document
*/
private Map<String, Collection<Pair<Number, Number>>> computeCounts(Document doc, ViewerBase viewer, ProgressListener progressListener) throws CanceledException {
progressListener.setTasks(cName + " vs " + cName, "Sampling from current leaves");
progressListener.setMaximum(11L * doc.getNumberOfSamples());
progressListener.setProgress(0);
Map<String, Collection<Pair<Number, Number>>> plotName2Counts = new HashMap<>();
String[] sampleNames = doc.getSampleNamesAsArray();
for (int i = 0; i < sampleNames.length; i++) {
String name1 = sampleNames[i];
for (int j = i + 1; j < sampleNames.length; j++) {
String name2 = sampleNames[j];
String name = name1 + " vs " + name2;
for (Node v : viewer.getSelectedNodes()) {
float[] counts = ((NodeData) v.getData()).getAssigned();
if (j < counts.length && counts[i] > 0 || counts[j] > 0) {
Collection<Pair<Number, Number>> pairs = plotName2Counts.computeIfAbsent(name, k -> new LinkedList<>());
pairs.add(new Pair<>(counts[i], counts[i + 1]));
}
}
}
}
return plotName2Counts;
}
/**
* computes the Pearson's correlation for a list of pairs
*
* @return r
*/
private static double computePearsonsCorrelation(Collection<Pair<Number, Number>> pairs) {
double[] mean = new double[2];
for (Pair<Number, Number> pair : pairs) {
mean[0] += pair.getFirst().doubleValue();
mean[1] += pair.getSecond().doubleValue();
}
mean[0] /= pairs.size();
mean[1] /= pairs.size();
double[] stddev = new double[2];
for (Pair<Number, Number> pair : pairs) {
stddev[0] += (pair.getFirst().doubleValue() - mean[0]) * (pair.getFirst().doubleValue() - mean[0]);
stddev[1] += (pair.getSecond().doubleValue() - mean[1]) * (pair.getSecond().doubleValue() - mean[1]);
}
stddev[0] = Math.sqrt(stddev[0] / pairs.size());
stddev[1] = Math.sqrt(stddev[1] / pairs.size());
double cor = 0;
for (Pair<Number, Number> pair : pairs) {
cor += (pair.getFirst().doubleValue() - mean[0]) * (pair.getSecond().doubleValue() - mean[1]) / (stddev[0] * stddev[1]);
}
cor /= pairs.size();
return cor;
}
/**
* get name for this type of parent
*
* @return name
*/
public String getClassName() {
return getClassName(cName);
}
public static String getClassName(String cName) {
return cName + "vs" + cName;
}
}
| 8,439 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IChartDrawer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/IChartDrawer.java | /*
* IChartDrawer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart;
import jloda.swing.util.ILabelGetter;
import jloda.swing.window.IPopupMenuModifier;
import megan.chart.cluster.ClusteringTree;
import megan.chart.data.IData;
import megan.chart.gui.ChartSelection;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.Label2LabelMapper;
import megan.util.ScalingType;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.Writer;
import java.util.concurrent.ExecutorService;
/**
* Interface for chart drawer
* Daniel Huson, 4.2015
*/
public interface IChartDrawer {
void setViewer(ChartViewer viewer);
void setChartData(IData chartData);
void setClass2HigherClassMapper(Label2LabelMapper class2HigherClassMapper);
void setSeriesLabelGetter(ILabelGetter seriesLabelGetter);
void setBackground(Color color);
double getClassLabelAngle();
void setClassLabelAngle(double classLabelAngle);
boolean canTranspose();
boolean isTranspose();
void setTranspose(boolean transpose);
ScalingType getScalingType();
void setScalingType(ScalingType scalingType);
boolean isSupportedScalingType(ScalingType scalingType);
boolean canShowLegend();
boolean canShowValues();
boolean isShowValues();
void setShowValues(boolean showValues);
boolean canColorByRank();
String getChartTitle();
void setChartTitle(String chartTitle);
boolean canShowYAxis();
boolean isShowYAxis();
void setShowYAxis(boolean showYAxis);
boolean canShowXAxis();
boolean isShowXAxis();
void setShowXAxis(boolean showXAxis);
void updateView();
ChartColorManager getChartColors();
IData getChartData();
void drawChart(Graphics2D gc);
void drawChartTransposed(Graphics2D gc);
void close();
void setFont(String target, Font font, Color color);
Font getFont(String target);
Color getFontColor(String target, Color defaultColor);
boolean isXYLocked();
boolean isShowInternalLabels();
void setShowInternalLabels(boolean showInternalLabels);
boolean canShowInternalLabels();
boolean selectOnMouseDown(MouseEvent mouseEvent, ChartSelection chartSelection);
boolean selectOnRubberBand(Rectangle rectangle, MouseEvent mouseEvent, ChartSelection chartSelection);
String[] getItemBelowMouse(MouseEvent mouseEvent, ChartSelection chartSelection);
Label2LabelMapper getClass2HigherClassMapper();
void forceUpdate();
ILabelGetter getSeriesLabelGetter();
JToolBar getBottomToolBar();
ScalingType getScalingTypePreference();
boolean getShowXAxisPreference();
boolean getShowYAxisPreference();
void repaint();
Rectangle2D getScrollBackReferenceRect();
void setScrollBackWindowPoint(Point2D center);
Point2D convertWindowToReference(Point2D center);
void setScrollBackReferencePoint(Point2D scrollBackReferencePoint);
void computeScrollBackReferenceRect();
Point2D getScrollBackReferencePoint();
Point2D getScrollBackWindowPoint();
Point2D convertReferenceToWindow(Point2D scrollBackReferencePoint);
JPanel getJPanel();
ChartViewer getViewer();
String getChartDrawerName();
void setExecutorService(ExecutorService executorService);
boolean usesHeatMapColors();
IPopupMenuModifier getPopupMenuModifier();
boolean isEnabled();
void writeData(Writer w) throws IOException;
boolean canCluster(ClusteringTree.TYPE type);
boolean canAttributes();
}
| 4,414 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ChartCommandHelper.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/data/ChartCommandHelper.java | /*
* ChartCommandHelper.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.data;
import jloda.swing.commands.ICommand;
import megan.chart.commandtemplates.SetChartDrawerCommand;
import megan.chart.commandtemplates.SetChartDrawerSpecificCommand;
import megan.chart.commandtemplates.ShowChartSpecificCommand;
import megan.chart.drawers.DrawerManager;
import java.util.ArrayList;
import java.util.Collection;
/**
* helper class for setting up chart commands
* Daniel Huson, 4.2015
*/
public class ChartCommandHelper {
/**
* open chart menu string for main viewers
*
* @return open chart menu string
*/
public static String getOpenChartMenuString() {
final StringBuilder buf = new StringBuilder();
for (String name : DrawerManager.getAllSupportedChartDrawers()) {
buf.append((new ShowChartSpecificCommand(name)).getName()).append(";");
}
return buf.toString();
}
/**
* gets the menu string for opening all registered viewers, is used in GUIConfiguration of chart viewer
*
* @return menu string
*/
public static String getSetDrawerCommandString() {
final StringBuilder buf = new StringBuilder();
for (String name : DrawerManager.getAllSupportedChartDrawers()) {
buf.append((new SetChartDrawerSpecificCommand(name)).getName()).append(";");
}
return buf.toString();
}
/**
* get all commands needed to draw charts, used in chart viewer
*
* @return commands
*/
public static Collection<ICommand> getChartDrawerCommands() {
final ArrayList<ICommand> commands = new ArrayList<>();
commands.add(new SetChartDrawerCommand());
for (String name : DrawerManager.getAllSupportedChartDrawers()) {
commands.add(new SetChartDrawerSpecificCommand(name));
commands.add(new ShowChartSpecificCommand(name));
}
return commands;
}
}
| 2,722 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
DefaultChartData.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/data/DefaultChartData.java | /*
* DefaultChartData.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.data;
import jloda.phylo.PhyloTree;
import jloda.util.Pair;
import megan.chart.gui.ChartSelection;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* maintains data used by charts
* Daniel Huson, 5.2012
*/
public class DefaultChartData implements IChartData {
private final ChartSelection chartSelection;
private String dataSetName;
private String seriesLabel;
private String classesLabel;
private String countsLabel;
private final ArrayList<String> seriesNames;
private final Map<String, Float> series2TotalSize; // maps to total size
private final Collection<String> classNames;
private final Map<String, Map<String, Number>> series2Class2Values;
private final Map<String, Double> series2size; // maps to size associated with selected data
private final Map<String, Double> classes2size;
private final Map<String, Pair<Number, Number>> series2Range;
private Pair<Number, Number> range;
private final Map<String, String> samplesTooltips;
private final Map<String, String> classesTooltips;
private boolean useTotalSize = false;
private PhyloTree tree;
/**
* constructor
*/
public DefaultChartData() {
chartSelection = new ChartSelection();
seriesNames = new ArrayList<>();
series2TotalSize = new HashMap<>();
classNames = new ArrayList<>();
series2Class2Values = new HashMap<>();
series2size = new HashMap<>();
classes2size = new HashMap<>();
series2Range = new HashMap<>();
samplesTooltips = new HashMap<>();
classesTooltips = new HashMap<>();
}
/**
* set dataset name
*
*/
public void setDataSetName(String name) {
this.dataSetName = name;
}
/**
* get dataset name
*
* @return series label
*/
public String getDataSetName() {
return dataSetName;
}
public String getSeriesLabel() {
return seriesLabel;
}
public void setSeriesLabel(String seriesLabel) {
this.seriesLabel = seriesLabel;
}
public String getClassesLabel() {
return classesLabel;
}
public void setClassesLabel(String classesLabel) {
this.classesLabel = classesLabel;
}
public String getCountsLabel() {
return countsLabel;
}
public void setCountsLabel(String countsLabel) {
this.countsLabel = countsLabel;
}
/**
* get the number of datasets
*
*/
public int getNumberOfSeries() {
return seriesNames.size();
}
/**
* get all series names including those currently disabled
*
* @return names
*/
public String[] getSeriesNamesIncludingDisabled() {
return (new ArrayList<>(series2size.keySet())).toArray(new String[series2size.size()]);
}
/**
* get all series names
*
* @return names
*/
public Collection<String> getSeriesNames() {
return seriesNames;
}
/**
* set the collection of series names in the order that they should appear
*
*/
public void setAllSeries(Collection<String> allSeries) {
this.seriesNames.clear();
this.seriesNames.addAll(allSeries);
}
/**
* set the total size for each series. This is needed when normalizing by the total number of reads in samples
*
*/
public void setAllSeriesTotalSizes(float... sizes) {
for (int i = 0; i < sizes.length; i++)
this.series2TotalSize.put(seriesNames.get(i), sizes[i]);
}
/**
* get the number of classes
*
* @return number of classes
*/
public int getNumberOfClasses() {
return classNames.size();
}
/**
* get the collection of class names in the order that they should appear
*
*/
public Collection<String> getClassNames() {
return classNames;
}
/**
* set the collection of class names in the order that they should appear
*
*/
public void setClassNames(Collection<String> classNames) {
this.classNames.clear();
this.classNames.addAll(classNames);
}
/**
* gets the value for the given series and className
*
* @return number or null
*/
public Number getValue(String series, String className) {
Map<String, Number> class2Values = series2Class2Values.get(series);
if (class2Values == null)
return 0;
else {
Number value = class2Values.get(className);
if (value == null)
return 0;
else
return value.doubleValue();
}
}
/**
* gets the value for the given series and className
*
* @return number or null
*/
public double getValueAsDouble(String series, String className) {
Map<String, Number> class2Values = series2Class2Values.get(series);
if (class2Values == null)
return 0;
Number value = class2Values.get(className);
return value == null ? 0 : value.doubleValue();
}
/**
* set the data for a specific data set
*
*/
public void setDataForSeries(String series, Map<String, Number> classes2values) {
series2Class2Values.put(series, classes2values);
Number min = null;
Number max = null;
double total = 0;
if (classes2values != null) {
for (Number value : classes2values.values()) {
if (min == null) {
min = value;
max = value;
} else {
if (value.doubleValue() < min.doubleValue())
min = value;
if (value.doubleValue() > max.doubleValue())
max = value;
}
total += value.doubleValue();
}
series2Range.put(series, new Pair<>(min, max));
if (range == null)
range = new Pair<>(min, max);
else if (min != null) {
if (min.doubleValue() < range.getFirst().doubleValue())
range.setFirst(min);
if (max.doubleValue() > range.getSecond().doubleValue())
range.setSecond(max);
}
series2size.put(series, total);
samplesTooltips.put(series, String.format("%s: %.0f", series, series2size.get(series)));
for (Map.Entry<String, Number> entry : classes2values.entrySet()) {
String className = entry.getKey();
Number value = entry.getValue();
Number previous = classes2size.get(className);
classes2size.put(className, previous == null ? value.doubleValue() : previous.doubleValue() + value.doubleValue());
}
for (String className : classes2size.keySet()) {
classesTooltips.put(className, String.format("%s: %.0f", className, classes2size.get(className)));
}
}
}
public Map<String, Number> getDataForSeries(String series) {
return series2Class2Values.get(series);
}
/**
* get the range (min,max) of all values
*
* @return range
*/
public Pair<Number, Number> getRange() {
return range;
}
/**
* gets the range of values for the given dataset
*
*/
public Pair<Number, Number> getRange(String series) {
return series2Range.get(series);
}
/**
* erase
*/
public void clear() {
chartSelection.clearSelectionClasses();
chartSelection.clearSelectionSeries();
series2Class2Values.clear();
series2Range.clear();
series2size.clear();
classes2size.clear();
samplesTooltips.clear();
classesTooltips.clear();
range = null;
}
/**
* put a data point
*
*/
public void putValue(String series, String className, Number value) {
if (value == null)
value = 0;
Map<String, Number> class2value = series2Class2Values.computeIfAbsent(series, k -> new HashMap<>());
class2value.put(className, value);
Pair<Number, Number> range = getRange(series);
if (range == null) {
range = new Pair<>(value, value);
series2Range.put(series, range);
} else {
if (value.doubleValue() < range.getFirst().doubleValue())
range.setFirst(value);
if (value.doubleValue() > range.getSecond().doubleValue())
range.setSecond(value);
}
Pair<Number, Number> wholeRange = getRange();
if (wholeRange == null) {
this.range = new Pair<>(value, value);
} else {
if (value.doubleValue() < wholeRange.getFirst().doubleValue())
wholeRange.setFirst(value);
if (value.doubleValue() > wholeRange.getSecond().doubleValue())
wholeRange.setSecond(value);
}
Double previous = series2size.get(series);
series2size.put(series, previous == null ? value.doubleValue() : previous + value.doubleValue());
samplesTooltips.put(series, String.format("%s: %.0f", series, series2size.get(series)));
previous = classes2size.get(className);
classes2size.put(className, previous == null ? value.doubleValue() : previous + value.doubleValue());
classesTooltips.put(className, String.format("%s: %.0f", className, classes2size.get(className)));
}
public double getTotalForSeries(String series) {
if (isUseTotalSize())
return series2TotalSize.get(series);
else
return series2size.get(series);
}
public double getTotalForSeriesIncludingDisabledAttributes(String series) {
if (isUseTotalSize())
return series2TotalSize.get(series);
else {
double total = 0;
for (String className : classes2size.keySet()) {
Number value = getValue(series, className);
if (value != null)
total += value.doubleValue();
}
return total;
}
}
public double getTotalForClass(String className) {
Double value = classes2size.get(className);
return value == null ? 0 : value;
}
public double getTotalForClassIncludingDisabledSeries(String className) {
double total = 0;
for (String series : series2size.keySet()) {
total += getValue(series, className).doubleValue();
}
return total;
}
public double getMaxTotalSeries() {
double max = 0;
for (String series : seriesNames) {
Number value = series2size.get(series);
if (value != null)
max = Math.max(max, value.doubleValue());
}
return max;
}
public double getMaxTotalClass() {
double max = 0;
for (String className : classNames) {
Number value = classes2size.get(className);
if (value != null)
max = Math.max(max, value.doubleValue());
}
return max;
}
public void read(Reader r) {
System.err.println("Read data: not implemented");
}
public void write(Writer w0) throws IOException {
BufferedWriter w = new BufferedWriter(w0);
w.write("#Series:");
for (String series : getSeriesNames()) {
w.write("\t");
w.write(series);
}
w.write("\n");
for (String className : getClassNames()) {
w.write(className);
for (String series : getSeriesNames()) {
w.write("\t" + getValue(series, className).toString());
}
w.write("\n");
}
w.flush();
}
public void setEnabledClassNames(Collection<String> classNames) {
this.classNames.clear();
this.classNames.addAll(classNames);
range = null;
for (String series : seriesNames) {
double total = 0;
for (String className : classNames) {
Number value = getValue(series, className);
if (value != null) {
total += value.doubleValue();
if (range == null) {
range = new Pair<>(value, value);
} else {
if (value.doubleValue() < range.getFirst().doubleValue())
range.setFirst(value);
if (value.doubleValue() > range.getSecond().doubleValue())
range.setSecond(value);
}
}
series2size.put(series, total);
}
}
}
public void setEnabledSeries(Collection<String> seriesNames) {
this.seriesNames.clear();
this.seriesNames.addAll(seriesNames);
range = null;
for (String className : classNames) {
double total = 0;
for (String series : seriesNames) {
Number value = getValue(series, className);
if (value != null) {
total += value.doubleValue();
if (range == null) {
range = new Pair<>(value, value);
} else {
if (value.doubleValue() < range.getFirst().doubleValue())
range.setFirst(value);
if (value.doubleValue() > range.getSecond().doubleValue())
range.setSecond(value);
}
}
}
classes2size.put(className, total);
}
}
public ChartSelection getChartSelection() {
return chartSelection;
}
public Map<String, String> getSamplesTooltips() {
return samplesTooltips;
}
public Map<String, String> getClassesTooltips() {
return classesTooltips;
}
public PhyloTree getTree() {
return tree;
}
public void setTree(PhyloTree tree) {
this.tree = tree;
}
public String[] getClassNamesIncludingDisabled() {
return classes2size.keySet().toArray(new String[0]);
}
public boolean isUseTotalSize() {
return useTotalSize && hasTotalSize();
}
public void setUseTotalSize(boolean useTotalSize) {
this.useTotalSize = useTotalSize;
}
public boolean hasTotalSize() {
return series2TotalSize.size() == seriesNames.size();
}
}
| 15,597 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
WhiskerData.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/data/WhiskerData.java | /*
* WhiskerData.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.data;
import jloda.util.Pair;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* whisker plot data
* Daniel Huson, 7.2016
*/
public class WhiskerData implements Iterable<Pair<Double, String>> {
private final SortedSet<Pair<Double, String>> values = new TreeSet<>();
private volatile double[] array;
public void clear() {
values.clear();
array = null;
}
public void add(Double a, String label) {
values.add(new Pair<>(a, label));
array = null;
}
public double getMin() {
return values.size() > 0 ? values.first().getFirst() : 0;
}
public double getMax() {
return values.size() > 0 ? values.last().getFirst() : 0;
}
public double getFirstQuarter() {
if (values.size() == 0)
return 0;
ensureArray();
return array[array.length / 4];
}
public double getThirdQuarter() {
if (values.size() == 0)
return 0;
ensureArray();
return array[(3 * array.length) / 4];
}
public double getMedian() {
if (values.size() == 0)
return 0;
ensureArray();
return array[array.length / 2];
}
public Iterator<Pair<Double, String>> iterator() {
return values.iterator();
}
private void ensureArray() {
if (array == null) {
synchronized (values) {
if (array == null) {
array = new double[values.size()];
int i = 0;
for (Pair<Double, String> pair : values) {
array[i++] = pair.getFirst();
}
}
}
}
}
}
| 2,570 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IData.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/data/IData.java | /*
* IData.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.data;
import jloda.phylo.PhyloTree;
import megan.chart.gui.ChartSelection;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.Collection;
import java.util.Map;
/**
* most general interface for chart data
* Daniel Huson, 6.2012
*/
public interface IData {
void clear();
ChartSelection getChartSelection();
void setDataSetName(String label);
String getDataSetName();
void setSeriesLabel(String label);
String getSeriesLabel();
void setClassesLabel(String label);
String getClassesLabel();
void setCountsLabel(String label);
String getCountsLabel();
void setEnabledSeries(Collection<String> series);
int getNumberOfSeries();
Collection<String> getSeriesNames();
void read(Reader r);
void write(Writer w) throws IOException;
Map<String, String> getSamplesTooltips();
Map<String, String> getClassesTooltips();
PhyloTree getTree();
void setTree(PhyloTree tree);
}
| 1,820 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IPlot2DData.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/data/IPlot2DData.java | /*
* IPlot2DData.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.data;
import jloda.util.Pair;
import java.util.Collection;
/**
* chart plot2D data interface
* Daniel Huson, 5.2012
*/
public interface IPlot2DData extends IData {
void setSeriesNames(Collection<String> series);
void addSeriesName(String name);
Collection<Pair<Number, Number>> getDataForSeries(String series);
void setDataForSeries(String series, Collection<Pair<Number, Number>> dataXY);
Pair<Number, Number> getRangeX();
Pair<Number, Number> getRangeX(String series);
Pair<Number, Number> getRangeY();
Pair<Number, Number> getRangeY(String series);
void addValue(String series, Number x, Number y);
}
| 1,482 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
DefaultPlot2DData.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/data/DefaultPlot2DData.java | /*
* DefaultPlot2DData.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.data;
import jloda.phylo.PhyloTree;
import jloda.util.Pair;
import megan.chart.gui.ChartSelection;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.*;
/**
* chart plot2D data interface
* Daniel Huson, 6.2012
*/
public class DefaultPlot2DData implements IPlot2DData {
private final ChartSelection chartSelection;
private String dataSetName;
private String seriesLabel;
private String classesLabel;
private String countsLabel;
private final Collection<String> seriesNames;
private final Set<String> seriesNamesAsSet;
private final Map<String, LinkedList<Pair<Number, Number>>> series2DataXY;
private final Map<String, Pair<Number, Number>> series2RangeX;
private final Map<String, Pair<Number, Number>> series2RangeY;
private final Pair<Number, Number> rangeX = new Pair<>(0, 0);
private final Pair<Number, Number> rangeY = new Pair<>(0, 0);
private final Map<String, String> seriesToolTips;
private final Map<String, String> classesToolTips;
public DefaultPlot2DData() {
chartSelection = new ChartSelection();
seriesNames = new LinkedList<>();
seriesNamesAsSet = new HashSet<>();
series2DataXY = new HashMap<>();
series2RangeX = new HashMap<>();
series2RangeY = new HashMap<>();
seriesToolTips = new HashMap<>();
classesToolTips = new HashMap<>();
}
public void clear() {
chartSelection.clearSelectionClasses();
chartSelection.clearSelectionSeries();
seriesNames.clear();
seriesNamesAsSet.clear();
series2DataXY.clear();
series2RangeX.clear();
series2RangeY.clear();
seriesToolTips.clear();
classesToolTips.clear();
rangeX.set(0, 0);
rangeY.set(0, 0);
}
public void setDataSetName(String dataSetName) {
this.dataSetName = dataSetName;
}
public String getDataSetName() {
return dataSetName;
}
public String getSeriesLabel() {
return seriesLabel;
}
public void setSeriesLabel(String seriesLabel) {
this.seriesLabel = seriesLabel;
}
public String getClassesLabel() {
return classesLabel;
}
public void setClassesLabel(String classesLabel) {
this.classesLabel = classesLabel;
}
public String getCountsLabel() {
return countsLabel;
}
public void setCountsLabel(String countsLabel) {
this.countsLabel = countsLabel;
}
public int getNumberOfSeries() {
return series2DataXY.keySet().size();
}
public Collection<String> getSeriesNames() {
return seriesNames;
}
public void setSeriesNames(Collection<String> seriesNames) {
this.seriesNames.clear();
this.seriesNamesAsSet.clear();
for (String name : seriesNames) {
if (!seriesNamesAsSet.contains(name)) {
this.seriesNames.add(name);
this.seriesNamesAsSet.add(name);
}
}
}
public void addSeriesName(String name) {
if (!seriesNamesAsSet.contains(name)) {
this.seriesNames.add(name);
this.seriesNamesAsSet.add(name);
}
}
public Collection<Pair<Number, Number>> getDataForSeries(String series) {
return series2DataXY.get(series);
}
public void setDataForSeries(String series, Collection<Pair<Number, Number>> dataXY) {
LinkedList<Pair<Number, Number>> list = new LinkedList<>(dataXY);
series2DataXY.put(series, list);
double minX = Double.MAX_VALUE;
double maxX = Double.NEGATIVE_INFINITY;
double minY = Double.MAX_VALUE;
double maxY = Double.NEGATIVE_INFINITY;
for (Pair<Number, Number> pair : list) {
double x = pair.getFirst().doubleValue();
double y = pair.getSecond().doubleValue();
minX = Math.min(x, minX);
maxX = Math.max(x, maxX);
minY = Math.min(y, minY);
maxY = Math.max(y, maxY);
}
series2RangeX.put(series, new Pair<>(minX, maxX));
series2RangeY.put(series, new Pair<>(minY, maxY));
if (rangeX.getFirst().doubleValue() == 0 && rangeX.getSecond().doubleValue() == 0)
rangeX.set(minX, maxX);
else
rangeX.set(Math.min(rangeX.getFirst().doubleValue(), minX), Math.max(rangeX.getSecond().doubleValue(), maxX));
if (rangeY.getFirst().doubleValue() == 0 && rangeY.getSecond().doubleValue() == 0)
rangeY.set(minY, maxY);
else
rangeY.set(Math.min(rangeY.getFirst().doubleValue(), minY), Math.max(rangeY.getSecond().doubleValue(), maxY));
addSeriesName(series);
seriesToolTips.put(series, String.format("%s X-range: %.1f - %.1f Y-range: %.1f - %.1f", series, minX, maxX, minY, maxY));
}
public Pair<Number, Number> getRangeX() {
return rangeX;
}
public Pair<Number, Number> getRangeX(String series) {
return series2RangeX.get(series);
}
public Pair<Number, Number> getRangeY() {
return rangeY;
}
public Pair<Number, Number> getRangeY(String series) {
return series2RangeY.get(series);
}
public void addValue(String series, Number x, Number y) {
LinkedList<Pair<Number, Number>> list = series2DataXY.computeIfAbsent(series, k -> new LinkedList<>());
list.add(new Pair<>(x, y));
Pair<Number, Number> rangeXd = series2RangeX.get(series);
if (rangeXd == null)
series2RangeX.put(series, new Pair<>(x, x));
else
rangeXd.set(Math.min(rangeXd.getFirst().doubleValue(), x.doubleValue()), Math.max(rangeXd.getSecond().doubleValue(), x.doubleValue()));
Pair<Number, Number> rangeYd = series2RangeY.get(series);
if (rangeYd == null)
series2RangeY.put(series, new Pair<>(y, y));
else
rangeYd.set(Math.min(rangeYd.getFirst().doubleValue(), y.doubleValue()), Math.max(rangeYd.getSecond().doubleValue(), y.doubleValue()));
if (rangeX.getFirst().doubleValue() == 0 && rangeX.getSecond().doubleValue() == 0)
rangeX.set(x, x);
else
rangeX.set(Math.min(rangeX.getFirst().doubleValue(), x.doubleValue()), Math.max(rangeX.getSecond().doubleValue(), x.doubleValue()));
if (rangeY.getFirst().doubleValue() == 0 && rangeY.getSecond().doubleValue() == 0)
rangeY.set(y, y);
else
rangeY.set(Math.min(rangeY.getFirst().doubleValue(), y.doubleValue()), Math.max(rangeY.getSecond().doubleValue(), y.doubleValue()));
}
public void read(Reader r) {
System.err.println("Read data: not implemented");
}
public void write(Writer w0) throws IOException {
BufferedWriter w = new BufferedWriter(w0);
for (String series : getSeriesNames()) {
Collection<Pair<Number, Number>> list = getDataForSeries(series);
w.write("#Series: " + series + "\n");
for (Pair<Number, Number> pair : list) {
w.write(pair.getFirst() + "\t" + pair.getSecond() + "\n");
}
w.flush();
}
}
public void setEnabledSeries(Collection<String> seriesNames) {
this.seriesNames.clear();
this.seriesNames.addAll(seriesNames);
// need to update the total range of values:
for (String series : seriesNames) {
Pair<Number, Number> rangeXd = series2RangeX.get(series);
Pair<Number, Number> rangeYd = series2RangeY.get(series);
if (rangeX.getFirst().doubleValue() == 0 && rangeX.getSecond().doubleValue() == 0)
rangeX.set(rangeXd.getFirst(), rangeXd.getSecond());
else
rangeX.set(Math.min(rangeX.getFirst().doubleValue(), rangeXd.getFirst().doubleValue()), Math.max(rangeX.getSecond().doubleValue(), rangeXd.getSecond().doubleValue()));
if (rangeY.getFirst().doubleValue() == 0 && rangeY.getSecond().doubleValue() == 0)
rangeY.set(rangeYd.getFirst(), rangeYd.getSecond());
else
rangeY.set(Math.min(rangeY.getFirst().doubleValue(), rangeYd.getFirst().doubleValue()), Math.max(rangeY.getSecond().doubleValue(), rangeYd.getSecond().doubleValue()));
}
}
public ChartSelection getChartSelection() {
return chartSelection;
}
public Map<String, String> getSamplesTooltips() {
return seriesToolTips;
}
public Map<String, String> getClassesTooltips() {
return classesToolTips;
}
public PhyloTree getTree() {
return null;
}
public void setTree(PhyloTree tree) {
}
}
| 9,616 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IChartData.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/data/IChartData.java | /*
* IChartData.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.data;
import jloda.util.Pair;
import java.util.Collection;
import java.util.Map;
/**
* chart data interface
* Daniel Huson, 5.2012
*/
public interface IChartData extends IData {
void setAllSeries(Collection<String> allSeries);
void setAllSeriesTotalSizes(float... sizes);
String[] getSeriesNamesIncludingDisabled();
boolean hasTotalSize();
boolean isUseTotalSize();
void setUseTotalSize(boolean value);
int getNumberOfClasses();
void setEnabledClassNames(Collection<String> classNames);
Collection<String> getClassNames();
String[] getClassNamesIncludingDisabled();
void setClassNames(Collection<String> classNames);
Number getValue(String series, String className);
double getValueAsDouble(String series, String className);
double getTotalForSeries(String series);
double getTotalForClass(String className);
void setDataForSeries(String series, Map<String, Number> classes2values);
Pair<Number, Number> getRange();
Pair<Number, Number> getRange(String series);
void putValue(String series, String className, Number value);
double getMaxTotalSeries();
double getMaxTotalClass();
Map<String, Number> getDataForSeries(String series);
double getTotalForSeriesIncludingDisabledAttributes(String series);
double getTotalForClassIncludingDisabledSeries(String className);
}
| 2,219 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SeriesList.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/gui/SeriesList.java | /*
* SeriesList.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.gui;
import jloda.swing.util.ListTransferHandler;
import jloda.swing.util.PopupMenu;
import megan.chart.ChartColorManager;
import megan.chart.data.IChartData;
import javax.swing.*;
/**
* side list for series
* Created by huson on 9/18/16.
*/
public class SeriesList extends LabelsJList {
private final ChartSelection chartSelection;
/**
* constructor
*
*/
public SeriesList(final ChartViewer viewer) {
super(viewer, createSyncListenerSeriesList(viewer), createPopupMenu(viewer));
this.chartSelection = viewer.getChartSelection();
setName("Series");
addListSelectionListener(listSelectionEvent -> {
if (!inSelection) {
inSelection = true;
try {
chartSelection.clearSelectionSeries();
chartSelection.setSelectedSeries(getSelectedLabels(), true);
} finally {
inSelection = false;
}
}
});
setDragEnabled(true);
setTransferHandler(new ListTransferHandler());
chartSelection.addSeriesSelectionListener(chartSelection -> {
if (!inSelection) {
inSelection = true;
try {
DefaultListModel model = (DefaultListModel) getModel();
for (int i = 0; i < model.getSize(); i++) {
String name = getModel().getElementAt(i);
if (chartSelection.isSelectedSeries(name))
addSelectionInterval(i, i + 1);
else
removeSelectionInterval(i, i + 1);
}
} finally {
inSelection = false;
}
}
});
}
/**
* call this when tab containing list is activated
*/
public void activate() {
getViewer().getSearchManager().setSearcher(getSearcher());
getViewer().getSearchManager().getFindDialogAsToolBar().clearMessage();
if (!inSelection) {
inSelection = true;
try {
chartSelection.clearSelectionSeries();
chartSelection.setSelectedSeries(getSelectedLabels(), true);
this.repaint(); // todo: or viewer.repaint() ??
} finally {
inSelection = false;
}
}
}
/**
* call this when tab containing list is deactivated
*/
public void deactivate() {
if (!inSelection) {
inSelection = true;
try {
chartSelection.clearSelectionSeries();
this.repaint(); // todo: or viewer.repaint() ??
} finally {
inSelection = false;
}
}
}
public ChartColorManager.ColorGetter getColorGetter() {
return getViewer().getDir().getDocument().getChartColorManager().getSeriesColorGetter();
}
private ChartViewer getViewer() {
return (ChartViewer) viewer;
}
private static SyncListener createSyncListenerSeriesList(final ChartViewer viewer) {
return enabledNames -> {
if (viewer.getChartData() instanceof IChartData) {
viewer.getChartData().setEnabledSeries(enabledNames);
}
};
}
private static PopupMenu createPopupMenu(ChartViewer viewer) {
return new PopupMenu(null, GUIConfiguration.getSeriesListPopupConfiguration(), viewer.getCommandManager());
}
}
| 4,375 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectionGraphics.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/gui/SelectionGraphics.java | /*
* SelectionGraphics.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.gui;
import jloda.swing.util.BasicSwing;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ImageObserver;
import java.awt.image.RenderedImage;
import java.awt.image.renderable.RenderableImage;
import java.text.AttributedCharacterIterator;
import java.util.LinkedList;
import java.util.Map;
/**
* class for selecting objects instead of drawing them
* Daniel Huson, 3.2013
*/
public class SelectionGraphics<T> extends Graphics2D {
private final Graphics2D gc;
private final LinkedList<T> selection = new LinkedList<>();
private T currentItem = null;
private T previouslySelectedItem = null;
private Rectangle selectionRectangle;
private final Rectangle rectangle = new Rectangle();
private final Line2D line = new Line2D.Float();
public enum Which {First, Last, All}
private Which useWhich = Which.All;
private boolean shiftDown = false;
private int mouseClicks = 0;
/**
* constructor
*
*/
public SelectionGraphics(Graphics gc) {
this.gc = (Graphics2D) gc;
}
public void setMouseLocation(Point mouseLocation) {
if (selectionRectangle == null)
selectionRectangle = new Rectangle(mouseLocation.x - 2, mouseLocation.y - 2, 4, 4);
else
selectionRectangle.setRect(mouseLocation.x - 2, mouseLocation.y - 2, 4, 4);
}
public Rectangle getSelectionRectangle() {
return selectionRectangle;
}
public void setSelectionRectangle(Rectangle selectionRectangle) {
this.selectionRectangle = selectionRectangle;
}
/**
* set the current label. If anything is hit while this is set, get selection will return it
*
*/
public void setCurrentItem(T currentItem) {
this.currentItem = currentItem;
}
/**
* get the current label or null
*
*/
public T getCurrentItem() {
return currentItem;
}
/**
* erase the current item
*/
public void clearCurrentItem() {
currentItem = null;
}
/**
* get selected objects
*
* @return selection
*/
public LinkedList<T> getSelectedItems() {
return selection;
}
/**
* erase selection
*/
public void clearSelection() {
selection.clear();
previouslySelectedItem = null;
shiftDown = false;
mouseClicks = 0;
}
public boolean isShiftDown() {
return shiftDown;
}
public void setShiftDown(boolean shiftDown) {
this.shiftDown = shiftDown;
}
public int getMouseClicks() {
return mouseClicks;
}
public void setMouseClicks(int mouseClicks) {
this.mouseClicks = mouseClicks;
}
private void testForHit(Shape shape, boolean onStroke) {
if (selectionRectangle != null && currentItem != null && currentItem != previouslySelectedItem) {
// if (gc != null && !gc.getTransform().isIdentity())
// shape = gc.getTransform().createTransformedShape(shape);
if (shape instanceof Line2D) {
if (shape.intersects(selectionRectangle)) {
selection.add(currentItem);
previouslySelectedItem = currentItem;
}
} else if (shape instanceof Rectangle2D) {
if (selectionRectangle.intersects(shape.getBounds())) {
selection.add(currentItem);
previouslySelectedItem = currentItem;
}
} else {
if ((new Area(shape)).intersects(selectionRectangle)) {
selection.add(currentItem);
previouslySelectedItem = currentItem;
}
}
}
}
/**
* which of the selected items should be used?
*
* @return use which
*/
public Which getUseWhich() {
return useWhich;
}
/**
* set which to be used
*
*/
public void setUseWhich(Which useWhich) {
this.useWhich = useWhich;
}
// todo: all the draw operations
public void draw(Shape shape) {
testForHit(shape, false);
}
public void fill(Shape shape) {
testForHit(shape, false);
}
public void drawString(String s, float x, float y) {
drawString(s, Math.round(x), Math.round(y));
}
public void drawString(String s, int x, int y) {
if (currentItem != null && gc != null) {
Dimension labelSize = BasicSwing.getStringSize(gc, s, gc.getFont()).getSize();
rectangle.setRect(x, y - labelSize.height, labelSize.width, labelSize.height);
testForHit(rectangle, false);
}
}
public void drawBytes(byte[] data, int offset, int length, int x, int y) {
if (currentItem != null) {
String string = new String(data, offset, length);
drawString(string, x, y);
}
}
public void drawChars(char[] data, int offset, int length, int x, int y) {
if (currentItem != null) {
String string = new String(data, offset, length);
drawString(string, x, y);
}
}
public void fillOval(int x, int y, int width, int height) {
if (currentItem != null) {
rectangle.setRect(x, y, width, height);
testForHit(rectangle, false);
}
}
public void drawOval(int x, int y, int width, int height) {
if (currentItem != null) {
rectangle.setRect(x, y, width, height);
testForHit(rectangle, true);
}
}
public void fillRect(int x, int y, int width, int height) {
if (currentItem != null) {
rectangle.setRect(x, y, width, height);
testForHit(rectangle, false);
}
}
public void fillPolygon(Polygon polygon) {
if (currentItem != null) {
testForHit(polygon, false);
}
}
public void drawPolygon(int[] ints, int[] ints1, int i) {
if (currentItem != null) {
Polygon polygon = new Polygon(ints, ints1, i);
testForHit(polygon, true);
}
}
public void draw3DRect(int x, int y, int width, int height, boolean b) {
if (currentItem != null) {
rectangle.setRect(x, y, width, height);
testForHit(rectangle, true);
}
}
public void fill3DRect(int x, int y, int width, int height, boolean b) {
if (currentItem != null) {
rectangle.setRect(x, y, width, height);
testForHit(rectangle, false);
}
}
public void drawRect(int x, int y, int width, int height) {
if (currentItem != null) {
rectangle.setRect(x, y, width, height);
testForHit(rectangle, true);
}
}
public void fillPolygon(int[] ints, int[] ints1, int i) {
if (currentItem != null) {
Polygon polygon = new Polygon(ints, ints1, i);
testForHit(polygon, false);
}
}
public void drawLine(int i, int i1, int i2, int i3) {
if (currentItem != null) {
line.setLine(i, i1, i2, i3);
testForHit(line, true);
}
}
public void drawPolyline(int[] ints, int[] ints1, int i) {
if (currentItem != null && gc != null) {
gc.drawPolyline(ints, ints1, i);
}
}
public void drawPolygon(Polygon polygon) {
if (currentItem != null && gc != null) {
gc.drawPolygon(polygon);
}
}
public void fillRoundRect(int x, int y, int width, int height, int i4, int i5) {
if (currentItem != null) {
rectangle.setRect(x, y, width, height);
testForHit(rectangle, false);
}
}
public void drawRoundRect(int x, int y, int width, int height, int i4, int i5) {
if (currentItem != null) {
rectangle.setRect(x, y, width, height);
testForHit(rectangle, true);
}
}
public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) {
if (currentItem != null) {
rectangle.setRect(x, y, width, height);
Arc2D arc = new Arc2D.Float(rectangle, startAngle, arcAngle, Arc2D.PIE);
testForHit(arc, true);
}
}
public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) {
if (currentItem != null) {
rectangle.setRect(x, y, width, height);
Arc2D arc = new Arc2D.Float(rectangle, startAngle, arcAngle, Arc2D.PIE);
testForHit(arc, false);
}
}
public void copyArea(int x, int y, int width, int height, int dx, int dy) {
if (currentItem != null) {
rectangle.setRect(x + dx, y + dy, width, height);
testForHit(rectangle, false);
}
}
public void drawImage(BufferedImage bufferedImage, BufferedImageOp bufferedImageOp, int x, int y) {
if (currentItem != null) {
rectangle.setRect(x, y, bufferedImage.getWidth(), bufferedImage.getHeight());
testForHit(rectangle, false);
}
}
public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer) {
if (currentItem != null) {
rectangle.setRect(dx1, dy1, dx2 - dx1, dy2 - dy1);
testForHit(rectangle, false);
}
return true;
}
public boolean drawImage(Image image, int x, int y, int width, int height, Color color, ImageObserver imageObserver) {
if (currentItem != null) {
rectangle.setRect(x, y, width, height);
testForHit(rectangle, false);
}
return true;
}
public boolean drawImage(Image image, int x, int y, Color color, ImageObserver imageObserver) {
if (currentItem != null) {
rectangle.setRect(x, y, image.getWidth(imageObserver), image.getWidth(imageObserver));
testForHit(rectangle, false);
}
return true;
}
public boolean drawImage(Image image, int x, int y, ImageObserver imageObserver) {
if (currentItem != null) {
rectangle.setRect(x, y, image.getWidth(imageObserver), image.getWidth(imageObserver));
testForHit(rectangle, false);
}
return true;
}
public boolean drawImage(Image image, int x, int y, int width, int height, ImageObserver imageObserver) {
if (currentItem != null) {
rectangle.setRect(x, y, width, height);
testForHit(rectangle, false);
}
return true;
}
public void drawRenderableImage(RenderableImage renderableImage, AffineTransform affineTransform) {
if (currentItem != null) {
// todo: implement when required
}
}
public void drawRenderedImage(RenderedImage renderedImage, AffineTransform affineTransform) {
if (currentItem != null) {
// todo: implement when required
}
}
public void drawGlyphVector(GlyphVector glyphVector, float x, float y) {
if (currentItem != null) {
testForHit(glyphVector.getOutline(x, y), false);
}
}
public boolean drawImage(Image image, AffineTransform affineTransform, ImageObserver imageObserver) {
if (currentItem != null) {
// todo: implement when required
}
return true;
}
public void drawString(AttributedCharacterIterator attributedCharacterIterator, float v, float v1) {
if (currentItem != null) {
// todo: implement when required
}
}
public void drawString(AttributedCharacterIterator attributedCharacterIterator, int i, int i1) {
if (currentItem != null) {
// todo: implement when required
}
}
// todo: leave all below as is:
public void rotate(double v, double v1, double v2) {
if (gc != null)
gc.rotate(v, v1, v2);
}
public void setComposite(Composite composite) {
if (gc != null) gc.setComposite(composite);
}
public void setRenderingHints(Map<?, ?> map) {
if (gc != null) gc.setRenderingHints(map);
}
public void shear(double v, double v1) {
if (gc != null) gc.shear(v, v1);
}
public void translate(double v, double v1) {
if (gc != null) gc.translate(v, v1);
}
public Stroke getStroke() {
if (gc != null)
return gc.getStroke();
else
return null;
}
public boolean hit(Rectangle rectangle, Shape shape, boolean b) {
if (gc != null)
return gc.hit(rectangle, shape, b);
else
return false;
}
public void setBackground(Color color) {
if (gc != null) gc.setBackground(color);
}
public void transform(AffineTransform affineTransform) {
if (gc != null) gc.transform(affineTransform);
}
public void setStroke(Stroke stroke) {
if (gc != null) gc.setStroke(stroke);
}
public void setRenderingHint(RenderingHints.Key key, Object o) {
if (gc != null) gc.setRenderingHint(key, o);
}
public void rotate(double v) {
if (gc != null) gc.rotate(v);
}
public RenderingHints getRenderingHints() {
if (gc != null) return gc.getRenderingHints();
else
return null;
}
public FontRenderContext getFontRenderContext() {
if (gc != null) return gc.getFontRenderContext();
else
return null;
}
public void setPaint(Paint paint) {
if (gc != null) gc.setPaint(paint);
}
public AffineTransform getTransform() {
if (gc != null) return gc.getTransform();
else return null;
}
public GraphicsConfiguration getDeviceConfiguration() {
if (gc != null) return gc.getDeviceConfiguration();
else return null;
}
public Object getRenderingHint(RenderingHints.Key key) {
if (gc != null) return gc.getRenderingHint(key);
else return null;
}
public void setTransform(AffineTransform affineTransform) {
if (gc != null) gc.setTransform(affineTransform);
}
public Composite getComposite() {
if (gc != null) return gc.getComposite();
else return null;
}
public Color getBackground() {
if (gc != null) return gc.getBackground();
else return null;
}
public Paint getPaint() {
if (gc != null) return gc.getPaint();
else return null;
}
public Graphics create() {
if (gc != null) return gc.create();
else return null;
}
public void clipRect(int i, int i1, int i2, int i3) {
if (gc != null) gc.clipRect(i, i1, i2, i3);
}
public void dispose() {
if (gc != null)
gc.dispose();
}
public FontMetrics getFontMetrics() {
if (gc != null) return gc.getFontMetrics();
else return null;
}
public Color getColor() {
if (gc != null) return gc.getColor();
else return null;
}
public Rectangle getClipBounds(Rectangle rectangle) {
if (gc != null)
return gc.getClipBounds(rectangle);
else return null;
}
public FontMetrics getFontMetrics(Font font) {
if (gc != null) return gc.getFontMetrics(font);
else return null;
}
public void setClip(int i, int i1, int i2, int i3) {
if (gc != null) gc.setClip(i, i1, i2, i3);
}
public Font getFont() {
if (gc != null) return gc.getFont();
else return null;
}
public Graphics create(int i, int i1, int i2, int i3) {
if (gc != null) return gc.create(i, i1, i2, i3);
else return null;
}
public Shape getClip() {
if (gc != null) return gc.getClip();
else return null;
}
public void setPaintMode() {
if (gc != null) gc.setPaintMode();
}
public void translate(int i, int i1) {
if (gc != null) gc.translate(i, i1);
}
public boolean hitClip(int i, int i1, int i2, int i3) {
if (gc != null) return gc.hitClip(i, i1, i2, i3);
else return false;
}
public void setColor(Color color) {
if (gc != null)
gc.setColor(color);
}
public void clearRect(int i, int i1, int i2, int i3) {
if (gc != null) gc.clearRect(i, i1, i2, i3);
}
public void setClip(Shape shape) {
if (gc != null) gc.setClip(shape);
}
public void setFont(Font font) {
if (gc != null) gc.setFont(font);
}
public boolean drawImage(Image image, int i, int i1, int i2, int i3, int i4, int i5, int i6, int i7, ImageObserver imageObserver) {
if (gc != null)
return gc.drawImage(image, i, i1, i2, i3, i4, i5, i6, i7, imageObserver);
else
return false;
}
public Rectangle getClipRect() {
if (gc != null) return gc.getClipRect();
else return null;
}
public Rectangle getClipBounds() {
if (gc != null) return gc.getClipBounds();
else return null;
}
public void setXORMode(Color color) {
if (gc != null) gc.setXORMode(color);
}
public void addRenderingHints(Map<?, ?> map) {
if (gc != null)
gc.addRenderingHints(map);
}
public void scale(double v, double v1) {
if (gc != null) gc.scale(v, v1);
}
public void clip(Shape shape) {
if (gc != null) gc.clip(shape);
}
}
| 18,565 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ClassesList.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/gui/ClassesList.java | /*
* ClassesList.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.gui;
import jloda.swing.util.ListTransferHandler;
import jloda.swing.util.PopupMenu;
import megan.chart.ChartColorManager;
import megan.chart.data.IChartData;
import javax.swing.*;
/**
* side list for classes
* Created by huson on 9/18/16.
*/
public class ClassesList extends LabelsJList {
private final ChartSelection chartSelection;
/**
* constructor
*
*/
public ClassesList(final ChartViewer viewer) {
super(viewer, createSyncListenerClassesList(viewer), createPopupMenu(viewer));
this.chartSelection = viewer.getChartSelection();
setName("Classes");
addListSelectionListener(listSelectionEvent -> {
if (!inSelection) {
inSelection = true;
try {
chartSelection.clearSelectionClasses();
chartSelection.setSelectedClass(getSelectedLabels(), true);
} finally {
inSelection = false;
}
}
});
setDragEnabled(true);
setTransferHandler(new ListTransferHandler());
chartSelection.addClassesSelectionListener(chartSelection -> {
if (!inSelection) {
inSelection = true;
try {
DefaultListModel model = (DefaultListModel) getModel();
for (int i = 0; i < model.getSize(); i++) {
String name = getModel().getElementAt(i);
if (chartSelection.isSelectedClass(name))
addSelectionInterval(i, i + 1);
else
removeSelectionInterval(i, i + 1);
}
} finally {
inSelection = false;
}
}
});
}
/**
* call this when tab containing list is activated
*/
public void activate() {
getViewer().getSearchManager().setSearcher(getSearcher());
getViewer().getSearchManager().getFindDialogAsToolBar().clearMessage();
if (!inSelection) {
inSelection = true;
try {
chartSelection.clearSelectionClasses();
chartSelection.setSelectedClass(getSelectedLabels(), true);
this.repaint(); // todo: or viewer.repaint() ??
} finally {
inSelection = false;
}
}
}
/**
* call this when tab containing list is deactivated
*/
public void deactivate() {
if (!inSelection) {
inSelection = true;
try {
chartSelection.clearSelectionClasses();
this.repaint(); // todo: or viewer.repaint() ??
} finally {
inSelection = false;
}
}
}
public ChartColorManager.ColorGetter getColorGetter() {
return getViewer().getDir().getDocument().getChartColorManager().getClassColorGetter();
}
private ChartViewer getViewer() {
return (ChartViewer) viewer;
}
private static SyncListener createSyncListenerClassesList(final ChartViewer viewer) {
return enabledNames -> {
if (viewer.getChartData() instanceof IChartData) {
((IChartData) viewer.getChartData()).setEnabledClassNames(enabledNames);
}
if (viewer.getChartColorManager().isColorByPosition()) {
viewer.getChartColorManager().setClassColorPositions(viewer.getClassesList().getEnabledLabels());
}
};
}
private static PopupMenu createPopupMenu(ChartViewer viewer) {
return new PopupMenu(null, GUIConfiguration.getClassesListPopupConfiguration(), viewer.getCommandManager());
}
}
| 4,600 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SyncListener.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/gui/SyncListener.java | /*
* SyncListener.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.gui;
import java.util.LinkedList;
/**
* listen for events to sync the list of enabled names to the chart
* Daniel Huson, 6.2012
*/
public interface SyncListener {
void syncList2Viewer(LinkedList<String> enabledNames);
}
| 1,058 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ChartViewer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/gui/ChartViewer.java | /*
* ChartViewer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.gui;
import jloda.swing.commands.CommandManager;
import jloda.swing.director.*;
import jloda.swing.find.FindToolBar;
import jloda.swing.find.SearchManager;
import jloda.swing.util.PopupMenu;
import jloda.swing.util.*;
import jloda.swing.window.MenuBar;
import jloda.swing.window.*;
import jloda.util.CanceledException;
import jloda.util.Pair;
import megan.chart.ChartColorManager;
import megan.chart.IChartDrawer;
import megan.chart.IMultiChartDrawable;
import megan.chart.data.IChartData;
import megan.chart.data.IData;
import megan.chart.data.IPlot2DData;
import megan.chart.drawers.*;
import megan.core.Director;
import megan.main.MeganProperties;
import megan.util.ScalingType;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Point2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* chart viewer
* Daniel Huson, 5.2012
*/
public class ChartViewer extends JFrame implements IDirectableViewer, IViewerWithFindToolBar, IViewerWithLegend, IUsesHeatMapColors, Printable {
private final IDirectableViewer parentViewer;
protected final Director dir;
private final IData chartData;
private final CommandManager commandManager;
private final ILabelGetter seriesLabelGetter;
private boolean isUptoDate = true;
private boolean locked = false;
private boolean showFindToolBar = false;
private final SearchManager searchManager;
private final ToolBar toolbar;
private final ToolBar toolBar4List;
private JToolBar bottomToolBar;
private final MenuBar jMenuBar;
private final JTabbedPane listsTabbedPane;
private final SeriesList seriesList;
private final ClassesList classesList;
private final AttributesList attributesList;
private final StatusBar statusbar;
private final JPanel mainPanel;
private final JScrollPane scrollPane;
private final JPanel contentPanel;
private final LegendPanel legendPanel;
private final JScrollPane legendScrollPane;
private final JSplitPane splitPane;
public static Font defaultFont;
private int downX;
private int downY;
private boolean firstUpdate = true;
private final Label2LabelMapper class2HigherClassMapper;
private String windowTitle = "Chart";
private String chartTitle = "Chart";
private double classLabelAngle = 0;
private boolean transpose = false;
private ScalingType scalingType = ScalingType.LINEAR;
private boolean showXAxis = true;
private boolean showYAxis = true;
private final ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
private boolean useRectangleShape = false;
public enum FontKeys {DrawFont, TitleFont, XAxisFont, YAxisFont, LegendFont, ValuesFont}
private final Map<String, Pair<Font, Color>> fonts = new HashMap<>();
private String showLegend = "none";
private boolean showValues = false;
private boolean showInternalLabels = true;
private boolean showVerticalGridLines = ProgramProperties.get("ChartShowVerticalGridLines", true);
private boolean showGapsBetweenBars = ProgramProperties.get("ChartShowGapsBetweenBars", true);
private IChartDrawer chartDrawer;
private final Map<String, IChartDrawer> name2DrawerInstance = new HashMap<>();
private IPopupMenuModifier popupMenuModifier;
/**
* constructor
*
*/
public ChartViewer(IDirectableViewer parentViewer, final Director dir, final ILabelGetter seriesLabelGetter, IData chartData, boolean useGUI) {
this.parentViewer = parentViewer;
this.dir = dir;
this.seriesLabelGetter = seriesLabelGetter;
this.chartData = chartData;
this.setIconImages(ProgramProperties.getProgramIconImages());
int[] geometry = ProgramProperties.get(MeganProperties.CHART_WINDOW_GEOMETRY, new int[]{100, 100, 800, 600});
getFrame().setSize(geometry[2], geometry[3]);
if (parentViewer != null)
setLocationRelativeTo(parentViewer.getFrame());
else
getFrame().setLocation(geometry[0] + (dir.getID() - 1) * 20, geometry[1] + (dir.getID() - 1) * 20);
name2DrawerInstance.putAll(DrawerManager.createChartDrawers());
this.commandManager = new CommandManager(dir, this, new String[]{"megan.commands", "megan.chart.commands"}, !useGUI);
// commandManager.addCommands(this, ChartCommandHelper.getChartDrawerCommands(), true);
class2HigherClassMapper = new Label2LabelMapper();
defaultFont = ProgramProperties.get("DefaultFont", Font.decode("Helvetica-PLAIN-12"));
for (FontKeys target : FontKeys.values()) {
fonts.put(target.toString(),
new Pair<>(ProgramProperties.get(target.toString(), defaultFont),
ProgramProperties.get(target + "Color", (Color) null)));
}
setIconImages(ProgramProperties.getProgramIconImages());
MenuConfiguration menuConfig = GUIConfiguration.getMenuConfiguration();
if (parentViewer == null)
jMenuBar = null;
else {
this.jMenuBar = new MenuBar(this, menuConfig, getCommandManager());
setJMenuBar(jMenuBar);
ProjectManager.addAnotherWindowWithWindowMenu(dir, jMenuBar.getWindowMenu());
}
toolBar4List = new ToolBar(this, GUIConfiguration.getToolBar4DomainListConfiguration(), commandManager);
JPanel listPanel = new JPanel();
listPanel.setLayout(new BorderLayout());
listPanel.add(toolBar4List, BorderLayout.NORTH);
JSplitPane horizontalSP = new JSplitPane();
horizontalSP.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
horizontalSP.setDividerLocation(150);
horizontalSP.setOneTouchExpandable(true);
listsTabbedPane = new JTabbedPane();
listsTabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent changeEvent) {
getChartSelection().setSelectedBasedOnSeries(getActiveLabelsJList() == seriesList);
}
});
seriesList = new SeriesList(this);
if (!(chartData instanceof IPlot2DData)) {
seriesList.setTabIndex(listsTabbedPane.getTabCount());
listsTabbedPane.addTab(seriesList.getName(), new JScrollPane(seriesList));
}
classesList = new ClassesList(this);
classesList.setTabIndex(listsTabbedPane.getTabCount());
listsTabbedPane.addTab(classesList.getName(), new JScrollPane(classesList));
attributesList = new AttributesList(this);
if (!(chartData instanceof IPlot2DData)) {
attributesList.setTabIndex(listsTabbedPane.getTabCount());
listsTabbedPane.addTab(attributesList.getName(), new JScrollPane(attributesList));
}
attributesList.setDragEnabled(true);
if (!(chartData instanceof IPlot2DData)) {
attributesList.setTransferHandler(new ListTransferHandler());
}
searchManager = new SearchManager(dir, this, seriesList.getSearcher(), false, true);
listsTabbedPane.addChangeListener(changeEvent -> {
if (listsTabbedPane.getSelectedIndex() == classesList.getTabIndex()) {
classesList.activate();
seriesList.deactivate();
attributesList.deactivate();
} else if (listsTabbedPane.getSelectedIndex() == seriesList.getTabIndex()) {
seriesList.activate();
classesList.deactivate();
attributesList.deactivate();
} else if (listsTabbedPane.getSelectedIndex() == attributesList.getTabIndex()) {
attributesList.activate();
seriesList.deactivate();
classesList.deactivate();
}
updateView(Director.ENABLE_STATE);
});
listPanel.add(listsTabbedPane, BorderLayout.CENTER);
horizontalSP.setLeftComponent(listPanel);
getContentPane().setLayout(new BorderLayout());
toolbar = new ToolBar(this, GUIConfiguration.getToolBarConfiguration(), commandManager);
getContentPane().add(toolbar, BorderLayout.NORTH);
contentPanel = new JPanel();
contentPanel.setLayout(new BorderLayout());
contentPanel.addMouseWheelListener(e -> {
if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) {
boolean xyLocked = getChartDrawer().isXYLocked();
boolean doScaleVertical = !e.isMetaDown() && !e.isAltDown() && !e.isShiftDown() && !xyLocked;
boolean doScaleHorizontal = !e.isMetaDown() && !e.isControlDown() && !e.isAltDown() && e.isShiftDown();
boolean doScrollVertical = !e.isMetaDown() && e.isAltDown() && !e.isShiftDown() && !xyLocked;
boolean doScrollHorizontal = !e.isMetaDown() && e.isAltDown() && e.isShiftDown() && !xyLocked;
boolean doScaleBoth = (e.isMetaDown() || xyLocked) && !e.isAltDown() && !e.isShiftDown();
boolean doRotate = !e.isShiftDown() && !e.isMetaDown() && !e.isControlDown() && e.isAltDown() && getChartDrawer() instanceof RadialSpaceFillingTreeDrawer;
if (doScrollVertical) {
getScrollPane().getVerticalScrollBar().setValue(getScrollPane().getVerticalScrollBar().getValue() + e.getUnitsToScroll());
} else if (doScaleVertical) {
double toScroll = 1.0 + (e.getUnitsToScroll() / 100.0);
double scale = (toScroll > 0 ? 1.0 / toScroll : toScroll);
if (scale >= 0 && scale <= 1000) {
zoom(1, (float) scale, e.getPoint());
}
} else if (doScaleBoth) {
double toScroll = 1.0 + (e.getUnitsToScroll() / 100.0);
double scale = (toScroll > 0 ? 1.0 / toScroll : toScroll);
if (scale >= 0 && scale <= 1000) {
zoom((float) scale, (float) scale, e.getPoint());
}
} else if (doScrollHorizontal) {
getScrollPane().getHorizontalScrollBar().setValue(getScrollPane().getHorizontalScrollBar().getValue() + e.getUnitsToScroll());
} else if (doScaleHorizontal && !xyLocked) { //scale
double toScroll = 1.0 + (e.getUnitsToScroll() / 100.0);
double scale = (toScroll > 0 ? 1.0 / toScroll : toScroll);
if (scale >= 0 && scale <= 1000) {
zoom((float) scale, 1, e.getPoint());
}
} else if (doRotate) {
RadialSpaceFillingTreeDrawer drawer = (RadialSpaceFillingTreeDrawer) getChartDrawer();
drawer.setAngleOffset(drawer.getAngleOffset() + e.getUnitsToScroll());
drawer.repaint();
}
}
});
contentPanel.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
downX = me.getXOnScreen();
downY = me.getYOnScreen();
scrollPane.setCursor(Cursors.getOpenHand());
scrollPane.requestFocusInWindow();
}
public void mouseReleased(MouseEvent mouseEvent) {
scrollPane.setCursor(Cursor.getDefaultCursor());
}
public void mouseClicked(MouseEvent me) {
boolean changed = false;
if (!me.isControlDown() && !me.isShiftDown()) { // deselect all
if (getChartSelection().getSelectedSeries().size() > 0 || getChartSelection().getSelectedClasses().size() > 0)
changed = true;
getChartSelection().clearSelectionSeries();
getChartSelection().clearSelectionClasses();
getChartDrawer().repaint();
}
if (me.getClickCount() == 2 && chartDrawer instanceof CoOccurrenceDrawer) {
changed = ((CoOccurrenceDrawer) chartDrawer).selectComponent(me);
} else if (chartDrawer.selectOnMouseDown(me, getChartSelection()))
changed = true;
if (changed) {
updateView(IDirector.ENABLE_STATE);
seriesList.ensureSelectedIsVisible();
classesList.ensureSelectedIsVisible();
attributesList.ensureSelectedIsVisible();
}
}
});
contentPanel.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent me) {
if (me.isPopupTrigger())
return;
JScrollPane scrollPane = getScrollPane();
scrollPane.setCursor(Cursors.getClosedHand());
int dX = me.getXOnScreen() - downX;
int dY = me.getYOnScreen() - downY;
if (dY != 0) {
JScrollBar scrollBar = scrollPane.getVerticalScrollBar();
scrollBar.setValue(scrollBar.getValue() - dY);
}
if (dX != 0) {
JScrollBar scrollBar = scrollPane.getHorizontalScrollBar();
scrollBar.setValue(scrollBar.getValue() - dX);
}
downX = me.getXOnScreen();
downY = me.getYOnScreen();
}
public void mouseMoved(MouseEvent mouseEvent) {
final String[] seriesClassAttribute = getChartDrawer().getItemBelowMouse(mouseEvent, getChartSelection());
StringBuilder label = new StringBuilder();
if (seriesClassAttribute != null) {
for (String str : seriesClassAttribute) {
if (str != null) {
if (label.length() == 0)
label = new StringBuilder(str);
else
label.append(", ").append(str);
}
}
}
ChartViewer.this.getContentPanel().setToolTipText(label.toString());
mainPanel.setToolTipText(label.toString());
}
});
scrollPane = new JScrollPane(contentPanel);
scrollPane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
scrollPane.setWheelScrollingEnabled(false);
scrollPane.setAutoscrolls(true);
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(scrollPane, BorderLayout.CENTER);
legendPanel = new LegendPanel(this);
legendPanel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
boolean changed = false;
if (!me.isShiftDown()) {
getChartSelection().clearSelectionSeries();
getChartSelection().clearSelectionClasses();
changed = true;
}
if (selectByMouseInLegendPanel(legendPanel, me.getPoint(), getChartSelection())) {
changed = true;
}
if (changed)
updateView(IDirector.ENABLE_STATE);
}
});
legendScrollPane = new JScrollPane(legendPanel);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, mainPanel, legendScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setEnabled(true);
splitPane.setResizeWeight(1.0);
splitPane.setDividerLocation(1.0);
splitPane.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent componentEvent) {
legendPanel.updateView();
if (getShowLegend().equals("none"))
splitPane.setDividerLocation(1.0);
}
});
horizontalSP.setRightComponent(splitPane);
getContentPane().add(horizontalSP);
if (chartData instanceof IChartData)
chooseDrawer(BarChartDrawer.NAME);
else
chooseDrawer(Plot2DDrawer.NAME);
statusbar = new StatusBar();
getContentPane().add(statusbar, BorderLayout.SOUTH);
contentPanel.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
if (me.isPopupTrigger()) {
final PopupMenu menu = new PopupMenu(this, GUIConfiguration.getMainPanelPopupConfiguration(), commandManager);
if (popupMenuModifier != null)
popupMenuModifier.apply(menu, commandManager);
menu.show(contentPanel, me.getX(), me.getY());
}
}
public void mouseReleased(MouseEvent me) {
if (me.isPopupTrigger()) {
final PopupMenu menu = new PopupMenu(this, GUIConfiguration.getMainPanelPopupConfiguration(), commandManager);
if (popupMenuModifier != null)
popupMenuModifier.apply(menu, commandManager);
menu.show(contentPanel, me.getX(), me.getY());
}
}
});
legendPanel.setPopupMenu(new PopupMenu(this, GUIConfiguration.getLegendPanelPopupConfiguration(), commandManager));
addWindowListener(new WindowListenerAdapter() {
public void windowDeactivated(WindowEvent event) {
ProjectManager.getPreviouslySelectedNodeLabels().clear();
final int i = listsTabbedPane.getSelectedIndex();
if (i == seriesList.getTabIndex()) {
ProjectManager.getPreviouslySelectedNodeLabels().addAll(getChartSelection().getSelectedSeries());
} else if (i == classesList.getTabIndex()) {
ProjectManager.getPreviouslySelectedNodeLabels().addAll(getChartSelection().getSelectedClasses());
} else if (i == attributesList.getTabIndex()) {
ProjectManager.getPreviouslySelectedNodeLabels().addAll(getChartSelection().getSelectedAttributes());
}
}
});
pack();
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
splitPane.setDividerLocation(1.0);
}
public ChartColorManager getChartColorManager() {
return dir.getDocument().getChartColorManager();
}
/**
* performs selection in legend panel
*
* @return true if something changed
*/
private boolean selectByMouseInLegendPanel(LegendPanel legendPanel, Point point, ChartSelection chartSelection) {
SelectionGraphics<String[]> selectionGraphics = new SelectionGraphics<>(getGraphics());
selectionGraphics.setMouseLocation(point);
legendPanel.paint(selectionGraphics);
Set<String> seriesToSelect = new HashSet<>();
Set<String> classesToSelect = new HashSet<>();
for (String[] pair : selectionGraphics.getSelectedItems()) {
if (pair[0] != null) {
seriesToSelect.add(pair[0]);
}
if (pair[1] != null) {
classesToSelect.add(pair[1]);
}
}
if (seriesToSelect.size() > 0)
chartSelection.setSelectedSeries(seriesToSelect, true);
if (classesToSelect.size() > 0)
chartSelection.setSelectedClass(classesToSelect, true);
return seriesToSelect.size() > 0 || classesToSelect.size() > 0;
}
public void zoomToFit() {
Dimension size = new Dimension(100, 100);
contentPanel.setSize(size);
contentPanel.setPreferredSize(size);
getContentPane().validate();
}
/**
* zoom in or out (making panel larger or smaller)
*
*/
public void zoom(float factorX, float factorY, Point center) {
if (getChartDrawer().isXYLocked()) {
if (factorX == 1)
factorX = factorY; // yes. ok
else if (factorY == 1)
factorY = factorX;
}
if (getChartDrawer().getScrollBackReferenceRect() != null) {
if (center == null)
center = new Point((int) contentPanel.getBounds().getCenterX(), (int) contentPanel.getBounds().getCenterY());
getChartDrawer().setScrollBackWindowPoint(center);
getChartDrawer().setScrollBackReferencePoint(getChartDrawer().convertWindowToReference(center));
}
Dimension size = contentPanel.getSize();
int newWidth = Math.max(100, (Math.round(factorX * size.width)));
int newHeight = Math.max(100, (Math.round(factorY * size.height)));
size = new Dimension(newWidth, newHeight);
contentPanel.setSize(size);
contentPanel.setPreferredSize(size);
contentPanel.validate();
updateScrollPane();
}
/**
* update scroll pane after zoom to keep centered on mouse position
*
*/
private void updateScrollPane() {
if (chartDrawer.getScrollBackReferenceRect() != null) {
chartDrawer.computeScrollBackReferenceRect();
if (chartDrawer.getScrollBackReferencePoint() != null && chartDrawer.getScrollBackWindowPoint() != null) {
Point2D apt = chartDrawer.convertReferenceToWindow(chartDrawer.getScrollBackReferencePoint());
int scrollX = (int) Math.round(apt.getX() - chartDrawer.getScrollBackWindowPoint().getX());
int scrollY = (int) Math.round(apt.getY() - chartDrawer.getScrollBackWindowPoint().getY());
chartDrawer.setScrollBackReferencePoint(null);
chartDrawer.setScrollBackWindowPoint(null);
if (scrollX != 0) {
scrollPane.getHorizontalScrollBar().setValue(scrollPane.getHorizontalScrollBar().getValue() + scrollX);
}
if (scrollY != 0) {
scrollPane.getVerticalScrollBar().setValue(scrollPane.getVerticalScrollBar().getValue() + scrollY);
}
}
}
}
/**
* is viewer uptodate?
*
* @return uptodate
*/
public boolean isUptoDate() {
return isUptoDate;
}
/**
* return the frame associated with the viewer
*
* @return frame
*/
public JFrame getFrame() {
return this;
}
/**
* gets the associated command manager
*
* @return command manager
*/
public CommandManager getCommandManager() {
return commandManager;
}
/**
* ask view to update itself. This is method is wrapped into a runnable object
* and put in the swing event queue to avoid concurrent modifications.
*
* @param what what should be updated? Possible values: Director.ALL or Director.TITLE
*/
public void updateView(String what) {
if (!(what.equals(IDirector.ENABLE_STATE) || what.equals(IDirector.TITLE))) {
if (getChartColorManager().isColorByPosition()) {
getChartColorManager().setClassColorPositions(classesList.getEnabledLabels());
}
chartDrawer.updateView();
}
if (chartDrawer instanceof CoOccurrenceDrawer) {
Set<String> visibleLabels = ((CoOccurrenceDrawer) chartDrawer).getAllVisibleLabels();
if (transpose) {
final Set<String> toDisable = new HashSet<>(seriesList.getAllLabels());
toDisable.removeAll(visibleLabels);
seriesList.disableLabels(toDisable);
} else {
final Set<String> toDisable = new HashSet<>(classesList.getAllLabels());
toDisable.removeAll(visibleLabels);
classesList.disableLabels(toDisable);
}
}
if (chartDrawer instanceof BarChartDrawer) {
((BarChartDrawer) chartDrawer).setGapBetweenBars(showGapsBetweenBars);
((BarChartDrawer) chartDrawer).setShowVerticalGridLines(showVerticalGridLines);
}
if (chartData.getNumberOfSeries() <= 1) {
if (firstUpdate) {
firstUpdate = false;
}
}
attributesList.setEnabled(chartDrawer.canAttributes());
final FindToolBar findToolBar = searchManager.getFindDialogAsToolBar();
if (listsTabbedPane.getSelectedIndex() == seriesList.getTabIndex())
searchManager.setSearcher(seriesList.getSearcher());
if (findToolBar.isClosing()) {
showFindToolBar = false;
findToolBar.setClosing(false);
}
if (!findToolBar.isEnabled() && showFindToolBar) {
mainPanel.add(findToolBar, BorderLayout.NORTH);
findToolBar.setEnabled(true);
getContentPane().validate();
} else if (findToolBar.isEnabled() && !showFindToolBar) {
mainPanel.remove(findToolBar);
findToolBar.setEnabled(false);
getContentPane().validate();
}
getCommandManager().updateEnableState();
if (findToolBar.isEnabled())
findToolBar.clearMessage();
if (chartData instanceof IChartData)
getStatusbar().setText2("Series=" + chartData.getNumberOfSeries() + " Classes=" + ((IChartData) chartData).getNumberOfClasses());
else
getStatusbar().setText2("Series=" + chartData.getNumberOfSeries());
if (chartDrawer.canAttributes() && attributesList.getAllLabels().size() > 0)
getStatusbar().setText2(getStatusbar().getText2() + " Attributes=" + attributesList.getAllLabels().size());
// todo: change to use only enabled attributes
if (getChartData().getNumberOfSeries() == 0 || getShowLegend().equals("none"))
splitPane.setDividerLocation(1.0);
legendPanel.updateView();
legendPanel.repaint();
setWindowTitle(windowTitle);
repaint();
}
/**
* ask view to prevent user input
*/
public void lockUserInput() {
locked = true;
statusbar.setText1("");
statusbar.setText2("Busy...");
searchManager.getFindDialogAsToolBar().setEnableCritical(false);
if (bottomToolBar != null)
bottomToolBar.setEnabled(false);
getCommandManager().setEnableCritical(false);
getJMenuBar().setEnableRecentFileMenuItems(false);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
/**
* ask view to allow user input
*/
public void unlockUserInput() {
locked = false;
getCommandManager().setEnableCritical(true);
searchManager.getFindDialogAsToolBar().setEnableCritical(true);
if (bottomToolBar != null)
bottomToolBar.setEnabled(true);
setCursor(Cursor.getDefaultCursor());
getContentPane().setCursor(Cursor.getDefaultCursor());
getJMenuBar().setEnableRecentFileMenuItems(true);
}
/**
* is viewer currently locked?
*
* @return true, if locked
*/
public boolean isLocked() {
return locked;
}
/**
* ask view to destroy itself
*/
public void destroyView() throws CanceledException {
ProgramProperties.put(MeganProperties.CHART_WINDOW_GEOMETRY, new int[]{
getLocation().x, getLocation().y, getSize().width, getSize().height});
MeganProperties.removePropertiesListListener(getJMenuBar().getRecentFilesListener());
executorService.shutdownNow();
boolean ok = false;
try {
ok = executorService.awaitTermination(2, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (!ok)
NotificationsInSwing.showInternalError(getFrame(), "Failed to terminate runaway threads... (consider restarting MEGAN)");
getChartDrawer().close();
if (searchManager != null && searchManager.getFindDialogAsToolBar() != null)
searchManager.getFindDialogAsToolBar().close();
dir.removeViewer(this);
dispose();
}
protected void setWindowTitle(String title) {
windowTitle = title;
String newTitle = windowTitle + " - " + dir.getDocument().getTitle();
if (dir.getDocument().isDirty())
newTitle += "*";
if (dir.getID() == 1)
newTitle += " - " + ProgramProperties.getProgramVersion();
else
newTitle += " - [" + dir.getID() + "] - " + ProgramProperties.getProgramVersion();
if (!getTitle().equals(newTitle)) {
super.setTitle(newTitle);
ProjectManager.updateWindowMenus();
}
}
public String getWindowTitle() {
return windowTitle;
}
public String getChartTitle() {
return chartTitle;
}
public void setChartTitle(String chartTitle) {
this.chartTitle = chartTitle;
chartDrawer.setChartTitle(chartTitle);
}
/**
* set uptodate state
*
*/
public void setUptoDate(boolean flag) {
isUptoDate = flag;
}
public boolean isShowFindToolBar() {
return showFindToolBar;
}
public void setShowFindToolBar(boolean show) {
this.showFindToolBar = show;
}
public SearchManager getSearchManager() {
return searchManager;
}
public IChartDrawer getChartDrawer() {
return chartDrawer;
}
private void setChartDrawer(IChartDrawer chartDrawer) {
if (bottomToolBar != null) {
mainPanel.remove(bottomToolBar);
bottomToolBar = null;
}
this.chartDrawer = chartDrawer;
setPopupMenuModifier(chartDrawer.getPopupMenuModifier());
contentPanel.removeAll();
contentPanel.add(chartDrawer.getJPanel());
contentPanel.revalidate();
}
public IData getChartData() {
return chartData;
}
public void chooseDrawer(String drawerType) {
if (!getChartDrawerName().equals(drawerType)) {
IChartDrawer drawer = name2DrawerInstance.get(drawerType);
drawer.setViewer(this);
drawer.setChartData(chartData);
drawer.setClass2HigherClassMapper(class2HigherClassMapper);
drawer.setSeriesLabelGetter(seriesLabelGetter);
drawer.setExecutorService(executorService);
if (!drawer.canTranspose())
setTranspose(false);
if (drawer instanceof IMultiChartDrawable) {
drawer.setViewer(this);
drawer.setChartData(chartData);
drawer.setClass2HigherClassMapper(class2HigherClassMapper);
drawer.setSeriesLabelGetter(seriesLabelGetter);
setChartDrawer(new MultiChartDrawer((IMultiChartDrawable) drawer));
} else
setChartDrawer(drawer);
bottomToolBar = getChartDrawer().getBottomToolBar();
if (bottomToolBar != null)
mainPanel.add(bottomToolBar, BorderLayout.SOUTH);
for (String target : fonts.keySet()) {
Pair<Font, Color> pair = fonts.get(target);
chartDrawer.setFont(target, pair.getFirst(), pair.getSecond());
}
chartDrawer.setShowValues(showValues);
chartDrawer.setShowInternalLabels(showInternalLabels);
chartDrawer.setTranspose(transpose);
chartDrawer.setClassLabelAngle(classLabelAngle);
chartDrawer.setChartTitle(getChartTitle());
scalingType = chartDrawer.getScalingTypePreference();
chartDrawer.setScalingType(scalingType);
showXAxis = chartDrawer.getShowXAxisPreference();
showYAxis = chartDrawer.getShowYAxisPreference();
if (!getChartDrawer().canShowLegend())
setShowLegend("none");
}
//repaint();
}
public String getChartDrawerName() {
return chartDrawer != null ? chartDrawer.getChartDrawerName() : "None";
}
/**
* get name for this type of viewer
*
* @return name
*/
public String getClassName() {
return "ChartViewer";
}
protected StatusBar getStatusbar() {
return statusbar;
}
public int print(Graphics gc0, PageFormat format, int pagenumber) {
if (pagenumber == 0) {
Graphics2D gc = ((Graphics2D) gc0);
gc.setFont(getFont());
Dimension dim = contentPanel.getSize();
int image_w = dim.width;
int image_h = dim.height;
double paper_x = format.getImageableX() + 1;
double paper_y = format.getImageableY() + 1;
double paper_w = format.getImageableWidth() - 2;
double paper_h = format.getImageableHeight() - 2;
double scale_x = paper_w / image_w;
double scale_y = paper_h / image_h;
double scale = Math.min(scale_x, scale_y);
double shift_x = paper_x + (paper_w - scale * image_w) / 2.0;
double shift_y = paper_y + (paper_h - scale * image_h) / 2.0;
gc.translate(shift_x, shift_y);
gc.scale(scale, scale);
gc.setStroke(new BasicStroke(1.0f));
gc.setColor(Color.BLACK);
contentPanel.paint(gc);
return Printable.PAGE_EXISTS;
} else
return Printable.NO_SUCH_PAGE;
}
protected ToolBar getToolbar() {
return toolbar;
}
public boolean isShowValues() {
return showValues;
}
public void setShowValues(boolean showValues) {
if (chartDrawer != null)
chartDrawer.setShowValues(showValues);
this.showValues = showValues;
}
public boolean isShowInternalLabels() {
return showInternalLabels;
}
public void setShowInternalLabels(boolean showInternalLabels) {
if (chartDrawer != null)
chartDrawer.setShowInternalLabels(showInternalLabels);
this.showInternalLabels = showInternalLabels;
}
public JPanel getContentPanel() {
return contentPanel;
}
public JScrollPane getScrollPane() {
return scrollPane;
}
public boolean isTranspose() {
return transpose;
}
public void setTranspose(boolean transpose) {
if (chartDrawer != null)
chartDrawer.setTranspose(transpose);
this.transpose = transpose;
}
public double getClassLabelAngle() {
return classLabelAngle;
}
public void setClassLabelAngle(double classLabelAngle) {
if (chartDrawer != null)
chartDrawer.setClassLabelAngle(classLabelAngle);
this.classLabelAngle = classLabelAngle;
}
public ScalingType getScalingType() {
return scalingType;
}
public void setScalingType(ScalingType scalingType) {
if (chartDrawer != null)
chartDrawer.setScalingType(scalingType);
this.scalingType = scalingType;
}
public MenuBar getJMenuBar() {
return jMenuBar;
}
/**
* synchronize data
*/
public void sync() throws CanceledException {
getChartDrawer().forceUpdate();
seriesList.sync(getChartData().getSeriesNames(), getChartData().getSamplesTooltips(), false);
if (getChartData() instanceof IChartData) {
classesList.sync(((IChartData) getChartData()).getClassNames(), getChartData().getClassesTooltips(), false);
classesList.fireSyncToViewer();
}
attributesList.sync(getDir().getDocument().getSampleAttributeTable().getNumericalAttributes(), null, false);
}
/**
* gets the active labels list
*
* @return active labels list
*/
public LabelsJList getActiveLabelsJList() {
if (listsTabbedPane != null && listsTabbedPane.getSelectedComponent() != null) {
JViewport viewport = ((JViewport) ((JScrollPane) listsTabbedPane.getSelectedComponent()).getComponent(0));
if (viewport != null)
return (LabelsJList) viewport.getComponent(0);
}
return getSeriesList();
}
public LabelsJList getLabelsJList(String name) {
return switch (name.toLowerCase()) {
case "attributes" -> getAttributesList();
case "classes" -> getClassesList();
default /* case "series" */ -> getSeriesList();
};
}
public SeriesList getSeriesList() {
return seriesList;
}
public ClassesList getClassesList() {
return classesList;
}
public AttributesList getAttributesList() {
return attributesList;
}
public boolean isShowXAxis() {
return showXAxis;
}
public void setShowXAxis(boolean showXAxis) {
chartDrawer.setShowXAxis(showXAxis);
this.showXAxis = showXAxis;
}
public boolean isShowYAxis() {
return showYAxis;
}
public void setShowYAxis(boolean showYAxis) {
chartDrawer.setShowYAxis(showYAxis);
this.showYAxis = showYAxis;
}
public void setUseRectangleShape(boolean useRectangleShape) {
if (getChartDrawer() instanceof WordCloudDrawer) {
WordCloudDrawer drawer = (WordCloudDrawer) getChartDrawer();
drawer.setUseRectangleShape(useRectangleShape);
} else if (getChartDrawer() instanceof MultiChartDrawer && ((MultiChartDrawer) getChartDrawer()).getBaseDrawer() instanceof WordCloudDrawer) {
final MultiChartDrawer drawer = (MultiChartDrawer) getChartDrawer();
((WordCloudDrawer) drawer.getBaseDrawer()).setUseRectangleShape(useRectangleShape);
}
this.useRectangleShape = useRectangleShape;
}
public boolean isUseRectangleShape() {
return useRectangleShape;
}
public ChartSelection getChartSelection() {
return chartData.getChartSelection();
}
public Label2LabelMapper getClass2HigherClassMapper() {
return class2HigherClassMapper;
}
public void setFont(String target, Font font, Color color) {
fonts.put(target, new Pair<>(font, color));
chartDrawer.setFont(target, font, color);
}
public Font getFont(String target) {
Pair<Font, Color> pair = fonts.get(target);
if (pair == null || pair.getFirst() == null)
return getFont();
else
return pair.getFirst();
}
/**
* gets the series color getter
*
* @return series color getter
*/
public ChartColorManager.ColorGetter getSeriesColorGetter() {
return new ChartColorManager.ColorGetter() {
private final ChartColorManager.ColorGetter colorGetter = getChartColorManager().getSeriesColorGetter();
public Color get(String label) {
if (transpose && getChartData().getNumberOfSeries() == 1 && getChartDrawerName().equals(BarChartDrawer.NAME))
return Color.WHITE;
if ((!transpose || (chartDrawer instanceof HeatMapDrawer)) && !(chartDrawer instanceof Plot2DDrawer))
return Color.WHITE;
else
return colorGetter.get(label);
}
};
}
/**
* gets the class color getter
*
* @return class color getter
*/
public ChartColorManager.ColorGetter getClassColorGetter() {
return new ChartColorManager.ColorGetter() {
private final ChartColorManager.ColorGetter colorGetter = getChartColorManager().getClassColorGetter();
public Color get(String label) {
label = class2HigherClassMapper.get(label);
if (transpose && getChartData().getNumberOfSeries() == 1 && getChartDrawerName().equals(BarChartDrawer.NAME))
return colorGetter.get(label);
if (transpose || (chartDrawer instanceof HeatMapDrawer))
return Color.WHITE;
else {
return colorGetter.get(label);
}
}
};
}
public ILabelGetter getSeriesLabelGetter() {
return seriesLabelGetter;
}
public LegendPanel getLegendPanel() {
return legendPanel;
}
public JScrollPane getLegendScrollPane() {
return legendScrollPane;
}
/**
* show the legend horizontal, vertical or none
*
*/
public void setShowLegend(String showLegend) {
this.showLegend = showLegend;
if (showLegend.equalsIgnoreCase("horizontal")) {
splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
Dimension size = new Dimension();
splitPane.validate();
legendPanel.setSize(splitPane.getWidth(), 50);
legendPanel.draw((Graphics2D) legendPanel.getGraphics(), size);
int height = (int) size.getHeight() + 10;
legendPanel.setPreferredSize(new Dimension(splitPane.getWidth(), height));
legendPanel.validate();
splitPane.setDividerLocation(splitPane.getSize().height - splitPane.getInsets().right - splitPane.getDividerSize() - height);
} else if (showLegend.equalsIgnoreCase("vertical")) {
splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
Dimension size = new Dimension();
splitPane.validate();
legendPanel.setSize(20, splitPane.getHeight());
legendPanel.draw((Graphics2D) legendPanel.getGraphics(), size);
int width = (int) size.getWidth() + 5;
legendPanel.setPreferredSize(new Dimension(width, splitPane.getHeight()));
legendPanel.validate();
splitPane.setDividerLocation(splitPane.getSize().width - splitPane.getInsets().right - splitPane.getDividerSize() - width);
} else {
splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
splitPane.setDividerLocation(1.0);
}
}
public String getShowLegend() {
return showLegend;
}
public Point getZoomCenter() {
Rectangle rect = getFrame().getBounds();
return new Point((int) rect.getCenterX() - rect.x + getScrollPane().getViewport().getViewPosition().x, (int) rect.getCenterY() - rect.y + getScrollPane().getViewport().getViewPosition().y);
}
public Director getDir() {
return dir;
}
public Collection<String> getChartDrawerNames() {
return name2DrawerInstance.keySet();
}
public boolean isShowGapsBetweenBars() {
return showGapsBetweenBars;
}
public void setShowGapsBetweenBars(boolean showGapsBetweenBars) {
this.showGapsBetweenBars = showGapsBetweenBars;
ProgramProperties.put("ChartShowGapsBetweenBars", showGapsBetweenBars);
}
public boolean isShowVerticalGridLines() {
return showVerticalGridLines;
}
public void setShowVerticalGridLines(boolean showVerticalGridLines) {
this.showVerticalGridLines = showVerticalGridLines;
ProgramProperties.put("ChartShowVerticalGridLines", showVerticalGridLines);
}
public IPopupMenuModifier getPopupMenuModifier() {
return popupMenuModifier;
}
private void setPopupMenuModifier(IPopupMenuModifier popupMenuModifier) {
this.popupMenuModifier = popupMenuModifier;
}
public IDirectableViewer getParentViewer() {
return parentViewer;
}
public boolean isSeriesTabSelected() {
return seriesList != null && listsTabbedPane.getSelectedIndex() == seriesList.getTabIndex();
}
@Override
public boolean useHeatMapColors() {
return getChartDrawer().usesHeatMapColors();
}
}
| 44,971 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
RedGradient.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/gui/RedGradient.java | /*
* RedGradient.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.gui;
import java.awt.*;
/**
* a red color gradient
* Daniel Huson, 6.2015
*/
public class RedGradient {
static private final Color separatorColor = new Color(255, 200, 200);
private final int maxCount;
private final double factor;
/**
* setup the green gradient
*
*/
public RedGradient(int maxCount) {
this.maxCount = maxCount;
factor = maxCount / Math.log(maxCount);
}
/**
* get color on linear scale
*
* @return color
*/
private Color getColor(int count) {
if (maxCount == 0)
return Color.WHITE;
if (count > maxCount)
count = maxCount;
int scaled = Math.min(255, (int) Math.round(255.0 / maxCount * count));
if (count > 0)
scaled = Math.max(1, scaled);
return new Color(255, 255 - scaled, 255 - scaled);
}
/**
* get color on log scale
*
* @return color
*/
public Color getLogColor(int count) {
int value = (int) Math.max(0, (Math.round(factor * Math.log(count))));
if (count > 0)
value = Math.max(1, value);
return getColor(value);
}
/**
* get border color used to separate different regions
*
* @return separator color
*/
public static Color getSeparatorColor() {
return separatorColor;
}
/**
* gets the max count
*
* @return max count
*/
public int getMaxCount() {
return maxCount;
}
/**
* this is used in the node drawer of the main viewer
*
* @return color on a log scale
*/
public static Color getColorLogScale(int count, double inverseLogMaxReads) {
int value = (count <= 0 ? 0 : Math.min(255, Math.max(1, (int) Math.round(255.0 * Math.log(count + 1) * inverseLogMaxReads))));
if (count > 0 && value < 1)
value = 1;
return new Color(255, 255 - value, 255 - value);
}
/**
* this is used in the node drawer of the main viewer
*
* @return color on a log scale
*/
public static Color getColorSqrtScale(int count, double inverseSqrtMaxReads) {
int value = (count <= 0 ? 0 : Math.min(255, Math.max(1, (int) Math.round(255.0 * Math.sqrt(count) * inverseSqrtMaxReads))));
if (count > 0 && value < 1)
value = 1;
return new Color(255, 255 - value, 255 - value);
}
/**
* get color on linear scale
*
* @return color
*/
public static Color getColor(int count, int maxCount) {
int value = (count <= 0 ? 0 : Math.min(255, Math.max(1, (int) Math.round(255.0 * count / (double) maxCount))));
if (count > 0 && value < 1)
value = 1;
return new Color(255, 255 - value, 255 - value);
}
}
| 3,628 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
AttributesList.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/gui/AttributesList.java | /*
* AttributesList.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.gui;
import jloda.swing.util.ListTransferHandler;
import jloda.swing.util.PopupMenu;
import megan.chart.ChartColorManager;
import javax.swing.*;
/**
* side by list for attributes
* Created by huson on 9/18/16.
*/
public class AttributesList extends LabelsJList {
private final ChartSelection chartSelection;
/**
* constructor
*
*/
public AttributesList(final ChartViewer viewer) {
super(viewer, createSyncListenerAttributesList(viewer), createPopupMenu(viewer));
this.chartSelection = viewer.getChartSelection();
setName("Attributes");
addListSelectionListener(listSelectionEvent -> {
if (!inSelection) {
inSelection = true;
try {
chartSelection.clearSelectionAttributes();
chartSelection.setSelectedAttribute(getSelectedLabels(), true);
} finally {
inSelection = false;
}
}
});
setDragEnabled(true);
setTransferHandler(new ListTransferHandler());
chartSelection.addAttributesSelectionListener(chartSelection -> {
if (!inSelection) {
inSelection = true;
try {
DefaultListModel model = (DefaultListModel) getModel();
for (int i = 0; i < model.getSize(); i++) {
String name = getModel().getElementAt(i);
if (chartSelection.isSelectedAttribute(name))
addSelectionInterval(i, i + 1);
else
removeSelectionInterval(i, i + 1);
}
} finally {
inSelection = false;
}
}
});
}
/**
* call this when tab containing list is activated
*/
public void activate() {
getViewer().getSearchManager().setSearcher(getSearcher());
getViewer().getSearchManager().getFindDialogAsToolBar().clearMessage();
if (!inSelection) {
inSelection = true;
try {
chartSelection.clearSelectionAttributes();
chartSelection.setSelectedAttribute(getSelectedLabels(), true);
this.repaint(); // todo: or viewer.repaint() ??
} finally {
inSelection = false;
}
}
}
/**
* call this when tab containing list is deactivated
*/
public void deactivate() {
if (!inSelection) {
inSelection = true;
try {
chartSelection.clearSelectionAttributes();
this.repaint(); // todo: or viewer.repaint() ??
} finally {
inSelection = false;
}
}
}
private ChartViewer getViewer() {
return (ChartViewer) viewer;
}
public ChartColorManager.ColorGetter getColorGetter() {
return getViewer().getDir().getDocument().getChartColorManager().getAttributeColorGetter();
}
private static SyncListener createSyncListenerAttributesList(final ChartViewer viewer) {
return enabledNames -> {
if (viewer.getChartDrawer().canAttributes()) {
viewer.getChartDrawer().forceUpdate();
}
};
}
private static PopupMenu createPopupMenu(ChartViewer viewer) {
return new PopupMenu(null, GUIConfiguration.getAttributesListPopupConfiguration(), viewer.getCommandManager());
}
}
| 4,384 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IChartSelectionListener.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/gui/IChartSelectionListener.java | /*
* IChartSelectionListener.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.gui;
/**
* listens for changes of selection state
* Daniel Huson, 7.2012
*/
interface IChartSelectionListener {
void selectionChanged(ChartSelection chartSelection);
}
| 1,015 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
LegendPanel.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/gui/LegendPanel.java | /*
* LegendPanel.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.gui;
import jloda.swing.util.BasicSwing;
import megan.chart.data.IChartData;
import megan.chart.data.IPlot2DData;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* the panel that contains the legend
* Daniel Huson, 3.2013
*/
public class LegendPanel extends JPanel {
private final ChartViewer chartViewer;
private JPopupMenu popupMenu = null;
/**
* constructor
*
*/
public LegendPanel(ChartViewer chartViewer) {
this.chartViewer = chartViewer;
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent mouseEvent) {
if (mouseEvent.isPopupTrigger() && popupMenu != null)
popupMenu.show(LegendPanel.this, mouseEvent.getX(), mouseEvent.getY());
}
public void mouseReleased(MouseEvent mouseEvent) {
if (mouseEvent.isPopupTrigger() && popupMenu != null)
popupMenu.show(LegendPanel.this, mouseEvent.getX(), mouseEvent.getY());
}
});
}
public void setPopupMenu(JPopupMenu popupMenu) {
this.popupMenu = popupMenu;
}
/**
* draw the legend
*
*/
public void paint(Graphics gc0) {
Graphics2D gc = (Graphics2D) gc0;
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
if (sgc == null) {
super.paint(gc);
gc.setColor(Color.WHITE);
gc.fill(getVisibleRect());
}
draw(gc, null);
}
/**
* update the view
*/
public void updateView() {
Graphics2D gc = (Graphics2D) getGraphics();
Dimension size = new Dimension();
draw(gc, size);
setPreferredSize(size);
revalidate();
}
/**
* draw the legend
*
*/
void draw(Graphics2D gc, Dimension size) {
if (!chartViewer.isTranspose())
drawLegend(gc, size);
else
drawLegendTransposed(gc, size);
}
/**
* draw a legend for class colors
*
*/
private void drawLegend(Graphics2D gc, Dimension size) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
boolean doDraw = (size == null);
if (chartViewer.getChartData() instanceof IChartData) {
boolean vertical = chartViewer.getShowLegend().equals("vertical");
gc.setFont(chartViewer.getChartDrawer().getFont(ChartViewer.FontKeys.LegendFont.toString()));
int yStart = getFont().getSize();
int x = 3;
int maxX = x;
{
String legend;
if (chartViewer.getChartData().getClassesLabel() != null)
legend = "Legend (" + chartViewer.getChartData().getClassesLabel() + "):";
else
legend = "Legend:";
if (doDraw) {
gc.setColor(Color.BLACK);
gc.drawString(legend, x, yStart);
}
Dimension labelSize = BasicSwing.getStringSize(gc, legend, gc.getFont()).getSize();
maxX = Math.max(maxX, labelSize.width);
}
int y = yStart + (int) (1.5 * gc.getFont().getSize());
for (String className : ((IChartData) chartViewer.getChartData()).getClassNames()) {
Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize();
if (x + 12 + labelSize.width + 2 > getWidth() || vertical) {
x = 2;
y += 1.5 * gc.getFont().getSize();
}
if (doDraw) {
Color color = chartViewer.getChartColorManager().getClassColor(chartViewer.getClass2HigherClassMapper().get(className));
gc.setColor(color);
if (sgc != null)
sgc.setCurrentItem(new String[]{null, className});
gc.fillRect(x, y - labelSize.height, labelSize.height, labelSize.height);
gc.setColor(color.darker());
gc.drawRect(x, y - labelSize.height, labelSize.height, labelSize.height);
gc.setColor(chartViewer.getChartDrawer().getFontColor(ChartViewer.FontKeys.LegendFont.toString(), Color.BLACK));
gc.drawString(className, x + labelSize.height + 2, y);
if (sgc != null)
sgc.clearCurrentItem();
}
maxX = Math.max(maxX, x);
x += labelSize.height + 2 + labelSize.width + 10;
if (vertical)
maxX = Math.max(maxX, x);
}
if (!doDraw) {
size.setSize(maxX, y + 5);
}
} else if (chartViewer.getChartData() instanceof IPlot2DData) {
boolean vertical = chartViewer.getShowLegend().equals("vertical");
int yStart = getFont().getSize();
int x = 3;
int maxX = x;
if (doDraw) {
String legend = "Legend (samples):";
gc.setColor(Color.BLACK);
gc.drawString(legend, x, yStart);
Dimension labelSize = BasicSwing.getStringSize(gc, legend, gc.getFont()).getSize();
maxX = Math.max(maxX, labelSize.width);
}
int y = yStart + (int) (1.5 * gc.getFont().getSize());
for (String sampleName : chartViewer.getChartData().getSeriesNames()) {
String label = chartViewer.getSeriesLabelGetter().getLabel(sampleName);
if (!label.equals(sampleName))
label += " (" + sampleName + ")";
final Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
if (x + 12 + labelSize.width + 2 > getWidth() || vertical) {
x = 3;
y += 1.5 * gc.getFont().getSize();
}
if (doDraw) {
Color color = chartViewer.getChartColorManager().getSampleColor(sampleName);
gc.setColor(color);
if (sgc != null)
sgc.setCurrentItem(new String[]{sampleName, null});
gc.fillRect(x, y - labelSize.height, labelSize.height, labelSize.height);
gc.setColor(color.darker());
gc.drawRect(x, y - labelSize.height, labelSize.height, labelSize.height);
gc.setColor(chartViewer.getChartDrawer().getFontColor(ChartViewer.FontKeys.LegendFont.toString(), Color.BLACK));
gc.drawString(label, x + labelSize.height + 2, y);
if (sgc != null)
sgc.clearCurrentItem();
}
maxX = Math.max(maxX, x);
x += labelSize.height + 2 + labelSize.width + 10;
if (vertical)
maxX = Math.max(maxX, x);
}
if (!doDraw) {
size.setSize(maxX, y + 5);
}
}
}
/**
* draw a legend for dataset colors
*
*/
private void drawLegendTransposed(Graphics2D gc, Dimension size) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
boolean vertical = chartViewer.getShowLegend().equals("vertical");
try {
gc.setFont(chartViewer.getFont(ChartViewer.FontKeys.LegendFont.toString()));
} catch (Exception ignored) {
}
boolean doDraw = (size == null);
int yStart = getFont().getSize();
int x = 3;
int maxX = x;
if (doDraw) {
String legend;
if (chartViewer.getChartData().getSeriesLabel() != null)
legend = "Legend (" + chartViewer.getChartData().getSeriesLabel() + "):";
else
legend = "Legend:";
gc.setColor(Color.BLACK);
gc.drawString(legend, x, yStart);
Dimension labelSize = BasicSwing.getStringSize(gc, legend, gc.getFont()).getSize();
maxX = Math.max(maxX, labelSize.width);
}
int y = yStart + (int) (1.5 * gc.getFont().getSize());
for (String sampleName : chartViewer.getChartData().getSeriesNames()) {
String label = chartViewer.getSeriesLabelGetter().getLabel(sampleName);
if (!label.equals(sampleName))
label += " (" + sampleName + ")";
final Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
if (x + 12 + labelSize.width + 2 > getWidth() || vertical) {
x = 3;
y += 1.5 * gc.getFont().getSize();
}
if (doDraw) {
Color color = chartViewer.getChartColorManager().getSampleColor(sampleName);
gc.setColor(color);
if (sgc != null)
sgc.setCurrentItem(new String[]{sampleName, null});
gc.fillRect(x, y - labelSize.height, labelSize.height, labelSize.height);
gc.setColor(color.darker());
gc.drawRect(x, y - labelSize.height, labelSize.height, labelSize.height);
gc.setColor(chartViewer.getChartDrawer().getFontColor(ChartViewer.FontKeys.LegendFont.toString(), Color.BLACK));
gc.drawString(label, x + labelSize.height + 2, y);
if (sgc != null)
sgc.clearCurrentItem();
}
maxX = Math.max(maxX, x);
x += labelSize.height + 2 + labelSize.width + 10;
if (vertical)
maxX = Math.max(maxX, x);
}
if (!doDraw) {
size.setSize(maxX, y + 5);
}
}
}
| 10,784 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
GUIConfiguration.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/gui/GUIConfiguration.java | /*
* GUIConfiguration.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.gui;
import jloda.swing.window.MenuConfiguration;
import megan.chart.data.ChartCommandHelper;
import megan.classification.data.ClassificationCommandHelper;
/**
* configuration for menu and toolbar
* Daniel Huson, 7.2010
*/
public class GUIConfiguration {
/**
* get the menu configuration
*
* @return menu configuration
*/
public static MenuConfiguration getMenuConfiguration() {
MenuConfiguration menuConfig = new MenuConfiguration();
menuConfig.defineMenuBar("File;Edit;Options;Layout;Chart;Window;Help;");
menuConfig.defineMenu("File", "New...;|;Open...;@Open Recent;|;Open From Server...;|;Compare...;|;Import From BLAST...;@Import;Meganize DAA File...;|;Save As...;|;" +
"Export Image...;Export Legend...;Export Data...;|;Page Setup...;Print...;|;Close;|;Quit;");
menuConfig.defineMenu("Open Recent", ";");
menuConfig.defineMenu("Import", "Import Text (CSV) Format...;Import BIOM Format...;|;Import Metadata...;");
menuConfig.defineMenu("Edit", "Cut;Copy Label;Copy Image;Copy Legend;Paste;|;Select All;Select None;Select Top...;|;From Previous Window;|;Show All;Show Selected;|;" +
"Hide Unselected;Hide Selected;|;Set Color...;|;Find...;Find Again;|;Colors...;");
menuConfig.defineMenu("Options", "Set Title...;Set Series Label...;Set Classes Label...;Set Counts Label...;|;" +
"Linear Scale;Sqrt Scale;Log Scale;Percentage Scale;Z-Score Scale;|;Use Percent of Total;|;Cluster Series;Cluster Classes;Cluster Attributes;|;Grid Lines;Gaps Between Bars;");
menuConfig.defineMenu("Layout", "@Font;|;Show Legend;Show Values;|;Show x-Axis;Show y-Axis;|;Use Jitter;Rectangle Shape;Show Internal Labels;" +
"Set Max Radius...;|;Labels Standard;Labels Up 45o;Labels Down 45o;Labels Up 90o;Labels Down 90o;|;" +
"Expand Horizontal;Contract Horizontal;Expand Vertical;Contract Vertical;Zoom To Fit;|;Rotate Left;Rotate Right;|;Transpose;");
menuConfig.defineMenu("Font", "Title Font...;X-Axis Font...;Y-Axis Font...;Legend Font...;Values Font...;|;Draw Font...;");
menuConfig.defineMenu("Chart", ChartCommandHelper.getSetDrawerCommandString() + "|;Sync;");
menuConfig.defineMenu("Window", "Close All Other Windows...;|;Reset Window Location;Set Window Size...;|;Message Window...;|;" +
"Inspector Window...;|;Main Viewer...;" + ClassificationCommandHelper.getOpenViewerMenuString() + "|;Samples Viewer...;|;");
menuConfig.defineMenu("Help", "About...;How to Cite...;|;Community Website...;Reference Manual...;|;Check For Updates...;");
return menuConfig;
}
/**
* gets the toolbar configuration
*
* @return toolbar configuration
*/
public static String getToolBarConfiguration() {
return "Open...;Print...;Export Image...;|;Find...;|;" +
"Expand Vertical;Contract Vertical;Expand Horizontal;Contract Horizontal;|;Zoom To Fit;|;Transpose;Colors...;|;" +
ChartCommandHelper.getSetDrawerCommandString() + "|;" + "Linear Scale;Sqrt Scale;Log Scale;Percentage Scale;Z-Score Scale;|;" +
"Labels Standard;Labels Up 45o;Labels Down 45o;Labels Up 90o;Labels Down 90o;|;" +
"Main Viewer...;" + ClassificationCommandHelper.getOpenViewerMenuString() + "|;Samples Viewer...;Show Legend;|;";
}
/**
* gets the toolbar configuration
*
* @return toolbar configuration
*/
public static String getToolBar4DomainListConfiguration() {
return "Sort Alphabetically;Sort Alphabetically Backward;Sort By Values (Down);Sort By Values (Up);Group Enabled Entries;Cluster;";
}
public static String getMainPanelPopupConfiguration() {
return "Zoom To Fit;|;Copy Image;Export Image...;";
}
public static String getLegendPanelPopupConfiguration() {
return "Copy Legend;Export Legend...;";
}
public static String getSeriesListPopupConfiguration() {
return "Copy Label;|;Select All;Select None;|;Show Selected;Hide Selected;|;Show All;Hide All;|;Set Color...;";
}
public static String getClassesListPopupConfiguration() {
return "Copy Label;|;Select All;Select None;|;Show Selected;Hide Selected;|;Show All;Hide All;|;Set Color...;";
}
public static String getAttributesListPopupConfiguration() {
return "Copy Label;|;Select All;Select None;|;Show Selected;Hide Selected;|;Show All;Hide All;|;Set Color...;";
}
}
| 5,383 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
LabelsJList.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/gui/LabelsJList.java | /*
* LabelsJList.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.gui;
import jloda.swing.director.IDirectableViewer;
import jloda.swing.director.IDirector;
import jloda.swing.find.JListSearcher;
import jloda.swing.util.ListTransferHandler;
import jloda.swing.util.ProgramProperties;
import jloda.util.Basic;
import megan.chart.ChartColorManager;
import javax.swing.*;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.*;
/**
* labels JList
* Daniel Huson, 6.2012
*/
public class LabelsJList extends JList<String> {
final IDirectableViewer viewer;
private final JListSearcher searcher;
private boolean doClustering;
private int tabIndex = -1;
private boolean inSync = false;
private final JPopupMenu popupMenu;
private final Set<String> disabledLabels = new HashSet<>();
private Map<String, String> label2ToolTips;
private final SyncListener syncListener;
public boolean inSelection = false; // use this to avoid selection bounce
/**
* constructor
*
*/
public LabelsJList(final IDirectableViewer viewer, final SyncListener syncListener, final JPopupMenu popupMenu) {
super(new DefaultListModel<>());
this.viewer = viewer;
this.syncListener = syncListener;
this.popupMenu = popupMenu;
searcher = new JListSearcher(this);
setDragEnabled(true);
setTransferHandler(new ListTransferHandler());
getModel().addListDataListener(new ListDataListener() {
public void intervalAdded(ListDataEvent event) {
}
public void intervalRemoved(ListDataEvent event) {
if (!inSync) {
syncListener.syncList2Viewer(getEnabledLabels());
viewer.updateView(IDirector.ALL);
}
}
public void contentsChanged(ListDataEvent event) {
}
});
addListSelectionListener(event -> {
if (!inSync && !inSelection)
viewer.updateView("enable_state");
});
setCellRenderer(new MyCellRenderer());
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent me) {
int index = locationToIndex(me.getPoint());
if (getModel().getSize() > 0 && getCellBounds(index, index) != null
&& !getCellBounds(index, index).contains(me.getPoint())) {
clearSelection();
}
}
@Override
public void mousePressed(MouseEvent me) {
/*
if (getSelectedIndices().length == 0) {
JList list = (JList) me.getComponent();
int index = list.locationToIndex(me.getPoint());
setSelectedIndex(index);
}
*/
if (me.isPopupTrigger())
popup(me);
}
@Override
public void mouseReleased(MouseEvent me) {
if (me.isPopupTrigger())
popup(me);
}
void popup(MouseEvent me) {
if (LabelsJList.this.popupMenu != null) {
LabelsJList.this.popupMenu.show(LabelsJList.this, me.getX(), me.getY());
}
}
});
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent event) {
if (!viewer.isLocked()) {
int clicks = event.getClickCount();
if (clicks == 3) {
boolean changed = false;
int index = getSelectedIndex();
String label = ((DefaultListModel<?>) getModel()).get(index).toString();
String prefix5 = label.length() > 5 ? label.substring(0, 5) : label;
for (int i = 0; i < ((DefaultListModel<?>) getModel()).size(); i++) {
String item = ((DefaultListModel<?>) getModel()).getElementAt(i).toString();
if (!item.startsWith(prefix5)) {
disabledLabels.add(item);
changed = true;
} else {
if (disabledLabels.contains(item)) {
disabledLabels.remove(item);
changed = true;
}
}
}
if (changed) {
if (!inSync) {
syncListener.syncList2Viewer(getEnabledLabels());
viewer.updateView(IDirector.ALL);
}
}
} else if (clicks == 2) {
boolean changed = false;
int[] indices = getSelectedIndices();
boolean hasOneActive = false;
boolean hasOneInactive = false;
for (int element : indices) {
String label = ((DefaultListModel<?>) getModel()).getElementAt(element).toString();
if (disabledLabels.contains(label))
hasOneInactive = true;
else
hasOneActive = true;
if (hasOneActive && hasOneInactive)
break;
}
boolean enable = !hasOneActive || hasOneInactive;
for (int element : indices) {
String label = ((DefaultListModel<?>) getModel()).getElementAt(element).toString();
if (enable && disabledLabels.contains(label)) {
disabledLabels.remove(label);
changed = true;
} else if (!enable && !disabledLabels.contains(label)) {
disabledLabels.add(label);
changed = true;
}
}
if (changed) {
if (!inSync) {
if (!viewer.isLocked()) {
viewer.lockUserInput();
syncListener.syncList2Viewer(getEnabledLabels());
viewer.updateView(IDirector.ALL);
viewer.unlockUserInput();
}
}
}
}
}
}
});
setDoClustering(ProgramProperties.get(getName() + "DoClustering", doClustering));
}
public void ensureSelectedIsVisible() {
if (getSelectedIndices().length > 0) {
ensureIndexIsVisible(getSelectedIndex());
}
}
/**
* gets the tab index
*
* @return tab index
*/
public int getTabIndex() {
return tabIndex;
}
public void setTabIndex(int index) {
this.tabIndex = index;
}
/**
* get searcher
*
*/
public JListSearcher getSearcher() {
return searcher;
}
/**
* get all labels held by this list
*
* @return all labels
*/
public LinkedList<String> getAllLabels() {
final LinkedList<String> result = new LinkedList<>();
for (int i = 0; i < getModel().getSize(); i++) {
String label = getModel().getElementAt(i);
result.add(label);
}
return result;
}
public LinkedList<String> getSelectedLabels() {
final LinkedList<String> result = new LinkedList<>();
final DefaultListModel model = (DefaultListModel) getModel();
for (int i = 0; i < model.getSize(); i++) {
if (isSelectedIndex(i)) {
result.add(model.getElementAt(i).toString());
}
}
return result;
}
public void selectTop(int top) {
final DefaultListModel model = (DefaultListModel) getModel();
top = Math.min(top, model.getSize());
clearSelection();
if (top > 0)
setSelectionInterval(0, top - 1);
}
/**
* gets the list of enabled labels
*
* @return enabled labels
*/
public LinkedList<String> getEnabledLabels() {
final LinkedList<String> result = new LinkedList<>();
for (int i = 0; i < getModel().getSize(); i++) {
String label = getModel().getElementAt(i);
if (!disabledLabels.contains(label))
result.add(label);
}
return result;
}
/**
* get all the currently disabled labels
*
* @return disabled labels
*/
public LinkedList<String> getDisabledLabels() {
return new LinkedList<>(disabledLabels);
}
/**
* set the disabled labels
*
*/
public void setDisabledLabels(Collection<String> labels) {
disabledLabels.clear();
disabledLabels.addAll(labels);
}
/**
* disable the named labels
*
*/
public void disableLabels(Collection<String> labels) {
disabledLabels.addAll(labels);
}
/**
* enable the named labels
*
*/
public void enableLabels(Collection<String> labels) {
disabledLabels.removeAll(labels);
}
/**
* sync to the given list of labels
*
*/
public void sync(final Collection<String> labels, final Map<String, String> label2toolTip, final boolean clearOldOrder) {
if (!inSelection && !inSync) {
inSync = true;
this.label2ToolTips = label2toolTip;
try {
Runnable runnable = () -> {
disabledLabels.clear();
if (clearOldOrder)
((DefaultListModel<?>) getModel()).removeAllElements();
final Set<String> labelsSet = new HashSet<>(labels);
final Set<String> toDelete = new HashSet<>();
for (String label : disabledLabels) {
if (!labelsSet.contains(label))
toDelete.add(label);
}
disabledLabels.removeAll(toDelete);
final List<String> toKeep = new LinkedList<>();
for (int i = 0; i < getModel().getSize(); i++) {
String label = getModel().getElementAt(i);
if (labelsSet.contains(label))
toKeep.add(label);
}
((DefaultListModel<String>) getModel()).removeAllElements();
for (String label : toKeep) {
((DefaultListModel<String>) getModel()).addElement(label);
}
final Set<String> seen = new HashSet<>(toKeep);
for (String label : labels) {
if (!seen.contains(label))
((DefaultListModel<String>) getModel()).addElement(label);
}
validate();
};
if (SwingUtilities.isEventDispatchThread())
runnable.run();
else
SwingUtilities.invokeAndWait(runnable);
} catch (Exception e) {
Basic.caught(e);
} finally {
inSync = false;
}
}
}
/**
* syncs the selection in this list to the viewer
*/
public void fireSyncToViewer() {
syncListener.syncList2Viewer(getEnabledLabels());
}
public String getToolTipText(MouseEvent evt) {
if (label2ToolTips == null)
return null;
// Get item index
int index = locationToIndex(evt.getPoint());
// Get item
String label = getModel().getElementAt(index);
String toolTip = label2ToolTips.get(label);
if (toolTip != null)
return toolTip;
else
return label;
}
public Map<String, String> getLabel2ToolTips() {
return label2ToolTips;
}
/**
* cell renderer
*/
class MyCellRenderer extends JPanel implements ListCellRenderer<String> {
private final JPanel box = new JPanel();
private final JLabel label = new JLabel();
MyCellRenderer() {
final Dimension dim = new Dimension(10, 10);
if (getColorGetter() != null) {
box.setMinimumSize(dim);
box.setMaximumSize(dim);
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(box);
add(Box.createHorizontalStrut(2));
}
// label.setFont(new Font("Arial", Font.PLAIN,12));
add(label);
setOpaque(true);
setForeground(Color.black);
setBackground(Color.WHITE);
}
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
box.setEnabled(enabled);
label.setEnabled(enabled);
}
@Override
public Component getListCellRendererComponent(JList<? extends String> list, String value, int index, boolean isSelected, boolean cellHasFocus) {
label.setText(value);
setEnabled(!disabledLabels.contains(value) && LabelsJList.this.isEnabled());
if (isSelected) {
setBorder(BorderFactory.createLineBorder(ProgramProperties.SELECTION_COLOR_DARKER));
setBackground(ProgramProperties.SELECTION_COLOR);
} else {
setBorder(BorderFactory.createLineBorder(Color.WHITE));
setBackground(Color.WHITE);
}
if (getColorGetter() != null) {
Color color;
if (isEnabled() && LabelsJList.this.isEnabled()) {
color = getColorGetter().get(value);
box.setBackground(color);
if (color.equals(Color.WHITE))
box.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
box.setBorder(BorderFactory.createLineBorder(color.darker()));
} else {
box.setBackground(Color.WHITE);
box.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
}
box.repaint();
}
return this;
}
}
public JPopupMenu getPopupMenu() {
return popupMenu;
}
ChartColorManager.ColorGetter getColorGetter() {
return null;
}
public boolean isDoClustering() {
return doClustering;
}
public void setDoClustering(boolean doClustering) {
this.doClustering = doClustering;
ProgramProperties.put(getName() + "DoClustering", doClustering);
}
}
| 16,160 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ChartSelection.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/gui/ChartSelection.java | /*
* ChartSelection.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.gui;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
/**
* selection manager
* Daniel Huson, 7.2012
*/
public class ChartSelection {
private final Set<String> selectedSeries = new HashSet<>();
private final Set<String> selectedClasses = new HashSet<>();
private final Set<String> selectedAttributes = new HashSet<>();
private final LinkedList<IChartSelectionListener> seriesSelectionListeners = new LinkedList<>();
private final LinkedList<IChartSelectionListener> classesSelectionListeners = new LinkedList<>();
private final LinkedList<IChartSelectionListener> attributesSelectionListeners = new LinkedList<>();
private boolean isSelectedBasedOnSeries = true;
/**
* is series selected and isSelectedBasedOnSeries==true or className selected and isSelectedBasedOnSeries==false?
* Logic is flipped if transposed is set
*
* @return true, if either condition holds
*/
public boolean isSelected(String series, String className) {
if (isSelectedBasedOnSeries)
return selectedSeries.contains(series);
else
return selectedClasses.contains(className);
}
public boolean isSelectedBasedOnSeries() {
return isSelectedBasedOnSeries;
}
public void setSelectedBasedOnSeries(boolean isSelectedBasedOnSeries) {
this.isSelectedBasedOnSeries = isSelectedBasedOnSeries;
}
public Set<String> getSelectedSeries() {
return selectedSeries;
}
public boolean isSelectedSeries(String series) {
return selectedSeries.contains(series);
}
public void setSelectedSeries(String series, boolean select) {
if (select)
selectedSeries.add(series);
else
selectedSeries.remove(series);
fireSeriesSelectionListeners();
}
public void setSelectedSeries(java.util.Collection<String> series, boolean select) {
if (select)
selectedSeries.addAll(series);
else
selectedSeries.removeAll(series);
fireSeriesSelectionListeners();
}
public void clearSelectionSeries() {
selectedSeries.clear();
fireSeriesSelectionListeners();
}
public void toggleSelectedSeries(java.util.Collection<String> series) {
Collection<String> toSelect = new HashSet<>(series);
toSelect.removeAll(selectedSeries);
selectedSeries.removeAll(series);
selectedSeries.addAll(toSelect);
fireSeriesSelectionListeners();
}
public Set<String> getSelectedClasses() {
return selectedClasses;
}
public boolean isSelectedClass(String className) {
return selectedClasses.contains(className);
}
public void setSelectedClass(String className, boolean select) {
if (select)
selectedClasses.add(className);
else
selectedClasses.remove(className);
fireClassesSelectionListeners();
}
public void toggleSelectedClasses(java.util.Collection<String> classes) {
Collection<String> toSelect = new HashSet<>(classes);
toSelect.removeAll(selectedClasses);
selectedClasses.removeAll(classes);
selectedClasses.addAll(toSelect);
fireClassesSelectionListeners();
}
public void setSelectedClass(java.util.Collection<String> classes, boolean select) {
if (select)
selectedClasses.addAll(classes);
else
selectedClasses.removeAll(classes);
fireClassesSelectionListeners();
}
public void clearSelectionClasses() {
selectedClasses.clear();
fireClassesSelectionListeners();
}
public Set<String> getSelectedAttributes() {
return selectedAttributes;
}
public boolean isSelectedAttribute(String className) {
return selectedAttributes.contains(className);
}
public void setSelectedAttribute(String name, boolean select) {
if (select)
selectedAttributes.add(name);
else
selectedAttributes.remove(name);
fireAttributesSelectionListeners();
}
public void toggleSelectedAttributes(java.util.Collection<String> attributes) {
Collection<String> toSelect = new HashSet<>(attributes);
toSelect.removeAll(selectedAttributes);
selectedAttributes.removeAll(attributes);
selectedAttributes.addAll(toSelect);
fireAttributesSelectionListeners();
}
public void setSelectedAttribute(java.util.Collection<String> attributes, boolean select) {
if (select)
selectedAttributes.addAll(attributes);
else
selectedAttributes.removeAll(attributes);
fireAttributesSelectionListeners();
}
public void clearSelectionAttributes() {
selectedAttributes.clear();
fireAttributesSelectionListeners();
}
public void addSeriesSelectionListener(IChartSelectionListener listener) {
seriesSelectionListeners.add(listener);
}
public void removeSeriesSelectionListener(IChartSelectionListener listener) {
seriesSelectionListeners.remove(listener);
}
private void fireSeriesSelectionListeners() {
for (IChartSelectionListener selectionListener : seriesSelectionListeners) {
selectionListener.selectionChanged(this);
}
}
public void addClassesSelectionListener(IChartSelectionListener listener) {
classesSelectionListeners.add(listener);
}
public void removeClassesSelectionListener(IChartSelectionListener listener) {
classesSelectionListeners.remove(listener);
}
private void fireClassesSelectionListeners() {
for (IChartSelectionListener selectionListener : classesSelectionListeners) {
selectionListener.selectionChanged(this);
}
}
public void addAttributesSelectionListener(IChartSelectionListener listener) {
attributesSelectionListeners.add(listener);
}
public void removeAttributesSelectionListener(IChartSelectionListener listener) {
attributesSelectionListeners.remove(listener);
}
private void fireAttributesSelectionListeners() {
for (IChartSelectionListener selectionListener : attributesSelectionListeners) {
selectionListener.selectionChanged(this);
}
}
/**
* set selected
*
* @param target series, classes or attributes
*/
public void setSelected(String target, java.util.Collection<String> list, boolean select) {
switch (target.toLowerCase()) {
case "series" -> setSelectedSeries(list, select);
case "classes" -> setSelectedClass(list, select);
case "attributes" -> setSelectedAttribute(list, select);
}
}
/**
* clear selection
*
* @param target series, classes or attributes
*/
public void clearSelection(String target) {
switch (target.toLowerCase()) {
case "series" -> clearSelectionSeries();
case "classes" -> clearSelectionClasses();
case "attributes" -> clearSelectionAttributes();
}
}
}
| 8,038 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
Label2LabelMapper.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/gui/Label2LabelMapper.java | /*
* Label2LabelMapper.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.gui;
import java.util.HashMap;
import java.util.Map;
/**
* default label 2 label mapper
* Daniel Huson, 7.2012
*/
public class Label2LabelMapper {
private final Map<String, String> label2label = new HashMap<>();
/**
* get mapped label for label
*
* @return replacement label
*/
public String get(String label) {
String result = label2label.get(label);
if (result != null)
return result;
else
return label;
}
/**
* set a label 2 label map
*
*/
public void put(String label, String newLabel) {
label2label.put(label, newLabel);
}
/**
* get size
*
* @return size
*/
public int size() {
return label2label.size();
}
/**
* erase
*/
public void clear() {
label2label.clear();
}
}
| 1,702 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ClusteringTree.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/cluster/ClusteringTree.java | /*
* ClusteringTree.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.cluster;
import jloda.graph.Edge;
import jloda.graph.Node;
import jloda.phylo.PhyloTree;
import jloda.swing.graphview.PhyloTreeView;
import jloda.swing.util.ProgramProperties;
import jloda.util.Correlation;
import jloda.util.Table;
import megan.chart.gui.ChartSelection;
import megan.chart.gui.SelectionGraphics;
import megan.clusteranalysis.tree.Distances;
import megan.clusteranalysis.tree.Taxa;
import megan.clusteranalysis.tree.UPGMA;
import java.awt.*;
import java.awt.geom.Point2D;
import java.util.*;
/**
* do clustering of series or class names
* Created by huson on 3/9/16.
*/
public class ClusteringTree {
public enum TYPE {SERIES, CLASSES, ATTRIBUTES}
public enum SIDE {LEFT, RIGHT, BOTTOM, TOP}
private final ArrayList<String> labelOrder;
private final PhyloTree tree;
private final PhyloTreeView treeView;
private Rectangle previousRectangle;
private TYPE type;
private SIDE rootSide;
private ChartSelection chartSelection;
private final SelectionGraphics<Edge> selectionGraphics;
private boolean inUpdate;
/**
* constructor
*/
public ClusteringTree(TYPE type, SIDE rootSide) {
this.type = type;
this.rootSide = rootSide;
labelOrder = new ArrayList<>();
tree = new PhyloTree();
treeView = new PhyloTreeView(tree);
selectionGraphics = new SelectionGraphics<>(null);
}
public void clear() {
tree.deleteAllNodes();
labelOrder.clear();
}
public SIDE getRootSide() {
return rootSide;
}
public void setRootSide(SIDE rootSide) {
this.rootSide = rootSide;
}
/**
* update clustering
*
*/
public void updateClustering(Table<String, String, Double> seriesAndClass2Value) {
if (!inUpdate) {
try {
inUpdate = true;
labelOrder.clear();
previousRectangle = null;
final Taxa taxa;
final Distances distances;
switch (type) {
case SERIES -> {
final String[] series = seriesAndClass2Value.rowKeySet().toArray(new String[0]);
taxa = new Taxa();
for (String seriesName : series)
taxa.add(seriesName);
distances = new Distances(taxa.size());
for (int i = 0; i < series.length; i++) {
for (int j = 0; j < series.length; j++) {
distances.set(i + 1, j + 1, computeCorrelationDistanceBetweenSeries(series[i], series[j], seriesAndClass2Value));
}
}
}
case CLASSES -> {
final String[] classes = seriesAndClass2Value.columnKeySet().toArray(new String[0]);
taxa = new Taxa();
for (String className : classes)
taxa.add(className);
distances = new Distances(taxa.size());
for (int i = 0; i < classes.length; i++) {
for (int j = 0; j < classes.length; j++) {
distances.set(i + 1, j + 1, computeCorrelationDistanceBetweenClasses(classes[i], classes[j], seriesAndClass2Value));
}
}
}
default -> throw new RuntimeException("Invalid case: " + type);
}
treeView.getGraph().clear();
UPGMA.apply(taxa, distances, treeView);
flipCoordinates(treeView, rootSide);
labelOrder.addAll(getLabelOrder(treeView));
// if(rootSide==SIDE.RIGHT)
// Basic.reverseList(labelOrder);
} finally {
inUpdate = false;
}
}
}
/**
* update clustering
*
*/
public void updateClustering(String[] labels, Table<String, String, Float> matrix) {
if (!inUpdate) {
try {
inUpdate = true;
labelOrder.clear();
treeView.getGraph().clear();
previousRectangle = null;
if (labels.length > 0) {
final Taxa taxa = new Taxa();
for (String label : labels)
taxa.add(label);
if (labels.length == 1) {
final Node root = treeView.getPhyloTree().newNode();
treeView.getPhyloTree().setRoot(root);
treeView.setLabel(root, labels[0]);
labelOrder.addAll(getLabelOrder(treeView));
} else {
final Distances distances = new Distances(taxa.size());
for (int i = 0; i < labels.length; i++) {
final float[] iValues = getValuesRow(labels[i], matrix);
for (int j = i + 1; j < labels.length; j++) {
final float[] jValues = getValuesRow(labels[j], matrix);
distances.set(i + 1, j + 1, computeCorrelationDistances(iValues.length, iValues, jValues));
}
}
UPGMA.apply(taxa, distances, treeView);
// treeView.topologicallySortTreeLexicographically();
// UPGMA.embedTree(treeView);
flipCoordinates(treeView, rootSide);
labelOrder.addAll(getLabelOrder(treeView));
}
// if(rootSide==SIDE.RIGHT)
// Basic.reverseList(labelOrder);
}
} finally {
inUpdate = false;
}
}
}
private float[] getValuesRow(String rowKey, Table<String, String, Float> matrix) {
final float[] array = new float[matrix.columnKeySet().size()];
final Map<String, Float> row = matrix.row(rowKey);
int i = 0;
for (String colKey : row.keySet()) {
array[i++] = matrix.get(rowKey, colKey);
}
return array;
}
/**
* compute order of labels
*
* @return labels as ordered in tree
*/
private static ArrayList<String> getLabelOrder(PhyloTreeView treeView) {
final ArrayList<String> order = new ArrayList<>();
final PhyloTree tree = treeView.getPhyloTree();
if (tree.getRoot() != null) {
final Stack<Node> stack = new Stack<>();
stack.add(tree.getRoot());
while (stack.size() > 0) {
Node v = stack.pop();
if (v.getOutDegree() == 0)
order.add(treeView.getLabel(v));
else
for (Edge e = v.getLastOutEdge(); e != null; e = v.getPrevOutEdge(e)) {
stack.push(e.getTarget());
}
}
}
return order;
}
/**
* compute correlation distance between two series
*
* @return distance
*/
private static double computeCorrelationDistanceBetweenSeries(String seriesA, String seriesB, Table<String, String, Double> seriesAndClass2Value) {
final Set<String> classes = seriesAndClass2Value.columnKeySet();
final ArrayList<Double> xValues = new ArrayList<>(classes.size());
final ArrayList<Double> yValues = new ArrayList<>(classes.size());
for (String className : classes) {
xValues.add(seriesAndClass2Value.get(seriesA, className));
yValues.add(seriesAndClass2Value.get(seriesB, className));
}
return 1 - Correlation.computePersonsCorrelationCoefficent(classes.size(), xValues, yValues);
}
/**
* compute correlation distance between two series
*
* @return distance
*/
private static double computeCorrelationDistances(int n, float[] seriesA, float[] seriesB) {
return 1 - Correlation.computePersonsCorrelationCoefficent(n, seriesA, seriesB);
}
/**
* compute correlation distance between two classes
*
* @return distance
*/
private static double computeCorrelationDistanceBetweenClasses(String classA, String classB, Table<String, String, Double> seriesAndClass2Value) {
final Set<String> series = seriesAndClass2Value.rowKeySet();
final ArrayList<Double> xValues = new ArrayList<>(series.size());
final ArrayList<Double> yValues = new ArrayList<>(series.size());
for (String seriesName : series) {
xValues.add(seriesAndClass2Value.get(seriesName, classA));
yValues.add(seriesAndClass2Value.get(seriesName, classB));
}
return 1 - Correlation.computePersonsCorrelationCoefficent(series.size(), xValues, yValues);
}
public ArrayList<String> getLabelOrder() {
return (ArrayList) labelOrder.clone();
}
public PhyloTreeView getPanel() {
return treeView;
}
/**
* paint the tree
*
*/
public void paint(Graphics2D gc, Rectangle rect) {
try {
if (gc instanceof SelectionGraphics) {
final SelectionGraphics sgc = (SelectionGraphics) gc;
select(rect, sgc.getSelectionRectangle(), sgc.getMouseClicks());
} else if (!inUpdate) {
doPaint(gc, rect);
}
} catch (Exception ex) {
// Basic.caught(ex);
}
}
/**
* paint the tree
*
*/
private void doPaint(Graphics2D gc, Rectangle rect) {
if (!(gc instanceof SelectionGraphics))
selectEdgesAbove();
gc.setStroke(new BasicStroke(1));
if (!rect.equals(previousRectangle)) {
previousRectangle = rect;
fitToRectangle(treeView, rect);
}
for (Edge e = tree.getFirstEdge(); e != null; e = tree.getNextEdge(e)) {
try {
if (inUpdate)
break;
Point2D a = treeView.getLocation(e.getSource());
Point2D b = treeView.getLocation(e.getTarget());
if (treeView.getSelected(e))
gc.setColor(ProgramProperties.SELECTION_COLOR_DARKER);
else
gc.setColor(Color.BLACK);
if (gc instanceof SelectionGraphics)
((SelectionGraphics) gc).setCurrentItem(e);
final int ax = (int) Math.round(a.getX());
final int ay = (int) Math.round(a.getY());
gc.fillOval(ax - 1, ay - 1, 3, 3);
switch (rootSide) {
case BOTTOM, TOP -> {
gc.drawLine(ax, ay, (int) Math.round(b.getX()), ay);
gc.drawLine((int) Math.round(b.getX()), ay, (int) Math.round(b.getX()), (int) Math.round(b.getY()));
}
case RIGHT, LEFT -> {
gc.drawLine(ax, ay, (int) Math.round(a.getX()), (int) Math.round(b.getY()));
gc.drawLine(ax, (int) Math.round(b.getY()), (int) Math.round(b.getX()), (int) Math.round(b.getY()));
}
}
/*
if (e.getTarget().getOutDegree() == 0)
gc.drawString(treeView.getLabel(e.getTarget()), (int) b.getX(), (int) b.getY());
*/
} finally {
if (gc instanceof SelectionGraphics)
((SelectionGraphics<?>) gc).clearCurrentItem();
}
}
}
/**
* select series or classes
*
*/
private void select(Rectangle rect, Rectangle selectionRect, int mouseClicks) {
if (selectionRect == null || chartSelection == null || mouseClicks != 1)
return;
selectionGraphics.setSelectionRectangle(selectionRect);
selectionGraphics.getSelectedItems().clear();
doPaint(selectionGraphics, rect);
final Collection<Edge> hitEdges = selectionGraphics.getSelectedItems();
if (hitEdges.size() > 0) {
final Set<Node> seen = new HashSet<>();
final Stack<Node> stack = new Stack<>();
for (Edge e : hitEdges) {
stack.add(e.getTarget());
}
while (stack.size() > 0) {
final Node v = stack.pop();
if (v.getOutDegree() == 0) {
if (type == TYPE.SERIES)
chartSelection.setSelectedSeries(treeView.getLabel(v), true);
else if (type == TYPE.CLASSES)
chartSelection.setSelectedClass(treeView.getLabel(v), true);
else if (type == TYPE.ATTRIBUTES)
chartSelection.setSelectedAttribute(treeView.getLabel(v), true);
} else {
for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) {
if (!seen.contains(e.getTarget())) {
stack.push(e.getTarget());
seen.add(e.getTarget());
}
}
}
}
}
}
private void selectEdgesAbove() {
treeView.getSelectedEdges().clear();
treeView.getSelectedNodes().clear();
if (tree.getRoot() != null) {
final Map<Node, Integer> below = new HashMap<>();
final int countBelow = countSelectedBelowRec(tree.getRoot(), below);
if (countBelow > 0)
selectBelowRec(tree.getRoot(), below, countBelow);
}
}
private int countSelectedBelowRec(Node v, Map<Node, Integer> below) {
if (v.getOutDegree() == 0) {
if (type == TYPE.SERIES)
below.put(v, chartSelection.isSelectedSeries(treeView.getLabel(v)) ? 1 : 0);
else if (type == TYPE.CLASSES)
below.put(v, chartSelection.isSelectedClass(treeView.getLabel(v)) ? 1 : 0);
else
below.put(v, chartSelection.isSelectedAttribute(treeView.getLabel(v)) ? 1 : 0);
} else {
int count = 0;
for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) {
count += countSelectedBelowRec(e.getTarget(), below);
}
below.put(v, count);
}
return below.get(v);
}
private void selectBelowRec(Node v, Map<Node, Integer> below, final int count) {
for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) {
final Node w = e.getTarget();
final Integer countW = below.get(w);
if (countW != null && countW > 0) {
selectBelowRec(w, below, count);
if (countW == count)
return; // have seen all below
// System.err.println("Select "+e);
treeView.setSelected(e, true);
treeView.setSelected(v, true);
treeView.setSelected(w, true);
}
}
}
/**
* flip coordinates so as to fit the specified root side
*
*/
private static void flipCoordinates(final PhyloTreeView treeView, final SIDE rootSide) {
final PhyloTree tree = treeView.getPhyloTree();
for (Node v = tree.getFirstNode(); v != null; v = tree.getNextNode(v)) {
final Point2D loc = treeView.getLocation(v);
switch (rootSide) {
case TOP:
treeView.setLocation(v, loc.getY(), loc.getX());
break;
case BOTTOM:
treeView.setLocation(v, loc.getY(), -loc.getX());
break;
case RIGHT:
treeView.setLocation(v, -loc.getX(), loc.getY());
break;
default:
case LEFT:
break;
}
}
}
/**
* fit coordinates into rect
*
*/
private static void fitToRectangle(final PhyloTreeView treeView, final Rectangle rect) {
final PhyloTree tree = treeView.getPhyloTree();
double minX = Integer.MAX_VALUE;
double minY = Integer.MAX_VALUE;
double maxX = Integer.MIN_VALUE;
double maxY = Integer.MIN_VALUE;
for (Node v = tree.getFirstNode(); v != null; v = tree.getNextNode(v)) {
final Point2D loc = treeView.getLocation(v);
minX = Math.min(minX, loc.getX());
minY = Math.min(minY, loc.getY());
maxX = Math.max(maxX, loc.getX());
maxY = Math.max(maxY, loc.getY());
}
final double mX = ((maxX - minX) != 0 ? rect.getWidth() / (maxX - minX) : 0);
final double mY = ((maxY - minY) != 0 ? rect.getHeight() / (maxY - minY) : 0);
for (Node v = tree.getFirstNode(); v != null; v = tree.getNextNode(v)) {
final Point2D loc = treeView.getLocation(v);
treeView.setLocation(v, rect.getX() + mX * (loc.getX() - minX), rect.getY() + mY * (loc.getY() - minY));
}
}
public ChartSelection getChartSelection() {
return chartSelection;
}
public void setChartSelection(ChartSelection chartSelection) {
this.chartSelection = chartSelection;
}
/**
* does the tree have exactly one selected subtree?
*
* @return true, if a complete non-empty subtree is selected
*/
public boolean hasSelectedSubTree() {
boolean foundASelectedRoot = false;
if (treeView.getNumberSelectedNodes() > 1) {
for (Node v : treeView.getSelectedNodes()) {
if (v.getInDegree() == 0 || !treeView.getSelected(v.getFirstInEdge().getSource())) {
if (foundASelectedRoot)
return false; // has more than one selected root
else
foundASelectedRoot = true;
}
}
}
return foundASelectedRoot;
}
/**
* rotate all currently selected subtrees
*/
public void rotateSelectedSubTree() {
boolean changed = false;
if (treeView.getNumberSelectedNodes() > 1) {
for (Node v : treeView.getSelectedNodes()) {
if (v.getInDegree() == 0 || !treeView.getSelected(v.getFirstInEdge().getSource())) {
Stack<Node> stack = new Stack<>();
stack.push(v);
while (stack.size() > 0) {
Node w = stack.pop();
if (w.getOutDegree() > 1) {
w.reverseOrderAdjacentEdges();
changed = true;
}
if (w.getOutDegree() > 0) {
for (Edge e = w.getFirstOutEdge(); e != null; e = w.getNextOutEdge(e)) {
stack.push(e.getTarget());
}
}
}
}
}
}
if (changed) {
labelOrder.clear();
labelOrder.addAll(getLabelOrder(treeView));
UPGMA.embedTree(treeView);
flipCoordinates(treeView, rootSide);
previousRectangle = null;
}
}
public void setType(TYPE type) {
this.type = type;
}
}
| 20,428 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
DrawerManager.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/DrawerManager.java | /*
* DrawerManager.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.util.PluginClassLoader;
import megan.chart.IChartDrawer;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
/**
* manages the chart drawers
* <p/>
* Daniel Huson, 4.2015
*/
public class DrawerManager {
private static final Set<String> allSupportedChartDrawers = new TreeSet<>(); // alphabetical order...
public static String[] paths = new String[]{"megan.chart.drawers"};
/**
* creates a copy of all chart drawers
*
* @return chart drawers
*/
public static Map<String, IChartDrawer> createChartDrawers() {
synchronized (allSupportedChartDrawers) { // only want to fill allSupportedChartDrawers once
final boolean fillAllSupportedDrawers = (allSupportedChartDrawers.size() == 0);
final Map<String, IChartDrawer> name2DrawerInstance = new HashMap<>();
for (IChartDrawer object : PluginClassLoader.getInstances(IChartDrawer.class, paths)) {
if (object instanceof IChartDrawer) {
final IChartDrawer drawer = object;
if (!(drawer instanceof MultiChartDrawer) && drawer.isEnabled()) {
name2DrawerInstance.put(drawer.getChartDrawerName(), drawer);
if (fillAllSupportedDrawers && !(object instanceof Plot2DDrawer))
allSupportedChartDrawers.add(drawer.getChartDrawerName());
}
}
}
return name2DrawerInstance;
}
}
/**
* gets the list of all supported drawers
*
* @return all supported drawers
*/
public static Set<String> getAllSupportedChartDrawers() {
if (allSupportedChartDrawers.size() == 0)
createChartDrawers();
return allSupportedChartDrawers;
}
}
| 2,695 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
PieChartDrawer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/PieChartDrawer.java | /*
* PieChartDrawer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.swing.util.Geometry;
import jloda.swing.util.ProgramProperties;
import megan.chart.IChartDrawer;
import megan.chart.IMultiChartDrawable;
import megan.chart.data.DefaultChartData;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.SelectionGraphics;
import megan.util.ScalingType;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Arc2D;
import java.awt.geom.Point2D;
/**
* draws a pie chart
* Daniel Huson, 6.2012
*/
public class PieChartDrawer extends BarChartDrawer implements IChartDrawer, IMultiChartDrawable {
private static final String NAME = "PieChart";
private Graphics graphics;
private int width;
private int height;
/**
* constructor
*/
public PieChartDrawer() {
setSupportedScalingTypes(ScalingType.LINEAR, ScalingType.PERCENT);
}
/**
* draw a pie in which slices are classes
*
*/
public void drawChart(Graphics2D gc) {
int x0 = 2;
int x1 = getWidth() - 2;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
if (x0 >= x1)
return;
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
Rectangle deviceBBox = new Rectangle(x0, y1, x1 - x0, y0 - y1);
int diameter = Math.min(deviceBBox.width, deviceBBox.height) - 70;
deviceBBox.x = deviceBBox.x + (deviceBBox.width - diameter) / 2;
deviceBBox.y = deviceBBox.y + (deviceBBox.height - diameter) / 2;
if (getChartData().getSeriesNames().size() == 0)
return; // nothing to draw.
String series = getChartData().getSeriesNames().iterator().next();
double factor = 360.0 / getChartData().getTotalForSeriesIncludingDisabledAttributes(series);
double totalValue = 0;
Arc2D arc = new Arc2D.Double();
arc.setArcType(Arc2D.PIE);
arc.setFrame(deviceBBox.x + 1, deviceBBox.y + 1, diameter, diameter);
Point center = new Point((int) arc.getFrame().getCenterX(), (int) arc.getFrame().getCenterY());
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
for (String className : getChartData().getClassNames()) {
double value = getChartData().getValue(series, className).doubleValue();
if (value > 0) {
arc.setAngleStart(totalValue * factor);
arc.setAngleExtent(value * factor);
totalValue += value;
gc.setColor(getChartColors().getClassColor(class2HigherClassMapper.get(className)));
if (sgc != null)
sgc.setCurrentItem(new String[]{series, className});
gc.fill(arc);
if (sgc != null)
sgc.clearCurrentItem();
gc.setColor(Color.black);
gc.draw(arc);
}
boolean isSelected = getChartData().getChartSelection().isSelected(null, className);
if (isShowValues() || isSelected) {
double textAngle = Geometry.deg2rad(360 - (arc.getAngleStart() + arc.getAngleExtent() / 2));
Point2D apt = Geometry.translateByAngle(center, textAngle, diameter / 2 + 5);
if (isSelected)
gc.setColor(ProgramProperties.SELECTION_COLOR_ADDITIONAL_TEXT);
else
gc.setColor(getFontColor(ChartViewer.FontKeys.ValuesFont.toString(), Color.DARK_GRAY));
if (sgc != null)
sgc.setCurrentItem(new String[]{series, className});
drawString(gc, "" + (int) value, apt.getX(), apt.getY(), textAngle);
if (sgc != null)
sgc.clearCurrentItem();
}
}
// now draw all the selected stuff
if (getChartData().getChartSelection().getSelectedClasses().size() > 0) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
totalValue = 0;
for (String className : getChartData().getClassNames()) {
double value = getChartData().getValue(series, className).doubleValue();
arc.setAngleStart(totalValue * factor);
arc.setAngleExtent(value * factor);
totalValue += value;
if (getChartData().getChartSelection().isSelected(null, className)) {
gc.draw(arc);
}
}
gc.setStroke(NORMAL_STROKE);
}
}
/**
* draw a pie in which slices are series
*
*/
public void drawChartTransposed(Graphics2D gc) {
int x0 = 2;
int x1 = getWidth() - 2;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
if (x0 >= x1)
return;
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
Rectangle deviceBBox = new Rectangle(x0, y1, x1 - x0, y0 - y1);
int diameter = Math.min(deviceBBox.width, deviceBBox.height) - 70;
deviceBBox.x = deviceBBox.x + (deviceBBox.width - diameter) / 2;
deviceBBox.y = deviceBBox.y + (deviceBBox.height - diameter) / 2;
if (getChartData().getMaxTotalSeries() <= 0) {
return; // nothing to draw.
}
String className = getChartData().getClassNames().iterator().next();
double factor = 360.0 / getChartData().getTotalForClassIncludingDisabledSeries(className);
double totalValue = 0;
Arc2D arc = new Arc2D.Double();
arc.setArcType(Arc2D.PIE);
arc.setFrame(deviceBBox.x + 1, deviceBBox.y + 1, diameter, diameter);
Point center = new Point((int) arc.getFrame().getCenterX(), (int) arc.getFrame().getCenterY());
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
for (String series : getChartData().getSeriesNames()) {
double value = getChartData().getValue(series, className).doubleValue();
if (value > 0) {
arc.setAngleStart(totalValue * factor);
arc.setAngleExtent(value * factor);
totalValue += value;
gc.setColor(getChartColors().getSampleColor(series));
if (sgc != null)
sgc.setCurrentItem(new String[]{series, className});
gc.fill(arc);
if (sgc != null)
sgc.clearCurrentItem();
gc.setColor(Color.black);
gc.draw(arc);
boolean isSelected = getChartData().getChartSelection().isSelected(series, null);
if (isShowValues() || isSelected) {
double textAngle = Geometry.deg2rad(360 - (arc.getAngleStart() + arc.getAngleExtent() / 2));
Point2D apt = Geometry.translateByAngle(center, textAngle, diameter / 2 + 5);
if (isSelected)
gc.setColor(ProgramProperties.SELECTION_COLOR_ADDITIONAL_TEXT);
else
gc.setColor(getFontColor(ChartViewer.FontKeys.ValuesFont.toString(), Color.DARK_GRAY));
if (sgc != null)
sgc.setCurrentItem(new String[]{series, className});
drawString(gc, "" + (int) value, apt.getX(), apt.getY(), textAngle);
if (sgc != null)
sgc.clearCurrentItem();
}
}
}
if (chartData.getChartSelection().getSelectedSeries().size() > 0) {
totalValue = 0;
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
for (String series : getChartData().getSeriesNames()) {
double value = getChartData().getValue(series, className).doubleValue();
arc.setAngleStart(totalValue * factor);
arc.setAngleExtent(value * factor);
totalValue += value;
if (getChartData().getChartSelection().isSelected(series, null)) {
gc.draw(arc);
}
}
gc.setStroke(NORMAL_STROKE);
}
}
@Override
public boolean isShowXAxis() {
return false;
}
@Override
public boolean isShowYAxis() {
return false;
}
public boolean canShowValues() {
return true;
}
/**
* create a new instance of the given type of drawer, sharing internal data structures
*
*/
public PieChartDrawer createInstance() {
final PieChartDrawer drawer = new PieChartDrawer();
drawer.setViewer(viewer);
drawer.setChartData(new DefaultChartData());
drawer.setClass2HigherClassMapper(class2HigherClassMapper);
drawer.setSeriesLabelGetter(seriesLabelGetter);
drawer.setExecutorService(executorService);
return drawer;
}
@Override
public void setWidth(int width) {
this.width = width;
}
@Override
public void setHeight(int height) {
this.height = height;
}
@Override
public void setGraphics(Graphics graphics) {
this.graphics = graphics;
}
@Override
public Graphics getGraphics() {
return graphics;
}
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return height;
}
@Override
public JToolBar getBottomToolBar() {
return null;
}
@Override
public boolean getShowXAxisPreference() {
return false;
}
@Override
public boolean getShowYAxisPreference() {
return false;
}
/**
* copy all user parameters from the given base drawer
*
*/
@Override
public void setValues(IMultiChartDrawable baseDrawer) {
}
@Override
public String getChartDrawerName() {
return NAME;
}
}
| 10,818 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
AttributeCorrelationPlotDrawer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/AttributeCorrelationPlotDrawer.java | /*
* AttributeCorrelationPlotDrawer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.Geometry;
import jloda.swing.util.ProgramProperties;
import jloda.swing.window.IPopupMenuModifier;
import jloda.util.Basic;
import jloda.util.Correlation;
import jloda.util.NumberUtils;
import jloda.util.StringUtils;
import megan.chart.IChartDrawer;
import megan.chart.cluster.ClusteringTree;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.SelectionGraphics;
import megan.util.ScalingType;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.geom.Point2D;
import java.io.IOException;
import java.io.Writer;
import java.util.*;
/**
* draws a correlation plot
* Daniel Huson, 11.2015
*/
public class AttributeCorrelationPlotDrawer extends CorrelationPlotDrawer implements IChartDrawer {
private static final String NAME = "AttributeCorrelationPlot";
private String[] attributeNames;
private final Set<String> previousAttributes = new HashSet<>();
private final ClusteringTree attributesClusteringTree;
private final ClusteringTree classesClusteringTree;
private boolean previousClusterAttributes = false;
/**
* constructor
*/
public AttributeCorrelationPlotDrawer() {
super();
attributesClusteringTree = new ClusteringTree(ClusteringTree.TYPE.ATTRIBUTES, ClusteringTree.SIDE.RIGHT);
classesClusteringTree = new ClusteringTree(ClusteringTree.TYPE.CLASSES, ClusteringTree.SIDE.TOP);
previousTranspose = isTranspose();
}
/**
* draw correlation plot chart
*
*/
public void drawChart(Graphics2D gc) {
final SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
gc.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
int x0 = leftMargin;
int scaleWidth = 30;
int x1 = getWidth() - rightMargin - scaleWidth;
if (x0 >= x1)
return;
if (inUpdateCoordinates) {
gc.setFont(getFont("Default"));
gc.setColor(Color.LIGHT_GRAY);
gc.drawString("Computing correlation plot...", x0, y1 + 20);
viewer.getScrollPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
return;
} else
viewer.getScrollPane().setCursor(Cursor.getDefaultCursor());
if (sgc != null) {
drawYAxis(gc, null); // need this for selection
}
if (!getChartTitle().startsWith("Correlation plot: "))
setChartTitle("Correlation plot: " + getChartTitle());
final int numberOfClasses = (classNames != null ? classNames.length : 0);
final int numberOfAttributes = (attributeNames != null ? attributeNames.length : 0);
if (viewer.getClassesList().isDoClustering())
y1 += topTreeSpace; // do this before other clustering
if (sgc == null) {
drawScaleBar(gc, x1, scaleWidth, y1, y0 - y1);
}
if (viewer.getAttributesList().isDoClustering()) {
x1 -= rightTreeSpace;
int height = (int) Math.round((y0 - y1) / (numberOfAttributes + 1.0) * numberOfAttributes);
int yStart = y0 + ((y1 - y0) - height) / 2;
final Rectangle rect = new Rectangle(x1, yStart, rightTreeSpace, height);
attributesClusteringTree.paint(gc, rect);
}
if (viewer.getClassesList().isDoClustering()) {
int width = (int) ((x1 - x0) / (numberOfClasses + 1.0) * numberOfClasses);
int xStart = x0 + ((x1 - x0) - width) / 2;
final Rectangle rect = new Rectangle(xStart, y1 - topTreeSpace, width, topTreeSpace);
classesClusteringTree.paint(gc, rect);
}
// main drawing loop:
if (numberOfClasses > 0 && numberOfAttributes > 0) {
double xStep = (x1 - x0) / (double) numberOfClasses;
double yStep = (y0 - y1) / (double) numberOfAttributes;
int d = 0;
for (String classNameX : classNames) {
final double xLabel = x0 + (d + 0.5) * xStep;
Point2D apt = new Point2D.Double(xLabel, getHeight() - bottomMargin + 10);
final Dimension labelSize = BasicSwing.getStringSize(gc, classNameX, gc.getFont()).getSize();
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
if (getChartData().getChartSelection().isSelected(null, classNameX)) {
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.DARK_GRAY));
drawString(gc, classNameX, apt.getX(), apt.getY(), classLabelAngle);
if (sgc != null) {
sgc.setCurrentItem(new String[]{null, classNameX});
drawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle);
sgc.clearCurrentItem();
}
int c = numberOfAttributes - 1;
for (String attributeNameY : attributeNames) {
final Float correlationCoefficient = dataMatrix.get(classNameX, attributeNameY);
if (correlationCoefficient != null) {
final double[] boundingBox = new double[]{x0 + d * xStep, y0 - (c + 1) * yStep, xStep, yStep};
// gc.drawRect((int) Math.round(boundingBox[0]), (int) Math.round(boundingBox[1]), (int) Math.round(boundingBox[2]), (int) Math.round(boundingBox[3]));
drawCell(gc, boundingBox, correlationCoefficient);
if (sgc != null && !sgc.isShiftDown()) {
sgc.setCurrentItem(new String[]{null, classNameX, attributeNameY});
gc.fillRect((int) Math.round(boundingBox[0]), (int) Math.round(boundingBox[1]), (int) Math.round(boundingBox[2]), (int) Math.round(boundingBox[3]));
sgc.clearCurrentItem();
sgc.setCurrentItem(new String[]{null, null, attributeNameY});
gc.fillRect((int) Math.round(boundingBox[0]), (int) Math.round(boundingBox[1]), (int) Math.round(boundingBox[2]), (int) Math.round(boundingBox[3]));
sgc.clearCurrentItem();
}
boolean isSelected = false;
if (getChartData().getChartSelection().isSelectedClass(classNameX)) {
if (getChartData().getChartSelection().isSelectedAttribute(attributeNameY) || getChartData().getChartSelection().getSelectedAttributes().size() == 0)
isSelected = true;
} else if (getChartData().getChartSelection().getSelectedClasses().size() == 0 && getChartData().getChartSelection().isSelectedAttribute(attributeNameY))
isSelected = true;
if (isSelected) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.drawRect((int) Math.round(boundingBox[0]), (int) Math.round(boundingBox[1]), (int) Math.round(boundingBox[2]), (int) Math.round(boundingBox[3]));
gc.setStroke(NORMAL_STROKE);
}
if (showValues || isSelected) {
String aLabel = String.format("%.3f", correlationCoefficient);
valuesList.add(new DrawableValue(aLabel, (int) Math.round(boundingBox[0] + boundingBox[2] / 2), (int) Math.round(boundingBox[1] + boundingBox[3] / 2) - gc.getFont().getSize() / 2, isSelected));
}
}
c--;
}
d++;
}
}
if (valuesList.size() > 0) {
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
DrawableValue.drawValues(gc, valuesList, true, true);
valuesList.clear();
}
}
/**
* draw correlation plot chart
*
*/
public void drawChartTransposed(Graphics2D gc) {
final SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
gc.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
int x0 = leftMargin;
int scaleWidth = 30;
int x1 = getWidth() - rightMargin - scaleWidth;
if (x0 >= x1)
return;
if (inUpdateCoordinates) {
gc.setFont(getFont("Default"));
gc.setColor(Color.LIGHT_GRAY);
gc.drawString("Computing correlation plot...", x0, y1 + 20);
viewer.getScrollPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
return;
} else
viewer.getScrollPane().setCursor(Cursor.getDefaultCursor());
if (sgc != null) {
drawYAxis(gc, null);
}
if (!getChartTitle().startsWith("Correlation plot: "))
setChartTitle("Correlation plot: " + getChartTitle());
final int numberOfClasses = (classNames != null ? classNames.length : 0);
final int numberOfAttributes = (attributeNames != null ? attributeNames.length : 0);
if (viewer.getAttributesList().isDoClustering())
y1 += topTreeSpace; // do this before other clustering
if (sgc == null) {
drawScaleBar(gc, x1, scaleWidth, y1, y0 - y1);
}
if (viewer.getClassesList().isDoClustering()) {
x1 -= rightTreeSpace;
int height = (int) Math.round((y0 - y1) / (numberOfClasses + 1.0) * numberOfClasses);
int yStart = y0 + ((y1 - y0) - height) / 2;
final Rectangle rect = new Rectangle(x1, yStart, rightTreeSpace, height);
classesClusteringTree.paint(gc, rect);
}
if (viewer.getAttributesList().isDoClustering()) {
int width = (int) ((x1 - x0) / (numberOfAttributes + 1.0) * numberOfAttributes);
int xStart = x0 + ((x1 - x0) - width) / 2;
final Rectangle rect = new Rectangle(xStart, y1 - topTreeSpace, width, topTreeSpace);
attributesClusteringTree.paint(gc, rect);
}
double xStep = (x1 - x0) / (double) numberOfAttributes;
double yStep = (y0 - y1) / (double) numberOfClasses;
// main drawing loop:
if (numberOfClasses > 0 && numberOfAttributes > 0) {
int d = 0;
for (String attributeNameX : attributeNames) {
final double xLabel = x0 + (d + 0.5) * xStep;
Point2D apt = new Point2D.Double(xLabel, getHeight() - bottomMargin + 10);
final Dimension labelSize = BasicSwing.getStringSize(gc, attributeNameX, gc.getFont()).getSize();
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
if (getChartData().getChartSelection().isSelectedAttribute(attributeNameX)) {
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.DARK_GRAY));
drawString(gc, attributeNameX, apt.getX(), apt.getY(), classLabelAngle);
if (sgc != null) {
sgc.setCurrentItem(new String[]{null, attributeNameX});
drawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle);
sgc.clearCurrentItem();
}
int c = numberOfClasses - 1;
for (String classNameY : classNames) {
final Float correlationCoefficient = dataMatrix.get(classNameY, attributeNameX);
if (correlationCoefficient != null) {
final double[] boundingBox = new double[]{x0 + d * xStep, y0 - (c + 1) * yStep, xStep, yStep};
// gc.drawRect((int) Math.round(boundingBox[0]), (int) Math.round(boundingBox[1]), (int) Math.round(boundingBox[2]), (int) Math.round(boundingBox[3]));
drawCell(gc, boundingBox, correlationCoefficient);
if (sgc != null && !sgc.isShiftDown()) {
sgc.setCurrentItem(new String[]{null, classNameY, attributeNameX});
gc.fillRect((int) Math.round(boundingBox[0]), (int) Math.round(boundingBox[1]), (int) Math.round(boundingBox[2]), (int) Math.round(boundingBox[3]));
sgc.clearCurrentItem();
sgc.setCurrentItem(new String[]{null, classNameY, attributeNameX});
gc.fillRect((int) Math.round(boundingBox[0]), (int) Math.round(boundingBox[1]), (int) Math.round(boundingBox[2]), (int) Math.round(boundingBox[3]));
sgc.clearCurrentItem();
}
boolean isSelected = false;
if (getChartData().getChartSelection().isSelectedClass(classNameY)) {
if (getChartData().getChartSelection().isSelectedAttribute(attributeNameX) || getChartData().getChartSelection().getSelectedAttributes().size() == 0)
isSelected = true;
} else if (getChartData().getChartSelection().getSelectedClasses().size() == 0 && getChartData().getChartSelection().isSelectedAttribute(attributeNameX))
isSelected = true;
if (isSelected) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.drawRect((int) Math.round(boundingBox[0]), (int) Math.round(boundingBox[1]), (int) Math.round(boundingBox[2]), (int) Math.round(boundingBox[3]));
gc.setStroke(NORMAL_STROKE);
}
if (showValues || isSelected) {
String aLabel = String.format("%.3f", correlationCoefficient);
valuesList.add(new DrawableValue(aLabel, (int) Math.round(boundingBox[0] + boundingBox[2] / 2), (int) Math.round(boundingBox[1] + boundingBox[3] / 2) - gc.getFont().getSize() / 2, isSelected));
}
}
c--;
}
d++;
}
}
if (valuesList.size() > 0) {
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
DrawableValue.drawValues(gc, valuesList, true, true);
valuesList.clear();
}
}
/**
* draw the y-axis
*
*/
protected void drawYAxis(Graphics2D gc, Dimension size) {
if (inUpdateCoordinates)
return;
if (isTranspose()) {
drawYAxisTransposed(gc, size);
return;
}
final int numberOfAttributes = (attributeNames == null ? 0 : attributeNames.length);
if (numberOfAttributes > 0) {
final SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString()));
final boolean doDraw = (size == null);
Rectangle bbox = null;
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
if (viewer.getClassesList().isDoClustering())
y1 += topTreeSpace;
int longest = 0;
for (String attributeName : attributeNames) {
longest = Math.max(longest, BasicSwing.getStringSize(gc, attributeName, gc.getFont()).getSize().width);
}
int right = Math.max(leftMargin, longest + 5);
if (doDraw)
gc.setColor(getFontColor(ChartViewer.FontKeys.YAxisFont.toString(), Color.BLACK));
double yStep = (y0 - y1) / (double) numberOfAttributes;
int d = numberOfAttributes - 1;
for (String attributeName : attributeNames) {
Dimension labelSize = BasicSwing.getStringSize(gc, attributeName, gc.getFont()).getSize();
int x = right - labelSize.width - 4;
int y = (int) Math.round(y0 - (d + 0.5) * yStep);
if (doDraw) {
if (getChartData().getChartSelection().isSelectedAttribute(attributeName)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, x, y, labelSize.width, labelSize.height, 0, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.YAxisFont.toString(), Color.DARK_GRAY));
gc.drawString(attributeName, x, y);
} else {
Rectangle rect = new Rectangle(x, y, labelSize.width, labelSize.height);
if (bbox == null)
bbox = rect;
else
bbox.add(rect);
}
if (sgc != null) {
sgc.setCurrentItem(new String[]{null, null, attributeName});
drawRect(gc, x, y, labelSize.width, labelSize.height, 0);
sgc.clearCurrentItem();
}
d--;
}
if (size != null && bbox != null) {
size.setSize(bbox.width + 3, bbox.height);
}
}
}
/**
* draw the y-axis
*
*/
protected void drawYAxisTransposed(Graphics2D gc, Dimension size) {
final int numberOfClasses = (classNames == null ? 0 : classNames.length);
if (numberOfClasses > 0) {
final SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString()));
final boolean doDraw = (size == null);
Rectangle bbox = null;
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
if (viewer.getAttributesList().isDoClustering())
y1 += topTreeSpace;
int longest = 0;
for (String className : classNames) {
longest = Math.max(longest, BasicSwing.getStringSize(gc, className, gc.getFont()).getSize().width);
}
int right = Math.max(leftMargin, longest + 5);
if (doDraw)
gc.setColor(getFontColor(ChartViewer.FontKeys.YAxisFont.toString(), Color.BLACK));
double yStep = (y0 - y1) / (double) numberOfClasses;
int c = numberOfClasses - 1;
for (String className : classNames) {
Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize();
int x = right - labelSize.width - 4;
int y = (int) Math.round(y0 - (c + 0.5) * yStep);
if (doDraw) {
if (getChartData().getChartSelection().isSelectedClass(className)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, x, y, labelSize.width, labelSize.height, 0, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.YAxisFont.toString(), Color.DARK_GRAY));
gc.drawString(className, x, y);
} else {
Rectangle rect = new Rectangle(x, y, labelSize.width, labelSize.height);
if (bbox == null)
bbox = rect;
else
bbox.add(rect);
}
if (sgc != null) {
sgc.setCurrentItem(new String[]{null, className});
drawRect(gc, x, y, labelSize.width, labelSize.height, 0);
sgc.clearCurrentItem();
}
c--;
}
if (size != null && bbox != null) {
size.setSize(bbox.width + 3, bbox.height);
}
}
}
/**
* do we need to recompute coordinates?
*
* @return true, if coordinates need to be recomputed
*/
private boolean mustUpdateCoordinates() {
boolean mustUpdate = (dataMatrix.size() == 0);
if (previousTranspose != isTranspose()) {
mustUpdate = true;
}
if (scalingType != ScalingType.LINEAR)
return mustUpdate;
if (previousTranspose != isTranspose()) {
previousTranspose = isTranspose();
previousClusterAttributes = false;
previousClusterClasses = false;
}
{
final ArrayList<String> currentClasses = new ArrayList<>(getChartData().getClassNames());
if (!previousClasses.equals(currentClasses)) {
mustUpdate = true;
previousClasses.clear();
previousClasses.addAll(currentClasses);
}
}
{
final ArrayList<String> currentSamples = new ArrayList<>(getChartData().getSeriesNames());
if (!previousSamples.equals(currentSamples)) {
mustUpdate = true;
previousSamples.clear();
previousSamples.addAll(currentSamples);
}
}
{
final Set<String> currentAttributes = new HashSet<>(getViewer().getAttributesList().getEnabledLabels());
if (!previousAttributes.equals(currentAttributes)) {
mustUpdate = true;
previousAttributes.clear();
previousAttributes.addAll(currentAttributes);
}
}
{
if (!previousClusterClasses && viewer.getClassesList().isDoClustering())
mustUpdate = true;
}
{
if (!previousClusterAttributes && viewer.getAttributesList().isDoClustering())
mustUpdate = true;
}
if (!mustUpdate) {
final Set<String> currentAttributes = new HashSet<>(getViewer().getAttributesList().getAllLabels());
if (!currentAttributes.equals(viewer.getDir().getDocument().getSampleAttributeTable().getNumericalAttributes())) {
viewer.getAttributesList().sync(viewer.getDir().getDocument().getSampleAttributeTable().getNumericalAttributes(), null, false);
mustUpdate = true;
}
}
return mustUpdate;
}
/**
* updates the view
*/
public void updateView() {
if (mustUpdateCoordinates()) {
if (future != null) {
future.cancel(true);
future = null;
}
future = executorService.submit(() -> {
try {
inUpdateCoordinates = true;
updateCoordinates();
SwingUtilities.invokeAndWait(() -> {
try {
if (!previousClusterClasses && viewer.getClassesList().isDoClustering())
updateClassesJList();
previousClusterClasses = viewer.getClassesList().isDoClustering();
if (!previousClusterAttributes && viewer.getAttributesList().isDoClustering())
updateAttributesJList();
previousClusterAttributes = viewer.getAttributesList().isDoClustering();
viewer.repaint();
} catch (Exception e) {
Basic.caught(e);
}
});
} catch (Exception e) {
//Basic.caught(e);
} finally {
future = null;
inUpdateCoordinates = false;
}
});
} else {
if (!previousClusterClasses && viewer.getClassesList().isDoClustering())
updateClassesJList();
previousClusterClasses = viewer.getClassesList().isDoClustering();
if (!previousClusterAttributes && viewer.getAttributesList().isDoClustering())
updateAttributesJList();
previousClusterAttributes = viewer.getAttributesList().isDoClustering();
}
}
/**
* force update
*/
@Override
public void forceUpdate() {
dataMatrix.clear();
}
protected void updateCoordinates() {
System.err.println("Updating...");
dataMatrix.clear();
previousClasses.clear();
previousSamples.clear();
attributesClusteringTree.clear();
classesClusteringTree.clear();
if (classesClusteringTree.getChartSelection() == null)
classesClusteringTree.setChartSelection(viewer.getChartSelection());
if (attributesClusteringTree.getChartSelection() == null)
attributesClusteringTree.setChartSelection(viewer.getChartSelection());
final String[] currentClasses;
{
final Collection<String> list = getViewer().getClassesList().getEnabledLabels();
currentClasses = list.toArray(new String[0]);
}
final String[] currentAttributes;
{
final Collection<String> list = getViewer().getAttributesList().getEnabledLabels();
currentAttributes = list.toArray(new String[0]);
}
for (String className : currentClasses) {
for (String attributeName : currentAttributes) {
try {
dataMatrix.put(className, attributeName, computeCorrelationCoefficent(className, attributeName));
} catch (Exception ex) {
Basic.caught(ex);
}
}
}
if (viewer.getClassesList().isDoClustering()) {
classesClusteringTree.setRootSide(isTranspose() ? ClusteringTree.SIDE.RIGHT : ClusteringTree.SIDE.TOP);
classesClusteringTree.updateClustering(currentClasses, dataMatrix.copy());
final Collection<String> list = classesClusteringTree.getLabelOrder();
classNames = list.toArray(new String[0]);
} else
classNames = currentClasses;
if (viewer.getAttributesList().isDoClustering()) {
attributesClusteringTree.setRootSide(isTranspose() ? ClusteringTree.SIDE.TOP : ClusteringTree.SIDE.RIGHT);
attributesClusteringTree.updateClustering(currentAttributes, dataMatrix.computeTransposedTable());
final Collection<String> list = attributesClusteringTree.getLabelOrder();
attributeNames = list.toArray(new String[0]);
} else
attributeNames = currentAttributes;
chartData.setClassesLabel("");
}
private void updateClassesJList() {
final Collection<String> selected = new ArrayList<>(viewer.getChartSelection().getSelectedClasses());
final Collection<String> ordered = new ArrayList<>(Arrays.asList(classNames));
final Collection<String> others = viewer.getClassesList().getAllLabels();
others.removeAll(ordered);
ordered.addAll(others);
viewer.getClassesList().sync(ordered, viewer.getClassesList().getLabel2ToolTips(), true);
viewer.getClassesList().setDisabledLabels(others);
viewer.getChartSelection().setSelectedClass(selected, true);
}
private void updateAttributesJList() {
final Collection<String> selected = new ArrayList<>(viewer.getChartSelection().getSelectedAttributes());
final Collection<String> ordered = new ArrayList<>(Arrays.asList(attributeNames));
final Collection<String> others = viewer.getAttributesList().getAllLabels();
others.removeAll(ordered);
ordered.addAll(others);
viewer.getAttributesList().sync(ordered, null, true);
viewer.getAttributesList().setDisabledLabels(others);
viewer.getChartSelection().setSelectedAttribute(selected, true);
}
/**
* return Pearson's correlation coefficient
*
* @return Pearson's correlation coefficient
*/
private float computeCorrelationCoefficent(String classNameX, String attributeNameY) {
ArrayList<Double> xValues = new ArrayList<>(getChartData().getSeriesNames().size());
ArrayList<Double> yValues = new ArrayList<>(getChartData().getSeriesNames().size());
for (String sample : getChartData().getSeriesNames()) {
final double x = getChartData().getValueAsDouble(sample, classNameX);
final double y;
final Object obj = viewer.getDir().getDocument().getSampleAttributeTable().get(sample, attributeNameY);
if (obj == null)
y = 0;
else if (obj instanceof Number)
y = ((Number) obj).doubleValue();
else if (NumberUtils.isDouble(obj.toString())) {
y = NumberUtils.parseDouble(obj.toString());
} else
throw new IllegalArgumentException("Attribute '" + attributeNameY + "': has non-numerical value: " + obj);
xValues.add(x);
yValues.add(y);
}
return (float) Correlation.computePersonsCorrelationCoefficent(xValues.size(), xValues, yValues);
}
@Override
public String getChartDrawerName() {
return NAME;
}
public IPopupMenuModifier getPopupMenuModifier() {
return (menu, commandManager) -> {
AttributeCorrelationPlotDrawer.super.getPopupMenuModifier().apply(menu, commandManager);
menu.addSeparator();
{
final AbstractAction action = (new AbstractAction("Show Correlation Values...") {
@Override
public void actionPerformed(ActionEvent e) {
final String classification = viewer.getParentViewer().getClassName();
final StringBuilder buf = new StringBuilder();
buf.append("show window=Message;");
for (String attribute : getChartData().getChartSelection().getSelectedSeries()) {
buf.append(";correlate class='").append(StringUtils.toString(getChartData().getChartSelection().getSelectedClasses(), "' '")).append("'")
.append(" classification='").append(classification).append("' attribute='").append(attribute).append("';");
}
commandManager.getDir().execute(buf.toString(), commandManager);
}
});
action.setEnabled(getChartData().getChartSelection().getSelectedClasses().size() >= 1 &&
getChartData().getChartSelection().getSelectedSeries().size() >= 1);
menu.add(action);
}
menu.addSeparator();
{
final AbstractAction action = (new AbstractAction("Flip Selected Subtree") {
@Override
public void actionPerformed(ActionEvent e) {
if (classesClusteringTree.hasSelectedSubTree()) {
//System.err.println("Rotate Classes");
classesClusteringTree.rotateSelectedSubTree();
final Collection<String> list = classesClusteringTree.getLabelOrder();
classNames = list.toArray(new String[0]);
updateClassesJList();
getJPanel().repaint();
} else if (attributesClusteringTree.hasSelectedSubTree()) {
// System.err.println("Old order: "+Basic.toString(seriesClusteringTree.getLabelOrder(),","));
//System.err.println("Rotate Series");
attributesClusteringTree.rotateSelectedSubTree();
//System.err.println("New order: "+Basic.toString(seriesClusteringTree.getLabelOrder(),","));
final Collection<String> list = attributesClusteringTree.getLabelOrder();
attributeNames = list.toArray(new String[0]);
updateAttributesJList();
getJPanel().repaint();
}
}
});
action.setEnabled(classesClusteringTree.hasSelectedSubTree() != attributesClusteringTree.hasSelectedSubTree());
menu.add(action);
}
};
}
@Override
public void writeData(Writer w) throws IOException {
w.write("AttributeCorrelationPlot");
for (String className : classNames) {
w.write("\t" + className);
}
w.write("\n");
for (String attributeName : attributeNames) {
w.write(attributeName);
for (String className : classNames) {
final double correlationCoefficient = dataMatrix.get(className, attributeName);
w.write(String.format("\t%.4g", correlationCoefficient));
}
w.write("\n");
}
}
@Override
public boolean canCluster(ClusteringTree.TYPE type) {
return (type == null || type == ClusteringTree.TYPE.ATTRIBUTES || type == ClusteringTree.TYPE.CLASSES);
}
public boolean canAttributes() {
return true;
}
} | 35,920 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
BoxChartDrawer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/BoxChartDrawer.java | /*
* BoxChartDrawer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.Geometry;
import jloda.swing.util.ProgramProperties;
import jloda.util.Pair;
import megan.chart.IChartDrawer;
import megan.chart.data.WhiskerData;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.SelectionGraphics;
import megan.core.Document;
import megan.util.ScalingType;
import java.awt.*;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* draws a box chart
* Daniel Huson, 7.2016
*/
public class BoxChartDrawer extends BarChartDrawer implements IChartDrawer {
private static final String NAME = "BoxChart";
/**
* constructor
*/
public BoxChartDrawer() {
super();
}
protected double computeXAxisLabelHeight(Graphics2D gc) {
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
double theHeight = 2 * gc.getFont().getSize();
if (classLabelAngle != 0) {
double sin = Math.abs(Math.sin(classLabelAngle));
for (String className : getChartData().getClassNames()) {
Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize();
theHeight = Math.max(theHeight, gc.getFont().getSize() + sin * labelSize.width);
}
}
return theHeight + 12;
}
protected double computeXAxisLabelHeightTransposed(Graphics2D gc) {
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
double theHeight = 2 * gc.getFont().getSize();
if (classLabelAngle != 0) {
double sin = Math.abs(Math.sin(classLabelAngle));
for (String className : getChartData().getClassNames()) {
Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize();
theHeight = Math.max(theHeight, gc.getFont().getSize() + sin * labelSize.width);
}
}
return theHeight + 12;
}
/**
* draw the x axis
*
*/
protected void drawXAxis(Graphics2D gc) {
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.BLACK));
int x = 5;
int y = getHeight() - bottomMargin + 25;
if (isTranspose())
gc.drawString(getChartData().getClassesLabel(), x, y);
else {
String prefix = null;
final Document doc = getViewer().getDir().getDocument();
final boolean hasGroups = doc.getSampleAttributeTable().hasGroups();
for (String sample : doc.getSampleAttributeTable().getSampleOrder()) {
String groupId = hasGroups ? doc.getSampleAttributeTable().getGroupId(sample) : "all";
if (groupId != null) {
int pos = groupId.indexOf('=');
if (pos > 0) {
if (prefix == null)
prefix = groupId.substring(0, pos);
else if (!prefix.equals(groupId.substring(0, pos))) {
prefix = null;
break;
}
}
}
}
gc.drawString(prefix != null ? prefix : "Grouped", x, y);
}
}
/**
* draw chart
*
*/
public void drawChart(Graphics2D gc) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
// if(sgc!=null) lastDown=(Rectangle)sgc.getSelectionRectangle().clone();
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
double topY;
if (scalingType == ScalingType.PERCENT)
topY = 101;
else if (scalingType == ScalingType.LOG) {
topY = computeMaxYAxisValueLogScale(getMaxValue());
} else if (scalingType == ScalingType.SQRT) {
topY = Math.sqrt(getMaxValue());
} else
topY = 1.1 * getMaxValue();
double yFactor = (y0 - y1) / topY;
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
if (x0 >= x1)
return;
final Document doc = getViewer().getDir().getDocument();
final Map<String, Integer> group2index = new HashMap<>();
final ArrayList<Pair<String, ArrayList<String>>> groupSamplePairs = new ArrayList<>();
final boolean hasGroups = doc.getSampleAttributeTable().hasGroups();
final Random random = new Random(666);
for (String series : doc.getSampleAttributeTable().getSampleOrder()) {
series = cleanSeriesName(series);
if (chartData.getSeriesNames().contains(series)) {
String groupId = hasGroups ? doc.getSampleAttributeTable().getGroupId(series) : "all";
if (groupId != null) {
Integer index = group2index.get(groupId);
if (index == null) {
index = groupSamplePairs.size();
groupSamplePairs.add(new Pair<>(groupId, new ArrayList<>()));
group2index.put(groupId, index);
}
final ArrayList<String> list = groupSamplePairs.get(index).getSecond();
list.add(series);
}
}
}
final WhiskerData whiskerData = new WhiskerData();
final WhiskerData whiskerDataTransformed = new WhiskerData();
int numberOfGroups = groupSamplePairs.size(); // because all samples shown in one column
int numberOfClasses = getChartData().getNumberOfClasses();
if (numberOfGroups == 0 || numberOfClasses == 0)
return;
double xStep = (x1 - x0) / ((numberOfClasses + (isGapBetweenBars() ? 1 : 0)) * numberOfGroups);
final double bigSpace = Math.max(2, Math.min(10, xStep));
xStep = (x1 - x0 - (isGapBetweenBars() ? bigSpace * numberOfGroups : 0)) / (numberOfClasses * numberOfGroups);
final BasicStroke dotted = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{1, 2}, 0);
// main drawing loop:
int d = 0;
for (Pair<String, ArrayList<String>> pair : groupSamplePairs) {
final String groupName = pair.getFirst();
if (isShowXAxis()) {
final double xLabel = leftMargin + (isGapBetweenBars() ? (d + 1) * bigSpace : 0) + ((d + 0.5) * numberOfClasses) * xStep;
Point2D apt = new Point2D.Double(xLabel, getHeight() - 2);
Dimension labelSize = BasicSwing.getStringSize(gc, groupName, gc.getFont()).getSize();
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.BLACK));
drawString(gc, groupName, apt.getX(), apt.getY(), 0);
}
// for each class, compute the whisker data and then draw
int c = 0;
for (String className : getChartData().getClassNames()) {
int xPos = (int) Math.round(x0 + (isGapBetweenBars() ? (d + 1) * bigSpace : 0) + (d * numberOfClasses + c) * xStep);
final boolean isSelected = getChartData().getChartSelection().isSelected(null, className);
if (isShowXAxis()) {
Point2D apt = new Point2D.Double(xPos, getHeight() - bottomMargin + 10);
Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize();
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
if (sgc != null)
sgc.setCurrentItem(new String[]{null, className});
if (isSelected) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.BLACK));
drawString(gc, className, apt.getX(), apt.getY(), classLabelAngle);
if (sgc != null)
sgc.clearCurrentItem();
}
whiskerData.clear();
whiskerDataTransformed.clear();
for (String series : pair.getSecond()) {
double value = getChartData().getValueAsDouble(series, className);
whiskerData.add(value, series);
switch (scalingType) { // modify if not linear scale:
case PERCENT -> {
double total = getChartData().getTotalForSeriesIncludingDisabledAttributes(series);
if (total == 0)
value = 0;
else
value *= (100 / total);
}
case LOG -> {
if (value == 1)
value = Math.log10(2) / 2;
else if (value > 0)
value = Math.log10(value);
}
case SQRT -> {
if (value > 0)
value = Math.sqrt(value);
}
}
whiskerDataTransformed.add(value, series);
}
// draw whiskers:
// coordinates for d-th dataset and c-th class:
final Color color = getChartColors().getClassColor(class2HigherClassMapper.get(className));
final Color darkColor = color.darker();
for (final Pair<Double, String> p : whiskerDataTransformed) {
boolean isSelected2 = isSelected;
final double value = p.getFirst();
final String series = p.getSecond();
if (sgc != null) {
sgc.setCurrentItem(new String[]{series, className});
} else if (!isSelected2)
isSelected2 = getChartData().getChartSelection().isSelected(series, null);
final int x = xPos + random.nextInt(6) - 3;
int height = (int) Math.round(y0 - Math.max(1, value * yFactor));
if (isSelected2) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.fillOval(x - 5, height - 5, 10, 10);
}
gc.setColor(color);
gc.fillOval(x - 1, height - 1, 2, 2);
gc.setColor(darkColor);
gc.drawOval(x - 1, height - 1, 2, 2);
if (sgc != null) {
sgc.clearCurrentItem();
}
}
gc.setColor(isSelected ? ProgramProperties.SELECTION_COLOR : darkColor);
final int minHeight = (int) Math.round(y0 - Math.max(1, whiskerDataTransformed.getMin() * yFactor));
final int quarterHeight = (int) Math.round(y0 - Math.max(1, whiskerDataTransformed.getFirstQuarter() * yFactor));
final int medianHeight = (int) Math.round(y0 - Math.max(1, whiskerDataTransformed.getMedian() * yFactor));
final int threeQuaterHeigth = (int) Math.round(y0 - Math.max(1, whiskerDataTransformed.getThirdQuarter() * yFactor));
final int maxHeight = (int) Math.round(y0 - Math.max(1, whiskerDataTransformed.getMax() * yFactor));
gc.drawLine(xPos - 4, minHeight, xPos + 4, minHeight);
gc.drawLine(xPos - 4, maxHeight, xPos + 4, maxHeight);
gc.drawLine(xPos - 7, quarterHeight, xPos + 7, quarterHeight);
gc.setStroke(HEAVY_STROKE);
gc.drawLine(xPos - 6, medianHeight, xPos + 6, medianHeight);
gc.setStroke(NORMAL_STROKE);
gc.drawLine(xPos - 7, threeQuaterHeigth, xPos + 7, threeQuaterHeigth);
gc.drawLine(xPos - 7, quarterHeight, xPos - 7, threeQuaterHeigth);
gc.drawLine(xPos + 7, quarterHeight, xPos + 7, threeQuaterHeigth);
gc.setStroke(dotted);
gc.drawLine(xPos, minHeight, xPos, quarterHeight);
gc.drawLine(xPos, maxHeight, xPos, threeQuaterHeigth);
gc.setStroke(NORMAL_STROKE);
if (sgc != null)
sgc.clearCurrentItem();
if (showValues || isSelected) {
String label = "" + (int) whiskerData.getMedian();
valuesList.add(new DrawableValue(label, xPos - 4, medianHeight - 1, isSelected));
if (minHeight > medianHeight) {
label = "" + (int) whiskerData.getMin();
valuesList.add(new DrawableValue(label, xPos - 4, minHeight + getFont().getSize() + 1, isSelected));
}
if (medianHeight - getFont().getSize() > maxHeight) {
label = "" + (int) whiskerData.getMax();
valuesList.add(new DrawableValue(label, xPos - 4, maxHeight - 1, isSelected));
}
}
c++;
}
d++;
}
if (valuesList.size() > 0) {
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
DrawableValue.drawValues(gc, valuesList, true, false);
valuesList.clear();
}
}
/**
* draw chart
*
*/
public void drawChartTransposed(Graphics2D gc) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
// if(sgc!=null) lastDown=(Rectangle)sgc.getSelectionRectangle().clone();
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
double topY;
if (scalingType == ScalingType.PERCENT)
topY = 101;
else if (scalingType == ScalingType.LOG) {
topY = computeMaxYAxisValueLogScale(getMaxValue());
} else if (scalingType == ScalingType.SQRT) {
topY = Math.sqrt(getMaxValue());
} else
topY = 1.1 * getMaxValue();
double yFactor = (y0 - y1) / topY;
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
if (x0 >= x1)
return;
final Document doc = getViewer().getDir().getDocument();
final Map<String, Integer> group2index = new HashMap<>();
final ArrayList<Pair<String, ArrayList<String>>> groupSamplePairs = new ArrayList<>();
final boolean hasGroups = doc.getSampleAttributeTable().hasGroups();
final Random random = new Random(666);
for (String series : doc.getSampleAttributeTable().getSampleOrder()) {
series = cleanSeriesName(series);
if (chartData.getSeriesNames().contains(series)) {
String groupId = hasGroups ? doc.getSampleAttributeTable().getGroupId(series) : "all";
if (groupId != null) {
Integer index = group2index.get(groupId);
if (index == null) {
index = groupSamplePairs.size();
groupSamplePairs.add(new Pair<>(groupId, new ArrayList<>()));
group2index.put(groupId, index);
}
final ArrayList<String> list = groupSamplePairs.get(index).getSecond();
list.add(series);
}
}
}
final WhiskerData whiskerData = new WhiskerData();
final WhiskerData whiskerDataTransformed = new WhiskerData();
int numberOfGroups = groupSamplePairs.size(); // because all samples shown in one column
int numberOfClasses = getChartData().getNumberOfClasses();
if (numberOfGroups == 0 || numberOfClasses == 0)
return;
double xStep = (x1 - x0) / ((numberOfGroups + (isGapBetweenBars() ? 1 : 0)) * numberOfClasses);
final double bigSpace = Math.max(2, Math.min(10, xStep));
xStep = (x1 - x0 - (isGapBetweenBars() ? bigSpace * numberOfClasses : 0)) / (numberOfClasses * numberOfGroups);
final BasicStroke dotted = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{1, 2}, 0);
// main drawing loop:
int d = 0;
for (Pair<String, ArrayList<String>> pair : groupSamplePairs) {
final String groupName = pair.getFirst();
// for each class, compute the whisker data and then draw
int c = 0;
for (String className : getChartData().getClassNames()) {
whiskerData.clear();
whiskerDataTransformed.clear();
final int xPos = (int) Math.round(x0 + (isGapBetweenBars() ? (c + 1) * bigSpace : 0) + (c * numberOfGroups + d) * xStep);
final boolean isSelected = getChartData().getChartSelection().isSelected(null, className);
if (isShowXAxis()) {
if (group2index.size() > 1) {
Point2D bpt = new Point2D.Double(xPos, getHeight() - bottomMargin + 10);
final Dimension labelSize = BasicSwing.getStringSize(gc, groupName, gc.getFont()).getSize();
if (classLabelAngle == 0) {
bpt.setLocation(bpt.getX() - labelSize.getWidth() / 2, bpt.getY() + getFont().getSize() + 1);
} else {
bpt.setLocation(bpt.getX() - getFont().getSize() - 1, bpt.getY());
if (classLabelAngle > Math.PI / 2) {
bpt = Geometry.translateByAngle(bpt, classLabelAngle, -labelSize.width);
}
}
gc.setColor(Color.LIGHT_GRAY);
drawString(gc, groupName, bpt.getX(), bpt.getY(), classLabelAngle);
}
Point2D apt = new Point2D.Double(xPos, getHeight() - bottomMargin + 10);
final Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize();
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
if (sgc != null)
sgc.setCurrentItem(new String[]{null, className});
if (isSelected) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.BLACK));
drawString(gc, className, apt.getX(), apt.getY(), classLabelAngle);
if (sgc != null)
sgc.clearCurrentItem();
}
for (String series : pair.getSecond()) {
double value = getChartData().getValueAsDouble(series, className);
whiskerData.add(value, series);
switch (scalingType) { // modify if not linear scale:
case PERCENT -> {
double total = getChartData().getTotalForSeriesIncludingDisabledAttributes(series);
if (total == 0)
value = 0;
else
value *= (100 / total);
}
case LOG -> {
if (value == 1)
value = Math.log10(2) / 2;
else if (value > 0)
value = Math.log10(value);
}
case SQRT -> {
if (value > 0)
value = Math.sqrt(value);
}
}
whiskerDataTransformed.add(value, series);
}
// draw whiskers:
// coordinates for d-th dataset and c-th class:
final Color color = getChartColors().getClassColor(class2HigherClassMapper.get(className));
final Color darkColor = color.darker();
for (final Pair<Double, String> p : whiskerDataTransformed) {
final double value = p.getFirst();
final String series = p.getSecond();
boolean isSelected2 = isSelected;
if (sgc != null) {
sgc.setCurrentItem(new String[]{series, className});
} else if (!isSelected2)
isSelected2 = getChartData().getChartSelection().isSelected(series, null);
final int x = xPos + random.nextInt(6) - 3;
int height = (int) Math.round(y0 - Math.max(1, value * yFactor));
if (isSelected2) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.fillOval(x - 5, height - 5, 10, 10);
}
gc.setColor(color);
gc.fillOval(x - 1, height - 1, 2, 2);
gc.setColor(darkColor);
gc.drawOval(x - 1, height - 1, 2, 2);
if (sgc != null)
sgc.clearCurrentItem();
}
gc.setColor(isSelected ? ProgramProperties.SELECTION_COLOR : darkColor);
final int minHeight = (int) Math.round(y0 - Math.max(1, whiskerDataTransformed.getMin() * yFactor));
final int quarterHeight = (int) Math.round(y0 - Math.max(1, whiskerDataTransformed.getFirstQuarter() * yFactor));
final int medianHeight = (int) Math.round(y0 - Math.max(1, whiskerDataTransformed.getMedian() * yFactor));
final int threeQuaterHeigth = (int) Math.round(y0 - Math.max(1, whiskerDataTransformed.getThirdQuarter() * yFactor));
final int maxHeight = (int) Math.round(y0 - Math.max(1, whiskerDataTransformed.getMax() * yFactor));
gc.drawLine(xPos - 4, minHeight, xPos + 4, minHeight);
gc.drawLine(xPos - 4, maxHeight, xPos + 4, maxHeight);
gc.drawLine(xPos - 7, quarterHeight, xPos + 7, quarterHeight);
gc.setStroke(HEAVY_STROKE);
gc.drawLine(xPos - 6, medianHeight, xPos + 6, medianHeight);
gc.setStroke(NORMAL_STROKE);
gc.drawLine(xPos - 7, threeQuaterHeigth, xPos + 7, threeQuaterHeigth);
gc.drawLine(xPos - 7, quarterHeight, xPos - 7, threeQuaterHeigth);
gc.drawLine(xPos + 7, quarterHeight, xPos + 7, threeQuaterHeigth);
gc.setStroke(dotted);
gc.drawLine(xPos, minHeight, xPos, quarterHeight);
gc.drawLine(xPos, maxHeight, xPos, threeQuaterHeigth);
gc.setStroke(NORMAL_STROKE);
if (sgc != null)
sgc.clearCurrentItem();
if (showValues || isSelected) {
String label = "" + (int) whiskerData.getMedian();
valuesList.add(new DrawableValue(label, xPos - 4, medianHeight - 1, isSelected));
if (minHeight > medianHeight) {
label = "" + (int) whiskerData.getMin();
valuesList.add(new DrawableValue(label, xPos - 4, minHeight + getFont().getSize() + 1, isSelected));
}
if (medianHeight - getFont().getSize() > maxHeight) {
label = "" + (int) whiskerData.getMax();
valuesList.add(new DrawableValue(label, xPos - 4, maxHeight - 1, isSelected));
}
}
c++;
}
d++;
}
if (valuesList.size() > 0) {
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
DrawableValue.drawValues(gc, valuesList, true, false);
valuesList.clear();
}
}
private String cleanSeriesName(String series) {
if (series.endsWith(".rma") || series.endsWith(".rma2") || series.endsWith(".rma6") || series.endsWith(".daa"))
return series.substring(0, series.lastIndexOf("."));
else
return series;
}
@Override
public String getChartDrawerName() {
return NAME;
}
public void updateView() {
System.err.println("UpdateView");
}
}
| 26,553 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
DrawableValue.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/DrawableValue.java | /*
* DrawableValue.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.ProgramProperties;
import java.awt.*;
import java.util.LinkedList;
/**
* a drawable value
* Daniel Huson, 2.2013
*/
public class DrawableValue {
private final String label;
private final int x;
private final int y;
private final boolean selected;
/**
* constructor
*
*/
public DrawableValue(String label, int x, int y, boolean selected) {
this.label = label;
this.x = x;
this.y = y;
this.selected = selected;
}
/**
* get label
*
* @return label
*/
public String getLabel() {
return label;
}
/**
* get x coordinate
*
* @return x coordinate
*/
public int getX() {
return x;
}
/**
* get y coordinate
*
* @return y coordinate
*/
public int getY() {
return y;
}
/**
* is selected
*
* @return selected
*/
private boolean isSelected() {
return selected;
}
/**
* draw the label
*
*/
private void draw(Graphics2D gc, boolean centerLabelWidth, boolean centerLabelHeight) {
if (centerLabelWidth || centerLabelHeight) {
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
gc.drawString(label, (int) (x - (centerLabelWidth ? labelSize.getWidth() / 2 : 0)), (int) (y + (centerLabelHeight ? labelSize.getHeight() / 2 : 0)));
} else
gc.drawString(label, x, y);
}
/**
* draw all values
*
*/
public static void drawValues(Graphics2D gc, LinkedList<DrawableValue> valuesList, boolean centerLabelWidth, boolean centerLabelHeight) {
gc.setColor(Color.LIGHT_GRAY);
for (DrawableValue value : valuesList) {
if (!value.isSelected())
value.draw(gc, centerLabelWidth, centerLabelHeight);
}
gc.setColor(ProgramProperties.SELECTION_COLOR_ADDITIONAL_TEXT);
for (DrawableValue value : valuesList) {
if (value.isSelected())
value.draw(gc, centerLabelWidth, centerLabelHeight);
}
}
}
| 3,030 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
LineChartDrawer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/LineChartDrawer.java | /*
* LineChartDrawer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.Geometry;
import jloda.swing.util.ProgramProperties;
import jloda.util.CollectionUtils;
import megan.chart.IChartDrawer;
import megan.chart.data.DefaultChartData;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.SelectionGraphics;
import megan.util.ScalingType;
import java.awt.*;
import java.awt.geom.Point2D;
import java.util.Objects;
/**
* draws a line chart
* Daniel Huson, 5.2012
*/
public class LineChartDrawer extends BarChartDrawer implements IChartDrawer {
private static final String NAME = "LineChart";
/**
* constructor
*/
public LineChartDrawer() {
}
/**
* draw bars with colors representing classes
*
*/
public void drawChart(Graphics2D gc) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
double topY;
if (scalingType == ScalingType.PERCENT)
topY = 101;
else if (scalingType == ScalingType.LOG) {
topY = computeMaxYAxisValueLogScale(getMaxValue());
} else if (scalingType == ScalingType.SQRT) {
topY = Math.sqrt(getMaxValue());
} else
topY = 1.1 * getMaxValue();
double yFactor = (y0 - y1) / topY;
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
if (x0 >= x1)
return;
int numberOfDataSets = getChartData().getNumberOfSeries();
double xStep = (x1 - x0) / (2 * numberOfDataSets);
double bigSpace = Math.max(2, Math.min(10, xStep));
xStep = (x1 - x0 - bigSpace * numberOfDataSets) / numberOfDataSets;
Point[] previousPoint = new Point[getChartData().getNumberOfClasses()];
// main drawing loop:
int d = 0;
for (String series : getChartData().getSeriesNames()) {
if (showXAxis) {
double xLabel = x0 + bigSpace + d * bigSpace + (d + 0.5) * xStep;
Point2D apt = new Point2D.Double(xLabel, getHeight() - bottomMargin + 10);
String label = seriesLabelGetter.getLabel(series);
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
if (getChartData().getChartSelection().isSelected(series, null)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.DARK_GRAY));
if (sgc != null)
sgc.setCurrentItem(new String[]{series, null});
drawString(gc, label, apt.getX(), apt.getY(), classLabelAngle);
if (sgc != null)
sgc.clearCurrentItem();
}
int c = 0;
for (String className : getChartData().getClassNames()) {
double value;
if (scalingType == ScalingType.PERCENT) {
double total = getChartData().getTotalForSeriesIncludingDisabledAttributes(series);
if (total == 0)
value = 0;
else
value = 100 * getChartData().getValueAsDouble(series, className) / total;
} else if (scalingType == ScalingType.LOG) {
value = getChartData().getValueAsDouble(series, className);
if (value > 0)
value = Math.log10(value);
} else if (scalingType == ScalingType.SQRT) {
value = getChartData().getValueAsDouble(series, className);
if (value > 0)
value = Math.sqrt(value);
} else
value = getChartData().getValueAsDouble(series, className);
double xBar = x0 + bigSpace + d * bigSpace + d * xStep;
double height = value * yFactor;
Point aPt = new Point((int) Math.round(xBar + xStep / 2.0), (int) Math.round(y0 - height));
boolean isSelected = getChartData().getChartSelection().isSelected(null, className);
Color color = getChartColors().getClassColor(class2HigherClassMapper.get(className));
if (isSelected) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.setStroke(HEAVY_STROKE);
} else {
gc.setColor(color);
gc.setStroke(NORMAL_STROKE);
}
Point bPt = previousPoint[c];
if (bPt != null) {
if (sgc != null)
sgc.setCurrentItem(new String[]{series, className});
gc.drawLine(bPt.x, bPt.y, aPt.x, aPt.y);
if (sgc != null)
sgc.clearCurrentItem();
}
previousPoint[c] = aPt;
if (!isSelected) {
isSelected = getChartData().getChartSelection().isSelected(series, className);
if (isSelected) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.setStroke(HEAVY_STROKE);
}
}
if (!isSelected) {
gc.setColor(color.darker());
if (sgc != null)
sgc.setCurrentItem(new String[]{series, className});
gc.drawOval(aPt.x - 1, aPt.y - 1, 2, 2);
if (sgc != null)
sgc.clearCurrentItem();
} else {
gc.drawOval(aPt.x - 2, aPt.y - 2, 4, 4);
gc.setStroke(NORMAL_STROKE);
}
c++;
if (showValues || isSelected) {
String label = "" + (int) getChartData().getValueAsDouble(series, className);
valuesList.add(new DrawableValue(label, aPt.x, aPt.y - 3, isSelected));
}
}
d++;
}
if (valuesList.size() > 0) {
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
DrawableValue.drawValues(gc, valuesList, true, false);
valuesList.clear();
}
}
/**
* draw bars in which colors are by dataset
*
*/
public void drawChartTransposed(Graphics2D gc) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
final int y0 = getHeight() - bottomMargin;
final int y1 = topMargin;
final String[] series = getChartData().getSeriesNames().toArray(new String[getChartData().getNumberOfSeries()]);
final double topY;
final double[] percentFactor;
if (scalingType == ScalingType.PERCENT) {
final String[] seriesIncludingDisabled = getChartData().getSeriesNamesIncludingDisabled();
var percentFactorIncludingDisabled = computePercentFactorPerSampleForTransposedChart((DefaultChartData) getChartData(), seriesIncludingDisabled);
topY = computeMaxClassValueUsingPercentFactorPerSeries((DefaultChartData) getChartData(), seriesIncludingDisabled, percentFactorIncludingDisabled);
percentFactor=new double[series.length];
for(var i=0;i<series.length;i++) {
var j= CollectionUtils.getIndex(series[i],seriesIncludingDisabled);
percentFactor[i]=percentFactorIncludingDisabled[j];
}
} else if (scalingType == ScalingType.LOG) {
topY = computeMaxYAxisValueLogScale(getMaxValue());
percentFactor = null;
} else if (scalingType == ScalingType.SQRT) {
topY = Math.sqrt(getMaxValue());
percentFactor = null;
} else {
topY = 1.1 * getMaxValue();
percentFactor = null;
}
final double yFactor = (y0 - y1) / topY;
final int x0 = leftMargin;
final int x1 = getWidth() - rightMargin;
if (x0 >= x1)
return;
final int numberOfClasses = getChartData().getNumberOfClasses();
double xStep = (x1 - x0) / (2 * numberOfClasses);
final double bigSpace = Math.max(2, Math.min(10, xStep));
xStep = (x1 - x0 - bigSpace * numberOfClasses) / numberOfClasses;
Point[] previousPoint = new Point[getChartData().getNumberOfSeries()];
// main drawing loop:
int c = 0;
for (String className : getChartData().getClassNames()) {
if (showXAxis) {
final double xLabel = x0 + bigSpace + c * bigSpace + (c + 0.5) * xStep;
Point2D apt = new Point2D.Double(xLabel, getHeight() - bottomMargin + 10);
final Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize();
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
if (getChartData().getChartSelection().isSelected(null, className)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.DARK_GRAY));
if (sgc != null)
sgc.setCurrentItem(new String[]{null, className});
drawString(gc, className, apt.getX(), apt.getY(), classLabelAngle);
if (sgc != null)
sgc.clearCurrentItem();
}
int d = 0;
for (int i = 0; i < series.length; i++) {
final String seriesName = series[i];
double value = getChartData().getValueAsDouble(seriesName, className);
switch (scalingType) { // modify if not linear scale:
case PERCENT -> {
value *= Objects.requireNonNull(percentFactor)[i];
}
case LOG -> {
if (value == 1)
value = Math.log10(2) / 2;
else if (value > 0)
value = Math.log10(value);
}
case SQRT -> {
if (value > 0)
value = Math.sqrt(value);
}
}
final double xBar = x0 + bigSpace + c * bigSpace + c * xStep;
final double height = value * yFactor;
final Point aPt = new Point((int) Math.round(xBar + xStep / 2.0), (int) Math.round(y0 - height));
boolean isSelected = getChartData().getChartSelection().isSelected(seriesName, null);
final Color color = getChartColors().getSampleColor(seriesName);
if (isSelected) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.setStroke(HEAVY_STROKE);
} else {
gc.setColor(color);
gc.setStroke(NORMAL_STROKE);
}
Point bPt = previousPoint[d];
if (bPt != null) {
if (sgc != null)
sgc.setCurrentItem(new String[]{seriesName, className});
gc.drawLine(bPt.x, bPt.y, aPt.x, aPt.y);
if (sgc != null)
sgc.clearCurrentItem();
}
previousPoint[d] = aPt;
if (!isSelected) {
isSelected = getChartData().getChartSelection().isSelected(seriesName, className);
if (isSelected) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.setStroke(HEAVY_STROKE);
}
}
if (!isSelected) {
gc.setColor(color.darker());
if (sgc != null)
sgc.setCurrentItem(new String[]{seriesName, className});
gc.drawOval(aPt.x - 1, aPt.y - 1, 2, 2);
if (sgc != null)
sgc.clearCurrentItem();
} else {
gc.drawOval(aPt.x - 2, aPt.y - 2, 4, 4);
gc.setStroke(NORMAL_STROKE);
}
d++;
if (showValues || isSelected) {
String label = "" + (int) getChartData().getValueAsDouble(seriesName, className);
valuesList.add(new DrawableValue(label, aPt.x, aPt.y - 3, isSelected));
}
}
c++;
}
if (valuesList.size() > 0) {
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
DrawableValue.drawValues(gc, valuesList, true, false);
valuesList.clear();
}
}
public boolean canShowValues() {
return true;
}
@Override
public String getChartDrawerName() {
return NAME;
}
}
| 14,995 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
StackedLineChartDrawer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/StackedLineChartDrawer.java | /*
* StackedLineChartDrawer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.Geometry;
import jloda.swing.util.ProgramProperties;
import jloda.util.CollectionUtils;
import jloda.util.Triplet;
import megan.chart.IChartDrawer;
import megan.chart.data.DefaultChartData;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.SelectionGraphics;
import megan.util.ScalingType;
import java.awt.*;
import java.awt.geom.Point2D;
import java.util.LinkedList;
import java.util.Objects;
/**
* draws a stacked line chart
* Daniel Huson, 5.2012
*/
public class StackedLineChartDrawer extends BarChartDrawer implements IChartDrawer {
private static final String NAME = "StackedLineChart";
/**
* constructor
*/
public StackedLineChartDrawer() {
transposedHeightsAdditive = true;
setSupportedScalingTypes(ScalingType.LINEAR, ScalingType.PERCENT);
}
/**
* draw bars with colors representing classes
*
*/
public void drawChart(Graphics2D gc) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
double topY = switch (scalingType) {
case PERCENT -> 101;
case LOG -> computeMaxYAxisValueLogScale(getMaxValue());
case SQRT -> Math.sqrt(getMaxValue());
default -> 1.1 * getMaxValue();
};
double yFactor = (y0 - y1) / topY;
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
if (x0 >= x1)
return;
int numberOfSeries = getChartData().getNumberOfSeries();
double xStep = (x1 - x0) / (2 * numberOfSeries);
double bigSpace = Math.max(2, Math.min(10, xStep));
xStep = (x1 - x0 - bigSpace * numberOfSeries) / numberOfSeries;
Point[] previousPoint = new Point[getChartData().getNumberOfClasses()];
java.util.List<Triplet<String, String, int[]>> list = new LinkedList<>();
// main drawing loop:
int d = 0;
for (String series : getChartData().getSeriesNames()) {
if (showXAxis) {
double xLabel = x0 + bigSpace + d * bigSpace + (d + 0.5) * xStep;
Point2D apt = new Point2D.Double(xLabel, getHeight() - bottomMargin + 10);
String label = seriesLabelGetter.getLabel(series);
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
if (getChartData().getChartSelection().isSelected(series, null)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.BLACK));
if (sgc != null)
sgc.setCurrentItem(new String[]{series, null});
drawString(gc, label, apt.getX(), apt.getY(), classLabelAngle);
if (sgc != null)
sgc.clearCurrentItem();
}
double currentHeight = y0;
double currentValueForLog = 0;
int c = 0;
for (String className : getChartData().getClassNames()) {
double value;
if (scalingType == ScalingType.PERCENT) {
double total = getChartData().getTotalForSeriesIncludingDisabledAttributes(series);
if (total == 0)
value = 0;
else
value = 100 * getChartData().getValueAsDouble(series, className) / total;
} else if (scalingType == ScalingType.LOG) {
value = getChartData().getValueAsDouble(series, className);
if (value >= 1) {
value = Math.log10(value + currentValueForLog);
if (currentValueForLog >= 1)
value -= Math.log10(currentValueForLog);
}
currentValueForLog += getChartData().getValueAsDouble(series, className);
} else if (scalingType == ScalingType.SQRT) {
value = getChartData().getValueAsDouble(series, className);
if (value >= 1) {
value = Math.sqrt(value + currentValueForLog);
if (currentValueForLog >= 1)
value -= Math.sqrt(currentValueForLog);
}
currentValueForLog += getChartData().getValueAsDouble(series, className);
} else
value = getChartData().getValueAsDouble(series, className);
double xBar = x0 + bigSpace + d * bigSpace + d * xStep;
double height = value * yFactor;
Point aPt = new Point((int) Math.round(xBar + xStep / 2.0), (int) Math.round(currentHeight - height));
currentHeight -= height;
Point bPt = previousPoint[c];
if (bPt == null && numberOfSeries == 1)
bPt = new Point(aPt.x - 2, aPt.y);
if (bPt != null) {
Triplet<String, String, int[]> triplet = new Triplet<>(series, className, new int[]{bPt.x, bPt.y, aPt.x, aPt.y});
list.add(triplet);
}
previousPoint[c] = aPt;
c++;
}
d++;
}
// need to draw in reverse order to get correct ordering of polygons
list = CollectionUtils.reverseList(list);
for (Triplet<String, String, int[]> pair : list) {
String series = pair.getFirst();
String className = pair.getSecond();
int[] coords = pair.getThird();
Color color = getChartColors().getClassColor(class2HigherClassMapper.get(className));
gc.setColor(color);
int[] xs = new int[]{coords[0], coords[2], coords[2], coords[0]};
int[] ys = new int[]{coords[1], coords[3], y0, y0};
gc.fillPolygon(xs, ys, 4);
gc.setColor(color.darker());
if (sgc != null)
sgc.setCurrentItem(new String[]{series, className});
gc.drawLine(coords[0], coords[1], coords[2], coords[3]);
if (sgc != null)
sgc.clearCurrentItem();
}
Triplet<String, String, int[]> current = null;
for (Triplet<String, String, int[]> next : list) {
if (current != null) {
String className = current.getSecond();
String series = current.getFirst();
int[] coords = current.getThird();
if (getChartData().getChartSelection().isSelected(null, className)) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.drawLine(coords[0], coords[1], coords[2], coords[3]);
coords = next.getThird();
gc.drawLine(coords[0], coords[1], coords[2], coords[3]);
gc.setStroke(NORMAL_STROKE);
} else if (getChartData().getChartSelection().isSelected(series, null)) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.drawOval(coords[2] - 1, coords[3] - 1, 2, 2);
gc.setStroke(NORMAL_STROKE);
}
}
current = next;
}
if (current != null) {
String className = current.getSecond();
String series = current.getFirst();
int[] coords = current.getThird();
if (getChartData().getChartSelection().isSelected(null, className)) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.drawLine(coords[0], coords[1], coords[2], coords[3]);
gc.setStroke(NORMAL_STROKE);
} else if (getChartData().getChartSelection().isSelected(series, null)) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.drawOval(coords[2] - 1, coords[3] - 1, 2, 2);
gc.setStroke(NORMAL_STROKE);
}
}
}
/**
* draw bars in which colors are by dataset
*
*/
public void drawChartTransposed(Graphics2D gc) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
final String[] series = getChartData().getSeriesNames().toArray(new String[getChartData().getNumberOfSeries()]);
final double topY;
final double[] percentFactor;
switch (scalingType) {
case PERCENT -> {
final String[] seriesIncludingDisabled = getChartData().getSeriesNamesIncludingDisabled();
var percentFactorIncludingDisabled = computePercentFactorPerSampleForTransposedChart((DefaultChartData) getChartData(), seriesIncludingDisabled);
topY = computeMaxClassValueUsingPercentFactorPerSeries((DefaultChartData) getChartData(), seriesIncludingDisabled, percentFactorIncludingDisabled);
percentFactor=new double[series.length];
for(var i=0;i<series.length;i++) {
var j= CollectionUtils.getIndex(series[i],seriesIncludingDisabled);
percentFactor[i]=percentFactorIncludingDisabled[j];
}
}
case LOG -> {
topY = computeMaxYAxisValueLogScale(getMaxValue());
percentFactor = null;
}
case SQRT -> {
topY = Math.sqrt(getMaxValue());
percentFactor = null;
}
default /* case LINEAR */ -> {
topY = 1.1 * getMaxValue();
percentFactor = null;
}
}
final double yFactor = (y0 - y1) / topY;
final int x0 = leftMargin;
final int x1 = getWidth() - rightMargin;
if (x0 >= x1)
return;
final int numberOfClasses = getChartData().getNumberOfClasses();
double xStep = (x1 - x0) / (2 * Math.max(1, numberOfClasses));
final double bigSpace = Math.max(2, Math.min(10, xStep));
xStep = (x1 - x0 - bigSpace * numberOfClasses) / numberOfClasses;
Point[] previousPoint = new Point[getChartData().getNumberOfSeries()];
java.util.List<Triplet<String, String, int[]>> list = new LinkedList<>();
// main drawing loop:
int c = 0;
for (String className : getChartData().getClassNames()) {
if (showXAxis) {
double xLabel = x0 + bigSpace + c * bigSpace + (c + 0.5) * xStep;
Point2D apt = new Point2D.Double(xLabel, getHeight() - bottomMargin + 10);
Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize();
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
if (getChartData().getChartSelection().isSelected(null, className)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.BLACK));
if (sgc != null)
sgc.setCurrentItem(new String[]{null, className});
drawString(gc, className, apt.getX(), apt.getY(), classLabelAngle);
if (sgc != null)
sgc.clearCurrentItem();
}
double currentHeight = y0;
double currentValueForLog = 0;
int d = 0;
for (int i = 0; i < series.length; i++) {
final String seriesName = series[i];
double value = getChartData().getValueAsDouble(seriesName, className);
switch (scalingType) { // modify if not linear scale:
case PERCENT -> {
value *= Objects.requireNonNull(percentFactor)[i];
}
case LOG -> {
if (value >= 1) {
if (currentValueForLog <= 1) {
value = Math.log10(value);
} else {
value = Math.log10(value + currentValueForLog) - Math.log10(currentValueForLog);
}
currentValueForLog += getChartData().getValueAsDouble(seriesName, className);
} else // no change in height
value = 0;
}
case SQRT -> {
if (value >= 1) {
if (currentValueForLog <= 1) {
value = Math.sqrt(value);
} else {
value = Math.sqrt(value + currentValueForLog) - Math.sqrt(currentValueForLog);
}
currentValueForLog += getChartData().getValueAsDouble(seriesName, className);
} else // no change in height
value = 0;
}
}
final double xBar = x0 + bigSpace + c * bigSpace + c * xStep;
final double height = value * yFactor;
final Point aPt = new Point((int) Math.round(xBar + xStep / 2.0), (int) Math.round(currentHeight - height));
currentHeight -= height;
Point bPt = previousPoint[d];
if (bPt == null && numberOfClasses == 1)
bPt = new Point(aPt.x - 2, aPt.y);
if (bPt != null) {
Triplet<String, String, int[]> triplet = new Triplet<>(seriesName, className, new int[]{bPt.x, bPt.y, aPt.x, aPt.y});
list.add(triplet);
}
previousPoint[d] = aPt;
d++;
}
c++;
}
// need to draw in reverse order to get correct ordering of polygons
list = CollectionUtils.reverseList(list);
for (Triplet<String, String, int[]> triplet : list) {
String seriesName = triplet.getFirst();
String className = triplet.getSecond();
int[] coords = triplet.getThird();
Color color = getChartColors().getSampleColor(seriesName);
gc.setColor(color);
int[] xs = new int[]{coords[0], coords[2], coords[2], coords[0]};
int[] ys = new int[]{coords[1], coords[3], y0, y0};
gc.fillPolygon(xs, ys, 4);
gc.setColor(color.darker());
if (sgc != null)
sgc.setCurrentItem(new String[]{seriesName, className});
gc.drawLine(coords[0], coords[1], coords[2], coords[3]);
if (sgc != null)
sgc.clearCurrentItem();
}
Triplet<String, String, int[]> current = null;
for (Triplet<String, String, int[]> next : list) {
if (current != null) {
String seriesName = current.getFirst();
String className = current.getSecond();
int[] coords = current.getThird();
if (getChartData().getChartSelection().isSelected(seriesName, null)) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.drawLine(coords[0], coords[1], coords[2], coords[3]);
coords = next.getThird();
gc.drawLine(coords[0], coords[1], coords[2], coords[3]);
gc.setStroke(NORMAL_STROKE);
} else if (getChartData().getChartSelection().isSelected(null, className)) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.drawOval(coords[2] - 1, coords[3] - 1, 2, 2);
gc.setStroke(NORMAL_STROKE);
}
}
current = next;
}
if (current != null) {
String seriesName = current.getFirst();
String className = current.getSecond();
int[] coords = current.getThird();
if (getChartData().getChartSelection().isSelected(seriesName, null)) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.drawLine(coords[0], coords[1], coords[2], coords[3]);
gc.setStroke(NORMAL_STROKE);
} else if (getChartData().getChartSelection().isSelected(null, className)) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.drawOval(coords[2] - 1, coords[3] - 1, 2, 2);
gc.setStroke(NORMAL_STROKE);
}
}
}
/**
* gets the max value used in the plot
*
* @return max value
*/
@Override
protected double getMaxValue() {
if (!isTranspose())
return getChartData().getMaxTotalSeries();
else {
double maxValue = 0;
for (String className : getChartData().getClassNames()) {
double sum = 0;
for (String series : getChartData().getSeriesNames()) {
sum += getChartData().getValueAsDouble(series, className);
}
maxValue = Math.max(sum, maxValue);
}
return maxValue;
}
}
public boolean canShowValues() {
return false;
}
@Override
public String getChartDrawerName() {
return NAME;
}
}
| 19,789 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
OverlapAvoider.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/OverlapAvoider.java | /*
* OverlapAvoider.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.util.Pair;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.util.*;
/**
* datastructure for avoiding overlaps of rectangles
* Daniel Huson, 7.2012
*/
public class OverlapAvoider<T> {
private final Vector<Pair<Rectangle2D, T>> data = new Vector<>();
private int currentComparison = 0;
private Rectangle2D previousHit;
private final SortedSet<Integer> sortedByMinX;
private final SortedSet<Integer> sortedByMaxX;
private final SortedSet<Integer> sortedByMinY;
private final SortedSet<Integer> sortedByMaxY;
private final Rectangle2D bbox = new Rectangle2D.Double();
/**
* constructor
*/
public OverlapAvoider() {
sortedByMinX = new TreeSet<>((id1, id2) -> {
double d1 = (id1 != currentComparison ? data.get(id1).getFirst().getMinX() : data.get(id1).getFirst().getMaxX());
double d2 = (id2 != currentComparison ? data.get(id2).getFirst().getMinX() : data.get(id2).getFirst().getMaxX());
if (d1 < d2)
return -1;
else if (d1 > d2)
return 1;
else return id1.compareTo(id2);
});
sortedByMaxX = new TreeSet<>((id1, id2) -> {
double d1 = (id1 != currentComparison ? data.get(id1).getFirst().getMaxX() : data.get(id1).getFirst().getMinX());
double d2 = (id2 != currentComparison ? data.get(id2).getFirst().getMaxX() : data.get(id2).getFirst().getMinX());
if (d1 < d2)
return -1;
else if (d1 > d2)
return 1;
else return id1.compareTo(id2);
});
sortedByMinY = new TreeSet<>((id1, id2) -> {
double d1 = (id1 != currentComparison ? data.get(id1).getFirst().getMinY() : data.get(id1).getFirst().getMaxY());
double d2 = (id2 != currentComparison ? data.get(id2).getFirst().getMinY() : data.get(id2).getFirst().getMaxY());
if (d1 < d2)
return -1;
else if (d1 > d2)
return 1;
else return id1.compareTo(id2);
});
sortedByMaxY = new TreeSet<>((id1, id2) -> {
double d1 = (id1 != currentComparison ? data.get(id1).getFirst().getMaxY() : data.get(id1).getFirst().getMinY());
double d2 = (id2 != currentComparison ? data.get(id2).getFirst().getMaxY() : data.get(id2).getFirst().getMinY());
if (d1 < d2)
return -1;
else if (d1 > d2)
return 1;
else return id1.compareTo(id2);
});
}
/**
* if rectangle does not overlap any rectangle already contained, then add it
*
* @return true if added, false if overlaps a rectangle already present
*/
public boolean addIfDoesNotOverlap(Pair<Rectangle2D, T> pair) {
if (previousHit != null && pair.getFirst().intersects(previousHit))
return false;
if (data.size() == data.capacity())
data.ensureCapacity(data.size() + 1);
int which = data.size();
data.add(pair);
currentComparison = which; // need to set this global variable so sorting uses reversed interval bounds in
// headset and tailset computations
BitSet startingX = getAll(sortedByMinX.headSet(which));
andAll(sortedByMaxX.tailSet(which), startingX);
boolean ok = (startingX.cardinality() == 0);
if (!ok) {
andAll(sortedByMinY.headSet(which), startingX);
ok = (startingX.cardinality() == 0);
if (!ok) {
andAll(sortedByMaxY.tailSet(which), startingX);
ok = (startingX.cardinality() == 0);
}
}
currentComparison = -1;
if (!ok) {
int id = startingX.nextSetBit(0);
previousHit = data.get(id).getFirst();
data.remove(which);
return false;
} else {
sortedByMaxX.add(which);
sortedByMinX.add(which);
sortedByMaxY.add(which);
sortedByMinY.add(which);
if (data.size() == 0)
bbox.setRect(pair.getFirst());
else
bbox.add(pair.getFirst());
return true;
}
}
private BitSet getAll(Set<Integer> set) {
BitSet result = new BitSet();
for (Integer i : set)
result.set(i);
return result;
}
private void andAll(Set<Integer> set, BitSet bitSet) {
bitSet.and(getAll(set));
}
/**
* get an iterator over all members
*
* @return iterator
*/
public Iterator<Pair<Rectangle2D, T>> iterator() {
return data.iterator();
}
/**
* erase
*/
public void clear() {
data.clear();
sortedByMaxX.clear();
sortedByMinX.clear();
sortedByMaxY.clear();
sortedByMinY.clear();
bbox.setRect(0, 0, 0, 0);
previousHit = null;
}
/**
* size
*
* @return size
*/
public int size() {
return data.size();
}
/**
* get the bounding box
*
* @return bounding box
*/
public Rectangle2D getBoundingBox() {
return (Rectangle2D) bbox.clone();
}
/**
* get the bounding box
*
*/
public void getBoundingBox(Rectangle rect) {
rect.setRect((int) Math.round(bbox.getX()), (int) Math.round(bbox.getY()), (int) Math.round(bbox.getWidth()), (int) Math.round(bbox.getHeight()));
}
}
| 6,367 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CorrelationPlotDrawer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/CorrelationPlotDrawer.java | /*
* CorrelationPlotDrawer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.Geometry;
import jloda.swing.util.ProgramProperties;
import jloda.swing.window.IPopupMenuModifier;
import jloda.util.Correlation;
import jloda.util.Table;
import megan.chart.IChartDrawer;
import megan.chart.cluster.ClusteringTree;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.SelectionGraphics;
import megan.util.CallBack;
import megan.util.PopupChoice;
import megan.util.ScalingType;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* draws a correlation plot
* Daniel Huson, 11.2015
*/
public class CorrelationPlotDrawer extends BarChartDrawer implements IChartDrawer {
public enum MODE {
Beans, Circles, Squares, Numbers, Colors;
static MODE valueOfIgnoreCase(String label) {
for (MODE mode : MODE.values()) {
if (mode.toString().equalsIgnoreCase(label))
return mode;
}
return null;
}
}
private static final String NAME = "CorrelationPlot";
final Table<String, String, Float> dataMatrix = new Table<>();
String[] classNames = null;
private String[] seriesNames = null;
final ArrayList<String> previousSamples = new ArrayList<>();
final ArrayList<String> previousClasses = new ArrayList<>();
private final ClusteringTree topClusteringTree;
private final ClusteringTree rightClusteringTree;
private boolean previousClusterSeries = false;
boolean previousClusterClasses = false;
boolean previousTranspose;
Future future; // used in recompute
final int topTreeSpace = ProgramProperties.get("topTreeHeight", 100);
final int rightTreeSpace = ProgramProperties.get("rightTreeWidth", 100);
private MODE mode;
boolean inUpdateCoordinates = true;
/**
* constructor
*/
public CorrelationPlotDrawer() {
setSupportedScalingTypes(ScalingType.LINEAR);
mode = MODE.valueOfIgnoreCase(ProgramProperties.get("CorrelationPlotMode", MODE.Beans.toString()));
rightClusteringTree = new ClusteringTree(ClusteringTree.TYPE.CLASSES, ClusteringTree.SIDE.RIGHT);
topClusteringTree = new ClusteringTree(ClusteringTree.TYPE.CLASSES, ClusteringTree.SIDE.TOP);
executorService = Executors.newSingleThreadExecutor(); // ensure we only use one thread at a time on update
}
/**
* draw correlation plot chart
*
*/
public void drawChart(Graphics2D gc) {
gc.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics) gc : null);
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
int x0 = leftMargin;
int scaleWidth = 30;
int x1 = getWidth() - rightMargin - scaleWidth;
if (x0 >= x1)
return;
if (inUpdateCoordinates) {
gc.setFont(getFont("Default"));
gc.setColor(Color.LIGHT_GRAY);
gc.drawString("Computing correlation plot...", x0, y1 + 20);
viewer.getScrollPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
return;
} else
viewer.getScrollPane().setCursor(Cursor.getDefaultCursor());
if (sgc != null) {
drawYAxis(gc, null);
}
if (!getChartTitle().startsWith("Correlation plot: "))
setChartTitle("Correlation plot: " + getChartTitle());
final int numberOfClasses = (classNames == null ? 0 : classNames.length);
if (viewer.getClassesList().isDoClustering())
y1 += topTreeSpace; // do this before other clustering
if (sgc == null) {
drawScaleBar(gc, x1, scaleWidth, y1, y0 - y1);
}
if (viewer.getClassesList().isDoClustering()) {
x1 -= rightTreeSpace;
int width = (int) ((x1 - x0) / (numberOfClasses + 1.0) * numberOfClasses);
int xStart = x0 + ((x1 - x0) - width) / 2;
final Rectangle rect = new Rectangle(xStart, y1 - topTreeSpace, width, topTreeSpace);
topClusteringTree.paint(gc, rect);
}
if (viewer.getClassesList().isDoClustering()) {
int height = (int) Math.round((y0 - y1) / (numberOfClasses + 1.0) * numberOfClasses);
int yStart = y0 + ((y1 - y0) - height) / 2;
final Rectangle rect = new Rectangle(x1, yStart, rightTreeSpace, height);
rightClusteringTree.paint(gc, rect);
}
if (numberOfClasses > 0) {
double xStep = (x1 - x0) / (double) numberOfClasses;
double yStep = (y0 - y1) / (double) numberOfClasses;
// main drawing loop:
int d = 0;
for (final String classNameX : classNames) {
final double xLabel = x0 + (d + 0.5) * xStep;
Point2D apt = new Point2D.Double(xLabel, getHeight() - bottomMargin + 10);
final Dimension labelSize = BasicSwing.getStringSize(gc, classNameX, gc.getFont()).getSize();
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
if (getChartData().getChartSelection().isSelected(null, classNameX)) {
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.DARK_GRAY));
drawString(gc, classNameX, apt.getX(), apt.getY(), classLabelAngle);
if (sgc != null) {
sgc.setCurrentItem(new String[]{null, classNameX});
drawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle);
sgc.clearCurrentItem();
}
int c = numberOfClasses - 1;
for (final String classNameY : classNames) {
final Float correlationCoefficient = dataMatrix.get(classNameX, classNameY);
if (correlationCoefficient != null) {
final double[] boundingBox = new double[]{x0 + d * xStep, y0 - (c + 1) * yStep, xStep, yStep};
// gc.drawRect((int) Math.round(boundingBox[0]), (int) Math.round(boundingBox[1]), (int) Math.round(boundingBox[2]), (int) Math.round(boundingBox[3]));
drawCell(gc, boundingBox, correlationCoefficient);
if (sgc != null && !sgc.isShiftDown()) {
sgc.setCurrentItem(new String[]{null, classNameX});
gc.fillRect((int) Math.round(boundingBox[0]), (int) Math.round(boundingBox[1]), (int) Math.round(boundingBox[2]), (int) Math.round(boundingBox[3]));
sgc.clearCurrentItem();
sgc.setCurrentItem(new String[]{null, classNameY});
gc.fillRect((int) Math.round(boundingBox[0]), (int) Math.round(boundingBox[1]), (int) Math.round(boundingBox[2]), (int) Math.round(boundingBox[3]));
sgc.clearCurrentItem();
}
boolean isSelected = !classNameX.equals(classNameY) && getChartData().getChartSelection().isSelected(null, classNameX) && getChartData().getChartSelection().isSelected(null, classNameY);
if (isSelected) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.drawRect((int) Math.round(boundingBox[0]), (int) Math.round(boundingBox[1]), (int) Math.round(boundingBox[2]), (int) Math.round(boundingBox[3]));
gc.setStroke(NORMAL_STROKE);
}
if (showValues || isSelected) {
String aLabel = String.format("%.3f", correlationCoefficient);
valuesList.add(new DrawableValue(aLabel, (int) Math.round(boundingBox[0] + boundingBox[2] / 2), (int) Math.round(boundingBox[1] + boundingBox[3] / 2) - gc.getFont().getSize() / 2, isSelected));
}
}
c--;
}
d++;
}
}
if (valuesList.size() > 0) {
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
DrawableValue.drawValues(gc, valuesList, true, true);
valuesList.clear();
}
}
/**
* draw correlation plot chart
*
*/
public void drawChartTransposed(Graphics2D gc) {
gc.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics) gc : null);
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
int x0 = leftMargin;
int scaleWidth = 30;
int x1 = getWidth() - rightMargin - scaleWidth;
if (x0 >= x1)
return;
if (inUpdateCoordinates) {
gc.setFont(getFont("Default"));
gc.setColor(Color.LIGHT_GRAY);
gc.drawString("Computing correlation plot...", x0, y1 + 20);
viewer.getScrollPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
return;
} else
viewer.getScrollPane().setCursor(Cursor.getDefaultCursor());
if (sgc != null) {
drawYAxis(gc, null);
}
if (sgc == null) {
drawScaleBar(gc, x1, scaleWidth, y1, y0 - y1);
}
if (!getChartTitle().startsWith("Correlation plot: "))
setChartTitle("Correlation plot: " + getChartTitle());
final int numberOfSeries = (seriesNames == null ? 0 : seriesNames.length);
if (viewer.getSeriesList().isDoClustering())
y1 += topTreeSpace; // do this before other clustering
if (sgc == null) {
drawScaleBar(gc, x1, scaleWidth, y1, y0 - y1);
}
if (viewer.getSeriesList().isDoClustering()) {
x1 -= rightTreeSpace;
int width = (int) ((x1 - x0) / (numberOfSeries + 1.0) * numberOfSeries);
int xStart = x0 + ((x1 - x0) - width) / 2;
final Rectangle rect = new Rectangle(xStart, y1 - topTreeSpace, width, topTreeSpace);
topClusteringTree.paint(gc, rect);
}
if (viewer.getSeriesList().isDoClustering()) {
int height = (int) Math.round((y0 - y1) / (numberOfSeries + 1.0) * numberOfSeries);
int yStart = y0 + ((y1 - y0) - height) / 2;
final Rectangle rect = new Rectangle(x1, yStart, rightTreeSpace, height);
rightClusteringTree.paint(gc, rect);
}
if (numberOfSeries > 0) {
double xStep = (x1 - x0) / (double) numberOfSeries;
double yStep = (y0 - y1) / (double) numberOfSeries;
// main drawing loop:
int d = 0;
for (final String seriesNameX : seriesNames) {
final double xLabel = x0 + (d + 0.5) * xStep;
Point2D apt = new Point2D.Double(xLabel, getHeight() - bottomMargin + 10);
final Dimension labelSize = BasicSwing.getStringSize(gc, seriesNameX, gc.getFont()).getSize();
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
if (getChartData().getChartSelection().isSelected(seriesNameX, null)) {
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.DARK_GRAY));
drawString(gc, seriesNameX, apt.getX(), apt.getY(), classLabelAngle);
if (sgc != null) {
sgc.setCurrentItem(new String[]{seriesNameX, null});
drawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle);
sgc.clearCurrentItem();
}
int c = numberOfSeries - 1;
for (final String seriesNameY : seriesNames) {
final Float correlationCoefficient = dataMatrix.get(seriesNameX, seriesNameY);
if (correlationCoefficient != null) {
final double[] boundingBox = new double[]{x0 + d * xStep, y0 - (c + 1) * yStep, xStep, yStep};
// gc.drawRect((int) Math.round(boundingBox[0]), (int) Math.round(boundingBox[1]), (int) Math.round(boundingBox[2]), (int) Math.round(boundingBox[3]));
drawCell(gc, boundingBox, correlationCoefficient);
if (sgc != null && !sgc.isShiftDown()) {
sgc.setCurrentItem(new String[]{seriesNameY, null});
gc.fillRect((int) Math.round(boundingBox[0]), (int) Math.round(boundingBox[1]), (int) Math.round(boundingBox[2]), (int) Math.round(boundingBox[3]));
sgc.clearCurrentItem();
sgc.setCurrentItem(new String[]{seriesNameY, null});
gc.fillRect((int) Math.round(boundingBox[0]), (int) Math.round(boundingBox[1]), (int) Math.round(boundingBox[2]), (int) Math.round(boundingBox[3]));
sgc.clearCurrentItem();
}
boolean isSelected = !seriesNameX.equals(seriesNameY) && getChartData().getChartSelection().isSelected(seriesNameX, null) && getChartData().getChartSelection().isSelected(seriesNameY, null);
if (isSelected) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.drawRect((int) Math.round(boundingBox[0]), (int) Math.round(boundingBox[1]), (int) Math.round(boundingBox[2]), (int) Math.round(boundingBox[3]));
gc.setStroke(NORMAL_STROKE);
}
if (showValues || isSelected) {
String aLabel = String.format("%.3f", correlationCoefficient);
valuesList.add(new DrawableValue(aLabel, (int) Math.round(boundingBox[0] + boundingBox[2] / 2), (int) Math.round(boundingBox[1] + boundingBox[3] / 2) - gc.getFont().getSize() / 2, isSelected));
}
}
c--;
}
d++;
}
}
if (valuesList.size() > 0) {
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
DrawableValue.drawValues(gc, valuesList, true, true);
valuesList.clear();
}
}
/**
* draw cell
*
*/
void drawCell(Graphics2D gc, double[] boundingBox, double correlationCoefficent) {
double centerX = boundingBox[0] + boundingBox[2] / 2; // center x
double centerY = boundingBox[1] + boundingBox[3] / 2; // center y
//Color color = ColorUtilities.interpolateRGB(lowColor, highColor, (float) ((correlationCoefficent + 1.0) / 2.0));
Color color = getChartColors().getHeatMapTable().getColor((int) Math.round(500.0 * (correlationCoefficent + 1.0)), 1000);
switch (getMode()) {
case Beans -> {
double width = 2 + Math.min(boundingBox[2], boundingBox[3]) * (correlationCoefficent + 1.0) / 2.0;
double height = 2 + Math.min(boundingBox[2], boundingBox[3]) * (1.0 - correlationCoefficent) / 2.0;
int x = (int) Math.round(centerX - width / 2.0); // left
int y = (int) Math.round(centerY - height / 2.0); // top
if (correlationCoefficent >= 1) { // diagonal up
gc.setColor(color.darker());
gc.rotate(Geometry.deg2rad(-45), centerX, centerY);
gc.drawLine(x, y, x + (int) Math.round(width), y);
gc.rotate(Geometry.deg2rad(45), centerX, centerY);
} else if (correlationCoefficent <= -1) { // diagonal down
gc.setColor(color.darker());
gc.rotate(Geometry.deg2rad(45), centerX, centerY);
gc.drawLine(x, y, x + (int) Math.round(width), y);
gc.rotate(Geometry.deg2rad(-45), centerX, centerY);
} else { // ellipse
gc.setColor(color);
gc.rotate(Geometry.deg2rad(-45), centerX, centerY);
gc.fillOval(x, y, (int) Math.round(width), (int) Math.round(height));
gc.setColor(color.darker());
gc.drawOval(x, y, (int) Math.round(width), (int) Math.round(height));
gc.rotate(Geometry.deg2rad(45), centerX, centerY);
}
}
case Circles -> {
double width = Math.min(boundingBox[2], boundingBox[3]);
double height = Math.min(boundingBox[2], boundingBox[3]);
double radius = Math.abs(correlationCoefficent) * Math.min(width, height);
int x = (int) Math.round(centerX - radius / 2.0); // left
int y = (int) Math.round(centerY - radius / 2.0); // top
gc.setColor(color);
gc.fillOval(x, y, (int) Math.round(radius), (int) Math.round(radius));
gc.setColor(color.darker());
gc.drawOval(x, y, (int) Math.round(radius), (int) Math.round(radius));
}
case Squares -> {
double width = Math.min(boundingBox[2], boundingBox[3]) * Math.abs(correlationCoefficent);
double height = Math.min(boundingBox[2], boundingBox[3]) * Math.abs(correlationCoefficent);
int x = (int) Math.round(centerX - width / 2.0); // left
int y = (int) Math.round(centerY - height / 2.0); // top
gc.setColor(color);
gc.fillRect(x, y, (int) Math.round(width), (int) Math.round(height));
gc.setColor(color.darker());
gc.drawRect(x, y, (int) Math.round(width), (int) Math.round(height));
}
case Colors -> {
final double width = boundingBox[2];
final double height = boundingBox[3];
final double x = centerX - width / 2.0; // left
final double y = centerY - height / 2.0; // top
gc.setColor(color);
if (isGapBetweenBars() && width > 3 && height > 3) {
final Rectangle2D rect = new Rectangle2D.Double(x + 1, y + 1, width - 2, height - 2);
gc.fill(rect);
} else {
final Rectangle2D rect = new Rectangle2D.Double(x, y, width + 1, height + 1);
gc.fill(rect);
if (isShowVerticalGridLines()) {
gc.setColor(color.darker());
gc.draw(rect);
}
}
}
case Numbers -> {
gc.setFont(getFont(ChartViewer.FontKeys.DrawFont.toString()));
String label = String.format("%.3f", correlationCoefficent);
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
int x = (int) Math.round(centerX - labelSize.width / 2.0); // left
int y = (int) Math.round(centerY); // top
gc.setColor(color.darker());
gc.drawString(label, x, y);
}
}
}
void drawScaleBar(Graphics2D gc, final int x, final int width, final int y, final int height) {
int x0 = x + Math.max(10, width - 25);
int xLabel = x0 + 15;
int boxWidth = 10;
int boxHeight = Math.min(150, height - 15);
int step = boxHeight / 10;
int y0 = y + 15;
for (int i = 0; i <= boxHeight; i++) {
float p = 1f - (float) i / (float) boxHeight; // is between 1 and 0
final Color color = getChartColors().getHeatMapTable().getColor(Math.round(1000 * p), 1000);
gc.setColor(color);
gc.drawLine(x0, y0 + i, x0 + boxWidth, y0 + i);
}
gc.setColor(Color.BLACK);
gc.drawRect(x0, y0, boxWidth, boxHeight);
gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString()));
for (float p = 1f; p >= -1f; p -= 0.2f) { // is between 1 and -1
gc.drawString(String.format("%+1.1f", p), xLabel, y0 + gc.getFont().getSize() / 2);
y0 += step;
}
}
/**
* draw the x axis
*
*/
protected void drawXAxis(Graphics2D gc) {
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.BLACK));
gc.setColor(Color.BLACK);
int x = 5;
int y = getHeight() - bottomMargin + 25;
gc.drawString(getChartData().getClassesLabel(), x, y);
}
/**
* draw the y-axis
*
*/
protected void drawYAxis(Graphics2D gc, Dimension size) {
if (inUpdateCoordinates)
return;
if (isTranspose()) {
drawYAxisTransposed(gc, size);
return;
}
final int numberOfClasses = (classNames == null ? 0 : classNames.length);
if (numberOfClasses > 0) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString()));
final boolean doDraw = (size == null);
Rectangle bbox = null;
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
if (viewer.getClassesList().isDoClustering())
y1 += topTreeSpace;
int longest = 0;
for (String className : classNames) {
longest = Math.max(longest, BasicSwing.getStringSize(gc, className, gc.getFont()).getSize().width);
}
int right = Math.max(leftMargin, longest + 5);
if (doDraw)
gc.setColor(getFontColor(ChartViewer.FontKeys.YAxisFont.toString(), Color.BLACK));
double yStep = (y0 - y1) / (double) numberOfClasses;
int c = numberOfClasses - 1;
for (String className : classNames) {
Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize();
int x = right - labelSize.width - 4;
int y = (int) Math.round(y0 - (c + 0.5) * yStep);
if (doDraw) {
if (getChartData().getChartSelection().isSelected(null, className)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, x, y, labelSize.width, labelSize.height, 0, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.YAxisFont.toString(), Color.DARK_GRAY));
gc.drawString(className, x, y);
} else {
Rectangle rect = new Rectangle(x, y, labelSize.width, labelSize.height);
if (bbox == null)
bbox = rect;
else
bbox.add(rect);
}
if (sgc != null) {
sgc.setCurrentItem(new String[]{null, className});
drawRect(gc, x, y, labelSize.width, labelSize.height, 0);
sgc.clearCurrentItem();
}
c--;
}
if (size != null && bbox != null) {
size.setSize(bbox.width + 3, bbox.height);
}
}
}
/**
* draw the y-axis
*
*/
void drawYAxisTransposed(Graphics2D gc, Dimension size) {
final int numberOfSeries = (seriesNames == null ? 0 : seriesNames.length);
if (numberOfSeries > 0) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics) gc : null);
gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString()));
final boolean doDraw = (size == null);
Rectangle bbox = null;
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
if (viewer.getSeriesList().isDoClustering())
y1 += topTreeSpace;
int longest = 0;
for (String seriesName : seriesNames) {
longest = Math.max(longest, BasicSwing.getStringSize(gc, seriesName, gc.getFont()).getSize().width);
}
int right = Math.max(leftMargin, longest + 5);
if (doDraw)
gc.setColor(getFontColor(ChartViewer.FontKeys.YAxisFont.toString(), Color.BLACK));
double yStep = (y0 - y1) / (double) numberOfSeries;
int c = numberOfSeries - 1;
for (String seriesName : seriesNames) {
Dimension labelSize = BasicSwing.getStringSize(gc, seriesName, gc.getFont()).getSize();
int x = right - labelSize.width - 4;
int y = (int) Math.round(y0 - (c + 0.5) * yStep);
if (doDraw) {
if (getChartData().getChartSelection().isSelected(seriesName, null)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, x, y, labelSize.width, labelSize.height, 0, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.YAxisFont.toString(), Color.DARK_GRAY));
gc.drawString(seriesName, x, y);
} else {
Rectangle rect = new Rectangle(x, y, labelSize.width, labelSize.height);
if (bbox == null)
bbox = rect;
else
bbox.add(rect);
}
if (sgc != null) {
sgc.setCurrentItem(new String[]{seriesName, null});
drawRect(gc, x, y, labelSize.width, labelSize.height, 0);
sgc.clearCurrentItem();
}
c--;
}
if (size != null && bbox != null) {
size.setSize(bbox.width + 3, bbox.height);
}
}
}
public boolean canShowLegend() {
return false;
}
@Override
public String getChartDrawerName() {
return NAME;
}
@Override
public boolean canTranspose() {
return true;
}
/**
* do we need to recompute coordinates?
*
* @return true, if coordinates need to be recomputed
*/
private boolean mustUpdateCoordinates() {
boolean mustUpdate = (dataMatrix.size() == 0);
if (previousTranspose != isTranspose()) {
mustUpdate = true;
}
if (scalingType != ScalingType.LINEAR)
return mustUpdate;
if (previousTranspose != isTranspose()) {
previousTranspose = isTranspose();
previousClusterSeries = false;
previousClusterClasses = false;
}
{
final ArrayList<String> currentClasses = new ArrayList<>(getChartData().getClassNames());
if (!previousClasses.equals(currentClasses)) {
mustUpdate = true;
previousClasses.clear();
previousClasses.addAll(currentClasses);
}
}
{
final ArrayList<String> currentSamples = new ArrayList<>(getChartData().getSeriesNames());
if (!previousSamples.equals(currentSamples)) {
mustUpdate = true;
previousSamples.clear();
previousSamples.addAll(currentSamples);
}
}
{
if (!previousClusterClasses && viewer.getClassesList().isDoClustering() && !isTranspose())
mustUpdate = true;
}
{
if (!previousClusterSeries && viewer.getSeriesList().isDoClustering() && isTranspose())
mustUpdate = true;
}
return mustUpdate;
}
/**
* force update
*/
@Override
public void forceUpdate() {
dataMatrix.clear();
}
/**
* updates the view
*/
public void updateView() {
if (mustUpdateCoordinates()) {
if (future != null) {
future.cancel(true);
future = null;
}
inUpdateCoordinates = true;
future = executorService.submit(() -> {
try {
updateCoordinates();
SwingUtilities.invokeAndWait(() -> {
if (!previousClusterClasses && viewer.getClassesList().isDoClustering())
updateClassesJList();
previousClusterClasses = viewer.getClassesList().isDoClustering();
if (!previousClusterSeries && viewer.getSeriesList().isDoClustering())
updateSeriesJList();
previousClusterSeries = viewer.getSeriesList().isDoClustering();
viewer.repaint();
});
} catch (Exception e) {
// Basic.caught(e);
} finally {
future = null;
inUpdateCoordinates = false;
}
});
}
}
void updateCoordinates() {
System.err.println("Updating...");
dataMatrix.clear();
previousClasses.clear();
previousSamples.clear();
topClusteringTree.clear();
rightClusteringTree.clear();
if (topClusteringTree.getChartSelection() == null)
topClusteringTree.setChartSelection(viewer.getChartSelection());
if (rightClusteringTree.getChartSelection() == null)
rightClusteringTree.setChartSelection(viewer.getChartSelection());
final String[] currentClasses;
{
final Collection<String> list = getViewer().getClassesList().getEnabledLabels();
currentClasses = list.toArray(new String[0]);
}
final String[] currentSeries;
{
final Collection<String> list = getViewer().getSeriesList().getEnabledLabels();
currentSeries = list.toArray(new String[0]);
}
if (!isTranspose()) {
for (int i = 0; i < currentClasses.length; i++) {
dataMatrix.put(currentClasses[i], currentClasses[i], 1f);
for (int j = i + 1; j < currentClasses.length; j++) {
final float value = computeCorrelationCoefficent(currentClasses[i], currentClasses[j]);
dataMatrix.put(currentClasses[i], currentClasses[j], value);
dataMatrix.put(currentClasses[j], currentClasses[i], value);
}
}
if (viewer.getClassesList().isDoClustering()) {
topClusteringTree.setType(ClusteringTree.TYPE.CLASSES);
topClusteringTree.updateClustering(currentClasses, dataMatrix);
rightClusteringTree.setType(ClusteringTree.TYPE.CLASSES);
rightClusteringTree.updateClustering(currentClasses, dataMatrix);
final Collection<String> list = topClusteringTree.getLabelOrder();
classNames = list.toArray(new String[0]);
} else
classNames = currentClasses;
} else {
for (int i = 0; i < currentSeries.length; i++) {
dataMatrix.put(currentSeries[i], currentSeries[i], 1f);
for (int j = i + 1; j < currentSeries.length; j++) {
final float value = computeCorrelationCoefficentTransposed(currentSeries[i], currentSeries[j]);
dataMatrix.put(currentSeries[i], currentSeries[j], value);
dataMatrix.put(currentSeries[j], currentSeries[i], value);
}
if (viewer.getSeriesList().isDoClustering()) {
topClusteringTree.setType(ClusteringTree.TYPE.SERIES);
topClusteringTree.updateClustering(currentSeries, dataMatrix);
rightClusteringTree.setType(ClusteringTree.TYPE.SERIES);
rightClusteringTree.updateClustering(currentSeries, dataMatrix);
final Collection<String> list = topClusteringTree.getLabelOrder();
seriesNames = list.toArray(new String[0]);
} else
seriesNames = currentSeries;
}
}
chartData.setClassesLabel("");
}
/**
* return Pearson's correlation coefficient
*
* @return Pearson's correlation coefficient
*/
private float computeCorrelationCoefficent(String classNameX, String classNameY) {
final ArrayList<Double> xValues = new ArrayList<>(getChartData().getSeriesNames().size());
final ArrayList<Double> yValues = new ArrayList<>(getChartData().getSeriesNames().size());
for (String sample : getChartData().getSeriesNames()) {
xValues.add(getChartData().getValueAsDouble(sample, classNameX));
yValues.add(getChartData().getValueAsDouble(sample, classNameY));
}
return (float) Correlation.computePersonsCorrelationCoefficent(xValues.size(), xValues, yValues);
}
/**
* return Pearson's correlation coefficient
*
* @return Pearson's correlation coefficient
*/
private float computeCorrelationCoefficentTransposed(String seriesNameX, String seriesNameY) {
final ArrayList<Double> xValues = new ArrayList<>(getChartData().getClassNames().size());
final ArrayList<Double> yValues = new ArrayList<>(getChartData().getClassNames().size());
for (String className : getChartData().getClassNames()) {
xValues.add(getChartData().getValueAsDouble(seriesNameX, className));
yValues.add(getChartData().getValueAsDouble(seriesNameY, className));
}
return (float) Correlation.computePersonsCorrelationCoefficent(xValues.size(), xValues, yValues);
}
private void updateClassesJList() {
final Collection<String> selected = new ArrayList<>(viewer.getChartSelection().getSelectedClasses());
final Collection<String> ordered = new ArrayList<>(Arrays.asList(classNames));
final Collection<String> others = viewer.getClassesList().getAllLabels();
others.removeAll(ordered);
ordered.addAll(others);
viewer.getClassesList().sync(ordered, viewer.getClassesList().getLabel2ToolTips(), true);
viewer.getClassesList().setDisabledLabels(others);
viewer.getChartSelection().setSelectedClass(selected, true);
}
private void updateSeriesJList() {
final Collection<String> selected = new ArrayList<>(viewer.getChartSelection().getSelectedSeries());
final Collection<String> ordered = new ArrayList<>(Arrays.asList(seriesNames));
final Collection<String> others = viewer.getSeriesList().getAllLabels();
others.removeAll(ordered);
ordered.addAll(others);
viewer.getSeriesList().sync(ordered, null, true);
viewer.getSeriesList().setDisabledLabels(others);
viewer.getChartSelection().setSelectedSeries(selected, true);
}
protected double computeXAxisLabelHeight(Graphics2D gc) {
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
double theHeight = 2 * gc.getFont().getSize();
if (classLabelAngle != 0) {
double sin = Math.abs(Math.sin(classLabelAngle));
for (String label : getChartData().getClassNames()) {
if (label.length() > 50)
label = label.substring(0, 50) + "...";
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
theHeight = Math.max(theHeight, gc.getFont().getSize() + sin * labelSize.width);
}
}
return theHeight;
}
private MODE getMode() {
return mode;
}
private void setMode(MODE mode) {
this.mode = mode;
}
public void setMode(String mode) {
this.mode = MODE.valueOfIgnoreCase(mode);
}
@Override
public boolean canColorByRank() {
return false;
}
@Override
public boolean usesHeatMapColors() {
return true;
}
public IPopupMenuModifier getPopupMenuModifier() {
return (menu, commandManager) -> {
menu.addSeparator();
MODE mode = MODE.valueOfIgnoreCase(ProgramProperties.get("CorrelationPlotMode", MODE.Beans.toString()));
final CallBack<MODE> callBack = new CallBack<>() {
public void call(MODE choice) {
setMode(choice);
ProgramProperties.put("CorrelationPlotMode", choice.toString());
getJPanel().repaint();
}
};
PopupChoice.addToJMenu(menu, MODE.values(), mode, callBack);
menu.addSeparator();
final AbstractAction action = (new AbstractAction("Flip Selected Subtree") {
@Override
public void actionPerformed(ActionEvent e) {
if (rightClusteringTree.hasSelectedSubTree()) {
//System.err.println("Rotate Classes");
rightClusteringTree.rotateSelectedSubTree();
final Collection<String> list = rightClusteringTree.getLabelOrder();
if (!isTranspose()) {
classNames = list.toArray(new String[0]);
updateClassesJList();
} else {
seriesNames = list.toArray(new String[0]);
updateSeriesJList();
}
getJPanel().repaint();
}
}
});
action.setEnabled(rightClusteringTree.hasSelectedSubTree());
menu.add(action);
};
}
@Override
public void writeData(Writer w) throws IOException {
w.write("CorrelationPlot");
if (!isTranspose()) {
for (String className : classNames) {
w.write("\t" + className);
}
w.write("\n");
for (String name1 : classNames) {
w.write(name1);
for (String name2 : classNames) {
w.write(String.format("\t%.4g", dataMatrix.get(name1, name2)));
}
w.write("\n");
}
} else {
for (String name : seriesNames) {
w.write("\t" + name);
}
w.write("\n");
for (String name1 : seriesNames) {
w.write(name1);
for (String name2 : seriesNames) {
w.write(String.format("\t%.4g", dataMatrix.get(name1, name2)));
}
w.write("\n");
}
}
}
@Override
public boolean canCluster(ClusteringTree.TYPE type) {
return ((type == null) || ((type == ClusteringTree.TYPE.CLASSES) && !isTranspose()) || ((type == ClusteringTree.TYPE.SERIES) && isTranspose()));
}
} | 41,894 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
WordCloudDrawer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/WordCloudDrawer.java | /*
* WordCloudDrawer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.RTree;
import jloda.util.Pair;
import jloda.util.Triplet;
import megan.chart.IChartDrawer;
import megan.chart.IMultiChartDrawable;
import megan.chart.data.DefaultChartData;
import megan.chart.data.IChartData;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.SelectionGraphics;
import megan.util.ScalingType;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.util.*;
import java.util.concurrent.Future;
/**
* draws a word cloud
* Daniel Huson, 6.2012
*/
public class WordCloudDrawer extends BarChartDrawer implements IChartDrawer, IMultiChartDrawable {
private static final String NAME = "WordCloud";
private boolean useRectangleShape = false;
private int maxFontSize;
private static final Map<Integer, Font> size2font = new HashMap<>();
private final Set<String> previousClasses = new HashSet<>();
private ScalingType previousScalingType = null;
private final RTree<Pair<String, Integer>> rTree;
private boolean inUpdateCoordinates = false;
private Future future; // used in recompute
private Graphics graphics;
private int width;
private int height;
/**
* constructor
*/
public WordCloudDrawer() {
super();
rTree = new RTree<>();
maxFontSize = ProgramProperties.get("WordCloudMaxFontSize", 128);
}
/**
* draw clouds in which words are datasets
*
*/
public void drawChart(Graphics2D gc) {
int x0 = 2;
int x1 = getWidth() - 2;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
if (x0 >= x1)
return;
if (inUpdateCoordinates) {
gc.setFont(getFont("Default"));
gc.setColor(Color.LIGHT_GRAY);
gc.drawString("Updating coordinates...", 20, 20);
return;
}
if (rTree.size() == 0)
return;
Rectangle deviceBBox = new Rectangle(x0, y1, x1 - x0, y0 - y1);
deviceBBox.x += deviceBBox.width / 2;
deviceBBox.y += deviceBBox.height / 2;
Rectangle worldBBox = new Rectangle();
rTree.getBoundingBox(worldBBox);
worldBBox.x += worldBBox.width / 2;
worldBBox.y += worldBBox.height / 2;
double xFactor = deviceBBox.width / (double) worldBBox.width;
double yFactor = deviceBBox.height / (double) worldBBox.height;
if (xFactor > 1)
xFactor = 1;
if (yFactor > 1)
yFactor = 1;
double factor = Math.min(xFactor, yFactor);
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
for (Iterator<Pair<Rectangle2D, Pair<String, Integer>>> it = rTree.iterator(); it.hasNext(); ) {
Pair<Rectangle2D, Pair<String, Integer>> pair = it.next();
Rectangle2D rect = pair.getFirst();
String label = pair.getSecond().getFirst();
int fontSize = (int) (factor * pair.getSecond().getSecond());
gc.setFont(getFontForSize(fontSize));
if (fontSize >= 1) {
double x = rect.getX();
double y = rect.getY() + rect.getHeight();
x = factor * (x - worldBBox.x) + deviceBBox.x;
y = factor * (y - worldBBox.y) + deviceBBox.y;
if (getChartData().getChartSelection().isSelected(null, label)) {
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.BLACK));
gc.setStroke(NORMAL_STROKE);
fillAndDrawRect(gc, x, y, labelSize.width, labelSize.height, 0, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
Color color = getFontColor(ChartViewer.FontKeys.DrawFont.toString(), null);
if (color == null)
color = getChartColors().getClassColor(class2HigherClassMapper.get(label));
gc.setColor(color);
if (sgc != null)
sgc.setCurrentItem(new String[]{null, label});
gc.drawString(label, (int) Math.round(x), (int) Math.round(y));
if (sgc != null)
sgc.clearCurrentItem();
/*
{
Dimension labelSize = Basic.getStringSize(gc, label, gc.getFont()).getSize();
gc.setColor(Color.LIGHT_GRAY);
gc.drawRect((int)x, (int)y-labelSize.height, labelSize.width, labelSize.height);
//drawRect(gc, x, y, labelSize.width, labelSize.height, 0);
}
*/
}
}
}
private boolean mustUpdateCoordinates() {
boolean mustUpdate = (previousScalingType != scalingType) || (((IChartData) chartData).getMaxTotalSeries() > 0 && rTree.size() == 0);
if (!mustUpdate) {
Set<String> currentClasses = new HashSet<>(getChartData().getSeriesNames());
if (!previousClasses.equals(currentClasses))
mustUpdate = true;
}
return mustUpdate;
}
/**
* compute coordinates
*/
private void updateCoordinates() {
previousScalingType = scalingType;
previousClasses.clear();
previousClasses.addAll(getChartData().getSeriesNames());
rTree.clear();
Graphics gc = getGraphics();
gc.setFont(getFont(ChartViewer.FontKeys.DrawFont.toString()));
size2font.clear();
double maxValue;
if (scalingType == ScalingType.PERCENT)
maxValue = 100;
else if (scalingType == ScalingType.LOG) {
maxValue = Math.log10(getChartData().getMaxTotalSeries());
} else if (scalingType == ScalingType.SQRT) {
maxValue = Math.sqrt(getChartData().getMaxTotalSeries());
} else
maxValue = getChartData().getMaxTotalSeries();
maxValue /= 10; // assume 10 is the average word length
double fontFactor = (maxValue > 0 ? (maxFontSize) / maxValue : 12);
final Triplet<Integer, Integer, Dimension> previous = new Triplet<>(-1, 1, new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
final Point center = new Point(0, 0);
SortedSet<Pair<Double, String>> sorted = new TreeSet<>((pair1, pair2) -> {
if (pair1.getFirst() > pair2.getFirst())
return -1;
if (pair1.getFirst() < pair2.getFirst())
return 1;
return pair1.getSecond().compareTo(pair2.getSecond());
});
for (String label : getChartData().getSeriesNames()) {
Double value = getChartData().getTotalForSeries(label);
sorted.add(new Pair<>(value, label));
}
for (Pair<Double, String> pair : sorted) {
double total = pair.getFirst();
String series = pair.getSecond();
double value;
if (scalingType == ScalingType.PERCENT) {
if (total == 0)
value = 0;
else
value = 100 * total / getChartData().getMaxTotalClass();
} else if (scalingType == ScalingType.LOG) {
value = total;
if (value > 0)
value = Math.log10(value);
} else if (scalingType == ScalingType.SQRT) {
value = total;
if (value > 0)
value = Math.sqrt(value);
} else
value = total;
value /= (0.5 * series.length());
int fontSize = (int) Math.min(maxFontSize, Math.round(fontFactor * value));
computeCoordinates(gc, center, series, getFontForSize(fontSize), previous);
}
}
/**
* draw clouds in which words are classes
*
*/
public void drawChartTransposed(Graphics2D gc) {
int x0 = 2;
int x1 = getWidth() - 2;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
if (x0 >= x1)
return;
if (inUpdateCoordinates) {
gc.setFont(getFont("Default"));
gc.setColor(Color.LIGHT_GRAY);
gc.drawString("Updating coordinates...", 20, 20);
return;
}
if (rTree.size() == 0)
return;
Rectangle deviceBBox = new Rectangle(x0, y1, x1 - x0, y0 - y1);
deviceBBox.x += deviceBBox.width / 2;
deviceBBox.y += deviceBBox.height / 2;
Rectangle worldBBox = new Rectangle();
rTree.getBoundingBox(worldBBox);
worldBBox.x += worldBBox.width / 2;
worldBBox.y += worldBBox.height / 2;
double xFactor = deviceBBox.width / (double) worldBBox.width;
double yFactor = deviceBBox.height / (double) worldBBox.height;
if (xFactor > 1)
xFactor = 1;
if (yFactor > 1)
yFactor = 1;
double factor = Math.min(xFactor, yFactor);
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
for (Iterator<Pair<Rectangle2D, Pair<String, Integer>>> it = rTree.iterator(); it.hasNext(); ) {
Pair<Rectangle2D, Pair<String, Integer>> pair = it.next();
Rectangle2D rect = pair.getFirst();
String label = pair.getSecond().getFirst();
int fontSize = (int) (factor * pair.getSecond().getSecond());
if (fontSize >= 1) {
gc.setFont(getFontForSize(fontSize));
Color color = getFontColor(ChartViewer.FontKeys.DrawFont.toString(), null);
if (color == null)
color = getChartColors().getSampleColor(label);
gc.setColor(color);
double x = rect.getX();
double y = rect.getY() + rect.getHeight();
x = factor * (x - worldBBox.x) + deviceBBox.x;
y = factor * (y - worldBBox.y) + deviceBBox.y;
if (sgc != null)
sgc.setCurrentItem(new String[]{label, null});
gc.drawString(label, (int) Math.round(x), (int) Math.round(y));
if (sgc != null)
sgc.clearCurrentItem();
if (getChartData().getChartSelection().isSelected(label, null)) {
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
drawRect(gc, x, y, labelSize.width, labelSize.height, 0);
gc.setStroke(NORMAL_STROKE);
}
}
}
}
private boolean mustUpdateCoordinatesTransposed() {
boolean mustUpdate = (previousScalingType != scalingType) || ((IChartData) chartData).getMaxTotalClass() > 0 && rTree.size() == 0;
if (!mustUpdate) {
Set<String> currentClasses = new HashSet<>(getChartData().getClassNames());
if (!previousClasses.equals(currentClasses))
mustUpdate = true;
}
return mustUpdate;
}
/**
* compute coordinates
*/
private void updateCoordinatesTransposed() {
previousScalingType = scalingType;
previousClasses.clear();
previousClasses.addAll(getChartData().getClassNames());
rTree.clear();
Graphics gc = getGraphics();
size2font.clear();
double maxValue;
if (scalingType == ScalingType.PERCENT)
maxValue = 100;
else if (scalingType == ScalingType.LOG) {
maxValue = Math.log10(getChartData().getMaxTotalClass());
} else if (scalingType == ScalingType.SQRT) {
maxValue = Math.sqrt(getChartData().getMaxTotalClass());
} else
maxValue = getChartData().getMaxTotalClass();
maxValue /= 10; // assume 10 is the average word length
double fontFactor = (maxValue > 0 ? (maxFontSize) / maxValue : 12);
final Triplet<Integer, Integer, Dimension> previous = new Triplet<>(-1, 1, new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));
Point center = new Point(0, 0);
SortedSet<Pair<Double, String>> sorted = new TreeSet<>((pair1, pair2) -> {
if (pair1.getFirst() > pair2.getFirst())
return -1;
if (pair1.getFirst() < pair2.getFirst())
return 1;
return pair1.getSecond().compareTo(pair2.getSecond());
});
for (String label : getChartData().getClassNames()) {
double value = getChartData().getTotalForClass(label);
sorted.add(new Pair<>(value, label));
}
for (Pair<Double, String> pair : sorted) {
double total = pair.getFirst();
double value;
String className = pair.getSecond();
if (scalingType == ScalingType.PERCENT) {
if (total == 0)
value = 0;
else
value = 100 * total / getChartData().getMaxTotalSeries();
} else if (scalingType == ScalingType.LOG) {
value = total;
if (value > 0)
value = Math.log10(value);
} else if (scalingType == ScalingType.SQRT) {
value = total;
if (value > 0)
value = Math.sqrt(value);
} else
value = total;
value /= (0.5 * className.length());
int fontSize = (int) Math.min(maxFontSize, Math.round(fontFactor * value));
computeCoordinates(gc, center, className, getFontForSize(fontSize), previous);
}
}
/**
* gets a font of the given size
*
* @return font
*/
private Font getFontForSize(Integer fontSize) {
Font font = size2font.get(fontSize);
if (font == null) {
Font theFont = getFont(ChartViewer.FontKeys.DrawFont.toString());
font = new Font(theFont.getName(), theFont.getStyle(), fontSize);
size2font.put(fontSize, font);
}
return font;
}
/**
* compute coordinates for word cloud
*
*/
private void computeCoordinates(Graphics gc, Point center, String label, Font font, Triplet<Integer, Integer, Dimension> previous) {
int x = center.x;
int y = center.y;
Rectangle bbox = new Rectangle();
Dimension labelSize = BasicSwing.getStringSize(gc, label, font).getSize();
if (labelSize.height < 1)
return;
bbox.setSize(labelSize);
if (rTree.size() == 0) {
bbox.setLocation(x - bbox.width / 2, y);
if (!rTree.overlaps(bbox)) {
Pair<String, Integer> pair = new Pair<>(label, font.getSize());
rTree.add(bbox, pair);
return;
}
}
int direction = previous.getFirst();
for (int k = 1; true; k++) { // number steps in a direction
for (int i = 0; i < 2; i++) { // two different directions
if (direction == 3)
direction = 0;
else
direction++;
for (int j = previous.getSecond(); j <= k; j++) { // the steps in the direction
switch (direction) {
case 0 -> x += useRectangleShape ? 8 : 5;
case 1 -> y += 5;
case 2 -> x -= useRectangleShape ? 8 : 5;
case 3 -> y -= 5;
}
bbox.setLocation(x - bbox.width / 2, y);
if (!rTree.overlaps(bbox)) {
Pair<String, Integer> pair = new Pair<>(label, font.getSize());
previous.setFirst(direction);
previous.setSecond(j);
previous.setThird(labelSize);
rTree.add(bbox, pair);
return;
}
}
}
}
}
private boolean isUseRectangleShape() {
return useRectangleShape;
}
public void setUseRectangleShape(boolean useRectangleShape) {
this.useRectangleShape = useRectangleShape;
}
public boolean isShowXAxis() {
return false;
}
public boolean isShowYAxis() {
return false;
}
public boolean canShowLegend() {
return false;
}
private int getMaxFontSize() {
return maxFontSize;
}
private void setMaxFontSize(int maxFontSize) {
this.maxFontSize = maxFontSize;
}
public void updateView() {
if ((!isTranspose() && mustUpdateCoordinates()) || (isTranspose() && mustUpdateCoordinatesTransposed())) {
if (future != null) {
future.cancel(true);
future = null;
}
inUpdateCoordinates = true;
future = executorService.submit(() -> {
try {
if (isTranspose()) {
updateCoordinatesTransposed();
} else
updateCoordinates();
if (SwingUtilities.isEventDispatchThread()) {
inUpdateCoordinates = false;
viewer.repaint();
future = null;
} else {
SwingUtilities.invokeAndWait(() -> {
inUpdateCoordinates = false;
viewer.repaint();
future = null;
});
}
} catch (Exception e) {
inUpdateCoordinates = false;
}
});
}
}
public void updateViewImmediately() {
if (isTranspose()) {
updateCoordinatesTransposed();
} else
updateCoordinates();
}
public void close() {
if (future != null) {
future.cancel(true);
future = null;
}
}
public boolean canShowValues() {
return false;
}
/**
* force update
*/
@Override
public void forceUpdate() {
previousScalingType = null;
}
/**
* create a new instance of the given type of drawer, sharing internal data structures
*
*/
public WordCloudDrawer createInstance() {
final WordCloudDrawer drawer = new WordCloudDrawer();
drawer.setViewer(viewer);
drawer.setChartData(new DefaultChartData());
drawer.setClass2HigherClassMapper(class2HigherClassMapper);
drawer.setSeriesLabelGetter(seriesLabelGetter);
drawer.setExecutorService(executorService);
return drawer;
}
@Override
public void setWidth(int width) {
this.width = width;
}
@Override
public void setHeight(int height) {
this.height = height;
}
public boolean canTranspose() {
return false;
}
@Override
public void setGraphics(Graphics graphics) {
this.graphics = graphics;
}
@Override
public Graphics getGraphics() {
return graphics;
}
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return height;
}
@Override
public JToolBar getBottomToolBar() {
return null;
}
@Override
public ScalingType getScalingTypePreference() {
return ScalingType.SQRT;
}
@Override
public boolean getShowXAxisPreference() {
return false;
}
@Override
public boolean getShowYAxisPreference() {
return false;
}
/**
* copy all user parameters from the given base drawer
*
*/
@Override
public void setValues(IMultiChartDrawable baseDrawer) {
setMaxFontSize(((WordCloudDrawer) baseDrawer).getMaxFontSize());
setUseRectangleShape(((WordCloudDrawer) baseDrawer).isUseRectangleShape());
}
@Override
public String getChartDrawerName() {
return NAME;
}
}
| 21,272 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
Black2RedGradient.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/Black2RedGradient.java | /*
* Black2RedGradient.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import java.awt.*;
/**
* a black to green color gradient
* Daniel Huson, 10.2010
*/
public class Black2RedGradient {
static private final Color separatorColor = new Color(150, 150, 150);
private final int maxCount;
private final double factor;
/**
* setup the green gradient
*
*/
public Black2RedGradient(int maxCount) {
this.maxCount = maxCount;
factor = maxCount / Math.log(maxCount);
}
/**
* get color on linear scale
*
* @return color
*/
private Color getColor(int count) {
if (maxCount == 0)
return Color.BLACK;
if (count > maxCount)
count = maxCount;
int scaled = Math.min(255, (int) Math.round(255.0 / maxCount * count));
if (count > 0)
scaled = Math.max(1, scaled);
return new Color(scaled, 0, 0);
}
/**
* get color on log scale
*
* @return color
*/
public Color getLogColor(int count) {
int value = (int) Math.max(0, (Math.round(factor * Math.log(count))));
if (count > 0)
value = Math.max(1, value);
return getColor(value);
}
/**
* get border color used to separate different regions
*
* @return separator color
*/
public static Color getSeparatorColor() {
return separatorColor;
}
/**
* gets the max count
*
* @return max count
*/
public int getMaxCount() {
return maxCount;
}
/**
* this is used in the node drawer of the main viewer
*
* @return color on a log scale
*/
public static Color getColorLogScale(int count, double maxReads, double inverLogMaxReads) {
int value = (int) (Math.round(maxReads * inverLogMaxReads * Math.log(count)));
value = Math.max(0, Math.min(255, (int) Math.round(255.0 / maxReads * value)));
if (count > 0)
value = Math.max(1, value);
return new Color(value, 0, 0);
}
/**
* get color on linear scale
*
* @return color
*/
public static Color getColor(int count, int maxCount) {
if (maxCount == 0)
return Color.WHITE;
if (count > maxCount)
count = maxCount;
int scaled = Math.min(255, (int) Math.round(255.0 / maxCount * count));
if (count > 0)
scaled = Math.max(1, scaled);
return new Color(scaled, 0, 0);
}
}
| 3,297 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
Plot2DDrawer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/Plot2DDrawer.java | /*
* Plot2DDrawer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.Geometry;
import jloda.swing.util.ProgramProperties;
import jloda.util.Pair;
import megan.chart.IChartDrawer;
import megan.chart.data.IPlot2DData;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.SelectionGraphics;
import megan.util.ScalingType;
import java.awt.*;
import java.awt.geom.Point2D;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
/**
* draws a 2D plot
* Daniel Huson, 5.2012
*/
public class Plot2DDrawer extends ChartDrawerBase implements IChartDrawer {
public static final String NAME = "Plot2D";
private final Double maxDisplayedXValue = null;
private Double maxDisplayedYValue = null;
public enum GridStyle {ABOVE, BELOW, NONE}
private GridStyle gridStyle = GridStyle.ABOVE;
private final Set<String> seriesWithoutLines = new HashSet<>();
private final Set<String> seriesWithoutDots = new HashSet<>();
private final Set<String> seriesWithJitter = new HashSet<>();
/**
* constructor
*/
public Plot2DDrawer() {
super();
setBackground(Color.WHITE);
leftMargin = 100;
rightMargin = 20;
}
/**
* paints the chart
*
*/
public void paint(Graphics gc0) {
super.paint(gc0);
final Graphics2D gc = (Graphics2D) gc0;
bottomMargin = 50;
if (isShowXAxis()) {
double xAxisLabelHeight = computeXAxisLabelHeight(gc);
bottomMargin += xAxisLabelHeight;
if (classLabelAngle > 0 && classLabelAngle < Math.PI / 2)
rightMargin = Math.max(75, (int) (0.8 * xAxisLabelHeight));
} else
bottomMargin += 20;
drawTitle(gc);
if (getChartData().getRangeX() == null || getChartData().getRangeY() == null)
return; // nothing to draw
if (isLargeEnough()) {
if (gridStyle == GridStyle.BELOW) {
// drawGrid(gc, gridStyle);
}
computeScrollBackReferenceRect();
drawChart(gc);
if (isShowXAxis())
drawXAxis(gc);
if (isShowYAxis())
drawYAxis(gc);
if (gridStyle == GridStyle.ABOVE) {
// drawGrid(gc, gridStyle);
}
}
}
/**
* draw the title of the chart
*
*/
private void drawTitle(Graphics2D gc) {
if (chartTitle != null) {
Dimension labelSize = BasicSwing.getStringSize(gc, chartTitle, gc.getFont()).getSize();
int x = (getWidth() - labelSize.width) / 2;
int y = labelSize.height + 5;
gc.setFont(getFont(ChartViewer.FontKeys.TitleFont.toString()));
gc.setColor(getFontColor(ChartViewer.FontKeys.TitleFont.toString(), Color.BLACK));
gc.drawString(chartTitle, x, y);
//gc.drawLine(x,y+4,x+labelSize.width,y+4);
}
}
/**
* is canvas large enough to draw chart?
*
* @return true, if can draw chart
*/
private boolean isLargeEnough() {
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
return x0 < x1 && y0 > y1;
}
/**
* draw the x axis
*
*/
private void drawXAxis(Graphics2D gc) {
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
// draw x-axis
gc.setColor(Color.BLACK);
gc.drawLine(x0, y0, x1 + 10, y0);
drawArrowHead(gc, new Point(x0, y0), new Point(x1 + 10, y0));
drawXAxisTicks(gc);
if (getChartData().getSeriesLabel() != null) {
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.BLACK));
int x = 5;
int y = getHeight() - bottomMargin + 25;
if (isTranspose())
gc.drawString(getChartData().getClassesLabel(), x, y);
else
gc.drawString(getChartData().getSeriesLabel(), x, y);
}
}
/**
* draw the ticks along the X axis
*
*/
private void drawXAxisTicks(Graphics2D gc) {
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
int y0 = getHeight() - bottomMargin;
double botX = 0;
double topX = transpose ? getChartData().getRangeY().getSecond().doubleValue() : getChartData().getRangeX().getSecond().doubleValue();
double xFactor;
if (topX > botX)
xFactor = (x1 - x0) / (topX - botX);
else
xFactor = 1;
int tickStepX = 0;
int minSpace = 50;
for (int i = 1; tickStepX == 0; i *= 10) {
if (i * xFactor >= minSpace)
tickStepX = i;
else if (2.5 * i * xFactor >= minSpace)
tickStepX = (int) (2.5 * i);
else if (5 * i * xFactor >= minSpace)
tickStepX = 5 * i;
}
int startX = 0;
while (startX + tickStepX < botX) {
startX += tickStepX;
}
double offsetX = botX - startX;
gc.setColor(Color.BLACK);
for (int value = startX; (value - 1) < topX; value += tickStepX) {
if (value >= botX) {
if (maxDisplayedXValue != null && value > maxDisplayedXValue)
break;
String label = "" + value;
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
double xPos = x0 + value * xFactor - offsetX;
// if (xPos - x0 > tickStepX)
Point2D apt = new Point2D.Double(xPos, (y0 + labelSize.getHeight() + 2));
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
drawString(gc, label, apt.getX(), apt.getY(), classLabelAngle);
gc.drawLine((int) xPos, y0, (int) xPos, y0 - 2);
}
}
}
private double computeXAxisLabelHeight(Graphics2D gc) {
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
double theHeight = 2 * gc.getFont().getSize();
if (classLabelAngle != 0) {
double sin = Math.abs(Math.sin(classLabelAngle));
Dimension labelSize = BasicSwing.getStringSize(gc, "" + maxDisplayedXValue, gc.getFont()).getSize();
theHeight = gc.getFont().getSize() + sin * labelSize.width;
}
return theHeight;
}
/**
* draw the y-axis
*
*/
private void drawYAxis(Graphics2D gc) {
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
gc.setColor(Color.BLACK);
// draw y-axis
gc.drawLine(x0, y0, x0, y1 - 10);
drawArrowHead(gc, new Point(x0, y0), new Point(x0, y1 - 10));
drawYAxisTicks(gc);
if (getChartData().getCountsLabel() != null) {
String label = getChartData().getCountsLabel();
if (scalingType == ScalingType.PERCENT)
label += " (%)";
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
int x = 15;
int y = (y0 + y1) / 2 - labelSize.width / 2;
gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString()));
gc.setColor(getFontColor(ChartViewer.FontKeys.YAxisFont.toString(), Color.BLACK));
drawString(gc, label, x, y, Math.PI / 2);
//gc.drawString(getyAxisLabel(),x,y);
}
}
/**
* draw the ticks along the Y axis
*
*/
private void drawYAxisTicks(Graphics2D gc) {
gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString()));
if (scalingType == ScalingType.LOG) {
drawYAxisTicksLog(gc);
return;
} else if (scalingType == ScalingType.SQRT) {
drawYAxisTicksSqrt(gc);
return;
}
int x0 = leftMargin;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
double botY;
double topY;
if (scalingType == ScalingType.PERCENT) {
botY = 0;
topY = 100;
} else {
botY = 0;
topY = getChartData().getRangeY().getSecond().doubleValue();
}
double yFactor;
if (topY > botY)
yFactor = (y0 - y1) / (topY - botY);
else
yFactor = 1;
int tickStepY = 0;
int minSpace = 50;
for (int i = 1; tickStepY == 0; i *= 10) {
if (i * yFactor >= minSpace)
tickStepY = i;
else if (2.5 * i * yFactor >= minSpace)
tickStepY = (int) (2.5 * i);
else if (5 * i * yFactor >= minSpace)
tickStepY = 5 * i;
}
int startY = 0;
while (startY + tickStepY < botY) {
startY += tickStepY;
}
double offsetY = botY - startY;
gc.setColor(Color.BLACK);
for (int value = startY; (value - 1) < topY; value += tickStepY) {
if (value >= botY) {
if (maxDisplayedYValue != null && value > maxDisplayedYValue)
break;
String label = "" + value;
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
double y = y0 - value * yFactor + offsetY;
if (y < y1)
break;
float yPos = (float) (y + labelSize.getHeight() / 2.0);
gc.drawString(label, leftMargin - (int) (labelSize.getWidth() + 3), yPos);
gc.drawLine(x0, (int) y, x0 + 2, (int) y);
}
}
}
/**
* draw the ticks along the Y axis
*
*/
private void drawYAxisTicksSqrt(Graphics2D gc) {
gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString()));
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
double maxValue = getChartData().getRangeY().getSecond().doubleValue();
double yFactor = (y0 - y1) / Math.sqrt(maxValue);
double value = 0;
double previousY = -100000;
int mantisse = 0;
int exponent = 0;
while (value <= maxValue) {
if (maxDisplayedYValue != null && value > maxDisplayedYValue)
break;
double yPos = y0 - (value > 0 ? Math.sqrt(value) : 0) * yFactor;
if ((mantisse <= 1 || mantisse == 5) && Math.abs(yPos - previousY) >= 20) {
String label = "" + (long) value;
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
previousY = yPos;
int x = leftMargin - (int) (labelSize.getWidth() + 3);
int y = (int) (yPos + labelSize.getHeight() / 2.0);
gc.setColor(Color.BLACK);
gc.drawString(label, x, y);
if (gridStyle == GridStyle.BELOW) {
gc.setColor(Color.LIGHT_GRAY);
gc.drawLine(x0, (int) Math.round(yPos), x1, (int) Math.round(yPos));
}
}
if (mantisse < 9)
mantisse++;
else {
mantisse = 1;
exponent++;
}
value = mantisse * Math.pow(10, exponent);
}
String axisLabel = getChartData().getCountsLabel() + " (sqrt scale)";
Dimension labelSize = BasicSwing.getStringSize(gc, axisLabel, gc.getFont()).getSize();
int x = 10;
int y = (y0 + y1) / 2 - labelSize.width;
gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString()));
drawString(gc, axisLabel, x, y, Math.PI / 2);
}
/**
* draw the ticks along the Y axis
*
*/
private void drawYAxisTicksLog(Graphics2D gc) {
gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString()));
int x0 = leftMargin;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
double maxValue = getChartData().getRangeY().getSecond().doubleValue();
double botY = 0;
double topY = computeMaxYAxisValueLogScale(maxValue);
double yFactor;
if (topY > botY)
yFactor = (y0 - y1) / (topY - botY);
else
yFactor = 1;
double value = 0;
double previousY = -100000;
int mantisse = 0;
int exponent = 0;
while (value <= maxValue) {
if (maxDisplayedYValue != null && value > maxDisplayedYValue)
break;
double yPos = y0 - (value > 0 ? Math.log10(value) : 0) * yFactor;
if ((mantisse <= 1 || mantisse == 5) && Math.abs(yPos - previousY) >= 20) {
String label = "" + (long) value;
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
previousY = yPos;
int x = leftMargin - (int) (labelSize.getWidth() + 3);
int y = (int) (yPos + labelSize.getHeight() / 2.0);
gc.drawString(label, x, y);
gc.drawLine(x0, (int) Math.round(yPos), x0 + 2, (int) Math.round(yPos));
}
if (mantisse < 9)
mantisse++;
else {
mantisse = 1;
exponent++;
}
value = mantisse * Math.pow(10, exponent);
}
}
/**
* draw bars in which colors are by dataset
*
*/
public void drawChart(Graphics2D gc) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
double botX = 0;
double topX = transpose ? getChartData().getRangeY().getSecond().doubleValue() : getChartData().getRangeX().getSecond().doubleValue();
double factorX;
if (topX > botX)
factorX = (x1 - x0) / (topX - botX);
else
factorX = 1;
int tickStepX = 0;
int minSpace = 50;
for (int i = 1; tickStepX == 0; i *= 10) {
if (i * factorX >= minSpace)
tickStepX = i;
else if (2.5 * i * factorX >= minSpace)
tickStepX = (int) (2.5 * i);
else if (5 * i * factorX >= minSpace)
tickStepX = 5 * i;
}
int startX = 0;
while (startX + tickStepX < botX) {
startX += tickStepX;
}
double offsetX = botX - startX;
double botY;
double topY;
if (scalingType == ScalingType.PERCENT) {
botY = 0;
topY = 100;
} else if (scalingType == ScalingType.LOG) {
botY = 0;
topY = computeMaxYAxisValueLogScale(getChartData().getRangeY().getSecond().doubleValue());
} else if (scalingType == ScalingType.SQRT) {
botY = 0;
topY = Math.sqrt(getChartData().getRangeY().getSecond().doubleValue());
} else {
botY = 0;
topY = getChartData().getRangeY().getSecond().doubleValue();
}
double factorY;
if (topY > botY)
factorY = (y0 - y1) / (topY - botY);
else
factorY = 1;
int tickStepY = 0;
for (int i = 1; tickStepY == 0; i *= 10) {
if (i * factorY >= minSpace)
tickStepY = i;
else if (2.5 * i * factorY >= minSpace)
tickStepY = (int) (2.5 * i);
else if (5 * i * factorY >= minSpace)
tickStepY = 5 * i;
}
int startY = 0;
while (startY + tickStepY < botY) {
startY += tickStepY;
}
double offsetY = botY - startY;
Random random = new Random(666);
double maxX = getChartData().getRangeX().getSecond().doubleValue();
double maxY = getChartData().getRangeY().getSecond().doubleValue();
for (String series : getChartData().getSeriesNames()) {
Point previous = null;
boolean showLines = isShowLines(series);
boolean showDots = isShowDots(series);
boolean useJitter = isUseJitter(series);
Color color = getChartColors().getSampleColor(series);
Color darker = color.darker();
boolean isSelected = getChartData().getChartSelection().isSelected(series, null);
if (sgc != null)
sgc.setCurrentItem(new String[]{series, null});
java.util.Collection<Pair<Number, Number>> data = getChartData().getDataForSeries(series);
for (Pair<Number, Number> pair : data) {
double xValue = pair.getFirst().doubleValue();
double yValue;
if (getScalingType() == ScalingType.PERCENT) {
yValue = (100.0 / maxY) * pair.getSecond().doubleValue();
} else if (getScalingType() == ScalingType.LOG) {
yValue = pair.getSecond().doubleValue();
if (yValue > 0)
yValue = Math.log10(yValue);
} else if (getScalingType() == ScalingType.SQRT) {
yValue = pair.getSecond().doubleValue();
if (yValue > 0)
yValue = Math.sqrt(yValue);
} else {
yValue = pair.getSecond().doubleValue();
}
int x = (int) Math.round(xValue * factorX + x0 - offsetX);
int y = (int) Math.round(y0 - yValue * factorY - offsetY);
if (useJitter) {
x += (random.nextInt(8) - 4);
y += (random.nextInt(8) - 4);
}
if (showLines) {
if (previous != null) {
if (isSelected) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.setStroke(HEAVY_STROKE);
gc.drawLine(previous.x, previous.y, x, y);
gc.setStroke(NORMAL_STROKE);
} else {
gc.setColor(color);
gc.drawLine(previous.x, previous.y, x, y);
}
}
previous = new Point(x, y);
}
if (showDots) {
if (isSelected) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.setStroke(HEAVY_STROKE);
gc.fillOval(x - 2, y - 2, 4, 4);
gc.setStroke(NORMAL_STROKE);
} else {
gc.setColor(darker);
gc.fillOval(x - 2, y - 2, 4, 4);
}
}
if (showValues || isSelected) {
String label = pair.getFirst() + "," + pair.getSecond();
valuesList.add(new DrawableValue(label, x + 4, y, isSelected));
}
}
if (sgc != null)
sgc.clearCurrentItem();
}
if (valuesList.size() > 0) {
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
DrawableValue.drawValues(gc, valuesList, false, false);
valuesList.clear();
}
}
public Double getMaxDisplayedYValue() {
return maxDisplayedYValue;
}
/**
* use this to set the max displayed y value
*
*/
public void setMaxDisplayedYValue(Double maxDisplayedYValue) {
this.maxDisplayedYValue = maxDisplayedYValue;
}
public GridStyle getGridStyle() {
return gridStyle;
}
public void setGridStyle(GridStyle gridStyle) {
this.gridStyle = gridStyle;
}
public void setShowLines(String series, boolean join) {
if (join)
seriesWithoutLines.remove(series);
else
seriesWithoutLines.add(series);
}
private boolean isShowLines(String series) {
return !seriesWithoutLines.contains(series);
}
public void setShowDots(String series, boolean join) {
if (join)
seriesWithoutDots.remove(series);
else
seriesWithoutDots.add(series);
}
private boolean isShowDots(String series) {
return !seriesWithoutDots.contains(series);
}
public boolean isUseJitter(String series) {
return seriesWithJitter.contains(series);
}
public void setUseJitter(String series, boolean useJitter) {
if (useJitter)
seriesWithJitter.add(series);
else
seriesWithJitter.remove(series);
}
public IPlot2DData getChartData() {
return (IPlot2DData) super.getChartData();
}
public boolean canTranspose() {
return false;
}
public boolean canShowValues() {
return true;
}
@Override
public String getChartDrawerName() {
return NAME;
}
}
| 22,594 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
MultiChartDrawer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/MultiChartDrawer.java | /*
* MultiChartDrawer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.ProgramProperties;
import jloda.util.Pair;
import megan.chart.IChartDrawer;
import megan.chart.IMultiChartDrawable;
import megan.chart.data.IChartData;
import megan.chart.gui.SelectionGraphics;
import megan.util.ScalingType;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.util.*;
/**
* draws a multi-chart
* Daniel Huson, 6.2012, 4.2105
*/
public class MultiChartDrawer extends BarChartDrawer implements IChartDrawer {
private final Dimension panelSize = new Dimension();
private final Map<String, IMultiChartDrawable> label2drawer = new HashMap<>();
private final IMultiChartDrawable baseDrawer;
private boolean labelsAreSeries = false;
/**
* constructor
*
*/
public MultiChartDrawer(IMultiChartDrawable baseDrawer) {
super();
this.baseDrawer = baseDrawer;
setViewer(baseDrawer.getViewer());
setChartData(baseDrawer.getChartData());
setClass2HigherClassMapper(baseDrawer.getClass2HigherClassMapper());
setSeriesLabelGetter(baseDrawer.getSeriesLabelGetter());
setScalingType(getScalingTypePreference());
setShowXAxis(getShowXAxisPreference());
setShowYAxis(getShowYAxisPreference());
}
/**
* draw chart in which colors are by series
*
*/
public void drawChart(Graphics2D gc) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
//if(sgc!=null) lastDown=(Rectangle)sgc.getSelectionRectangle().clone();
int numberOfPanels = getChartData().getNumberOfSeries();
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
int rows = Math.max(1, (int) Math.sqrt(numberOfPanels));
int cols = Math.max(1, (int) Math.ceil((double) numberOfPanels / rows));
panelSize.setSize(getWidth() / cols, (y0 - y1) / rows - 14);
Font labelFont = getFont("Default");
AffineTransform transform = gc.getTransform();
int panel = 0;
for (String series : getChartData().getSeriesNames()) {
final int h = (panel % cols) * panelSize.width;
final int v = (panel / cols) * (panelSize.height + 14) + y1;
final IMultiChartDrawable chartDrawer = label2drawer.get(series);
if (chartDrawer == null)
continue;
chartDrawer.setMargins(0, 0, 0, 0);
chartDrawer.setTranspose(true);
chartDrawer.setScalingType(getScalingType());
chartDrawer.setShowValues(isShowValues());
chartDrawer.getChartData().setDataSetName(getChartData().getDataSetName());
chartDrawer.getChartData().setSeriesLabel(series);
chartDrawer.getChartData().getChartSelection().clearSelectionClasses();
chartDrawer.getChartData().getChartSelection().setSelectedClass(getChartData().getChartSelection().getSelectedClasses(), true);
chartDrawer.getChartData().getChartSelection().clearSelectionSeries();
chartDrawer.getChartData().getChartSelection().setSelectedSeries(getChartData().getChartSelection().getSelectedSeries(), true);
chartDrawer.getChartData().getChartSelection().setSelectedBasedOnSeries(getChartData().getChartSelection().isSelectedBasedOnSeries());
chartDrawer.setValues(baseDrawer);
chartDrawer.setWidth(panelSize.width);
chartDrawer.setHeight(panelSize.height);
chartDrawer.updateView();
AffineTransform newTransform = (AffineTransform) transform.clone();
newTransform.translate(h, v);
gc.setTransform(newTransform);
Rectangle saveClip = gc.getClipBounds();
Rectangle newClip = new Rectangle(0, 0, panelSize.width, panelSize.height + 14);
if (saveClip != null) { // can be null when using selection graphics
newClip = newClip.intersection(saveClip);
gc.setClip(newClip);
}
if (sgc != null) {
sgc.setCurrentItem(new String[]{series, null});
gc.fillRect(0, 0, panelSize.width, panelSize.height + 14);
sgc.clearCurrentItem();
}
chartDrawer.drawChart(gc);
if (numberOfPanels > 1) {
gc.setColor(Color.DARK_GRAY);
gc.setFont(labelFont);
String label = seriesLabelGetter.getLabel(series);
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
while (labelSize.width + 2 > panelSize.width && label.length() >= 5) {
label = label.substring(0, label.length() - 4) + "...";
labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
}
if (sgc != null)
sgc.setCurrentItem(new String[]{series, null});
gc.drawString(label, (panelSize.width - labelSize.width) / 2, panelSize.height + 12);
if (sgc != null)
sgc.clearCurrentItem();
}
if (saveClip != null)
gc.setClip(saveClip);
if (numberOfPanels > 1) {
gc.setColor(Color.LIGHT_GRAY);
gc.drawRect(0, 0, panelSize.width, panelSize.height + 14);
}
if (getChartData().getChartSelection().isSelected(series, null)) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.drawRect(0, 0, panelSize.width, panelSize.height + 14);
gc.setStroke(NORMAL_STROKE);
}
panel++;
}
gc.setTransform(transform);
if (sgc == null && lastDown != null) {
gc.setColor(Color.green);
gc.draw(lastDown);
}
}
/**
* draw chart with colors representing classes
*
*/
public void drawChartTransposed(Graphics2D gc) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
int numberOfPanels = getChartData().getNumberOfClasses();
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
int rows = Math.max(1, (int) Math.sqrt(numberOfPanels));
int cols = Math.max(1, (int) Math.ceil((double) numberOfPanels / rows));
panelSize.setSize(getWidth() / cols, (y0 - y1) / rows - 14);
Font labelFont = getFont("Default");
AffineTransform transform = gc.getTransform();
int panel = 0;
for (String className : getChartData().getClassNames()) {
final int h = (panel % cols) * panelSize.width;
final int v = (panel / cols) * (panelSize.height + 14) + y1;
final IMultiChartDrawable chartDrawer = label2drawer.get(className);
if (chartDrawer == null)
continue;
chartDrawer.setMargins(0, 0, 0, 0);
chartDrawer.setTranspose(false);
chartDrawer.setScalingType(getScalingType());
chartDrawer.setShowValues(isShowValues());
chartDrawer.getChartData().setSeriesLabel(chartData.getSeriesLabel());
chartDrawer.getChartData().setClassesLabel(chartData.getClassesLabel());
chartDrawer.getChartData().setCountsLabel(chartData.getCountsLabel());
chartDrawer.getChartData().setDataSetName(getChartData().getDataSetName());
chartDrawer.getChartData().getChartSelection().clearSelectionClasses();
chartDrawer.getChartData().getChartSelection().setSelectedClass(getChartData().getChartSelection().getSelectedClasses(), true);
chartDrawer.getChartData().getChartSelection().clearSelectionSeries();
chartDrawer.getChartData().getChartSelection().setSelectedSeries(getChartData().getChartSelection().getSelectedSeries(), true);
chartDrawer.getChartData().getChartSelection().setSelectedBasedOnSeries(getChartData().getChartSelection().isSelectedBasedOnSeries());
chartDrawer.setWidth(panelSize.width);
chartDrawer.setHeight(panelSize.height);
chartDrawer.setValues(baseDrawer);
chartDrawer.updateView();
AffineTransform newTransform = (AffineTransform) transform.clone();
newTransform.translate(h, v);
gc.setTransform(newTransform);
Rectangle saveClip = gc.getClipBounds();
Rectangle newClip = new Rectangle(0, 0, panelSize.width, panelSize.height + 14);
if (saveClip != null) {
newClip = newClip.intersection(saveClip);
gc.setClip(newClip);
}
chartDrawer.drawChartTransposed(gc);
if (numberOfPanels > 1) {
gc.setColor(Color.DARK_GRAY);
gc.setFont(labelFont);
String label = className;
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
while (labelSize.width + 2 > panelSize.width && label.length() >= 5) {
label = className.substring(0, label.length() - 4) + "...";
labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
}
if (sgc != null)
sgc.setCurrentItem(new String[]{null, className});
gc.drawString(label, (panelSize.width - labelSize.width) / 2, panelSize.height + 12);
if (sgc != null)
sgc.clearCurrentItem();
}
if (saveClip != null)
gc.setClip(saveClip);
if (numberOfPanels > 1) {
gc.setColor(Color.LIGHT_GRAY);
gc.drawRect(0, 0, panelSize.width, panelSize.height + 14);
}
if (getChartData().getChartSelection().isSelected(null, className)) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.drawRect(0, 0, panelSize.width, panelSize.height + 14);
gc.setStroke(NORMAL_STROKE);
}
if (sgc != null) {
sgc.setCurrentItem(new String[]{null, className});
gc.fillRect(0, 0, panelSize.width, panelSize.height + 14);
sgc.clearCurrentItem();
}
panel++;
}
gc.setTransform(transform);
}
/**
* draw the x axis
*
*/
protected void drawXAxis(Graphics2D gc) {
}
/**
* draw the y-axis
*
*/
protected void drawYAxis(Graphics2D gc, Dimension size) {
}
public void updateView() {
if (!isTranspose()) {
if (!labelsAreSeries) {
label2drawer.clear();
labelsAreSeries = true;
}
Set<String> toDelete = new HashSet<>();
for (String label : label2drawer.keySet()) {
if (!getChartData().getSeriesNames().contains(label)) {
toDelete.add(label);
label2drawer.get(label).close();
}
}
label2drawer.keySet().removeAll(toDelete);
for (String label : getChartData().getSeriesNames()) {
IMultiChartDrawable chartDrawer = label2drawer.get(label);
if (chartDrawer == null) {
chartDrawer = baseDrawer.createInstance();
label2drawer.put(label, chartDrawer);
}
chartDrawer.setWidth(panelSize.width);
chartDrawer.setHeight(panelSize.height);
chartDrawer.setGraphics(getGraphics());
chartDrawer.setValues(baseDrawer);
chartDrawer.setChartTitle(getChartTitle());
((IChartData) chartDrawer.getChartData()).setDataForSeries(label, getChartData().getDataForSeries(label));
((IChartData) chartDrawer.getChartData()).setEnabledClassNames(getChartData().getClassNames());
chartDrawer.getChartData().setEnabledSeries(Collections.singletonList(label));
for (String target : fonts.keySet()) {
Pair<Font, Color> pair = fonts.get(target);
chartDrawer.setFont(target, pair.getFirst(), pair.getSecond());
}
}
} else {
if (labelsAreSeries) {
label2drawer.clear();
labelsAreSeries = false;
}
Set<String> toDelete = new HashSet<>();
for (String label : label2drawer.keySet()) {
if (!getChartData().getClassNames().contains(label)) {
toDelete.add(label);
label2drawer.get(label).close();
}
}
label2drawer.keySet().removeAll(toDelete);
for (String label : getChartData().getClassNames()) {
IMultiChartDrawable chartDrawer = label2drawer.get(label);
if (chartDrawer == null) {
chartDrawer = baseDrawer.createInstance();
label2drawer.put(label, chartDrawer);
}
chartDrawer.setWidth(panelSize.width);
chartDrawer.setHeight(panelSize.height);
chartDrawer.setGraphics(getGraphics());
chartDrawer.setValues(baseDrawer);
chartDrawer.setChartTitle(getChartTitle());
for (String series : getChartData().getSeriesNames()) {
((IChartData) chartDrawer.getChartData()).putValue(series, label, getChartData().getValue(series, label));
}
chartDrawer.getChartData().setEnabledSeries(getChartData().getSeriesNames());
((IChartData) chartDrawer.getChartData()).setEnabledClassNames(Collections.singletonList(label));
for (String target : fonts.keySet()) {
Pair<Font, Color> pair = fonts.get(target);
chartDrawer.setFont(target, pair.getFirst(), pair.getSecond());
}
}
}
}
public void forceUpdate() {
for (IMultiChartDrawable drawer : label2drawer.values()) {
drawer.forceUpdate();
}
}
public boolean canShowLegend() {
return baseDrawer.canShowLegend();
}
public boolean canTranspose() {
return baseDrawer.canTranspose();
}
public boolean canShowXAxis() {
return false;
}
public boolean canShowYAxis() {
return false;
}
public boolean canShowValues() {
return baseDrawer.canShowValues();
}
public void close() {
for (String label : label2drawer.keySet())
label2drawer.get(label).close();
}
public boolean isXYLocked() {
return baseDrawer.isXYLocked();
}
public IMultiChartDrawable getBaseDrawer() {
return baseDrawer;
}
@Override
public JToolBar getBottomToolBar() {
return baseDrawer.getBottomToolBar();
}
@Override
public ScalingType getScalingTypePreference() {
return baseDrawer != null ? baseDrawer.getScalingTypePreference() : ScalingType.LINEAR;
}
@Override
public boolean getShowXAxisPreference() {
return baseDrawer != null && baseDrawer.getShowXAxisPreference();
}
@Override
public boolean getShowYAxisPreference() {
return baseDrawer != null && baseDrawer.getShowYAxisPreference();
}
@Override
public String getChartDrawerName() {
return baseDrawer.getChartDrawerName();
}
@Override
public boolean isSupportedScalingType(ScalingType scalingType) {
return baseDrawer.isSupportedScalingType(scalingType);
}
@Override
public void setScalingType(ScalingType scalingType) {
if (scalingType != getScalingType()) {
super.setScalingType(scalingType);
forceUpdate();
}
}
}
| 17,014 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
BubbleChartDrawer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/BubbleChartDrawer.java | /*
* BubbleChartDrawer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.Geometry;
import jloda.swing.util.ProgramProperties;
import megan.chart.IChartDrawer;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.SelectionGraphics;
import megan.util.DrawScaleBox;
import megan.util.ScalingType;
import megan.viewer.gui.NodeDrawer;
import java.awt.*;
import java.awt.geom.Point2D;
/**
* draws a bubble chart
* Daniel Huson, 6.2012
*/
public class BubbleChartDrawer extends BarChartDrawer implements IChartDrawer {
private static final String NAME = "BubbleChart";
int maxRadius = 30;
/**
* constructor
*/
public BubbleChartDrawer() {
}
/**
* draw bubbles with colors representing classes
*
*/
public void drawChart(Graphics2D gc) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
x1 -= (2 * maxRadius + 50);
if (x0 >= x1)
return;
int numberOfSeries = getChartData().getNumberOfSeries();
int numberOfClasses = getChartData().getNumberOfClasses();
double xStep = (x1 - x0) / numberOfSeries;
double yStep = (y0 - y1) / (0.5 + numberOfClasses);
double maxCount = getChartData().getRange().getSecond().doubleValue();
double maxValue = maxCount;
if (scalingType == ScalingType.LOG && maxValue > 0)
maxValue = Math.log(maxValue);
else if (scalingType == ScalingType.SQRT && maxValue > 0)
maxValue = Math.sqrt(maxValue);
else if (scalingType == ScalingType.PERCENT) {
maxValue = 100;
maxCount = 100;
}
if (sgc == null)
DrawScaleBox.draw("Scale",gc, x1, y1 + 40, null, NodeDrawer.Style.Circle, scalingType == ScalingType.PERCENT ? ScalingType.SQRT : scalingType, (int) Math.round(maxCount), maxRadius);
double factor = (maxValue > 0 ? getMaxRadius() / maxValue : 1);
// main drawing loop:
int d = 0;
for (String series : getChartData().getSeriesNames()) {
if (isShowXAxis()) {
double xLabel = x0 + (d + 0.5) * xStep;
Point2D apt = new Point2D.Double(xLabel, getHeight() - bottomMargin + 10);
String label = seriesLabelGetter.getLabel(series);
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
if (getChartData().getChartSelection().isSelected(series, null)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.DARK_GRAY));
if (sgc != null)
sgc.setCurrentItem(new String[]{series, null});
drawString(gc, label, apt.getX(), apt.getY(), classLabelAngle);
if (sgc != null)
sgc.clearCurrentItem();
}
int c = 0;
for (String className : getChartData().getClassNames()) {
double value;
if (scalingType == ScalingType.PERCENT) {
double total = getChartData().getTotalForSeriesIncludingDisabledAttributes(series);
if (total == 0)
value = 0;
else
value = 100 * Math.sqrt(getChartData().getValueAsDouble(series, className)) / Math.sqrt(total);
} else if (scalingType == ScalingType.LOG) {
value = getChartData().getValueAsDouble(series, className);
if (value > 1)
value = Math.log(value);
} else if (scalingType == ScalingType.SQRT) {
value = getChartData().getValueAsDouble(series, className);
if (value > 0)
value = Math.sqrt(value);
} else
value = getChartData().getValueAsDouble(series, className);
value *= factor;
int[] oval = new int[]{(int) ((x0 + (d + 0.5) * xStep) - value), (int) ((y0 - (c + 1) * yStep) - value), (int) (2 * value), (int) (2 * value)};
Color color = getChartColors().getClassColor(class2HigherClassMapper.get(className), 150);
gc.setColor(color);
if (sgc != null)
sgc.setCurrentItem(new String[]{series, className});
gc.fillOval(oval[0], oval[1], oval[2], oval[3]);
if (sgc != null)
sgc.clearCurrentItem();
boolean isSelected = getChartData().getChartSelection().isSelected(series, className);
if (isSelected) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
if (oval[2] <= 1) {
oval[0] -= 1;
oval[1] -= 1;
oval[2] += 2;
oval[3] += 2;
}
gc.setStroke(HEAVY_STROKE);
gc.drawOval(oval[0], oval[1], oval[2], oval[3]);
gc.setStroke(NORMAL_STROKE);
} else {
gc.setColor(color.darker());
gc.drawOval(oval[0], oval[1], oval[2], oval[3]);
}
c++;
if (showValues || isSelected) {
String label = "" + (int) getChartData().getValueAsDouble(series, className);
valuesList.add(new DrawableValue(label, oval[0] + oval[2] + 2, oval[1] + oval[3] / 2, isSelected));
}
}
d++;
}
if (valuesList.size() > 0) {
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
DrawableValue.drawValues(gc, valuesList, false, true);
valuesList.clear();
}
}
/**
* draw bubbles in which colors are by dataset
*
*/
public void drawChartTransposed(Graphics2D gc) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
if (x0 >= x1)
return;
int numberOfClasses = getChartData().getNumberOfClasses();
int numberOfSeries = getChartData().getNumberOfSeries();
double xStep = (x1 - x0) / numberOfClasses;
double yStep = (y0 - y1) / (0.5 + numberOfSeries);
double maxValue = getChartData().getRange().getSecond().doubleValue();
double maxCount = maxValue;
if (scalingType == ScalingType.LOG && maxValue > 0)
maxValue = Math.log(maxValue);
else if (scalingType == ScalingType.SQRT && maxValue > 0)
maxValue = Math.sqrt(maxValue);
else if (scalingType == ScalingType.PERCENT) {
maxValue = 100;
maxCount = 100;
}
if (sgc == null)
DrawScaleBox.draw("Scale",gc, x1, y1 + 40, null, NodeDrawer.Style.Circle, scalingType == ScalingType.PERCENT ? ScalingType.SQRT : scalingType, (int) Math.round(maxCount), maxRadius);
double factor = (maxValue > 0 ? getMaxRadius() / maxValue : 1);
// main drawing loop:
int c = 0;
for (String className : getChartData().getClassNames()) {
if (isShowXAxis()) {
double xLabel = x0 + (c + 0.5) * xStep;
Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize();
Point2D apt = new Point2D.Double(xLabel, getHeight() - bottomMargin + 10);
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
if (getChartData().getChartSelection().isSelected(null, className)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.DARK_GRAY));
if (sgc != null)
sgc.setCurrentItem(new String[]{null, className});
drawString(gc, className, apt.getX(), apt.getY(), classLabelAngle);
if (sgc != null)
sgc.clearCurrentItem();
}
int d = 0;
for (String series : getChartData().getSeriesNames()) {
double value;
if (scalingType == ScalingType.PERCENT) {
double total = getChartData().getTotalForClassIncludingDisabledSeries(className);
if (total == 0)
value = 0;
else
value = 100 * Math.sqrt(getChartData().getValueAsDouble(series, className)) / Math.sqrt(total);
} else if (scalingType == ScalingType.LOG) {
value = getChartData().getValueAsDouble(series, className);
if (value > 1)
value = Math.log(value);
} else if (scalingType == ScalingType.SQRT) {
value = getChartData().getValueAsDouble(series, className);
if (value > 1)
value = Math.sqrt(value);
} else
value = getChartData().getValueAsDouble(series, className);
value *= factor;
int[] oval = new int[]{(int) ((x0 + (c + 0.5) * xStep) - value), (int) ((y0 - (d + 1) * yStep) - value), (int) (2 * value), (int) (2 * value)};
Color color = getChartColors().getSampleColorWithAlpha(series, 150);
gc.setColor(color);
if (sgc != null)
sgc.setCurrentItem(new String[]{series, className});
gc.fillOval(oval[0], oval[1], oval[2], oval[3]);
if (sgc != null)
sgc.clearCurrentItem();
boolean isSelected = getChartData().getChartSelection().isSelected(series, className);
if (isSelected) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
if (oval[2] <= 1) {
oval[0] -= 1;
oval[1] -= 1;
oval[2] += 2;
oval[3] += 2;
}
gc.setStroke(HEAVY_STROKE);
gc.drawOval(oval[0], oval[1], oval[2], oval[3]);
gc.setStroke(NORMAL_STROKE);
} else {
gc.setColor(color.darker());
gc.drawOval(oval[0], oval[1], oval[2], oval[3]);
}
d++;
if (showValues || isSelected) {
String label = "" + (int) getChartData().getValueAsDouble(series, className);
valuesList.add(new DrawableValue(label, oval[0] + oval[2] + 2, oval[1] + oval[3] / 2, isSelected));
}
}
c++;
}
if (valuesList.size() > 0) {
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
DrawableValue.drawValues(gc, valuesList, false, true);
valuesList.clear();
}
}
private int getMaxRadius() {
return maxRadius;
}
public void setMaxRadius(int maxRadius) {
this.maxRadius = maxRadius;
}
/**
* draw the x axis
*
*/
protected void drawXAxis(Graphics2D gc) {
}
/**
* draw the y-axis
*
*/
protected void drawYAxis(Graphics2D gc, Dimension size) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString()));
boolean doDraw = (size == null);
Rectangle bbox = null;
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
if (!isTranspose()) {
int longest = 0;
for (String className : getChartData().getClassNames()) {
longest = Math.max(longest, BasicSwing.getStringSize(gc, className, gc.getFont()).getSize().width);
}
int colorRectTotalWidth = gc.getFont().getSize() + 4;
int right = Math.max(leftMargin, longest + maxRadius / 2 + 2);
int numberOfClasses = getChartData().getNumberOfClasses();
double yStep = (y0 - y1) / (0.5 + numberOfClasses);
int c = 0;
for (String className : getChartData().getClassNames()) {
Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize();
int x = right - maxRadius / 2 - 2 - labelSize.width - colorRectTotalWidth;
int y = (int) Math.round(y0 - (c + 1) * yStep);
int height = gc.getFont().getSize();
if (doDraw) {
gc.setColor(getChartColors().getClassColor(class2HigherClassMapper.get(className), 150));
gc.fillRect(right - maxRadius / 2 - colorRectTotalWidth, y - height + 4, height - 5, height - 5);
if (getChartData().getChartSelection().isSelected(null, className)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, x, y, labelSize.width, labelSize.height, 0, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.YAxisFont.toString(), Color.DARK_GRAY));
if (sgc != null)
sgc.setCurrentItem(new String[]{null, className});
gc.drawString(className, x, y);
if (sgc != null)
sgc.clearCurrentItem();
} else {
int width = labelSize.width + colorRectTotalWidth;
Rectangle rect = new Rectangle(x, y, width + 2, labelSize.height);
if (bbox == null)
bbox = rect;
else
bbox.add(rect);
}
c++;
}
} else // tranposed
{
if (x0 >= x1)
return;
int longest = 0;
for (String series : getChartData().getSeriesNames()) {
String label = seriesLabelGetter.getLabel(series);
longest = Math.max(longest, BasicSwing.getStringSize(gc, label, gc.getFont()).getSize().width);
}
int colorRectTotalWidth = gc.getFont().getSize() + 4;
int right = Math.max(leftMargin, longest + maxRadius / 2 + 2);
int numberOfDataSets = getChartData().getNumberOfSeries();
double yStep = (y0 - y1) / (0.5 + numberOfDataSets);
int d = 0;
for (String series : getChartData().getSeriesNames()) {
String label = seriesLabelGetter.getLabel(series);
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
int x = right - maxRadius / 2 - 2 - labelSize.width - colorRectTotalWidth;
int y = (int) Math.round(y0 - (d + 1) * yStep);
int height = gc.getFont().getSize();
if (doDraw) {
gc.setColor(getChartColors().getSampleColor(series));
gc.fillRect(right - maxRadius / 2 - colorRectTotalWidth, y - height + 4, height - 5, height - 5);
if (getChartData().getChartSelection().isSelected(series, null)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, x, y, labelSize.width, labelSize.height, 0, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.YAxisFont.toString(), Color.DARK_GRAY));
if (sgc != null)
sgc.setCurrentItem(new String[]{series, null});
gc.drawString(label, x, y);
if (sgc != null)
sgc.clearCurrentItem();
} else {
int width = labelSize.width + colorRectTotalWidth;
Rectangle rect = new Rectangle(x, y, width + 2, labelSize.height);
if (bbox == null)
bbox = rect;
else
bbox.add(rect);
}
d++;
}
}
if (size != null && bbox != null) {
size.setSize(bbox.width + maxRadius / 2, bbox.height);
}
}
private int replaceAllButFirstDigitByZero(int value) {
String str = "" + value;
return Integer.parseInt(str.charAt(0) + str.substring(1).replaceAll(".", "0")); // use, replace all digits by 0
}
private int replaceFirstDigitByOne(int value) {
String str = "" + value;
return Integer.parseInt("1" + str.substring(1));
}
public boolean canShowValues() {
return true;
}
@Override
public ScalingType getScalingTypePreference() {
return ScalingType.SQRT;
}
@Override
public String getChartDrawerName() {
return NAME;
}
}
| 19,621 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
HeatMapDrawer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/HeatMapDrawer.java | /*
* HeatMapDrawer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.ColorTable;
import jloda.swing.util.Geometry;
import jloda.swing.util.ProgramProperties;
import jloda.swing.window.IPopupMenuModifier;
import jloda.util.Basic;
import jloda.util.Statistics;
import jloda.util.Table;
import megan.chart.IChartDrawer;
import megan.chart.cluster.ClusteringTree;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.SelectionGraphics;
import megan.util.ScalingType;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.geom.Point2D;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* draws a heatmap chart
* Daniel Huson, 6.2012
*/
public class HeatMapDrawer extends BarChartDrawer implements IChartDrawer {
private static final String NAME = "HeatMap";
private String[] seriesNames;
private String[] classNames;
private ColorTable colorTable;
private final Table<String, String, Double> zScores = new Table<>();
private final double zScoreCutoff = 3;
private final ArrayList<String> previousSamples = new ArrayList<>();
private final ArrayList<String> previousClasses = new ArrayList<>();
private final ClusteringTree seriesClusteringTree;
private final ClusteringTree classesClusteringTree;
private boolean previousTranspose;
private boolean previousClusterSeries;
private boolean previousClusterClasses;
private final int topTreeSpace = ProgramProperties.get("topTreeSpace", 100);
private final int rightTreeSpace = ProgramProperties.get("rightTreeSpace", 100);
private Future future; // used in recompute
private boolean inUpdateCoordinates = true;
/**
* constructor
*/
public HeatMapDrawer() {
getSupportedScalingTypes().add(ScalingType.ZSCORE);
seriesClusteringTree = new ClusteringTree(ClusteringTree.TYPE.SERIES, ClusteringTree.SIDE.TOP);
classesClusteringTree = new ClusteringTree(ClusteringTree.TYPE.CLASSES, ClusteringTree.SIDE.RIGHT);
previousTranspose = isTranspose();
executorService = Executors.newSingleThreadExecutor(); // ensure we only use one thread at a time on update
}
/**
* draw heat map with colors representing classes
*
*/
public void drawChart(Graphics2D gc) {
final SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
gc.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString()));
colorTable = getChartColors().getHeatMapTable();
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
int x0 = leftMargin;
int scaleWidth = 30;
int x1 = getWidth() - rightMargin - scaleWidth;
if (x0 >= x1)
return;
if (inUpdateCoordinates) {
gc.setFont(getFont("Default"));
gc.setColor(Color.LIGHT_GRAY);
gc.drawString("Computing z-scores...", x0, y1 + 20);
viewer.getScrollPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
return;
} else {
viewer.getScrollPane().setCursor(Cursor.getDefaultCursor());
}
final int numberOfSeries = (seriesNames == null ? 0 : seriesNames.length);
final int numberOfClasses = (classNames == null ? 0 : classNames.length);
if (scalingType == ScalingType.ZSCORE && viewer.getSeriesList().isDoClustering())
y1 += topTreeSpace;
if (sgc == null)
drawScaleBar(gc, x1, scaleWidth, y1, y0 - y1);
if (scalingType == ScalingType.ZSCORE && viewer.getClassesList().isDoClustering()) {
x1 -= rightTreeSpace;
int height = (int) Math.round((y0 - y1) / (numberOfClasses + 1.0) * numberOfClasses);
int yStart = y0 + ((y1 - y0) - height) / 2;
final Rectangle rect = new Rectangle(x1, yStart, rightTreeSpace, height);
classesClusteringTree.paint(gc, rect);
}
if (scalingType == ScalingType.ZSCORE && viewer.getSeriesList().isDoClustering()) {
int width = (int) ((x1 - x0) / (numberOfSeries + 1.0) * numberOfSeries);
int xStart = x0 + ((x1 - x0) - width) / 2;
final Rectangle rect = new Rectangle(xStart, y1 - topTreeSpace, width, topTreeSpace);
seriesClusteringTree.paint(gc, rect);
}
double xStep = (x1 - x0) / (double) numberOfSeries;
double yStep = (y0 - y1) / (double) (numberOfClasses);
double maxValue = getChartData().getRange().getSecond().doubleValue();
double inverseMaxValueLog = 0;
if (scalingType == ScalingType.LOG && maxValue > 0) {
maxValue = Math.log(maxValue);
if (maxValue != 0)
inverseMaxValueLog = 1 / maxValue;
} else if (scalingType == ScalingType.SQRT && maxValue > 0) {
maxValue = Math.sqrt(maxValue);
} else if (scalingType == ScalingType.PERCENT) {
maxValue = 100;
}
// main drawing loop:
if (numberOfClasses > 0 && numberOfSeries > 0) {
int d = 0;
for (String series : seriesNames) {
double xLabel = x0 + (d + 0.5) * xStep;
Point2D apt = new Point2D.Double(xLabel, getHeight() - bottomMargin + 10);
String label = seriesLabelGetter.getLabel(series);
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
if (getChartData().getChartSelection().isSelectedSeries(series)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.DARK_GRAY));
drawString(gc, label, apt.getX(), apt.getY(), classLabelAngle);
if (sgc != null) {
sgc.setCurrentItem(new String[]{label, null});
drawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle);
sgc.clearCurrentItem();
}
int c = numberOfClasses - 1;
for (String className : classNames) {
final Color color;
if (scalingType == ScalingType.PERCENT) {
double total = getChartData().getTotalForSeriesIncludingDisabledAttributes(series);
double value;
if (total == 0)
value = 0;
else
value = 100 * getChartData().getValueAsDouble(series, className) / total;
color = colorTable.getColor((int) (1000 * value), (int) (1000 * maxValue));
} else if (scalingType == ScalingType.LOG) {
double value = getChartData().getValueAsDouble(series, className);
color = colorTable.getColorLogScale((int) value, inverseMaxValueLog);
} else if (scalingType == ScalingType.SQRT) {
double value = Math.sqrt(getChartData().getValueAsDouble(series, className));
color = colorTable.getColor((int) value, (int) maxValue);
} else if (scalingType == ScalingType.ZSCORE) {
double value = Math.max(-zScoreCutoff, Math.min(zScoreCutoff, zScores.get(series, className) != null ? zScores.get(series, className) : 0));
color = colorTable.getColor((int) (value + zScoreCutoff), (int) (2 * zScoreCutoff));
} else {
double value = getChartData().getValueAsDouble(series, className);
color = colorTable.getColor((int) value, (int) maxValue);
}
gc.setColor(color);
int[] rect = new int[]{(int) Math.round(x0 + d * xStep), (int) Math.round(y0 - (c + 1) * yStep),
(int) Math.round(xStep), (int) Math.round(yStep)};
if (sgc != null)
sgc.setCurrentItem(new String[]{series, className});
if (isGapBetweenBars() && rect[2] > 2 && rect[3] > 2) {
gc.fillRect(rect[0] + 1, rect[1] + 1, rect[2] - 2, rect[3] - 2);
} else {
gc.fillRect(rect[0], rect[1], rect[2] + 1, rect[3] + 1);
}
if (sgc != null)
sgc.clearCurrentItem();
boolean isSelected = getChartData().getChartSelection().isSelectedSeries(series)
|| getChartData().getChartSelection().isSelectedClass(className);
if (isSelected) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.drawRect(rect[0], rect[1], rect[2], rect[3]);
gc.setStroke(NORMAL_STROKE);
}
if (showValues || isSelected) {
String aLabel;
if (scalingType == ScalingType.ZSCORE)
aLabel = String.format("%.2f", zScores.get(series, className));
else
aLabel = "" + (int) getChartData().getValueAsDouble(series, className);
valuesList.add(new DrawableValue(aLabel, rect[0] + rect[2] / 2, rect[1] + rect[3] / 2, isSelected));
}
c--;
}
d++;
}
}
if (valuesList.size() > 0) {
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
DrawableValue.drawValues(gc, valuesList, true, true);
valuesList.clear();
}
gc.setColor(Color.WHITE);
}
/**
* draw heat map with colors representing series
*
*/
public void drawChartTransposed(Graphics2D gc) {
final SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
gc.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
colorTable = getChartColors().getHeatMapTable();
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
int x0 = leftMargin;
int scaleWidth = 30;
int x1 = getWidth() - rightMargin - scaleWidth;
if (x0 >= x1)
return;
if (inUpdateCoordinates) {
gc.setFont(getFont("Default"));
gc.setColor(Color.LIGHT_GRAY);
gc.drawString("Computing z-scores...", x0, y1 + 20);
viewer.getScrollPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
return;
} else
viewer.getScrollPane().setCursor(Cursor.getDefaultCursor());
final int numberOfSeries = (seriesNames == null ? 0 : seriesNames.length);
final int numberOfClasses = (classNames == null ? 0 : classNames.length);
if (scalingType == ScalingType.ZSCORE && viewer.getClassesList().isDoClustering())
y1 += topTreeSpace;
if (sgc == null)
drawScaleBar(gc, x1, scaleWidth, y1, y0 - y1);
if (scalingType == ScalingType.ZSCORE && viewer.getSeriesList().isDoClustering()) {
x1 -= rightTreeSpace;
int height = (int) Math.round((y0 - y1) / (numberOfSeries + 1.0) * numberOfSeries);
int yStart = y0 + ((y1 - y0) - height) / 2;
final Rectangle rect = new Rectangle(x1, yStart, rightTreeSpace, height);
seriesClusteringTree.paint(gc, rect);
}
if (scalingType == ScalingType.ZSCORE && viewer.getClassesList().isDoClustering()) {
int width = (int) ((x1 - x0) / (numberOfClasses + 1.0) * numberOfClasses);
int xStart = x0 + ((x1 - x0) - width) / 2;
final Rectangle rect = new Rectangle(xStart, y1 - topTreeSpace, width, topTreeSpace);
classesClusteringTree.paint(gc, rect);
}
double xStep = (x1 - x0) / (double) numberOfClasses;
double yStep = (y0 - y1) / (double) numberOfSeries;
double maxValue = getChartData().getRange().getSecond().doubleValue();
double inverseMaxValueLog = 0;
if (scalingType == ScalingType.LOG && maxValue > 0) {
maxValue = Math.log(maxValue);
if (maxValue != 0)
inverseMaxValueLog = 1 / maxValue;
} else if (scalingType == ScalingType.SQRT && maxValue > 0) {
maxValue = Math.sqrt(maxValue);
} else if (scalingType == ScalingType.PERCENT)
maxValue = 100;
// main drawing loop:
if (numberOfClasses > 0 && numberOfSeries > 0) {
int d = 0;
for (String className : classNames) {
double xLabel = x0 + (d + 0.5) * xStep;
Point2D apt = new Point2D.Double(xLabel, getHeight() - bottomMargin + 10);
Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize();
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
if (getChartData().getChartSelection().isSelectedClass(className)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.DARK_GRAY));
drawString(gc, className, apt.getX(), apt.getY(), classLabelAngle);
if (sgc != null) {
sgc.setCurrentItem(new String[]{null, className});
drawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle);
sgc.clearCurrentItem();
}
int c = numberOfSeries - 1;
for (String series : seriesNames) {
Color color;
if (scalingType == ScalingType.PERCENT) {
double total = getChartData().getTotalForClassIncludingDisabledSeries(className);
double value;
if (total == 0)
value = 0;
else
value = 100 * getChartData().getValueAsDouble(series, className) / total;
color = colorTable.getColor((int) value, (int) maxValue);
} else if (scalingType == ScalingType.LOG) {
double value = getChartData().getValueAsDouble(series, className);
color = colorTable.getColorLogScale((int) value, inverseMaxValueLog);
} else if (scalingType == ScalingType.SQRT) {
double value = Math.sqrt(getChartData().getValueAsDouble(series, className));
color = colorTable.getColor((int) value, (int) maxValue);
} else if (scalingType == ScalingType.ZSCORE) {
double value = Math.max(-zScoreCutoff, Math.min(zScoreCutoff, zScores.get(series, className)));
color = colorTable.getColor((int) (value + zScoreCutoff), (int) (2 * zScoreCutoff));
} else {
double value = getChartData().getValueAsDouble(series, className);
color = colorTable.getColor((int) value, (int) maxValue);
}
gc.setColor(color);
int[] rect = new int[]{(int) Math.round(x0 + d * xStep), (int) Math.round(y0 - (c + 1) * yStep),
(int) Math.round(xStep), (int) Math.round(yStep)};
if (sgc != null)
sgc.setCurrentItem(new String[]{series, className});
if (isGapBetweenBars() && rect[2] > 2 && rect[3] > 2) {
gc.fillRect(rect[0] + 1, rect[1] + 1, rect[2] - 2, rect[3] - 2);
} else
gc.fillRect(rect[0], rect[1], rect[2] + 1, rect[3] + 1);
if (sgc != null)
sgc.clearCurrentItem();
boolean isSelected = getChartData().getChartSelection().isSelectedSeries(series)
|| getChartData().getChartSelection().isSelectedClass(className);
if (isSelected) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.drawRect(rect[0], rect[1], rect[2], rect[3]);
gc.setStroke(NORMAL_STROKE);
}
if (showValues || isSelected) {
String aLabel;
if (scalingType == ScalingType.ZSCORE)
aLabel = String.format("%.2f", zScores.get(series, className));
else
aLabel = "" + (int) getChartData().getValueAsDouble(series, className);
valuesList.add(new DrawableValue(aLabel, rect[0] - rect[2] / 2, rect[1] + rect[3] / 2, isSelected));
}
c--;
}
d++;
}
}
if (valuesList.size() > 0) {
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
DrawableValue.drawValues(gc, valuesList, true, true);
valuesList.clear();
}
}
/**
* draw the x axis
*
*/
protected void drawXAxis(Graphics2D gc) {
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.BLACK));
gc.setColor(Color.BLACK);
int x = 5;
int y = getHeight() - bottomMargin + 25;
if (!isTranspose())
gc.drawString(getChartData().getSeriesLabel(), x, y);
else
gc.drawString(getChartData().getClassesLabel(), x, y);
}
/**
* draw the y-axis
*
*/
protected void drawYAxis(Graphics2D gc, Dimension size) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
boolean doDraw = (size == null);
Rectangle bbox = null;
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
/*
if (getyAxisLabel() != null) {
gc.setColor(Color.BLACK);
Dimension labelSize = Basic.getStringSize(gc, getyAxisLabel(), getFont()).getSize();
int x = 10;
int y = (y0 + y1) / 2 - labelSize.width;
drawString(gc, getyAxisLabel(), x, y, Math.PI / 2);
//gc.drawString(getyAxisLabel(),x,y);
}
*/
if (isTranspose()) {
if (scalingType == ScalingType.ZSCORE && viewer.getClassesList().isDoClustering())
y1 += topTreeSpace;
if (x0 >= x1)
return;
final int numberOfSeries = (seriesNames == null ? 0 : seriesNames.length);
if (numberOfSeries > 0) {
int longest = 0;
for (String series : seriesNames) {
String label = seriesLabelGetter.getLabel(series);
longest = Math.max(longest, BasicSwing.getStringSize(gc, label, gc.getFont()).getSize().width);
}
int right = Math.max(leftMargin, longest + 5);
if (doDraw)
gc.setColor(getFontColor(ChartViewer.FontKeys.YAxisFont.toString(), Color.BLACK));
int numberOfDataSets = getChartData().getNumberOfSeries();
double yStep = (y0 - y1) / (numberOfDataSets);
int d = numberOfSeries - 1;
for (String series : seriesNames) {
String label = seriesLabelGetter.getLabel(series);
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
int x = right - labelSize.width - 4;
int y = (int) Math.round(y0 - (d + 0.5) * yStep);
if (doDraw) {
if (getChartData().getChartSelection().isSelectedSeries(series)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, x, y, labelSize.width, labelSize.height, 0, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.DARK_GRAY));
gc.drawString(label, x, y);
} else {
Rectangle rect = new Rectangle(x, y, labelSize.width, labelSize.height);
if (bbox == null)
bbox = rect;
else
bbox.add(rect);
}
if (sgc != null) {
sgc.setCurrentItem(new String[]{series, null});
drawRect(gc, x, y, labelSize.width, labelSize.height, 0);
sgc.clearCurrentItem();
}
d--;
}
}
} else {
if (scalingType == ScalingType.ZSCORE && viewer.getSeriesList().isDoClustering())
y1 += topTreeSpace;
final int numberOfClasses = (classNames == null ? 0 : classNames.length);
if (numberOfClasses > 0) {
int longest = 0;
for (String className : classNames) {
longest = Math.max(longest, BasicSwing.getStringSize(gc, className, gc.getFont()).getSize().width);
}
int right = Math.max(leftMargin, longest + 5);
if (doDraw)
gc.setColor(getFontColor(ChartViewer.FontKeys.YAxisFont.toString(), Color.BLACK));
double yStep = (y0 - y1) / (double) numberOfClasses;
int c = numberOfClasses - 1;
for (String className : classNames) {
Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize();
int x = right - labelSize.width - 4;
int y = (int) Math.round(y0 - (c + 0.5) * yStep);
if (doDraw) {
if (getChartData().getChartSelection().isSelectedClass(className)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, x, y, labelSize.width, labelSize.height, 0, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.DARK_GRAY));
gc.drawString(className, x, y);
} else {
Rectangle rect = new Rectangle(x, y, labelSize.width, labelSize.height);
if (bbox == null)
bbox = rect;
else
bbox.add(rect);
}
c--;
if (sgc != null) {
sgc.setCurrentItem(new String[]{null, className});
drawRect(gc, x, y, labelSize.width, labelSize.height, 0);
sgc.clearCurrentItem();
}
}
}
}
if (size != null && bbox != null) {
size.setSize(bbox.width + 3, bbox.height);
}
}
/**
* draw scale bar
*
*/
private void drawScaleBar(Graphics2D gc, final int x, final int width, final int y, final int height) {
final int x0 = x + Math.max(10, width - 25);
int xLabel = x0 + 15;
int boxWidth = 10;
int boxHeight = Math.min(150, height - 15);
int y0 = y;
for (int i = 0; i <= boxHeight; i++) {
float p = 1f - (float) i / (float) boxHeight; // is between 1 and 0
final Color color = getChartColors().getHeatMapTable().getColor(Math.round(1000 * p), 1000);
gc.setColor(color);
gc.drawLine(x0, y0 + i, x0 + boxWidth, y0 + i);
}
gc.setColor(Color.BLACK);
gc.drawRect(x0, y0, boxWidth, boxHeight);
final double max;
final double min;
final double step;
final double yStep;
final String format;
switch (getScalingType()) {
case ZSCORE -> {
gc.drawString("z-score", x0, y - 5);
max = zScoreCutoff;
min = -zScoreCutoff;
step = 1;
yStep = boxHeight / (2.0 * zScoreCutoff);
format = "%+1.1f";
}
case PERCENT -> {
gc.drawString("%", x0, y - 5);
max = 100;
min = 0;
step = 20;
yStep = boxHeight / 5;
format = "%.0f";
}
case LINEAR -> {
double maxValue = 0;
for (String series : getChartData().getSeriesNames()) {
maxValue = Math.max(maxValue, getChartData().getRange(series).getSecond().intValue());
}
gc.drawString("Count", x0, y - 5);
int tens = 1;
int factor = 1;
while (factor * tens < maxValue) {
if (factor < 9)
factor++;
else {
tens *= 10;
factor = 1;
}
}
max = factor * tens;
min = 0;
if (factor >= 4) {
step = tens;
yStep = boxHeight / factor;
} else {
step = tens / 2;
yStep = boxHeight / (2 * factor);
}
format = "%,.0f";
}
case LOG -> {
double maxValue = 0;
for (String series : getChartData().getSeriesNames()) {
maxValue = Math.max(maxValue, getChartData().getRange(series).getSecond().intValue());
}
gc.drawString("Count", x0, y - 5);
int tens = 1;
int factor = 1;
while (factor * tens < maxValue) {
if (factor < 9)
factor++;
else {
tens *= 10;
factor = 1;
}
}
max = factor * tens;
min = 1;
format = "%,.0f";
double q = boxHeight / Math.log10(factor * tens);
gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString()));
boolean first = true;
for (double p = max; p >= min; p /= 10) {
double yy = y0 + boxHeight - q * Math.log10(p);
gc.drawString(String.format(format, p), xLabel, Math.round(yy + gc.getFont().getSize() / 2));
if (first) {
p /= factor;
first = false;
}
}
return;
}
case SQRT -> {
double maxValue = 0;
for (String series : getChartData().getSeriesNames()) {
maxValue = Math.max(maxValue, getChartData().getRange(series).getSecond().intValue());
}
gc.drawString("Count", x0, y - 5);
int tens = 1;
int factor = 1;
while (factor * tens < maxValue) {
if (factor < 9)
factor++;
else {
tens *= 10;
factor = 1;
}
}
max = factor * tens;
min = 0;
if (factor >= 4) {
step = tens;
} else {
step = tens / 2;
}
format = "%,.0f";
double q = boxHeight / Math.sqrt(factor * tens);
gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString()));
for (double p = min; p <= max; p += step) {
double yy = y0 + boxHeight - q * Math.sqrt(p);
gc.drawString(String.format(format, p), xLabel, Math.round(yy + gc.getFont().getSize() / 2));
}
return;
}
default -> {
double maxValue = 0;
for (String series : getChartData().getSeriesNames()) {
maxValue = Math.max(maxValue, getChartData().getRange(series).getSecond().intValue());
}
gc.drawString("Count", x0, y - 5);
int tens = 1;
int factor = 1;
while (factor * tens < maxValue) {
if (factor < 9)
factor++;
else {
tens *= 10;
factor = 1;
}
}
max = factor * tens;
min = 0;
step = max;
yStep = boxHeight;
format = "%,.0f";
}
}
gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString()));
for (double p = max; p >= min; p -= step) {
gc.drawString(String.format(format, p), xLabel, y0 + gc.getFont().getSize() / 2);
y0 += yStep;
}
}
/**
* do we need to recompute coordinates?
*
* @return true, if coordinates need to be recomputed
*/
private boolean mustUpdateCoordinates() {
boolean mustUpdate = (zScores.size() == 0);
if (previousTranspose != isTranspose()) {
mustUpdate = true;
}
if (!mustUpdate && scalingType == ScalingType.ZSCORE && getChartData().getNumberOfClasses() > 0 &&
getChartData().getNumberOfSeries() > 0 && zScores.size() == 0) {
mustUpdate = true;
}
if (previousTranspose != isTranspose()) {
previousTranspose = isTranspose();
previousClusterSeries = false;
previousClusterClasses = false;
}
if (!mustUpdate && classNames != null) {
final ArrayList<String> currentClasses = new ArrayList<>(getChartData().getClassNames());
if (!previousClasses.equals(currentClasses)) {
mustUpdate = true;
previousClasses.clear();
previousClasses.addAll(currentClasses);
}
}
if (!mustUpdate && seriesNames != null) {
final ArrayList<String> currentSamples = new ArrayList<>(getChartData().getSeriesNames());
if (!previousSamples.equals(currentSamples)) {
mustUpdate = true;
previousSamples.clear();
previousSamples.addAll(currentSamples);
}
}
if (!mustUpdate) {
if (!previousClusterClasses && viewer.getClassesList().isDoClustering())
mustUpdate = true;
}
if (!mustUpdate) {
if (!previousClusterSeries && viewer.getSeriesList().isDoClustering())
mustUpdate = true;
}
return mustUpdate;
}
/**
* updates the view
*/
public void updateView() {
if (mustUpdateCoordinates()) {
if (future != null) {
future.cancel(true);
future = null;
}
future = executorService.submit(() -> {
try {
inUpdateCoordinates = true;
updateCoordinates();
SwingUtilities.invokeAndWait(() -> {
try {
if (!previousClusterClasses && viewer.getClassesList().isDoClustering())
updateClassesJList();
previousClusterClasses = viewer.getClassesList().isDoClustering();
if (!previousClusterSeries && viewer.getSeriesList().isDoClustering())
updateSeriesJList();
previousClusterSeries = viewer.getSeriesList().isDoClustering();
viewer.repaint();
} catch (Exception e) {
Basic.caught(e);
}
});
} catch (Exception e) {
//Basic.caught(e);
} finally {
future = null;
inUpdateCoordinates = false;
}
});
} else {
if (!previousClusterClasses && viewer.getClassesList().isDoClustering())
updateClassesJList();
previousClusterClasses = viewer.getClassesList().isDoClustering();
if (!previousClusterSeries && viewer.getSeriesList().isDoClustering())
updateSeriesJList();
previousClusterSeries = viewer.getSeriesList().isDoClustering();
}
}
/**
* force update
*/
@Override
public void forceUpdate() {
zScores.clear();
}
/**
* computes z-scores on scale of -zScoreCutoff to zScoreCutoff
*/
private void updateCoordinates() {
System.err.println("Updating...");
zScores.clear();
seriesClusteringTree.clear();
classesClusteringTree.clear();
if (classesClusteringTree.getChartSelection() == null)
classesClusteringTree.setChartSelection(viewer.getChartSelection());
if (seriesClusteringTree.getChartSelection() == null)
seriesClusteringTree.setChartSelection(viewer.getChartSelection());
final String[] currentClasses;
{
final Collection<String> list = getViewer().getClassesList().getEnabledLabels();
currentClasses = list.toArray(new String[0]);
}
final String[] currentSeries;
{
final Collection<String> list = getViewer().getSeriesList().getEnabledLabels();
currentSeries = list.toArray(new String[0]);
}
if (true) {
final Map<String, HashMap<String, Double>> class2series2value = new HashMap<>();
for (String series : currentSeries) {
for (String className : currentClasses) {
HashMap<String, Double> series2value = class2series2value.computeIfAbsent(className, k -> new HashMap<>());
final double total = getChartData().getTotalForSeries(series);
series2value.put(series, total > 0 ? getChartData().getValueAsDouble(series, className) / total : total);
}
}
for (String className : currentClasses) {
final Statistics statistics = new Statistics(class2series2value.get(className).values());
for (String series : currentSeries) {
zScores.put(series, className, statistics.getZScore(class2series2value.get(className).get(series)));
}
}
} else {
for (String className : currentClasses) {
final Map<String, Double> series2value = new HashMap<>();
for (String series : currentSeries) {
final double total = getChartData().getTotalForSeries(series);
series2value.put(series, (total > 0 ? (getChartData().getValueAsDouble(series, className) / total) : 0));
}
final Statistics statistics = new Statistics(series2value.values());
for (String series : currentSeries) {
final double value = series2value.get(series);
zScores.put(series, className, statistics.getZScore(value));
}
}
}
if (viewer.getClassesList().isDoClustering()) {
classesClusteringTree.setRootSide(isTranspose() ? ClusteringTree.SIDE.TOP : ClusteringTree.SIDE.RIGHT);
classesClusteringTree.updateClustering(zScores);
final Collection<String> list = classesClusteringTree.getLabelOrder();
classNames = list.toArray(new String[0]);
} else
classNames = currentClasses;
if (viewer.getSeriesList().isDoClustering()) {
seriesClusteringTree.setRootSide(isTranspose() ? ClusteringTree.SIDE.RIGHT : ClusteringTree.SIDE.TOP);
seriesClusteringTree.updateClustering(zScores);
final Collection<String> list = seriesClusteringTree.getLabelOrder();
seriesNames = list.toArray(new String[0]);
} else
seriesNames = currentSeries;
}
protected void drawYAxisGrid(Graphics2D gc) {
}
public boolean canShowLegend() {
return false;
}
@Override
public String getChartDrawerName() {
return NAME;
}
@Override
public boolean usesHeatMapColors() {
return true;
}
public ScalingType getScalingTypePreference() {
return ScalingType.ZSCORE;
}
public IPopupMenuModifier getPopupMenuModifier() {
return (menu, commandManager) -> {
menu.addSeparator();
final AbstractAction action = (new AbstractAction("Flip Selected Subtree") {
@Override
public void actionPerformed(ActionEvent e) {
if (classesClusteringTree.hasSelectedSubTree()) {
//System.err.println("Rotate Classes");
classesClusteringTree.rotateSelectedSubTree();
final Collection<String> list = classesClusteringTree.getLabelOrder();
classNames = list.toArray(new String[0]);
updateClassesJList();
getJPanel().repaint();
} else if (seriesClusteringTree.hasSelectedSubTree()) {
// System.err.println("Old order: "+Basic.toString(seriesClusteringTree.getLabelOrder(),","));
//System.err.println("Rotate Series");
seriesClusteringTree.rotateSelectedSubTree();
//System.err.println("New order: "+Basic.toString(seriesClusteringTree.getLabelOrder(),","));
final Collection<String> list = seriesClusteringTree.getLabelOrder();
seriesNames = list.toArray(new String[0]);
updateSeriesJList();
getJPanel().repaint();
}
}
});
action.setEnabled(classesClusteringTree.hasSelectedSubTree() != seriesClusteringTree.hasSelectedSubTree());
menu.add(action);
};
}
private void updateSeriesJList() {
final Collection<String> selected = new ArrayList<>(viewer.getChartSelection().getSelectedSeries());
final Collection<String> ordered = new ArrayList<>(Arrays.asList(seriesNames));
final Collection<String> others = viewer.getSeriesList().getAllLabels();
others.removeAll(ordered);
ordered.addAll(others);
viewer.getSeriesList().sync(ordered, viewer.getSeriesList().getLabel2ToolTips(), true);
viewer.getSeriesList().setDisabledLabels(others);
viewer.getChartSelection().setSelectedSeries(selected, true);
}
private void updateClassesJList() {
final Collection<String> selected = new ArrayList<>(viewer.getChartSelection().getSelectedClasses());
final Collection<String> ordered = new ArrayList<>(Arrays.asList(classNames));
final Collection<String> others = viewer.getClassesList().getAllLabels();
others.removeAll(ordered);
ordered.addAll(others);
viewer.getClassesList().sync(ordered, viewer.getClassesList().getLabel2ToolTips(), true);
viewer.getClassesList().setDisabledLabels(others);
viewer.getChartSelection().setSelectedClass(selected, true);
}
@Override
public boolean canCluster(ClusteringTree.TYPE type) {
return scalingType == ScalingType.ZSCORE && (type == null || type == ClusteringTree.TYPE.SERIES || type == ClusteringTree.TYPE.CLASSES);
}
}
| 43,048 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CoOccurrenceToolBar.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/CoOccurrenceToolBar.java | /*
* CoOccurrenceToolBar.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.NumberUtils;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* widget for controlling the co-occurrence drawer
* Daniel Huson, 5.2013
*/
public class CoOccurrenceToolBar extends JToolBar {
private final static Font font = new Font((new JLabel()).getFont().getFamily(), (new JLabel()).getFont().getStyle(), 10);
private final JTextField minThresholdField = new JTextField(8);
private final JTextField minPrevalenceField = new JTextField(3);
private final JSlider minPrevalenceSlider = new JSlider();
private final JTextField maxPrevalenceField = new JTextField(3);
private final JSlider maxPrevalenceSlider = new JSlider();
private final JTextField minProbabilityField = new JTextField(3);
private final JSlider minProbabilitySlider = new JSlider();
private final JComboBox<CoOccurrenceDrawer.Method> methodCBox = new JComboBox<>();
private final JCheckBox showCooccurring = new JCheckBox();
private final JCheckBox showAntiOccurring = new JCheckBox();
private final JButton applyButton;
/**
* constructor
*
*/
public CoOccurrenceToolBar(final ChartViewer chartViewer, final CoOccurrenceDrawer coOccurrenceDrawer) {
setFloatable(false);
setBorder(BorderFactory.createEtchedBorder());
setMaximumSize(new Dimension(1000000, 22));
setPreferredSize(new Dimension(1000000, 22));
add(getSmallLabel("Detection (%)"));
minThresholdField.setMaximumSize(new Dimension(88, 15));
minThresholdField.setText(String.format("%2.5f", NumberUtils.restrictToRange(0.0, 100.0, coOccurrenceDrawer.getMinThreshold())));
minThresholdField.setFont(font);
minThresholdField.setToolTipText("Minimum % of reads that class must have to be considered present in a sample");
add(minThresholdField);
addSeparator();
add(getSmallLabel("Min samples (%)"));
minPrevalenceField.setMaximumSize(new Dimension(33, 15));
minPrevalenceField.setText("" + NumberUtils.restrictToRange(0, 100, coOccurrenceDrawer.getMinPrevalence()));
minPrevalenceField.setFont(font);
minPrevalenceField.setToolTipText("Minimum % of samples for which class must be considered present");
minPrevalenceSlider.setToolTipText(minPrevalenceField.getToolTipText());
minPrevalenceSlider.setValue(NumberUtils.restrictToRange(0, 100, coOccurrenceDrawer.getMinPrevalence()));
minPrevalenceSlider.addChangeListener(e -> {
int newValue = ((JSlider) e.getSource()).getValue();
minPrevalenceField.setText("" + newValue);
});
minPrevalenceField.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (NumberUtils.isFloat(minPrevalenceField.getText())) {
int value = NumberUtils.restrictToRange(0, 100, (int) Float.parseFloat(minPrevalenceField.getText()));
minPrevalenceSlider.setValue(value);
}
}
});
add(minPrevalenceSlider);
add(minPrevalenceField);
addSeparator();
add(getSmallLabel("Max samples (%)"));
maxPrevalenceField.setMaximumSize(new Dimension(33, 15));
maxPrevalenceField.setText("" + NumberUtils.restrictToRange(0, 100, coOccurrenceDrawer.getMaxPrevalence()));
maxPrevalenceField.setFont(font);
maxPrevalenceField.setToolTipText("Maximum % of samples for which class must be considered present");
maxPrevalenceSlider.setToolTipText(maxPrevalenceField.getToolTipText());
maxPrevalenceSlider.setValue(NumberUtils.restrictToRange(0, 100, coOccurrenceDrawer.getMaxPrevalence()));
maxPrevalenceSlider.addChangeListener(e -> {
int newValue = ((JSlider) e.getSource()).getValue();
maxPrevalenceField.setText("" + newValue);
});
maxPrevalenceField.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (NumberUtils.isFloat(maxPrevalenceField.getText())) {
int value = NumberUtils.restrictToRange(0, 100, (int) Float.parseFloat(maxPrevalenceField.getText()));
maxPrevalenceSlider.setValue(value);
}
}
});
add(maxPrevalenceSlider);
add(maxPrevalenceField);
addSeparator();
add(getSmallLabel("Edge threshold (%)"));
minProbabilityField.setMaximumSize(new Dimension(33, 15));
minProbabilityField.setText("" + NumberUtils.restrictToRange(0, 100, coOccurrenceDrawer.getMinProbability()));
minProbabilityField.setFont(font);
minProbabilityField.setToolTipText("Minimum % co-occurrence (or anti-occurrence) score required for two classes to be joined by an edge");
minProbabilitySlider.setToolTipText(minProbabilityField.getToolTipText());
minProbabilitySlider.setValue(NumberUtils.restrictToRange(0, 100, coOccurrenceDrawer.getMinProbability()));
minProbabilitySlider.addChangeListener(e -> {
int newValue = ((JSlider) e.getSource()).getValue();
minProbabilityField.setText("" + newValue);
});
minProbabilityField.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (NumberUtils.isFloat(minProbabilityField.getText())) {
int value = NumberUtils.restrictToRange(0, 100, (int) Float.parseFloat(minProbabilityField.getText()));
minProbabilitySlider.setValue(value);
}
}
});
add(minProbabilitySlider);
add(minProbabilityField);
addSeparator();
methodCBox.setEditable(false);
methodCBox.setFont(font);
for (CoOccurrenceDrawer.Method method : CoOccurrenceDrawer.Method.values())
methodCBox.addItem(method);
methodCBox.setSelectedItem(coOccurrenceDrawer.getMethod());
add(methodCBox);
methodCBox.setToolTipText("Jaccard: # samples containing both classes / samples containing at least one of the two\n" +
"Kendall's tau: (# concordant pairs - # discordant pairs) / (# concordant pairs + # discordant pairs)\n" +
"Pearson's r: sample Pearson correlation coefficient");
showCooccurring.setText("Co");
showCooccurring.setFont(font);
showCooccurring.setToolTipText("Show co-occurrence edges");
showCooccurring.setSelected(coOccurrenceDrawer.isShowCoOccurring());
showCooccurring.addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
coOccurrenceDrawer.setShowCoOccurring(showCooccurring.isSelected());
if (!showCooccurring.isSelected() && !showAntiOccurring.isSelected()) {
showAntiOccurring.setSelected(true);
coOccurrenceDrawer.setShowAntiOccurring(true);
}
// applyButton.getAction().actionPerformed(null);
}
});
add(showCooccurring);
showAntiOccurring.setText("Anti");
showAntiOccurring.setFont(font);
showAntiOccurring.setToolTipText("Show anti-occurrence edges");
showAntiOccurring.setSelected(coOccurrenceDrawer.isShowAntiOccurring());
showAntiOccurring.addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
coOccurrenceDrawer.setShowAntiOccurring(showAntiOccurring.isSelected());
if (!showCooccurring.isSelected() && !showAntiOccurring.isSelected()) {
showCooccurring.setSelected(true);
coOccurrenceDrawer.setShowCoOccurring(true);
}
// applyButton.getAction().actionPerformed(null);
}
});
add(showAntiOccurring);
addSeparator();
applyButton = new JButton(new AbstractAction("Apply") {
public void actionPerformed(ActionEvent actionEvent) {
try {
//chartViewer.getClassesList().enableLabels(chartViewer.getClassesList().getAllLabels());
coOccurrenceDrawer.setMinThreshold(Float.parseFloat(minThresholdField.getText()));
coOccurrenceDrawer.setMinProbability(Integer.parseInt(minProbabilityField.getText()));
coOccurrenceDrawer.setMinPrevalence(minPrevalenceSlider.getValue());
// coOccurrenceDrawer.setMinPrevalence(Float.parseFloat(minPrevalenceField.getText()));
coOccurrenceDrawer.setMaxPrevalence(Integer.parseInt(maxPrevalenceField.getText()));
if (methodCBox.getSelectedItem() != null)
coOccurrenceDrawer.setMethod((CoOccurrenceDrawer.Method) methodCBox.getSelectedItem());
chartViewer.getDir().execute("show what=all target=classes;", chartViewer.getCommandManager());
} catch (Exception ex) {
NotificationsInSwing.showInternalError(chartViewer.getFrame(), "CoOccurrence drawer: " + ex.getMessage());
}
}
});
applyButton.setFont(font);
add(applyButton);
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
minThresholdField.setEnabled(enabled);
minPrevalenceField.setEnabled(enabled);
minPrevalenceSlider.setEnabled(enabled);
maxPrevalenceField.setEnabled(enabled);
maxPrevalenceSlider.setEnabled(enabled);
minProbabilityField.setEnabled(enabled);
minProbabilitySlider.setEnabled(enabled);
methodCBox.setEnabled(enabled);
showCooccurring.setEnabled(enabled);
showAntiOccurring.setEnabled(enabled);
applyButton.setEnabled(enabled);
}
private static JLabel getSmallLabel(String text) {
JLabel label = new JLabel(text);
label.setFont(font);
return label;
}
}
| 11,109 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ChartDrawerBase.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/ChartDrawerBase.java | /*
* ChartDrawerBase.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.Geometry;
import jloda.swing.util.ILabelGetter;
import jloda.swing.util.ProgramProperties;
import jloda.swing.window.IPopupMenuModifier;
import jloda.util.Pair;
import megan.chart.ChartColorManager;
import megan.chart.cluster.ClusteringTree;
import megan.chart.data.IData;
import megan.chart.gui.ChartSelection;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.Label2LabelMapper;
import megan.chart.gui.SelectionGraphics;
import megan.util.ScalingType;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.Writer;
import java.util.*;
import java.util.concurrent.ExecutorService;
/**
* base class for chart drawers
* Daniel Huson, 5.2012
*/
public class ChartDrawerBase extends JPanel {
double classLabelAngle = Math.PI / 4;
final Map<String, Pair<Font, Color>> fonts = new HashMap<>();
int leftMargin = 80;
int rightMargin = 75;
int bottomMargin = 200;
int topMargin = 20;
IData chartData;
Label2LabelMapper class2HigherClassMapper;
ILabelGetter seriesLabelGetter;
boolean transpose = false;
boolean showValues = false;
boolean showXAxis = true;
private boolean showYAxis = true;
String chartTitle = "Chart";
ScalingType scalingType = ScalingType.LINEAR;
private final EnumSet<ScalingType> supportedScalingTypes = EnumSet.of(ScalingType.LINEAR, ScalingType.LOG,
ScalingType.PERCENT, ScalingType.SQRT);
final Stroke NORMAL_STROKE;
final Stroke HEAVY_STROKE;
private Rectangle2D scrollBackReferenceRect = null; // reference rectangle
private Point2D scrollBackWindowPoint = null;
private Point2D scrollBackReferencePoint = null;
// used when drawing values:
final LinkedList<DrawableValue> valuesList = new LinkedList<>();
ChartViewer viewer;
ExecutorService executorService;
boolean transposedHeightsAdditive = false;
public ChartDrawerBase() {
NORMAL_STROKE = new BasicStroke((float)ProgramProperties.get("ChartLineWidth",1.0));
HEAVY_STROKE = new BasicStroke(2*(float)ProgramProperties.get("ChartLineWidth",1.0));
}
public void setViewer(ChartViewer viewer) {
ChartDrawerBase.this.viewer = viewer;
ChartDrawerBase.this.scalingType = getScalingTypePreference();
ChartDrawerBase.this.showXAxis = getShowXAxisPreference();
ChartDrawerBase.this.showYAxis = getShowYAxisPreference();
}
public void setChartData(IData chartData) {
ChartDrawerBase.this.chartData = chartData;
}
public void setClass2HigherClassMapper(Label2LabelMapper class2HigherClassMapper) {
ChartDrawerBase.this.class2HigherClassMapper = class2HigherClassMapper;
}
public void setSeriesLabelGetter(ILabelGetter seriesLabelGetter) {
ChartDrawerBase.this.seriesLabelGetter = seriesLabelGetter;
}
/**
* draw a string at the given anchor point at the given angle (in radiant)
*
*/
public static void drawString(Graphics2D gc, String label, double x, double y, double labelAngle) {
labelAngle = Geometry.moduloTwoPI(labelAngle);
Point2D apt = new Point2D.Float((float) x, (float) y);
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
// save current transform:
final AffineTransform saveTransform = gc.getTransform();
// rotate label to desired angle
if (labelAngle >= 0.5 * Math.PI && labelAngle <= 1.5 * Math.PI) {
apt = Geometry.translateByAngle(apt, labelAngle, labelSize.getWidth());
gc.rotate(Geometry.moduloTwoPI(labelAngle - Math.PI), apt.getX(), apt.getY());
} else {
gc.rotate(labelAngle, apt.getX(), apt.getY());
}
// double dy= 0.5 * labelSize.height;
double dy = 0;
// fixes bug in Java7:
// see: http://stackoverflow.com/questions/14569475/java-rotated-text-has-reversed-characters-sequence
FontRenderContext frc = new FontRenderContext(gc.getTransform(), true, true);
gc.drawGlyphVector(gc.getFont().createGlyphVector(frc, label), (int) (apt.getX()), (int) (apt.getY() + dy));
gc.setColor(Color.BLACK);
gc.setTransform(saveTransform);
}
/**
* draw string centered
*
* @param addHeight if true, y is used as bottom coordinate, not top
*/
public static void drawStringCentered(Graphics gc, String label, double x, double y, boolean addHeight) {
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
gc.drawString(label, (int) Math.round(x - labelSize.getWidth() / 2), (int) Math.round(addHeight ? y + labelSize.getHeight() : y));
}
/**
* draw a rectangle at the given anchor point at the given angle (in radiant)
*
*/
public static void drawRect(Graphics2D gc, double x, double y, double width, double height, double labelAngle) {
Dimension theSize = new Dimension((int) Math.round(width), (int) Math.round(height));
Point2D apt = new Point2D.Float((float) x, (float) y);
// save current transform:
AffineTransform saveTransform = gc.getTransform();
// rotate label to desired angle
if (labelAngle >= 0.5 * Math.PI && labelAngle <= 1.5 * Math.PI) {
apt = Geometry.translateByAngle(apt, labelAngle, theSize.getWidth());
gc.rotate(Geometry.moduloTwoPI(labelAngle - Math.PI), apt.getX(), apt.getY());
} else {
gc.rotate(labelAngle, apt.getX(), apt.getY());
}
gc.drawRect((int) Math.round(apt.getX()), (int) Math.round(apt.getY()) - theSize.height, theSize.width, theSize.height);
gc.setTransform(saveTransform);
}
/**
* draw a rectangle at the given anchor point at the given angle (in radiant)
*
*/
public static void fillAndDrawRect(Graphics2D gc, double x, double y, double width, double height, double labelAngle, Color fillColor, Color drawColor) {
Dimension theSize = new Dimension((int) Math.round(width), (int) Math.round(height));
Point2D apt = new Point2D.Float((float) x, (float) y);
// save current transform:
AffineTransform saveTransform = gc.getTransform();
// rotate label to desired angle
if (labelAngle >= 0.5 * Math.PI && labelAngle <= 1.5 * Math.PI) {
apt = Geometry.translateByAngle(apt, labelAngle, theSize.getWidth());
gc.rotate(Geometry.moduloTwoPI(labelAngle - Math.PI), apt.getX(), apt.getY());
} else {
gc.rotate(labelAngle, apt.getX(), apt.getY());
}
gc.setColor(fillColor);
gc.fillRect((int) Math.round(apt.getX()), (int) Math.round(apt.getY()) - theSize.height, theSize.width, theSize.height);
gc.setColor(drawColor);
gc.drawRect((int) Math.round(apt.getX()), (int) Math.round(apt.getY()) - theSize.height, theSize.width, theSize.height);
gc.setTransform(saveTransform);
}
public double getClassLabelAngle() {
return classLabelAngle;
}
public void setClassLabelAngle(double classLabelAngle) {
ChartDrawerBase.this.classLabelAngle = Geometry.moduloTwoPI(classLabelAngle);
}
/**
* Draw an arrow head.
*
* @param gc Graphics
* @param vp Point
* @param wp Point
*/
public void drawArrowHead(Graphics gc, Point vp, Point wp) {
final int arrowLength = 5;
final double arrowAngle = 2.2;
double alpha = Geometry.computeAngle(new Point(wp.x - vp.x, wp.y - vp.y));
Point a = new Point(arrowLength, 0);
a = Geometry.rotate(a, alpha + arrowAngle);
a.translate(wp.x, wp.y);
Point b = new Point(arrowLength, 0);
b = Geometry.rotate(b, alpha - arrowAngle);
b.translate(wp.x, wp.y);
gc.drawLine(a.x, a.y, wp.x, wp.y);
gc.drawLine(wp.x, wp.y, b.x, b.y);
}
public boolean canTranspose() {
return true;
}
public boolean isTranspose() {
return transpose;
}
public void setTranspose(boolean transpose) {
ChartDrawerBase.this.transpose = transpose;
}
public ScalingType getScalingType() {
return scalingType;
}
public void setScalingType(ScalingType scalingType) {
ChartDrawerBase.this.scalingType = scalingType;
}
public boolean isSupportedScalingType(ScalingType scalingType) {
return supportedScalingTypes.contains(scalingType);
}
public void setSupportedScalingTypes(ScalingType... scalingType) {
supportedScalingTypes.clear();
supportedScalingTypes.addAll(Arrays.asList(scalingType));
}
public EnumSet<ScalingType> getSupportedScalingTypes() {
return supportedScalingTypes;
}
public boolean canShowLegend() {
return true;
}
public boolean canShowValues() {
return false;
}
public boolean isShowValues() {
return showValues;
}
public void setShowValues(boolean showValues) {
ChartDrawerBase.this.showValues = showValues;
}
public boolean canColorByRank() {
return true;
}
public String getChartTitle() {
return chartTitle;
}
public void setChartTitle(String chartTitle) {
ChartDrawerBase.this.chartTitle = chartTitle;
}
public boolean canShowYAxis() {
return true;
}
public boolean isShowYAxis() {
return showYAxis;
}
public void setShowYAxis(boolean showYAxis) {
ChartDrawerBase.this.showYAxis = showYAxis;
}
public boolean canShowXAxis() {
return true;
}
public boolean isShowXAxis() {
return showXAxis;
}
public void setShowXAxis(boolean showXAxis) {
ChartDrawerBase.this.showXAxis = showXAxis;
}
/**
* compute the maximum value on a log scale
*
* @return max value on a log scale
*/
protected double computeMaxYAxisValueLogScale(double maxValue) {
double v = 0;
int mantisse = 0;
int exponent = 0;
while (v < maxValue) {
if (mantisse < 9)
mantisse++;
else {
mantisse = 1;
exponent++;
}
v = mantisse * Math.pow(10, exponent);
}
return Math.log10(v);
}
/**
* override if necessary
*/
public void updateView() {
}
public ChartColorManager getChartColors() {
return viewer.getChartColorManager();
}
public IData getChartData() {
return chartData;
}
public void setExecutorService(ExecutorService executorService) {
ChartDrawerBase.this.executorService = executorService;
}
public void drawChart(Graphics2D gc) {
}
public void drawChartTransposed(Graphics2D gc) {
}
public void close() {
}
public void setFont(String target, Font font, Color color) {
fonts.put(target, new Pair<>(font, color));
}
public Font getFont(String target) {
Pair<Font, Color> pair = fonts.get(target);
if (pair == null || pair.getFirst() == null)
return getFont();
else
return pair.getFirst();
}
public Color getFontColor(String target, Color defaultColor) {
Pair<Font, Color> pair = fonts.get(target);
if (pair == null || pair.getSecond() == null)
return defaultColor;
else
return pair.getSecond();
}
/**
* converts a point from window coordinates to reference coordinates
*
* @return reference coordinates
*/
public Point2D convertWindowToReference(Point2D apt) {
if (scrollBackReferenceRect == null)
return null;
else
return new Point2D.Double((apt.getX() - scrollBackReferenceRect.getX()) / scrollBackReferenceRect.getWidth(),
(apt.getY() - scrollBackReferenceRect.getY()) / scrollBackReferenceRect.getHeight());
}
/**
* converts a point from reference coordinates to window coordinates
*
* @return window coordinates
*/
public Point2D convertReferenceToWindow(Point2D refPoint) {
if (scrollBackReferenceRect == null)
return null;
else
return new Point2D.Double(Math.round(refPoint.getX() * scrollBackReferenceRect.getWidth() + scrollBackReferenceRect.getX()),
Math.round(refPoint.getY() * scrollBackReferenceRect.getHeight() + scrollBackReferenceRect.getY()));
}
public Rectangle2D getScrollBackReferenceRect() {
return scrollBackReferenceRect;
}
public void setScrollBackReferenceRect(Rectangle2D scrollBackReferenceRect) {
ChartDrawerBase.this.scrollBackReferenceRect = scrollBackReferenceRect;
}
public void setScrollBackWindowPoint(Point2D scrollBackWindowPoint) {
ChartDrawerBase.this.scrollBackWindowPoint = scrollBackWindowPoint;
}
public void setScrollBackReferencePoint(Point2D scrollBackReferencePoint) {
ChartDrawerBase.this.scrollBackReferencePoint = scrollBackReferencePoint;
}
public Point2D getScrollBackWindowPoint() {
return scrollBackWindowPoint;
}
public Point2D getScrollBackReferencePoint() {
return scrollBackReferencePoint;
}
public void computeScrollBackReferenceRect() {
scrollBackReferenceRect = new Rectangle2D.Double(0, 0, getWidth(), getHeight());
}
public boolean isXYLocked() {
return false;
}
public boolean isShowInternalLabels() {
return false;
}
public void setShowInternalLabels(boolean showInternalLabels) {
}
public boolean canShowInternalLabels() {
return false;
}
public boolean canCluster(ClusteringTree.TYPE type) {
return false;
}
/**
* select series and classes that contain given location
*
* @return true if something selected
*/
public boolean selectOnMouseDown(MouseEvent mouseEvent, ChartSelection chartSelection) {
return selectOnRubberBand(new Rectangle(mouseEvent.getX() - 1, mouseEvent.getY() - 1, 2, 2), mouseEvent, chartSelection);
}
/**
* select all classes and series that intersection given rectangle
*
* @return true if something selected
*/
public boolean selectOnRubberBand(Rectangle rectangle, MouseEvent mouseEvent, ChartSelection chartSelection) {
if (mouseEvent.isControlDown())
return false;
if (!mouseEvent.isShiftDown())
chartSelection.clearSelectionAttributes(); // todo: don't know why only need to do this for attributes
final SelectionGraphics<String[]> selectionGraphics = new SelectionGraphics<>(getGraphics());
selectionGraphics.setSelectionRectangle(rectangle);
selectionGraphics.setShiftDown(mouseEvent.isShiftDown());
selectionGraphics.setMouseClicks(mouseEvent.getClickCount());
if (this instanceof BubbleChartDrawer) {
((BubbleChartDrawer) ChartDrawerBase.this).drawYAxis(selectionGraphics, null);
}
if (this instanceof HeatMapDrawer) {
((HeatMapDrawer) ChartDrawerBase.this).drawYAxis(selectionGraphics, null);
}
if (transpose)
drawChartTransposed(selectionGraphics);
else
drawChart(selectionGraphics);
final Set<String> seriesToSelect = new HashSet<>();
final Set<String> classesToSelect = new HashSet<>();
final Set<String> attributesToSelect = new HashSet<>();
int count = 0;
int size = selectionGraphics.getSelectedItems().size();
for (String[] seriesClassAttribute : selectionGraphics.getSelectedItems()) {
if (selectionGraphics.getUseWhich() == SelectionGraphics.Which.Last && count++ < size - 1)
continue;
if (seriesClassAttribute[0] != null) {
seriesToSelect.add(seriesClassAttribute[0]);
}
if (seriesClassAttribute[1] != null) {
classesToSelect.add(seriesClassAttribute[1]);
}
if (seriesClassAttribute.length >= 3 && seriesClassAttribute[2] != null) {
attributesToSelect.add(seriesClassAttribute[2]);
}
if (selectionGraphics.getUseWhich() == SelectionGraphics.Which.First)
break;
}
if (seriesToSelect.size() > 0) {
chartSelection.toggleSelectedSeries(seriesToSelect);
}
if (classesToSelect.size() > 0)
chartSelection.toggleSelectedClasses(classesToSelect);
if (attributesToSelect.size() > 0)
chartSelection.toggleSelectedAttributes(attributesToSelect);
return seriesToSelect.size() > 0 || classesToSelect.size() > 0 || attributesToSelect.size() > 0;
}
/**
* get item below mouse
*
* @return label for item below mouse
*/
public String[] getItemBelowMouse(MouseEvent mouseEvent, ChartSelection chartSelection) {
final SelectionGraphics<String[]> selectionGraphics = new SelectionGraphics<>(getGraphics());
selectionGraphics.setMouseLocation(mouseEvent.getPoint());
selectionGraphics.setShiftDown(mouseEvent.isShiftDown());
selectionGraphics.setMouseClicks(mouseEvent.getClickCount());
if (this instanceof BubbleChartDrawer) {
((BubbleChartDrawer) ChartDrawerBase.this).drawYAxis(selectionGraphics, null);
}
if (this instanceof HeatMapDrawer) {
((HeatMapDrawer) ChartDrawerBase.this).drawYAxis(selectionGraphics, null);
}
if (transpose)
drawChartTransposed(selectionGraphics);
else
drawChart(selectionGraphics);
int count = 0;
int size = selectionGraphics.getSelectedItems().size();
for (String[] seriesClassAttribute : selectionGraphics.getSelectedItems()) {
if (selectionGraphics.getUseWhich() == SelectionGraphics.Which.Last && count++ < size - 1)
continue;
return seriesClassAttribute;
}
return null;
}
public Label2LabelMapper getClass2HigherClassMapper() {
return class2HigherClassMapper;
}
/**
* force update
*/
public void forceUpdate() {
}
public ILabelGetter getSeriesLabelGetter() {
return seriesLabelGetter;
}
public JToolBar getBottomToolBar() {
return null;
}
public ScalingType getScalingTypePreference() {
return ScalingType.LINEAR;
}
public boolean getShowXAxisPreference() {
return true;
}
public boolean getShowYAxisPreference() {
return true;
}
public void setMargins(int leftMargin, int topMargin, int rightMargin, int bottomMargin) {
ChartDrawerBase.this.leftMargin = leftMargin;
ChartDrawerBase.this.topMargin = topMargin;
ChartDrawerBase.this.rightMargin = rightMargin;
ChartDrawerBase.this.bottomMargin = bottomMargin;
}
public ChartViewer getViewer() {
return viewer;
}
public boolean usesHeatMapColors() {
return false;
}
public IPopupMenuModifier getPopupMenuModifier() {
return null;
}
public JPanel getJPanel() {
return this;
}
public void writeData(Writer w) throws IOException {
chartData.write(w);
}
public boolean canAttributes() {
return false;
}
}
| 20,638 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
RadialSpaceFillingTreeDrawer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/RadialSpaceFillingTreeDrawer.java | /*
* RadialSpaceFillingTreeDrawer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.graph.Edge;
import jloda.graph.Node;
import jloda.graph.NodeData;
import jloda.phylo.PhyloTree;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.Geometry;
import jloda.swing.util.ProgramProperties;
import megan.chart.IChartDrawer;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.RedGradient;
import megan.chart.gui.SelectionGraphics;
import megan.util.ScalingType;
import java.awt.*;
import java.awt.geom.*;
import java.util.LinkedList;
/**
* draws a radial space filling chart
* Daniel Huson, 3.2013
*/
public class RadialSpaceFillingTreeDrawer extends BarChartDrawer implements IChartDrawer {
private static final String NAME = "RadialTreeChart";
private enum DrawWhat {RegionsAndBars, Names, Selection, Values}
private boolean colorByClasses = true;
private boolean colorBySeries = false;
private boolean showInternalLabels = true;
private int angleOffset = 0;
private final LinkedList<Area> areas = new LinkedList<>();
/**
* constructor
*/
public RadialSpaceFillingTreeDrawer() {
}
/**
* draw a Radial Chart
*
*/
public void drawChart(Graphics2D gc) {
colorByClasses = true;
colorBySeries = false;
doDraw(gc);
}
/**
* draw a transposed Radial Chart
*
*/
public void drawChartTransposed(Graphics2D gc) {
colorByClasses = false;
colorBySeries = true;
doDraw(gc);
}
/**
* draw both chart and transposed chart
*
*/
private void doDraw(Graphics2D gc) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
if (sgc != null)
sgc.setUseWhich(SelectionGraphics.Which.Last);
int x0 = 2;
int x1 = getWidth() - 2;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
if (x0 >= x1)
return;
Rectangle deviceBBox = new Rectangle(x0, y1, x1 - x0, y0 - y1);
if (getChartData().getSeriesNames().size() == 0)
return; // nothing to draw.
PhyloTree tree = getChartData().getTree();
if (tree == null || tree.getRoot() == null)
return;
double centerRadius = 0.5; // proportional size of center disk
double maxLevel = determineMaxLevel(getChartData().getTree()) + centerRadius;
double radiusFactor = Math.min((deviceBBox.getHeight() - 100) / 2, (deviceBBox.getWidth() - 100) / 2) / (maxLevel + 2);
radiusFactor *= ProgramProperties.get("RadialChartScalingFactor", 1f);
Point2D center = new Point2D.Double(deviceBBox.getCenterX(), deviceBBox.getCenterY());
double maxValue = getMaxValue();
double topY;
if (scalingType == ScalingType.PERCENT)
topY = 101;
else if (scalingType == ScalingType.LOG) {
topY = computeMaxYAxisValueLogScale(maxValue);
maxValue = Math.log(maxValue);
} else if (scalingType == ScalingType.SQRT) {
topY = Math.sqrt(maxValue);
maxValue = Math.sqrt(maxValue);
} else
topY = getMaxValue();
double barFactor = radiusFactor / topY; // multiple value by this to get height of bar
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
gc.setColor(getFontColor(ChartViewer.FontKeys.ValuesFont.toString(), Color.DARK_GRAY));
// draw regions and bars, selected bars are highlighted in red
areas.clear();
drawRec(DrawWhat.RegionsAndBars, gc, tree, center, radiusFactor, tree.getRoot(), centerRadius, maxLevel, 0.0, 360.0, barFactor, maxValue);
// draw center disk
Ellipse2D disk = new Ellipse2D.Double(center.getX() - centerRadius * radiusFactor, center.getY() - centerRadius * radiusFactor,
2 * centerRadius * radiusFactor, 2 * centerRadius * radiusFactor);
gc.setColor(Color.WHITE);
gc.fill(disk);
gc.setColor(Color.LIGHT_GRAY);
gc.draw(disk);
if (isShowValues()) {
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
gc.setColor(getFontColor(ChartViewer.FontKeys.ValuesFont.toString(), Color.DARK_GRAY));
areas.clear();
drawRec(DrawWhat.Values, gc, tree, center, radiusFactor, tree.getRoot(), centerRadius, maxLevel, 0.0, 360.0, barFactor, maxValue);
}
{// show class labels
gc.setFont(getFont(ChartViewer.FontKeys.LegendFont.toString()));
gc.setColor(getFontColor(ChartViewer.FontKeys.LegendFont.toString(), Color.BLACK));
areas.clear();
drawRec(DrawWhat.Names, gc, tree, center, radiusFactor, tree.getRoot(), centerRadius, maxLevel, 0.0, 360.0, barFactor, maxValue);
}
if (getChartData().getChartSelection().getSelectedClasses().size() > 0) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
areas.clear();
drawRec(DrawWhat.Selection, gc, tree, center, radiusFactor, tree.getRoot(), centerRadius, maxLevel, 0.0, 360.0, barFactor, maxValue);
}
}
/**
* recursively draw the graph
*
*/
private void drawRec(DrawWhat what, Graphics2D gc, PhyloTree tree, Point2D center, double radiusFactor, Node v, double level, double maxLevel, double angleV, double extentV, double barFactor, double maxValue) {
if (v.getOutDegree() > 0) {
// recursively visit all nodes below:
float countV = ((NodeData) v.getData()).getCountSummarized() - ((NodeData) v.getData()).getCountAssigned();
if (countV > 0) {
double factor = extentV / countV;
double used = 0;
for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) {
Node w = e.getTarget();
float countW = ((NodeData) w.getData()).getCountSummarized();
double angleW = angleV + used;
double extentW = factor * countW;
drawRec(what, gc, tree, center, radiusFactor, w, level + 1, maxLevel, angleW, extentW, barFactor, maxValue);
used += extentW;
}
}
}
if (v.getInDegree() > 0) // not root
{
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
String className = tree.getLabel(v);
if (getChartData().getClassNames().contains(className)) {
boolean classIsSelected = (getChartData().getChartSelection().isSelected(null, className));
// draw class regions:
if (what == DrawWhat.RegionsAndBars) {
double radius = (v.getOutDegree() > 0 ? level : maxLevel) * radiusFactor;
Rectangle2D rect = new Rectangle2D.Double(center.getX() - radius, center.getY() - radius, 2 * radius, 2 * radius);
Arc2D arc = new Arc2D.Double(rect, modulo360(angleV + angleOffset), extentV, Arc2D.PIE);
if (isTranspose() && chartData.getNumberOfSeries() == 1) { // if tranposed and only one dataset, draw colored by count
String series = chartData.getSeriesNames().iterator().next();
Color color;
if (scalingType == ScalingType.PERCENT) {
double total = getChartData().getTotalForSeriesIncludingDisabledAttributes(series);
double value;
if (total == 0)
value = 0;
else
value = 100 * getChartData().getValueAsDouble(series, className) / total;
color = RedGradient.getColor((int) value, (int) maxValue);
} else if (scalingType == ScalingType.LOG) {
double value = getChartData().getValueAsDouble(series, className);
double inverseMaxValueLog = 1 / Math.log(maxValue);
color = RedGradient.getColorLogScale((int) value, inverseMaxValueLog);
} else if (scalingType == ScalingType.SQRT) {
double value = Math.sqrt(getChartData().getValueAsDouble(series, className));
color = RedGradient.getColor((int) value, (int) maxValue);
} else {
double value = getChartData().getValueAsDouble(series, className);
color = RedGradient.getColor((int) value, (int) maxValue);
}
gc.setColor(color);
} else {
if (colorByClasses)
gc.setColor(getChartColors().getClassColor(class2HigherClassMapper.get(className), 255));
else
gc.setColor(Color.WHITE);
}
if (sgc != null)
sgc.setCurrentItem(new String[]{null, className});
gc.fill(arc);
gc.setColor(Color.LIGHT_GRAY);
gc.draw(arc);
if (sgc != null)
sgc.clearCurrentItem();
}
// draw series bar charts, the selected ones get colored red here
if (what == DrawWhat.RegionsAndBars) {
int numberOfBars = getChartData().getNumberOfSeries();
if (numberOfBars > 1) {
double part = extentV / numberOfBars;
double used = 0;
for (String series : chartData.getSeriesNames()) {
double value;
if (scalingType == ScalingType.PERCENT) {
double total = getChartData().getTotalForSeriesIncludingDisabledAttributes(series);
if (total == 0)
value = 0;
else
value = 100 * getChartData().getValueAsDouble(series, className) / total;
} else if (scalingType == ScalingType.LOG) {
value = getChartData().getValueAsDouble(series, className);
if (value > 0)
value = Math.log10(value);
} else if (scalingType == ScalingType.SQRT) {
value = getChartData().getValueAsDouble(series, className);
if (value > 0)
value = Math.sqrt(value);
} else
value = getChartData().getValueAsDouble(series, className);
double radius = (level - 1) * radiusFactor + value * barFactor;
final Rectangle2D rect = new Rectangle2D.Double(center.getX() - radius, center.getY() - radius, 2 * radius, 2 * radius);
final Arc2D arc = new Arc2D.Double(rect, modulo360(angleV + used + angleOffset), part, Arc2D.PIE);
used += part;
if (colorBySeries) {
gc.setColor(getChartColors().getSampleColor(series));
} else {
final Color color = getChartColors().getClassColor(class2HigherClassMapper.get(className));
gc.setColor(color.brighter());
}
if (sgc != null)
sgc.setCurrentItem(new String[]{series, className});
gc.fill(arc);
gc.setColor(Color.GRAY);
gc.draw(arc);
if (sgc != null)
sgc.clearCurrentItem();
if (getChartData().getChartSelection().isSelected(series, null)) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.draw(arc);
double textAngle = Geometry.deg2rad(360 - (arc.getAngleStart() + arc.getAngleExtent() / 2));
Point2D apt = Geometry.translateByAngle(center, textAngle, radius + 2);
String label = "" + getChartData().getValueAsDouble(series, className);
gc.setColor(ProgramProperties.SELECTION_COLOR_ADDITIONAL_TEXT);
drawString(gc, label, apt.getX(), apt.getY(), textAngle);
radius = (level - 1) * radiusFactor + 2;
rect.setRect(center.getX() - radius, center.getY() - radius, 2 * radius, 2 * radius);
arc.setFrame(rect);
gc.setColor(ProgramProperties.SELECTION_COLOR);
arc.setArcType(Arc2D.OPEN);
gc.draw(arc);
gc.setColor(Color.BLACK);
gc.setStroke(NORMAL_STROKE);
}
}
}
}
if (what == DrawWhat.RegionsAndBars && classIsSelected) {
// draw selected class regions:
double radius = (v.getOutDegree() > 0 ? level : maxLevel) * radiusFactor;
Rectangle2D rect = new Rectangle2D.Double(center.getX() - radius, center.getY() - radius, 2 * radius, 2 * radius);
Arc2D arc = new Arc2D.Double(rect, modulo360(angleV + angleOffset), extentV, Arc2D.PIE);
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.draw(arc);
radius = (level - 1) * radiusFactor + 2;
rect.setRect(center.getX() - radius, center.getY() - radius, 2 * radius, 2 * radius);
arc.setFrame(rect);
arc.setArcType(Arc2D.OPEN);
gc.draw(arc);
gc.setColor(Color.BLACK);
gc.setStroke(NORMAL_STROKE);
}
if (what == DrawWhat.Names || what == DrawWhat.Selection) {
if (v.getOutDegree() > 0) {
if (showInternalLabels) {
Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize();
double angleInDeg = modulo360(angleV + angleOffset + extentV / 2.0);
double angleInRad = Geometry.deg2rad(270.0 - (angleV + angleOffset + extentV / 2.0));
double top = 2;
for (double shift = 0.3; shift < top; shift += 0.1) {
Point2D apt = Geometry.translateByAngle(center, Geometry.deg2rad(angleInDeg), (level - (1 - shift)) * radiusFactor);
apt.setLocation(apt.getX(), 2 * center.getY() - apt.getY()); // middle or region
apt = Geometry.translateByAngle(apt, angleInRad, -labelSize.width / 2); // move label back so that it will be centered at center of region
angleInRad = Geometry.deg2rad(270.0 - (angleV + angleOffset + extentV / 2.0));
if (shift < top - 0.05) {
Shape shape = getLabelShape(apt, labelSize, angleInRad);
boolean collision = false;
for (Area aArea : areas) {
Area area = new Area(shape);
if (area.getBounds().intersects(aArea.getBounds())) {
area.intersect(aArea);
if (!area.isEmpty()) {
collision = true;
break;
}
}
}
if (collision)
continue; // try next shift
} else {
shift = 0.3; // couldn't find a good place
apt = Geometry.translateByAngle(center, Geometry.deg2rad(angleInDeg), (level - shift) * radiusFactor);
apt.setLocation(apt.getX(), 2 * center.getY() - apt.getY()); // middle or region
apt = Geometry.translateByAngle(apt, angleInRad, -labelSize.width / 2); // move label back so that it will be centered at center of region
angleInRad = Geometry.deg2rad(270.0 - (angleV + angleOffset + extentV / 2.0));
}
areas.add(new Area(getLabelShape(apt, labelSize, angleInRad)));
if ((what == DrawWhat.Names && extentV > 2) || classIsSelected) {
if (sgc != null)
sgc.setCurrentItem(new String[]{null, className});
if (classIsSelected) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, angleInRad, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.DARK_GRAY));
drawString(gc, className, apt.getX(), apt.getY(), angleInRad);
if (classIsSelected)
gc.setColor(Color.BLACK);
if (sgc != null)
sgc.clearCurrentItem();
}
break;
}
}
} else // draw label of leaf node
{
if ((extentV > 2 && what == DrawWhat.Names) || classIsSelected) {
double angleInRad = Geometry.deg2rad(360.0 - (angleV + angleOffset + extentV / 2.0));
Point2D apt = Geometry.translateByAngle(center, angleInRad, (maxLevel - 0.5) * radiusFactor + 5);
Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize();
//apt.setLocation(apt.getX(), 2 * center.getY() - apt.getY());
//gc.drawString(className, (int)apt.getX(),(int)apt.getY());
if (sgc != null)
sgc.setCurrentItem(new String[]{null, className});
if (classIsSelected) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, angleInRad, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.DARK_GRAY));
drawString(gc, className, apt.getX(), apt.getY(), angleInRad);
if (classIsSelected)
gc.setColor(Color.BLACK);
if (sgc != null)
sgc.clearCurrentItem();
}
}
}
if ((what == DrawWhat.Values && !classIsSelected)
|| (what == DrawWhat.Selection && classIsSelected)) {
if (extentV > 2 || classIsSelected) {
Point2D apt = Geometry.translateByAngle(center, Geometry.deg2rad(angleV + angleOffset + extentV / 2), (level - 0.5) * radiusFactor);
apt.setLocation(apt.getX(), 2 * center.getY() - apt.getY());
String label = "" + (int) getChartData().getTotalForClass(className);
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
if (classIsSelected)
gc.setColor(ProgramProperties.SELECTION_COLOR_ADDITIONAL_TEXT);
gc.drawString(label, (int) (apt.getX() - labelSize.width / 2), (int) apt.getY() + labelSize.height + 3);
if (classIsSelected)
gc.setColor(Color.BLACK);
}
}
}
}
}
private static double modulo360(double angle) {
while (angle > 360)
angle -= 360;
while (angle < 0)
angle += 360;
return angle;
}
/**
* gets the max value used in the plot.
*
* @return max value
*/
protected double getMaxValue() {
double maxValue = 0;
PhyloTree tree = getChartData().getTree();
for (Node v = tree.getFirstNode(); v != null; v = tree.getNextNode(v)) {
if (v.getInDegree() > 0) {
String className = tree.getLabel(v);
for (String series : getChartData().getSeriesNames()) {
if (getChartData().getValue(series, className) != null)
maxValue = Math.max(maxValue, getChartData().getValue(series, className).doubleValue());
}
}
}
return maxValue;
}
/**
* determine the max levels of the tree
*
* @return max levels
*/
private int determineMaxLevel(PhyloTree tree) {
return determineMaxLevelRec(0, tree.getRoot());
}
/**
* recursively does the work
*
* @return level
*/
private int determineMaxLevelRec(int level, Node v) {
int newLevel = level;
for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) {
newLevel = Math.max(newLevel, determineMaxLevelRec(level, e.getTarget()) + 1);
}
return newLevel;
}
public boolean isShowXAxis() {
return false;
}
public boolean isShowYAxis() {
return false;
}
public boolean canShowValues() {
return true;
}
public boolean isXYLocked() {
return true;
}
public boolean isShowInternalLabels() {
return showInternalLabels;
}
public void setShowInternalLabels(boolean showInternalLabels) {
this.showInternalLabels = showInternalLabels;
}
public boolean canShowInternalLabels() {
return true;
}
public boolean canShowXAxis() {
return false;
}
public boolean canShowYAxis() {
return false;
}
public int getAngleOffset() {
return angleOffset;
}
public void setAngleOffset(int angleOffset) {
this.angleOffset = (int) Math.round(modulo360(angleOffset));
}
private Shape getLabelShape(Point2D labelPosition, Dimension labelSize, double labelAngle) {
if (labelSize != null) {
Point2D apt = labelPosition;
if (apt != null) {
if (labelAngle == 0) {
return new Rectangle((int) apt.getX(), (int) apt.getY() - labelSize.height + 1, labelSize.width, labelSize.height);
} else {
labelAngle = labelAngle + 0.0001; // to ensure that labels all get same orientation in
AffineTransform localTransform = new AffineTransform();
// rotate label to desired angle
if (labelAngle >= 0.5 * Math.PI && labelAngle <= 1.5 * Math.PI) {
double d = labelSize.getWidth();
apt = Geometry.translateByAngle(apt, labelAngle, d);
localTransform.rotate(Geometry.moduloTwoPI(labelAngle - Math.PI), apt.getX(), apt.getY());
} else
localTransform.rotate(labelAngle, apt.getX(), apt.getY());
double[] pts = new double[]{apt.getX(), apt.getY(),
apt.getX() + labelSize.width, apt.getY(),
apt.getX() + labelSize.width, apt.getY() - labelSize.height,
apt.getX(), apt.getY() - labelSize.height};
localTransform.transform(pts, 0, pts, 0, 4);
return new Polygon(new int[]{(int) pts[0], (int) pts[2], (int) pts[4], (int) pts[6]}, new int[]{(int) pts[1], (int) pts[3],
(int) pts[5], (int) pts[7]}, 4);
}
}
}
return null;
}
@Override
public ScalingType getScalingTypePreference() {
return ScalingType.SQRT;
}
@Override
public boolean getShowXAxisPreference() {
return false;
}
@Override
public boolean getShowYAxisPreference() {
return false;
}
@Override
public String getChartDrawerName() {
return NAME;
}
}
| 26,833 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
BricksChartDrawer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/BricksChartDrawer.java | /*
* BricksChartDrawer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.Geometry;
import jloda.swing.util.ProgramProperties;
import megan.chart.IChartDrawer;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.SelectionGraphics;
import megan.util.ScalingType;
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
/**
* draws a bricks chart
* Daniel Huson, 3.2013
*/
public class BricksChartDrawer extends BubbleChartDrawer implements IChartDrawer {
private static final String NAME = "BricksChart";
/**
* constructor
*/
public BricksChartDrawer() {
}
/**
* draw bricks with colors representing classes
*
*/
public void drawChart(Graphics2D gc) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
if (x0 >= x1)
return;
int numberOfDataSets = getChartData().getNumberOfSeries();
int numberOfClasses = getChartData().getNumberOfClasses();
double xStep = (x1 - x0) / numberOfDataSets;
double yStep = (y0 - y1) / (0.5 + numberOfClasses);
double maxValue = getChartData().getRange().getSecond().doubleValue();
if (scalingType == ScalingType.LOG && maxValue > 0)
maxValue = Math.log(maxValue);
else if (scalingType == ScalingType.SQRT && maxValue > 0)
maxValue = Math.sqrt(maxValue);
else if (scalingType == ScalingType.PERCENT)
maxValue = 100;
int gridWidth = 5;
double drawWidth = (double) maxRadius / (double) gridWidth;
int totalBoxes = gridWidth * gridWidth;
int e = maxValue > 0 ? (int) Math.ceil(Math.log10(maxValue)) : 0;
int x = (int) Math.ceil(maxValue / Math.pow(10, e));
int boxValue = (int) ((x * Math.pow(10, e)) / totalBoxes);
// main drawing loop:
int d = 0;
for (String series : getChartData().getSeriesNames()) {
if (isShowXAxis()) {
double xLabel = x0 + (d + 0.5) * xStep;
Point2D apt = new Point2D.Double(xLabel, getHeight() - bottomMargin + 10);
String label = seriesLabelGetter.getLabel(series);
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
if (getChartData().getChartSelection().isSelected(series, null)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.DARK_GRAY));
if (sgc != null)
sgc.setCurrentItem(new String[]{series, null});
drawString(gc, label, apt.getX(), apt.getY(), classLabelAngle);
if (sgc != null)
sgc.clearCurrentItem();
}
int c = 0;
for (String className : getChartData().getClassNames()) {
double value;
if (scalingType == ScalingType.PERCENT) {
double total = getChartData().getTotalForSeriesIncludingDisabledAttributes(series);
if (total == 0)
value = 0;
else
value = 100 * getChartData().getValueAsDouble(series, className) / total;
} else if (scalingType == ScalingType.LOG) {
value = getChartData().getValueAsDouble(series, className);
if (value > 1)
value = Math.log(value);
} else if (scalingType == ScalingType.SQRT) {
value = getChartData().getValueAsDouble(series, className);
if (value > 0)
value = Math.sqrt(value);
} else
value = getChartData().getValueAsDouble(series, className);
Point bottomLeft = new Point((int) ((x0 + (d + 0.5) * xStep) - maxRadius / 2), (int) ((y0 - (c + 1) * yStep)));
Color color = getChartColors().getClassColor(class2HigherClassMapper.get(className), 150);
gc.setColor(color);
int numberOfBoxes = (value <= 0 ? 0 : (int) Math.ceil(totalBoxes / maxValue * value));
int currentWidth = Math.min(totalBoxes, (int) Math.ceil(Math.sqrt(numberOfBoxes + 1)));
Rectangle2D rect = new Rectangle2D.Double();
{
if (sgc != null)
sgc.setCurrentItem(new String[]{series, className});
int row = 0;
int col = 0;
for (int i = 1; i <= numberOfBoxes; i++) {
rect.setRect(bottomLeft.x + col * drawWidth, bottomLeft.y - row * drawWidth, drawWidth, drawWidth);
if (i == numberOfBoxes) // scale the last box to show how full it is:
{
double coveredValue = (numberOfBoxes - 1) * boxValue;
double diff = value - coveredValue;
double factor = diff / boxValue;
double height = rect.getHeight() * factor;
double y = rect.getY() + (rect.getHeight() - height);
rect.setRect(rect.getX(), y, rect.getWidth(), height);
}
gc.fill(rect);
if ((i % currentWidth) == 0) {
col = 0;
row++;
} else
col++;
}
if (sgc != null)
sgc.clearCurrentItem();
}
gc.setColor(color.darker());
{
int row = 0;
int col = 0;
for (int i = 1; i <= numberOfBoxes; i++) {
rect.setRect(bottomLeft.x + col * drawWidth, bottomLeft.y - row * drawWidth, drawWidth, drawWidth);
gc.draw(rect);
if ((i % currentWidth) == 0) {
col = 0;
row++;
} else
col++;
}
}
boolean isSelected = getChartData().getChartSelection().isSelected(series, className);
if (isSelected) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
int row = 0;
int col = 0;
for (int i = 1; i <= numberOfBoxes; i++) {
rect.setRect(bottomLeft.x + col * drawWidth, bottomLeft.y - row * drawWidth, drawWidth, drawWidth);
gc.draw(rect);
if ((i % currentWidth) == 0) {
col = 0;
row++;
} else
col++;
}
gc.setStroke(NORMAL_STROKE);
}
c++;
if (showValues || isSelected) {
String label = "" + (int) getChartData().getValueAsDouble(series, className);
valuesList.add(new DrawableValue(label, bottomLeft.x + maxRadius + 2, bottomLeft.y - maxRadius / 2, isSelected));
}
}
d++;
}
if (valuesList.size() > 0) {
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
DrawableValue.drawValues(gc, valuesList, false, true);
valuesList.clear();
}
drawScale(gc, drawWidth, boxValue);
}
/**
* draw bricks in which colors are by sample
*
*/
public void drawChartTransposed(Graphics2D gc) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
if (x0 >= x1)
return;
int numberOfClasses = getChartData().getNumberOfClasses();
int numberOfDataSets = getChartData().getNumberOfSeries();
double xStep = (x1 - x0) / numberOfClasses;
double yStep = (y0 - y1) / (0.5 + numberOfDataSets);
double maxValue = getChartData().getRange().getSecond().doubleValue();
if (scalingType == ScalingType.LOG && maxValue > 0)
maxValue = Math.log(maxValue);
else if (scalingType == ScalingType.SQRT && maxValue > 0)
maxValue = Math.sqrt(maxValue);
else if (scalingType == ScalingType.PERCENT)
maxValue = 100;
int gridWidth = 5;
double drawWidth = (double) maxRadius / (double) gridWidth;
int totalBoxes = gridWidth * gridWidth;
int e = maxValue > 0 ? (int) Math.ceil(Math.log10(maxValue)) : 0;
int x = (int) Math.ceil(maxValue / Math.pow(10, e));
int boxValue = (int) ((x * Math.pow(10, e)) / totalBoxes);
// main drawing loop:
int c = 0;
for (String className : getChartData().getClassNames()) {
if (isShowXAxis()) {
double xLabel = x0 + (c + 0.5) * xStep;
Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize();
Point2D apt = new Point2D.Double(xLabel, getHeight() - bottomMargin + 10);
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
if (getChartData().getChartSelection().isSelected(null, className)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.DARK_GRAY));
if (sgc != null)
sgc.setCurrentItem(new String[]{null, className});
drawString(gc, className, apt.getX(), apt.getY(), classLabelAngle);
if (sgc != null)
sgc.clearCurrentItem();
}
int d = 0;
for (String series : getChartData().getSeriesNames()) {
double value;
if (scalingType == ScalingType.PERCENT) {
double total = getChartData().getTotalForClassIncludingDisabledSeries(className);
if (total == 0)
value = 0;
else
value = 100 * getChartData().getValueAsDouble(series, className) / total;
} else if (scalingType == ScalingType.LOG) {
value = getChartData().getValueAsDouble(series, className);
if (value > 1)
value = Math.log(value);
} else if (scalingType == ScalingType.SQRT) {
value = getChartData().getValueAsDouble(series, className);
if (value > 1)
value = Math.sqrt(value);
} else
value = getChartData().getValueAsDouble(series, className);
Point bottomLeft = new Point((int) ((x0 + (c + 0.5) * xStep) - maxRadius / 2), (int) ((y0 - (d + 1) * yStep)));
Color color = getChartColors().getSampleColorWithAlpha(series, 150);
gc.setColor(color);
int numberOfBoxes = (value <= 0 ? 0 : (int) Math.ceil(totalBoxes / maxValue * value));
int currentWidth = Math.min(totalBoxes, (int) Math.ceil(Math.sqrt(numberOfBoxes + 1)));
Rectangle2D rect = new Rectangle2D.Double();
{
if (sgc != null)
sgc.setCurrentItem(new String[]{series, className});
int row = 0;
int col = 0;
for (int i = 1; i <= numberOfBoxes; i++) {
rect.setRect(bottomLeft.x + col * drawWidth, bottomLeft.y - row * drawWidth, drawWidth, drawWidth);
if (i == numberOfBoxes) // scale the last box to show how full it is:
{
double coveredValue = (numberOfBoxes - 1) * boxValue;
double diff = value - coveredValue;
double factor = diff / boxValue;
double height = rect.getHeight() * factor;
double y = rect.getY() + (rect.getHeight() - height);
rect.setRect(rect.getX(), y, rect.getWidth(), height);
}
gc.fill(rect);
if ((i % currentWidth) == 0) {
col = 0;
row++;
} else
col++;
}
if (sgc != null)
sgc.clearCurrentItem();
}
gc.setColor(color.darker());
{
int row = 0;
int col = 0;
for (int i = 1; i <= numberOfBoxes; i++) {
rect.setRect(bottomLeft.x + col * drawWidth, bottomLeft.y - row * drawWidth, drawWidth, drawWidth);
gc.draw(rect);
if ((i % currentWidth) == 0) {
col = 0;
row++;
} else
col++;
}
}
boolean isSelected = getChartData().getChartSelection().isSelected(series, className);
if (isSelected) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
int row = 0;
int col = 0;
for (int i = 1; i <= numberOfBoxes; i++) {
rect.setRect(bottomLeft.x + col * drawWidth, bottomLeft.y - row * drawWidth, drawWidth, drawWidth);
gc.draw(rect);
if ((i % currentWidth) == 0) {
col = 0;
row++;
} else
col++;
}
gc.setStroke(NORMAL_STROKE);
}
d++;
if (showValues || isSelected) {
String label = "" + (int) getChartData().getValueAsDouble(series, className);
valuesList.add(new DrawableValue(label, bottomLeft.x + maxRadius + 2, bottomLeft.y - maxRadius / 2, isSelected));
}
}
c++;
}
if (valuesList.size() > 0) {
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
DrawableValue.drawValues(gc, valuesList, false, true);
valuesList.clear();
}
drawScale(gc, drawWidth, boxValue);
}
/**
* draw scale
*
*/
private void drawScale(Graphics2D gc, double drawWidth, int boxValue) {
int x = 20;
int y = topMargin - 30;
Rectangle rect = new Rectangle(x, y, (int) drawWidth, (int) drawWidth);
gc.setColor(Color.LIGHT_GRAY);
gc.fill(rect);
gc.setColor(Color.DARK_GRAY);
gc.draw(rect);
gc.setFont(getFont(ChartViewer.FontKeys.LegendFont.toString()));
gc.drawString(String.format(" = %,d", boxValue), (int) (x + rect.getWidth()), (int) (y + rect.getHeight()));
}
@Override
public String getChartDrawerName() {
return NAME;
}
}
| 17,886 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
StackedBarChartDrawer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/StackedBarChartDrawer.java | /*
* StackedBarChartDrawer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.Geometry;
import jloda.swing.util.ProgramProperties;
import jloda.util.CollectionUtils;
import megan.chart.IChartDrawer;
import megan.chart.data.DefaultChartData;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.SelectionGraphics;
import megan.util.ScalingType;
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
/**
* draws a stacked bar chart
* Daniel Huson, 5.2012
*/
public class StackedBarChartDrawer extends BarChartDrawer implements IChartDrawer {
private static final String NAME = "StackedBarChart";
/**
* constructor
*/
public StackedBarChartDrawer() {
transposedHeightsAdditive = true;
setSupportedScalingTypes(ScalingType.LINEAR, ScalingType.PERCENT);
}
/**
* draw bars with colors representing classes
*
*/
public void drawChart(Graphics2D gc) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
double topY;
if (scalingType == ScalingType.PERCENT) {
topY = 101;
} else {
topY = 1.1 * getMaxValue();
}
double yFactor = (y0 - y1) / topY;
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
if (x0 >= x1)
return;
int numberOfDataSets = getChartData().getNumberOfSeries();
double xStep = (x1 - x0) / (2 * numberOfDataSets);
double bigSpace = Math.max(2, Math.min(10, xStep));
xStep = (x1 - x0 - (isGapBetweenBars() ? bigSpace * numberOfDataSets : 0)) / numberOfDataSets;
// main drawing loop:
int d = 0;
for (String series : getChartData().getSeriesNames()) {
{
String label = seriesLabelGetter.getLabel(series);
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
double xLabel = x0 + (isGapBetweenBars() ? (d + 1) * bigSpace : 0) + (d + 0.5) * xStep;
Point2D apt = new Point2D.Double(xLabel, getHeight() - bottomMargin + 12);
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
if (getChartData().getChartSelection().isSelected(series, null)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.BLACK));
if (sgc != null)
sgc.setCurrentItem(new String[]{series, null});
drawString(gc, label, apt.getX(), apt.getY(), classLabelAngle);
if (sgc != null)
sgc.clearCurrentItem();
}
double currentHeight = y0;
for (String className : getChartData().getClassNames()) {
double value;
if (scalingType == ScalingType.PERCENT) {
double total = getChartData().getTotalForSeriesIncludingDisabledAttributes(series);
if (total == 0)
value = 0;
else
value = 100 * getChartData().getValueAsDouble(series, className) / total;
} else
value = getChartData().getValueAsDouble(series, className);
double xBar = x0 + (isGapBetweenBars() ? (d + 1) * bigSpace : 0) + d * xStep;
double height = value * yFactor;
Rectangle2D rect = new Rectangle((int) Math.round(xBar),
(int) Math.round(currentHeight - height), (int) Math.round(xStep), (int) Math.round(height));
currentHeight -= height;
Color color = getChartColors().getClassColor(class2HigherClassMapper.get(className));
gc.setColor(color);
if (sgc != null)
sgc.setCurrentItem(new String[]{series, className});
gc.fill(rect);
if (sgc != null)
sgc.clearCurrentItem();
if (getChartData().getChartSelection().isSelected(series, className)) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.draw(rect);
gc.setStroke(NORMAL_STROKE);
} else {
gc.setColor(color.darker());
gc.draw(rect);
}
}
d++;
}
}
/**
* draw bars in which colors are by dataset
*
*/
public void drawChartTransposed(Graphics2D gc) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
final int y0 = getHeight() - bottomMargin;
final int y1 = topMargin;
final String[] series = getChartData().getSeriesNames().toArray(new String[getChartData().getNumberOfSeries()]);
double topY;
final double[] percentFactor;
if (scalingType == ScalingType.PERCENT) {
final String[] seriesIncludingDisabled = getChartData().getSeriesNamesIncludingDisabled();
var percentFactorIncludingDisabled = computePercentFactorPerSampleForTransposedChart((DefaultChartData) getChartData(), seriesIncludingDisabled);
topY = computeMaxClassValueUsingPercentFactorPerSeries((DefaultChartData) getChartData(), seriesIncludingDisabled, percentFactorIncludingDisabled);
percentFactor=new double[series.length];
for(var i=0;i<series.length;i++) {
var j= CollectionUtils.getIndex(series[i],seriesIncludingDisabled);
percentFactor[i]=percentFactorIncludingDisabled[j];
}
} else {
topY = 1.1 * getMaxValue();
percentFactor = null;
}
final double yFactor = (y0 - y1) / topY;
final int x0 = leftMargin;
final int x1 = getWidth() - rightMargin;
if (x0 >= x1)
return;
final int numberOfClasses = getChartData().getNumberOfClasses();
if (numberOfClasses == 0)
return;
double xStep = (x1 - x0) / (2 * numberOfClasses);
final double bigSpace = Math.max(2, Math.min(10, xStep));
xStep = (x1 - x0 - (isGapBetweenBars() ? bigSpace * numberOfClasses : 0)) / numberOfClasses;
// main drawing loop:
int c = 0;
for (String className : getChartData().getClassNames()) {
double currentHeight = y0;
{
final Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize();
final double xLabel = x0 + (isGapBetweenBars() ? (c + 1) * bigSpace : 0) + (c + 0.5) * xStep;
Point2D apt = new Point2D.Double(xLabel, getHeight() - bottomMargin + 12);
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
if (getChartData().getChartSelection().isSelected(null, className)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.BLACK));
if (sgc != null)
sgc.setCurrentItem(new String[]{null, className});
drawString(gc, className, apt.getX(), apt.getY(), classLabelAngle);
if (sgc != null)
sgc.clearCurrentItem();
}
for (int i = 0; i < series.length; i++) {
String seriesName = series[i];
double value = getChartData().getValueAsDouble(seriesName, className);
if (scalingType == ScalingType.PERCENT && percentFactor != null) {
value *= percentFactor[i];
}
final double xBar = x0 + (isGapBetweenBars() ? (c + 1) * bigSpace : 0) + c * xStep;
final double height = value * yFactor;
final Rectangle2D rect = new Rectangle((int) Math.round(xBar),
(int) Math.round(currentHeight - height), (int) Math.round(xStep), (int) Math.round(height));
currentHeight -= height;
final Color color = getChartColors().getSampleColor(seriesName);
gc.setColor(color);
if (sgc != null)
sgc.setCurrentItem(new String[]{seriesName, className});
gc.fill(rect);
if (sgc != null)
sgc.clearCurrentItem();
if (getChartData().getChartSelection().isSelected(seriesName, className)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.setStroke(HEAVY_STROKE);
gc.draw(rect);
gc.setStroke(NORMAL_STROKE);
} else {
gc.setColor(color.darker());
gc.draw(rect);
}
}
c++;
}
}
/**
* gets the max value used in the plot
*
* @return max value
*/
@Override
protected double getMaxValue() {
if (!isTranspose())
return getChartData().getMaxTotalSeries();
else {
double maxValue = 0;
for (String className : getChartData().getClassNames()) {
double sum = 0;
for (String series : getChartData().getSeriesNames()) {
sum += getChartData().getValueAsDouble(series, className);
}
maxValue = Math.max(sum, maxValue);
}
return maxValue;
}
}
public boolean canShowValues() {
return false;
}
@Override
public String getChartDrawerName() {
return NAME;
}
}
| 11,789 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
BarChartDrawer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/BarChartDrawer.java | /*
* BarChartDrawer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.Geometry;
import jloda.swing.util.ProgramProperties;
import jloda.util.CollectionUtils;
import megan.chart.IChartDrawer;
import megan.chart.data.DefaultChartData;
import megan.chart.data.IChartData;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.SelectionGraphics;
import megan.util.ScalingType;
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.Objects;
/**
* draws a bar chart
* Daniel Huson, 5.2012
*/
public class BarChartDrawer extends ChartDrawerBase implements IChartDrawer {
public static final String NAME = "BarChart";
private Double maxDisplayedYValue = null;
final Rectangle lastDown = null;
private boolean showVerticalGridLines = true;
private boolean gapBetweenBars = true;
/**
* constructor
*/
public BarChartDrawer() {
setBackground(Color.WHITE);
}
/**
* paints the chart
*
*/
public void paint(Graphics gc0) {
super.paint(gc0);
leftMargin = 90;
rightMargin = 75;
bottomMargin = 200;
topMargin = 20;
final Graphics2D gc = (Graphics2D) gc0;
if (getChartData().getRange() == null || getChartData().getNumberOfClasses() == 0 || getChartData().getNumberOfSeries() == 0) {
drawTitle(gc, null);
gc.setColor(Color.LIGHT_GRAY);
String label = "No data to show: please select nodes in main viewer and then press 'sync'";
gc.setFont(getFont("Default"));
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
gc.drawString(label, (getWidth() - labelSize.width) / 2, 50);
return;
}
Dimension dim = new Dimension();
drawTitle(gc, dim);
topMargin = dim.height;
if (isShowYAxis()) {
drawYAxis(gc, dim);
leftMargin = dim.width;
}
bottomMargin = 0;
if (isShowXAxis()) {
int xAxisLabelHeight;
if (isTranspose())
xAxisLabelHeight = (int) Math.round(computeXAxisLabelHeightTransposed(gc) + 15);
else
xAxisLabelHeight = (int) Math.round(computeXAxisLabelHeight(gc) + 15);
xAxisLabelHeight = Math.min((int) (0.7 * getHeight()), xAxisLabelHeight);
bottomMargin += xAxisLabelHeight;
if (classLabelAngle > 0 && classLabelAngle < Math.PI / 2)
rightMargin = Math.max(75, (int) (0.8 * xAxisLabelHeight));
} else
bottomMargin += 20;
drawTitle(gc, null);
if (isLargeEnough()) {
if (isShowXAxis())
drawXAxis(gc);
if (isShowYAxis())
drawYAxis(gc, null);
if (isTranspose()) {
computeScrollBackReferenceRect();
drawChartTransposed(gc);
} else // color by dataset
{
computeScrollBackReferenceRect();
drawChart(gc);
}
}
}
/**
* draw the title of the chart.
* If size!=null, sets the size only, does not draw
*
*/
private void drawTitle(Graphics2D gc, Dimension size) {
gc.setFont(getFont(ChartViewer.FontKeys.TitleFont.toString()));
if (chartTitle != null) {
Dimension labelSize = BasicSwing.getStringSize(gc, chartTitle, gc.getFont()).getSize();
if (size != null) {
size.setSize(labelSize.getWidth(), labelSize.getHeight() + 20);
return;
}
int x = (getWidth() - labelSize.width) / 2;
int y = labelSize.height;
gc.setColor(getFontColor(ChartViewer.FontKeys.TitleFont.toString(), Color.BLACK));
gc.drawString(chartTitle, x, y);
//gc.drawLine(x,y+4,x+labelSize.width,y+4);
} else if (size != null)
size.setSize(0, 20);
}
/**
* is canvas large enough to draw chart?
*
* @return true, if can draw chart
*/
private boolean isLargeEnough() {
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
return x0 < x1 && y0 > y1;
}
/**
* draw the x axis
*
*/
protected void drawXAxis(Graphics2D gc) {
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.BLACK));
int x = 5;
int y = getHeight() - bottomMargin + 25;
if (isTranspose())
gc.drawString(getChartData().getClassesLabel(), x, y);
else
gc.drawString(getChartData().getSeriesLabel(), x, y);
}
/**
* draw the y-axis
*
*/
protected void drawYAxis(Graphics2D gc, Dimension size) {
gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString()));
double topY;
if (scalingType == ScalingType.PERCENT) {
if (isTranspose()) {
final String[] seriesIncludingDisabled = getChartData().getSeriesNamesIncludingDisabled();
final double[] percentFactor;
percentFactor = computePercentFactorPerSampleForTransposedChart((DefaultChartData) getChartData(), seriesIncludingDisabled);
topY = computeMaxClassValueUsingPercentFactorPerSeries((DefaultChartData) getChartData(), seriesIncludingDisabled, percentFactor);
if (transposedHeightsAdditive && seriesIncludingDisabled.length > 0) {
topY /= seriesIncludingDisabled.length;
}
} else
topY = 101;
} else if (scalingType == ScalingType.LOG) {
drawYAxisLog(gc, size);
return;
} else if (scalingType == ScalingType.SQRT) {
drawYAxisSqrt(gc, size);
return;
} else
topY = 1.1 * getMaxValue();
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
boolean doDraw = (size == null);
Rectangle bbox = null;
double yFactor = (y0 - y1) / topY;
int tickStep = 0;
int minSpace = 50;
for (int i = 1; tickStep == 0; i *= 10) {
if (i * yFactor >= minSpace)
tickStep = i;
else if (2.5 * i * yFactor >= minSpace)
tickStep = (int) (2.5 * i);
else if (5 * i * yFactor >= minSpace)
tickStep = 5 * i;
}
for (int value = 0; (value - 1) < topY; value += tickStep) {
if (maxDisplayedYValue != null && value > maxDisplayedYValue)
break;
String label = String.format("%,d", value);
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
double yPos = y0 - value * yFactor;
int x = leftMargin - (int) (labelSize.getWidth() + 3);
int y = (int) (yPos + labelSize.getHeight() / 2.0);
if (doDraw) {
gc.setColor(getFontColor(ChartViewer.FontKeys.YAxisFont.toString(), Color.BLACK));
gc.drawString(label, x, y);
if (value == 0 || isShowVerticalGridLines()) {
gc.setColor(Color.LIGHT_GRAY);
gc.drawLine(x0, (int) Math.round(yPos), x1, (int) Math.round(yPos));
}
} else {
Rectangle rect = new Rectangle(x, y, labelSize.width, labelSize.height);
if (bbox == null)
bbox = rect;
else
bbox.add(rect);
}
}
String axisLabel = getChartData().getCountsLabel() + (scalingType == ScalingType.PERCENT ? " (%)" : "");
Dimension labelSize = BasicSwing.getStringSize(gc, axisLabel, gc.getFont()).getSize();
int x = 10;
int y = (y0 + y1) / 2 - labelSize.width;
if (doDraw) {
gc.setColor(getFontColor(ChartViewer.FontKeys.YAxisFont.toString(), Color.BLACK));
drawString(gc, axisLabel, x, y, Math.PI / 2);
} else {
Rectangle rect = new Rectangle(x, y, labelSize.height, labelSize.width); // yes, other way around (because label rotated)
if (bbox == null)
bbox = rect;
else
bbox.add(rect);
}
// draw y-axis
if (doDraw) {
gc.setColor(Color.BLACK);
gc.drawLine(x0, y0, x0, y1);
drawArrowHead(gc, new Point(x0, y0), new Point(x0, y1));
}
if (size != null)
size.setSize(bbox.width + 5, bbox.height);
}
/**
* draw the y-axis on a log scale
*
*/
protected void drawYAxisLog(Graphics2D gc, Dimension size) {
gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString()));
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
boolean doDraw = (size == null);
Rectangle bbox = null;
double maxValue = getMaxValue();
double yFactor = (y0 - y1) / computeMaxYAxisValueLogScale(maxValue);
double value = 0;
double previousY = -100000;
int mantisse = 0;
int exponent = 0;
while (value <= maxValue) {
if (maxDisplayedYValue != null && value > maxDisplayedYValue)
break;
double yPos = y0 - (value > 0 ? Math.log10(value) : 0) * yFactor;
if ((mantisse <= 1 || mantisse == 5) && Math.abs(yPos - previousY) >= 20) {
String label = String.format("%,d", (long) value);
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
previousY = yPos;
int x = leftMargin - (int) (labelSize.getWidth() + 3);
int y = (int) (yPos + labelSize.getHeight() / 2.0);
if (doDraw) {
gc.setColor(getFontColor(ChartViewer.FontKeys.YAxisFont.toString(), Color.BLACK));
gc.drawString(label, x, y);
if (value == 0 || isShowVerticalGridLines()) {
gc.setColor(Color.LIGHT_GRAY);
gc.drawLine(x0, (int) Math.round(yPos), x1, (int) Math.round(yPos));
}
} else {
Rectangle rect = new Rectangle(x, y, labelSize.width, labelSize.height);
if (bbox == null)
bbox = rect;
else
bbox.add(rect);
}
}
if (mantisse < 9)
mantisse++;
else {
mantisse = 1;
exponent++;
}
value = mantisse * Math.pow(10, exponent);
}
String axisLabel = getChartData().getCountsLabel();
Dimension labelSize = BasicSwing.getStringSize(gc, axisLabel, gc.getFont()).getSize();
int x = 10;
int y = (y0 + y1) / 2 - labelSize.width;
if (doDraw) {
gc.setColor(getFontColor(ChartViewer.FontKeys.YAxisFont.toString(), Color.BLACK));
drawString(gc, axisLabel, x, y, Math.PI / 2);
} else {
Rectangle rect = new Rectangle(x, y, labelSize.height, labelSize.width); // yes, other way around (because label rotated)
if (bbox == null)
bbox = rect;
else
bbox.add(rect);
}
// draw y-axis
if (doDraw) {
gc.setColor(Color.BLACK);
gc.drawLine(x0, y0, x0, y1);
drawArrowHead(gc, new Point(x0, y0), new Point(x0, y1));
}
if (size != null)
size.setSize(bbox.width + 5, bbox.height);
}
/**
* draw the y-axis on a sqrt scale
*
*/
private void drawYAxisSqrt(Graphics2D gc, Dimension size) {
gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString()));
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
boolean doDraw = (size == null);
Rectangle bbox = null;
double maxValue = getMaxValue();
double yFactor = (y0 - y1) / Math.sqrt(maxValue);
double value = 0;
double previousY = -100000;
int mantisse = 0;
int exponent = 0;
while (value <= maxValue) {
if (maxDisplayedYValue != null && value > maxDisplayedYValue)
break;
double yPos = y0 - (value > 0 ? Math.sqrt(value) : 0) * yFactor;
if ((mantisse <= 1 || mantisse == 5) && Math.abs(yPos - previousY) >= 20) {
String label = String.format("%,d", (long) value);
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
previousY = yPos;
int x = leftMargin - (int) (labelSize.getWidth() + 3);
int y = (int) (yPos + labelSize.getHeight() / 2.0);
if (doDraw) {
gc.setColor(getFontColor(ChartViewer.FontKeys.YAxisFont.toString(), Color.BLACK));
gc.drawString(label, x, y);
if (showVerticalGridLines) {
gc.setColor(Color.LIGHT_GRAY);
gc.drawLine(x0, (int) Math.round(yPos), x1, (int) Math.round(yPos));
}
} else {
Rectangle rect = new Rectangle(x, y, labelSize.width, labelSize.height);
if (bbox == null)
bbox = rect;
else
bbox.add(rect);
}
}
if (mantisse < 9)
mantisse++;
else {
mantisse = 1;
exponent++;
}
value = mantisse * Math.pow(10, exponent);
}
String axisLabel = getChartData().getCountsLabel();
Dimension labelSize = BasicSwing.getStringSize(gc, axisLabel, gc.getFont()).getSize();
int x = 10;
int y = (y0 + y1) / 2 - labelSize.width;
if (doDraw) {
gc.setColor(getFontColor(ChartViewer.FontKeys.YAxisFont.toString(), Color.BLACK));
drawString(gc, axisLabel, x, y, Math.PI / 2);
} else {
Rectangle rect = new Rectangle(x, y, labelSize.height, labelSize.width); // yes, other way around (because label rotated)
if (bbox == null)
bbox = rect;
else
bbox.add(rect);
}
// draw y-axis
if (doDraw) {
gc.setColor(Color.BLACK);
gc.drawLine(x0, y0, x0, y1);
drawArrowHead(gc, new Point(x0, y0), new Point(x0, y1));
}
if (size != null)
size.setSize(bbox.width + 5, bbox.height);
}
protected double computeXAxisLabelHeight(Graphics2D gc) {
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
double theHeight = 2 * gc.getFont().getSize();
if (classLabelAngle != 0) {
double sin = Math.abs(Math.sin(classLabelAngle));
for (String series : getChartData().getSeriesNames()) {
String label = seriesLabelGetter.getLabel(series);
if (label.length() > 50)
label = label.substring(0, 50) + "...";
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
theHeight = Math.max(theHeight, gc.getFont().getSize() + sin * labelSize.width);
}
}
return theHeight;
}
protected double computeXAxisLabelHeightTransposed(Graphics2D gc) {
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
double theHeight = 2 * gc.getFont().getSize();
if (classLabelAngle != 0) {
double sin = Math.abs(Math.sin(classLabelAngle));
for (String className : getChartData().getClassNames()) {
Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize();
theHeight = Math.max(theHeight, gc.getFont().getSize() + sin * labelSize.width);
}
}
return theHeight;
}
/**
* draw chart
*
*/
public void drawChart(Graphics2D gc) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
// if(sgc!=null) lastDown=(Rectangle)sgc.getSelectionRectangle().clone();
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
double topY;
if (scalingType == ScalingType.PERCENT)
topY = 101;
else if (scalingType == ScalingType.LOG) {
topY = computeMaxYAxisValueLogScale(getMaxValue());
} else if (scalingType == ScalingType.SQRT) {
topY = Math.sqrt(getMaxValue());
} else
topY = 1.1 * getMaxValue();
double yFactor = (y0 - y1) / topY;
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
if (x0 >= x1)
return;
int numberOfDataSets = getChartData().getNumberOfSeries();
int numberOfClasses = getChartData().getNumberOfClasses();
if (numberOfDataSets == 0 || numberOfClasses == 0)
return;
double xStep = (x1 - x0) / ((numberOfClasses + (isGapBetweenBars() ? 1 : 0)) * numberOfDataSets);
final double bigSpace = Math.max(2, Math.min(10, xStep));
xStep = (x1 - x0 - (isGapBetweenBars() ? bigSpace * numberOfDataSets : 0)) / (numberOfClasses * numberOfDataSets);
// main drawing loop:
int d = 0;
for (String series : getChartData().getSeriesNames()) {
if (isShowXAxis()) {
final double xLabel = leftMargin + (isGapBetweenBars() ? (d + 1) * bigSpace : 0) + ((d + 0.5) * numberOfClasses) * xStep;
Point2D apt = new Point2D.Double(xLabel, getHeight() - bottomMargin + 10);
String label = seriesLabelGetter.getLabel(series);
Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
if (sgc != null)
sgc.setCurrentItem(new String[]{series, null});
if (getChartData().getChartSelection().isSelected(series, null)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.BLACK));
drawString(gc, label, apt.getX(), apt.getY(), classLabelAngle);
if (sgc != null)
sgc.clearCurrentItem();
}
var percentFactor=0.0;
if(scalingType==ScalingType.PERCENT) {
var total = getChartData().getTotalForSeriesIncludingDisabledAttributes(series);
if(total>0)
percentFactor=100.0/total;
}
int c = 0;
for (String className : getChartData().getClassNames()) {
double value = getChartData().getValueAsDouble(series, className);
switch (scalingType) { // modify if not linear scale:
case PERCENT -> {
value *= percentFactor;
}
case LOG -> {
if (value == 1)
value = Math.log10(2) / 2;
else if (value > 0)
value = Math.log10(value);
}
case SQRT -> {
if (value > 0)
value = Math.sqrt(value);
}
}
// coordinates for d-th dataset and c-th class:
double xBar = x0 + (isGapBetweenBars() ? (d + 1) * bigSpace : 0) + (d * numberOfClasses + c) * xStep;
double height = Math.max(1, value * yFactor);
Rectangle2D rect = new Rectangle((int) Math.round(xBar),
(int) Math.round(y0 - height), Math.max(1, (int) Math.round(xStep)), (int) Math.round(height));
boolean isSelected = getChartData().getChartSelection().isSelected(series, className);
Color color = getChartColors().getClassColor(class2HigherClassMapper.get(className));
gc.setColor(color);
if (sgc != null)
sgc.setCurrentItem(new String[]{series, className});
gc.fill(rect);
if (sgc != null)
sgc.clearCurrentItem();
if (isSelected) {
gc.setStroke(HEAVY_STROKE);
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.draw(rect);
gc.setStroke(NORMAL_STROKE);
} else {
gc.setColor(color.darker());
gc.draw(rect);
}
if (showValues || isSelected) {
String label = "" + (int) getChartData().getValueAsDouble(series, className);
valuesList.add(new DrawableValue(label, (int) (rect.getX() + rect.getWidth() / 2), (int) (rect.getY() - 2), isSelected));
}
c++;
}
d++;
}
if (!valuesList.isEmpty()) {
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
DrawableValue.drawValues(gc, valuesList, true, false);
valuesList.clear();
}
if (sgc == null && lastDown != null) {
gc.setColor(Color.green);
gc.draw(lastDown);
}
}
/**
* draw bars in which colors are by dataset
*
*/
public void drawChartTransposed(Graphics2D gc) {
SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
// if(sgc!=null) lastDown=(Rectangle)sgc.getSelectionRectangle().clone();
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
final int y0 = getHeight() - bottomMargin;
final int y1 = topMargin;
final String[] series = getChartData().getSeriesNames().toArray(new String[getChartData().getNumberOfSeries()]);
final double topY;
final double[] percentFactor;
if (scalingType == ScalingType.PERCENT) {
final String[] seriesIncludingDisabled = getChartData().getSeriesNamesIncludingDisabled();
var percentFactorIncludingDisabled = computePercentFactorPerSampleForTransposedChart((DefaultChartData) getChartData(), seriesIncludingDisabled);
topY = computeMaxClassValueUsingPercentFactorPerSeries((DefaultChartData) getChartData(), seriesIncludingDisabled, percentFactorIncludingDisabled);
percentFactor=new double[series.length];
for(var i=0;i<series.length;i++) {
var j= CollectionUtils.getIndex(series[i],seriesIncludingDisabled);
percentFactor[i]=percentFactorIncludingDisabled[j];
}
} else if (scalingType == ScalingType.LOG) {
topY = computeMaxYAxisValueLogScale(getMaxValue());
percentFactor = null;
} else if (scalingType == ScalingType.SQRT) {
topY = Math.sqrt(getMaxValue());
percentFactor = null;
} else {
topY = 1.1 * getMaxValue();
percentFactor = null;
}
final double yFactor = (y0 - y1) / topY;
final int x0 = leftMargin;
final int x1 = getWidth() - rightMargin;
if (x0 >= x1)
return;
final int numberOfDataSets = getChartData().getNumberOfSeries();
final int numberOfClasses = getChartData().getNumberOfClasses();
double xStep = (double) (x1 - x0) / (numberOfClasses * (numberOfDataSets + (isGapBetweenBars() ? 1 : 0))); // step size if big spaces were as big as bars
final double bigSpace = Math.max(2.0, Math.min(10.0, xStep));
xStep = (x1 - x0 - (isGapBetweenBars() ? bigSpace * (numberOfClasses) : 0)) / (double) (numberOfClasses * numberOfDataSets);
// main drawing loop:
int c = 0;
for (String className : getChartData().getClassNames()) {
if (isShowXAxis()) {
final double xLabel = leftMargin + (isGapBetweenBars() ? (c + 1) * bigSpace : 0) + ((c + 0.5) * numberOfDataSets) * xStep;
Point2D apt = new Point2D.Double(xLabel, getHeight() - bottomMargin + 10);
final Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize();
if (classLabelAngle == 0) {
apt.setLocation(apt.getX() - labelSize.getWidth() / 2, apt.getY());
} else if (classLabelAngle > Math.PI / 2) {
apt = Geometry.translateByAngle(apt, classLabelAngle, -labelSize.width);
}
if (getChartData().getChartSelection().isSelected(null, className)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, apt.getX(), apt.getY(), labelSize.width, labelSize.height, classLabelAngle, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.BLACK));
if (sgc != null)
sgc.setCurrentItem(new String[]{null, className});
drawString(gc, className, apt.getX(), apt.getY(), classLabelAngle);
if (sgc != null)
sgc.clearCurrentItem();
}
int d = 0;
for (int i = 0; i < series.length; i++) {
final String seriesName = series[i];
double value = getChartData().getValueAsDouble(seriesName, className);
switch (scalingType) { // modify if not linear scale:
case PERCENT -> {
var oldValue=value;
if(percentFactor!=null)
value*=percentFactor[i];
}
case LOG -> {
if (value == 1)
value = Math.log10(2) / 2;
else if (value > 0)
value = Math.log10(value);
}
case SQRT -> {
if (value > 0)
value = Math.sqrt(value);
}
}
final double xBar = leftMargin + (isGapBetweenBars() ? (c + 1) * bigSpace : 0) + (c * numberOfDataSets + d) * xStep;
final double height = Math.max(0, value * yFactor);
final Rectangle2D rect = new Rectangle((int) Math.round(xBar),
(int) Math.round(y0 - height), Math.max(1, (int) Math.round(xStep)), (int) Math.round(height));
final Color color = getChartColors().getSampleColor(seriesName);
gc.setColor(color);
if (sgc != null)
sgc.setCurrentItem(new String[]{seriesName, className});
gc.fill(rect);
if (sgc != null)
sgc.clearCurrentItem();
final boolean isSelected = getChartData().getChartSelection().isSelected(seriesName, className);
if (isSelected) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
gc.setStroke(HEAVY_STROKE);
gc.draw(rect);
gc.setStroke(NORMAL_STROKE);
} else {
gc.setColor(color.darker());
gc.draw(rect);
}
if (showValues || isSelected) {
String label = "" + (int) getChartData().getValueAsDouble(seriesName, className);
valuesList.add(new DrawableValue(label, (int) (rect.getX() + rect.getWidth() / 2), (int) (rect.getY() - 2), isSelected));
}
d++;
}
c++;
}
if (!valuesList.isEmpty()) {
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
DrawableValue.drawValues(gc, valuesList, true, false);
valuesList.clear();
}
if (sgc == null && lastDown != null) {
gc.setColor(Color.green);
gc.draw(lastDown);
}
}
public Double getMaxDisplayedYValue() {
return maxDisplayedYValue;
}
/**
* use this to set the max displayed y value
*
*/
public void setMaxDisplayedYValue(Double maxDisplayedYValue) {
this.maxDisplayedYValue = maxDisplayedYValue;
}
/**
* gets the max value used in the plot. Stacked bar chart overrides this
*
* @return max value
*/
protected double getMaxValue() {
try {
return getChartData().getRange().getSecond().doubleValue();
} catch (NullPointerException ex) {
return 100;
}
}
public IChartData getChartData() {
return (IChartData) chartData;
}
public boolean canShowValues() {
return true;
}
@Override
public String getChartDrawerName() {
return NAME;
}
/**
* gets factor used to compute percentage for a series in a transposed chart
*
* @return factors
*/
public double[] computePercentFactorPerSampleForTransposedChart(DefaultChartData chartData, String[] series) {
final double[] percentFactorPerSample = new double[series.length];
for (int i = 0; i < series.length; i++) {
double value = chartData.getTotalForSeriesIncludingDisabledAttributes(series[i]);
percentFactorPerSample[i] = (value == 0 ? 0 : 100 / value);
}
return percentFactorPerSample;
}
/**
* gets the max percentage value for a given class in a transposed chart
*
* @return max percentage value or sum (if transposedHeightsAdditive) seen for any of the classes
*/
public double computeMaxClassValueUsingPercentFactorPerSeries(DefaultChartData chartData, String[] series, double[] percentFactorPerSeries) {
var maxValue = 0.0;
for (String className : chartData.getClassNamesIncludingDisabled()) {
var classValue = 0.0;
for (int i = 0; i < series.length; i++) {
String seriesName = series[i];
if (transposedHeightsAdditive) // stacked charts
{
classValue += percentFactorPerSeries[i] * chartData.getValueAsDouble(seriesName, className);
}
else // bar chart, line chart
{
var value=percentFactorPerSeries[i] * chartData.getValueAsDouble(seriesName, className);
classValue = Math.max(classValue,value);
}
}
if (classValue > maxValue) {
maxValue = classValue;
}
}
return 1.1 * maxValue;
}
public boolean isShowVerticalGridLines() {
return showVerticalGridLines;
}
public void setShowVerticalGridLines(boolean showVerticalGridLines) {
this.showVerticalGridLines = showVerticalGridLines;
}
public boolean isGapBetweenBars() {
return gapBetweenBars;
}
public void setGapBetweenBars(boolean gapBetweenBars) {
this.gapBetweenBars = gapBetweenBars;
}
}
| 33,405 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CoOccurrenceDrawer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/drawers/CoOccurrenceDrawer.java | /*
* CoOccurrenceDrawer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.drawers;
import jloda.graph.*;
import jloda.graph.algorithms.FruchtermanReingoldLayout;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.ProgramProperties;
import jloda.util.APoint2D;
import jloda.util.Basic;
import jloda.util.StringUtils;
import megan.chart.IChartDrawer;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.SelectionGraphics;
import megan.util.ScalingType;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* draws a co-occurrence graph
* Daniel Huson, 6.2012
*/
public class CoOccurrenceDrawer extends BarChartDrawer implements IChartDrawer {
public static final String NAME = "CoOccurrencePlot";
public enum Method {Jaccard, PearsonsR, KendallsTau}
private int maxRadius = ProgramProperties.get("COMaxRadius", 40);
private final Graph graph;
private final EdgeArray<Float> edgeValue;
private final Color PositiveColor = new Color(0x3F861C);
private final Color NegativeColor = new Color(0xFB6542);
private final Rectangle2D boundingBox = new Rectangle2D.Double();
private double minThreshold = ProgramProperties.get("COMinThreshold", 0.01d); // min percentage for class
private int minProbability = ProgramProperties.get("COMinProbability", 70); // min co-occurrence probability in percent
private int minPrevalence = ProgramProperties.get("COMinPrevalence", 10); // minimum prevalence in percent
private int maxPrevalence = ProgramProperties.get("COMaxPrevalence", 90); // maximum prevalence in percent
private boolean showAntiOccurring = ProgramProperties.get("COShowAntiOccurring", true);
private boolean showCoOccurring = ProgramProperties.get("COShowCoOccurring", true);
private Method method = Method.valueOf(ProgramProperties.get("COMethod", Method.Jaccard.toString()));
/**
* constructor
*/
public CoOccurrenceDrawer() {
graph = new Graph();
edgeValue = new EdgeArray<>(graph);
setSupportedScalingTypes(ScalingType.LINEAR);
}
/**
* draw heat map with colors representing classes
*
*/
public void drawChart(Graphics2D gc) {
final SelectionGraphics<String[]> sgc = (gc instanceof SelectionGraphics ? (SelectionGraphics<String[]>) gc : null);
int y0 = getHeight() - bottomMargin;
int y1 = topMargin;
int x0 = leftMargin;
int x1 = getWidth() - rightMargin;
if (x0 >= x1)
return;
int leftRightLabelOverhang = (getWidth() > 200 ? 100 : 0);
double drawWidth = (getWidth() - 2 * leftRightLabelOverhang);
double drawHeight = (getHeight() - topMargin - 20 - 20); // minus extra 20 for bottom toolbar
double factorX = drawWidth / boundingBox.getWidth();
double factorY = drawHeight / boundingBox.getHeight();
double dx = leftRightLabelOverhang - factorX * boundingBox.getMinX() + (drawWidth - factorX * boundingBox.getWidth()) / 2;
double dy = topMargin + 20 - factorY * boundingBox.getMinY() + (drawHeight - factorY * boundingBox.getHeight()) / 2;
Line2D line = new Line2D.Double();
/*
gc.setColor(Color.BLUE);
gc.drawRect((int) (factorX * boundingBox.getX() + dx) + 3, (int) (factorY * boundingBox.getY() + dy) + 3,
(int) (factorX * boundingBox.getWidth()) - 6, (int) (factorY * boundingBox.getHeight()) - 6);
*/
gc.setColor(Color.BLACK);
for (Edge e = graph.getFirstEdge(); e != null; e = graph.getNextEdge(e)) {
Node v = e.getSource();
Point2D pv = ((NodeData) v.getData()).getLocation();
Node w = e.getTarget();
Point2D pw = ((NodeData) w.getData()).getLocation();
try {
line.setLine(factorX * pv.getX() + dx, factorY * pv.getY() + dy, factorX * pw.getX() + dx, factorY * pw.getY() + dy);
gc.setColor(edgeValue.get(e) > 0 ? PositiveColor : NegativeColor);
gc.draw(line);
if (isShowValues()) {
gc.setColor(Color.DARK_GRAY);
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
gc.drawString(StringUtils.removeTrailingZerosAfterDot(String.format("%.4f", edgeValue.get(e))), (int) Math.round(0.5 * factorX * (pv.getX() + pw.getX()) + dx), (int) Math.round(0.5 * factorY * (pv.getY() + pw.getY()) + dy));
}
} catch (Exception ex) {
Basic.caught(ex);
}
}
double maxPrevalence = 1;
for (Node v = graph.getFirstNode(); v != null; v = graph.getNextNode(v)) {
Integer prevalence = ((NodeData) v.getData()).getPrevalence();
if (prevalence > maxPrevalence)
maxPrevalence = prevalence;
}
// draw all nodes in white to mask edges
for (Node v = graph.getFirstNode(); v != null; v = graph.getNextNode(v)) {
Point2D pv = ((NodeData) v.getData()).getLocation();
Integer prevalence = ((NodeData) v.getData()).getPrevalence();
double value;
if (scalingType == ScalingType.PERCENT) {
value = prevalence / maxPrevalence;
} else if (scalingType == ScalingType.LOG) {
value = Math.log(prevalence + 1) / Math.log(maxPrevalence + 1);
} else if (scalingType == ScalingType.SQRT) {
value = Math.sqrt(prevalence) / Math.sqrt(maxPrevalence);
} else
value = prevalence / maxPrevalence;
double size = Math.max(1, value * (double) maxRadius);
int[] oval = {(int) (factorX * pv.getX() + dx - size), (int) (factorY * pv.getY() + dy - size), (int) (2 * size), (int) (2 * size)};
gc.setColor(Color.WHITE); // don't want to see the edges behind the nodes
gc.fillOval(oval[0], oval[1], oval[2], oval[3]);
}
// draw all nodes in color:
for (Node v = graph.getFirstNode(); v != null; v = graph.getNextNode(v)) {
String className = ((NodeData) v.getData()).getLabel();
Point2D pv = ((NodeData) v.getData()).getLocation();
Integer prevalence = ((NodeData) v.getData()).getPrevalence();
double value;
if (scalingType == ScalingType.PERCENT) {
value = prevalence / maxPrevalence;
} else if (scalingType == ScalingType.LOG) {
value = Math.log(prevalence + 1) / Math.log(maxPrevalence + 1);
} else if (scalingType == ScalingType.SQRT) {
value = Math.sqrt(prevalence) / Math.sqrt(maxPrevalence);
} else
value = prevalence / maxPrevalence;
double size = Math.max(1, value * (double) maxRadius);
int[] oval = {(int) (factorX * pv.getX() + dx - size), (int) (factorY * pv.getY() + dy - size), (int) (2 * size), (int) (2 * size)};
Color color = getChartColors().getClassColor(class2HigherClassMapper.get(className), 150);
gc.setColor(color);
if (sgc != null)
sgc.setCurrentItem(new String[]{null, className});
gc.fillOval(oval[0], oval[1], oval[2], oval[3]);
if (sgc != null)
sgc.clearCurrentItem();
boolean isSelected = getChartData().getChartSelection().isSelected(null, className);
if (isSelected) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
if (oval[2] <= 1) {
oval[0] -= 1;
oval[1] -= 1;
oval[2] += 2;
oval[3] += 2;
}
gc.setStroke(HEAVY_STROKE);
gc.drawOval(oval[0], oval[1], oval[2], oval[3]);
gc.setStroke(NORMAL_STROKE);
} else {
gc.setColor(color.darker());
gc.drawOval(oval[0], oval[1], oval[2], oval[3]);
}
if ((showValues && value > 0) || isSelected) {
String label = "" + prevalence;
valuesList.add(new DrawableValue(label, oval[0] + oval[2] + 2, oval[1] + oval[3] / 2, isSelected));
}
}
// show labels if requested
if (isShowXAxis()) {
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
for (Node v = graph.getFirstNode(); v != null; v = graph.getNextNode(v)) {
String className = ((NodeData) v.getData()).getLabel();
Point2D pv = ((NodeData) v.getData()).getLocation();
Integer prevalence = ((NodeData) v.getData()).getPrevalence();
double value;
if (scalingType == ScalingType.PERCENT) {
value = prevalence / maxPrevalence;
} else if (scalingType == ScalingType.LOG) {
value = Math.log(prevalence + 1) / Math.log(maxPrevalence + 1);
} else if (scalingType == ScalingType.SQRT) {
value = Math.sqrt(prevalence) / Math.sqrt(maxPrevalence);
} else
value = prevalence / maxPrevalence;
double size = Math.max(1, value * (double) maxRadius);
int[] oval = {(int) (factorX * pv.getX() + dx - size), (int) (factorY * pv.getY() + dy - size), (int) (2 * size), (int) (2 * size)};
Dimension labelSize = BasicSwing.getStringSize(gc, className, gc.getFont()).getSize();
int x = (int) Math.round(oval[0] + oval[2] / 2.0 - labelSize.getWidth() / 2);
int y = oval[1] - 2;
if (getChartData().getChartSelection().isSelected(null, className)) {
gc.setColor(ProgramProperties.SELECTION_COLOR);
fillAndDrawRect(gc, x, y, labelSize.width, labelSize.height, 0, ProgramProperties.SELECTION_COLOR, ProgramProperties.SELECTION_COLOR_DARKER);
}
gc.setColor(getFontColor(ChartViewer.FontKeys.XAxisFont.toString(), Color.BLACK));
if (sgc != null)
sgc.setCurrentItem(new String[]{null, className});
gc.drawString(className, x, y);
if (sgc != null)
sgc.clearCurrentItem();
}
}
if (!valuesList.isEmpty()) {
gc.setFont(getFont(ChartViewer.FontKeys.YAxisFont.toString()));
gc.setFont(getFont(ChartViewer.FontKeys.ValuesFont.toString()));
DrawableValue.drawValues(gc, valuesList, false, true);
valuesList.clear();
}
}
/**
* draw heat map with colors representing series
*
*/
public void drawChartTransposed(Graphics2D gc) {
gc.setFont(getFont(ChartViewer.FontKeys.XAxisFont.toString()));
}
/**
* update the view
*/
public void updateView() {
// todo: may need to this in a separate thread
updateGraph();
embedGraph();
}
/**
* computes the co-occurrences graph
*/
private void updateGraph() {
graph.clear();
Map<String, Node> className2Node = new HashMap<>();
// setup nodes
for (String aClassName : getChartData().getClassNames()) {
int numberOfSeriesContainingClass = 0;
for (String series : getChartData().getSeriesNames()) {
final double percentage = 100.0 * getChartData().getValue(series, aClassName).doubleValue() / getChartData().getTotalForSeries(series);
if (percentage >= getMinThreshold())
numberOfSeriesContainingClass++;
}
final double percentageOfSeriesContainingClass = 100.0 * numberOfSeriesContainingClass / (double) getChartData().getNumberOfSeries();
if (percentageOfSeriesContainingClass >= getMinPrevalence() && percentageOfSeriesContainingClass <= getMaxPrevalence()) {
final Node v = graph.newNode();
final NodeData nodeData = new NodeData();
nodeData.setLabel(aClassName);
v.setData(nodeData);
className2Node.put(aClassName, v);
nodeData.setPrevalence(numberOfSeriesContainingClass);
}
}
final String[] series = getChartData().getSeriesNames().toArray(new String[0]);
final int n = series.length;
if (n >= 2) { // setup edges
for (Node v = graph.getFirstNode(); v != null; v = v.getNext()) {
final String classA = ((NodeData) v.getData()).getLabel();
for (Node w = v.getNext(); w != null; w = w.getNext()) {
final String classB = ((NodeData) w.getData()).getLabel();
final float score;
switch (method) {
default /* case Jaccard */ -> {
final Set<String> intersection = new HashSet<>();
final Set<String> union = new HashSet<>();
for (String series1 : series) {
double total = getChartData().getTotalForSeries(series1);
double percentage1 = 100.0 * getChartData().getValue(series1, classA).doubleValue() / total;
double percentage2 = 100.0 * getChartData().getValue(series1, classB).doubleValue() / total;
if (percentage1 >= getMinThreshold() || percentage2 >= getMinThreshold()) {
union.add(series1);
}
if (percentage1 > getMinThreshold() && percentage2 >= getMinThreshold()) {
intersection.add(series1);
}
}
if (!union.isEmpty()) {
final boolean positive;
if (isShowCoOccurring() && !isShowAntiOccurring())
positive = true;
else if (!isShowCoOccurring() && isShowAntiOccurring())
positive = false;
else
positive = (intersection.size() >= 0.5 * union.size());
if (positive)
score = ((float) intersection.size() / (float) union.size());
else
score = -((float) (union.size() - intersection.size()) / (float) union.size());
} else
score = 0;
}
case PearsonsR -> {
double meanA = 0;
double meanB = 0;
for (String series1 : series) {
meanA += getChartData().getValue(series1, classA).doubleValue();
meanB += getChartData().getValue(series1, classB).doubleValue();
}
meanA /= n;
meanB /= n;
double valueTop = 0;
double valueBottomA = 0;
double valueBottomB = 0;
for (String series1 : series) {
final double a = getChartData().getValue(series1, classA).doubleValue();
final double b = getChartData().getValue(series1, classB).doubleValue();
valueTop += (a - meanA) * (b - meanB);
valueBottomA += (a - meanA) * (a - meanA);
valueBottomB += (b - meanB) * (b - meanB);
}
valueBottomA = Math.sqrt(valueBottomA);
valueBottomB = Math.sqrt(valueBottomB);
score = (float) (valueTop / (valueBottomA * valueBottomB));
}
case KendallsTau -> {
int countConcordant = 0;
int countDiscordant = 0;
for (int i = 0; i < series.length; i++) {
String series1 = series[i];
double aIn1 = getChartData().getValue(series1, classA).doubleValue();
double bIn1 = getChartData().getValue(series1, classB).doubleValue();
for (int j = i + 1; j < series.length; j++) {
String series2 = series[j];
double aIn2 = getChartData().getValue(series2, classA).doubleValue();
double bIn2 = getChartData().getValue(series2, classB).doubleValue();
if (aIn1 != aIn2 && bIn1 != bIn2) {
if ((aIn1 < aIn2) == (bIn1 < bIn2))
countConcordant++;
else
countDiscordant++;
}
}
}
if (countConcordant + countDiscordant > 0)
score = (float) (countConcordant - countDiscordant) / (float) (countConcordant + countDiscordant);
else
score = 0;
//System.err.println(classA+" vs "+classB+": conc: "+countConcordant+" disc: "+countDiscordant+" score: "+score);
}
}
if (showCoOccurring && 100 * score >= getMinProbability() || showAntiOccurring && -100 * score >= getMinProbability()) {
Edge e = graph.newEdge(className2Node.get(classA), className2Node.get(classB));
graph.setInfo(e, score);
edgeValue.put(e, score); // negative value indicates anticorrelated
}
}
}
}
}
/**
* do embedding of graph
*/
private void embedGraph() {
final FruchtermanReingoldLayout fruchtermanReingoldLayout = new FruchtermanReingoldLayout(graph, null);
final NodeArray<APoint2D<?>> coordinates = new NodeArray<>(graph);
fruchtermanReingoldLayout.apply(1000, coordinates);
boolean first = true;
for (Node v = graph.getFirstNode(); v != null; v = v.getNext()) {
NodeData nodeData = (NodeData) v.getData();
nodeData.setLocation(coordinates.get(v).getX(), coordinates.get(v).getY());
if (first) {
boundingBox.setRect(coordinates.get(v).getX(), coordinates.get(v).getY(), 1, 1);
first = false;
} else
boundingBox.add(coordinates.get(v).getX(), coordinates.get(v).getY());
}
boundingBox.setRect(boundingBox.getX() - maxRadius, boundingBox.getY() - maxRadius, boundingBox.getWidth() + 2 * maxRadius,
boundingBox.getHeight() + 2 * maxRadius);
}
public int getMaxRadius() {
return maxRadius;
}
public void setMaxRadius(int maxRadius) {
this.maxRadius = maxRadius;
}
/**
* draw the x axis
*
*/
protected void drawXAxis(Graphics2D gc) {
}
/**
* draw the y-axis
*
*/
protected void drawYAxis(Graphics2D gc, Dimension size) {
}
protected void drawYAxisGrid(Graphics2D gc) {
}
public boolean canShowLegend() {
return false;
}
public double getMinThreshold() {
return minThreshold;
}
public void setMinThreshold(float minThreshold) {
this.minThreshold = minThreshold;
ProgramProperties.put("COMinThreshold", minThreshold);
}
public int getMinProbability() {
return minProbability;
}
public void setMinProbability(int minProbability) {
this.minProbability = minProbability;
ProgramProperties.put("COMinProbability", minProbability);
}
public int getMinPrevalence() {
return minPrevalence;
}
public void setMinPrevalence(int minPrevalence) {
this.minPrevalence = minPrevalence;
ProgramProperties.put("COMinPrevalence", minPrevalence);
}
public int getMaxPrevalence() {
return maxPrevalence;
}
public void setMaxPrevalence(int maxPrevalence) {
this.maxPrevalence = maxPrevalence;
ProgramProperties.put("COMaxPrevalence", maxPrevalence);
}
public void setShowAntiOccurring(boolean showAntiOccurring) {
this.showAntiOccurring = showAntiOccurring;
ProgramProperties.put("COShowAntiOccurring", showAntiOccurring);
}
public boolean isShowAntiOccurring() {
return showAntiOccurring;
}
public boolean isShowCoOccurring() {
return showCoOccurring;
}
public void setShowCoOccurring(boolean showCoOccurring) {
this.showCoOccurring = showCoOccurring;
ProgramProperties.put("COShowCoOccurring", showCoOccurring);
}
public Method getMethod() {
return method;
}
public void setMethod(Method method) {
this.method = method;
ProgramProperties.put("COMethod", method.toString());
}
static class NodeData {
private String label;
private Integer prevalence;
private Point2D location;
String getLabel() {
return label;
}
void setLabel(String label) {
this.label = label;
}
Integer getPrevalence() {
return prevalence;
}
void setPrevalence(Integer prevalence) {
this.prevalence = prevalence;
}
Point2D getLocation() {
return location;
}
public void setLocation(Point2D location) {
this.location = location;
}
void setLocation(double x, double y) {
this.location = new Point2D.Double(x, y);
}
}
/**
* must x and y coordinates by zoomed together?
*
*/
@Override
public boolean isXYLocked() {
return true;
}
/**
* selects all nodes in the connected component hit by the mouse
*
* @return true if anything selected
*/
public boolean selectComponent(MouseEvent event) {
final SelectionGraphics<String[]> selectionGraphics = new SelectionGraphics<>(getGraphics());
selectionGraphics.setMouseLocation(event.getPoint());
if (transpose)
drawChartTransposed(selectionGraphics);
else
drawChart(selectionGraphics);
Set<String> seriesToSelect = new HashSet<>();
Set<String> classesToSelect = new HashSet<>();
int count = 0;
int size = selectionGraphics.getSelectedItems().size();
for (String[] pair : selectionGraphics.getSelectedItems()) {
if (selectionGraphics.getUseWhich() == SelectionGraphics.Which.Last && count++ < size - 1)
continue;
if (pair[0] != null) {
seriesToSelect.add(pair[0]);
}
if (pair[1] != null) {
classesToSelect.add(pair[1]);
}
if (selectionGraphics.getUseWhich() == SelectionGraphics.Which.First)
break;
}
if (transpose) {
} else {
Set<Node> toVisit = new HashSet<>();
for (Node v = graph.getFirstNode(); v != null; v = v.getNext()) {
NodeData nodeData = (NodeData) v.getData();
if (classesToSelect.contains(nodeData.getLabel())) {
toVisit.add(v);
}
}
while (toVisit.size() > 0) {
Node v = toVisit.iterator().next();
toVisit.remove(v);
selectRec(v, classesToSelect);
}
}
if (seriesToSelect.size() > 0)
getChartData().getChartSelection().setSelectedSeries(seriesToSelect, true);
if (classesToSelect.size() > 0)
getChartData().getChartSelection().setSelectedClass(classesToSelect, true);
return seriesToSelect.size() > 0 || classesToSelect.size() > 0;
}
/**
* recursively select all nodes in the same component
*
*/
private void selectRec(Node v, Set<String> selected) {
for (Edge e = v.getFirstAdjacentEdge(); e != null; e = v.getNextAdjacentEdge(e)) {
Node w = e.getOpposite(v);
String label = ((NodeData) w.getData()).getLabel();
if (!selected.contains(label)) {
selected.add(label);
selectRec(w, selected);
}
}
}
/**
* gets all the labels shown in the graph
*
* @return labels
*/
public Set<String> getAllVisibleLabels() {
Set<String> labels = new HashSet<>();
for (Node v = graph.getFirstNode(); v != null; v = v.getNext()) {
labels.add(((NodeData) v.getData()).getLabel());
}
return labels;
}
@Override
public JToolBar getBottomToolBar() {
return new CoOccurrenceToolBar(viewer, this);
}
@Override
public ScalingType getScalingTypePreference() {
return ScalingType.SQRT;
}
@Override
public String getChartDrawerName() {
return NAME;
}
}
| 26,736 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetScaleByPercentCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SetScaleByPercentCommand.java | /*
* SetScaleByPercentCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import megan.util.ScalingType;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class SetScaleByPercentCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getChartDrawer() != null && chartViewer.getChartDrawer().getScalingType() == ScalingType.PERCENT;
}
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
execute("set chartScale=percent;");
}
public boolean isApplicable() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getChartData() != null && chartViewer.getChartDrawer() != null && chartViewer.getChartDrawer().isSupportedScalingType(ScalingType.PERCENT);
}
public String getName() {
return "Percentage Scale";
}
public String getDescription() {
return "Show values as percentage assigned";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Percent16.gif");
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,458 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetColorCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SetColorCommand.java | /*
* SetColorCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.director.IDirector;
import jloda.swing.util.ChooseColorDialog;
import jloda.swing.util.ColorUtilsSwing;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.ChartColorManager;
import megan.chart.gui.ChartViewer;
import megan.core.Director;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.HashSet;
import java.util.Set;
/**
* show all
* Daniel Huson, 7.2012
*/
public class SetColorCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
ChartViewer viewer = (ChartViewer) getViewer();
ChartColorManager chartColors = viewer.getChartColorManager();
np.matchIgnoreCase("set color=");
Color color = ColorUtilsSwing.convert(np.getColor());
String series = null;
if (np.peekMatchIgnoreCase("series")) {
np.matchIgnoreCase("series=");
series = np.getLabelRespectCase();
}
String className = null;
if (np.peekMatchIgnoreCase("class")) {
np.matchIgnoreCase("class=");
className = np.getLabelRespectCase();
}
np.matchIgnoreCase(";");
if (series != null)
chartColors.setSampleColor(series, color);
if (className != null)
chartColors.setClassColor(className, color);
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set color=<color> [series=<name>] [class=<name>];";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
ChartViewer viewer = (ChartViewer) getViewer();
ChartColorManager chartColors = viewer.getChartColorManager();
if (viewer.isSeriesTabSelected()) {
int count = viewer.getChartData().getChartSelection().getSelectedSeries().size();
Set<String> done = new HashSet<>();
for (String series : viewer.getChartData().getChartSelection().getSelectedSeries()) {
final ColorChooser chooser = new ColorChooser(viewer, "Change color for series '" + series + "'", series, null, chartColors, count - done.size() >= 2);
if (chooser.getResult() == null)
return; // canceled
else {
if (chooser.isApplyToAll()) {
Set<String> toDo = new HashSet<>(viewer.getChartData().getChartSelection().getSelectedSeries());
toDo.removeAll(done);
for (String label : toDo) {
chartColors.setSampleColor(label, chooser.getResult());
}
viewer.repaint();
break;
} else {
Color color = chartColors.getSampleColor(series);
if (!chooser.getResult().equals(color)) {
chartColors.setSampleColor(series, chooser.getResult());
done.add(series);
viewer.repaint();
}
}
}
}
((Director) getDir()).getDocument().setDirty(true);
getDir().notifyUpdateViewer(IDirector.TITLE);
} else // target equals classes
{
int count = viewer.getChartData().getChartSelection().getSelectedClasses().size();
Set<String> done = new HashSet<>();
for (String className : viewer.getChartData().getChartSelection().getSelectedClasses()) {
final ColorChooser chooser = new ColorChooser(viewer, "Change color for class '" + className + "'",
viewer.getChartData().getDataSetName(), className, chartColors, count - done.size() >= 2);
if (chooser.getResult() == null)
return; // canceled
else {
if (chooser.isApplyToAll()) {
Set<String> toDo = new HashSet<>(viewer.getChartData().getChartSelection().getSelectedClasses());
toDo.removeAll(done);
for (String label : toDo) {
chartColors.setClassColor(viewer.getClass2HigherClassMapper().get(label), chooser.getResult());
}
viewer.repaint();
break;
} else {
Color color = chartColors.getClassColor(viewer.getClass2HigherClassMapper().get(className));
if (!chooser.getResult().equals(color)) {
chartColors.setClassColor(viewer.getClass2HigherClassMapper().get(className), chooser.getResult());
done.add(className);
viewer.repaint();
}
}
}
}
((Director) getDir()).getDocument().setDirty(true);
getDir().notifyUpdateViewer(IDirector.TITLE);
}
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Set Color...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Set the color of a series or class";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("YellowSquare16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
ChartViewer viewer = (ChartViewer) getViewer();
return (viewer.isSeriesTabSelected() && viewer.getChartData().getChartSelection().getSelectedSeries().size() > 0)
|| (!viewer.isSeriesTabSelected() && viewer.getChartData().getChartSelection().getSelectedClasses().size() > 0);
}
static class ColorChooser extends JDialog {
Color result;
private boolean applyToAll = false;
/**
* constructor
*
*/
ColorChooser(ChartViewer viewer, String message, String series, String className, ChartColorManager colors, boolean showApplyToAll) {
super(viewer.getFrame());
setSize(500, 400);
setModal(true);
setLocationRelativeTo(viewer.getFrame());
getContentPane().setLayout(new BorderLayout());
JLabel header = new JLabel(message);
getContentPane().add(header, BorderLayout.NORTH);
if (className == null)
result = colors.getSampleColor(series);
else
result = colors.getClassColor(viewer.getClass2HigherClassMapper().get(className));
final JColorChooser colorChooser = ChooseColorDialog.colorChooser;
colorChooser.setColor(result);
getContentPane().add(colorChooser, BorderLayout.CENTER);
JPanel buttons = new JPanel();
buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
JButton doneButton = new JButton(new AbstractAction("Done") {
public void actionPerformed(ActionEvent actionEvent) {
result = null;
ColorChooser.this.setVisible(false);
}
});
doneButton.setToolTipText("Close the dialog");
buttons.add(Box.createHorizontalGlue());
buttons.add(doneButton);
if (showApplyToAll) {
JButton applyToAllButton = new JButton(new AbstractAction("Apply To All") {
public void actionPerformed(ActionEvent actionEvent) {
result = colorChooser.getColor();
applyToAll = true;
ColorChooser.this.setVisible(false);
}
});
applyToAllButton.setToolTipText("Apply to all remaining selected items");
buttons.add(applyToAllButton);
}
JButton applyButton = new JButton(new AbstractAction("Apply") {
public void actionPerformed(ActionEvent actionEvent) {
result = colorChooser.getColor();
ColorChooser.this.setVisible(false);
}
});
applyButton.setToolTipText("Apply to current item");
buttons.add(applyButton);
getContentPane().add(buttons, BorderLayout.SOUTH);
setVisible(true);
}
Color getResult() {
return result;
}
boolean isApplyToAll() {
return applyToAll;
}
}
}
| 10,413 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowClusteringCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/ShowClusteringCommand.java | /*
* ShowClusteringCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.cluster.ClusteringTree;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.LabelsJList;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ShowClusteringCommand extends CommandBase implements ICheckBoxCommand {
@Override
public boolean isSelected() {
if (!isApplicable())
return false;
final ChartViewer chartViewer = (ChartViewer) getViewer();
return switch (chartViewer.getActiveLabelsJList().getName().toLowerCase()) {
case "series" -> chartViewer.getSeriesList().isDoClustering();
case "classes" -> chartViewer.getClassesList().isDoClustering();
case "attributes" -> chartViewer.getAttributesList().isDoClustering();
default -> false;
};
}
public String getSyntax() {
return "cluster what={series|classes|attributes} state={true|false};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("cluster what=");
final String what = np.getWordMatchesIgnoringCase("series classes attributes");
np.matchIgnoreCase("state=");
final boolean state = np.getBoolean();
np.matchIgnoreCase(";");
final ChartViewer chartViewer = (ChartViewer) getViewer();
if (what.equalsIgnoreCase("series"))
chartViewer.getSeriesList().setDoClustering(state);
if (what.equalsIgnoreCase("classes"))
chartViewer.getClassesList().setDoClustering(state);
if (what.equalsIgnoreCase("attributes"))
chartViewer.getAttributesList().setDoClustering(state);
}
public void actionPerformed(ActionEvent event) {
final ChartViewer viewer = (ChartViewer) getViewer();
final LabelsJList list = viewer.getActiveLabelsJList();
execute("cluster what=" + list.getName() + " state=" + !list.isDoClustering() + ";");
}
public boolean isApplicable() {
final ChartViewer viewer = (ChartViewer) getViewer();
final LabelsJList list = viewer.getActiveLabelsJList();
if (list != null && viewer.getChartDrawer() != null) {
switch (list.getName().toLowerCase()) {
case "series":
return viewer.getChartDrawer().canCluster(ClusteringTree.TYPE.SERIES);
case "classes":
return viewer.getChartDrawer().canCluster(ClusteringTree.TYPE.CLASSES);
case "attributes":
return viewer.getChartDrawer().canCluster(ClusteringTree.TYPE.ATTRIBUTES);
}
}
return false;
}
public String getName() {
return "Cluster";
}
public KeyStroke getAcceleratorKey() {
return null;
}
public String getDescription() {
return "Turn clustering on or off";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Cluster16.gif");
}
public boolean isCritical() {
return true;
}
}
| 4,031 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetCountsLabelCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SetCountsLabelCommand.java | /*
* SetCountsLabelCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* set series label
* Daniel Huson, 6.2012
*/
public class SetCountsLabelCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "set countsLabel=<label>;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set countsLabel=");
String label = np.getLabelRespectCase();
np.matchIgnoreCase(";");
ChartViewer chartViewer = (ChartViewer) getViewer();
chartViewer.getChartData().setCountsLabel(label);
chartViewer.repaint();
}
public void actionPerformed(ActionEvent event) {
ChartViewer viewer = (ChartViewer) getViewer();
String result = JOptionPane.showInputDialog(viewer.getFrame(), "Set Counts Label", viewer.getChartData().getCountsLabel());
if (result != null)
execute("set countsLabel='" + result.replaceAll("'", "\"") + "';");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Set Counts Label...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Preferences16.gif");
}
public String getDescription() {
return "Set the counts label of the data set";
}
public boolean isCritical() {
return false;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,504 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowXAxisCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/ShowXAxisCommand.java | /*
* ShowXAxisCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* show x axis
* Daniel Huson, 6.2012
*/
public class ShowXAxisCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return isApplicable() && chartViewer.isShowXAxis();
}
public String getSyntax() {
return "show xAxis={true|false};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("show xAxis=");
boolean show = np.getBoolean();
np.matchIgnoreCase(";");
ChartViewer chartViewer = (ChartViewer) getViewer();
chartViewer.setShowXAxis(show);
chartViewer.repaint();
}
public void actionPerformed(ActionEvent event) {
executeImmediately("show xAxis=" + (!isSelected()) + ";");
}
public boolean isApplicable() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getChartDrawer() != null && chartViewer.getChartDrawer().canShowXAxis();
}
public String getName() {
return "Show x-Axis";
}
public String getDescription() {
return "Show the x-axis";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,534 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CopyLabelCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/CopyLabelCommand.java | /*
* CopyLabelCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.LabelsJList;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
/**
* copy the currently selected labels
* Daniel Huson, DATE
*/
public class CopyLabelCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Copy";
}
public String getAltName() {
return "Copy Label";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Copy selected labels";
}
/**
* 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 null;
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
ChartViewer chartViewer = (ChartViewer) getViewer();
LabelsJList list = chartViewer.getActiveLabelsJList();
StringBuilder buf = new StringBuilder();
int count = list.getSelectedLabels().size();
for (String label : list.getSelectedLabels()) {
buf.append(label);
if (count > 1)
buf.append("\n");
}
if (buf.toString().length() > 0) {
StringSelection selection = new StringSelection(buf.toString());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, 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() {
ChartViewer chartViewer = (ChartViewer) getViewer();
LabelsJList list = chartViewer.getActiveLabelsJList();
return list != null && !list.isSelectionEmpty();
}
}
| 3,711 | 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/chart/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.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.export.TransferableGraphic;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class CopyImageCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
ChartViewer chartViewer = (ChartViewer) getViewer();
TransferableGraphic tg = new TransferableGraphic(chartViewer.getContentPanel(), chartViewer.getScrollPane());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(tg, tg);
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Copy Image";
}
public String getDescription() {
return "Copy image to clipboard";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Copy16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | java.awt.event.InputEvent.SHIFT_DOWN_MASK);
}
}
| 2,283 | 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/chart/commands/ExpandHorizontalCommand.java | /*
* ExpandHorizontalCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class ExpandHorizontalCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "expand direction={horizontal|vertical};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("expand direction=");
String direction = np.getWordMatchesIgnoringCase("horizontal vertical");
np.matchIgnoreCase(";");
ChartViewer chartViewer = (ChartViewer) getViewer();
Point center = chartViewer.getZoomCenter();
if (direction.equalsIgnoreCase("horizontal"))
chartViewer.zoom(1.2f, 1, center);
else if (direction.equalsIgnoreCase("vertical"))
chartViewer.zoom(1, 1.2f, center);
}
public void actionPerformed(ActionEvent event) {
executeImmediately("expand direction=horizontal;");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Expand Horizontal";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("ExpandHorizontal16.gif");
}
public String getDescription() {
return "Expand view";
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 2,657 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetScaleByLogCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SetScaleByLogCommand.java | /*
* SetScaleByLogCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import megan.util.ScalingType;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class SetScaleByLogCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getChartDrawer() != null && chartViewer.getScalingType() == ScalingType.LOG;
}
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
execute("set chartScale=log;");
}
public boolean isApplicable() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getChartData() != null && chartViewer.getChartDrawer() != null && chartViewer.getChartDrawer().isSupportedScalingType(ScalingType.LOG);
}
public String getName() {
return "Log Scale";
}
public String getDescription() {
return "Show values on log scale";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("LogScale16.gif");
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,405 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ColorByRankCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/ColorByRankCommand.java | /*
* ColorByRankCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ProgramProperties;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.chart.TaxaChart;
import megan.chart.data.IChartData;
import megan.chart.gui.ChartViewer;
import megan.viewer.TaxonomicLevels;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ColorByRankCommand extends CommandBase implements ICheckBoxCommand {
private final String[] ranks = new String[]{TaxonomicLevels.Domain, TaxonomicLevels.Phylum, TaxonomicLevels.Class,
TaxonomicLevels.Order, TaxonomicLevels.Family, TaxonomicLevels.Genus, TaxonomicLevels.Species, "None"};
@Override
public boolean isSelected() {
return isApplicable() && ((TaxaChart) getViewer()).getColorByRank() != null && !((TaxaChart) getViewer()).getColorByRank().equalsIgnoreCase("none");
}
public String getSyntax() {
return "colorBy rank={" + StringUtils.toString(ranks, "|") + "};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("colorBy rank=");
String rank = np.getWordMatchesRespectingCase(StringUtils.toString(ranks, " "));
np.matchIgnoreCase(";");
if (rank != null) {
ChartViewer chartViewer = (ChartViewer) getViewer();
if (chartViewer instanceof TaxaChart) {
TaxaChart taxaChart = (TaxaChart) chartViewer;
taxaChart.setColorByRank(rank);
taxaChart.updateColorByRank();
}
chartViewer.repaint();
}
}
public void actionPerformed(ActionEvent event) {
ChartViewer chartViewer = (ChartViewer) getViewer();
String choice = ranks[ranks.length - 1];
if (chartViewer instanceof TaxaChart) {
TaxaChart taxaChart = (TaxaChart) chartViewer;
if (taxaChart.getColorByRank() != null)
choice = taxaChart.getColorByRank();
}
String result = (String) JOptionPane.showInputDialog(getViewer().getFrame(), "Choose rank for coloring", "Choose colors", JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon(), ranks, choice);
if (result != null)
execute("colorBy rank=" + result + ";");
}
public boolean isApplicable() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer != null && chartViewer.getChartDrawer() != null && chartViewer.getChartDrawer().canColorByRank() && chartViewer.getChartData() instanceof IChartData && chartViewer instanceof TaxaChart;
}
public static final String NAME = "Color Taxa by Rank...";
public String getName() {
return NAME;
}
public String getDescription() {
return "Color classes by taxonomic rank";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 4,006 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
HideSelectedCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/HideSelectedCommand.java | /*
* HideSelectedCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* show all
* Daniel Huson, 7.2012
*/
public class HideSelectedCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute("hide what=selected;");
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Hide Selected";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Hide selected data items";
}
/**
* 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_U, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | java.awt.event.InputEvent.SHIFT_DOWN_MASK);
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
final ChartViewer viewer = (ChartViewer) getViewer();
return viewer.getActiveLabelsJList() != null && viewer.getActiveLabelsJList().getSelectedIndex() != -1;
}
}
| 3,067 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SortByAssignedUpCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SortByAssignedUpCommand.java | /*
* SortByAssignedUpCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.LabelsJList;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class SortByAssignedUpCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
execute("set sort=up;");
}
public boolean isApplicable() {
final LabelsJList list = ((ChartViewer) getViewer()).getActiveLabelsJList();
return list != null && list.isEnabled() && !list.isDoClustering();
}
public String getName() {
return "Sort By Values (Up)";
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
public String getDescription() {
return "Sort the list of entries by increasing number of assigned reads";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("SortNrHitsBackward16.gif");
}
public boolean isCritical() {
return true;
}
}
| 2,219 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetScaleLinearCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SetScaleLinearCommand.java | /*
* SetScaleLinearCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import megan.util.ScalingType;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class SetScaleLinearCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getChartDrawer() != null && chartViewer.getScalingType() == ScalingType.LINEAR;
}
public String getSyntax() {
return "set chartScale={" + StringUtils.toString(ScalingType.values(), "|") + "};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set chartScale=");
String scale = np.getWordMatchesIgnoringCase(StringUtils.toString(ScalingType.values(), " "));
np.matchIgnoreCase(";");
final ChartViewer chartViewer = (ChartViewer) getViewer();
chartViewer.setScalingType(ScalingType.valueOf(scale.toUpperCase()));
chartViewer.repaint();
}
public void actionPerformed(ActionEvent event) {
execute("set chartScale=linear;");
}
public boolean isApplicable() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getChartData() != null && chartViewer.getChartDrawer() != null && chartViewer.getChartDrawer().isSupportedScalingType(ScalingType.LINEAR);
}
public String getName() {
return "Linear Scale";
}
public String getDescription() {
return "Show values on a linear scale";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("LinScale16.gif");
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,897 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowVerticalGridLinesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/ShowVerticalGridLinesCommand.java | /*
* ShowVerticalGridLinesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.chart.drawers.BarChartDrawer;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* show vertical grid lines in bar chart
* Daniel Huson, 1.2016
*/
public class ShowVerticalGridLinesCommand extends CommandBase implements ICheckBoxCommand {
@Override
public boolean isSelected() {
return getViewer() instanceof ChartViewer && ((ChartViewer) getViewer()).isShowVerticalGridLines();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("show gridLines=");
boolean show = np.getBoolean();
np.matchIgnoreCase(";");
if (getViewer() instanceof ChartViewer) {
((ChartViewer) getViewer()).setShowVerticalGridLines(show);
}
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "show gridLines={true|false}";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute("show gridLines=" + (!isSelected()) + ";");
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Grid Lines";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Show grid lines";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getViewer() instanceof ChartViewer && ((ChartViewer) getViewer()).getChartDrawer() instanceof BarChartDrawer;
}
}
| 3,405 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
HideAllCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/HideAllCommand.java | /*
* HideAllCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.chart.data.IChartData;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.LabelsJList;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.HashSet;
import java.util.Set;
/**
* show all
* Daniel Huson, 7.2012
*/
public class HideAllCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
ChartViewer viewer = (ChartViewer) getViewer();
np.matchIgnoreCase("hide what=");
final String what = np.getWordMatchesIgnoringCase("all none selected unselected");
final LabelsJList list;
if (np.peekMatchIgnoreCase("target=")) {
np.matchIgnoreCase("target=");
list = viewer.getLabelsJList(np.getWordMatchesIgnoringCase("series classes attributes"));
} else {
list = viewer.getActiveLabelsJList();
}
np.matchIgnoreCase(";");
if (what.equalsIgnoreCase("none")) {
list.enableLabels(list.getAllLabels());
} else if (what.equalsIgnoreCase("selected")) {
list.disableLabels(list.getSelectedLabels());
} else if (what.equalsIgnoreCase("unselected")) {
final Set<String> labels = new HashSet<>(list.getAllLabels());
list.getSelectedLabels().forEach(labels::remove);
list.disableLabels(labels);
} else // all
{
list.disableLabels(list.getAllLabels());
}
if (list.getName().equalsIgnoreCase("series"))
viewer.getChartData().setEnabledSeries(list.getEnabledLabels());
else if (list.getName().equalsIgnoreCase("classes"))
((IChartData) viewer.getChartData()).setEnabledClassNames(list.getEnabledLabels());
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "hide what={all|none|selected} [target={series|classes|attributes}];";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute("hide what=all;");
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Hide All";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Hide data items";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
}
| 4,261 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetChartTitleFontCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SetChartTitleFontCommand.java | /*
* SetChartTitleFontCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.ChooseFontDialog;
import jloda.swing.util.ColorUtilsSwing;
import jloda.swing.util.ProgramProperties;
import jloda.util.Pair;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* set font
* Daniel Huson, 9.2012
*/
public class SetChartTitleFontCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
ChartViewer chartViewer = (ChartViewer) getViewer();
String target = ChartViewer.FontKeys.TitleFont.toString();
Font font = ProgramProperties.get(target, ChartViewer.defaultFont);
Color color = ProgramProperties.get(target + "Color", (Color) null);
Pair<Font, Color> result = ChooseFontDialog.showChooseFontDialog(chartViewer.getFrame(), "Choose title font", font, color);
if (result != null)
execute("set chartFont='" + BasicSwing.encode(result.getFirst())
+ "' color=" + (result.getSecond() != null ? ColorUtilsSwing.toString3Int(result.getSecond()) : "default") + " target='" + target + "';");
}
public boolean isApplicable() {
ChartViewer viewer = (ChartViewer) getViewer();
return viewer != null;
}
public String getName() {
return "Title Font...";
}
public ImageIcon getIcon() {
return null;
}
public String getDescription() {
return "Set the font used for the title";
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,712 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowYAxisCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/ShowYAxisCommand.java | /*
* ShowYAxisCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* show Y axis
* Daniel Huson, 6.2012
*/
public class ShowYAxisCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return isApplicable() && chartViewer.isShowYAxis();
}
public String getSyntax() {
return "show yAxis={true|false};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("show yAxis=");
boolean show = np.getBoolean();
np.matchIgnoreCase(";");
ChartViewer chartViewer = (ChartViewer) getViewer();
chartViewer.setShowYAxis(show);
chartViewer.repaint();
}
public void actionPerformed(ActionEvent event) {
executeImmediately("show yAxis=" + (!isSelected()) + ";");
}
public boolean isApplicable() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getChartDrawer() != null && chartViewer.getChartDrawer().canShowYAxis();
}
public String getName() {
return "Show y-Axis";
}
public String getDescription() {
return "Show the y-axis";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,534 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SortAlphabeticallyBackwardCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SortAlphabeticallyBackwardCommand.java | /*
* SortAlphabeticallyBackwardCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.LabelsJList;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class SortAlphabeticallyBackwardCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
execute("set sort=alphaBackward;");
}
public boolean isApplicable() {
final LabelsJList list = ((ChartViewer) getViewer()).getActiveLabelsJList();
return list != null && list.isEnabled() && !list.isDoClustering();
}
public String getName() {
return "Sort Alphabetically Backward";
}
public KeyStroke getAcceleratorKey() {
return null;
}
public String getDescription() {
return "Sort the list of entries backward";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("SortAlphaBackward16.gif");
}
public boolean isCritical() {
return true;
}
}
| 2,085 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetClassesLabelCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SetClassesLabelCommand.java | /*
* SetClassesLabelCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* set series label
* Daniel Huson, 6.2012
*/
public class SetClassesLabelCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "set classesLabel=<label>;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set classesLabel=");
String label = np.getLabelRespectCase();
np.matchIgnoreCase(";");
ChartViewer chartViewer = (ChartViewer) getViewer();
chartViewer.getChartData().setClassesLabel(label);
chartViewer.repaint();
}
public void actionPerformed(ActionEvent event) {
ChartViewer viewer = (ChartViewer) getViewer();
String result = JOptionPane.showInputDialog(viewer.getFrame(), "Set Classes Label", viewer.getChartData().getClassesLabel());
if (result != null)
execute("set classesLabel='" + result.replaceAll("'", "\"") + "';");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Set Classes Label...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Preferences16.gif");
}
public String getDescription() {
return "Set the classes label of the data set";
}
public boolean isCritical() {
return false;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,514 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowValuesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/ShowValuesCommand.java | /*
* ShowValuesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class ShowValuesCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return isApplicable() && chartViewer.isShowValues();
}
public String getSyntax() {
return "show values={true|false};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("show values=");
boolean value = np.getBoolean();
np.matchIgnoreCase(";");
ChartViewer chartViewer = (ChartViewer) getViewer();
chartViewer.setShowValues(value);
chartViewer.repaint();
}
public void actionPerformed(ActionEvent event) {
executeImmediately("show values='" + (!isSelected()) + "';");
}
public boolean isApplicable() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getChartDrawer() != null && chartViewer.getChartDrawer().canShowValues();
}
public String getName() {
return "Show Values";
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | java.awt.event.InputEvent.SHIFT_DOWN_MASK);
}
public String getDescription() {
return "Show values as text";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
}
| 2,582 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetChartValuesFontCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SetChartValuesFontCommand.java | /*
* SetChartValuesFontCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.ChooseFontDialog;
import jloda.swing.util.ColorUtilsSwing;
import jloda.swing.util.ProgramProperties;
import jloda.util.Pair;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* set font
* Daniel Huson, 9.2012
*/
public class SetChartValuesFontCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
ChartViewer chartViewer = (ChartViewer) getViewer();
String target = ChartViewer.FontKeys.ValuesFont.toString();
Font font = ProgramProperties.get(target, ChartViewer.defaultFont);
Color color = ProgramProperties.get(target + "Color", (Color) null);
Pair<Font, Color> result = ChooseFontDialog.showChooseFontDialog(chartViewer.getFrame(), "Choose values font", font, color);
if (result != null)
execute("set chartFont='" + BasicSwing.encode(result.getFirst())
+ "' color=" + (result.getSecond() != null ? ColorUtilsSwing.toString3Int(result.getSecond()) : "default") + " target='" + target + "';");
}
public boolean isApplicable() {
ChartViewer viewer = (ChartViewer) getViewer();
return viewer != null;
}
public String getName() {
return "Values Font...";
}
public ImageIcon getIcon() {
return null;
}
public String getDescription() {
return "Set the font used for values";
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,714 | 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/chart/commands/ContractHorizontalCommand.java | /*
* ContractHorizontalCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class ContractHorizontalCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "contract direction={horizontal|vertical};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("contract direction=");
String direction = np.getWordMatchesIgnoringCase("horizontal vertical");
np.matchIgnoreCase(";");
ChartViewer chartViewer = (ChartViewer) getViewer();
if (direction.equalsIgnoreCase("horizontal"))
chartViewer.zoom(1f / 1.2f, 1, chartViewer.getZoomCenter());
else if (direction.equalsIgnoreCase("vertical"))
chartViewer.zoom(1, 1f / 1.2f, chartViewer.getZoomCenter());
}
public void actionPerformed(ActionEvent event) {
executeImmediately("contract direction=horizontal;");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Contract Horizontal";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("ContractHorizontal16.gif");
}
public String getDescription() {
return "Contract view";
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 2,673 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetLabelStandardCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SetLabelStandardCommand.java | /*
* SetLabelStandardCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class SetLabelStandardCommand extends CommandBase implements ICheckBoxCommand {
@Override
public boolean isSelected() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getClassLabelAngle() == 0;
}
public String getSyntax() {
return "set labelOrientation={standard|up45|up90|down45|down90};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set labelOrientation=");
String what = np.getWordMatchesIgnoringCase("standard up45 up90 down45 down90");
np.matchIgnoreCase(";");
ChartViewer chartViewer = (ChartViewer) getViewer();
switch (what) {
case "standard" -> chartViewer.setClassLabelAngle(0);
case "up45" -> chartViewer.setClassLabelAngle(-Math.PI / 4);
case "up90" -> chartViewer.setClassLabelAngle(Math.PI / 2);
case "down45" -> chartViewer.setClassLabelAngle(Math.PI / 4);
case "down90" -> chartViewer.setClassLabelAngle(-Math.PI / 2);
}
}
public boolean isApplicable() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getChartDrawer() != null && chartViewer.getChartDrawer().canShowXAxis();
}
public boolean isCritical() {
return true;
}
public void actionPerformed(ActionEvent event) {
execute("set labelOrientation=standard;");
}
public String getName() {
return "Labels Standard";
}
public KeyStroke getAcceleratorKey() {
return null;
}
public String getDescription() {
return "Category labels drawn standard";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("LabelsStandard16.gif");
}
}
| 2,908 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetChartYAxisFontCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SetChartYAxisFontCommand.java | /*
* SetChartYAxisFontCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.ChooseFontDialog;
import jloda.swing.util.ColorUtilsSwing;
import jloda.swing.util.ProgramProperties;
import jloda.util.Pair;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* set font
* Daniel Huson, 9.2012
*/
public class SetChartYAxisFontCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
ChartViewer chartViewer = (ChartViewer) getViewer();
String target = ChartViewer.FontKeys.YAxisFont.toString();
Font font = ProgramProperties.get(target, ChartViewer.defaultFont);
Color color = ProgramProperties.get(target + "Color", (Color) null);
Pair<Font, Color> result = ChooseFontDialog.showChooseFontDialog(chartViewer.getFrame(), "Choose y-axis font", font, color);
if (result != null)
execute("set chartFont='" + BasicSwing.encode(result.getFirst())
+ "' color=" + (result.getSecond() != null ? ColorUtilsSwing.toString3Int(result.getSecond()) : "default") + " target='" + target + "';");
}
public boolean isApplicable() {
ChartViewer viewer = (ChartViewer) getViewer();
return viewer != null;
}
public String getName() {
return "Y-Axis Font...";
}
public ImageIcon getIcon() {
return null;
}
public String getDescription() {
return "Set the font used for the y-axis";
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,715 | 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/chart/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.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class SyncCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "sync;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
ChartViewer chartViewer = (ChartViewer) getViewer();
chartViewer.sync();
chartViewer.zoomToFit();
}
public void actionPerformed(ActionEvent event) {
execute(getSyntax());
}
public boolean isApplicable() {
return true;
}
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,129 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ClusterAttributesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/ClusterAttributesCommand.java | /*
* ClusterAttributesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.cluster.ClusteringTree;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ClusterAttributesCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
final ChartViewer chartViewer = (ChartViewer) getViewer();
return isApplicable() && chartViewer.getAttributesList().isDoClustering();
}
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
execute("cluster what=attributes state=" + !isSelected() + ";");
}
public boolean isApplicable() {
final ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getChartDrawer() != null && chartViewer.getChartDrawer().canCluster(ClusteringTree.TYPE.ATTRIBUTES);
}
public String getName() {
return "Cluster Attributes";
}
public KeyStroke getAcceleratorKey() {
return null;
}
public String getDescription() {
return "Cluster attributes";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Cluster16.gif");
}
public boolean isCritical() {
return true;
}
}
| 2,311 | 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/chart/commands/ContractVerticalCommand.java | /*
* ContractVerticalCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class ContractVerticalCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
executeImmediately("contract direction=vertical;");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Contract Vertical";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("ContractVertical16.gif");
}
public String getDescription() {
return "Contract view vertically";
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 2,098 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
HideUnselectedCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/HideUnselectedCommand.java | /*
* HideUnselectedCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* show all
* Daniel Huson, 7.2012
*/
public class HideUnselectedCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute("hide what=unSelected;");
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Hide Unselected";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Hide unselected data items";
}
/**
* 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_U, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
final ChartViewer viewer = (ChartViewer) getViewer();
return viewer.getActiveLabelsJList() != null && viewer.getActiveLabelsJList().getSelectedIndex() != -1;
}
}
| 3,033 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowInternalLabelsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/ShowInternalLabelsCommand.java | /*
* ShowInternalLabelsCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ShowInternalLabelsCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return isApplicable() && chartViewer.isShowInternalLabels();
}
public String getSyntax() {
return "show internalLabels={true|false};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("show internalLabels=");
boolean value = np.getBoolean();
np.matchIgnoreCase(";");
ChartViewer chartViewer = (ChartViewer) getViewer();
chartViewer.setShowInternalLabels(value);
chartViewer.repaint();
}
public void actionPerformed(ActionEvent event) {
executeImmediately("show internalLabels='" + (!isSelected()) + "';");
}
public boolean isApplicable() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getChartDrawer() != null && chartViewer.getChartDrawer().canShowInternalLabels();
}
public String getName() {
return "Show Internal Labels";
}
public KeyStroke getAcceleratorKey() {
return null;
}
public String getDescription() {
return "Show internal labels in Radial Chart";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
}
| 2,488 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportDataCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/ExportDataCommand.java | /*
* ExportDataCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.util.TextFileFilter;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.FileUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* export data command
* Daniel Huson, 11.2010
*/
public class ExportDataCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "export what=chartData file=<filename>;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("export what=chartData file=");
String fileName = np.getAbsoluteFileName();
np.matchIgnoreCase(";");
try {
ChartViewer chartViewer = (ChartViewer) getViewer();
FileWriter w = new FileWriter(fileName);
chartViewer.getChartDrawer().writeData(w);
w.close();
} catch (IOException e) {
NotificationsInSwing.showError("Export Data failed: " + e.getMessage());
}
}
public void actionPerformed(ActionEvent event) {
ChartViewer viewer = (ChartViewer) getViewer();
String name = StringUtils.toCleanName(viewer.getChartData().getDataSetName()) + "-chart";
String lastOpenFile = ProgramProperties.get("DataFile", "");
if (lastOpenFile == null)
lastOpenFile = name + ".txt";
else
lastOpenFile = (new File((new File(lastOpenFile)).getParent(), name)).getPath();
File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), new File(lastOpenFile), new TextFileFilter(), new TextFileFilter(), event, "Save data file", ".txt");
if (file != null) {
if (FileUtils.getFileSuffix(file.getName()) == null)
file = FileUtils.replaceFileSuffix(file, ".txt");
ProgramProperties.put("DataFile", file.getPath());
execute("export what=chartData file='" + file.getPath() + "';");
}
}
// if in ask to save, modify event source to tell calling method can see that user has canceled
void replyUserHasCanceledInAskToSave(ActionEvent event) {
((Boolean[]) event.getSource())[0] = true;
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Export Data...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/SaveAs16.gif");
}
public String getDescription() {
return "Export data to a file";
}
public boolean isCritical() {
return false;
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_D, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 3,905 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectTopCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SelectTopCommand.java | /*
* SelectTopCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.NumberUtils;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.LabelsJList;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* select all series
* Daniel Huson, 7.2012
*/
public class SelectTopCommand extends CommandBase implements ICommand {
static private int previousValue = 10;
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("select top=");
int number = np.getInt(0, Integer.MAX_VALUE);
np.matchIgnoreCase(";");
final ChartViewer viewer = (ChartViewer) getViewer();
final LabelsJList list = viewer.getActiveLabelsJList();
list.selectTop(number);
viewer.repaint();
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "select top=<number>;";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
final ChartViewer viewer = (ChartViewer) getViewer();
final LabelsJList list = viewer.getActiveLabelsJList();
previousValue = Math.min(list.getAllLabels().size(), previousValue);
final String result = JOptionPane.showInputDialog(viewer.getFrame(), "Set number of top items to select", previousValue);
if (result != null && NumberUtils.isInteger(result)) {
execute("select top='" + result + "';");
previousValue = NumberUtils.parseInt(result);
}
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Select Top...";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Select top items only";
}
/**
* 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_T, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | java.awt.event.InputEvent.SHIFT_DOWN_MASK);
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
}
| 3,825 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetScaleBySqrtCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SetScaleBySqrtCommand.java | /*
* SetScaleBySqrtCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import megan.util.ScalingType;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class SetScaleBySqrtCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getChartDrawer() != null && chartViewer.getScalingType() == ScalingType.SQRT;
}
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
execute("set chartScale=sqrt;");
}
public boolean isApplicable() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getChartData() != null && chartViewer.getChartDrawer() != null && chartViewer.getChartDrawer().isSupportedScalingType(ScalingType.SQRT);
}
public String getName() {
return "Sqrt Scale";
}
public String getDescription() {
return "Show values on square-root scale";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("SqrtScale16.gif");
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,420 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectFromPreviousWindowCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SelectFromPreviousWindowCommand.java | /*
* SelectFromPreviousWindowCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* select from previous window
* Daniel Huson, 7.2012
*/
public class SelectFromPreviousWindowCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute("select what=previous;");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "From Previous Window";
}
public String getDescription() {
return "Select from previous window";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Empty16.gif");
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_P, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 2,389 | 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/chart/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.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.chart.data.IChartData;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* select all series
* Daniel Huson, 7.2012
*/
public class SelectNoneCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute("select what=none;");
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Select None";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Deselect all";
}
/**
* 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() | java.awt.event.InputEvent.SHIFT_DOWN_MASK);
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
ChartViewer viewer = (ChartViewer) getViewer();
return (viewer.isSeriesTabSelected() && viewer.getChartSelection().getSelectedSeries().size() > 0)
|| (!viewer.isSeriesTabSelected() && viewer.getChartData() instanceof IChartData
&& viewer.getChartSelection().getSelectedClasses().size() > 0)
|| (viewer.getChartData() instanceof IChartData && viewer.getChartSelection().getSelectedAttributes().size() > 0);
}
}
| 3,390 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowLegendCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/ShowLegendCommand.java | /*
* ShowLegendCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class ShowLegendCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return isApplicable() && !chartViewer.getShowLegend().equals("none");
}
public String getSyntax() {
return "show chartLegend={horizontal|vertical|none};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("show chartLegend=");
String value = np.getWordMatchesIgnoringCase("horizontal vertical none");
np.matchIgnoreCase(";");
ChartViewer chartViewer = (ChartViewer) getViewer();
chartViewer.setShowLegend(value);
}
public void actionPerformed(ActionEvent event) {
String legend = ((ChartViewer) getViewer()).getShowLegend();
switch (legend) {
case "none" -> executeImmediately("show chartLegend=horizontal;");
case "horizontal" -> executeImmediately("show chartLegend=vertical;");
case "vertical" -> executeImmediately("show chartLegend=none;");
}
}
public boolean isApplicable() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getChartDrawer() != null && chartViewer.getChartDrawer().canShowLegend();
}
public String getName() {
return "Show Legend";
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_J, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | java.awt.event.InputEvent.SHIFT_DOWN_MASK);
}
public String getDescription() {
return "Show chart legend";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Legend16.gif");
}
public boolean isCritical() {
return true;
}
}
| 2,981 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
UseJitterCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/UseJitterCommand.java | /*
* UseJitterCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.chart.drawers.Plot2DDrawer;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class UseJitterCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ChartViewer chartViewer = (ChartViewer) getViewer();
if (chartViewer.getChartDrawer() instanceof Plot2DDrawer) {
Plot2DDrawer drawer = (Plot2DDrawer) chartViewer.getChartDrawer();
for (String series : chartViewer.getChartData().getSeriesNames()) {
if (drawer.isUseJitter(series))
return true;
}
}
return false;
}
public String getSyntax() {
return "set jitter={false|true};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set jitter=");
boolean value = np.getBoolean();
np.matchIgnoreCase(";");
ChartViewer chartViewer = (ChartViewer) getViewer();
if (chartViewer.getChartDrawer() instanceof Plot2DDrawer) {
Plot2DDrawer drawer = (Plot2DDrawer) chartViewer.getChartDrawer();
for (String series : chartViewer.getChartData().getChartSelection().getSelectedSeries()) {
drawer.setUseJitter(series, value);
}
}
chartViewer.repaint();
}
public void actionPerformed(ActionEvent event) {
executeImmediately("set jitter='" + (!isSelected()) + "';");
}
public boolean isApplicable() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return (chartViewer.getChartDrawer() instanceof Plot2DDrawer) && chartViewer.getChartData().getChartSelection().getSelectedSeries().size() > 0;
}
public String getName() {
return "Use Jitter";
}
public KeyStroke getAcceleratorKey() {
return null;
}
public String getDescription() {
return "Jitter points in 2D plot to make them more visible";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
}
| 3,092 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ScaleByTotalSampleCountCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/ScaleByTotalSampleCountCommand.java | /*
* ScaleByTotalSampleCountCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.data.IChartData;
import megan.chart.gui.ChartViewer;
import megan.util.ScalingType;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ScaleByTotalSampleCountCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
final ChartViewer chartViewer = (ChartViewer) getViewer();
return (chartViewer.getChartData() instanceof IChartData) && ((IChartData) chartViewer.getChartData()).isUseTotalSize();
}
public String getSyntax() {
return "set usePercentOfTotal=<bool>;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set usePercentOfTotal=");
boolean use = np.getBoolean();
np.matchIgnoreCase(";");
final ChartViewer chartViewer = (ChartViewer) getViewer();
((IChartData) chartViewer.getChartData()).setUseTotalSize(use);
}
public void actionPerformed(ActionEvent event) {
execute("set usePercentOfTotal=" + (isApplicable() && !isSelected()) + ";");
}
public boolean isApplicable() {
final ChartViewer chartViewer = (ChartViewer) getViewer();
return (chartViewer.getChartData() != null && chartViewer.getChartData() instanceof IChartData) && ((IChartData) chartViewer.getChartData()).hasTotalSize()
&& chartViewer.getChartDrawer() != null && chartViewer.getChartDrawer().getScalingType() == ScalingType.PERCENT;
}
public String getName() {
return "Use Percent of Total";
}
public String getDescription() {
return "When selected, 'Percent' and 'Z-score' are based on total sample size, otherwise they are only based on total counts for selected nodes.";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Percent16.gif");
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 3,105 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SortByAssignedDownCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SortByAssignedDownCommand.java | /*
* SortByAssignedDownCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.LabelsJList;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class SortByAssignedDownCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
execute("set sort=down;");
}
public String getName() {
return "Sort By Values (Down)";
}
public boolean isApplicable() {
final LabelsJList list = ((ChartViewer) getViewer()).getActiveLabelsJList();
return list != null && list.isEnabled() && !list.isDoClustering();
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
public String getDescription() {
return "Sort the list of entries by decreasing number of assigned reads";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("SortNrHits16.gif");
}
public boolean isCritical() {
return true;
}
}
| 2,220 | 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/chart/commands/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.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ZoomToFitCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "zoom fit;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
ChartViewer chartViewer = (ChartViewer) getViewer();
chartViewer.zoomToFit();
}
public void actionPerformed(ActionEvent event) {
executeImmediately(getSyntax());
}
public String getName() {
return "Zoom To Fit";
}
public String getDescription() {
return "Zoom to fit";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/AlignCenter16.gif");
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,398 | 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/chart/commands/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.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.chart.drawers.RadialSpaceFillingTreeDrawer;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class RotateRightCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
executeImmediately("rotate direction=right;");
}
public boolean isApplicable() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getChartDrawer() instanceof RadialSpaceFillingTreeDrawer;
}
public String getName() {
return "Rotate Right";
}
public ImageIcon getIcon() {
return null;
}
public String getDescription() {
return "Rotate Radial Chart right";
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | java.awt.event.InputEvent.SHIFT_DOWN_MASK);
}
}
| 2,256 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetLabelUp90Command.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SetLabelUp90Command.java | /*
* SetLabelUp90Command.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class SetLabelUp90Command extends CommandBase implements ICheckBoxCommand {
@Override
public boolean isSelected() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getClassLabelAngle() == Math.PI / 2;
}
public String getSyntax() {
return null;
}
public void actionPerformed(ActionEvent event) {
execute("set labelorientation=up90;");
}
public String getName() {
return "Labels Up 90o";
}
public KeyStroke getAcceleratorKey() {
return null;
}
public String getDescription() {
return "Category labels drawn upward in 90o angle";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("LabelsUp9016.gif");
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getChartDrawer() != null && chartViewer.getChartDrawer().canShowXAxis();
}
}
| 2,586 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowAllCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/ShowAllCommand.java | /*
* ShowAllCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.chart.data.IChartData;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.LabelsJList;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* show all
* Daniel Huson, 7.2012
*/
public class ShowAllCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
ChartViewer viewer = (ChartViewer) getViewer();
np.matchIgnoreCase("show what=");
String what = np.getWordMatchesIgnoringCase("all none selected");
final LabelsJList list;
if (np.peekMatchIgnoreCase("target=")) {
np.matchIgnoreCase("target=");
list = viewer.getLabelsJList(np.getWordMatchesIgnoringCase("series classes attributes"));
} else {
list = viewer.getActiveLabelsJList();
}
np.matchIgnoreCase(";");
if (what.equalsIgnoreCase("none")) {
list.disableLabels(list.getAllLabels());
} else if (what.equalsIgnoreCase("selected")) {
list.enableLabels(list.getSelectedLabels());
} else // all
{
list.enableLabels(list.getAllLabels());
}
if (list.getName().equalsIgnoreCase("series"))
viewer.getChartData().setEnabledSeries(list.getEnabledLabels());
else if (list.getName().equalsIgnoreCase("classes"))
((IChartData) viewer.getChartData()).setEnabledClassNames(list.getEnabledLabels());
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "show what={all|none|selected} [target={series|classes|attributes}];";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute("show what=all;");
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Show All";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Show data items";
}
/**
* 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());
}
/**
* 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() {
final LabelsJList list = ((ChartViewer) getViewer()).getActiveLabelsJList();
return list != null && list.getDisabledLabels().size() > 0;
}
}
| 4,235 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetSeriesLabelCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SetSeriesLabelCommand.java | /*
* SetSeriesLabelCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* set series label
* Daniel Huson, 6.2012
*/
public class SetSeriesLabelCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "set seriesLabel=<label>;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set seriesLabel=");
String label = np.getLabelRespectCase();
np.matchIgnoreCase(";");
ChartViewer chartViewer = (ChartViewer) getViewer();
chartViewer.getChartData().setSeriesLabel(label);
chartViewer.repaint();
}
public void actionPerformed(ActionEvent event) {
ChartViewer viewer = (ChartViewer) getViewer();
String result = JOptionPane.showInputDialog(viewer.getFrame(), "Set Series Label", viewer.getChartData().getSeriesLabel());
if (result != null)
execute("set seriesLabel='" + result.replaceAll("'", "\"") + "';");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Set Series Label...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Preferences16.gif");
}
public String getDescription() {
return "Set the series label of the data set";
}
public boolean isCritical() {
return false;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,504 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SortByEnabledCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SortByEnabledCommand.java | /*
* SortByEnabledCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.LabelsJList;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.LinkedList;
public class SortByEnabledCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "set sort=enabled;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
ChartViewer chartViewer = (ChartViewer) getViewer();
final LabelsJList list = chartViewer.getActiveLabelsJList();
LinkedList<String> disabled = new LinkedList<>(list.getDisabledLabels());
LinkedList<String> labels = new LinkedList<>();
labels.addAll(list.getEnabledLabels());
labels.addAll(list.getDisabledLabels());
list.sync(labels, list.getLabel2ToolTips(), true);
list.disableLabels(disabled);
list.fireSyncToViewer();
}
public void actionPerformed(ActionEvent event) {
executeImmediately(getSyntax());
}
public boolean isApplicable() {
final LabelsJList list = ((ChartViewer) getViewer()).getActiveLabelsJList();
return list != null && list.isEnabled() && !list.isDoClustering() && list.getAllLabels().size() > list.getEnabledLabels().size();
}
public String getName() {
return "Group Enabled Entries";
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_N, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
public String getDescription() {
return "Groups the list of enabled entries";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("GroupEnabledDomains16.gif");
}
public boolean isCritical() {
return true;
}
}
| 2,852 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetMaximumRadiusCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SetMaximumRadiusCommand.java | /*
* SetMaximumRadiusCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.util.NumberUtils;
import jloda.util.parse.NexusStreamParser;
import megan.chart.drawers.CoOccurrenceDrawer;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* set max radius
* Daniel Huson, 2.2015
*/
public class SetMaximumRadiusCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "set maxRadius=<number>;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set maxRadius=");
int maxRadius = np.getInt(1, 1000);
np.matchIgnoreCase(";");
ChartViewer chartViewer = (ChartViewer) getViewer();
if (chartViewer.getChartDrawer() instanceof CoOccurrenceDrawer) {
((CoOccurrenceDrawer) chartViewer.getChartDrawer()).setMaxRadius(maxRadius);
ProgramProperties.put("COMaxRadius", maxRadius);
}
chartViewer.repaint();
}
public void actionPerformed(ActionEvent event) {
ChartViewer chartViewer = (ChartViewer) getViewer();
if (chartViewer.getChartDrawer() instanceof CoOccurrenceDrawer) {
String result = JOptionPane.showInputDialog(chartViewer.getFrame(), "Set Max Radius", ((CoOccurrenceDrawer) chartViewer.getChartDrawer()).getMaxRadius());
if (result != null && NumberUtils.isInteger(result))
execute("set maxRadius='" + result + "';");
}
}
public boolean isApplicable() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer != null && chartViewer.getChartDrawer() instanceof CoOccurrenceDrawer;
}
public String getName() {
return "Set Max Radius...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Preferences16.gif");
}
public String getDescription() {
return "Set the max radius to use for nodes in a co-occurrence plot";
}
public boolean isCritical() {
return false;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 3,075 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
RectangularWordCloudCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/RectangularWordCloudCommand.java | /*
* RectangularWordCloudCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.chart.drawers.MultiChartDrawer;
import megan.chart.drawers.WordCloudDrawer;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class RectangularWordCloudCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.isUseRectangleShape();
}
public String getSyntax() {
return "set shape={square|rectangle};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set shape=");
String shape = np.getWordMatchesIgnoringCase("rectangle square");
np.matchIgnoreCase(";");
ChartViewer chartViewer = (ChartViewer) getViewer();
chartViewer.setUseRectangleShape(shape.equalsIgnoreCase("rectangle"));
if (chartViewer.getChartDrawer() instanceof MultiChartDrawer)
chartViewer.getChartDrawer().forceUpdate(); // need to recompute word clouds
}
public void actionPerformed(ActionEvent event) {
execute("set shape='" + (isSelected() ? "square" : "rectangle") + "';");
}
public boolean isApplicable() {
ChartViewer viewer = (ChartViewer) getViewer();
return viewer.getChartDrawer() instanceof WordCloudDrawer
|| (viewer.getChartDrawer() instanceof MultiChartDrawer && ((MultiChartDrawer) viewer.getChartDrawer()).getBaseDrawer() instanceof WordCloudDrawer);
}
public String getName() {
return "Rectangle Shape";
}
public KeyStroke getAcceleratorKey() {
return null;
}
public String getDescription() {
return "Set wordcloud shape";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
}
| 2,836 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetChartDrawFontCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/SetChartDrawFontCommand.java | /*
* SetChartDrawFontCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.ChooseFontDialog;
import jloda.swing.util.ColorUtilsSwing;
import jloda.swing.util.ProgramProperties;
import jloda.util.Pair;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.chart.drawers.MultiChartDrawer;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* set series label
* Daniel Huson, 6.2012
*/
public class SetChartDrawFontCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "set chartfont=<name-style-size> color={<color>|default} target={" + StringUtils.toString(ChartViewer.FontKeys.values(), "|") + "};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set chartfont=");
String fontLabel = np.getWordRespectCase();
Color color;
np.matchIgnoreCase("color=");
if (np.peekMatchIgnoreCase("default")) {
np.matchIgnoreCase("default");
color = null;
} else {
color = ColorUtilsSwing.convert(np.getColor());
}
np.matchIgnoreCase("target=");
String target = np.getWordMatchesRespectingCase(StringUtils.toString(ChartViewer.FontKeys.values(), " "));
np.matchIgnoreCase(";");
ProgramProperties.put(target, fontLabel);
ProgramProperties.put(target + "Color", color);
ChartViewer chartViewer = (ChartViewer) getViewer();
chartViewer.setFont(target, Font.decode(fontLabel), color);
if (target.equalsIgnoreCase(ChartViewer.FontKeys.DrawFont.toString()) && chartViewer.getChartDrawer() instanceof MultiChartDrawer) {
chartViewer.getChartDrawer().forceUpdate(); // need to recompute word clouds
//chartViewer.updateView(Director.ALL);
}
chartViewer.repaint();
}
public void actionPerformed(ActionEvent event) {
ChartViewer chartViewer = (ChartViewer) getViewer();
String target = ChartViewer.FontKeys.DrawFont.toString();
Font font = ProgramProperties.get(target, ChartViewer.defaultFont);
Color color = ProgramProperties.get(target + "Color", (Color) null);
Pair<Font, Color> result = ChooseFontDialog.showChooseFontDialog(chartViewer.getFrame(), "Choose drawing font", font, color);
if (result != null)
execute("set chartFont='" + BasicSwing.encode(result.getFirst())
+ "' color=" + (result.getSecond() != null ? ColorUtilsSwing.toString3Int(result.getSecond()) : "default") + " target='" + target + "';");
}
public boolean isApplicable() {
ChartViewer viewer = (ChartViewer) getViewer();
return viewer != null;
}
public String getName() {
return "Draw Font...";
}
public ImageIcon getIcon() {
return null;
}
public String getDescription() {
return "Set the font used for drawing";
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 4,025 | 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/chart/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.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.director.ProjectManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import megan.chart.gui.LabelsJList;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* select all series
* Daniel Huson, 7.2012
*/
public class SelectAllCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("select what=");
final List<String> labels = new LinkedList<>();
if (np.peekMatchAnyTokenIgnoreCase("all none previous")) {
labels.add(np.getWordMatchesIgnoringCase("all none previous"));
np.matchIgnoreCase(";");
} else labels.addAll(np.getTokensRespectCase(null, ";"));
final ChartViewer viewer = (ChartViewer) getViewer();
final LabelsJList list = viewer.getActiveLabelsJList();
for (String name : labels) {
if (name.equalsIgnoreCase("all"))
viewer.getChartSelection().setSelected(list.getName(), list.getAllLabels(), true);
else if (name.equalsIgnoreCase("none"))
viewer.getChartSelection().clearSelection(list.getName());
else if (name.equals("previous"))
viewer.getChartSelection().setSelected(list.getName(), ProjectManager.getPreviouslySelectedNodeLabels(), true);
else
viewer.getChartSelection().setSelected(list.getName(), Collections.singletonList(name), true);
}
viewer.repaint();
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "select what={all|none|previous|<name...>};";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
execute("select what=all;");
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Select All";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Selection";
}
/**
* 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());
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
}
| 4,192 | 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/chart/commands/ExpandVerticalCommand.java | /*
* ExpandVerticalCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class ExpandVerticalCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
executeImmediately("expand direction=vertical;");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Expand Vertical";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("ExpandVertical16.gif");
}
public String getDescription() {
return "Expand view vertically";
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_UP, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 2,084 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ClusterSeriesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/ClusterSeriesCommand.java | /*
* ClusterSeriesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.cluster.ClusteringTree;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ClusterSeriesCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
final ChartViewer chartViewer = (ChartViewer) getViewer();
return isApplicable() && chartViewer.getSeriesList().isDoClustering();
}
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
execute("cluster what=series state=" + !isSelected() + ";");
}
public boolean isApplicable() {
final ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getChartDrawer() != null && chartViewer.getChartDrawer().canCluster(ClusteringTree.TYPE.SERIES);
}
public String getName() {
return "Cluster Series";
}
public KeyStroke getAcceleratorKey() {
return null;
}
public String getDescription() {
return "Cluster series";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Cluster16.gif");
}
public boolean isCritical() {
return true;
}
}
| 2,282 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
TransposeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/chart/commands/TransposeCommand.java | /*
* TransposeCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package megan.chart.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.chart.gui.ChartViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class TransposeCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.isTranspose();
}
public String getSyntax() {
return "set transpose={true|false};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set transpose=");
boolean value = np.getBoolean();
np.matchIgnoreCase(";");
ChartViewer chartViewer = (ChartViewer) getViewer();
chartViewer.setTranspose(value);
}
public void actionPerformed(ActionEvent event) {
execute("set transpose=" + (!isSelected()) + ";");
}
public boolean isApplicable() {
ChartViewer chartViewer = (ChartViewer) getViewer();
return chartViewer.getChartDrawer() != null && chartViewer.getChartDrawer().canTranspose();
}
public String getName() {
return "Transpose";
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_T, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
public String getDescription() {
return "Transpose the chart, i.e. group by attribute (such as taxa or function) rather than by sample";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Transpose16.gif");
}
public boolean isCritical() {
return true;
}
}
| 2,628 | 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.