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
Injector.java
/FileExtraction/Java_unseen/MokkowDev_LiquidBouncePlusPlus/src/main/java/de/enzaxd/viaforge/platform/Injector.java
package de.enzaxd.viaforge.platform; import com.viaversion.viaversion.api.platform.ViaInjector; import com.viaversion.viaversion.libs.gson.JsonObject; import de.enzaxd.viaforge.ViaForge; import de.enzaxd.viaforge.handler.CommonTransformer; public class Injector implements ViaInjector { @Override public void inject() { } @Override public void uninject() { } @Override public int getServerProtocolVersion() { return ViaForge.SHARED_VERSION; } @Override public String getEncoderName() { return CommonTransformer.HANDLER_ENCODER_NAME; } @Override public String getDecoderName() { return CommonTransformer.HANDLER_DECODER_NAME; } @Override public JsonObject getDump() { JsonObject obj = new JsonObject(); return obj; } }
838
Java
.java
MokkowDev/LiquidBouncePlusPlus
82
28
3
2022-07-27T12:21:34Z
2023-12-31T08:57:34Z
ViaConfig.java
/FileExtraction/Java_unseen/MokkowDev_LiquidBouncePlusPlus/src/main/java/de/enzaxd/viaforge/platform/ViaConfig.java
package de.enzaxd.viaforge.platform; import com.viaversion.viaversion.configuration.AbstractViaConfig; import java.io.File; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Map; public class ViaConfig extends AbstractViaConfig { // Based on Sponge ViaVersion private static List<String> UNSUPPORTED = Arrays.asList("bungee-ping-interval", "bungee-ping-save", "bungee-servers", "quick-move-action-fix", "nms-player-ticking", "velocity-ping-interval", "velocity-ping-save", "velocity-servers", "blockconnection-method", "change-1_9-hitbox", "change-1_14-hitbox"); public ViaConfig(File configFile) { super(configFile); // Load config reloadConfig(); } @Override public URL getDefaultConfigURL() { return getClass().getClassLoader().getResource("assets/viaversion/config.yml"); } @Override protected void handleConfig(Map<String, Object> config) { // Nothing Currently } @Override public List<String> getUnsupportedOptions() { return UNSUPPORTED; } @Override public boolean isNMSPlayerTicking() { return false; } @Override public boolean is1_12QuickMoveActionFix() { return false; } @Override public String getBlockConnectionMethod() { return "packet"; } @Override public boolean is1_9HitboxFix() { return false; } @Override public boolean is1_14HitboxFix() { return false; } }
1,560
Java
.java
MokkowDev/LiquidBouncePlusPlus
82
28
3
2022-07-27T12:21:34Z
2023-12-31T08:57:34Z
JLoggerToLog4j.java
/FileExtraction/Java_unseen/MokkowDev_LiquidBouncePlusPlus/src/main/java/de/enzaxd/viaforge/util/JLoggerToLog4j.java
package de.enzaxd.viaforge.util; import java.text.MessageFormat; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; public class JLoggerToLog4j extends Logger { private final org.apache.logging.log4j.Logger base; public JLoggerToLog4j(org.apache.logging.log4j.Logger logger) { super("logger", null); this.base = logger; } public void log(LogRecord record) { this.log(record.getLevel(), record.getMessage()); } public void log(Level level, String msg) { if (level == Level.FINE) { this.base.debug(msg); } else if (level == Level.WARNING) { this.base.warn(msg); } else if (level == Level.SEVERE) { this.base.error(msg); } else if (level == Level.INFO) { this.base.info(msg); } else { this.base.trace(msg); } } public void log(Level level, String msg, Object param1) { if (level == Level.FINE) { this.base.debug(msg, param1); } else if (level == Level.WARNING) { this.base.warn(msg, param1); } else if (level == Level.SEVERE) { this.base.error(msg, param1); } else if (level == Level.INFO) { this.base.info(msg, param1); } else { this.base.trace(msg, param1); } } public void log(Level level, String msg, Object[] params) { log(level, MessageFormat.format(msg, params)); } public void log(Level level, String msg, Throwable params) { if (level == Level.FINE) { this.base.debug(msg, params); } else if (level == Level.WARNING) { this.base.warn(msg, params); } else if (level == Level.SEVERE) { this.base.error(msg, params); } else if (level == Level.INFO) { this.base.info(msg, params); } else { this.base.trace(msg, params); } } }
1,997
Java
.java
MokkowDev/LiquidBouncePlusPlus
82
28
3
2022-07-27T12:21:34Z
2023-12-31T08:57:34Z
FutureTaskId.java
/FileExtraction/Java_unseen/MokkowDev_LiquidBouncePlusPlus/src/main/java/de/enzaxd/viaforge/util/FutureTaskId.java
package de.enzaxd.viaforge.util; import com.viaversion.viaversion.api.platform.PlatformTask; import java.util.concurrent.Future; public class FutureTaskId implements PlatformTask<Future<?>> { private final Future<?> object; public FutureTaskId(Future<?> object) { this.object = object; } @Override public Future<?> getObject() { return object; } @Override public void cancel() { object.cancel(false); } }
471
Java
.java
MokkowDev/LiquidBouncePlusPlus
82
28
3
2022-07-27T12:21:34Z
2023-12-31T08:57:34Z
AttackOrder.java
/FileExtraction/Java_unseen/MokkowDev_LiquidBouncePlusPlus/src/main/java/de/enzaxd/viaforge/util/AttackOrder.java
/* * This code was taken from Foreheadchann/ViaMCP-Reborn as an attempt to fix Verus's Killaura flags on 1.9+ */ package de.enzaxd.viaforge.util; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.MovingObjectPosition; import de.enzaxd.viaforge.ViaForge; import de.enzaxd.viaforge.protocol.ProtocolCollection; public class AttackOrder { private static final Minecraft mc = Minecraft.getMinecraft(); private static final int VER_1_8_ID = 47; public static void sendConditionalSwing(MovingObjectPosition mop) { if (mop != null && mop.typeOfHit != MovingObjectPosition.MovingObjectType.ENTITY) { mc.thePlayer.swingItem(); } } public static void sendFixedAttack(EntityPlayer entityIn, Entity target) { // Using this instead of ViaForge.PROTOCOL_VERSION so does not need to be changed between 1.8.x and 1.12.2 base // getVersion() can be null, but not in this case, as ID 47 exists, if not removed if(ViaForge.getInstance().getVersion() <= ProtocolCollection.getProtocolById(VER_1_8_ID).getVersion()) { send1_8Attack(entityIn, target); } else { send1_9Attack(entityIn, target); } } private static void send1_8Attack(EntityPlayer entityIn, Entity target) { mc.thePlayer.swingItem(); mc.playerController.attackEntity(entityIn, target); } private static void send1_9Attack(EntityPlayer entityIn, Entity target) { mc.playerController.attackEntity(entityIn, target); mc.thePlayer.swingItem(); } }
1,706
Java
.java
MokkowDev/LiquidBouncePlusPlus
82
28
3
2022-07-27T12:21:34Z
2023-12-31T08:57:34Z
ProtocolCollection.java
/FileExtraction/Java_unseen/MokkowDev_LiquidBouncePlusPlus/src/main/java/de/enzaxd/viaforge/protocol/ProtocolCollection.java
package de.enzaxd.viaforge.protocol; import com.viaversion.viaversion.api.protocol.version.ProtocolVersion; public enum ProtocolCollection { R1_19_4(new ProtocolVersion(762, "1.19.4")), R1_19_3(new ProtocolVersion(761, "1.19.3")), R1_19_2(new ProtocolVersion(760, "1.19.1/2")), R1_19(new ProtocolVersion(759, "1.19")), R1_18_2(new ProtocolVersion(758, "1.18.2")), R1_18_1(new ProtocolVersion(757, "1.18/1")), R1_17_1(new ProtocolVersion(756, "1.17.1")), R1_17(new ProtocolVersion(755, "1.17")), R1_16_5(new ProtocolVersion(754, "1.16.4/5")), R1_16_3(new ProtocolVersion(753, "1.16.3")), R1_16_2(new ProtocolVersion(751, "1.16.2")), R1_16_1(new ProtocolVersion(736, "1.16.1")), R1_16(new ProtocolVersion(735, "1.16")), R1_15_2(new ProtocolVersion(578, "1.15.2")), R1_15_1(new ProtocolVersion(575, "1.15.1")), R1_15(new ProtocolVersion(573, "1.15")), R1_14_4(new ProtocolVersion(498, "1.14.4")), R1_14_3(new ProtocolVersion(490, "1.14.3")), R1_14_2(new ProtocolVersion(485, "1.14.2")), R1_14_1(new ProtocolVersion(480, "1.14.1")), R1_14(new ProtocolVersion(477, "1.14")), R1_13_2(new ProtocolVersion(404, "1.13.2")), R1_13_1(new ProtocolVersion(401, "1.13.1")), R1_13(new ProtocolVersion(393, "1.13")), R1_12_2(new ProtocolVersion(340, "1.12.2")), R1_12_1(new ProtocolVersion(338, "1.12.1")), R1_12(new ProtocolVersion(335, "1.12")), R1_11_1(new ProtocolVersion(316, "1.11.1/2")), R1_11(new ProtocolVersion(315, "1.11")), R1_10(new ProtocolVersion(210, "1.10.x")), R1_9_4(new ProtocolVersion(110, "1.9.3/4")), R1_9_2(new ProtocolVersion(109, "1.9.2")), R1_9_1(new ProtocolVersion(108, "1.9.1")), R1_9(new ProtocolVersion(107, "1.9")), R1_8(new ProtocolVersion(47, "1.8.x")); private ProtocolVersion version; private ProtocolCollection(ProtocolVersion version) { this.version = version; } public ProtocolVersion getVersion() { return version; } public static ProtocolVersion getProtocolById(int id) { for (ProtocolCollection coll : values()) if (coll.getVersion().getVersion() == id) return coll.getVersion(); return null; } }
2,271
Java
.java
MokkowDev/LiquidBouncePlusPlus
82
28
3
2022-07-27T12:21:34Z
2023-12-31T08:57:34Z
OutlineUtils.java
/FileExtraction/Java_unseen/MokkowDev_LiquidBouncePlusPlus/src/main/java/co/uk/hexeption/utils/OutlineUtils.java
package co.uk.hexeption.utils; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.shader.Framebuffer; import org.lwjgl.opengl.EXTFramebufferObject; import org.lwjgl.opengl.EXTPackedDepthStencil; import static org.lwjgl.opengl.GL11.*; import java.awt.*; /** * Outline ESP * * @author Hexeption */ public class OutlineUtils { public static void renderOne(final float lineWidth) { checkSetupFBO(); glPushAttrib(GL_ALL_ATTRIB_BITS); glDisable(GL_ALPHA_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glLineWidth(lineWidth); glEnable(GL_LINE_SMOOTH); glEnable(GL_STENCIL_TEST); glClear(GL_STENCIL_BUFFER_BIT); glClearStencil(0xF); glStencilFunc(GL_NEVER, 1, 0xF); glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } public static void renderTwo() { glStencilFunc(GL_NEVER, 0, 0xF); glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } public static void renderThree() { glStencilFunc(GL_EQUAL, 1, 0xF); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } public static void renderFour(final Color color) { setColor(color); glDepthMask(false); glDisable(GL_DEPTH_TEST); glEnable(GL_POLYGON_OFFSET_LINE); glPolygonOffset(1.0F, -2000000F); OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240.0F, 240.0F); } public static void renderFive() { glPolygonOffset(1.0F, 2000000F); glDisable(GL_POLYGON_OFFSET_LINE); glEnable(GL_DEPTH_TEST); glDepthMask(true); glDisable(GL_STENCIL_TEST); glDisable(GL_LINE_SMOOTH); glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE); glEnable(GL_BLEND); glEnable(GL_LIGHTING); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glPopAttrib(); } public static void setColor(final Color color) { glColor4d(color.getRed() / 255F, color.getGreen() / 255F, color.getBlue() / 255F, color.getAlpha() / 255F); } public static void checkSetupFBO() { // Gets the FBO of Minecraft final Framebuffer fbo = Minecraft.getMinecraft().getFramebuffer(); // Check if FBO isn't null if(fbo != null) { // Checks if screen has been resized or new FBO has been created if(fbo.depthBuffer > -1) { // Sets up the FBO with depth and stencil extensions (24/8 bit) setupFBO(fbo); // Reset the ID to prevent multiple FBO's fbo.depthBuffer = -1; } } } /** * Sets up the FBO with depth and stencil * * @param fbo Framebuffer */ private static void setupFBO(final Framebuffer fbo) { // Deletes old render buffer extensions such as depth // Args: Render Buffer ID EXTFramebufferObject.glDeleteRenderbuffersEXT(fbo.depthBuffer); // Generates a new render buffer ID for the depth and stencil extension final int stencil_depth_buffer_ID = EXTFramebufferObject.glGenRenderbuffersEXT(); // Binds new render buffer by ID // Args: Target (GL_RENDERBUFFER_EXT), ID EXTFramebufferObject.glBindRenderbufferEXT(EXTFramebufferObject.GL_RENDERBUFFER_EXT, stencil_depth_buffer_ID); // Adds the depth and stencil extension // Args: Target (GL_RENDERBUFFER_EXT), Extension (GL_DEPTH_STENCIL_EXT), // Width, Height EXTFramebufferObject.glRenderbufferStorageEXT(EXTFramebufferObject.GL_RENDERBUFFER_EXT, EXTPackedDepthStencil.GL_DEPTH_STENCIL_EXT, Minecraft.getMinecraft().displayWidth, Minecraft.getMinecraft().displayHeight); // Adds the stencil attachment // Args: Target (GL_FRAMEBUFFER_EXT), Attachment // (GL_STENCIL_ATTACHMENT_EXT), Target (GL_RENDERBUFFER_EXT), ID EXTFramebufferObject.glFramebufferRenderbufferEXT(EXTFramebufferObject.GL_FRAMEBUFFER_EXT, EXTFramebufferObject.GL_STENCIL_ATTACHMENT_EXT, EXTFramebufferObject.GL_RENDERBUFFER_EXT, stencil_depth_buffer_ID); // Adds the depth attachment // Args: Target (GL_FRAMEBUFFER_EXT), Attachment // (GL_DEPTH_ATTACHMENT_EXT), Target (GL_RENDERBUFFER_EXT), ID EXTFramebufferObject.glFramebufferRenderbufferEXT(EXTFramebufferObject.GL_FRAMEBUFFER_EXT, EXTFramebufferObject.GL_DEPTH_ATTACHMENT_EXT, EXTFramebufferObject.GL_RENDERBUFFER_EXT, stencil_depth_buffer_ID); } }
4,795
Java
.java
MokkowDev/LiquidBouncePlusPlus
82
28
3
2022-07-27T12:21:34Z
2023-12-31T08:57:34Z
ExampleUnitTest.java
/FileExtraction/Java_unseen/Foso_JKAndroidWebserver/app/src/test/java/jensklingenberg/de/jkandroidwebserver/ExampleUnitTest.java
package jensklingenberg.de.jkandroidwebserver; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
403
Java
.java
Foso/JKAndroidWebserver
10
5
0
2017-07-31T22:16:15Z
2018-06-03T08:25:18Z
MainActivity.java
/FileExtraction/Java_unseen/Foso_JKAndroidWebserver/app/src/main/java/jensklingenberg/de/jkandroidwebserver/MainActivity.java
package jensklingenberg.de.jkandroidwebserver; import android.net.wifi.WifiManager; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.format.Formatter; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import java.io.IOException; public class MainActivity extends AppCompatActivity { private static MyHTTPD server; @BindView(R.id.txtIpAddress) TextView txtIpAddress; @BindView(R.id.btnStart) Button btnStart; @BindView(R.id.btnStop) Button btnStop; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); try { server = new MyHTTPD(); } catch (IOException e) { e.printStackTrace(); } btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { server.start(); initIPAddress(); } catch (IOException e) { e.printStackTrace(); } } }); btnStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { server.stop(); txtIpAddress.setText(""); } }); } private void initIPAddress() { WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress()); txtIpAddress.setText("Server running at: " + ip + ":" + MyHTTPD.PORT); Log.i("TAG", "onCreate: " + ip); } }
1,693
Java
.java
Foso/JKAndroidWebserver
10
5
0
2017-07-31T22:16:15Z
2018-06-03T08:25:18Z
MyHTTPD.java
/FileExtraction/Java_unseen/Foso_JKAndroidWebserver/app/src/main/java/jensklingenberg/de/jkandroidwebserver/MyHTTPD.java
package jensklingenberg.de.jkandroidwebserver; import android.os.Environment; import android.util.Log; import fi.iki.elonen.NanoHTTPD; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * Created by jens on 25.03.17. */ public class MyHTTPD extends NanoHTTPD { public static final int PORT = 8765; public MyHTTPD() throws IOException { super(PORT); } @Override public Response serve(IHTTPSession session) { Log.i("TAG", "serve: "+session.getUri()); String uri = session.getUri(); if (uri.equals("/hello")) { String response = "<!DOCTYPE html>\n" + "<html>\n" + "<body>\n" + "\n" + "<p>Hello World</p></body></html>"; return newFixedLengthResponse(response); } return null; } }
938
Java
.java
Foso/JKAndroidWebserver
10
5
0
2017-07-31T22:16:15Z
2018-06-03T08:25:18Z
ExampleInstrumentedTest.java
/FileExtraction/Java_unseen/Foso_JKAndroidWebserver/app/src/androidTest/java/jensklingenberg/de/jkandroidwebserver/ExampleInstrumentedTest.java
package jensklingenberg.de.jkandroidwebserver; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("jensklingenberg.de.jkandroidwebserver", appContext.getPackageName()); } }
758
Java
.java
Foso/JKAndroidWebserver
10
5
0
2017-07-31T22:16:15Z
2018-06-03T08:25:18Z
module-info.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/module-info.java
module megan { requires transitive jloda; requires transitive javafx.swing; requires transitive javafx.controls; requires transitive javafx.fxml; requires transitive com.install4j.runtime; requires transitive java.sql; requires transitive jdk.httpserver; requires Jama; requires sis.jhdf5.batteries.included; requires gson; requires commons.math3; requires contrasts; requires transitive java.desktop; requires transitive java.net.http; requires bcyrpt; requires transitive org.xerial.sqlitejdbc; requires transitive java.sql.rowset; exports megan.accessiondb; exports megan.algorithms; exports megan.alignment; exports megan.alignment.commands; exports megan.alignment.gui; exports megan.alignment.gui.colors; exports megan.fx.dialogs.decontam; exports megan.assembly; exports megan.assembly.alignment; exports megan.assembly.commands; exports megan.biom.biom1; exports megan.biom.biom2; exports megan.blastclient; exports megan.chart; exports megan.chart.cluster; exports megan.chart.commands; exports megan.chart.commandtemplates; exports megan.chart.data; exports megan.chart.drawers; exports megan.chart.gui; exports megan.classification; exports megan.classification.commandtemplates; exports megan.classification.data; exports megan.classification.util; exports megan.clusteranalysis; exports megan.clusteranalysis.commands; exports megan.clusteranalysis.commands.geom3d; exports megan.clusteranalysis.commands.zoom; exports megan.clusteranalysis.gui; exports megan.clusteranalysis.indices; exports megan.clusteranalysis.nnet; exports megan.clusteranalysis.pcoa; exports megan.clusteranalysis.pcoa.geom3d; exports megan.clusteranalysis.tree; exports megan.commands; exports megan.commands.additional; exports megan.commands.algorithms; exports megan.commands.clipboard; exports megan.commands.color; exports megan.commands.compare; exports megan.commands.export; exports megan.commands.find; exports megan.commands.format; exports megan.commands.load; exports megan.commands.mapping; exports megan.commands.preferences; exports megan.commands.select; exports megan.commands.show; exports megan.commands.zoom; exports megan.core; exports megan.daa; exports megan.daa.connector; exports megan.daa.io; exports megan.data; exports megan.data.merge; exports megan.dialogs.attributes; exports megan.dialogs.attributes.commands; exports megan.dialogs.compare; exports megan.dialogs.compare.commands; exports megan.dialogs.export; exports megan.dialogs.export.analysis; exports megan.dialogs.extractor; exports megan.dialogs.extractor.commands; exports megan.dialogs.importcsv; exports megan.dialogs.input; exports megan.dialogs.lrinspector; exports megan.dialogs.lrinspector.commands; exports megan.dialogs.meganize; exports megan.dialogs.meganize.commands; exports megan.dialogs.reanalyze.commands; exports megan.dialogs.parameters; exports megan.dialogs.parameters.commands; exports megan.dialogs.profile; exports megan.dialogs.profile.commands; exports megan.dialogs.reads; exports megan.fx; exports megan.genes; exports megan.groups; exports megan.groups.commands; exports megan.importblast; exports megan.importblast.commands; exports megan.inspector; exports megan.inspector.commands; exports megan.io; exports megan.io.experimental; exports megan.main; exports megan.parsers; exports megan.parsers.blast; exports megan.parsers.blast.blastxml; exports megan.parsers.maf; exports megan.parsers.sam; exports megan.rma2; exports megan.rma3; exports megan.rma6; exports megan.samplesviewer; exports megan.samplesviewer.commands; exports megan.samplesviewer.commands.attributes; exports megan.samplesviewer.commands.format; exports megan.samplesviewer.commands.samples; exports megan.stats; exports megan.timeseriesviewer; exports megan.timeseriesviewer.commands; exports megan.tools; exports megan.treeviewer; exports megan.util; exports megan.viewer; exports megan.viewer.commands; exports megan.viewer.commands.collapse; exports megan.viewer.gui; exports megan.xtra; opens megan.resources; opens megan.resources.css; opens megan.resources.icons; opens megan.resources.images; opens megan.resources.files; opens megan.resources.files.ms; opens megan.biom.biom1; opens megan.biom.biom2; opens megan.fx.dialogs.decontam; opens megan.dialogs.lrinspector; opens megan.dialogs.reads; exports megan.resources; exports megan.ms; exports megan.ms.client; exports megan.ms.client.connector; exports megan.ms.clientdialog; exports megan.ms.clientdialog.commands; opens megan.ms.clientdialog.commands; exports megan.ms.server; exports megan.ms.clientdialog.service; exports megan.tools.utils; }
5,183
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IReadBlockIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/IReadBlockIterator.java
/* * IReadBlockIterator.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import jloda.util.ICloseableIterator; import java.io.Closeable; /** * Iterator over a set of read blocks * Daniel Huson, 4.2010 */ public interface IReadBlockIterator extends ICloseableIterator<IReadBlock>, Closeable { /** * get a string reporting stats * * @return stats string */ String getStats(); }
1,171
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ReadBlockIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/ReadBlockIterator.java
/* * ReadBlockIterator.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import jloda.util.Basic; import java.io.IOException; import java.util.Iterator; /** * iterator over reads in named classes * <p/> * Daniel Huson, 4.2015 */ public class ReadBlockIterator implements IReadBlockIterator { private final IReadBlockGetter readBlockGetter; private final Iterator<Long> iterator; private final long numberOfReads; private int countReads = 0; /** * constructor * */ public ReadBlockIterator(Iterator<Long> readIdsIterator, long numberOfReads, IReadBlockGetter readBlockGetter) { this.iterator = readIdsIterator; this.numberOfReads = numberOfReads; this.readBlockGetter = readBlockGetter; } @Override public String getStats() { return "Reads: " + countReads; } @Override public void close() { readBlockGetter.close(); } @Override public long getMaximumProgress() { return numberOfReads; } @Override public long getProgress() { return countReads; } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public IReadBlock next() { countReads++; try { return readBlockGetter.getReadBlock(iterator.next()); } catch (IOException e) { Basic.caught(e); return null; } } @Override public void remove() { } }
2,251
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
DataSelection.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/DataSelection.java
/* * DataSelection.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; /** * selection * Daniel Huson, 4.2015 */ public class DataSelection { private boolean wantReadText; private boolean wantMatches; public boolean isWantMatches() { return wantMatches; } public void setWantMatches(boolean wantMatches) { this.wantMatches = wantMatches; } public boolean isWantReadText() { return wantReadText; } public void setWantReadText(boolean wantReadText) { this.wantReadText = wantReadText; } }
1,325
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ReadBlockFromBlast.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/ReadBlockFromBlast.java
/* * ReadBlockFromBlast.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import jloda.util.StringUtils; import megan.rma2.ReadBlockRMA2; /** * readblock with information on location of text in file * Daniel Huson, 10.2010 */ public class ReadBlockFromBlast extends ReadBlockRMA2 implements IReadBlock, IReadBlockWithLocation { private Location location; /** * constructor */ public ReadBlockFromBlast() { } /** * set read sequence. Overloaded to also compute complexity and read length * */ public void setReadSequence(String readSequence) { super.setReadSequence(readSequence); if (readSequence != null) { setReadLength(StringUtils.getNumberOfNonSpaceCharacters(readSequence)); } } /** * gets the location of the text * * @return location of read text or null */ public Location getTextLocation() { return location; } /** * sets the location of the text * */ public void setTextLocation(Location location) { this.location = location; } /** * get the i-th match block * * @return match block */ public IMatchBlockWithLocation getMatchBlock(int i) { return (IMatchBlockWithLocation) super.getMatchBlock(i); } /** * erase the block */ public void clear() { super.clear(); location = null; } }
2,193
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IClassificationBlock.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/IClassificationBlock.java
/* * IClassificationBlock.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import java.util.Set; public interface IClassificationBlock { /** * get the number associated with a key * * @return number */ int getSum(Integer key); /** * set the number associated with a key -> just set not write to disk * */ void setSum(Integer key, int num); /** * get the weighted number associated with a key * * @return number */ float getWeightedSum(Integer key); /** * set the weighted sum * */ void setWeightedSum(Integer key, float num); /** * get the name of this classification * * @return name */ String getName(); /** * set the name of this classification * */ void setName(String name); /** * get human readable representation * * @return human readable */ String toString(); Set<Integer> getKeySet(); }
1,744
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ReadBlockIteratorMaxCount.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/ReadBlockIteratorMaxCount.java
/* * ReadBlockIteratorMaxCount.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import java.io.IOException; /** * Iterator over a set of read blocks, upto a given max count * Daniel Huson, 6.2016 */ public class ReadBlockIteratorMaxCount implements IReadBlockIterator { private final IReadBlockIterator it; private final int maxCount; private int count; public ReadBlockIteratorMaxCount(IReadBlockIterator it, int maxCount) { this.it = it; this.maxCount = maxCount; count = 0; } @Override public String getStats() { return it.getStats(); } @Override public void close() throws IOException { it.close(); } @Override public long getMaximumProgress() { return maxCount; } @Override public long getProgress() { return count; } @Override public boolean hasNext() { return count < maxCount && it.hasNext(); } @Override public IReadBlock next() { count++; return it.next(); } }
1,816
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ReadBlockWithLocationAdapter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/ReadBlockWithLocationAdapter.java
/* * ReadBlockWithLocationAdapter.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; /** * holds a read block and additional location information * Daniel Huson, 2.2011 */ public class ReadBlockWithLocationAdapter implements IReadBlockWithLocation { private final IReadBlock readBlock; private IMatchBlockWithLocation[] matchBlocks; private Location location; public ReadBlockWithLocationAdapter(IReadBlock readBlock, Location location) { this.readBlock = readBlock; setMatchBlocks(readBlock.getMatchBlocks()); this.location = location; } public long getUId() { return readBlock.getUId(); } public void setUId(long uid) { readBlock.setUId(uid); } public String getReadName() { return readBlock.getReadName(); } public String getReadHeader() { return readBlock.getReadHeader(); } public void setReadHeader(String readHeader) { readBlock.setReadHeader(readHeader); } public String getReadSequence() { return readBlock.getReadSequence(); } public void setReadSequence(String readSequence) { readBlock.setReadSequence(readSequence); } /** * set the weight of a read * */ public void setReadWeight(int weight) { readBlock.setReadWeight(weight); } /** * get the weight of a read * * @return weight */ public int getReadWeight() { return readBlock.getReadWeight(); } public long getMateUId() { return readBlock.getMateUId(); } public void setMateUId(long mateReadUId) { readBlock.setMateUId(mateReadUId); } public byte getMateType() { return readBlock.getMateType(); } public void setMateType(byte type) { readBlock.setMateType(type); } public void setReadLength(int readLength) { readBlock.setReadLength(readLength); } public int getReadLength() { return readBlock.getReadLength(); } public void setComplexity(float complexity) { readBlock.setComplexity(complexity); } public float getComplexity() { return readBlock.getComplexity(); } public int getNumberOfMatches() { return readBlock.getNumberOfMatches(); } public void setNumberOfMatches(int numberOfMatches) { readBlock.setNumberOfMatches(numberOfMatches); } public int getNumberOfAvailableMatchBlocks() { return readBlock.getNumberOfAvailableMatchBlocks(); } public IMatchBlockWithLocation[] getMatchBlocks() { return matchBlocks; } public void setMatchBlocks(IMatchBlock[] matchBlocks) { this.matchBlocks = new IMatchBlockWithLocation[matchBlocks.length]; for (int i = 0; i < matchBlocks.length; i++) { this.matchBlocks[i] = new MatchBlockWithLocationAdapter(matchBlocks[i], null); } } public String toString() { return readBlock + (location != null ? "\n" + location : ""); } public IMatchBlockWithLocation getMatchBlock(int i) { return matchBlocks[i]; } public Location getTextLocation() { return location; } public void setTextLocation(Location location) { this.location = location; } }
4,060
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Location.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/Location.java
/* * Location.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import java.io.Serial; import java.io.Serializable; /** * Stores the location of a text * Daniel Huson, 10.2010 */ public class Location implements Serializable { @Serial private static final long serialVersionUID = -6952597828705416365L; // DHH: changed id because LocationManager removed private int fileId; private long position; private int size; /** * default constructor */ public Location() { } /** * constructor * */ public Location(int fileId, long position, int size) { this.fileId = fileId; this.position = position; this.size = size; } public int getFileId() { return fileId; } public long getPosition() { return position; } public int getSize() { return size; } public void setFileId(int fileId) { this.fileId = fileId; } public void setPosition(long position) { this.position = position; } public void setSize(int size) { this.size = size; } public String toString() { return "[fileId=" + fileId + ", pos=" + position + ", size=" + size + "]"; } public Object clone() { return new Location(fileId, position, size); } }
2,090
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
AllReadsIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/AllReadsIterator.java
/* * AllReadsIterator.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import jloda.util.Basic; import java.io.IOException; /** * Iterates over all reads in a file * Daniel Huson, 8.2015 */ public class AllReadsIterator implements IReadBlockIterator { private final IReadBlockGetter readBlockGetter; private long countReads = 0; private final long totalCount; /** * constructor * */ public AllReadsIterator(IReadBlockGetter readBlockGetter) { this.readBlockGetter = readBlockGetter; totalCount = readBlockGetter.getCount(); } @Override public String getStats() { return "Reads: " + countReads; } @Override public void close() { readBlockGetter.close(); } @Override public long getMaximumProgress() { return totalCount; } @Override public long getProgress() { return countReads; } @Override public boolean hasNext() { return countReads < totalCount; } @Override public IReadBlock next() { if (!hasNext()) return null; try { final IReadBlock readBlock = readBlockGetter.getReadBlock(-1); countReads++; return readBlock; } catch (IOException e) { Basic.caught(e); return null; } } @Override public void remove() { } }
2,171
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IMatchBlock.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/IMatchBlock.java
/* * IMatchBlock.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; /** * matchblock interface * Daniel Huson, 4.2010 */ public interface IMatchBlock { /** * get the unique identifier for this match (unique within a dataset). * In an RMA file, this is always the file position for the match * * @return uid */ long getUId(); void setUId(long uid); /** * get the taxon id of the match * */ int getTaxonId(); void setTaxonId(int taxonId); /** * get the score of the match * */ float getBitScore(); void setBitScore(float bitScore); /** * get percent identity * */ float getPercentIdentity(); void setPercentIdentity(float percentIdentity); /** * get the refseq id * */ String getRefSeqId(); void setRefSeqId(String refSeqId); /** * gets the E-value * */ void setExpected(float expected); float getExpected(); /** * gets the match length * */ void setLength(int length); int getLength(); /** * get the ignore status * */ boolean isIgnore(); void setIgnore(boolean ignore); /** * get the text * */ String getText(); /** * get the first word of the text * */ String getTextFirstWord(); /** * set the text * */ void setText(String text); int getId(String cName); void setId(String cName, Integer id); int[] getIds(String[] cNames); /** * get the start position of the alignment in the query * * @return query start position */ int getAlignedQueryStart(); /** * get the end position of the alignment in the query * * @return query end position */ int getAlignedQueryEnd(); /** * get the length of the reference sequence * * @return reference sequence length */ int getRefLength(); }
2,724
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
TextStorageReader.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/TextStorageReader.java
/* * TextStorageReader.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import jloda.util.Pair; import megan.io.InputReader; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.HashSet; import java.util.Set; /** * reads text from storage * Daniel Huson, 10.2010 */ public class TextStorageReader { private final LocationManager locationManager; private final static int MAX_NUMBER_OF_OPEN_FILES = 5; private int numberOfOpenFiles = 0; private final InputReader[] fileId2raf; private final long[] fileId2lastUsed; private final static Set<String> warned = new HashSet<>(); /** * constructor * */ public TextStorageReader(LocationManager locationManager) { this.locationManager = locationManager; int maxId = 0; for (File file : locationManager.getFiles()) maxId = Math.max(maxId, locationManager.getFileId(file)); fileId2raf = new InputReader[maxId + 1]; fileId2lastUsed = new long[maxId + 1]; } /** * close all files used for fetching text */ public void closeAllFiles() { for (InputReader r : fileId2raf) { try { if (r != null) r.close(); } catch (Exception ignored) { } } } /** * gets the text stored at the named location * * @return text */ public String getText(Location location) throws IOException { int fileId = location.getFileId(); if (fileId < 0 || fileId >= fileId2raf.length) return null; if (fileId2raf[fileId] == null) { if (numberOfOpenFiles >= MAX_NUMBER_OF_OPEN_FILES) { long min = Long.MAX_VALUE; int minId = -1; for (int i = 0; i < fileId2lastUsed.length; i++) { if (fileId2raf[i] != null && fileId2lastUsed[i] < min) { min = fileId2lastUsed[i]; minId = i; } } if (minId != -1) { fileId2raf[minId].close(); fileId2raf[minId] = null; numberOfOpenFiles--; } } File file = locationManager.getFile(fileId); if (!(file.exists() && file.canRead())) file = new File(System.getProperty("user.dir") + File.separator + file.getPath()); if (file.exists() && file.canRead()) { fileId2raf[fileId] = new InputReader(file, null, null, true); numberOfOpenFiles++; } else { if (!warned.contains(file.getPath())) { System.err.println("Warning: Can't open file to read: " + file.getPath()); warned.add(file.getPath()); } return null; } } fileId2lastUsed[fileId] = System.currentTimeMillis(); InputReader raf = fileId2raf[fileId]; if (location.getPosition() >= raf.length()) throw new IOException("Location out of range: " + location.getPosition() + " >= " + raf.length()); raf.seek(location.getPosition()); if (locationManager.getTextStoragePolicy() == TextStoragePolicy.Reference) { byte[] bytes = new byte[location.getSize()]; raf.read(bytes, 0, bytes.length); return new String(bytes, 0, bytes.length, StandardCharsets.UTF_8); } else // must be dump file or on-board dump file { raf.seek(location.getPosition()); return raf.readString(); } } /** * gets the header and sequence for a read * * @return header and sequence */ public Pair<String, String> getHeaderAndSequence(Location location) throws IOException { Pair<String, String> headerAndSequence = new Pair<>(); getHeaderAndSequence(location, headerAndSequence); return headerAndSequence; } /** * gets the header and sequence for a read * */ private void getHeaderAndSequence(Location location, Pair<String, String> headerAndSequence) throws IOException { String string = getText(location); if (string == null) { headerAndSequence.setFirst(">Unknown"); headerAndSequence.setSecond("Unknown"); } else { int eol = string.indexOf('\n'); // header is first line if (eol <= 0) { headerAndSequence.setFirst(string); headerAndSequence.setSecond(null); } else { headerAndSequence.setFirst(string.substring(0, eol)); headerAndSequence.setSecond(string.substring(eol + 1)); } } } }
5,595
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IReadBlockWithLocation.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/IReadBlockWithLocation.java
/* * IReadBlockWithLocation.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; /** * readblock with additional location information, which is only required when creating a dataset * Daniel Huson, 2.2011 */ public interface IReadBlockWithLocation extends IReadBlock { Location getTextLocation(); void setTextLocation(Location location); IMatchBlockWithLocation getMatchBlock(int i); }
1,161
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IReadBlockGetter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/IReadBlockGetter.java
/* * IReadBlockGetter.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import java.io.Closeable; import java.io.IOException; /** * Provides access to read blocks by uid * Daniel Huson, 10.2010 */ public interface IReadBlockGetter extends Closeable { /** * gets the read block associated with the given uid * * @return read block or null */ IReadBlock getReadBlock(long uid) throws IOException; /** * closes the accessor * */ void close(); /** * get total number of reads * * @return total number of reads */ long getCount(); }
1,368
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
FindAllReadsIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/FindAllReadsIterator.java
/* * FindAllReadsIterator.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import jloda.util.Basic; import jloda.util.Single; import java.io.IOException; import java.util.regex.Pattern; /** * find all reads * Daniel Huson, 8.2015 */ public class FindAllReadsIterator implements IReadBlockIterator { private final Pattern pattern; private final FindSelection findSelector; private final Single<Boolean> canceled; private final IReadBlockIterator allReadsIterator; private IReadBlock nextRead; private int countReads = 0; /** * constructor * */ public FindAllReadsIterator(String regularExpression, FindSelection findSelector, IReadBlockIterator allReadsIterator, Single<Boolean> canceled) { this.findSelector = findSelector; this.canceled = canceled; pattern = Pattern.compile(regularExpression); this.allReadsIterator = allReadsIterator; nextRead = fetchNext(); } @Override public String getStats() { return "Reads: " + countReads; } @Override public void close() { try { allReadsIterator.close(); } catch (IOException e) { Basic.caught(e); } } @Override public long getMaximumProgress() { return allReadsIterator.getMaximumProgress(); } @Override public long getProgress() { return allReadsIterator.getProgress(); } @Override public boolean hasNext() { return !canceled.get() && nextRead != null; } @Override public IReadBlock next() { final IReadBlock result = nextRead; if (result != null) { countReads++; nextRead = fetchNext(); } return result; } @Override public void remove() { } /** * fetches the next read that matches the search pattern * * @return next match */ private IReadBlock fetchNext() { while (!canceled.get() && allReadsIterator.hasNext()) { IReadBlock readBlock = allReadsIterator.next(); if (FindSelection.doesMatch(findSelector, readBlock, pattern)) return readBlock; } return null; } }
2,995
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ExtractToNewDocument.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/ExtractToNewDocument.java
/* * ExtractToNewDocument.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import jloda.seq.BlastMode; import jloda.swing.util.ProgramProperties; import jloda.util.FileLineIterator; import jloda.util.FileUtils; import jloda.util.Single; import jloda.util.progress.ProgressListener; import megan.core.Document; import megan.core.MeganFile; import megan.parsers.blast.BlastN2SAMIterator; import megan.parsers.blast.BlastP2SAMIterator; import megan.parsers.blast.BlastX2SAMIterator; import megan.parsers.blast.ISAMIterator; import megan.rma6.RMA6FileCreator; import java.io.IOException; import java.util.Arrays; import java.util.Collection; /** * extract a given classification and class-ids to a new document * Daniel Huson, 4.2015 */ public class ExtractToNewDocument { /** * extract all named classes in the given classsification to a new RMA6 file * */ public static void apply(Document srcDoc, String srcClassification, Collection<Integer> srcClassIds, String tarRMA6FileName, ProgressListener progress, Single<Long> totalReads) throws IOException { final long startTime = System.currentTimeMillis(); final IConnector connector = srcDoc.getConnector(); final String[] classifications = connector.getAllClassificationNames().clone(); final RMA6FileCreator rma6FileCreator = new RMA6FileCreator(tarRMA6FileName, true); rma6FileCreator.writeHeader(ProgramProperties.getProgramVersion(), srcDoc.getBlastMode(), classifications, false); rma6FileCreator.startAddingQueries(); try { // user might cancel inside this block // determine the set of all positions to extract: try (IReadBlockIterator iterator = connector.getReadsIteratorForListOfClassIds(srcClassification, srcClassIds, 0, 10, true, true)) { progress.setTasks("Extracting", "Processing file: " + FileUtils.getFileNameWithoutPath(srcDoc.getMeganFile().getFileName())); progress.setProgress(0); progress.setMaximum(iterator.getMaximumProgress()); while (iterator.hasNext()) { final IReadBlock readBlock = iterator.next(); totalReads.set(totalReads.get() + 1); final int numberOfMatches = readBlock.getNumberOfAvailableMatchBlocks(); final StringBuilder blastTextBuf = new StringBuilder(); blastTextBuf.append(FileLineIterator.PREFIX_TO_INDICATE_TO_PARSE_FILENAME_STRING); blastTextBuf.append("Query= ").append(readBlock.getReadHeader()).append("\n"); final int[][] match2classification2id = new int[numberOfMatches][classifications.length]; for (int m = 0; m < numberOfMatches; m++) { final IMatchBlock matchBlock = readBlock.getMatchBlock(m); blastTextBuf.append(matchBlock.getText()); for (int k = 0; k < classifications.length; k++) { match2classification2id[m][k] = matchBlock.getId(classifications[k]); } } final byte[] readBytes = (">" + readBlock.getReadHeader() + "\n" + readBlock.getReadSequence()).getBytes(); final byte[] matchBytes = computeSAM(srcDoc.getBlastMode(), numberOfMatches, blastTextBuf.toString()); rma6FileCreator.addQuery(readBytes, readBytes.length, numberOfMatches, matchBytes, matchBytes.length, match2classification2id, 0L); progress.setProgress(iterator.getProgress()); } } } finally { // finish file, whether user has canceled or not... rma6FileCreator.endAddingQueries(); rma6FileCreator.writeClassifications(new String[0], null, null); rma6FileCreator.writeAuxBlocks(null); rma6FileCreator.close(); final Document doc = new Document(); doc.setProgressListener(progress); doc.getMeganFile().setFile(tarRMA6FileName, MeganFile.Type.RMA6_FILE); doc.getActiveViewers().addAll(Arrays.asList(classifications)); } System.err.println("Extraction required " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds"); } /** * compute SAM representation * */ private static byte[] computeSAM(BlastMode blastMode, int maxNumberOfReads, String matchesText) throws IOException { final ISAMIterator iterator; switch (blastMode) { case BlastN -> { final BlastN2SAMIterator blastN2SAMIterator = new BlastN2SAMIterator(matchesText, maxNumberOfReads); blastN2SAMIterator.setReportAllMatchesInOriginalOrder(true); iterator = blastN2SAMIterator; } case BlastP -> { final BlastP2SAMIterator blastP2SAMIterator = new BlastP2SAMIterator(matchesText, maxNumberOfReads); blastP2SAMIterator.setReportAllMatchesInOriginalOrder(true); iterator = blastP2SAMIterator; } case BlastX -> { final BlastX2SAMIterator blastX2SAMIterator = new BlastX2SAMIterator(matchesText, maxNumberOfReads); blastX2SAMIterator.setReportAllMatchesInOriginalOrder(true); iterator = blastX2SAMIterator; } default -> throw new IOException("Invalid BLAST mode: " + blastMode); } try { // don't want any long read optimizations as they will change the order of the reads! iterator.next(); return iterator.getMatchesText(); } finally { iterator.close(); } } }
6,478
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
FindSelection.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/FindSelection.java
/* * FindSelection.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * selector where to match regular expressions in find * Daniel Huson, 4.2010 */ public class FindSelection { public boolean useReadName = false; public final boolean useReadHeader = false; public final boolean useReadSequence = false; public final boolean useMatchText = false; /** * does the given readBlock match the given pattern * * @return true, if match */ static public boolean doesMatch(FindSelection findSelection, IReadBlock readBlock, Pattern pattern) { try { if (findSelection.useReadName && matches(pattern, readBlock.getReadName())) return true; if (findSelection.useReadHeader && matches(pattern, readBlock.getReadHeader())) return true; if (findSelection.useReadSequence && matches(pattern, readBlock.getReadSequence())) return true; if (findSelection.useMatchText) { for (int i = 0; i < readBlock.getNumberOfAvailableMatchBlocks(); i++) { if (matches(pattern, readBlock.getMatchBlock(i).getText())) return true; } } } catch (Exception ignored) { } return false; } /** * does label match pattern? * * @return true, if match */ private static boolean matches(Pattern pattern, String label) { if (label == null) label = ""; Matcher matcher = pattern.matcher(label); return matcher.find(); } }
2,444
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IReadBlock.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/IReadBlock.java
/* * IReadBlock.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import java.io.Serializable; /** * interface to ReadBlock * Daniel Huson, 4.2010 */ public interface IReadBlock extends Serializable { /** * get the unique identifier for this read (unique within a dataset). * In an RMA file, this is always the file position for the read * * @return uid */ long getUId(); void setUId(long uid); /** * get the name of the read (first word in header) * * @return name */ String getReadName(); /** * get the fastA header for the read * * @return fastA header */ String getReadHeader(); void setReadHeader(String readHeader); /** * get the sequence of the read * * @return sequence */ String getReadSequence(); void setReadSequence(String readSequence); /** * gets the uid of the mated read * * @return uid of mate or 0 */ long getMateUId(); void setMateUId(long mateReadUId); /** * get the mate type * Possible values: FIRST_MATE, SECOND_MATE * * @return mate type * @deprecated */ @Deprecated byte getMateType(); /** * get mate type * * @deprecated */ @Deprecated void setMateType(byte type); /** * set the read length * */ void setReadLength(int readLength); int getReadLength(); /** * get the complexity * */ void setComplexity(float complexity); float getComplexity(); /** * set the weight of a read * */ void setReadWeight(int weight); /** * get the weight of a read * * @return weight */ int getReadWeight(); /** * get the original number of matches * * @return number of matches */ int getNumberOfMatches(); void setNumberOfMatches(int numberOfMatches); /** * gets the current number of matches available * */ int getNumberOfAvailableMatchBlocks(); /** * get the matches. May be less than the original number of matches (when filtering matches) * */ IMatchBlock[] getMatchBlocks(); void setMatchBlocks(IMatchBlock[] matchBlocks); /** * get the i-th match block * * @return match block */ IMatchBlock getMatchBlock(int i); }
3,151
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IConnector.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/IConnector.java
/* * IConnector.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import jloda.util.Single; import jloda.util.progress.ProgressListener; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map; /** * connection to RMA file, remote RMA file or database * Daniel Huson, 4.2010 */ public interface IConnector { // classification names used below are defined in ClassificationBlock /** * set the file name of interest. Only one file can be used. * */ void setFile(String filename) throws IOException; public String getFilename(); /** * is connected document readonly? * * @return true, if read only */ boolean isReadOnly(); /** * gets the unique identifier for the given filename. * This method is also used to test whether dataset exists and can be connected to * * @return unique id */ long getUId() throws IOException; /** * get all reads with specified matches. If minScore=0 and topPercent=0, no filtering * * @param minScore ignore * @param maxExpected ignore */ IReadBlockIterator getAllReadsIterator(float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException; /** * get getLetterCodeIterator over all reads for given classification and classId. If minScore=0 and topPercent=0, no filtering * * @param minScore ignore * @param maxExpected ignore */ IReadBlockIterator getReadsIterator(String classification, int classId, float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException; /** * get getLetterCodeIterator over all reads for given classification and a collection of classids. If minScore=0 and topPercent=0, no filtering * * @return getLetterCodeIterator over reads filtered by given parameters */ IReadBlockIterator getReadsIteratorForListOfClassIds(String classification, Collection<Integer> classIds, float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException; /** * gets a read block accessor * * @param minScore ignored * @param maxExpected ignored */ IReadBlockGetter getReadBlockGetter(float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException; /** * get array of all classification names associated with this file or db * * @return classifications */ String[] getAllClassificationNames() throws IOException; /** * gets the number of classes in the named classification * * @return number of classes */ int getClassificationSize(String classificationName) throws IOException; /** * gets the number of reads in a given class * * @return number of reads */ int getClassSize(String classificationName, int classId) throws IOException; /** * gets the named classification block * * @return classification block */ IClassificationBlock getClassificationBlock(String classificationName) throws IOException; /** * updates the classId values for a collection of reads * * @param classificationNames names of classifications in the order that their values will appear in * @param updateItems list of rescan items */ void updateClassifications(final String[] classificationNames, final List<UpdateItem> updateItems, ProgressListener progressListener) throws IOException; /** * get all reads that match the given expression * * @param findSelection where to search for matches * @return getLetterCodeIterator over reads that match */ IReadBlockIterator getFindAllReadsIterator(String regEx, FindSelection findSelection, Single<Boolean> canceled) throws IOException; /** * gets the number of reads * * @return number of reads */ int getNumberOfReads() throws IOException; /** * get the total number of matches * * @return number of matches */ int getNumberOfMatches() throws IOException; /** * sets the number of reads. Note that the logical number of reads may differ from * the actual number of reads stored, so this needs to be stored explicitly * */ void setNumberOfReads(int numberOfReads) throws IOException; /** * puts the MEGAN auxiliary data associated with the dataset * */ void putAuxiliaryData(Map<String, byte[]> label2data) throws IOException; /** * gets the MEGAN auxiliary data associated with the dataset * (Old style data should be returned with label USER_STATE) * * @return auxiliaryData */ Map<String, byte[]> getAuxiliaryData() throws IOException; }
5,672
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Stats.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/Stats.java
package megan.data; import java.util.function.Function; /** * will be used for stats * Daniel Huson, 11.2023 */ public class Stats { public static Function<Integer,Boolean> count = c->true; }
198
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IName2IdMap.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/IName2IdMap.java
/* * IName2IdMap.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import java.util.Collection; /** * name to id interface * Daniel Huson, 4.2015 */ public interface IName2IdMap { int get(String name); String get(int id); void put(String name, int id); Collection<Integer> getIds(); Collection<String> getNames(); int size(); }
1,122
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MatchBlockWithLocationAdapter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/MatchBlockWithLocationAdapter.java
/* * MatchBlockWithLocationAdapter.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; /** * adapts a match block to be a match block with location * Daniel Huson, 2.2011 */ public class MatchBlockWithLocationAdapter implements IMatchBlock, IMatchBlockWithLocation { private final IMatchBlock matchBlock; private Location location; public MatchBlockWithLocationAdapter(IMatchBlock matchBlock, Location location) { this.matchBlock = matchBlock; this.location = location; } public long getUId() { return matchBlock.getUId(); } public void setUId(long uid) { matchBlock.setUId(uid); } public int getTaxonId() { return matchBlock.getTaxonId(); } public void setTaxonId(int taxonId) { matchBlock.setTaxonId(taxonId); } @Override public int getId(String cName) { return matchBlock.getId(cName); } @Override public void setId(String cName, Integer id) { matchBlock.setId(cName, id); } /** * gets all defined ids * * @return ids */ public int[] getIds(String[] cNames) { return matchBlock.getIds(cNames); } public float getBitScore() { return matchBlock.getBitScore(); } public void setBitScore(float bitScore) { matchBlock.setBitScore(bitScore); } public float getPercentIdentity() { return matchBlock.getPercentIdentity(); } public void setPercentIdentity(float percentIdentity) { matchBlock.setPercentIdentity(percentIdentity); } public String getRefSeqId() { return matchBlock.getRefSeqId(); } public void setRefSeqId(String refSeqId) { matchBlock.setRefSeqId(refSeqId); } public void setExpected(float expected) { matchBlock.setExpected(expected); } public float getExpected() { return matchBlock.getExpected(); } public void setLength(int length) { matchBlock.setLength(length); } public int getLength() { return matchBlock.getLength(); } public boolean isIgnore() { return matchBlock.isIgnore(); } public void setIgnore(boolean ignore) { matchBlock.setIgnore(ignore); } public String getText() { return matchBlock.getText(); } @Override public String getTextFirstWord() { return matchBlock.getTextFirstWord(); } public void setText(String text) { matchBlock.setText(text); } public String toString() { return matchBlock + (location != null ? "\n" + location : ""); } public Location getTextLocation() { return location; } public void setTextLocation(Location location) { this.location = location; } @Override public int getAlignedQueryStart() { return matchBlock.getAlignedQueryStart(); } @Override public int getAlignedQueryEnd() { return matchBlock.getAlignedQueryEnd(); } @Override public int getRefLength() { return matchBlock.getRefLength(); } }
3,870
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
TextStoragePolicy.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/TextStoragePolicy.java
/* * TextStoragePolicy.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import jloda.util.NumberUtils; /** * Constants for the different storage policies * Daniel Huson, 10.2010 */ public enum TextStoragePolicy { Embed, Reference, InRMAZ; public static String getDescription(TextStoragePolicy policy) { return switch (policy) { case Embed -> "Embed matches and reads in MEGAN file"; case Reference -> "Save references to original files for lookup of matches and reads"; case InRMAZ -> "Save matches and reads in an auxiliary .rmaz file"; }; } /** * get value of label ignoring case * * @return value */ public static TextStoragePolicy valueOfIgnoreCase(String label) { for (TextStoragePolicy policy : values()) { if (label.equalsIgnoreCase(policy.toString())) return policy; } if (NumberUtils.isInteger(label)) return fromId(NumberUtils.parseInt(label)); else return null; } /** * gets an id * */ public static int getId(TextStoragePolicy policy) { return switch (policy) { case Embed -> 0; case Reference -> 1; case InRMAZ -> 2; }; } public static TextStoragePolicy fromId(int id) { return switch (id) { case 0 -> Embed; case 1 -> Reference; case 2 -> InRMAZ; default -> null; }; } }
2,217
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ReadBlockIteratorCombiner.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/ReadBlockIteratorCombiner.java
/* * ReadBlockIteratorCombiner.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import java.io.IOException; /** * combines multiple read block iterators into one * Created by huson on 5/24/17. */ public class ReadBlockIteratorCombiner implements IReadBlockIterator { private final IReadBlockIterator[] iterators; private int which = 0; private long maxProgress = 0; private long prevProgress = 0; public ReadBlockIteratorCombiner(final IReadBlockIterator[] iterators) { this.iterators = iterators; for (IReadBlockIterator iterator : iterators) { maxProgress += iterator.getMaximumProgress(); } } @Override public String getStats() { return iterators[which].getStats(); } @Override public void close() throws IOException { for (IReadBlockIterator iterator : iterators) iterator.close(); } @Override public long getMaximumProgress() { return maxProgress; } @Override public long getProgress() { return prevProgress + iterators[which].getProgress(); } @Override public boolean hasNext() { while (which < iterators.length) { if (iterators[which].hasNext()) return true; else { prevProgress += iterators[which].getMaximumProgress(); which++; } } return false; } @Override public IReadBlock next() { while (which < iterators.length) { if (iterators[which].hasNext()) { IReadBlock readBlock = iterators[which].next(); long bits = ((long) which << 54); // we use the top bits of the UID to track which dataset the read comes from readBlock.setUId(readBlock.getUId() | bits); return readBlock; } else { prevProgress += iterators[which].getMaximumProgress(); which++; } } return null; } @Override public void remove() { } }
2,845
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IMatchBlockWithLocation.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/IMatchBlockWithLocation.java
/* * IMatchBlockWithLocation.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; /** * DESCRIPTION * Daniel Huson, DATE */ public interface IMatchBlockWithLocation extends IMatchBlock { Location getTextLocation(); void setTextLocation(Location location); }
1,028
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
UpdateItem.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/UpdateItem.java
/* * UpdateItem.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import java.util.Comparator; /** * records necessary updates to data * Daniel Huson, 1.2009 */ public class UpdateItem { private long readUId; // position of read private UpdateItem[] nextInClass; // next item in each classification private int[] classId; // class id /** * only for use as comparable item */ public UpdateItem() { } /** * constructor * */ public UpdateItem(int numberClassifications) { nextInClass = new UpdateItem[numberClassifications]; classId = new int[numberClassifications]; } /** * Get classIds * */ public int[] getClassIds() { return classId; } public UpdateItem getNextInClassification(int classificationId) { return nextInClass[classificationId]; } public void setNextInClassifaction(int classificationId, UpdateItem item) { nextInClass[classificationId] = item; } public long getReadUId() { return readUId; } public void setReadUId(long readUId) { this.readUId = readUId; } public int getClassId(int i) { return classId[i]; } public void setClassId(int i, int classId) { this.classId[i] = classId; } public int size() { return nextInClass.length; } public String toString() { StringBuilder buf = new StringBuilder(); buf.append("readUid= ").append(readUId).append(", classIds="); for (int id : classId) buf.append(" ").append(id); buf.append(" nextInClass="); for (UpdateItem nextInClas : nextInClass) buf.append(" ").append(nextInClas.getReadUId()); return buf.toString(); } public static Comparator<UpdateItem> getComparator() { return (a, b) -> { if (a.readUId < b.readUId) return -1; else if (a.readUId > b.readUId) return 1; else { for (int i = 0; i < a.classId.length; i++) { if (a.classId[i] < b.classId[i]) return -1; else if (a.classId[i] > b.classId[i]) return 1; } } return 0; }; } }
3,078
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MatchBlockFromBlast.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/MatchBlockFromBlast.java
/* * MatchBlockFromBlast.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import megan.rma2.MatchBlockRMA2; /** * MatchBlock with information on location of text in file * Daniel Huson, 10.2010 */ public class MatchBlockFromBlast extends MatchBlockRMA2 implements IMatchBlock, IMatchBlockWithLocation { private Location location; /** * constructor */ public MatchBlockFromBlast() { } /** * gets the location of the text * * @return location of read text or null */ public Location getTextLocation() { return location; } /** * sets the location of the text * */ public void setTextLocation(Location location) { this.location = location; } /** * erase the block */ public void clear() { super.clear(); location = null; } }
1,629
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
LocationManager.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/LocationManager.java
/* * LocationManager.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import java.io.File; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import java.util.Vector; /** * manages locations of read and match texts * Daniel Huson, 10.2010 */ public class LocationManager { private final Vector<File> files = new Vector<>(); private final Vector<Long> fileSizes = new Vector<>(); private final Map<File, Integer> file2id = new HashMap<>(); private final TextStoragePolicy textStoragePolicy; /** * constructor * */ public LocationManager(TextStoragePolicy textStoragePolicy) { this.textStoragePolicy = textStoragePolicy; } /** * constructor * * @param fileName file to add */ public LocationManager(TextStoragePolicy textStoragePolicy, String fileName) { this.textStoragePolicy = textStoragePolicy; if (fileName != null) addFile(new File(fileName)); } /** * gets the id of the file, adds it if not already present * * @return id */ public int getFileId(File file) { Integer id = file2id.get(file); if (id == null) { id = file2id.size(); file2id.put(file, id); files.add(id, file); fileSizes.add(id, file.length()); // System.err.println("Added file, id: " + id + ", file: " + files.get(id)); } return id; } /** * add a file, if not already present * */ public void addFile(File file) { getFileId(file); } /** * add a file, if not already present and explicitly set its size * */ public void addFile(File file, Long fileSize) { int fileId = getFileId(file); if (fileSize != null) fileSizes.set(fileId, fileSize); } /** * get the file associated with the given id * */ public File getFile(int fileId) { return files.get(fileId); } /** * get all files * * @return files */ public Vector<File> getFiles() { return files; } /** * get all file names * * @return file names */ public String[] getFileNames() { String[] fileNames = new String[files.size()]; for (int i = 0; i < files.size(); i++) fileNames[i] = files.get(i).getPath(); return fileNames; } /** * gets all the file sizes * * @return file sizes */ public Long[] getFileSizes() { Long[] array = new Long[files.size()]; for (int i = 0; i < fileSizes.size(); i++) array[i] = fileSizes.get(i); return array; } /** * get the location type * * @return type */ public TextStoragePolicy getTextStoragePolicy() { return textStoragePolicy; } /** * get as string * * @return string */ public String toString() { StringWriter w = new StringWriter(); w.write("Storage: " + TextStoragePolicy.getDescription(textStoragePolicy) + "\n"); for (int i = 0; i < files.size(); i++) { w.write(" " + i + " -> " + files.get(i).getPath() + "\n"); } return w.toString(); } /** * get mapping of files to ids * * @return files to ids */ public Map<File, Integer> getMapping() { return file2id; } }
4,225
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
UpdateItemList.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/UpdateItemList.java
/* * UpdateItemList.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; import java.io.IOException; import java.util.*; /** * list of necessary updates to RMA file * Daniel Huson, 1.2009 */ public class UpdateItemList extends LinkedList<UpdateItem> { private final int numberOfClassifications; private final Map<Integer, UpdateItem>[] first; private final Map<Integer, UpdateItem>[] last; private final Map<Integer, Float>[] weights; /** * constructor * */ @SuppressWarnings("unchecked") public UpdateItemList(int numberOfClassifications) { super(); this.numberOfClassifications = numberOfClassifications; first = new HashMap[numberOfClassifications]; last = new HashMap[numberOfClassifications]; weights = new HashMap[numberOfClassifications]; for (int i = 0; i < numberOfClassifications; i++) { first[i] = new HashMap<>(1000000); last[i] = new HashMap<>(1000000); weights[i] = new HashMap<>(1000000); } } /** * add an item * */ public void addItem(final long readUid, float readWeight, final int[] classIds) throws IOException { if (classIds.length != numberOfClassifications) throw new IOException("classIds has wrong length: " + classIds.length + ", should be: " + numberOfClassifications); final UpdateItem item = new UpdateItem(numberOfClassifications); item.setReadUId(readUid); add(item); if (readWeight == 0) { // throw new RuntimeException("Internal error: ReadWeight=0"); readWeight = 1; } for (int i = 0; i < numberOfClassifications; i++) { final int id = classIds[i]; if (id != 0) { item.setClassId(i, id); UpdateItem lastInClass = last[i].get(id); if (lastInClass == null) { first[i].put(id, item); last[i].put(id, item); weights[i].put(id, readWeight); } else { lastInClass.setNextInClassifaction(i, item); last[i].put(id, item); weights[i].put(id, weights[i].get(id) + readWeight); } } } } /** * get the weighted size of a class for a given classification * * @return size of class */ public float getWeight(int classificationId, int classId) { Float result = weights[classificationId].get(classId); return Objects.requireNonNullElse(result, 0f); } private void setWeight(int classificationId, int classId, float weight) { this.weights[classificationId].put(classId, weight); } /** * gets the mapping of class ids to sizes for a given classification * * @return class-id to size map */ public Map<Integer, Float> getClassIdToWeightMap(int classificationId) { return weights[classificationId]; } /** * get the first UpdateItem for a given classification and class * * @return first */ public UpdateItem getFirst(int classificationId, int classId) { return first[classificationId].get(classId); } /** * set the first UpdateItem for a given classification and class * */ private void setFirst(int classificationId, int classId, UpdateItem item) { first[classificationId].put(classId, item); } /** * get the last UpdateItem for a given classification and class * * @return first */ private UpdateItem getLast(int classificationId, int classId) { return last[classificationId].get(classId); } /** * set the last UpdateItem for a given classification and class * */ private void setLast(int classificationId, int classId, UpdateItem item) { last[classificationId].put(classId, item); } /** * gets the set of class ids defined for a given classification * */ public Set<Integer> getClassIds(int classificationId) { return first[classificationId].keySet(); } /** * remove the given class from the given classification * */ private void removeClass(int classificationId, int classId) { first[classificationId].put(classId, null); first[classificationId].remove(classId); last[classificationId].put(classId, null); last[classificationId].remove(classId); weights[classificationId].put(classId, null); weights[classificationId].remove(classId); } /** * append the src class to the target class * */ public void appendClass(int classificationId, int srcClassId, int tarClassId) { float newSize = getWeight(classificationId, srcClassId) + getWeight(classificationId, tarClassId); if (newSize > 0) { UpdateItem firstItemSrc = getFirst(classificationId, srcClassId); if (firstItemSrc == null) { System.err.println("Warning: srcClassId=" + srcClassId + ", tarClassId=" + tarClassId + " firstItemSrc=null"); return; } // replace class for all elements in src class: UpdateItem item = firstItemSrc; while (item != null) { item.setClassId(classificationId, tarClassId); item = item.getNextInClassification(classificationId); } // rescan first and last items: UpdateItem firstItemTar = getFirst(classificationId, tarClassId); if (firstItemTar == null) setFirst(classificationId, tarClassId, firstItemSrc); UpdateItem lastItemTar = getLast(classificationId, tarClassId); if (lastItemTar != null) lastItemTar.setNextInClassifaction(classificationId, firstItemSrc); UpdateItem lastItemSrc = getLast(classificationId, srcClassId); setLast(classificationId, tarClassId, lastItemSrc); setWeight(classificationId, tarClassId, newSize); removeClass(classificationId, srcClassId); sortChain(classificationId, tarClassId); } } /** * after appending a class to an existing class, sorts all UpdateItems so that they appear in the order in * which the reads occur in the file, for a given classId. * This is useful for when we extract all reads for a given classId, as then we go through the file sequentially * */ private void sortChain(int classificationId, int classId) { // sort all UpdateItems by readUid: final ArrayList<UpdateItem> sorted = new ArrayList<>(100000); UpdateItem item = getFirst(classificationId, classId); while (item != null) { sorted.add(item); item = item.getNextInClassification(classificationId); } sorted.sort(UpdateItem.getComparator()); // re-build chain: UpdateItem first = null; UpdateItem prev = null; UpdateItem last = null; for (UpdateItem current : sorted) { if (first == null) first = current; if (prev != null) prev.setNextInClassifaction(classificationId, current); prev = current; last = current; } if (first != null) setFirst(classificationId, classId, first); if (last != null) { setLast(classificationId, classId, last); last.setNextInClassifaction(classificationId, null); } } }
8,389
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IReadBlockIteratorFromBlast.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/IReadBlockIteratorFromBlast.java
/* * IReadBlockIteratorFromBlast.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.data; /** * Iterator over a set of read blocks * Daniel Huson, 4.2010 */ interface IReadBlockIteratorFromBlast extends IReadBlockIterator { /** * gets the location manager for the blast and read files * * @return location manager */ LocationManager getLocationManager(); int getTotalReads(); int getTotalMatches(); int getTotalNoHits(); int getTotalDiscardedMatches(); int getCountParseErrors(); int getMaxMatchesPerRead(); void setMaxMatchesPerRead(int maxMatchesPerRead); }
1,380
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MergeReadBlock.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/merge/MergeReadBlock.java
package megan.data.merge; import megan.data.IMatchBlock; import megan.data.IReadBlock; /** * readblock used in bundle * The getUid() methods contains the file number in its two most signficant bytes */ public class MergeReadBlock implements IReadBlock { private final IReadBlock readBlock; private final int fileNumber; public MergeReadBlock(int fileNumber, IReadBlock readBlock) { this.fileNumber=fileNumber; this.readBlock=readBlock; } @Override public long getUId() { return getCombinedFileNumberAndUid(fileNumber,readBlock.getUId()); } @Override public void setUId(long uid) { readBlock.setUId(uid); } @Override public String getReadName() { return readBlock.getReadName(); } @Override public String getReadHeader() { return readBlock.getReadHeader(); } @Override public void setReadHeader(String readHeader) { readBlock.setReadHeader(readHeader); } @Override public String getReadSequence() { return readBlock.getReadSequence(); } @Override public void setReadSequence(String readSequence) { readBlock.setReadSequence(readSequence); } @Override public long getMateUId() { return ((long)fileNumber <<48) | readBlock.getMateUId(); } @Override public void setMateUId(long mateReadUId) { readBlock.setMateUId(mateReadUId); } @Override public byte getMateType() { return readBlock.getMateType(); } @Override public void setMateType(byte type) { readBlock.setMateType(type); } @Override public void setReadLength(int readLength) { readBlock.setReadLength(readLength); } @Override public int getReadLength() { return readBlock.getReadLength(); } @Override public void setComplexity(float complexity) { readBlock.setComplexity(complexity); } @Override public float getComplexity() { return readBlock.getComplexity(); } @Override public void setReadWeight(int weight) { readBlock.setReadWeight(weight); } @Override public int getReadWeight() { return readBlock.getReadWeight(); } @Override public int getNumberOfMatches() { return readBlock.getNumberOfMatches(); } @Override public void setNumberOfMatches(int numberOfMatches) { readBlock.setNumberOfMatches(numberOfMatches); } @Override public int getNumberOfAvailableMatchBlocks() { return readBlock.getNumberOfAvailableMatchBlocks(); } @Override public IMatchBlock[] getMatchBlocks() { return readBlock.getMatchBlocks(); } @Override public void setMatchBlocks(IMatchBlock[] matchBlocks) { readBlock.setMatchBlocks(matchBlocks); } @Override public IMatchBlock getMatchBlock(int i) { return readBlock.getMatchBlock(i); } public static long getCombinedFileNumberAndUid(int fileNumber,long uid) { return ((long)fileNumber<<48) | uid; } public static long getOriginalUid(long uidWithFileNumber) { return uidWithFileNumber & 0x00FFFFFFFFFFFFFFFL; } public static int getFileNumber(long uidWithFileNumber) { return (int)(uidWithFileNumber >>>48); } }
2,957
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MergeReaderGetter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/merge/MergeReaderGetter.java
package megan.data.merge; import jloda.util.FunctionWithIOException; import megan.data.IReadBlock; import megan.data.IReadBlockGetter; import java.io.IOException; import java.util.*; /** * read getter for a bundle of files * Daniel Huson, 5.2022 */ public class MergeReaderGetter implements IReadBlockGetter { private final Set<Integer> fileNumbers=new TreeSet<>(); private final Map<Integer,IReadBlockGetter> fileGetterMap=new HashMap<>(); private final FunctionWithIOException<Integer,IReadBlockGetter> fileReadGetterFunction; private long count=0; public MergeReaderGetter(Collection<Integer> fileNumbers, FunctionWithIOException<Integer,IReadBlockGetter> fileIReadBlockGetterFunction) throws IOException { this.fileNumbers.addAll(fileNumbers); this.fileReadGetterFunction =fileIReadBlockGetterFunction; } @Override public IReadBlock getReadBlock(long uid) throws IOException { var fileId= MergeReadBlock.getFileNumber(uid); if(fileNumbers.contains(fileId)) { uid = MergeReadBlock.getOriginalUid(uid); if(uid>=0) { var readGetter = fileGetterMap.get(fileId); if (readGetter == null) { readGetter = fileReadGetterFunction.apply(fileId); fileGetterMap.put(fileId, readGetter); } return readGetter.getReadBlock(uid); } } return null; } @Override public void close() { for(var readGetter:fileGetterMap.values()) { readGetter.close(); } } @Override public long getCount() { if(count==0) { for(var fileId:fileNumbers) { var readGetter = fileGetterMap.get(fileId); if (readGetter == null) { try { readGetter = fileReadGetterFunction.apply(fileId); fileGetterMap.put(fileId, readGetter); count+=readGetter.getCount(); } catch (IOException ignored) { } } } } return count; } }
1,807
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MergeConnector.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/merge/MergeConnector.java
package megan.data.merge; import jloda.util.BiFunctionWithIOException; import jloda.util.FunctionWithIOException; import jloda.util.NumberUtils; import jloda.util.Single; import jloda.util.progress.ProgressListener; import megan.core.DataTable; import megan.core.MeganFile; import megan.core.SampleAttributeTable; import megan.core.SyncArchiveAndDataTable; import megan.data.*; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.util.*; /** * opens a set of DAA or RMA files as a merged summary file * Daniel Huson, 5.2022 */ public class MergeConnector implements IConnector { private String fileName; private final ArrayList<MeganFile> files=new ArrayList<>(); private final Map<String,IClassificationBlock> classificationNameBlockMap=new HashMap<>(); private final Map<String,Integer> classificationSizeMap=new HashMap<>(); private String[] allClassificationNames; private int numberOfReads=0; private int numberOfMatches=0; private final Map<String, byte[]> auxiliaryData=new HashMap<>(); public static FunctionWithIOException<Collection<String>,Boolean> checkConnectors; static { checkConnectors=files->{ var ok=true; for(var file:files) { if(!MeganFile.hasReadableDAAConnector(file)) { ok=false; System.err.println("Warning: File not found or not of required type: "+file); } } return ok; }; } public MergeConnector(String fileName, Collection<String> inputFiles) throws IOException { setFile(fileName); setInputFiles(inputFiles); } @Override public String getFilename() { return fileName; } public static boolean canOpenAllConnectors(Collection<String> fileNames) throws IOException { return fileNames.size()>0 && checkConnectors.apply(fileNames); } @Override public void setFile(String filename) throws IOException { this.fileName=filename; files.clear(); classificationSizeMap.clear(); numberOfReads=0; numberOfMatches=0; } public void setInputFiles(Collection<String> inputFiles) throws IOException { files.clear(); classificationSizeMap.clear(); numberOfReads=0; numberOfMatches=0; var classificationNames=new ArrayList<String>(); for(var name:inputFiles) { var meganFile = new MeganFile(); meganFile.setFileFromExistingFile(name, true); if (meganFile.hasDataConnector()) { files.add(meganFile); var connector=meganFile.getConnector(); numberOfReads+=connector.getNumberOfReads(); numberOfMatches+=connector.getNumberOfMatches(); for(var cName:connector.getAllClassificationNames()) { var size=connector.getClassificationSize(cName); classificationSizeMap.put(cName,classificationSizeMap.getOrDefault(cName,0)+size); if(!classificationNames.contains(cName)) classificationNames.add(cName); } } else { System.err.println("Not a DAA or RMA file, skipped: "+name); } } allClassificationNames=classificationNames.toArray(new String[0]); if(files.size()==0) throw new IOException("Bundle does not contain any existing DAA or RMA files: "+fileName); } @Override public boolean isReadOnly() { return true; } @Override public long getUId() throws IOException { return Files.readAttributes(Paths.get(fileName), BasicFileAttributes.class).creationTime().toMillis(); } @Override public IReadBlockIterator getAllReadsIterator(float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException { return new MergeReadIterator(files, f->f.getConnector().getAllReadsIterator(minScore,maxExpected,wantReadSequence,wantMatches)); } @Override public IReadBlockIterator getReadsIterator(String classification, int classId, float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException { return new MergeReadIterator(files, f->f.getConnector().getReadsIterator(classification,classId,minScore,maxExpected,wantReadSequence,wantMatches)); } @Override public IReadBlockIterator getReadsIteratorForListOfClassIds(String classification, Collection<Integer> classIds, float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException { return new MergeReadIterator(files, f->f.getConnector().getReadsIteratorForListOfClassIds(classification,classIds,minScore,maxExpected,wantReadSequence,wantMatches)); } @Override public IReadBlockGetter getReadBlockGetter(float minScore, float maxExpected, boolean wantReadSequence, boolean wantMatches) throws IOException { return new MergeReaderGetter( NumberUtils.range(0,files.size()), f->files.get(f).getConnector().getReadBlockGetter(minScore,maxExpected,wantReadSequence,wantMatches)); } @Override public String[] getAllClassificationNames() throws IOException { return allClassificationNames; } @Override public int getClassificationSize(String classificationName) throws IOException { return classificationSizeMap.get(classificationName); } @Override public int getClassSize(String classificationName, int classId) throws IOException { var size = 0; for (var file : files) { size+=file.getConnector().getClassSize(classificationName,classId); } return size; } @Override public IClassificationBlock getClassificationBlock(String classificationName) throws IOException { var classificationBlock=classificationNameBlockMap.get(classificationName); if(classificationBlock==null) { classificationBlock = new MergeClassificationBlock(classificationName, files); classificationNameBlockMap.put(classificationName, classificationBlock); } return classificationBlock; } @Override public void updateClassifications(String[] classificationNames, List<UpdateItem> updateItems, ProgressListener progressListener) throws IOException { throw new RuntimeException("Read only"); } @Override public IReadBlockIterator getFindAllReadsIterator(String regEx, FindSelection findSelection, Single<Boolean> canceled) throws IOException { return new MergeReadIterator(files, f->f.getConnector().getFindAllReadsIterator(regEx,findSelection,canceled)); } @Override public int getNumberOfReads() throws IOException { return numberOfReads; } @Override public int getNumberOfMatches() throws IOException { return numberOfMatches; } @Override public void setNumberOfReads(int numberOfReads) throws IOException { throw new RuntimeException("Read only"); } @Override public void putAuxiliaryData(Map<String, byte[]> label2data) throws IOException { throw new RuntimeException("Read only"); } @Override public Map<String, byte[]> getAuxiliaryData() throws IOException { if(auxiliaryData.size()==0) { auxiliaryData.putAll(createAuxiliaryData(fileName,files)); } return auxiliaryData; } public static Map<String, byte[]> createAuxiliaryData(String fileName,Collection<MeganFile> inputFiles) throws IOException { var auxiliaryData=new HashMap<String,byte[]>(); var table = new DataTable(); for(var file:inputFiles) { var label2data = file.getConnector().getAuxiliaryData(); if(table.getNumberOfSamples()==0) { SyncArchiveAndDataTable.syncAux2Summary(fileName, label2data.get(SampleAttributeTable.USER_STATE), table); if (label2data.containsKey(SampleAttributeTable.SAMPLE_ATTRIBUTES)) { auxiliaryData.put(SampleAttributeTable.SAMPLE_ATTRIBUTES, label2data.get(SampleAttributeTable.SAMPLE_ATTRIBUTES)); } } else { // add counts: var otherTable=new DataTable(); SyncArchiveAndDataTable.syncAux2Summary(fileName, label2data.get(SampleAttributeTable.USER_STATE), otherTable); for(var classification:otherTable.getClassification2Class2Counts().keySet()){ var classMap=table.getClass2Counts(classification); var otherMap=otherTable.getClass2Counts(classification); for(var id:otherMap.keySet()) { var other=otherMap.get(id); if(other!=null) { var array=classMap.get(id); if(array!=null) { array[0]+=other[0]; } else { classMap.put(id,other); } } } }; table.setTotalReads(table.getTotalReads()+otherTable.getTotalReads()); table.setTotalReadWeights(table.getTotalReadWeights()+otherTable.getTotalReadWeights()); table.setSamples(new String[]{fileName},new Long[]{table.getSampleUIds()[0]}, new float[]{table.getSampleSizes()[0]+otherTable.getSampleSizes()[0]},table.getBlastModes()); } } auxiliaryData.put(SampleAttributeTable.USER_STATE, table.getUserStateAsBytes()); return auxiliaryData; } }
8,640
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MergeReadIterator.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/merge/MergeReadIterator.java
package megan.data.merge; import jloda.util.FunctionWithIOException; import megan.core.MeganFile; import megan.data.IReadBlock; import megan.data.IReadBlockIterator; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.NoSuchElementException; /** * iterates over all reads in a bundle */ public class MergeReadIterator implements IReadBlockIterator { private int whichFile=-1; private final long numberOfFiles; private IReadBlockIterator current; private final Iterator<IReadBlockIterator> metaIterator; private long countReads =0; public MergeReadIterator(ArrayList<MeganFile> files, FunctionWithIOException<MeganFile,IReadBlockIterator> fileIteratorFunction){ numberOfFiles =files.size(); metaIterator =new Iterator<>() { @Override public boolean hasNext() { return whichFile<files.size(); } @Override public IReadBlockIterator next() { try { return fileIteratorFunction.apply(files.get(++whichFile)); } catch (Exception e) { return null; } } }; current= metaIterator.next(); while(current!=null && !current.hasNext()) { try { current.close(); } catch (IOException ignored) { } if(metaIterator.hasNext()) current= metaIterator.next(); else current=null; } } @Override public void close() throws IOException { if(current!=null) current.close(); } @Override public long getMaximumProgress() { return numberOfFiles; } @Override public long getProgress() { return whichFile; } @Override public String getStats() { return "Reads: " + countReads; } @Override public boolean hasNext() { return current!=null && current.hasNext(); } @Override public IReadBlock next() { if(current==null) throw new NoSuchElementException(); var next=current.next(); while(current!=null && !current.hasNext()) { try { current.close(); } catch (IOException ignored) { } if(metaIterator.hasNext()) current= metaIterator.next(); else current=null; } countReads++; return next; } }
2,078
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MergeClassificationBlock.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/data/merge/MergeClassificationBlock.java
package megan.data.merge; import megan.core.MeganFile; import megan.data.IClassificationBlock; import java.io.IOException; import java.util.*; public class MergeClassificationBlock implements IClassificationBlock { private final ArrayList<MeganFile> files=new ArrayList<>(); private Map<Integer, Integer> id2sum; private Map<Integer, Float> id2weight; private String classificationName; public MergeClassificationBlock(String classificationName, Collection<MeganFile> files0) { this.classificationName=classificationName; files.addAll(files0); } @Override public int getSum(Integer key) { if(id2sum==null) { id2sum=new HashMap<>(); for(var file:files) { try { var classificationBlock = file.getConnector().getClassificationBlock(classificationName); for(var a:classificationBlock.getKeySet()) { id2sum.put(a,id2sum.getOrDefault(a,0)+classificationBlock.getSum(a)); } } catch (IOException ignored) { } } } return id2sum.getOrDefault(key,0); } @Override public void setSum(Integer key, int num) { throw new RuntimeException("Read only"); } @Override public float getWeightedSum(Integer key) { if(id2weight==null) { id2weight=new HashMap<>(); for(var file:files) { try { var classificationBlock = file.getConnector().getClassificationBlock(classificationName); for(var a:classificationBlock.getKeySet()) { id2weight.put(a,id2weight.getOrDefault(a,0f)+classificationBlock.getWeightedSum(a)); } } catch (IOException ignored) { } } } return id2weight.getOrDefault(key,0f); } @Override public void setWeightedSum(Integer key, float num) { throw new RuntimeException("Read only"); } @Override public String getName() { return classificationName; } @Override public void setName(String classificationName) { this.classificationName=classificationName; } @Override public Set<Integer> getKeySet() { if(id2sum==null) { id2sum=new HashMap<>(); for(var file:files) { try { var classificationBlock = file.getConnector().getClassificationBlock(classificationName); for(var a:classificationBlock.getKeySet()) { id2sum.put(a,id2sum.getOrDefault(a,0)+classificationBlock.getSum(a)); } } catch (IOException ignored) { } } } return id2sum.keySet(); } }
2,331
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Megan6.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/main/Megan6.java
/* * Megan6.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.main; import javafx.embed.swing.JFXPanel; import jloda.fx.util.ResourceManagerFX; import jloda.swing.commands.CommandManager; import jloda.swing.graphview.GraphView; import jloda.swing.graphview.NodeView; import jloda.swing.message.MessageWindow; import jloda.swing.util.ArgsOptions; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.swing.window.About; import jloda.swing.window.NotificationsInSwing; import jloda.util.Basic; import jloda.util.PeakMemoryUsageMonitor; import jloda.util.StringUtils; import megan.chart.data.ChartCommandHelper; import megan.classification.data.ClassificationCommandHelper; import megan.core.Director; import megan.util.ClassificationRegistration; import javax.swing.*; import java.awt.*; import java.io.File; /** * MEGAN community version * Daniel Huson 5.2015 */ public class Megan6 { /** * runs MEGAN6 */ public static void main(String[] args) { Runtime.getRuntime().addShutdownHook(new Thread(()->{ try { if (MessageWindow.getInstance() != null) MessageWindow.getInstance().setVisible(false); System.err.println("Total time: " + PeakMemoryUsageMonitor.getSecondsSinceStartString()); System.err.println("Peak memory: " + PeakMemoryUsageMonitor.getPeakUsageString()); } catch(Exception ignored){} })); PeakMemoryUsageMonitor.start(); try { { ResourceManager.insertResourceRoot(megan.resources.Resources.class); // need to read properties so that registration can add external files directory if (ProgramProperties.isMacOS()) MeganProperties.initializeProperties(System.getProperty("user.home") + "/Library/Preferences/Megan.def"); else MeganProperties.initializeProperties(System.getProperty("user.home") + File.separator + ".Megan.def"); ClassificationRegistration.register(true); } ensureInitFXInSwingProgram(); NotificationsInSwing.setTitle("MEGAN6"); //run application (new Megan6()).parseArguments(args); } catch (Throwable th) { //catch any exceptions and the like that propagate up to the top level if (!th.getMessage().equals("Help")) { System.err.println("MEGAN fatal error:" + "\n" + th); Basic.caught(th); System.exit(1); } if (!ArgsOptions.hasMessageWindow()) System.exit(1); } } public static String[] processOpenFileArgs(String[] args) { try { if (args.length == 1 && !args[0].startsWith("-")) {// assume this is a single file name or URL var fileName = args[0]; if (fileName.startsWith("megan:")) fileName = StringUtils.convertPercentEncoding(fileName.substring("megan:".length())); return new String[]{"-f", fileName}; } } catch (Exception ex) { Basic.caught(ex); } return args; } /** * parse command line arguments and launch program * */ private void parseArguments(String[] args) throws Exception { Basic.startCollectionStdErr(); args = processOpenFileArgs(args); GraphView.defaultNodeView.setShape(NodeView.OVAL_NODE); ResourceManager.insertResourceRoot(megan.resources.Resources.class); ResourceManagerFX.addResourceRoot(Megan6.class, "megan.resources"); CommandManager.getGlobalCommands().addAll(ClassificationCommandHelper.getGlobalCommands()); CommandManager.getGlobalCommands().addAll(ChartCommandHelper.getChartDrawerCommands()); ProgramProperties.setProgramName(Version.NAME); ProgramProperties.setProgramVersion(Version.SHORT_DESCRIPTION); ProgramProperties.setProgramLicence("Copyright (C) 2024 Daniel H. Huson. This program comes with ABSOLUTELY NO WARRANTY.\n" + "This is free software, licensed under the terms of the GNU General Public License, Version 3.\n" + "Sources available at: https://github.com/husonlab/megan-ce"); ProgramProperties.setUseGUI(true); final var options = new ArgsOptions(args, this, "MEGAN MetaGenome Analyzer Community Edition"); if (options.isDoHelp()) { Basic.restoreSystemErr(System.out); // send system err to system out System.err.println(Basic.stopCollectingStdErr()); } options.setAuthors("Daniel H. Huson"); options.setVersion(ProgramProperties.getProgramVersion()); options.setLicense(ProgramProperties.getProgramLicence()); final var meganFiles = options.getOption("-f", "files", "MEGAN RMA file(s) to open", new String[0]); final var propertiesFile = options.getOption("-p", "propertiesFile", "Properties file",megan.main.Megan6.getDefaultPropertiesFile()); final var showMessageWindow = !options.getOption("+w", "hideMessageWindow", "Hide message window", false); final var silentMode = options.getOption("-S", "silentMode", "Silent mode", false); Basic.setDebugMode(options.getOption("-d", "debug", "Debug mode", false)); options.done(); if (silentMode) { Basic.hideSystemErr(); Basic.hideSystemOut(); Basic.stopCollectingStdErr(); } MeganProperties.initializeProperties(propertiesFile); final var treeFile = ProgramProperties.get(MeganProperties.TAXONOMYFILE, MeganProperties.DEFAULT_TAXONOMYFILE); About.setVersionStringOffset(205,140); About.setAbout("megan6.png", ProgramProperties.getProgramVersion(), JDialog.DISPOSE_ON_CLOSE,0.25f); About.getAbout().showAbout(); SwingUtilities.invokeLater(() -> { try { final var newDir = Director.newProject(); final var viewer = newDir.getMainViewer(); viewer.getFrame().setVisible(true); if (MessageWindow.getInstance() == null) { MessageWindow.setInstance(new MessageWindow(ProgramProperties.getProgramIcon(), "Messages - MEGAN", viewer.getFrame(), false)); MessageWindow.getInstance().getTextArea().setFont(new Font("Monospaced", Font.PLAIN, 12)); } if (showMessageWindow) Director.showMessageWindow(); Basic.restoreSystemOut(System.err); // send system out to system err System.err.println(Basic.stopCollectingStdErr()); MeganProperties.notifyListChange("RecentFiles"); newDir.executeOpen(treeFile, meganFiles, null); } catch (Exception e) { Basic.caught(e); } }); } public static void ensureInitFXInSwingProgram() { final var jframe = new JFrame("Not used"); jframe.add(new JFXPanel()); } public static String getDefaultPropertiesFile() { if (ProgramProperties.isMacOS()) return System.getProperty("user.home") + "/Library/Preferences/MEGAN.def"; else return System.getProperty("user.home") + File.separator + ".MEGAN.def"; } }
8,186
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Version.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/main/Version.java
/* * Version.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.main; /** * Maintains the version string * * @author huson * Date: 18.12.2003 */ public class Version { static public final String NAME = "MEGAN"; static public final String SHORT_DESCRIPTION = "MEGAN Community Edition (version 6.25.10, built 26 Jan 2024)"; }
1,086
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
CheckForUpdate.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/main/CheckForUpdate.java
/* * CheckForUpdate.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.main; import com.install4j.api.launcher.ApplicationLauncher; import com.install4j.api.update.ApplicationDisplayMode; import com.install4j.api.update.UpdateChecker; import com.install4j.api.update.UpdateDescriptor; import com.install4j.api.update.UpdateDescriptorEntry; import jloda.swing.util.ProgramProperties; import jloda.swing.window.NotificationsInSwing; import jloda.util.Basic; import javax.swing.*; /** * check for update * Daniel Huson, 3.2020 */ public class CheckForUpdate { public static final String programURL = "https://software-ab.cs.uni-tuebingen.de/download/megan6"; public static final String updaterApplicationId = "1691242905"; public static String updates = "updates.xml"; /** * check for update, download and install, if present */ public static void apply() { final boolean verbose = ProgramProperties.get("verbose-check-for-update", false); try { final ApplicationDisplayMode applicationDisplayMode = ProgramProperties.isUseGUI() ? ApplicationDisplayMode.GUI : ApplicationDisplayMode.CONSOLE; final String url = programURL + "/" + updates; if (verbose) System.err.println("URL: " + url); final UpdateDescriptor updateDescriptor = UpdateChecker.getUpdateDescriptor(url, applicationDisplayMode); final UpdateDescriptorEntry possibleUpdate = updateDescriptor.getPossibleUpdateEntry(); if (verbose) System.err.println("Possible update: " + possibleUpdate); if (possibleUpdate == null) { NotificationsInSwing.showInformation("Installed version is up-to-date"); } else { System.err.println("New version available: " + programURL + "/" + possibleUpdate.getFileName()); if (ProgramProperties.isUseGUI()) { final Runnable runnable = () -> { if (verbose) System.err.println("Launching : update installer (id=" + updaterApplicationId + ")..."); ApplicationLauncher.launchApplicationInProcess(updaterApplicationId, null, new ApplicationLauncher.Callback() { public void exited(int exitValue) { if (verbose) System.err.println("Exit value: " + exitValue); } public void prepareShutdown() { ProgramProperties.store(); } }, ApplicationLauncher.WindowMode.FRAME, null); }; SwingUtilities.invokeLater(runnable); } } } catch (Exception e) { Basic.caught(e); NotificationsInSwing.showInformation("Failed to check for updates: " + e); } } }
3,876
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
MeganProperties.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/main/MeganProperties.java
/* * MeganProperties.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.main; import jloda.swing.export.ExportImageDialog; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.util.PropertiesListListener; import megan.util.ReadMagnitudeParser; import java.awt.*; import java.io.File; import java.util.LinkedList; import java.util.StringTokenizer; /** * manages megan properties, in cooperation with jloda.director.Properties * * @author huson Date: 11-Nov-2004 */ public class MeganProperties { // property names public static final String MEGANFILE = "OpenFile"; public static final String SAVEFILE = "SaveFile"; public static final String TAXONOMYFILE = "TaxonomyFile"; public static final String ADDITION_CLASSIFICATION_FILES = "AdditionClassifications"; public static final String CONTAMINANT_FILE = "ContaminantFile"; public static final String MICROBIALATTRIBUTESFILE = "MicrobialAttributesFiles"; private static final String MAPPINGFILE = "MappingFile"; public static final String PARSE_TAXON_NAMES = "UseParseTextTaxonomy"; private static final String EXPORTFILE = "ExportFile"; public static final String RECENTFILES = "RecentFiles"; private static final String MAXRECENTFILES = "MaxRecentFiles"; public static final String EXTRACT_OUTFILE_DIR = "ExtractOutFileDir"; public static final String EXTRACT_OUTFILE_TEMPLATE = "ExtractOutFileTemplate"; public static final String FINDREAD = "FindRead"; public static final String FINDTAXON = "FindTaxon"; public static final String DEFAULT_PROPERTIES = "DefaultParameters"; public static final String BLASTFILE = "BlastFile"; public static final String READSFILE = "ReadsFile"; public static final String CSVFILE = "CSVFile"; public static final String BIOMFILE = "BIOMFile"; private static final String BLASTOUTFILE = "BlastOutFile"; public static final String COMPARISON_STYLE = "CompareStyle"; public static final String DISABLED_TAXA = "DisabledTaxa"; public static final int[] DISABLED_TAXA_DEFAULT = {32644, 37965, 134367, 2323, 28384, 61964, 48510, 47936, 186616, 12908, 48479, 156614, 367897}; public static final String PVALUE_COLOR = "PValueColor"; public static final String INSPECTOR_WINDOW_GEOMETRY = "InspectorWindowGeometry"; public static final String CHART_WINDOW_GEOMETRY = "ChartWindowGeometry"; public static final String TAXA_CHART_WINDOW_GEOMETRY = "TaxaChartWindowGeometry"; public static final String NETWORK_DIRECTORY = "NetworkDirectory"; public static final String PAIRED_READ_SUFFIX1 = "PairedRead1"; public static final String PAIRED_READ_SUFFIX2 = "PairedRead2"; public static final String MININUM_READS_IN_ALIGNMENT = "MinReadsInAlignment"; public static final String DEFAULT_TAXONOMYFILE = "ncbi.tre"; private static final String DEFAULT_MAPPINGFILE = "ncbi.map"; private static final String DEFAULT_MICROBIALATTRIBUTESFILE = "microbialattributes.map"; public static final String TAXONOMIC_CLASSIFICATIONS = "AdditionalTaxonomyViewers"; public static Runnable runnable; /** * sets the program properties * */ public static void initializeProperties(String propertiesFile) { ProgramProperties.setPropertiesFileName(propertiesFile); if(ProgramProperties.isUseGUI()) { ProgramProperties.setProgramIcons(ResourceManager.getIcons("megan16.png", "megan32.png", "megan48.png", "megan64.png", "megan128.png")); } // first set all necessary defaults: ProgramProperties.put(MEGANFILE, System.getProperty("user.dir")); ProgramProperties.put(SAVEFILE, System.getProperty("user.dir")); ProgramProperties.put(EXPORTFILE, System.getProperty("user.dir")); ProgramProperties.put(TAXONOMYFILE, DEFAULT_TAXONOMYFILE); ProgramProperties.put(MAPPINGFILE, DEFAULT_MAPPINGFILE); ProgramProperties.put(MICROBIALATTRIBUTESFILE, DEFAULT_MICROBIALATTRIBUTESFILE); ProgramProperties.put(BLASTFILE, ""); ProgramProperties.put(BLASTOUTFILE, ""); ProgramProperties.put(PVALUE_COLOR, Color.YELLOW); ProgramProperties.put(RECENTFILES, ""); ProgramProperties.put(MAXRECENTFILES, 30); ProgramProperties.put(ExportImageDialog.GRAPHICSFORMAT, ".pdf"); ProgramProperties.put(ExportImageDialog.GRAPHICSDIR, System.getProperty("user.dir")); ProgramProperties.put(DISABLED_TAXA, DISABLED_TAXA_DEFAULT); // then read in file to override defaults: ProgramProperties.load(propertiesFile); if (!ProgramProperties.get("Version", "").equals(ProgramProperties.getProgramName())) { // System.err.println("Version has changed, resetting path to initialization files"); // Version has changed, reset paths to taxonomy ProgramProperties.put("Version", ProgramProperties.getProgramName()); // make sure we find the initialization files: ProgramProperties.put(TAXONOMYFILE, DEFAULT_TAXONOMYFILE); ProgramProperties.put(MAPPINGFILE, DEFAULT_MAPPINGFILE); ProgramProperties.put(MICROBIALATTRIBUTESFILE, DEFAULT_MICROBIALATTRIBUTESFILE); } ProgramProperties.put(MeganProperties.DEFAULT_PROPERTIES, ""); ProgramProperties.put(TAXONOMIC_CLASSIFICATIONS, new String[]{"Taxonomy", "GTDB"}); //ProgramProperties.put(TAXONOMIC_CLASSIFICATIONS,new String[]{}); ReadMagnitudeParser.setEnabled(ProgramProperties.get("allow-read-weights", false)); ReadMagnitudeParser.setUnderScoreEnabled(ProgramProperties.get("allow-read-weights-underscore", false)); ProgramProperties.addPresets(); if(runnable!=null) runnable.run(); } /** * add a file to the recent files list * * @param file c */ public static void addRecentFile(File file) { addRecentFile(file.getPath()); } /** * add a file to the recent files list * */ public static void addRecentFile(String pathName) { int maxRecentFiles = ProgramProperties.get(MAXRECENTFILES, 20); StringTokenizer st = new StringTokenizer(ProgramProperties.get(RECENTFILES, ""), ";"); int count = 1; java.util.List<String> recentFiles = new LinkedList<>(); recentFiles.add(pathName); while (st.hasMoreTokens()) { String next = st.nextToken(); if (!pathName.equals(next)) { recentFiles.add(next); if (++count == maxRecentFiles) break; } } StringBuilder buf = new StringBuilder(); for (String recentFile : recentFiles) buf.append(recentFile).append(";"); ProgramProperties.put(RECENTFILES, buf.toString()); notifyListChange(RECENTFILES); } /** * clears the list of recent files */ public static void clearRecentFiles() { String str = ProgramProperties.get(RECENTFILES, ""); if (str.length() != 0) { ProgramProperties.put(RECENTFILES, ""); notifyListChange(RECENTFILES); } } private static final java.util.List<PropertiesListListener> propertieslistListeners = new LinkedList<>(); /** * notify listeners that list of values for the given name has changed * * @param name such as RecentFiles */ public static void notifyListChange(String name) { java.util.List<String> list = new LinkedList<>(); StringTokenizer st = new StringTokenizer(ProgramProperties.get(name, ""), ";"); while (st.hasMoreTokens()) { list.add(st.nextToken()); } synchronized (propertieslistListeners) { for (PropertiesListListener listener : propertieslistListeners) { if (listener.isInterested(name)) listener.hasChanged(list); } } } /** * add recent file listener * */ public static void addPropertiesListListener(PropertiesListListener listener) { if (!propertieslistListeners.contains(listener)) { synchronized (propertieslistListeners) { propertieslistListeners.add(listener); } } } /** * remove recent file listener * */ public static void removePropertiesListListener(PropertiesListListener listener) { synchronized (propertieslistListeners) { propertieslistListeners.remove(listener); } } }
9,382
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
WordCountAnalysis.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/WordCountAnalysis.java
/* * WordCountAnalysis.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment; import jloda.util.CanceledException; import jloda.util.Pair; import jloda.util.Single; import jloda.util.progress.ProgressListener; import megan.alignment.gui.Alignment; import megan.alignment.gui.Lane; import java.util.*; /** * computes the word-count analysis on an alignment * Daniel Huson, 5.2012 */ public class WordCountAnalysis { /** * runs the word count analysis * */ public static void apply(Alignment alignment, int wordSize, int step, int minDepth, ProgressListener progressListener, Collection<Pair<Number, Number>> depthVsDifferences, SortedMap<Number, Number> rank2percentage) throws CanceledException { if (!alignment.getSequenceType().equalsIgnoreCase(Alignment.DNA) && !alignment.getSequenceType().equalsIgnoreCase(Alignment.cDNA)) return; if (wordSize < 1 || step < 1) return; int firstCol = Integer.MAX_VALUE; int lastCol = 0; for (int row = 0; row < alignment.getNumberOfSequences(); row++) { Lane lane = alignment.getLane(row); firstCol = Math.min(firstCol, lane.getFirstNonGapPosition()); lastCol = Math.max(firstCol, lane.getLastNonGapPosition()); } if (progressListener != null) { progressListener.setTasks("Computing diversity plot", ""); progressListener.setMaximum(lastCol / step); progressListener.setProgress(0); } Set<String> words = new HashSet<>(); Map<String, Integer> word2count = new HashMap<>(); Map<Integer, Pair<Integer, Integer>> rank2countAndTotal = new HashMap<>(); for (int col = firstCol; col <= lastCol; col += step) { words.clear(); int n = 0; for (int row = 0; row < alignment.getNumberOfSequences(); row++) { Lane lane = alignment.getLane(row); if (col >= lane.getFirstNonGapPosition() && col + wordSize <= lane.getLastNonGapPosition()) { int start = col - lane.getFirstNonGapPosition(); String word = lane.getBlock().substring(start, start + wordSize).toUpperCase(); words.add(word); n++; Integer previousCount = word2count.get(word); word2count.put(word, previousCount == null ? 1 : previousCount + 1); } } if (n >= minDepth) { depthVsDifferences.add(new Pair<>(n, words.size())); SortedSet<Pair<Integer, String>> ranker = new TreeSet<>((pair1, pair2) -> { if (pair1.getFirst() > pair2.getFirst()) return -1; else if (pair1.getFirst() < pair2.getFirst()) return 1; else return pair1.getSecond().compareTo(pair2.getSecond()); }); for (Map.Entry<String, Integer> entry : word2count.entrySet()) { ranker.add(new Pair<>(entry.getValue(), entry.getKey())); } int rank = 1; for (Pair<Integer, String> pair : ranker) { rank2countAndTotal.put(rank, new Pair<>(pair.getFirst(), n)); } } if (progressListener != null) progressListener.incrementProgress(); } // compute average coverage for each rank: for (Map.Entry<Integer, Pair<Integer, Integer>> entry : rank2countAndTotal.entrySet()) { Pair<Integer, Integer> pair = entry.getValue(); rank2percentage.put(entry.getKey(), (float) ((100.0 * pair.getFirst()) / pair.getSecond())); } } /** * compute the Menten kinetics for a list of values, see http://en.wikipedia.org/wiki/Michaelis-Menten_kinetics * * @return points to be plotted */ public static LinkedList<Pair<Number, Number>> computeMentenKinetics(Collection<Pair<Number, Number>> depthVsDifferences, Single<Integer> extrapolatedCount) { if (depthVsDifferences.size() == 0) return new LinkedList<>(); Pair<Number, Number>[] array = (Pair<Number, Number>[]) depthVsDifferences.toArray(new Pair[0]); int minX = Integer.MAX_VALUE; int maxX = Integer.MIN_VALUE; int vMax = 0; for (Pair<Number, Number> pair : array) { minX = Math.min(minX, pair.getFirst().intValue()); maxX = Math.max(maxX, pair.getFirst().intValue()); vMax = Math.max(vMax, pair.getSecond().intValue()); } // sort by increasing first value Arrays.sort(array); // smooth the values: vMax = 0; double[] smoothedValues = new double[array.length]; double sum = 0; int count = 0; for (int i = 0; i < array.length; i++) { Pair<Number, Number> pair = array[i]; sum += pair.getSecond().intValue(); if (count < 10) count++; else sum -= array[i - 10].getSecond().intValue(); if (i > 5) smoothedValues[i - 5] = sum / count; } for (int i = 0; i < Math.min(5, smoothedValues.length); i++) { smoothedValues[i] = smoothedValues[Math.min(5, smoothedValues.length) - 1]; } for (int i = 0; i < array.length; i++) { smoothedValues[i] = smoothedValues[Math.max(0, array.length - 6)]; } for (int i = 0; i < array.length; i++) { Pair<Number, Number> pair = array[i]; array[i] = new Pair<>(pair.getFirst(), smoothedValues[i]); // pair.setSecond(smoothedValues[i]); // uncomment this line to plot the smoothed values vMax = Math.max(vMax, (int) smoothedValues[i]); } int first = 0; while (first < array.length - 1 && array[first + 1].getSecond().intValue() < vMax / 2) first++; int kM = array[first].getFirst().intValue(); float stepX = Math.max(0.1f, (maxX - minX) / 100.0f); System.err.println("vMax: " + vMax + " kM: " + kM); if (extrapolatedCount != null) { int x = Math.max(100000, 1000 * maxX); extrapolatedCount.set(Math.max(1, (int) Math.round((vMax * x) / (double) (kM + x)))); System.err.println("Extrapolated count: " + extrapolatedCount.get()); } LinkedList<Pair<Number, Number>> result = new LinkedList<>(); for (float x = minX; x <= maxX; x += stepX) { float y = (vMax * x) / (kM + x); result.add(new Pair<>(x, y)); } return result; } /** * compute the average k and N values * * @return average N and K values */ public static Pair<Float, Float> computeAverageNandK(LinkedList<Pair<Number, Number>> values) { if (values.size() == 0) return new Pair<>(0f, 0f); double n = 0; double k = 0; for (Pair<Number, Number> pair : values) { n += pair.getFirst().doubleValue(); k += pair.getSecond().doubleValue(); } return new Pair<>((float) (n / values.size()), (float) (k / values.size())); } }
8,155
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
AlignmentViewer.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/AlignmentViewer.java
/* * AlignmentViewer.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment; import jloda.swing.commands.CommandManager; import jloda.swing.director.IDirectableViewer; import jloda.swing.director.IDirector; import jloda.swing.director.IViewerWithFindToolBar; import jloda.swing.director.ProjectManager; import jloda.swing.find.FindToolBar; import jloda.swing.find.JListSearcher; import jloda.swing.find.SearchManager; import jloda.swing.util.StatusBar; import jloda.swing.util.ToolBar; import jloda.swing.window.MenuBar; import jloda.swing.window.NotificationsInSwing; import jloda.util.*; import jloda.util.progress.ProgressCmdLine; import jloda.util.progress.ProgressListener; import jloda.util.progress.ProgressPercentage; import megan.alignment.commands.*; import megan.alignment.gui.*; import megan.alignment.gui.colors.ColorSchemeAminoAcids; import megan.alignment.gui.colors.ColorSchemeNucleotides; import megan.alignment.gui.colors.ColorSchemeText; import megan.assembly.alignment.AlignmentAssembler; import megan.core.Director; import megan.main.MeganProperties; import megan.viewer.MainViewer; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; /** * alignment window * Daniel Huson, 9.2011 */ public class AlignmentViewer extends JFrame implements IDirectableViewer, IViewerWithFindToolBar, Printable { private boolean uptoDate = true; private boolean locked = false; private final Director dir; private final CommandManager commandManager; private final MenuBar menuBar; private final StatusBar statusBar; private final JTextField classNameTextField = new JTextField(); private final JTextField referenceNameTextField = new JTextField(); private final AlignmentViewerPanel alignmentViewerPanel = new AlignmentViewerPanel(); private final JPanel referencePanel; private final JList referenceJList = new JList(new DefaultListModel()); private String selectedReference = null; private boolean showFindToolBar = false; private final SearchManager searchManager; private String infoString = ""; private final Blast2Alignment blast2Alignment; private boolean showAminoAcids = false; public enum AlignmentLayout { Mapping, ByStart, ByName, ByContigs, Unsorted; public static AlignmentLayout valueOfIgnoreCase(String str) { for (AlignmentLayout a : values()) { if (a.toString().equalsIgnoreCase(str)) return a; } return Mapping; } } private AlignmentLayout alignmentLayout = AlignmentLayout.valueOfIgnoreCase(ProgramProperties.get("AlignmentLayout", AlignmentLayout.Mapping.toString())); private boolean showInsertions = true; private String aminoAcidColoringScheme = ProgramProperties.get("AminoAcidColorScheme", ColorSchemeAminoAcids.NAMES.Default.toString()); private String nucleotideColoringScheme = ProgramProperties.get("NucleotideColorScheme", ColorSchemeNucleotides.NAMES.Default.toString()); /** * constructor * */ public AlignmentViewer(final Director dir) { this.dir = dir; blast2Alignment = new Blast2Alignment(dir.getDocument()); statusBar = new StatusBar(); searchManager = new SearchManager(dir, this, new JListSearcher(referenceJList), false, true); commandManager = new CommandManager(dir, this, new String[]{"megan.alignment.commands", "megan.commands"}, !ProgramProperties.isUseGUI()); setAminoAcidColoringScheme(ProgramProperties.get("AminoAcidColorScheme", "Default")); setNucleotideColoringScheme(ProgramProperties.get("NucleotideColorScheme", "Default")); setTitle(); menuBar = new MenuBar(this, GUIConfiguration.getMenuConfiguration(), commandManager); setJMenuBar(menuBar); MeganProperties.addPropertiesListListener(menuBar.getRecentFilesListener()); MeganProperties.notifyListChange(ProgramProperties.RECENTFILES); ProjectManager.addAnotherWindowWithWindowMenu(dir, menuBar.getWindowMenu()); final JFrame frame = getFrame(); frame.setLocationRelativeTo(MainViewer.getLastActiveFrame()); final int[] geometry = ProgramProperties.get("AlignerViewerGeometry", new int[]{100, 100, 850, 600}); frame.setSize(geometry[2], geometry[3]); JToolBar toolBar = new ToolBar(this, GUIConfiguration.getToolBarConfiguration(), commandManager); getContentPane().setLayout(new BorderLayout()); getContentPane().add(toolBar, BorderLayout.NORTH); JPanel main = new JPanel(); frame.getContentPane().add(main, BorderLayout.CENTER); main.setLayout(new BorderLayout()); referencePanel = new JPanel(); referencePanel.setBorder(BorderFactory.createEmptyBorder(1, 10, 5, 10)); referencePanel.setLayout(new BorderLayout()); JPanel aPanel = new JPanel(); // need this because north border of reference used by find toolbar aPanel.setLayout(new BorderLayout()); classNameTextField.setEditable(false); classNameTextField.setBackground(aPanel.getBackground()); classNameTextField.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); aPanel.add(classNameTextField, BorderLayout.NORTH); aPanel.add(new JScrollPane(referenceJList), BorderLayout.CENTER); referencePanel.add(aPanel, BorderLayout.CENTER); JPanel bPanel = new JPanel(); bPanel.setLayout(new BorderLayout()); referenceNameTextField.setEditable(false); referenceNameTextField.setBackground(bPanel.getBackground()); referenceNameTextField.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); bPanel.add(referenceNameTextField, BorderLayout.NORTH); bPanel.add(alignmentViewerPanel, BorderLayout.CENTER); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); splitPane.setOneTouchExpandable(true); splitPane.setDividerLocation(90); splitPane.add(referencePanel); splitPane.add(bPanel); main.add(splitPane, BorderLayout.CENTER); JPanel botPanel = new JPanel(); botPanel.setLayout(new BoxLayout(botPanel, BoxLayout.Y_AXIS)); botPanel.add(statusBar); main.add(botPanel, BorderLayout.SOUTH); getContentPane().validate(); JPopupMenu namesPopup = new JPopupMenu(); namesPopup.add(commandManager.getJMenuItem(FindReadCommand.NAME)); namesPopup.add(commandManager.getJMenuItem(CopyReadNamesCommand.NAME)); namesPopup.addSeparator(); namesPopup.add(commandManager.getJMenuItem(ShowInspectReadsCommand.NAME)); namesPopup.addSeparator(); namesPopup.add(commandManager.getJMenuItem(LayoutByNameCommand.NAME)); namesPopup.add(commandManager.getJMenuItem(LayoutByStartCommand.NAME)); namesPopup.add(commandManager.getJMenuItem(LayoutByContigsCommand.NAME)); namesPopup.addSeparator(); namesPopup.add(commandManager.getJMenuItem(MoveUpCommand.NAME)); namesPopup.add(commandManager.getJMenuItem(MoveDownCommand.NAME)); alignmentViewerPanel.getNamesPanel().setComponentPopupMenu(namesPopup); alignmentViewerPanel.setShowAsMapping(true); JPopupMenu alignmentPopup = new JPopupMenu(); alignmentPopup.add(commandManager.getJMenuItem(ShowMatchCommand.NAME)); alignmentPopup.add(commandManager.getJMenuItem(CopyReadNamesCommand.NAME)); alignmentPopup.addSeparator(); alignmentPopup.add(commandManager.getJMenuItem(ShowInspectReadsCommand.NAME)); alignmentPopup.addSeparator(); alignmentPopup.add(commandManager.getJMenuItem(ZoomToSelectionCommand.NAME)); alignmentPopup.add(commandManager.getJMenuItem(ZoomToFitCommand.NAME)); alignmentPopup.addSeparator(); alignmentPopup.add(commandManager.getJMenuItem("Select All")); alignmentPopup.add(commandManager.getJMenuItem("Select None")); alignmentViewerPanel.getAlignmentPanel().setComponentPopupMenu(alignmentPopup); ((DefaultListModel) referenceJList.getModel()).addElement("Loading..."); referenceJList.setEnabled(false); referenceJList.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { if (me.getClickCount() == 2) { ReferenceItem item = (ReferenceItem) referenceJList.getSelectedValue(); if (item != null && item.name.length() > 0 && !isLocked()) { setSelectedReference(item.name); dir.execute("apply;", commandManager); } else setSelectedReference(null); } } public void mousePressed(MouseEvent me) { super.mousePressed(me); if (me.isPopupTrigger()) { referenceJList.setSelectedIndex(referenceJList.locationToIndex(me.getPoint())); JPopupMenu popupMenu = new JPopupMenu(); popupMenu.add(commandManager.getJMenuItem(ApplyCommand.NAME)); popupMenu.show(referenceJList, me.getX(), me.getY()); } } public void mouseReleased(MouseEvent me) { super.mouseReleased(me); if (me.isPopupTrigger()) mousePressed(me); } }); referenceJList.addListSelectionListener(evt -> { if (!evt.getValueIsAdjusting()) { ReferenceItem item = (ReferenceItem) referenceJList.getSelectedValue(); if (item != null) setSelectedReference(item.name); else setSelectedReference(null); } }); addWindowListener(new WindowAdapter() { @Override public void windowActivated(WindowEvent windowEvent) { super.windowActivated(windowEvent); getAlignmentViewerPanel().getAlignmentPanel().setAnimateSelection(true); } @Override public void windowDeactivated(WindowEvent windowEvent) { super.windowDeactivated(windowEvent); getAlignmentViewerPanel().getAlignmentPanel().setAnimateSelection(false); if (!isShowAsMapping()) { Set<String> selectedLabels = new HashSet<>(); for (int row = getSelectedBlock().getFirstRow(); row <= getSelectedBlock().getLastRow(); row++) { selectedLabels.add(StringUtils.getFirstWord(getAlignment().getLane(row).getName())); } if (selectedLabels.size() != 0) { ProjectManager.getPreviouslySelectedNodeLabels().clear(); ProjectManager.getPreviouslySelectedNodeLabels().addAll(selectedLabels); } } } }); frame.addComponentListener(new ComponentAdapter() { public void componentMoved(ComponentEvent e) { componentResized(e); } public void componentResized(ComponentEvent event) { if ((event.getID() == ComponentEvent.COMPONENT_RESIZED || event.getID() == ComponentEvent.COMPONENT_MOVED) && (frame.getExtendedState() & JFrame.MAXIMIZED_HORIZ) == 0 && (frame.getExtendedState() & JFrame.MAXIMIZED_VERT) == 0) { ProgramProperties.put("AlignerViewerGeometry", new int[] {frame.getLocation().x, frame.getLocation().y, frame.getSize().width, frame.getSize().height}); } } }); getSelectedBlock().addSelectionListener((selected, minRow, minCol, maxRow, maxCol) -> { commandManager.updateEnableState(); if (getSelectedBlock().isSelected()) statusBar.setText2("Selection: " + getSelectedBlock().getNumberOfSelectedRows() + " x " + getSelectedBlock().getNumberOfSelectedCols()); else statusBar.setText2(infoString); }); if (alignmentViewerPanel.isShowReference()) alignmentViewerPanel.setShowReference(true); // rescan size of reference panel if (alignmentViewerPanel.isShowAsMapping()) alignmentViewerPanel.setNamesPanelVisible(false); updateView(IDirector.ALL); } public boolean isUptoDate() { return uptoDate; } public JFrame getFrame() { return this; } public void updateView(String what) { setTitle(); int h = getAlignmentViewerPanel().getAlignmentScrollPane().getHorizontalScrollBar().getValue(); int v = getAlignmentViewerPanel().getAlignmentScrollPane().getVerticalScrollBar().getValue(); if (referenceJList.getModel().getSize() == 1 && referenceJList.getModel().getElementAt(0).toString().contains("Loading...")) { SortedSet<ReferenceItem> sorted = new TreeSet<>((a, b) -> { if (a.count > b.count) return -1; else if (a.count < b.count) return 1; else return a.getText().compareTo(b.getText()); }); for (String reference : blast2Alignment.getReferences()) { sorted.add(new ReferenceItem(blast2Alignment.getReference2Count(reference), reference)); } if (sorted.size() > 0) { ((DefaultListModel<?>) referenceJList.getModel()).removeElementAt(0); for (ReferenceItem item : sorted) { ((DefaultListModel) referenceJList.getModel()).addElement(item); } referenceJList.setEnabled(true); }/* else { ((DefaultListModel) referenceJList.getModel()).removeElementAt(0); ((DefaultListModel) referenceJList.getModel()).addElement("No alignments available"); } */ } if (referenceJList.getModel().getSize() > 1) classNameTextField.setText("List of " + referenceJList.getModel().getSize() + " available reference sequences for '" + blast2Alignment.getClassName() + "' (double click on one to see alignment):"); if (selectedReference == null) referenceNameTextField.setText("Alignment panel:"); else referenceNameTextField.setText("Alignment for reference sequence '" + selectedReference + "':"); alignmentViewerPanel.setShowReference(alignmentViewerPanel.isShowReference()); // rescan size of reference panel alignmentViewerPanel.setShowConsensus(alignmentViewerPanel.isShowConsensus()); // rescan size of consensus panel alignmentViewerPanel.revalidateGrid(); commandManager.updateEnableState(); getAlignmentViewerPanel().getAlignmentScrollPane().getHorizontalScrollBar().setValue(h); getAlignmentViewerPanel().getAlignmentScrollPane().getVerticalScrollBar().setValue(v); statusBar.setText1("Alignment: " + getAlignment().getNumberOfSequences() + " x " + getAlignment().getLength()); statusBar.setText2(infoString); FindToolBar findToolBar = searchManager.getFindDialogAsToolBar(); if (findToolBar.isClosing()) { showFindToolBar = false; findToolBar.setClosing(false); } if (!findToolBar.isEnabled() && showFindToolBar) { referencePanel.add(findToolBar, BorderLayout.NORTH); referencePanel.setPreferredSize(new Dimension(200, 1000000)); findToolBar.setEnabled(true); getContentPane().validate(); getCommandManager().updateEnableState(); } else if (findToolBar.isEnabled() && !showFindToolBar) { referencePanel.remove(findToolBar); findToolBar.setEnabled(false); getContentPane().validate(); getCommandManager().updateEnableState(); } if (findToolBar.isEnabled()) findToolBar.clearMessage(); } public boolean isShowInsertions() { return showInsertions; } public void setShowInsertions(boolean showInsertions) { this.showInsertions = showInsertions; } static class ReferenceItem extends JButton { final int count; final String name; ReferenceItem(Integer count, String name) { this.count = count; this.name = name; setBold(true); } void setBold(boolean bold) { if (bold) setText("<html><strong>" + name + ":: " + count + "</strong></html>"); // store negative count to get correct sorting else setText(name + ":: " + count); // store negative count to get correct sorting } public String toString() { return getText(); } } /** * gets the selected block * * @return selected block */ public SelectedBlock getSelectedBlock() { return alignmentViewerPanel.getSelectedBlock(); } public void lockUserInput() { statusBar.setText1(""); statusBar.setText2("Busy..."); locked = true; commandManager.setEnableCritical(false); searchManager.getFindDialogAsToolBar().setEnableCritical(false); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); referenceJList.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } public void unlockUserInput() { commandManager.setEnableCritical(true); searchManager.getFindDialogAsToolBar().setEnableCritical(true); locked = false; setCursor(Cursor.getDefaultCursor()); referenceJList.setCursor(Cursor.getDefaultCursor()); } /** * is viewer currently locked? * * @return true, if locked */ public boolean isLocked() { return locked; } public void destroyView() { MeganProperties.removePropertiesListListener(menuBar.getRecentFilesListener()); ProgramProperties.put("AlignerViewerGeometry", new int[] {getLocation().x, getLocation().y, getSize().width, getSize().height}); searchManager.getFindDialogAsToolBar().close(); alignmentViewerPanel.getAlignmentPanel().close(); setVisible(false); dir.removeViewer(this); dispose(); } public void setUptoDate(boolean flag) { uptoDate = flag; } /** * set the title of the window */ private void setTitle() { String className = getAlignment().getName(); if (className == null) className = "Untitled"; else if (className.length() > 80) className = className.substring(0, 80) + "."; String newTitle = "Alignment for '" + className + "' - " + dir.getDocument().getTitle() + " - " + ProgramProperties.getProgramName(); if (!getFrame().getTitle().equals(newTitle)) { getFrame().setTitle(newTitle); ProjectManager.updateWindowMenus(); } } public CommandManager getCommandManager() { return commandManager; } /** * set the alignment for this viewer * */ public void setAlignment(Alignment alignment, boolean updateInfoString) { lockUserInput(); for (int i = 0; i < referenceJList.getModel().getSize(); i++) { ReferenceItem item = (ReferenceItem) referenceJList.getModel().getElementAt(i); if (item.name.equals(getSelectedReference())) { item.setBold(false); break; } } if (alignment.getNumberOfSequences() > 0 && alignment.getLength() > 0 && alignment.getReference().getLength() == 0) alignmentViewerPanel.setShowReference(false); alignment.getGapColumnContractor().processAlignment(alignment); setAlignmentLayout(getAlignmentLayout(), new ProgressPercentage()); if (isShowAsMapping()) { alignment.getRowCompressor().update(); } else { alignment.getRowCompressor().clear(); if (getAlignmentLayout() != AlignmentLayout.ByContigs) // todo: not sure this is ok, but want to avoid doing assembly twice setAlignmentLayout(getAlignmentLayout(), new ProgressPercentage()); } if (!alignment.getReferenceType().equals(alignment.getSequenceType())) { alignmentViewerPanel.getAlignmentPanel().setColorMatchesVsReference(true); alignmentViewerPanel.getAlignmentPanel().setColorMismatchesVsReference(true); } alignmentViewerPanel.zoom("both", "fit", null); final SelectedBlock selectedBlock = getSelectedBlock(); final AlignmentPanel alignmentPanel = alignmentViewerPanel.getAlignmentPanel(); final NamesPanel namesPanel = alignmentViewerPanel.getNamesPanel(); final ReferencePanel referencePanel = alignmentViewerPanel.getReferencePanel(); final ConsensusPanel consensusPanel = alignmentViewerPanel.getConsensusPanel(); final AxisPanel axisPanel = alignmentViewerPanel.getAxisPanel(); selectedBlock.setTotalRows(alignment.getNumberOfSequences()); selectedBlock.setTotalCols(alignment.getLength()); namesPanel.setAlignment(alignment); axisPanel.setAlignment(alignment); alignmentPanel.setAlignment(alignment); referencePanel.setAlignment(alignment); consensusPanel.setAlignment(alignment); switch (alignment.getSequenceType()) { case Alignment.PROTEIN -> { alignmentPanel.setColorScheme(new ColorSchemeAminoAcids(aminoAcidColoringScheme)); referencePanel.setColorScheme(new ColorSchemeAminoAcids(aminoAcidColoringScheme)); consensusPanel.setColorScheme(new ColorSchemeAminoAcids(aminoAcidColoringScheme)); } case Alignment.DNA -> { alignmentPanel.setColorScheme(new ColorSchemeNucleotides(nucleotideColoringScheme)); referencePanel.setColorScheme(new ColorSchemeNucleotides(nucleotideColoringScheme)); consensusPanel.setColorScheme(new ColorSchemeNucleotides(nucleotideColoringScheme)); } case Alignment.cDNA -> { if (alignment.isTranslate()) { alignmentPanel.setColorScheme(new ColorSchemeAminoAcids(aminoAcidColoringScheme)); consensusPanel.setColorScheme(new ColorSchemeAminoAcids(aminoAcidColoringScheme)); } else { alignmentPanel.setColorScheme(new ColorSchemeNucleotides(nucleotideColoringScheme)); consensusPanel.setColorScheme(new ColorSchemeNucleotides(nucleotideColoringScheme)); } referencePanel.setColorScheme(new ColorSchemeAminoAcids(aminoAcidColoringScheme)); } default -> { alignmentPanel.setColorScheme(new ColorSchemeText()); consensusPanel.setColorScheme(new ColorSchemeText()); referencePanel.setColorScheme(new ColorSchemeText()); } } if (alignment.getNumberOfSequences() < 5000 && alignment.getLength() < 10000) if (alignment.getSequenceType().equals(Alignment.DNA) || alignment.getSequenceType().equals(Alignment.cDNA)) { try { Pair<Double, Double> gcAndCoverage = ComputeAlignmentProperties.computeCGContentAndCoverage(alignment, new ProgressCmdLine()); infoString = String.format("GC-content=%.1f %% Coverage=%.1f", gcAndCoverage.getFirst(), gcAndCoverage.getSecond()); } catch (CanceledException e) { Basic.caught(e); } } alignmentViewerPanel.zoom("both", "fit", null); // System.err.println("Consensus:\n"+alignment.getConsensus()); } /** * Print the frame associated with this viewer. * * @param gc0 the graphics context. * @param format page format * @param pagenumber page index */ public int print(Graphics gc0, PageFormat format, int pagenumber) { if (pagenumber == 0) { Graphics2D gc = ((Graphics2D) gc0); gc.setFont(getFont()); Dimension dim = getContentPane().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); getContentPane().paint(gc); return Printable.PAGE_EXISTS; } else return Printable.NO_SUCH_PAGE; } public boolean isShowAminoAcids() { return showAminoAcids; } /** * show amino acids in alignment * */ public void setShowAminoAcids(boolean showAminoAcids) { this.showAminoAcids = showAminoAcids; if (getAlignment().getSequenceType().equals(Alignment.cDNA)) getAlignment().setTranslate(showAminoAcids); final AlignmentPanel alignmentPanel = alignmentViewerPanel.getAlignmentPanel(); final ConsensusPanel consensusPanel = alignmentViewerPanel.getConsensusPanel(); final ReferencePanel referencePanel = alignmentViewerPanel.getReferencePanel(); if (showAminoAcids && (getAlignment().getSequenceType().equals(Alignment.PROTEIN) || getAlignment().getSequenceType().equals(Alignment.cDNA))) { alignmentPanel.setColorScheme(new ColorSchemeAminoAcids(aminoAcidColoringScheme)); consensusPanel.setColorScheme(new ColorSchemeAminoAcids(aminoAcidColoringScheme)); referencePanel.setColorScheme(new ColorSchemeAminoAcids(aminoAcidColoringScheme)); } else if (getAlignment().getSequenceType().equals(Alignment.DNA)) { alignmentPanel.setColorScheme(new ColorSchemeNucleotides(nucleotideColoringScheme)); consensusPanel.setColorScheme(new ColorSchemeNucleotides(nucleotideColoringScheme)); referencePanel.setColorScheme(new ColorSchemeAminoAcids(nucleotideColoringScheme)); } else if (getAlignment().getSequenceType().equals(Alignment.cDNA)) { alignmentPanel.setColorScheme(new ColorSchemeNucleotides(nucleotideColoringScheme)); consensusPanel.setColorScheme(new ColorSchemeNucleotides(nucleotideColoringScheme)); referencePanel.setColorScheme(new ColorSchemeAminoAcids(aminoAcidColoringScheme)); } else { alignmentPanel.setColorScheme(new ColorSchemeText()); consensusPanel.setColorScheme(new ColorSchemeText()); referencePanel.setColorScheme(new ColorSchemeText()); } if (alignmentPanel.getAlignment().isTranslate() && getSelectedBlock().getNumberOfSelectedCols() > 0) getSelectedBlock().selectCols(getSelectedBlock().getFirstCol(), getSelectedBlock().getLastCol(), true); } public boolean isContractGaps() { return getAlignment().getGapColumnContractor().isEnabled(); } public void setContractGaps(boolean contract) { getAlignment().getGapColumnContractor().setEnabled(contract); if (contract) alignmentViewerPanel.zoom("horizontal", "fit", null); } /** * get the alignment * * @return alignment */ public Alignment getAlignment() { return alignmentViewerPanel.getAlignment(); } public boolean isAllowNucleotides() { return getAlignment() != null && (getAlignment().getSequenceType().equals(Alignment.DNA) || getAlignment().getSequenceType().equals(Alignment.cDNA)); } public boolean isAllowAminoAcids() { return getAlignment() != null && (getAlignment().getSequenceType().equals(Alignment.PROTEIN) || getAlignment().getSequenceType().equals(Alignment.cDNA)); } public AlignmentLayout getAlignmentLayout() { return alignmentLayout; } public void setAlignmentLayout(AlignmentLayout alignmentLayout, final ProgressListener progressListener) { this.alignmentLayout = alignmentLayout; ProgramProperties.put("AlignmentViewLayout", alignmentLayout.toString()); switch (alignmentLayout) { case Unsorted: getAlignmentViewerPanel().setNamesPanelVisible(true); getAlignment().getRowCompressor().clear(); alignmentViewerPanel.setShowAsMapping(false); AlignmentSorter.sortByOriginalOrder(getAlignment()); break; case ByStart: getAlignmentViewerPanel().setNamesPanelVisible(true); getAlignment().getRowCompressor().clear(); alignmentViewerPanel.setShowAsMapping(false); AlignmentSorter.sortByStart(getAlignment(), false); break; case ByName: getAlignmentViewerPanel().setNamesPanelVisible(true); getAlignment().getRowCompressor().clear(); alignmentViewerPanel.setShowAsMapping(false); AlignmentSorter.sortByName(getAlignment(), false); break; case ByContigs: try { getAlignmentViewerPanel().setNamesPanelVisible(true); getAlignment().getRowCompressor().clear(); alignmentViewerPanel.setShowAsMapping(false); progressListener.setTasks("Sorting reads by contigs", "Assembling"); final AlignmentAssembler alignmentAssembler = new AlignmentAssembler(); final int minOverlap = ProgramProperties.get("AssemblyMinOverlap", 20); System.err.println("Assuming minOverlap=" + minOverlap + " (use setProp AssemblyMinOverlap=<number> to change)"); alignmentAssembler.computeOverlapGraph(minOverlap, getAlignment(), progressListener); final int count = alignmentAssembler.computeContigs(0, 0, 0, 0, true, progressListener); repaint(); NotificationsInSwing.showInformation(getFrame(), "Number of contigs assembled: " + count); } catch (IOException e) { Basic.caught(e); } break; default: case Mapping: getAlignmentViewerPanel().setNamesPanelVisible(false); AlignmentSorter.sortByOriginalOrder(getAlignment()); alignmentViewerPanel.setShowAsMapping(true); getAlignment().getRowCompressor().update(); break; } repaint(); } public Blast2Alignment getBlast2Alignment() { return blast2Alignment; } public AlignmentViewerPanel getAlignmentViewerPanel() { return alignmentViewerPanel; } public boolean isShowAsMapping() { return alignmentViewerPanel.isShowAsMapping(); } public void setShowAsMapping(boolean showAsMapping) { alignmentViewerPanel.setShowAsMapping(showAsMapping); } public String getAminoAcidColoringScheme() { return aminoAcidColoringScheme; } public void setAminoAcidColoringScheme(String aminoAcidColoringScheme) { this.aminoAcidColoringScheme = aminoAcidColoringScheme; } public String getNucleotideColoringScheme() { return nucleotideColoringScheme; } public void setNucleotideColoringScheme(String nucleotideColoringScheme) { this.nucleotideColoringScheme = nucleotideColoringScheme; } public String getSelectedReference() { return selectedReference; } private void setSelectedReference(String selectedReference) { this.selectedReference = selectedReference; } public SearchManager getSearchManager() { return searchManager; } public boolean isShowFindToolBar() { return showFindToolBar; } public void setShowFindToolBar(boolean showFindToolBar) { this.showFindToolBar = showFindToolBar; } /** * get name for this type of viewer * * @return name */ public String getClassName() { return "AlignmentViewer"; } }
34,046
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ComputeAlignmentProperties.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/ComputeAlignmentProperties.java
/* * ComputeAlignmentProperties.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment; import jloda.util.CanceledException; import jloda.util.Pair; import jloda.util.progress.ProgressListener; import megan.alignment.gui.Alignment; import megan.alignment.gui.Lane; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; /** * compute different properties of an alignment * Daniel Huson, 9.2011 */ public class ComputeAlignmentProperties { /** * computes the k-mer based diversity index * * @return k/n */ public static Pair<Double, Double> computeSequenceDiversityRatio(Alignment alignment, int kmer, int step, int minDepth, ProgressListener progressListener) throws CanceledException { progressListener.setTasks("Computing diversity ratio k/n", ""); progressListener.setMaximum(alignment.getNumberOfSequences()); progressListener.setProgress(0); int firstCol = Integer.MAX_VALUE; int lastCol = 0; for (int row = 0; row < alignment.getNumberOfSequences(); row++) { Lane lane = alignment.getLane(row); firstCol = Math.min(firstCol, lane.getFirstNonGapPosition()); lastCol = Math.max(firstCol, lane.getLastNonGapPosition()); } Set<String> words = new HashSet<>(); List<Pair<Integer, Integer>> listKN = new LinkedList<>(); for (int col = firstCol; col <= lastCol; col += step) { words.clear(); int n = 0; for (int row = 0; row < alignment.getNumberOfSequences(); row++) { Lane lane = alignment.getLane(row); if (col >= lane.getFirstNonGapPosition() && col + kmer <= lane.getLastNonGapPosition()) { int start = col - lane.getFirstNonGapPosition(); String word = lane.getBlock().substring(start, start + kmer); if (!(word.contains("-") || word.contains("N"))) { words.add(word); n++; } } if (n >= minDepth) { listKN.add(new Pair<>(words.size(), n)); } progressListener.incrementProgress(); } } if (listKN.size() == 0) return new Pair<>(0.0, 0.0); double averageK = 0; double averageN = 0; //System.err.println("k, n:"); for (Pair<Integer, Integer> kn : listKN) { averageK += kn.getFirst(); averageN += kn.getSecond(); // System.err.println(kn.getFirst()+", "+kn.getSecond()); } averageK /= listKN.size(); averageN /= listKN.size(); // System.err.println("Average k,n="+averageK+" "+averageN); return new Pair<>(averageK, averageN); } /** * computes the CG content and coverage * * @return CG content (in percent) and coverage */ public static Pair<Double, Double> computeCGContentAndCoverage(Alignment alignment, ProgressListener progressListener) throws CanceledException { if (progressListener != null) { progressListener.setTasks("Computing CG content and coverage", ""); progressListener.setMaximum(alignment.getNumberOfSequences()); progressListener.setProgress(0); } int cgCount = 0; int atCount = 0; int otherLetterCount = 0; int firstCol = Integer.MAX_VALUE; int lastCol = 0; for (int row = 0; row < alignment.getNumberOfSequences(); row++) { Lane lane = alignment.getLane(row); firstCol = Math.min(firstCol, lane.getFirstNonGapPosition()); lastCol = Math.max(lastCol, lane.getLastNonGapPosition()); String block = lane.getBlock(); for (int i = 0; i < block.length(); i++) { int ch = Character.toUpperCase(block.charAt(i)); if (ch == 'C' || ch == 'G') { cgCount++; } else if (ch == 'A' || ch == 'T' || ch == 'U') { atCount++; } else if (Character.isLetter(ch)) otherLetterCount++; } if (progressListener != null) progressListener.incrementProgress(); } double totalCount = cgCount + atCount + otherLetterCount; double cgContent = 100 * (totalCount > 0 ? (double) cgCount / totalCount : 0); double totalLength = lastCol - firstCol + 1; double coverage = (firstCol <= lastCol ? totalCount / totalLength : 0); return new Pair<>(cgContent, coverage); } }
5,452
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/alignment/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.alignment; import jloda.swing.window.MenuConfiguration; import megan.chart.data.ChartCommandHelper; import megan.classification.data.ClassificationCommandHelper; /** * configuration for menu and toolbar * Daniel Huson, 7.2010 */ class GUIConfiguration { /** * get the menu configuration * * @return menu configuration */ public static MenuConfiguration getMenuConfiguration() { MenuConfiguration menuConfig = new MenuConfiguration(); menuConfig.defineMenuBar("File;Edit;Options;Layout;Window;Help;"); menuConfig.defineMenu("File", "New...;|;Open...;@Open Recent;|;Open From Server...;|;Compare...;|;Import From BLAST...;|;Export Image...;Export Legend...;@Export;|;Page Setup...;Print...;|;Close;|;Quit;"); menuConfig.defineMenu("Export", "Export Alignment...;Export Consensus...;Export Reference...;|;Overlap Graph...;Gene-Centric Assembly...;"); menuConfig.defineMenu("Open Recent", ";"); menuConfig.defineMenu("Edit", "Cut;Copy;Paste;|;Copy Alignment;Copy Consensus;Copy Reference;Copy Read Names;|;Select All;Select None;From Previous Alignment;|;Find...;Find Again;|;Find Read...;|;@Preferences;"); menuConfig.defineMenu("Preferences", "Set Minimum Number of Reads...;"); menuConfig.defineMenu("Options", "Move Up;Move Down;|;Translate...;|;Chart Diversity...;" + "Show Insertions;Contract Gaps;|;" + "Show Nucleotides;Show Amino Acids;|;Show Reference;Show Consensus;Show Unaligned;|;Set Amino Acid Colors...;|;" + "Matches Vs Reference;Mismatches Vs Reference;|;Matches Vs Consensus;Mismatches Vs Consensus;"); menuConfig.defineMenu("Layout", "As Mapping;By Start;By Name;By Contigs;Unsorted;|;@Expand/Contract;|;Zoom To Fit;|;Expand To Height;Reset Zoom;"); menuConfig.defineMenu("Expand/Contract", "Expand Horizontal Alignment;Contract Horizontal Alignment;Expand Vertical Alignment;Contract Vertical Alignment;"); menuConfig.defineMenu("Window", "Close All Other Windows...;|;Reset Window Location;Set Window Size...;|;Message Window...;|;" + "Inspector Window...;|;Main Viewer...;" + ClassificationCommandHelper.getOpenViewerMenuString() + "|;Samples Viewer...;|;" + ChartCommandHelper.getOpenChartMenuString() + "|;Chart Microbial Attributes...;|;"); 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 Horizontal Alignment;Contract Horizontal Alignment;Expand Vertical Alignment;Contract Vertical Alignment;|;" + "Zoom To Fit;|;Expand To Height;Reset Zoom;|;Main Viewer...;" + ClassificationCommandHelper.getOpenViewerMenuString() + "|;Samples Viewer...;|;Chart Diversity...;|;" + "Contract Gaps;Show Reference;Show Consensus;Show Unaligned;|;" + "Show Nucleotides;Show Amino Acids;|;By Start;As Mapping;"; } }
4,070
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Blast2Alignment.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/Blast2Alignment.java
/* * Blast2Alignment.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment; import jloda.seq.SequenceUtils; import jloda.util.*; import jloda.util.progress.ProgressListener; import megan.algorithms.ActiveMatches; import megan.alignment.gui.Alignment; import megan.alignment.gui.Lane; import megan.core.Document; import megan.data.IMatchBlock; import megan.data.IReadBlock; import megan.data.IReadBlockIterator; import megan.main.MeganProperties; import megan.util.BlastParsingUtils; import java.io.IOException; import java.io.StringWriter; import java.util.*; /** * create an alignment from BLAST matches * Daniel Huson, 8.2011 */ public class Blast2Alignment { private final Document doc; private String classificationName; private String className; private int totalNumberOfReads = 0; private final Map<String, List<byte[][]>> reference2ReadMatchPairs = new HashMap<>(); // list of triplets, readName, readSequence, match as text final public static String BLASTX = "BlastX"; final public static String BLASTP = "BlastP"; final public static String BLASTN = "BlastN"; final public static String UNKNOWN = "Unknown"; private String blastType = UNKNOWN; /** * create an aligner for * */ public Blast2Alignment(Document doc) { this.doc = doc; } public String getClassificationName() { return classificationName; } public String getClassName() { return className; } /** * loads data for aligning. This also determines the type of blast data * */ public void loadData(String classificationName, Set<Integer> classIds, String name, ProgressListener progressListener) throws IOException, CanceledException { this.classificationName = classificationName; this.className = name; totalNumberOfReads = 0; int totalReadsUsed = 0; reference2ReadMatchPairs.clear(); setBlastType(UNKNOWN); boolean blastFormatUnknown = true; boolean warnedUnknownBlastFormatEncountered = false; final Set<String> matchesSeenForGivenRead = new HashSet<>(); progressListener.setTasks("Alignment viewer", "Collecting data"); System.err.println("Collecting data..."); if (!doc.getMeganFile().hasDataConnector()) throw new IOException("Alignment requires archive"); final Map<String, Set<Long>> reference2seen = new HashMap<>(100000); int count = 0; boolean seenActiveMatch = false; try (IReadBlockIterator it = doc.getConnector().getReadsIteratorForListOfClassIds(classificationName, classIds, doc.getMinScore(), doc.getMaxExpected(), true, true)) { progressListener.setMaximum(it.getMaximumProgress()); progressListener.setProgress(0); while (it.hasNext()) // iterate over all reads { final BitSet activeMatches = new BitSet(); final IReadBlock readBlock = it.next(); totalNumberOfReads++; count++; boolean readUsed = false; ActiveMatches.compute(doc.getMinScore(), doc.getTopPercent(), doc.getMaxExpected(), doc.getMinPercentIdentity(), readBlock, classificationName, activeMatches); if (activeMatches.cardinality() > 0) { final String readHeader = StringUtils.swallowLeadingGreaterSign(readBlock.getReadHeader()).replaceAll("[\r\n]", "").trim(); final String readSequence; { final String sequence = readBlock.getReadSequence(); if (sequence == null) throw new IOException("Can't display alignments, reads sequences appear to be missing from RMA file"); readSequence = sequence.replaceAll("[\t\r\n ]", ""); } for (int i = 0; i < readBlock.getNumberOfAvailableMatchBlocks(); i++) { IMatchBlock matchBlock = readBlock.getMatchBlock(i); if (matchBlock.getText() == null) { System.err.println("Error: Match text: null"); continue; } if (doc.isUseIdentityFilter() && matchBlock.getPercentIdentity() > 0 && matchBlock.getPercentIdentity() < 97) continue; // keep only high-identity alignments if (activeMatches.get(i)) { final String matchText = BlastParsingUtils.removeReferenceHeaderFromBlastMatch(BlastParsingUtils.truncateBeforeSecondOccurrence(matchBlock.getText(), "Score =")); // todo: not sure what the following was supposed to do, but it broke the code: .replaceAll("[\t\r\n ]+", " "); String key = StringUtils.getFirstLine(matchBlock.getText()); // if this is an augmented DNA reference, remove everything from |pos| onward // System.err.println("key: "+key); // System.err.println("text: "+matchText); if (blastFormatUnknown) { setBlastType(BlastParsingUtils.guessBlastType(matchText)); if (getBlastType().equals(UNKNOWN)) { if (!warnedUnknownBlastFormatEncountered) { System.err.println("Error: Unknown BLAST format encountered"); warnedUnknownBlastFormatEncountered = true; } continue; } else blastFormatUnknown = false; } Set<Long> seen = reference2seen.computeIfAbsent(key, k -> new HashSet<>(10000)); final long uid = readBlock.getUId(); if (!seen.contains(uid)) // this ensures that any given reference only contains one copy of a read { if (uid != 0) seen.add(uid); if (!matchesSeenForGivenRead.contains(key)) { matchesSeenForGivenRead.add(key); List<byte[][]> pairs = reference2ReadMatchPairs.computeIfAbsent(key, k -> new LinkedList<>()); pairs.add(new byte[][]{readHeader.getBytes(), readSequence.getBytes(), matchText.getBytes()}); readUsed = true; } } } } if (readUsed) { totalReadsUsed++; } matchesSeenForGivenRead.clear(); if (!seenActiveMatch && activeMatches.cardinality() > 0) seenActiveMatch = true; } if ((count % 100) == 0) { progressListener.setSubtask("Collecting data (" + count + " reads processed)"); progressListener.setProgress(count); } } } catch (CanceledException ex) { System.err.println("USER CANCELED EXECUTE, dataset may be incomplete"); } finally { reference2seen.clear(); } if (!seenActiveMatch) throw new IOException("No active matches found"); final int minReads = ProgramProperties.get(MeganProperties.MININUM_READS_IN_ALIGNMENT, 10); if (minReads > 1) { boolean hasMinReads = false; for (List<byte[][]> list : reference2ReadMatchPairs.values()) { if (list.size() >= minReads) { hasMinReads = true; break; } } if (hasMinReads) { System.err.print("Removing all alignments with less than " + minReads + " reads: "); List<String> toDelete = new LinkedList<>(); for (String reference : reference2ReadMatchPairs.keySet()) { if (reference2ReadMatchPairs.get(reference).size() < minReads) toDelete.add(reference); } toDelete.forEach(reference2ReadMatchPairs.keySet()::remove); System.err.println(toDelete.size()); } } System.err.println("Reads total: " + totalNumberOfReads); System.err.println("Reads used: " + totalReadsUsed); System.err.println("References: " + reference2ReadMatchPairs.keySet().size()); if (getBlastType().equals(UNKNOWN)) throw new IOException("Couldn't determine BLAST flavor. Aligner requires BLASTX, BLASTP or BLASTN matches"); } /** * load some existing data. Used by alignment exporter * */ public void loadData(String classificationName, Integer classId, String name, String key, List<Pair<IReadBlock, IMatchBlock>> readMatchPairs) { this.classificationName = classificationName; this.className = name; reference2ReadMatchPairs.clear(); final List<byte[][]> newList = new ArrayList<>(readMatchPairs.size()); for (Pair<IReadBlock, IMatchBlock> pair : readMatchPairs) { final IReadBlock readBlock = pair.getFirst(); final IMatchBlock matchBlock = pair.getSecond(); final String readSequence = readBlock.getReadSequence().replaceAll("[\t\r\n ]", ""); final String readName = readBlock.getReadHeader(); final String matchText = BlastParsingUtils.removeReferenceHeaderFromBlastMatch(BlastParsingUtils.truncateBeforeSecondOccurrence(matchBlock.getText(), "Score =")); newList.add(new byte[][]{readName.getBytes(), readSequence.getBytes(), matchText.getBytes()}); } reference2ReadMatchPairs.put(key, newList); totalNumberOfReads = readMatchPairs.size(); } private String getBlastType() { return blastType; } private void setBlastType(String blastType) { this.blastType = blastType; } /** * gets the number of reads for a given reference string * * @return number of reads */ public int getReference2Count(String matchRefLine) { return reference2ReadMatchPairs.get(matchRefLine).size(); } /** * gets the collection of references * * @return references */ public Collection<String> getReferences() { return reference2ReadMatchPairs.keySet(); } /** * returns the total number of reads * */ public int getTotalNumberOfReads() { return totalNumberOfReads; } /** * builds an alignment for the given reference string * */ public void makeAlignment(String matchRefLine, Alignment alignment, boolean showInsertions, ProgressListener progressListener) throws IOException { alignment.clear(); alignment.setName(className); // set sequence type switch (getBlastType()) { case BLASTX -> { alignment.setReferenceType(Alignment.PROTEIN); alignment.setSequenceType(Alignment.cDNA); } case BLASTP -> { alignment.setReferenceType(Alignment.PROTEIN); alignment.setSequenceType(Alignment.PROTEIN); } case BLASTN -> { alignment.setReferenceType(Alignment.DNA); alignment.setSequenceType(Alignment.DNA); } } int totalReadsIn = 0; int totalReadsOut = 0; int totalErrors = 0; final List<byte[][]> readMatchPairs = reference2ReadMatchPairs.get(matchRefLine); progressListener.setMaximum(readMatchPairs.size()); progressListener.setProgress(0); final Single<char[]> referenceSequence = new Single<>(); final Single<char[]> originalReferenceSequence = new Single<>(); // used in case of BlastX final SortedMap<Integer, Collection<Pair<Integer, String>>> pos2Insertions = new TreeMap<>(); Integer which = 0; for (byte[][] readMatchPair : readMatchPairs) { String readHeader = StringUtils.toString(readMatchPair[0]); String readSequence = StringUtils.toString(readMatchPair[1]); String matchText = StringUtils.toString(readMatchPair[2]); totalReadsIn++; if (getBlastType().equals(UNKNOWN)) setBlastType(BlastParsingUtils.guessBlastType(matchText)); // set sequence type switch (getBlastType()) { case BLASTX -> { alignment.setReferenceType(Alignment.PROTEIN); alignment.setSequenceType(Alignment.cDNA); } case BLASTP -> { alignment.setReferenceType(Alignment.PROTEIN); alignment.setSequenceType(Alignment.PROTEIN); } case BLASTN -> { alignment.setReferenceType(Alignment.DNA); alignment.setSequenceType(Alignment.DNA); } } try { Collection<Pair<Integer, String>> insertions = new LinkedList<>(); switch (getBlastType()) { case BLASTX -> computeGappedSequenceBlastX(readHeader, readSequence, matchText, insertions, showInsertions, referenceSequence, originalReferenceSequence, alignment); case BLASTP -> computeGappedSequenceBlastP(readHeader, readSequence, matchText, insertions, showInsertions, referenceSequence, alignment); case BLASTN -> computeGappedSequenceBlastN(readHeader, readSequence, matchText, insertions, showInsertions, referenceSequence, alignment); } totalReadsOut++; for (Pair<Integer, String> insertion : insertions) { Collection<Pair<Integer, String>> list = pos2Insertions.computeIfAbsent(insertion.getFirst(), k -> new LinkedList<>()); list.add(new Pair<>(which, insertion.getSecond())); } which++; } catch (Exception ex) { Basic.caught(ex); System.err.println("Error: " + ex); totalErrors++; } progressListener.incrementProgress(); } if (referenceSequence.get() != null) { int originalLength = referenceSequence.get().length; int trueLength = referenceSequence.get().length; while (trueLength > 0 && referenceSequence.get()[trueLength - 1] == 0) { if (alignment.getReferenceType().equals(Alignment.PROTEIN) && trueLength > 2 && referenceSequence.get()[trueLength - 3] != 0) break; trueLength--; } if (trueLength < originalLength) { referenceSequence.set(Arrays.copyOf(referenceSequence.get(), trueLength)); alignment.trimToTrueLength(trueLength); } for (int i = 0; i < referenceSequence.get().length; i++) { if (referenceSequence.get()[i] == 0) referenceSequence.get()[i] = ' '; } alignment.setReference(matchRefLine, new String(referenceSequence.get())); if (originalReferenceSequence.get() != null) alignment.setOriginalReference(new String(originalReferenceSequence.get())); } if (showInsertions && pos2Insertions.size() > 0) { addInsertionsToAlignment(pos2Insertions, alignment, progressListener); } if (totalReadsIn != totalReadsOut) { System.err.println("Reads in: " + totalReadsIn); System.err.println("Reads out: " + totalReadsOut); } if (totalErrors > 0) System.err.println("Errors: " + totalErrors); } /** * add the given insertions to the alignment * */ private void addInsertionsToAlignment(SortedMap<Integer, Collection<Pair<Integer, String>>> pos2Insertions, Alignment alignment, ProgressListener progressListener) throws CanceledException { // insertions into reference sequence: if (alignment.getReference().getLength() > 0) { Lane reference = alignment.getReference(); int offset = 0; for (Integer col : pos2Insertions.keySet()) { int maxInsertion = 0; Collection<Pair<Integer, String>> insertions = pos2Insertions.get(col); for (Pair<Integer, String> pair : insertions) { maxInsertion = Math.max(maxInsertion, pair.getSecond().length()); } col += offset; if (maxInsertion > 0) { if (col < reference.getLeadingGaps()) { reference.setLeadingGaps(reference.getLeadingGaps() + maxInsertion); } else if (col < reference.getLeadingGaps() + reference.getBlock().length()) { int insertAfter = col - reference.getLeadingGaps(); reference.setBlock(reference.getBlock().substring(0, insertAfter + 1) + gaps(maxInsertion) + reference.getBlock().substring(insertAfter + 1)); } else if (col > reference.getLeadingGaps() + reference.getBlock().length()) { reference.setTrailingGaps(reference.getTrailingGaps() + maxInsertion); } offset += maxInsertion; } for (int i = col + 1; i < col + maxInsertion + 1; i++) { alignment.getInsertionsIntoReference().add(i); } progressListener.checkForCancel(); } } // insertions into alignment if (alignment.getNumberOfSequences() > 0) { for (int row = 0; row < alignment.getNumberOfSequences(); row++) { alignment.getLane(row).setBlock(alignment.getLane(row).getBlock().toUpperCase()); } int offset = 0; for (Integer col : pos2Insertions.keySet()) { int maxInsertion = 0; Collection<Pair<Integer, String>> insertions = pos2Insertions.get(col); for (Pair<Integer, String> pair : insertions) { maxInsertion = Math.max(maxInsertion, pair.getSecond().length()); } col += offset; if (maxInsertion > 0) { Set<Integer> seen = new HashSet<>(); for (Pair<Integer, String> pair : insertions) { int row = pair.getFirst(); seen.add(row); String insert = pair.getSecond(); Lane lane = alignment.getLane(row); if (col < lane.getLeadingGaps()) { lane.setLeadingGaps(lane.getLeadingGaps() + maxInsertion); } else if (col < lane.getLeadingGaps() + lane.getBlock().length()) { int insertAfter = col - lane.getLeadingGaps(); lane.setBlock(lane.getBlock().substring(0, insertAfter + 1) + insert.toLowerCase() + gaps(maxInsertion - insert.length()) + lane.getBlock().substring(insertAfter + 1)); } else if (col > lane.getLeadingGaps() + lane.getBlock().length()) { lane.setTrailingGaps(lane.getTrailingGaps() + maxInsertion); } } for (int row = 0; row < alignment.getNumberOfSequences(); row++) { if (!seen.contains(row)) { Lane lane = alignment.getLane(row); if (col < lane.getLeadingGaps()) { lane.setLeadingGaps(lane.getLeadingGaps() + maxInsertion); } else if (col < lane.getLeadingGaps() + lane.getBlock().length()) { int insertAfter = col - lane.getLeadingGaps(); lane.setBlock(lane.getBlock().substring(0, insertAfter + 1) + gaps(maxInsertion) + lane.getBlock().substring(insertAfter + 1)); } else if (col > lane.getLeadingGaps() + lane.getBlock().length()) { lane.setTrailingGaps(lane.getTrailingGaps() + maxInsertion); } } } offset += maxInsertion; } progressListener.checkForCancel(); } } } /** * get string of n gaps * * @return string of n gaps */ private String gaps(int n) { StringBuilder buf = new StringBuilder(); for (; n > 0; n--) { buf.append('-'); } return buf.toString(); } /** * compute the aligned read sequence * */ private static void computeGappedSequenceBlastX(String readName, String readSequence, String text, Collection<Pair<Integer, String>> insertions, boolean showInsertions, Single<char[]> referenceSequence, Single<char[]> originalReferenceSequence, Alignment alignment) throws IOException { int length = NumberUtils.parseInt(BlastParsingUtils.grabNext(text, "Length =", "Length=")); if (length == 0) length = 10000; if (referenceSequence.get() == null) referenceSequence.set(new char[3 * length]); if (originalReferenceSequence.get() == null) { originalReferenceSequence.set(new char[length]); for (int i = 0; i < length; i++) { originalReferenceSequence.get()[i] = '?'; } } final int frame = NumberUtils.parseInt(BlastParsingUtils.grabNext(text, "Frame =", "Frame=")); int startQuery = NumberUtils.parseInt(BlastParsingUtils.grabNext(text, "Query:", "Query")); int endQuery = NumberUtils.parseInt(BlastParsingUtils.grabLastInLinePassedScore(text, "Query")); if (readSequence == null) throw new IOException("Read '" + readName + "': sequence not found"); if (readSequence.length() < Math.max(startQuery, endQuery)) { throw new IOException("Read '" + readName + "': read length too short: " + readSequence.length() + " < " + Math.max(startQuery, endQuery)); } int startSubject = NumberUtils.parseInt(BlastParsingUtils.grabNext(text, "Sbjct:", "Sbjct")); int endSubject = NumberUtils.parseInt(BlastParsingUtils.grabLastInLinePassedScore(text, "Sbjct")); String queryString = BlastParsingUtils.grabQueryString(text); String subjectString = BlastParsingUtils.grabSubjectString(text); int p = startSubject; for (int i = 0; i < subjectString.length(); i++) { if (subjectString.charAt(i) != '-') { referenceSequence.get()[3 * (p - 1)] = subjectString.charAt(i); originalReferenceSequence.get()[p - 1] = subjectString.charAt(i); p++; } } if (frame < 0) { readName += " (rev)"; startQuery = readSequence.length() - startQuery + 1; endQuery = readSequence.length() - endQuery + 1; readSequence = SequenceUtils.getReverseComplement(readSequence); } int pos = startQuery - 1; // position in actual sequence int alignPos = 3 * (startSubject - 1); // pos in DNA alignment //System.err.println("read-length: "+readSequence.length()); //System.err.println("query-length: "+queryString.length()); //System.err.println("sbjct-length: "+subjectString.length()); Pair<Integer, String> insertion = null; StringWriter w = new StringWriter(); for (int mPos = 0; mPos < queryString.length(); mPos++) { if (queryString.charAt(mPos) == '-') { if (insertion != null) { insertion = null; } w.write("---"); alignPos += 3; } else if (subjectString.charAt(mPos) == '-') { if (showInsertions) { if (insertion == null) { insertion = new Pair<>(alignPos - 1, readSequence.substring(pos, pos + 3)); insertions.add(insertion); } else { insertion.setSecond(insertion.getSecond() + readSequence.substring(pos, pos + 3)); } } pos += 3; alignPos += 3; } else { if (insertion != null) { insertion = null; } if (pos < 0) { throw new IOException("pos too small: " + pos); } if (pos >= readSequence.length()) { throw new IOException("pos overrun end of read: " + pos + " >= " + readSequence.length()); } else { w.write(readSequence.charAt(pos++)); w.write(readSequence.charAt(pos++)); w.write(readSequence.charAt(pos++)); alignPos += 3; } } } /* if (pos != endQuery) { System.err.println("Pos not exhausted: "+pos+" != "+endQuery); } */ final String block = w.toString(); final int leadingGaps = 3 * (startSubject - 1); final int trailingGaps = 3 * (length - endSubject); final String unalignedPrefix = readSequence.substring(0, startQuery); final String unalignedSuffix = readSequence.substring(endQuery); alignment.addSequence(readName, text, null, unalignedPrefix, leadingGaps, block, trailingGaps, unalignedSuffix); } /** * compute the aligned read sequence * */ private static void computeGappedSequenceBlastP(String readName, String readSequence, String text, Collection<Pair<Integer, String>> insertions, boolean showInsertions, Single<char[]> referenceSequence, Alignment alignment) throws IOException { int length = NumberUtils.parseInt(BlastParsingUtils.grabNext(text, "Length =", "Length=")); if (length == 0) length = 10000; if (referenceSequence.get() == null) referenceSequence.set(new char[length]); int startQuery = NumberUtils.parseInt(BlastParsingUtils.grabNext(text, "Query:", "Query")); int endQuery = NumberUtils.parseInt(BlastParsingUtils.grabLastInLinePassedScore(text, "Query")); if (readSequence == null) throw new IOException("Read '" + readName + "': sequence not found"); if (readSequence.length() < Math.max(startQuery, endQuery)) { throw new IOException("Read '" + readName + "': read length too short: " + readSequence.length() + " < " + Math.max(startQuery, endQuery)); } int startSubject = NumberUtils.parseInt(BlastParsingUtils.grabNext(text, "Sbjct:", "Sbjct")); int endSubject = NumberUtils.parseInt(BlastParsingUtils.grabLastInLinePassedScore(text, "Sbjct")); String queryString = BlastParsingUtils.grabQueryString(text); String subjectString = BlastParsingUtils.grabSubjectString(text); int p = startSubject; for (int i = 0; i < subjectString.length(); i++) { if (subjectString.charAt(i) != '-') { referenceSequence.get()[p - 1] = subjectString.charAt(i); p++; } } int alignPos = (startSubject - 1); // pos in DNA alignment //System.err.println("read-length: "+readSequence.length()); //System.err.println("query-length: "+queryString.length()); //System.err.println("sbjct-length: "+subjectString.length()); Pair<Integer, String> insertion = null; final StringWriter w = new StringWriter(); for (int mPos = 0; mPos < queryString.length(); mPos++) { char ch = queryString.charAt(mPos); if (ch == '-') { if (insertion != null) { insertion = null; } w.write("-"); alignPos += 1; } else if (subjectString.charAt(mPos) == '-') { if (showInsertions) { if (insertion == null) { insertion = new Pair<>(alignPos - 1, queryString.substring(mPos, mPos + 1)); insertions.add(insertion); } else { insertion.setSecond(insertion.getSecond() + readSequence.charAt(mPos)); } } alignPos += 1; } else { if (insertion != null) { insertion = null; } w.write(ch); alignPos += 1; } } String block = w.toString(); int leadingGaps = startSubject - 1; int trailingGaps = length - endSubject; String unalignedPrefix = readSequence.substring(0, startQuery); String unalignedSuffix = readSequence.substring(endQuery); alignment.addSequence(readName, text, null, unalignedPrefix, leadingGaps, block, trailingGaps, unalignedSuffix); } /** * compute the aligned read sequence * */ private static void computeGappedSequenceBlastN(String readName, String readSequence, String text, Collection<Pair<Integer, String>> insertions, boolean showInsertions, Single<char[]> referenceSequence, Alignment alignment) throws IOException { boolean hasExactLength; int length = NumberUtils.parseInt(BlastParsingUtils.grabNext(text, "Length =", "Length=")); if (length > 0) { hasExactLength = true; } else { hasExactLength = false; length = NumberUtils.parseInt(BlastParsingUtils.grabNext(text, "Length >=", "Length>=")); if (referenceSequence.get() != null && referenceSequence.get().length < length) { // need to resize the reference sequence char[] newRef = new char[length + 1]; System.arraycopy(referenceSequence.get(), 0, newRef, 0, referenceSequence.get().length); referenceSequence.set(newRef); } } String[] strand; String tmpString = BlastParsingUtils.grabNext(text, "Strand =", "Strand="); if (tmpString != null && tmpString.contains("/")) { int pos = tmpString.indexOf("/"); strand = new String[]{tmpString.substring(0, pos), "/", tmpString.substring(pos + 1)}; } else strand = BlastParsingUtils.grabNext3(text, "Strand =", "Strand="); if (referenceSequence.get() == null) referenceSequence.set(new char[length + 10000]); int startQuery = NumberUtils.parseInt(BlastParsingUtils.grabNext(text, "Query:", "Query")); int endQuery = NumberUtils.parseInt(BlastParsingUtils.grabLastInLinePassedScore(text, "Query")); if (readSequence == null) throw new IOException("Read '" + readName + "': sequence not found"); if (readSequence.length() < Math.max(startQuery, endQuery)) { throw new IOException("Read '" + readName + "': read length too short: " + readSequence.length() + " < " + Math.max(startQuery, endQuery)); } int startSubject = BlastParsingUtils.getStartSubject(text); int endSubject = BlastParsingUtils.getEndSubject(text); String queryString = BlastParsingUtils.grabQueryString(text); String subjectString = BlastParsingUtils.grabSubjectString(text); if (strand != null && strand[0].equalsIgnoreCase("Minus") && strand[2].equalsIgnoreCase("Minus")) { throw new IOException("Can't parse matches with Strand = Minus / Minus"); } if (strand != null && strand[0].equalsIgnoreCase("Minus")) { int tmp = Math.max(startQuery, endQuery); startQuery = Math.min(startQuery, endQuery); endQuery = tmp; //queryString = SequenceUtils.getReverseComplement(queryString); // subject string has positive strand //subjectString = SequenceUtils.getReverseComplement(subjectString); readName += " (-/+)"; } if (strand != null && strand[2].equalsIgnoreCase("Minus")) { int tmp = Math.max(startSubject, endSubject); startSubject = Math.min(startSubject, endSubject); endSubject = tmp; queryString = SequenceUtils.getReverseComplement(queryString); subjectString = SequenceUtils.getReverseComplement(subjectString); if (!strand[0].equalsIgnoreCase("Minus")) readName += " (+/-)"; } int p = startSubject; for (int i = 0; i < subjectString.length(); i++) { if (subjectString.charAt(i) != '-') { /* char previousCh=referenceSequence.get()[p - 1]; char newCh=subjectString.charAt(i); if(p==792) System.err.println("Setting subj["+(p-1)+"]="+newCh+" previous="+previousCh); */ // todo: Just reactivated this, might cause problems: referenceSequence.get()[p - 1] = subjectString.charAt(i); p++; } } int alignPos = (startSubject - 1); // pos in DNA alignment //System.err.println("read-length: "+readSequence.length()); //System.err.println("query-length: "+queryString.length()); //System.err.println("sbjct-length: "+subjectString.length()); StringWriter w = new StringWriter(); Pair<Integer, String> insertion = null; for (int mPos = 0; mPos < queryString.length(); mPos++) { char ch = queryString.charAt(mPos); if (ch == '-') { if (insertion != null) { insertion = null; } w.write("-"); alignPos += 1; } else if (subjectString.charAt(mPos) == '-') { if (showInsertions) { if (insertion == null) { insertion = new Pair<>(alignPos - 1, queryString.substring(mPos, mPos + 1)); insertions.add(insertion); } else { insertion.setSecond(insertion.getSecond() + queryString.charAt(mPos)); } } alignPos += 1; } else { if (insertion != null) { insertion = null; } { w.write(ch); alignPos += 1; } } } String block = w.toString(); int leadingGaps = startSubject - 1; int trailingGaps = length - endSubject; String unalignedPrefix = readSequence.substring(0, startQuery - 1); String unalignedSuffix = readSequence.substring(endQuery); alignment.addSequence(readName, text, null, unalignedPrefix, leadingGaps, block, trailingGaps, unalignedSuffix); if (!hasExactLength) { boolean hasLengthDifferences = false; int longest = 0; for (int row = 0; row < alignment.getNumberOfSequences(); row++) { int aLength = alignment.getLane(row).getLength(); if (aLength > longest) { if (longest > 0) hasLengthDifferences = true; longest = aLength; } } if (hasLengthDifferences) { for (int row = 0; row < alignment.getNumberOfSequences(); row++) { Lane lane = alignment.getLane(row); if (lane.getLength() < longest) { lane.setTrailingGaps(lane.getTrailingGaps() + (longest - lane.getLength())); } } } } } }
37,419
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
AlignmentExporter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/AlignmentExporter.java
/* * AlignmentExporter.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment; import jloda.seq.SequenceUtils; import jloda.util.*; import jloda.util.progress.ProgressCmdLine; import jloda.util.progress.ProgressListener; import megan.alignment.gui.Alignment; import megan.alignment.gui.Lane; import megan.core.Document; import megan.data.IMatchBlock; import megan.data.IReadBlock; import megan.data.IReadBlockIterator; import megan.rma2.MatchBlockRMA2; import megan.rma2.ReadBlockRMA2; import javax.swing.*; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; /** * exports alignments to a set of files * Daniel Huson, 9.2011 */ public class AlignmentExporter { private final Document doc; private final JFrame parent; private String classificationName; private int classId; private String className; private final Map<String, List<Pair<IReadBlock, IMatchBlock>>> reference2ReadMatchPairs = new HashMap<>(); private final Set<String> usedReferences = new HashSet<>(); private boolean useEachReferenceOnlyOnce = true; private boolean warned = false; private boolean overwrite = true; private boolean verbose = false; /** * constructor * */ public AlignmentExporter(Document doc, JFrame parent) { this.doc = doc; this.parent = parent; } /** * load data for complete dataset * */ public void loadData(ProgressListener progressListener) throws CanceledException, IOException { className = "Total sample"; int totalReads = 0; int totalReadsUsed = 0; reference2ReadMatchPairs.clear(); Set<String> matchesSeenForGivenRead = new HashSet<>(); progressListener.setSubtask("Processing total dataset"); try (IReadBlockIterator it = doc.getConnector().getAllReadsIterator(doc.getMinScore(), doc.getMaxExpected(), true, true)) { progressListener.setMaximum(it.getMaximumProgress()); progressListener.setProgress(0); while (it.hasNext()) { IReadBlock readBlock = it.next(); totalReads++; boolean readUsed = false; for (IMatchBlock matchBlock : readBlock.getMatchBlocks()) { if (matchBlock.getBitScore() >= doc.getMinScore() && matchBlock.getExpected() <= doc.getMaxExpected() && (matchBlock.getPercentIdentity() == 0 || matchBlock.getPercentIdentity() >= doc.getMinPercentIdentity())) { String key = StringUtils.getFirstLine(matchBlock.getText()); if (!matchesSeenForGivenRead.contains(key)) { matchesSeenForGivenRead.add(key); List<Pair<IReadBlock, IMatchBlock>> pairs = reference2ReadMatchPairs.computeIfAbsent(key, k -> new LinkedList<>()); pairs.add(new Pair<>(readBlock, matchBlock)); readUsed = true; } } } matchesSeenForGivenRead.clear(); progressListener.incrementProgress(); if (readUsed) totalReadsUsed++; } } System.err.println("Reads total: " + totalReads); System.err.println("Reads used: " + totalReadsUsed); System.err.println("References: " + reference2ReadMatchPairs.keySet().size()); } /** * load data for given class * */ public void loadData(String classificationName, Integer classId, String name, boolean refSeqOnly, ProgressListener progressListener) throws CanceledException, IOException { this.classificationName = classificationName; this.classId = classId; this.className = name; int totalReads = 0; int totalReadsUsed = 0; reference2ReadMatchPairs.clear(); Set<String> matchesSeenForGivenRead = new HashSet<>(); progressListener.setSubtask("Processing '" + name + "'"); try (IReadBlockIterator it = doc.getConnector().getReadsIterator(classificationName, classId, 0, 10, true, true)) { progressListener.setMaximum(it.getMaximumProgress()); progressListener.setProgress(0); while (it.hasNext()) { IReadBlock readBlock = copy(it.next(), new String[]{classificationName}); totalReads++; boolean readUsed = false; for (IMatchBlock matchBlock : readBlock.getMatchBlocks()) { if (matchBlock.getBitScore() >= doc.getMinScore() && matchBlock.getExpected() <= doc.getMaxExpected() && (matchBlock.getPercentIdentity() == 0 || matchBlock.getPercentIdentity() >= doc.getMinPercentIdentity())) { if (!refSeqOnly || (matchBlock.getRefSeqId() != null && matchBlock.getRefSeqId().length() > 0)) { String key = StringUtils.getFirstLine(matchBlock.getText()); if (!matchesSeenForGivenRead.contains(key)) { matchesSeenForGivenRead.add(key); List<Pair<IReadBlock, IMatchBlock>> pairs = reference2ReadMatchPairs.computeIfAbsent(key, k -> new LinkedList<>()); pairs.add(new Pair<>(readBlock, matchBlock)); readUsed = true; } } } } matchesSeenForGivenRead.clear(); progressListener.incrementProgress(); if (readUsed) totalReadsUsed++; } } System.err.printf("Reads total: %,10d%n", totalReads); System.err.printf("Reads used: %,10d %n", totalReadsUsed); System.err.printf("References: %,10d%n", reference2ReadMatchPairs.keySet().size()); } private IReadBlock copy(IReadBlock src, String[] cNames) { final ReadBlockRMA2 readBlock = new ReadBlockRMA2(); readBlock.setReadHeader(src.getReadHeader()); readBlock.setReadSequence(src.getReadSequence()); readBlock.setReadWeight(src.getReadWeight()); readBlock.setNumberOfMatches(src.getNumberOfMatches()); IMatchBlock[] matches = new MatchBlockRMA2[src.getNumberOfMatches()]; for (int i = 0; i < src.getNumberOfMatches(); i++) matches[i] = copy(src.getMatchBlock(i), cNames); readBlock.setMatchBlocks(matches); return readBlock; } private IMatchBlock copy(IMatchBlock src, String[] cNames) { final MatchBlockRMA2 matchBlock = new MatchBlockRMA2(); matchBlock.setBitScore(src.getBitScore()); matchBlock.setExpected(src.getExpected()); matchBlock.setLength(src.getLength()); matchBlock.setPercentIdentity(src.getPercentIdentity()); matchBlock.setText(src.getText()); matchBlock.setIgnore(src.isIgnore()); for (String name : cNames) { matchBlock.setId(name, src.getId(name)); } return matchBlock; } /** * export all loaded alignments to individual files * * @return the number of reads and files */ public Pair<Integer, Integer> exportToFiles(int totalFilesWritten, final String fileNameTemplate, final boolean useAnyReadOnlyOnce, final boolean blastXAsProtein, final boolean asConsensus, int minReads, int minLength, final double minCoverage, final ProgressListener progressListener) throws IOException, CanceledException { // sort data by decreasing number of reads associated with a given reference sequence final SortedSet<Pair<String, List<Pair<IReadBlock, IMatchBlock>>>> sorted = new TreeSet<>((pair1, pair2) -> { if (pair1.getSecond().size() > pair2.getSecond().size()) return -1; else if (pair1.getSecond().size() < pair2.getSecond().size()) return 1; else return pair1.getFirst().compareTo(pair2.getFirst()); }); for (String reference : reference2ReadMatchPairs.keySet()) { List<Pair<IReadBlock, IMatchBlock>> value = reference2ReadMatchPairs.get(reference); if (value != null) sorted.add(new Pair<>(reference, value)); } Blast2Alignment blast2Alignment = new Blast2Alignment(doc); progressListener.setSubtask("Writing data"); progressListener.setMaximum(sorted.size()); progressListener.setProgress(0); int totalOutputSequences = 0; Set<String> fileNames = new HashSet<>(); final Alignment alignment = new Alignment(); // go through all alignments in decreasing order of size and write to files while (sorted.size() > 0) { progressListener.incrementProgress(); final Pair<String, List<Pair<IReadBlock, IMatchBlock>>> pair = sorted.first(); sorted.remove(pair); final String reference = pair.getFirst(); blast2Alignment.loadData(classificationName, classId, className, reference, pair.getSecond()); blast2Alignment.makeAlignment(reference, alignment, true, new ProgressCmdLine()); if (minReads > 1 && alignment.getNumberOfSequences() < minReads) { if (verbose) System.err.println(" (too few reads, skipped)"); continue; } if (verbose && minLength > 1 && alignment.getLength() < minLength) { if (verbose) System.err.println(" (too short, skipped)"); continue; } if (minCoverage > 0) { final Pair<Double, Double> gcAndCoverage = ComputeAlignmentProperties.computeCGContentAndCoverage(alignment, verbose ? new ProgressCmdLine() : null); if (verbose) System.err.printf("%s: %s: coverage=%.2f", className, reference, gcAndCoverage.getSecond()); if (gcAndCoverage.getSecond() < minCoverage) { if (verbose) System.err.println(" (coverage too low, skipped)"); continue; } else if (verbose) System.err.println(); } if (!(useEachReferenceOnlyOnce && usedReferences.contains(reference))) { if (useEachReferenceOnlyOnce) usedReferences.add(reference); totalFilesWritten++; String fileName = "" + fileNameTemplate; if (fileName.contains("%n")) fileName = fileNameTemplate.replaceAll("%n", String.format("%05d", totalFilesWritten)); if (fileName.contains("%c")) fileName = fileName.replaceAll("%c", (className != null ? StringUtils.toCleanName(className.trim()) : "")); if (fileName.contains("%r")) fileName = fileName.replaceAll("%r", StringUtils.toCleanName(reference.trim())); if (fileNames.contains(fileName)) fileName = FileUtils.replaceFileSuffix(fileName, "-" + totalFilesWritten + FileUtils.getFileSuffix(fileName)); fileNames.add(fileName); if ((new File(fileName)).exists()) { if (!warned) { if (ProgramProperties.isUseGUI()) { int result = JOptionPane.showConfirmDialog(parent, "Some files already exist, overwrite all existing files?", "Overwrite files?", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, jloda.swing.util.ProgramProperties.getProgramIcon()); switch (result) { case JOptionPane.NO_OPTION -> overwrite = false; case JOptionPane.CANCEL_OPTION -> throw new CanceledException(); default -> { } } } warned = true; } if (!overwrite) { System.err.println("Skipping existing file: '" + fileName + "'"); continue; } } final File outputFile = new File(fileName); try (BufferedWriter w = new BufferedWriter(new FileWriter(outputFile))) { if (asConsensus) { System.err.println("Writing consensus of " + alignment.getNumberOfSequences() + " reads to file: '" + fileName + "'"); String consensus = alignment.computeConsensus(); w.write("> Consensus\n" + consensus + "\n"); totalOutputSequences++; } else { System.err.println("Writing " + alignment.getNumberOfSequences() + " reads to file: '" + fileName + "'"); if (blastXAsProtein) { // Write DNA as translated if (alignment.getSequenceType().equals(Alignment.cDNA) && alignment.getReference() != null && alignment.getReference().getLength() > 0) { w.write(alignment.getReferenceName() + "\n"); final String ref; if (alignment.getOriginalReference() != null) ref = alignment.getOriginalReference().getSequence(); else ref = alignment.getReference().getSequence(); w.write(ref); // todo: ref sequence is currently missing leading gaps w.write("\n"); } int minRow = 0; int maxRow = alignment.getNumberOfSequences() - 1; for (int row = minRow; row <= maxRow; row++) { w.write(">" + StringUtils.swallowLeadingGreaterSign(alignment.getName(row)) + "\n"); Lane lane = alignment.getLane(row); for (int i = 0; i < lane.getFirstNonGapPosition(); i += 3) w.write("-"); String sequence = lane.getBlock(); for (int i = 0; i < sequence.length() - 2; i += 3) { w.write(SequenceUtils.getAminoAcid(sequence, i)); } for (int i = lane.getLastNonGapPosition() + 1; i < lane.getLength(); i += 3) w.write("-"); w.write("\n"); } } else { // write as DNA if (alignment.getSequenceType().equals(Alignment.cDNA) && alignment.getReference() != null && alignment.getReference().getLength() > 0) { w.write(alignment.getReferenceName() + "\n"); final String ref; if (alignment.getOriginalReference() != null) ref = alignment.getOriginalReference().getSequence(); else ref = alignment.getReference().getSequence(); w.write(ref); // todo: ref sequence is currently missing leading gaps w.write("\n"); } w.write(alignment.toFastA()); } totalOutputSequences += blast2Alignment.getTotalNumberOfReads(); } if (useAnyReadOnlyOnce) removeReadsFromSets(sorted, pair); // any read used is removed from all other alignments } if (outputFile.exists() && outputFile.length() == 0) { if (outputFile.delete()) totalFilesWritten--; } } } reference2ReadMatchPairs.clear(); System.err.printf("Output reads:%,10d%n", totalOutputSequences); System.err.printf("Output files:%,10d%n", totalFilesWritten); return new Pair<>(totalOutputSequences, totalFilesWritten); } /** * remove all reads used in current alignment from the remaining ones in the sorte dset. Reinserts modified alignments so that the sorted set stays sorted * */ private void removeReadsFromSets(SortedSet<Pair<String, List<Pair<IReadBlock, IMatchBlock>>>> sorted, Pair<String, List<Pair<IReadBlock, IMatchBlock>>> current) { // determine set of matches that have just been used Set<IReadBlock> reads = new HashSet<>(); for (Pair<IReadBlock, IMatchBlock> readAndMatch : current.getSecond()) { reads.add(readAndMatch.getFirst()); } // determine which remaining alignment sets contain at least one used read List<Pair<String, List<Pair<IReadBlock, IMatchBlock>>>> toModify = new LinkedList<>(); for (Pair<String, List<Pair<IReadBlock, IMatchBlock>>> refReadMatches : sorted) { for (Pair<IReadBlock, IMatchBlock> readMatch : refReadMatches.getSecond()) { if (reads.contains(readMatch.getFirst())) { toModify.add(refReadMatches); break; } } } // remove all used reads, re-inserting modified datasets into the sorted set. for (Pair<String, List<Pair<IReadBlock, IMatchBlock>>> refReadMatches : toModify) { sorted.remove(refReadMatches); List<Pair<IReadBlock, IMatchBlock>> toDelete = new LinkedList<>(); for (Pair<IReadBlock, IMatchBlock> readMatch : refReadMatches.getSecond()) { if (reads.contains(readMatch.getFirst())) { toDelete.add(readMatch); } } refReadMatches.getSecond().removeAll(toDelete); if (refReadMatches.getSecond().size() > 0) sorted.add(refReadMatches); } } public void setUseEachReferenceOnlyOnce(boolean useEachReferenceOnlyOnce) { this.useEachReferenceOnlyOnce = useEachReferenceOnlyOnce; } public boolean isUseEachReferenceOnlyOnce() { return useEachReferenceOnlyOnce; } public boolean isVerbose() { return verbose; } public void setVerbose(boolean verbose) { this.verbose = verbose; } }
19,680
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
AnimatedRectangle.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/AnimatedRectangle.java
/* * AnimatedRectangle.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui; import jloda.swing.util.ProgramProperties; import javax.swing.*; import java.awt.*; import java.awt.geom.Rectangle2D; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import static java.util.concurrent.TimeUnit.MILLISECONDS; /** * An animated rectangle * Daniel Huson, 9.2011 */ public class AnimatedRectangle { static private ScheduledExecutorService scheduler; static private final List<WeakReference<AnimatedRectangle>> animatedRectangles = new LinkedList<>(); static private final BasicStroke backgroundStroke = new BasicStroke(2); static private final BasicStroke evenStroke = new BasicStroke(2, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 1, new float[]{5, 5}, 0); static private final BasicStroke oddStroke = new BasicStroke(2, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 1, new float[]{5, 5}, 5); static private final BasicStroke basicStroke = new BasicStroke(1); static private final Rectangle2D drawRectangle = new Rectangle2D.Float(); private final static Color highlightColor = ProgramProperties.SELECTION_COLOR_ADDITIONAL_TEXT.darker(); private JPanel panel; private boolean animate; private Rectangle2D rectangle; private boolean even; /** */ public AnimatedRectangle(JPanel panel) { this.panel = panel; if (scheduler == null) { scheduler = Executors.newScheduledThreadPool(1); scheduler.scheduleAtFixedRate(() -> { try { SwingUtilities.invokeAndWait(() -> { synchronized (animatedRectangles) { for (WeakReference<AnimatedRectangle> weak : animatedRectangles) { weak.get().draw(); } } }); } catch (InterruptedException | InvocationTargetException ignored) { } }, 0, 500, MILLISECONDS); } animatedRectangles.add(new WeakReference<>(this)); } /** * currently blinking? * * @return true, if blinking */ public boolean isAnimate() { return animate; } /** * turn blinking on or off * */ public void setAnimate(boolean animate) { this.animate = animate; } /** * get the set rectangle * * @return rectangle */ public Rectangle2D getRectangle() { return rectangle; } /** * set rectangle in panel coordinates * */ public void setRectangle(JPanel panel, Rectangle2D rectangle) { this.panel = panel; this.rectangle = (Rectangle2D) rectangle.clone(); } /** * draws the blinking rectangle */ private void draw() { if (animate && rectangle != null) { Rectangle2D visibleRect = panel.getVisibleRect(); double xMin = Math.max(rectangle.getX(), visibleRect.getX()); double xMax = Math.min(rectangle.getX() + rectangle.getWidth(), visibleRect.getX() + visibleRect.getWidth() - 2); double width = xMax - xMin; double yMin = Math.max(rectangle.getY(), visibleRect.getY()); double yMax = Math.min(rectangle.getY() + rectangle.getHeight(), visibleRect.getY() + visibleRect.getHeight() - 2); double height = yMax - yMin; drawRectangle.setRect(xMin, yMin, width, height); Graphics2D gc = (Graphics2D) panel.getGraphics(); if (gc != null) { gc.setStroke(backgroundStroke); gc.setColor(Color.WHITE); gc.draw(drawRectangle); gc.setColor(highlightColor); if (even) { gc.setStroke(evenStroke); even = false; } else { gc.setStroke(oddStroke); even = true; } gc.draw(drawRectangle); gc.setStroke(basicStroke); } } } }
5,050
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
GapColumnContractor.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/GapColumnContractor.java
/* * GapColumnContractor.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui; import jloda.util.Pair; import java.util.*; /** * manages contracted columns in an alignment * Daniel Huson, 9.2011 */ public class GapColumnContractor { private final LinkedList<Pair<Integer, Integer>> origGapColumns = new LinkedList<>(); private final Map<Integer, Integer> orig2jump = new HashMap<>(); private final Map<Integer, Integer> layout2jump = new HashMap<>(); private int jumped; private int originalColumns; private boolean enabled = true; public GapColumnContractor() { clear(); } public void clear() { origGapColumns.clear(); orig2jump.clear(); originalColumns = 0; layout2jump.clear(); jumped = 0; } /** * compute gap columns for alignment * */ public void processAlignment(Alignment alignment) { clear(); if (alignment != null) { LinkedList<Pair<Integer, Integer>> events = new LinkedList<>(); for (int row = 0; row < alignment.getNumberOfSequences(); row++) { Lane lane = alignment.getLane(row); Pair<Integer, Integer> startEvent = new Pair<>(lane.getFirstNonGapPosition(), -1); events.add(startEvent); Pair<Integer, Integer> endEvent = new Pair<>(lane.getLastNonGapPosition(), 1); events.add(endEvent); } Pair<Integer, Integer>[] array = (Pair<Integer, Integer>[]) events.toArray(new Pair[0]); Arrays.sort(array); int lastStart = 0; int coverage = 0; for (Pair<Integer, Integer> event : array) { if (event.getSecond() == -1) // start { if (coverage == 0) { if (event.getFirst() - 1 >= 0 && lastStart != -1) { origGapColumns.add(new Pair<>(lastStart, event.getFirst() - 1)); orig2jump.put(lastStart, event.getFirst() - lastStart); lastStart = -1; } } coverage++; } else if (event.getSecond() == 1) // end of an interval { coverage--; if (coverage == 0) lastStart = event.getFirst(); } } if (lastStart != -1 && lastStart < alignment.getLength()) { origGapColumns.add(new Pair<>(lastStart, alignment.getLength())); orig2jump.put(lastStart, alignment.getLength() - lastStart); } originalColumns = alignment.getLength(); for (Pair<Integer, Integer> col : origGapColumns) { layout2jump.put(col.getFirst() - jumped, orig2jump.get(col.getFirst())); jumped += orig2jump.get(col.getFirst()); } /* for (Pair<Integer, Integer> col : origGapColumns) { System.err.println("Original gap column: " + col); System.err.println("jump: " + orig2jump.get(col.getFirst())); } for (Pair<Integer, Integer> col : layoutGapColumns) { System.err.println("Layout gap column: " + col); System.err.println("jump: " + layout2jump.get(col.getFirst())); } System.err.println("Original columns: " + getLastOriginalColumn()); System.err.println("Layout columns: " + getLastLayoutColumn()); */ } } /** * get the first column to be draw * * @return 0 */ public int getFirstLayoutColumn() { return 0; } /** * get last column to be layed out in the alignment window * * @return number of columns to be drawn */ public int getLastLayoutColumn() { if (enabled) return originalColumns - jumped; else return originalColumns; } /** * gets length of layed out alignment * * @return length */ public int getLayoutLength() { return getLastLayoutColumn() - getFirstLayoutColumn(); } /** * get the first original column. Usually 0 * * @return first original column */ public int getFirstOriginalColumn() { return 0; } /** * gets the last original column. Usually larger than the last layout column because of collapsed gaps * */ public int getLastOriginalColumn() { return originalColumns; } /** * given an original column (0..length), returns the number of gaps to jump, if any * * @return number of gaps to jump, or 0 */ public int getJumpBeforeOriginalColumn(int origColumn) { if (enabled) { Integer result = orig2jump.get(origColumn); return result == null ? 0 : result; } return 0; } /** * given layout column, returns the number of gaps that are jumped, if any * * @return number of gaps jumped, or 0 */ public int getJumpBeforeLayoutColumn(int layoutCol) { if (enabled) { Integer result = layout2jump.get(layoutCol); return result == null ? 0 : result; } return 0; } /** * given layout column, returns the number of gaps that are jumped, if any * * @return number of gaps jumped, or 0 */ public int getTotalJumpBeforeLayoutColumn(int layoutCol) { if (enabled) { int jump = 0; for (Map.Entry<Integer, Integer> entry : layout2jump.entrySet()) { if (entry.getKey() <= layoutCol) jump += entry.getValue(); } return jump; } return 0; } /** * get all jump positions * * @return jump positions */ public SortedSet<Integer> getJumpPositionsRelativeToOriginalColumns() { SortedSet<Integer> positions = new TreeSet<>(); if (enabled) positions.addAll(orig2jump.keySet()); return positions; } /** * get all jump positions * * @return jump positions */ public SortedSet<Integer> getJumpPositionsRelativeToLayoutColumns() { SortedSet<Integer> positions = new TreeSet<>(); if (enabled) positions.addAll(layout2jump.keySet()); return positions; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } }
7,436
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
BasePanel.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/BasePanel.java
/* * BasePanel.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui; import jloda.swing.util.ProgramProperties; import javax.swing.*; import java.awt.*; import java.awt.geom.Point2D; /** * base of scalable panels used in alignmentviewer * Daniel Huson, 9.2011 */ abstract public class BasePanel extends JPanel implements Scrollable { public static int MIN_CELL_HEIGHT = 6; double cellWidth; double cellHeight; Font sequenceFont = new Font(Font.MONOSPACED, Font.PLAIN, 14); final static Color highlightColor = ProgramProperties.SELECTION_COLOR_ADDITIONAL_TEXT.darker(); final static Color highlightColorSemiTransparent = new Color(ProgramProperties.SELECTION_COLOR_ADDITIONAL_TEXT.getRed(), ProgramProperties.SELECTION_COLOR_ADDITIONAL_TEXT.getGreen(), ProgramProperties.SELECTION_COLOR_ADDITIONAL_TEXT.getBlue(), 60); final SelectedBlock selectedBlock; public BasePanel(SelectedBlock selectedBlock) { this.selectedBlock = selectedBlock; selectedBlock.addSelectionListener((selected, minRow, minCol, maxRow, maxCol) -> repaint()); } public double getX(int col) { return cellWidth * col; } public double getY(int row) { return cellHeight * (row + 1); } Font getSequenceFont() { return sequenceFont; } public void setSequenceFont(Font sequenceFont) { this.sequenceFont = sequenceFont; revalidateGrid(); } /** * this should be overridden */ abstract void revalidateGrid(); int getRow(Point2D aPt) { return (int) (aPt.getY() / cellHeight); } int getCol(Point2D aPt) { return (int) (aPt.getX() / cellWidth); } SelectedBlock getSelectedBlock() { return selectedBlock; } public double getCellHeight() { return cellHeight; } public double getCellWidth() { return cellWidth; } /** * sets the scale * */ public void setScale(double hScale, double vScale) { double fontSize; if (hScale > 0 && vScale == 0) fontSize = hScale; else if (hScale == 0 && vScale > 0) fontSize = vScale; else if (hScale > 0 && vScale > 0) fontSize = Math.min(hScale, vScale); else return; sequenceFont = makeFont((int) Math.round(fontSize)); cellWidth = hScale > 0 ? hScale : vScale; cellHeight = vScale > 0 ? vScale : hScale; revalidateGrid(); } /** * makes a font of the correct apparent size * */ private Font makeFont(int fontSize) { FontMetrics seqMetrics = getFontMetrics(new Font(Font.MONOSPACED, Font.PLAIN, fontSize)); int fontHeight = seqMetrics.getAscent(); return new Font(Font.MONOSPACED, Font.PLAIN, (int) (((float) fontSize * fontSize) / fontHeight)); } public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); } public int getScrollableUnitIncrement(Rectangle rectangle, int direction, int value) { if (direction == SwingConstants.HORIZONTAL) return (int) (Math.round(cellWidth)); else return (int) (Math.round(cellHeight)); } public int getScrollableBlockIncrement(Rectangle rectangle, int direction, int value) { if (direction == SwingConstants.HORIZONTAL) return rectangle.width; else return rectangle.height; } public boolean getScrollableTracksViewportWidth() { return false; } public boolean getScrollableTracksViewportHeight() { return false; } }
4,426
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ReferencePanel.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/ReferencePanel.java
/* * ReferencePanel.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui; import jloda.swing.util.Cursors; import megan.alignment.gui.colors.ColorSchemeText; import megan.alignment.gui.colors.IColorScheme; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Rectangle2D; import java.util.SortedSet; /** * reference panel * Daniel Huson, 9.2011 */ public class ReferencePanel extends BasePanel { private Alignment alignment; private IColorScheme colorScheme = new ColorSchemeText(); private boolean showColors = true; /** * constructor */ public ReferencePanel(SelectedBlock selectedBlock) { super(selectedBlock); MyMouseListener listener = new MyMouseListener(); addMouseListener(listener); addMouseMotionListener(listener); setToolTipText("Reference sequence"); revalidate(); } private Alignment getAlignment() { return alignment; } public void setAlignment(Alignment alignment) { this.alignment = alignment; revalidateGrid(); } private IColorScheme getColorScheme() { return colorScheme; } public void setColorScheme(IColorScheme colorScheme) { this.colorScheme = colorScheme; } private boolean isShowColors() { return showColors; } public void setShowColors(boolean showColors) { this.showColors = showColors; } /** * paint * */ public void paint(Graphics g) { super.paint(g); paintReference(g); paintSelection(g); } /** * Paints the axis of the alignment * * @param g0 the graphics context of the sequence panel */ private void paintReference(Graphics g0) { Graphics2D g = (Graphics2D) g0; Rectangle rec = getVisibleRect(); g.setColor(Color.WHITE);//new Color(0.93f, 0.97f, 0.96f)); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.BLACK); g.setBackground(Color.WHITE); g.setFont(sequenceFont); // g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); final Lane referenceSequence = alignment.getReference(); if (alignment.getReference() != null) { final GapColumnContractor gapColumnContractor = getAlignment().getGapColumnContractor(); int minVisibleCol = (int) Math.max(0, (rec.getX() / cellWidth)) + gapColumnContractor.getFirstOriginalColumn(); int maxVisibleCol = (int) Math.min(gapColumnContractor.getLastOriginalColumn() - 1, (rec.getX() + rec.getWidth()) / cellWidth); if (minVisibleCol - 3 > 0) minVisibleCol -= 3; // just to cover previous codon if ((!alignment.getReferenceType().equals(Alignment.PROTEIN) && cellWidth < 1) || cellWidth < 0.5) { final Lane lane = alignment.getReference(); int firstLayoutCol = lane.getFirstNonGapPosition(); Integer[] jumpCols = gapColumnContractor.getJumpPositionsRelativeToOriginalColumns().toArray(new Integer[0]); if (jumpCols.length > 0) { int jc = 0; int jumped = 0; while (jc < jumpCols.length && jumpCols[jc] <= firstLayoutCol) { jumped += gapColumnContractor.getJumpBeforeOriginalColumn(jumpCols[jc]); jc++; } firstLayoutCol -= jumped; } int lastLayoutCol = lane.getLastNonGapPosition(); if (jumpCols.length > 0) { int jc = 0; int jumped = 0; while (jc < jumpCols.length && jumpCols[jc] < lastLayoutCol) { jumped += gapColumnContractor.getJumpBeforeOriginalColumn(jumpCols[jc]); jc++; } lastLayoutCol -= jumped; } double firstX = getX(firstLayoutCol); double lastX = getX(lastLayoutCol); if (firstX <= maxVisibleCol && lastX >= minVisibleCol) { g.setColor(Color.GRAY); g.fill(new Rectangle2D.Double(firstX, 0, lastX - firstX, getHeight())); } } else { final Rectangle2D drawRect = new Rectangle2D.Float(); if (isShowColors() && getColorScheme() != null) { // color scheme selected? g.setColor(Color.WHITE); Integer[] jumpCols = gapColumnContractor.getJumpPositionsRelativeToLayoutColumns().toArray(new Integer[0]); int jc = 0; int jumped = 0; int colorStreak = 0; for (int layoutCol = minVisibleCol; layoutCol <= maxVisibleCol; layoutCol++) { while (jc < jumpCols.length && jumpCols[jc] <= layoutCol) { jumped += gapColumnContractor.getJumpBeforeLayoutColumn(jumpCols[jc]); jc++; } int trueCol = layoutCol + jumped; char ch = referenceSequence.charAt(trueCol); // draw colors if (ch != ' ') // if space, keep previous color { g.setColor(getColorScheme().getBackground(ch)); colorStreak = 0; } else { // only repeat the same color 3 times (for a codon...) colorStreak++; if (colorStreak == 3) { g.setColor(Color.WHITE); colorStreak = 0; } } if (!g.getColor().equals(Color.WHITE)) { drawRect.setRect(getX(layoutCol) - 1, 0, cellWidth, getSize().height); g.fill(drawRect); } } g.setColor(Color.BLACK); } } if (cellWidth > 4) { Integer[] jumpCols = gapColumnContractor.getJumpPositionsRelativeToLayoutColumns().toArray(new Integer[0]); int jc = 0; int jumped = 0; for (int layoutCol = minVisibleCol; layoutCol <= maxVisibleCol; layoutCol++) { while (jc < jumpCols.length && jumpCols[jc] <= layoutCol) { jumped += gapColumnContractor.getJumpBeforeLayoutColumn(jumpCols[jc]); jc++; } int trueCol = layoutCol + jumped; if (trueCol < gapColumnContractor.getLastOriginalColumn()) { char ch = referenceSequence.charAt(trueCol); // draw colors if (isShowColors() && getColorScheme() != null) { // color scheme selected? g.setColor(Color.BLACK); } g.drawString("" + ch, Math.round(getX(layoutCol)), (int) Math.round(getSize().height - 0.5 * (getSize().height - cellHeight)) - 2); } } } if (cellWidth > 1) { SortedSet<Integer> jumpColumns = gapColumnContractor.getJumpPositionsRelativeToLayoutColumns(); for (Integer col : jumpColumns) { g.setColor(Color.WHITE); g.drawLine((int) getX(col), -1, (int) getX(col), getSize().height); g.setColor(Color.GRAY); g.drawLine((int) getX(col) - 1, -1, (int) getX(col) - 1, getSize().height); g.drawLine((int) getX(col) + 1, -1, (int) getX(col) + 1, getSize().height); } } } } /** * paint the selection rectangle * */ private void paintSelection(Graphics g0) { Graphics2D g = (Graphics2D) g0; SelectedBlock selectedBlock = getSelectedBlock(); if (selectedBlock.isSelected()) { Rectangle2D rect = new Rectangle2D.Double(Math.max(0, getX(selectedBlock.getFirstCol())), 0, 0, 0); rect.add(Math.min(getX(selectedBlock.getLastCol() + 1), getSize().getWidth()), getSize().height); g.setColor(highlightColorSemiTransparent); g.fill(rect); g.setColor(highlightColor); g.draw(rect); } } /** * Adapts the grid parameters to the current sequenceFont. It is invoked every time the sequenceFont changes. */ void revalidateGrid() { if (alignment != null) { setSize((int) (cellWidth * (alignment.getGapColumnContractor().getLayoutLength()) + 0.5) + 3, (int) Math.max(20, cellHeight)); } setPreferredSize(getSize()); revalidate(); } class MyMouseListener extends MouseAdapter implements MouseListener, MouseMotionListener { private final int inMove = 2; private final int inRubberband = 3; private final int inScrollByMouse = 4; private boolean stillDownWithoutMoving = false; Point mouseDown = null; private int current = 0; @Override public void mouseClicked(MouseEvent me) { super.mouseClicked(me); int inClick = 1; current = inClick; if (me.getClickCount() == 1) { if (me.isShiftDown()) { if (selectedBlock.isSelected()) { if (!selectedBlock.isSelectedCol(getCol(me.getPoint()))) selectedBlock.extendSelection(-1, getCol(me.getPoint())); else selectedBlock.reduceSelection(-1, getCol(me.getPoint())); } } else { selectedBlock.clear(); } } else if (me.getClickCount() == 2) { selectedBlock.selectCol(getCol(me.getPoint()), alignment.isTranslate()); } } @Override public void mousePressed(MouseEvent me) { super.mousePressed(me); mouseDown = me.getPoint(); boolean shiftDown = me.isShiftDown(); if (me.isAltDown() || me.isShiftDown()) { current = inRubberband; setCursor(Cursor.getDefaultCursor()); } else { current = inScrollByMouse; setCursor(Cursors.getClosedHand()); stillDownWithoutMoving = true; final Thread worker = new Thread(new Runnable() { public void run() { try { synchronized (this) { wait(500); } } catch (InterruptedException ignored) { } if (stillDownWithoutMoving) { current = inRubberband; setCursor(Cursor.getDefaultCursor()); } } }); worker.setPriority(Thread.currentThread().getPriority() - 1); worker.start(); } } @Override public void mouseMoved(MouseEvent me) { super.mouseMoved(me); stillDownWithoutMoving = false; //setToolTipText(); } @Override public void mouseDragged(MouseEvent me) { super.mouseDragged(me); stillDownWithoutMoving = false; if (current == inRubberband) { ReferencePanel viewer = ReferencePanel.this; Graphics2D gc = (Graphics2D) getGraphics(); if (gc != null) { Color color = viewer.getBackground() != null ? viewer.getBackground() : Color.WHITE; gc.setXORMode(color); int firstRow = 0; int firstCol = Math.min(getCol(mouseDown), getCol(me.getPoint())); int lastRow = Integer.MAX_VALUE; int lastCol = Math.max(getCol(mouseDown), getCol(me.getPoint())); getSelectedBlock().select(firstRow, firstCol, lastRow, lastCol, alignment.isTranslate()); paintSelection(gc); } } else if (current == inScrollByMouse) { if (ReferencePanel.this.getParent() != null && ReferencePanel.this.getParent().getParent() != null && ReferencePanel.this.getParent().getParent() instanceof JScrollPane) { JScrollPane scrollPane = (JScrollPane) ReferencePanel.this.getParent().getParent(); int dX = me.getX() - mouseDown.x; int dY = me.getY() - mouseDown.y; if (dY != 0) { JScrollBar scrollBar = scrollPane.getVerticalScrollBar(); int amount = Math.round(dY * (scrollBar.getMaximum() - scrollBar.getMinimum()) / getHeight()); if (amount != 0) { scrollBar.setValue(scrollBar.getValue() - amount); } } if (dX != 0) { JScrollBar scrollBar = scrollPane.getHorizontalScrollBar(); int amount = Math.round(dX * (scrollBar.getMaximum() - scrollBar.getMinimum()) / getWidth()); if (amount != 0) { scrollBar.setValue(scrollBar.getValue() - amount); } } } } } @Override public void mouseReleased(MouseEvent me) { super.mouseReleased(me); stillDownWithoutMoving = false; if (current == inRubberband) { if (!me.getPoint().equals(mouseDown)) { int firstCol = Math.min(getCol(mouseDown), getCol(me.getPoint())); int lastCol = Math.max(getCol(mouseDown), getCol(me.getPoint())); getSelectedBlock().selectCols(firstCol, lastCol, alignment.isTranslate()); } } //AlignmentPanel.this.repaint(); setCursor(Cursor.getDefaultCursor()); current = 0; } } }
15,571
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Alignment.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/Alignment.java
/* * Alignment.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui; import jloda.swing.util.ProgramProperties; import jloda.util.Pair; import jloda.util.StringUtils; import jloda.util.progress.ProgressPercentage; import java.io.StringWriter; import java.util.*; /** * describes an alignment * Daniel Huson, 9.2011 */ public class Alignment { private String name = "Untitled"; private int length = -1; private final Vector<Lane> lanes; private final ArrayList<Integer> order; // lists sequences in their sorted order private final GapColumnContractor gapColumnContractor; private final RowCompressor rowCompressor; private boolean translate = false; private String referenceName; private Lane reference; private Lane originalReference; private String referenceType = UNKNOWN; private Lane untranslatedConsensus; private Lane translatedConsensus; private static final String UNKNOWN = "Unknown"; static public final String DNA = "DNA"; static public final String cDNA = "codingDNA"; static public final String PROTEIN = "PROTEIN"; private String sequenceType = UNKNOWN; private final Set<Integer> insertionsIntoReference = new HashSet<>(); /** * constructor */ public Alignment() { lanes = new Vector<>(); order = new ArrayList<>(); // lists sequences in their sorted order gapColumnContractor = new GapColumnContractor(); rowCompressor = new RowCompressor(this); } public void clear() { length = -1; lanes.clear(); gapColumnContractor.clear(); rowCompressor.clear(); order.clear(); insertionsIntoReference.clear(); untranslatedConsensus = null; translatedConsensus = null; reference = null; originalReference = null; } public int getLength() { if (length == -1) { for (int i = 0; i < getNumberOfSequences(); i++) { length = Math.max(length, getLaneLength(i)); } } return length + ProgramProperties.get("alignmentViewerAdditionalPositions", 0); } public void setLength(int length) { this.length = length; } public String getSequenceType() { return sequenceType; } public void setSequenceType(String sequenceType) { this.sequenceType = sequenceType; } public int getNumberOfSequences() { return lanes.size(); } public String getName(int row) { return getLane(row).getName(); } public Lane getLane(int row0) { int row = getOrder(row0); if (row < lanes.size()) return lanes.get(row); else return null; } private int getLaneLength(int row0) { Lane lane = getLane(row0); try { return lane.getLength(); } catch (Exception e) { return 0; } } public Lane getReference() { return reference; } public String getReferenceName() { return referenceName; } public Lane getConsensus() { if (isTranslate()) { if (translatedConsensus == null || (translatedConsensus.toString().length() == 0 && getLength() > 0)) translatedConsensus = new Lane(null, "Consensus", "", "Consensus sequence", computeConsensus()); return translatedConsensus; } else { if (untranslatedConsensus == null || (untranslatedConsensus.toString().length() == 0 && getLength() > 0)) untranslatedConsensus = new Lane(null, "Consensus", "", "Consensus sequence", computeConsensus()); return untranslatedConsensus; } } public void setReferenceName(String name) { referenceName = name; } public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } public void setReference(String name, String reference) { referenceName = name; this.reference = new Lane(null, name, "", null, reference); // System.err.println("Reference length: " + reference.length()); } public Lane getOriginalReference() { return originalReference; } public void setOriginalReference(String originalReference) { this.originalReference = new Lane(null, name, "", null, originalReference); } /** * adds a sequence to the alignment * * @param unalignedPrefix unaligned prefix of sequence * @param leadingGaps number of gaps before alignment starts * @param block core of alignment * @param trailingGaps number of trailing gaps * @param unalignedSuffix unaligned suffix of sequence */ public void addSequence(String name, String text, String toolTip, String unalignedPrefix, int leadingGaps, String block, int trailingGaps, String unalignedSuffix) { lanes.add(new Lane(this, name, text, toolTip, unalignedPrefix, leadingGaps, block, trailingGaps, unalignedSuffix)); } /** * get string representation of block in alignment * * @param maxLayoutCol @return string */ public String toFastA(boolean includeUnalignedChars, int minRow, int minLayoutCol, int maxRow, int maxLayoutCol) { StringWriter w = new StringWriter(); if (!getRowCompressor().isEnabled()) { final Integer[] jumpCols = gapColumnContractor.getJumpPositionsRelativeToLayoutColumns().toArray(new Integer[0]); maxRow = Math.min(maxRow, getNumberOfSequences() - 1); for (int read = minRow; read <= maxRow; read++) { String readName = getName(read); if (readName.startsWith(">")) w.write(readName + "\n"); else w.write(">" + readName + "\n"); Lane lane = getLane(read); int jc = 0; int jumped = 0; for (int layoutCol = minLayoutCol; layoutCol <= maxLayoutCol; layoutCol++) { while (jc < jumpCols.length && jumpCols[jc] <= layoutCol) { jumped += gapColumnContractor.getJumpBeforeLayoutColumn(jumpCols[jc]); jc++; } int trueCol = layoutCol + jumped; if (trueCol < getLength()) { if (includeUnalignedChars && lane.hasUnalignedCharAt(trueCol)) { char ch = lane.getUnalignedCharAt(trueCol); w.write(ch); } else { if (trueCol >= lane.getFirstNonGapPosition() && trueCol <= lane.getLastNonGapPosition()) { char ch = lane.charAt(trueCol); if (ch == 0) ch = '-'; if (ch != ' ') w.write(ch); } else { if (!isTranslate() || (trueCol % 3) == 0) w.write('-'); } } } } w.write("\n"); } } else { maxRow = Math.min(maxRow, getRowCompressor().getNumberRows() - 1); final Integer[] jumpCols = gapColumnContractor.getJumpPositionsRelativeToLayoutColumns().toArray(new Integer[0]); int minTrueCol = gapColumnContractor.getTotalJumpBeforeLayoutColumn(minLayoutCol) + minLayoutCol; int maxTrueCol = gapColumnContractor.getTotalJumpBeforeLayoutColumn(maxLayoutCol - 1) + maxLayoutCol; for (int row = minRow; row <= maxRow; row++) { //w.write(">row" + (row + 1) + "\n"); int lastPos = minTrueCol - 1; for (int read : rowCompressor.getCompressedRow2Reads(row)) { int jc = 0; int jumped = 0; Lane lane = getLane(read); if (minTrueCol <= lane.getLastNonGapPosition() && maxTrueCol >= lane.getFirstNonGapPosition()) { // read intersects visible cols int startTrueCol = Math.max(minTrueCol, lane.getFirstNonGapPosition()); int endTrueCol = Math.min(maxTrueCol, lane.getLastNonGapPosition()); while (lastPos < startTrueCol - (isTranslate() ? 1 : 1)) { // todo: what is going on here? if (!translate || (lastPos % 3) == 0) w.write("-"); lastPos++; } for (int layoutCol = minLayoutCol; layoutCol <= maxLayoutCol; layoutCol++) { while (jc < jumpCols.length && jumpCols[jc] <= layoutCol) { jumped += gapColumnContractor.getJumpBeforeLayoutColumn(jumpCols[jc]); jc++; } int trueCol = layoutCol + jumped; if (trueCol >= startTrueCol && trueCol <= endTrueCol) { if (includeUnalignedChars && lane.hasUnalignedCharAt(trueCol)) { char ch = lane.getUnalignedCharAt(trueCol); w.write(ch); } else if (!isTranslate() || trueCol < lane.getLastNonGapPosition() - 2) { char ch = lane.charAt(trueCol); if (ch == 0) ch = '-'; if (ch != ' ') w.write(ch); } lastPos++; } } } } while (lastPos < maxTrueCol) { if (!translate || (lastPos % 3) == 0) w.write("-"); lastPos++; } w.write("\n"); } } return w.toString(); } /** * return a fastA representation in string * */ public String toFastA() { return toFastA(false, 0, 0, getNumberOfSequences() - 1, getLength()); } /** * get the position of the row in the row ordering * * @return ordered position */ public int getOrder(int row) { if (order.size() > row && order.get(row) != null) return order.get(row); else return row; } /** * gets the max length of any name * * @return max name length */ public int getMaxNameLength() { int result = 0; for (int i = 0; i < getNumberOfSequences(); i++) result = Math.max(result, getName(i).length()); return result; } public void resetOrder() { order.clear(); for (int i = 0; i < lanes.size(); i++) order.add(i); } public void setOrder(List<Integer> order) { if (order.size() < this.order.size()) { this.order.removeAll(order); final List<Integer> oldOrder = new LinkedList<>(this.order); this.order.clear(); this.order.addAll(order); this.order.addAll(oldOrder); } else { this.order.clear(); this.order.addAll(order); } } public String getToolTip(int read) { if (read >= 0 && read < lanes.size()) return lanes.get(getOrder(read)).getToolTip(); else return null; } public String getText(int read) { if (read >= 0 && read < lanes.size()) return lanes.get(getOrder(read)).getText(); else return ""; } public GapColumnContractor getGapColumnContractor() { return gapColumnContractor; } public RowCompressor getRowCompressor() { return rowCompressor; } /** * computes the consensus for the complete sequences * * @return consensus */ public String computeConsensus() { System.err.println("Computing consensus:"); // list of read start and end events final List<Pair<Integer, Integer>> list = new LinkedList<>(); for (int row = 0; row < getNumberOfSequences(); row++) { final Lane lane = getLane(row); Pair<Integer, Integer> pair = new Pair<>(lane.getFirstNonGapPosition(), row); list.add(pair); pair = new Pair<>(lane.getLastNonGapPosition() + 1, row); list.add(pair); } final Pair<Integer, Integer>[] array = (Pair<Integer, Integer>[]) list.toArray(new Pair[0]); // pair position,row Arrays.sort(array); ProgressPercentage progress = new ProgressPercentage(); progress.setCancelable(false); progress.setMaximum(array.length + 2); StringBuilder buf = new StringBuilder(); // consensus will be put here // prefix of gaps: final int firstPos = array.length > 0 ? array[0].getFirst() : getLength(); buf.append("-".repeat(Math.max(0, firstPos))); progress.incrementProgress(); final Set<Integer> activeRows = new HashSet<>(); for (int i = 0; i < array.length; i++) { // consider each event in turn progress.incrementProgress(); int pos = array[i].getFirst(); while (true) { int row = array[i].getSecond(); if (activeRows.contains(row)) // if is active, must remove activeRows.remove(row); else activeRows.add(row); // not yet active, add if (i + 1 < array.length && array[i + 1].getFirst() == pos) { i++; progress.incrementProgress(); } else break; } final int nextPos = (i + 1 < array.length ? array[i + 1].getFirst() : getLength()); boolean debug = false; if (debug) System.err.println("Active rows: " + StringUtils.toString(activeRows, ",")); if (activeRows.size() > 0) { for (int col = pos; col < nextPos; col++) { if (debug) System.err.println("col: " + col); Map<Character, Integer> char2count = new HashMap<>(); for (final int row : activeRows) { final Lane lane = getLane(row); char ch = lane.charAt(col); if (debug) System.err.println("row: " + row + " ch=" + ch); if (debug) System.err.println("row: " + lane.getFirstNonGapPosition() + " - " + lane.getLastNonGapPosition()); if (Character.isLetter(ch) || ch == ' ') { char2count.merge(ch, 1, Integer::sum); } } Character best = null; int bestCount = 0; for (Character ch : char2count.keySet()) { if (char2count.get(ch) > bestCount) { best = ch; bestCount = char2count.get(ch); } } if (best != null) { if (bestCount >= char2count.keySet().size() / 2) best = Character.toUpperCase(best); else best = Character.toLowerCase(best); buf.append(best); } else buf.append('-'); } } else { buf.append("-".repeat(Math.max(0, nextPos - pos))); } } // suffix of gaps: // prefix of gaps: int lastPos = array.length > 0 ? array[array.length - 1].getFirst() : getLength(); // todo: FIXME buf.append("-".repeat(lastPos - lastPos)); progress.incrementProgress(); progress.close(); return buf.toString(); } /** * get string representation of segment of consensus * * @return string */ public String getConsensusString(int minLayoutCol, int maxLayoutCol) { StringWriter w = new StringWriter(); final Integer[] jumpCols = gapColumnContractor.getJumpPositionsRelativeToLayoutColumns().toArray(new Integer[0]); final Lane lane = getConsensus(); int jc = 0; int jumped = 0; for (int layoutCol = minLayoutCol; layoutCol <= maxLayoutCol; layoutCol++) { while (jc < jumpCols.length && jumpCols[jc] <= layoutCol) { jumped += gapColumnContractor.getJumpBeforeLayoutColumn(jumpCols[jc]); jc++; } int trueCol = layoutCol + jumped; if (trueCol < getLength()) { if (trueCol >= lane.getFirstNonGapPosition() && trueCol <= lane.getLastNonGapPosition()) { char ch = lane.charAt(trueCol); if (ch == 0) ch = '-'; if (ch != ' ') w.write(ch); } else { if (!isTranslate() || (trueCol % 3) == 0) w.write('-'); } } } return w.toString(); } /** * get string representation of segment of reference * * @return string */ public String getReferenceString(int minLayoutCol, int maxLayoutCol) { StringWriter w = new StringWriter(); final Integer[] jumpCols = gapColumnContractor.getJumpPositionsRelativeToLayoutColumns().toArray(new Integer[0]); Lane lane = getReference(); int jc = 0; int jumped = 0; for (int layoutCol = minLayoutCol; layoutCol <= maxLayoutCol; layoutCol++) { while (jc < jumpCols.length && jumpCols[jc] <= layoutCol) { jumped += gapColumnContractor.getJumpBeforeLayoutColumn(jumpCols[jc]); jc++; } int trueCol = layoutCol + jumped; if (trueCol < getLength()) { if (trueCol >= lane.getFirstNonGapPosition() && trueCol <= lane.getLastNonGapPosition()) { char ch = lane.charAt(trueCol); if (ch == 0) ch = '-'; if (ch != ' ') w.write(ch); } else { if (!isTranslate() || (trueCol % 3) == 0) w.write('-'); } } } return w.toString(); } /** * gets all positions of alignment that are insertions into the reference * * @return all positions of insertions into the reference */ public Set<Integer> getInsertionsIntoReference() { return insertionsIntoReference; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isTranslate() { return translate; } public void setTranslate(boolean translate) { this.translate = translate; } /** * get the read that is displayed at the given row and column * * @return read or -1 */ public int getHitRead(int row, int col) { col += getGapColumnContractor().getTotalJumpBeforeLayoutColumn(col); return getRowCompressor().getRead(row, col); } public void trimToTrueLength(int trueLength) { for (Lane lane : lanes) { lane.trimFromEnd(trueLength); } } }
20,872
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
AlignmentPanel.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/AlignmentPanel.java
/* * AlignmentPanel.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui; import jloda.swing.director.ProjectManager; import jloda.swing.util.Cursors; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ToolTipHelper; import jloda.util.StringUtils; import megan.alignment.gui.colors.ColorSchemeText; import megan.alignment.gui.colors.IColorScheme; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.util.Objects; import java.util.SortedSet; /** * a sequence alignment panel * Daniel Huson, 9.2011 */ public class AlignmentPanel extends BasePanel { private Alignment alignment = new Alignment(); private IColorScheme colorScheme = new ColorSchemeText(); private boolean showColors = true; private boolean showUnalignedChars = false; private final AnimatedRectangle selectionRectangle; private final ToolTipHelper toolTipHelper; private boolean colorMatchesVsReference = false; private boolean colorMismatchesVsReference = true; private boolean colorMatchesVsConsensus = false; private boolean colorMismatchesVsConsensus = false; // used in drawing: private final Rectangle2D drawRect = new Rectangle2D.Double(); private final Line2D drawLine = new Line2D.Double(); /** * constructor */ public AlignmentPanel(final SelectedBlock selectedBlock) { super(selectedBlock); selectedBlock.addSelectionListener((selected, minRow, minCol, maxRow, maxCol) -> repaint()); toolTipHelper = new ToolTipHelper(this) { public String computeToolTip(Point mousePosition) { int read = alignment.getHitRead(getRow(mousePosition), getCol(mousePosition)); if (read != -1) return alignment.getToolTip(read); else return ""; } }; MyMouseListener listener = new MyMouseListener(); addMouseListener(listener); addMouseMotionListener(listener); selectionRectangle = new AnimatedRectangle(this); revalidate(); setDoubleBuffered(true); colorMatchesVsReference = ProgramProperties.get("ColorMatchesVsReference", colorMatchesVsReference); colorMismatchesVsReference = ProgramProperties.get("ColorMismatchesVsReference", colorMismatchesVsReference); colorMatchesVsConsensus = ProgramProperties.get("ColorMatchesVsConsensus", colorMatchesVsConsensus); colorMismatchesVsConsensus = ProgramProperties.get("ColorMismatchesVsConsensus", colorMismatchesVsConsensus); } /** * call this when window is destroyed to release tooltip thread */ public void close() { } public Alignment getAlignment() { return alignment; } public void setAlignment(Alignment alignment) { this.alignment = alignment; JScrollPane scrollPane = getScrollPane(); if (scrollPane != null) { scrollPane.getHorizontalScrollBar().setMinimum(0); scrollPane.getHorizontalScrollBar().setMaximum(alignment.getLength()); scrollPane.getVerticalScrollBar().setMinimum(0); scrollPane.getVerticalScrollBar().setMaximum(alignment.getRowCompressor().getNumberRows()); } revalidateGrid(); } public void setAnimateSelection(boolean animate) { selectionRectangle.setAnimate(animate); } /** * paint * */ public void paint(Graphics g) { try { super.paint(g); paintSequences(g); paintSelection(g); } catch (Exception ignored) { } } /** * Paints the sequences in the alignment * * @param g0 the graphics context of the sequence panel */ private void paintSequences(Graphics g0) { Graphics2D g = (Graphics2D) g0; Rectangle visibleRect = getVisibleRect(); // add preceeding column so that we see their letters, even when only partially if (visibleRect.getX() - cellWidth >= 0) visibleRect.setRect(visibleRect.getX() - cellWidth, visibleRect.getY(), visibleRect.getWidth() + cellWidth, visibleRect.getHeight()); g.setColor(Color.WHITE); //g.setColor(new Color(0.93f, 0.97f, 0.96f)); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.BLACK); g.setBackground(Color.WHITE); g.setFont(sequenceFont); //g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); final Lane referenceSequence = alignment.getReference(); final Lane consensusSequence = alignment.getConsensus(); if (alignment != null) { final GapColumnContractor gapColumnContractor = getAlignment().getGapColumnContractor(); final RowCompressor rowCompressor = getAlignment().getRowCompressor(); boolean showGaps = (!rowCompressor.isEnabled()); int minVisibleRow = (int) Math.max(0, (visibleRect.getY() / cellHeight) - 1); int maxVisibleRow = (int) Math.min(rowCompressor.getNumberRows() - 1, (visibleRect.getY() + visibleRect.getHeight()) / cellHeight); int minVisibleCol = (int) Math.max(0, (visibleRect.getX() / cellWidth)) + gapColumnContractor.getFirstOriginalColumn(); int maxVisibleCol = (int) Math.min(gapColumnContractor.getLastOriginalColumn() - 1, (visibleRect.getX() + visibleRect.getWidth()) / cellWidth); if (minVisibleCol - 3 > 0) minVisibleCol -= 3; // just to cover previous codon if ((!alignment.isTranslate() && cellWidth < 1) || cellWidth < 0.5) { // very small, draw gray bars minVisibleCol = 0; g.setColor(Color.GRAY); Integer[] jumpCols = gapColumnContractor.getJumpPositionsRelativeToOriginalColumns().toArray(new Integer[0]); for (int row = minVisibleRow; row <= maxVisibleRow; row++) { for (int read : rowCompressor.getCompressedRow2Reads(row)) { Lane lane = alignment.getLane(read); if (lane != null) { int firstLayoutCol = lane.getFirstNonGapPosition(); if (jumpCols.length > 0) { int jc = 0; int jumped = 0; while (jc < jumpCols.length && jumpCols[jc] <= firstLayoutCol) { jumped += gapColumnContractor.getJumpBeforeOriginalColumn(jumpCols[jc]); jc++; } firstLayoutCol -= jumped; } int lastLayoutCol = lane.getLastNonGapPosition(); if (jumpCols.length > 0) { int jc = 0; int jumped = 0; while (jc < jumpCols.length && jumpCols[jc] < lastLayoutCol) { jumped += gapColumnContractor.getJumpBeforeOriginalColumn(jumpCols[jc]); jc++; } lastLayoutCol -= jumped; } double firstX = getX(firstLayoutCol); double lastX = getX(lastLayoutCol); if (firstLayoutCol <= maxVisibleCol && lastLayoutCol >= minVisibleCol) { drawRect.setRect(firstX - 1, getY(row) - cellHeight, Math.max(2, lastX - firstX), Math.max(1, cellHeight - 1)); g.fill(drawRect); } } } } g.setColor(Color.BLACK); } else { // not very small, draw colored blocks if (showColors && colorScheme != null) { // color scheme selected? boolean notTiny = (cellHeight > 6); final int inset = notTiny ? 1 : 0; Integer[] jumpCols = gapColumnContractor.getJumpPositionsRelativeToLayoutColumns().toArray(new Integer[0]); g.setColor(Color.WHITE); for (int row = minVisibleRow; row <= maxVisibleRow; row++) { for (int read : rowCompressor.getCompressedRow2Reads(row)) { int jc = 0; int jumped = 0; Lane lane = alignment.getLane(read); for (int layoutCol = minVisibleCol; layoutCol <= maxVisibleCol; layoutCol++) { while (jc < jumpCols.length && jumpCols[jc] <= layoutCol) { jumped += gapColumnContractor.getJumpBeforeLayoutColumn(jumpCols[jc]); jc++; } int trueCol = layoutCol + jumped; if (trueCol < alignment.getLength()) { double x = getX(layoutCol) - 1; double y = getY(row); if (notTiny && lane != null && trueCol == lane.getFirstNonGapPosition()) { g.setColor(Color.LIGHT_GRAY); drawLine.setLine(x - 2, y - cellHeight + inset, x - 2, y - inset); g.draw(drawLine); } char ch = Objects.requireNonNull(lane).charAt(trueCol); if (ch != 0) { if (ch != ' ') { if ((colorMatchesVsReference && ch == referenceSequence.charAt(trueCol)) || (colorMismatchesVsReference && ch != referenceSequence.charAt(trueCol)) || (colorMatchesVsConsensus && ch == consensusSequence.charAt(trueCol)) || (colorMismatchesVsConsensus && ch != consensusSequence.charAt(trueCol))) g.setColor(getColorScheme().getBackground(ch)); else g.setColor(Color.LIGHT_GRAY); } drawRect.setRect(x, y - cellHeight + inset, cellWidth, cellHeight - inset); g.fill(drawRect); } if (notTiny && trueCol == lane.getLastNonGapPosition() - 1) // todo: does this mean that we skip the last column? { g.setColor(Color.LIGHT_GRAY); drawLine.setLine(x + cellWidth + 1, y - cellHeight + inset, x + cellWidth + 1, y - inset); g.draw(drawLine); } } } } } } } if (sequenceFont.getSize() > 6) { // font is big enough, draw text g.setColor(Color.BLACK); Integer[] jumpCols = gapColumnContractor.getJumpPositionsRelativeToLayoutColumns().toArray(new Integer[0]); for (int row = minVisibleRow; row <= maxVisibleRow; row++) { for (int read : rowCompressor.getCompressedRow2Reads(row)) { int jc = 0; int jumped = 0; Lane lane = alignment.getLane(read); for (int layoutCol = minVisibleCol; layoutCol <= maxVisibleCol; layoutCol++) { while (jc < jumpCols.length && jumpCols[jc] <= layoutCol) { jumped += gapColumnContractor.getJumpBeforeLayoutColumn(jumpCols[jc]); jc++; } int trueCol = layoutCol + jumped; if (trueCol < alignment.getLength()) { double xCoord = getX(layoutCol); double yCoord = getY(row) - 0.5 * cellHeight + 0.3 * getSequenceFont().getSize(); if (visibleRect.contains(xCoord, yCoord)) { if (isShowUnalignedChars() && lane.hasUnalignedCharAt(trueCol)) { char ch = lane.getUnalignedCharAt(trueCol); if (ch != '-') { g.setColor(Color.GRAY); g.drawString("" + ch, Math.round(xCoord), Math.round(yCoord)); } } else { char ch = lane.charAt(trueCol); if (ch == 0) { if (!showGaps) { continue; } else ch = '-'; } if (ch == ' ') { continue; } // draw colors if (showColors && colorScheme != null) { // color scheme selected? g.setColor(Color.BLACK); } g.drawString("" + ch, Math.round(xCoord), Math.round(yCoord)); } } } } } } // System.err.println("Rows painted: "+(maxVisibleRow-minVisibleRow+1)); // System.err.println("Cols painted: "+(maxVisibleCol-minVisibleCol+1)); } SortedSet<Integer> jumpColumns = gapColumnContractor.getJumpPositionsRelativeToLayoutColumns(); for (Integer col : jumpColumns) { if (cellWidth > 1) { g.setColor(Color.WHITE); g.drawLine((int) getX(col), -1, (int) getX(col), getSize().height); g.setColor(Color.GRAY); g.drawLine((int) getX(col) - 1, -1, (int) getX(col) - 1, getSize().height); g.drawLine((int) getX(col) + 1, -1, (int) getX(col) + 1, getSize().height); } else { g.setColor(Color.LIGHT_GRAY); g.drawLine((int) getX(col), -1, (int) getX(col), getSize().height); } } } } /** * paint the selection rectangle * */ private void paintSelection(Graphics g0) { if (selectedBlock.isSelected()) { Graphics2D g = (Graphics2D) g0; double xMin = Math.min(getX(selectedBlock.getFirstCol()), getSize().width); double xMax = Math.min((getX(selectedBlock.getLastCol() + 1)), getSize().width - 2); double yMin = Math.min(getY(selectedBlock.getFirstRow() - 1), getSize().height - 3); double yMax = Math.min(getY(selectedBlock.getLastRow()), getSize().height - 3); Rectangle2D rect = new Rectangle2D.Double(xMin, yMin, 0, 0); rect.add(xMax, yMax); g.setColor(highlightColor); g.draw(rect); g.setColor(highlightColorSemiTransparent); g.fill(rect); selectionRectangle.setRectangle(this, rect); } selectionRectangle.setAnimate(selectedBlock.isSelected()); } /** * Adapts the grid parameters to the current sequenceFont. It is invoked every time the sequenceFont changes. */ void revalidateGrid() { setSize((int) (cellWidth * alignment.getGapColumnContractor().getLayoutLength() + 0.5) + 3, (int) (cellHeight * alignment.getRowCompressor().getNumberRows() + 0.5) + 3); setPreferredSize(getSize()); JScrollPane scrollPane = getScrollPane(); revalidate(); scrollPane.getHorizontalScrollBar().setMaximum((int) (Math.round(getPreferredSize().getWidth()))); scrollPane.getVerticalScrollBar().setMaximum((int) (Math.round(getPreferredSize().getHeight()))); selectedBlock.fireSelectionChanged(); } public void setScale(double hScale, double vScale) { super.setScale(hScale, vScale); if (selectedBlock.isSelected()) { double xMin = Math.min(getX(selectedBlock.getFirstCol()), getSize().width); double xMax = Math.min((getX(selectedBlock.getLastCol())), getSize().width); double yMin = Math.min(getY(selectedBlock.getFirstRow() - 1), getSize().height - 3); double yMax = Math.min(getY(selectedBlock.getLastRow()), getSize().height - 3); Rectangle2D rect = new Rectangle2D.Double(xMin, yMin, 0, 0); rect.add(xMax, yMax); selectionRectangle.setRectangle(this, rect); selectionRectangle.setAnimate(selectedBlock.isSelected()); } } private IColorScheme getColorScheme() { return colorScheme; } public void setColorScheme(IColorScheme colorScheme) { this.colorScheme = colorScheme; } public boolean isShowColors() { return showColors; } public void setShowColors(boolean showColors) { this.showColors = showColors; } public boolean isShowUnalignedChars() { return showUnalignedChars; } public void setShowUnalignedChars(boolean showUnalignedChars) { this.showUnalignedChars = showUnalignedChars; } /** * gets the zoom factor required for the alignment to fit horizontally into the window * * @return horizontal zoom to fit factor */ public float getHZoomToFitFactor() { Rectangle rec = getScrollPane().getViewport().getViewRect(); Rectangle bounds = getBounds(); return (float) (rec.getWidth() / bounds.getWidth()); } /** * gets the zoom factor required for the selected block to fit horizontally into the window * * @return horizontal zoom to fit factor */ public float getHZoomToSelectionFactor() { if (selectedBlock.isSelected()) { Rectangle viewRect = getScrollPane().getViewport().getViewRect(); return (float) (viewRect.getWidth() / (cellWidth * (selectedBlock.getLastCol() - selectedBlock.getFirstCol() + 1))); } else return 1; } /** * gets the zoom factor required for the alignment to fit vertically into the window * * @return vertical zoom to fit factor */ public float getVZoomToFitFactor() { Rectangle rec = getScrollPane().getViewport().getViewRect(); Rectangle bounds = getBounds(); return (float) (rec.getHeight() / bounds.getHeight()); } /** * gets the zoom factor required for the selected block to fit vertically into the window * * @return vertical zoom to fit factor */ public float getVZoomToSelectionFactor() { if (selectedBlock.isSelected()) { Rectangle viewRect = getScrollPane().getViewport().getViewRect(); return (float) (viewRect.getHeight() / (cellHeight * (selectedBlock.getLastRow() - selectedBlock.getFirstRow() + 1))); } else return 1; } public JScrollPane getScrollPane() { return (JScrollPane) AlignmentPanel.this.getParent().getParent(); } class MyMouseListener extends MouseAdapter implements MouseListener, MouseMotionListener { private final int inMove = 2; private final int inRubberband = 3; private final int inScrollByMouse = 4; private boolean stillDownWithoutMoving = false; Point mouseDown = null; private int current = 0; @Override public void mouseClicked(MouseEvent me) { super.mouseClicked(me); int inClick = 1; current = inClick; int row = getRow(me.getPoint()); int col = getCol(me.getPoint()); if (me.getClickCount() == 1) { if (me.isShiftDown()) { if (selectedBlock.isSelected()) { if (!selectedBlock.isSelected(row, col)) selectedBlock.extendSelection(row, col); else selectedBlock.reduceSelection(row, col); } } else if (me.getButton() == 1 && !me.isControlDown() && !me.isAltDown()) { int read = alignment.getHitRead(row, col); if (read != -1) { Lane lane = alignment.getLane(read); int firstJump = alignment.getGapColumnContractor().getTotalJumpBeforeLayoutColumn(col); int firstCol = lane.getFirstNonGapPosition() - firstJump; int lastCol = lane.getLastNonGapPosition() - firstJump - 1; selectedBlock.select(row, firstCol, row, lastCol, alignment.isTranslate()); ProjectManager.getPreviouslySelectedNodeLabels().clear(); ProjectManager.getPreviouslySelectedNodeLabels().add(StringUtils.getFirstWord(lane.getName())); } else if ((me.isAltDown() && selectedBlock.isSelected()) || !selectedBlock.contains(row, col)) { selectedBlock.clear(); } } } else if (me.getClickCount() == 2) { if (!me.isAltDown()) selectedBlock.selectRow(row); else { selectedBlock.selectCol(col, alignment.isTranslate()); } } } @Override public void mousePressed(MouseEvent me) { super.mousePressed(me); mouseDown = me.getPoint(); boolean shiftDown = me.isShiftDown(); requestFocusInWindow(); if (me.isAltDown() || me.isShiftDown()) { current = inRubberband; setCursor(Cursor.getDefaultCursor()); } else { current = inScrollByMouse; setCursor(Cursors.getClosedHand()); stillDownWithoutMoving = true; final Thread worker = new Thread(new Runnable() { public void run() { try { synchronized (this) { wait(500); } } catch (InterruptedException ignored) { } if (stillDownWithoutMoving) { current = inRubberband; setCursor(Cursor.getDefaultCursor()); } } }); worker.setPriority(Thread.currentThread().getPriority() - 1); worker.start(); } } @Override public void mouseMoved(MouseEvent me) { super.mouseMoved(me); stillDownWithoutMoving = false; toolTipHelper.mouseMoved(me.getPoint()); } @Override public void mouseDragged(MouseEvent me) { super.mouseDragged(me); toolTipHelper.mouseMoved(me.getPoint()); stillDownWithoutMoving = false; if (current == inRubberband) { AlignmentPanel viewer = AlignmentPanel.this; Graphics2D gc = (Graphics2D) getGraphics(); if (gc != null) { Color color = viewer.getBackground() != null ? viewer.getBackground() : Color.WHITE; gc.setXORMode(color); int firstRow = Math.min(getRow(mouseDown), getRow(me.getPoint())); int firstCol = Math.min(getCol(mouseDown), getCol(me.getPoint())); int lastRow = Math.max(getRow(mouseDown), getRow(me.getPoint())); int lastCol = Math.max(getCol(mouseDown), getCol(me.getPoint())); getSelectedBlock().select(firstRow, firstCol, lastRow, lastCol, alignment.isTranslate()); } } else if (current == inScrollByMouse) { if (AlignmentPanel.this.getParent() != null && AlignmentPanel.this.getParent().getParent() != null && AlignmentPanel.this.getParent().getParent() instanceof JScrollPane) { JScrollPane scrollPane = (JScrollPane) AlignmentPanel.this.getParent().getParent(); int dX = me.getX() - mouseDown.x; int dY = me.getY() - mouseDown.y; if (dY != 0) { JScrollBar scrollBar = scrollPane.getVerticalScrollBar(); int amount = Math.round(dY * (scrollBar.getMaximum() - scrollBar.getMinimum()) / getHeight()); if (amount != 0) { scrollBar.setValue(scrollBar.getValue() - amount); } } if (dX != 0) { JScrollBar scrollBar = scrollPane.getHorizontalScrollBar(); int amount = Math.round(dX * (scrollBar.getMaximum() - scrollBar.getMinimum()) / getWidth()); if (amount != 0) { scrollBar.setValue(scrollBar.getValue() - amount); } } } } } @Override public void mouseReleased(MouseEvent me) { super.mouseReleased(me); stillDownWithoutMoving = false; if (current == inRubberband) { if (!me.getPoint().equals(mouseDown)) { int firstRow = Math.min(getRow(mouseDown), getRow(me.getPoint())); int firstCol = Math.min(getCol(mouseDown), getCol(me.getPoint())); int lastRow = Math.max(getRow(mouseDown), getRow(me.getPoint())); int lastCol = Math.max(getCol(mouseDown), getCol(me.getPoint())); getSelectedBlock().select(firstRow, firstCol, lastRow, lastCol, alignment.isTranslate()); } } setCursor(Cursor.getDefaultCursor()); current = 0; } } public boolean isColorMatchesVsReference() { return colorMatchesVsReference; } public void setColorMatchesVsReference(boolean colorMatchesVsReference) { this.colorMatchesVsReference = colorMatchesVsReference; if (colorMatchesVsReference) { colorMatchesVsConsensus = false; colorMismatchesVsConsensus = false; } } public boolean isColorMismatchesVsReference() { return colorMismatchesVsReference; } public void setColorMismatchesVsReference(boolean colorMismatchesVsReference) { this.colorMismatchesVsReference = colorMismatchesVsReference; if (colorMismatchesVsReference) { colorMatchesVsConsensus = false; colorMismatchesVsConsensus = false; } } public boolean isColorMatchesVsConsensus() { return colorMatchesVsConsensus; } public void setColorMatchesVsConsensus(boolean colorMatchesVsConsensus) { this.colorMatchesVsConsensus = colorMatchesVsConsensus; if (colorMatchesVsConsensus) { colorMatchesVsReference = false; colorMismatchesVsReference = false; } } public boolean isColorMismatchesVsConsensus() { return colorMismatchesVsConsensus; } public void setColorMismatchesVsConsensus(boolean colorMismatchesVsConsensus) { this.colorMismatchesVsConsensus = colorMismatchesVsConsensus; if (colorMismatchesVsConsensus) { colorMatchesVsReference = false; colorMismatchesVsReference = false; } } }
29,606
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ScrollPaneAdjuster.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/ScrollPaneAdjuster.java
/* * ScrollPaneAdjuster.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui; import javax.swing.*; import java.awt.*; /** * keep scrollbar centered on same point when zooming * Daniel Huson, 10.2011 */ public class ScrollPaneAdjuster { private final JScrollBar scrollBarX; private final JScrollBar scrollBarY; private final double xFactor; private final double yFactor; private final double xPortionOfVisible; private final double yPortionOfVisible; /** * construct object and "remember" how scrollpane is currently centered around middle of screen * */ public ScrollPaneAdjuster(JScrollPane scrollPane) { this(scrollPane, null); } /** * construct object and "remember" how scrollpane is currently centered * * @param centerDC center point in device coordinates */ public ScrollPaneAdjuster(JScrollPane scrollPane, Point centerDC) { Rectangle viewRect = scrollPane.getViewport().getViewRect(); scrollBarX = scrollPane.getHorizontalScrollBar(); scrollBarY = scrollPane.getVerticalScrollBar(); if (centerDC == null) { xPortionOfVisible = 0.5; yPortionOfVisible = 0.5; } else { xPortionOfVisible = (centerDC.x - viewRect.x) / (double) viewRect.width; yPortionOfVisible = (centerDC.y - viewRect.y) / (double) viewRect.height; } xFactor = (scrollBarX.getValue() + xPortionOfVisible * scrollBarX.getVisibleAmount()) / (scrollBarX.getMaximum() - scrollBarX.getMinimum()); yFactor = (scrollBarY.getValue() + yPortionOfVisible * scrollBarY.getVisibleAmount()) / (scrollBarY.getMaximum() - scrollBarY.getMinimum()); } /** * adjusts the scroll bars to recenter on world coordinates that were previously in * center of window * * @param horizontal adjust horizontally * @param vertical adjust vertically */ public void adjust(boolean horizontal, boolean vertical) { if (horizontal) { int newXValue = (int) Math.round(xFactor * (scrollBarX.getMaximum() - scrollBarX.getMinimum()) - xPortionOfVisible * scrollBarX.getVisibleAmount()); scrollBarX.setValue(newXValue); } if (vertical) { int newYValue = (int) Math.round(yFactor * (scrollBarY.getMaximum() - scrollBarY.getMinimum()) - yPortionOfVisible * scrollBarY.getVisibleAmount()); scrollBarY.setValue(newYValue); } } }
3,263
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
AlignmentViewerPanel.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/AlignmentViewerPanel.java
/* * AlignmentViewerPanel.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.util.NumberUtils; import megan.alignment.gui.colors.ColorSchemeAminoAcids; import megan.alignment.gui.colors.ColorSchemeNucleotides; import megan.alignment.gui.colors.ColorSchemeText; import javax.swing.*; import java.awt.*; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.MouseWheelEvent; /** * an alignment viewer panel * Daniel Huson, 9.2011 */ public class AlignmentViewerPanel extends JPanel { private final int laneHeight = 20; private final SelectedBlock selectedBlock = new SelectedBlock(); private final JSplitPane splitPane; private final JPanel emptyPanel; private final JPanel emptyPanel2; private final AlignmentPanel alignmentPanel; private final NamesPanel namesPanel; private final AxisPanel axisPanel; private final ReferencePanel referencePanel; private final ConsensusPanel consensusPanel; private final JScrollPane namesScrollPane; private final JScrollPane referenceScrollPane; private final JScrollPane consensusScrollPane; private final JScrollPane alignmentScrollPane; private final JScrollPane axisScrollPane; private static final int DEFAULT_SCALE = 11; private double hScale = DEFAULT_SCALE; private double vScale = DEFAULT_SCALE; private final JButton showRefButton; private final JLabel blastTypeLabel = new JLabel(); private boolean showReference = true; private boolean showConsensus = true; private boolean showAsMapping = false; private final String aminoAcidColorScheme = ColorSchemeAminoAcids.NAMES.Default.toString(); private final String nuceoltidesColorScheme = ColorSchemeNucleotides.NAMES.Default.toString(); /** * constructor */ public AlignmentViewerPanel() { JPanel mainPanel = this; mainPanel.setLayout(new BorderLayout()); emptyPanel = new JPanel(); emptyPanel.setLayout(new BorderLayout()); emptyPanel.setMinimumSize(new Dimension(100, laneHeight)); emptyPanel.setPreferredSize(new Dimension(100, laneHeight)); emptyPanel.setMaximumSize(new Dimension(100000, laneHeight)); blastTypeLabel.setBackground(emptyPanel.getBackground()); blastTypeLabel.setForeground(Color.LIGHT_GRAY); //emptyPanel.add(blastTypeLabel,BorderLayout.NORTH); GridBagConstraints emptyGBC = new GridBagConstraints(); emptyGBC.gridx = 0; emptyGBC.gridy = 0; emptyGBC.fill = GridBagConstraints.BOTH; emptyGBC.insets = new Insets(3, 0, 0, 4); emptyGBC.weightx = 1; emptyGBC.weighty = 0; emptyPanel2 = new JPanel(); emptyPanel2.setLayout(new BorderLayout()); emptyPanel2.setMinimumSize(new Dimension(100, 0)); emptyPanel2.setPreferredSize(new Dimension(100, 0)); emptyPanel2.setMaximumSize(new Dimension(100000, 0)); GridBagConstraints empty2GBC = new GridBagConstraints(); empty2GBC.gridx = 0; empty2GBC.gridy = 2; empty2GBC.fill = GridBagConstraints.BOTH; empty2GBC.insets = new Insets(3, 0, 0, 4); empty2GBC.weightx = 1; empty2GBC.weighty = 0; final JButton upButton = new JButton(new AbstractAction() { public void actionPerformed(ActionEvent actionEvent) { if (AlignmentSorter.moveUp(getAlignment(), selectedBlock.getFirstRow(), selectedBlock.getLastRow())) { selectedBlock.setFirstRow(selectedBlock.getFirstRow() - 1); selectedBlock.setLastRow(selectedBlock.getLastRow() - 1); selectedBlock.fireSelectionChanged(); repaint(); } } }); upButton.setBorder(BorderFactory.createEmptyBorder()); upButton.setToolTipText("Move selected sequences up"); upButton.setMaximumSize(new Dimension(16, 16)); upButton.setIcon(ResourceManager.getIcon("sun/Up16.gif")); final JButton downButton = new JButton(new AbstractAction() { public void actionPerformed(ActionEvent actionEvent) { if (AlignmentSorter.moveDown(getAlignment(), selectedBlock.getFirstRow(), selectedBlock.getLastRow())) { selectedBlock.setFirstRow(selectedBlock.getFirstRow() + 1); selectedBlock.setLastRow(selectedBlock.getLastRow() + 1); selectedBlock.fireSelectionChanged(); repaint(); } } }); downButton.setBorder(BorderFactory.createEmptyBorder()); downButton.setToolTipText("Move selected sequences down"); downButton.setMaximumSize(new Dimension(16, 16)); downButton.setIcon(ResourceManager.getIcon("sun/Down16.gif")); selectedBlock.addSelectionListener((selected, minRow, minCol, maxRow, maxCol) -> { upButton.setEnabled(getAlignment().getNumberOfSequences() > 0 && selectedBlock.isSelected() && selectedBlock.getFirstRow() > 0); downButton.setEnabled(getAlignment().getNumberOfSequences() > 0 && selectedBlock.isSelected() && selectedBlock.getLastRow() < getAlignment().getNumberOfSequences() - 1); }); showRefButton = new JButton(new AbstractAction() { public void actionPerformed(ActionEvent actionEvent) { setShowReference(!isShowReference()); } }); showRefButton.setBorder(BorderFactory.createEmptyBorder()); showRefButton.setToolTipText("Show/hide reference sequence (if available)"); showRefButton.setMaximumSize(new Dimension(16, 16)); showRefButton.setIcon(ResourceManager.getIcon("sun/Forward16.gif")); JButton showAsMappingButton = new JButton(new AbstractAction() { public void actionPerformed(ActionEvent actionEvent) { setShowAsMapping(!isShowAsMapping()); } }); showAsMappingButton.setBorder(BorderFactory.createEmptyBorder()); showAsMappingButton.setToolTipText("Show As Mapping"); //showAsMappingButton.setMaximumSize(new Dimension(16, 16)); JPanel row = new JPanel(); row.setLayout(new BoxLayout(row, BoxLayout.X_AXIS)); row.add(upButton); row.add(downButton); row.add(Box.createHorizontalGlue()); row.add(showRefButton); row.add(showAsMappingButton); emptyPanel.add(row, BorderLayout.SOUTH); namesPanel = new NamesPanel(selectedBlock); namesScrollPane = new JScrollPane(namesPanel); namesScrollPane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE); namesScrollPane.setPreferredSize(new Dimension(100, 50)); namesScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); namesScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); namesScrollPane.setAutoscrolls(true); namesScrollPane.setWheelScrollingEnabled(false); namesScrollPane.getViewport().setBackground(new Color(240, 240, 240)); GridBagConstraints namesGBC = new GridBagConstraints(); namesGBC.gridx = 0; namesGBC.gridy = 1; namesGBC.fill = GridBagConstraints.BOTH; namesGBC.insets = new Insets(0, 2, 0, 0); namesGBC.weightx = 1; namesGBC.weighty = 1; JPanel leftPanel = new JPanel(); leftPanel.setLayout(new GridBagLayout()); leftPanel.add(emptyPanel, emptyGBC); leftPanel.add(namesScrollPane, namesGBC); leftPanel.add(emptyPanel2, empty2GBC); axisPanel = new AxisPanel(selectedBlock); axisScrollPane = new JScrollPane(axisPanel); axisScrollPane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE); axisScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); axisScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); axisScrollPane.setMinimumSize(new Dimension(150, laneHeight)); axisScrollPane.setMaximumSize(new Dimension(100000, laneHeight)); axisScrollPane.setPreferredSize(new Dimension(100000, laneHeight)); axisScrollPane.getVerticalScrollBar().setEnabled(false); axisScrollPane.setAutoscrolls(true); axisScrollPane.setWheelScrollingEnabled(false); axisScrollPane.getViewport().setBackground(new Color(240, 240, 240)); GridBagConstraints axisGBC = new GridBagConstraints(); axisGBC.gridx = 0; axisGBC.gridy = 0; axisGBC.weightx = 1; axisGBC.weighty = 0; axisGBC.fill = GridBagConstraints.HORIZONTAL; referencePanel = new ReferencePanel(selectedBlock); referenceScrollPane = new JScrollPane(referencePanel); referenceScrollPane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE); referenceScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); referenceScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); referenceScrollPane.setMinimumSize(new Dimension(150, 0)); referenceScrollPane.setMaximumSize(new Dimension(100000, 0)); referenceScrollPane.setPreferredSize(new Dimension(100000, 0)); referenceScrollPane.getVerticalScrollBar().setEnabled(false); referenceScrollPane.getViewport().setBackground(new Color(240, 240, 240)); referenceScrollPane.setAutoscrolls(true); referenceScrollPane.setWheelScrollingEnabled(false); GridBagConstraints referenceGBC = new GridBagConstraints(); referenceGBC.gridx = 0; referenceGBC.gridy = 1; referenceGBC.weightx = 1; referenceGBC.weighty = 0; referenceGBC.fill = GridBagConstraints.HORIZONTAL; consensusPanel = new ConsensusPanel(selectedBlock); consensusScrollPane = new JScrollPane(consensusPanel); consensusScrollPane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE); consensusScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); consensusScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); consensusScrollPane.setMinimumSize(new Dimension(150, 0)); consensusScrollPane.setMaximumSize(new Dimension(100000, 0)); consensusScrollPane.setPreferredSize(new Dimension(100000, 0)); consensusScrollPane.getVerticalScrollBar().setEnabled(false); consensusScrollPane.getViewport().setBackground(new Color(240, 240, 240)); consensusScrollPane.setAutoscrolls(true); consensusScrollPane.setWheelScrollingEnabled(false); GridBagConstraints consensusGBC = new GridBagConstraints(); consensusGBC.gridx = 0; consensusGBC.gridy = 3; consensusGBC.weightx = 1; consensusGBC.weighty = 0; consensusGBC.fill = GridBagConstraints.HORIZONTAL; alignmentPanel = new AlignmentPanel(selectedBlock); alignmentScrollPane = new JScrollPane(alignmentPanel); alignmentScrollPane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE); alignmentScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); alignmentScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); alignmentScrollPane.getViewport().setBackground(new Color(240, 240, 240)); alignmentScrollPane.setAutoscrolls(true); GridBagConstraints alignmentGBC = new GridBagConstraints(); alignmentGBC.gridx = 0; alignmentGBC.gridy = 2; alignmentGBC.weightx = 1; alignmentGBC.weighty = 1; alignmentGBC.insets = new Insets(2, 0, 0, 0); alignmentGBC.fill = GridBagConstraints.BOTH; JPanel rightPanel = new JPanel(); rightPanel.setLayout(new GridBagLayout()); rightPanel.add(axisScrollPane, axisGBC); rightPanel.add(referenceScrollPane, referenceGBC); rightPanel.add(alignmentScrollPane, alignmentGBC); rightPanel.add(consensusScrollPane, consensusGBC); splitPane = new JSplitPane(); splitPane.setOneTouchExpandable(true); splitPane.setLeftComponent(leftPanel); splitPane.setRightComponent(rightPanel); splitPane.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent componentEvent) { super.componentResized(componentEvent); if (isShowAsMapping() && isNamesPanelVisible()) { setNamesPanelVisible(false); alignmentPanel.getScrollPane().revalidate(); } } }); mainPanel.add(splitPane); axisScrollPane.getHorizontalScrollBar().setModel(alignmentScrollPane.getHorizontalScrollBar().getModel()); referenceScrollPane.getHorizontalScrollBar().setModel(alignmentScrollPane.getHorizontalScrollBar().getModel()); namesScrollPane.getVerticalScrollBar().setModel(alignmentScrollPane.getVerticalScrollBar().getModel()); consensusScrollPane.getHorizontalScrollBar().setModel(alignmentScrollPane.getHorizontalScrollBar().getModel()); axisScrollPane.addMouseWheelListener(e -> { }); referenceScrollPane.addMouseWheelListener(e -> { }); consensusScrollPane.addMouseWheelListener(e -> { }); namesScrollPane.addMouseWheelListener(e -> { if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) { namesScrollPane.getVerticalScrollBar().setValue(alignmentScrollPane.getVerticalScrollBar().getValue() + e.getUnitsToScroll()); } }); alignmentPanel.addMouseWheelListener(e -> { if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) { boolean doScaleHorizontal = !e.isMetaDown() && !e.isAltDown() && !e.isShiftDown(); boolean doScaleVertical = !e.isMetaDown() && !e.isAltDown() && e.isShiftDown(); boolean doScrollVertical = !e.isMetaDown() && e.isAltDown() && !e.isShiftDown(); boolean doScrollHorizontal = !e.isMetaDown() && e.isAltDown() && e.isShiftDown(); if (ProgramProperties.isMacOS()) // has two-dimensional scrolling { boolean tmp = doScaleHorizontal; doScaleHorizontal = doScaleVertical; doScaleVertical = tmp; } if (doScrollVertical) { //scroll alignmentScrollPane.getVerticalScrollBar().setValue(alignmentScrollPane.getVerticalScrollBar().getValue() + e.getUnitsToScroll()); } else if (doScaleVertical) { //scale double toScroll = 1.0 + (e.getUnitsToScroll() / 100.0); double s = (toScroll > 0 ? 1.0 / toScroll : toScroll); double scale = s * vScale; if (scale > 0 && scale < 100) { zoom("vertical", "" + scale, e.getPoint()); } } else if (doScrollHorizontal) { alignmentScrollPane.getHorizontalScrollBar().setValue(alignmentScrollPane.getHorizontalScrollBar().getValue() + e.getUnitsToScroll()); } else if (doScaleHorizontal) { //scale double units = 1.0 + (e.getUnitsToScroll() / 100.0); double s = (units > 0 ? 1.0 / units : units); double scale = s * hScale; if (scale > 0 && scale < 100) { zoom("horizontal", "" + scale, e.getPoint()); } } } }); } /** * connect or disconnect scrollbar of name panel with that of alignment panel * */ private void connectNamePanel2AlignmentPane(boolean connect) { if (connect) namesScrollPane.getVerticalScrollBar().setModel(alignmentScrollPane.getVerticalScrollBar().getModel()); else namesScrollPane.getVerticalScrollBar().setModel(new DefaultBoundedRangeModel()); } /** * get the alignment * * @return alignment */ public Alignment getAlignment() { return alignmentPanel.getAlignment(); } /** * set the alignment for this viewer * */ public void setAlignment(Alignment alignment) { alignment.getGapColumnContractor().processAlignment(alignment); if (isShowAsMapping()) { alignment.getRowCompressor().update(); } else { alignment.getRowCompressor().clear(); } showRefButton.setEnabled(alignment.getReference().getLength() > 0); selectedBlock.setTotalRows(alignment.getNumberOfSequences()); selectedBlock.setTotalCols(alignment.getLength()); namesPanel.setAlignment(alignment); axisPanel.setAlignment(alignment); alignmentPanel.setAlignment(alignment); referencePanel.setAlignment(alignment); consensusPanel.setAlignment(alignment); switch (alignment.getSequenceType()) { case Alignment.PROTEIN -> { alignmentPanel.setColorScheme(new ColorSchemeAminoAcids(aminoAcidColorScheme)); consensusPanel.setColorScheme(new ColorSchemeAminoAcids(aminoAcidColorScheme)); } case Alignment.DNA -> { alignmentPanel.setColorScheme(new ColorSchemeNucleotides(nuceoltidesColorScheme)); consensusPanel.setColorScheme(new ColorSchemeNucleotides(nuceoltidesColorScheme)); } case Alignment.cDNA -> { alignmentPanel.setColorScheme(new ColorSchemeNucleotides(nuceoltidesColorScheme)); consensusPanel.setColorScheme(new ColorSchemeNucleotides(nuceoltidesColorScheme)); } default -> { alignmentPanel.setColorScheme(new ColorSchemeText()); consensusPanel.setColorScheme(new ColorSchemeText()); } } switch (alignment.getReferenceType()) { case Alignment.PROTEIN -> referencePanel.setColorScheme(new ColorSchemeAminoAcids(aminoAcidColorScheme)); case Alignment.DNA -> referencePanel.setColorScheme(new ColorSchemeNucleotides(nuceoltidesColorScheme)); case Alignment.cDNA -> referencePanel.setColorScheme(new ColorSchemeNucleotides(nuceoltidesColorScheme)); default -> referencePanel.setColorScheme(new ColorSchemeText()); } setShowConsensus(true); } public AlignmentPanel getSequencePanel() { return alignmentPanel; } public JSplitPane getSplitPane() { return splitPane; } public SelectedBlock getSelectedBlock() { return selectedBlock; } public void setShowReference(boolean showReference) { this.showReference = showReference; if (showReference) { emptyPanel.setMinimumSize(new Dimension(100, laneHeight + (int) referencePanel.getSize().getHeight())); emptyPanel.setPreferredSize(new Dimension(100, laneHeight + (int) referencePanel.getSize().getHeight())); emptyPanel.setMaximumSize(new Dimension(100000, laneHeight + (int) referencePanel.getSize().getHeight())); emptyPanel.revalidate(); referenceScrollPane.setMinimumSize(new Dimension(150, (int) referencePanel.getSize().getHeight())); referenceScrollPane.setMaximumSize(new Dimension(100000, (int) referencePanel.getSize().getHeight())); referenceScrollPane.setPreferredSize(new Dimension(100000, (int) referencePanel.getSize().getHeight())); referenceScrollPane.revalidate(); referencePanel.revalidateGrid(); } else { emptyPanel.setMinimumSize(new Dimension(100, laneHeight)); emptyPanel.setPreferredSize(new Dimension(100, laneHeight)); emptyPanel.setMaximumSize(new Dimension(100000, laneHeight)); emptyPanel.revalidate(); referenceScrollPane.setMinimumSize(new Dimension(150, 0)); referenceScrollPane.setMaximumSize(new Dimension(100000, 0)); referenceScrollPane.setPreferredSize(new Dimension(100000, 0)); referenceScrollPane.revalidate(); referencePanel.revalidateGrid(); } } public void setShowConsensus(boolean showConsensus) { this.showConsensus = showConsensus; if (showConsensus) { emptyPanel2.setMinimumSize(new Dimension(100, (int) consensusPanel.getSize().getHeight())); emptyPanel2.setPreferredSize(new Dimension(100, (int) consensusPanel.getSize().getHeight())); emptyPanel2.setMaximumSize(new Dimension(100000, (int) consensusPanel.getSize().getHeight())); emptyPanel2.revalidate(); consensusScrollPane.setMinimumSize(new Dimension(150, (int) consensusPanel.getSize().getHeight())); consensusScrollPane.setMaximumSize(new Dimension(100000, (int) consensusPanel.getSize().getHeight())); consensusScrollPane.setPreferredSize(new Dimension(100000, (int) consensusPanel.getSize().getHeight())); consensusScrollPane.revalidate(); consensusPanel.revalidateGrid(); } else { emptyPanel2.setMinimumSize(new Dimension(100, 0)); emptyPanel2.setPreferredSize(new Dimension(100, 0)); emptyPanel2.setMaximumSize(new Dimension(100000, 0)); emptyPanel2.revalidate(); consensusScrollPane.setMinimumSize(new Dimension(150, 0)); consensusScrollPane.setMaximumSize(new Dimension(100000, 0)); consensusScrollPane.setPreferredSize(new Dimension(100000, 0)); consensusScrollPane.revalidate(); consensusPanel.revalidateGrid(); } } public int getLaneHeight() { return laneHeight; } public JPanel getEmptyPanel() { return emptyPanel; } public AlignmentPanel getAlignmentPanel() { return alignmentPanel; } public NamesPanel getNamesPanel() { return namesPanel; } public AxisPanel getAxisPanel() { return axisPanel; } public ReferencePanel getReferencePanel() { return referencePanel; } public ConsensusPanel getConsensusPanel() { return consensusPanel; } public JScrollPane getNamesScrollPane() { return namesScrollPane; } public JScrollPane getReferenceScrollPane() { return referenceScrollPane; } public JScrollPane getAlignmentScrollPane() { return alignmentScrollPane; } public JScrollPane getAxisScrollPane() { return axisScrollPane; } public JLabel getBlastTypeLabel() { return blastTypeLabel; } public boolean isShowReference() { return showReference; } public boolean isShowConsensus() { return showConsensus; } public boolean isShowAsMapping() { return showAsMapping; } public void setShowAsMapping(boolean showAsMapping) { connectNamePanel2AlignmentPane(!showAsMapping); this.showAsMapping = showAsMapping; } public void revalidateGrid() { namesPanel.revalidateGrid(); namesScrollPane.revalidate(); axisPanel.revalidateGrid(); axisScrollPane.revalidate(); referencePanel.revalidateGrid(); referenceScrollPane.revalidate(); consensusPanel.revalidateGrid(); consensusScrollPane.revalidate(); alignmentPanel.revalidateGrid(); alignmentScrollPane.revalidate(); } /** * zoom either or both axes in or out, or reset to default scale * * @param axis vertical, horizontal or both * @param what in, out, reset or a number */ public void zoom(String axis, String what, Point centerPoint) { final JScrollPane alignmentScrollPane = getAlignmentScrollPane(); final AlignmentPanel alignmentPanel = getAlignmentPanel(); final NamesPanel namesPanel = getNamesPanel(); final ReferencePanel referencePanel = getReferencePanel(); final ConsensusPanel consensusPanel = getConsensusPanel(); final AxisPanel axisPanel = getAxisPanel(); ScrollPaneAdjuster scrollPaneAdjuster = new ScrollPaneAdjuster(alignmentScrollPane, centerPoint); if (axis.equals("horizontal") || axis.equals("both")) { if (what.equals("in")) hScale *= 1.2; else if (what.equals("out")) hScale /= 1.2; else if (what.equals("reset")) hScale = DEFAULT_SCALE; else if (what.equals("selection")) hScale *= alignmentPanel.getHZoomToSelectionFactor(); else if (what.equals("fit")) hScale *= alignmentPanel.getHZoomToFitFactor(); else if (NumberUtils.isDouble(what)) hScale = Math.max(0.0001, NumberUtils.parseDouble(what)); } if (axis.equals("vertical") || axis.equals("both")) { if (what.equals("in")) vScale *= 1.2; else if (what.equals("out")) vScale /= 1.2; else if (what.equals("reset")) vScale = DEFAULT_SCALE; else if (what.equals("selection")) vScale *= alignmentPanel.getVZoomToSelectionFactor(); else if (what.equals("fit")) vScale *= alignmentPanel.getVZoomToFitFactor(); else if (NumberUtils.isDouble(what)) vScale = Math.max(0.0001, NumberUtils.parseDouble(what)); } int maxFontSize = 24; if (hScale > maxFontSize) hScale = maxFontSize; if (vScale > maxFontSize) vScale = maxFontSize; alignmentPanel.setScale(hScale, vScale); namesPanel.setScale(0, vScale); axisPanel.setScale(hScale, 0); referencePanel.setScale(hScale, 0); consensusPanel.setScale(hScale, 0); if (isShowReference()) setShowReference(true); // update size of reference panel alignmentScrollPane.revalidate(); if (!what.equals("selection")) scrollPaneAdjuster.adjust(axis.equals("horizontal") || axis.equals("both"), axis.equals("vertical") || axis.equals("both")); else { Point aPoint = new Point((int) Math.round(alignmentPanel.getX(selectedBlock.getFirstCol())), (int) Math.round(alignmentPanel.getY(selectedBlock.getFirstRow() - 1))); alignmentScrollPane.getViewport().setViewPosition(aPoint); } } /** * copy selected alignment to clip-board */ public boolean copyAlignment() { final SelectedBlock selectedBlock = getSelectedBlock(); if (selectedBlock.isSelected()) { StringSelection ss = new StringSelection(getSelectedAlignment()); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null); return true; } return false; } /** * gets the selected alignment as a fastA string * * @return selected alignment or null */ public String getSelectedAlignment() { final SelectedBlock selectedBlock = getSelectedBlock(); if (selectedBlock.isSelected()) { return getAlignment().toFastA(getAlignmentPanel().isShowUnalignedChars(), selectedBlock.getFirstRow(), selectedBlock.getFirstCol(), selectedBlock.getLastRow(), selectedBlock.getLastCol()); } return null; } /** * copy selected consensus to clip-board */ public void copyConsensus() { final SelectedBlock selectedBlock = getSelectedBlock(); if (selectedBlock.isSelected()) { StringSelection ss = new StringSelection(getSelectedConsensus()); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null); } } /** * gets the selected consensus string * * @return selected consensus or null */ public String getSelectedConsensus() { final SelectedBlock selectedBlock = getSelectedBlock(); if (selectedBlock.isSelected()) { return getAlignment().getConsensusString(selectedBlock.getFirstCol(), selectedBlock.getLastCol()); } return null; } /** * copy selected reference to clip-board */ public void copyReference() { final SelectedBlock selectedBlock = getSelectedBlock(); if (selectedBlock.isSelected()) { StringSelection ss = new StringSelection(getSelectedReference()); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null); } } /** * gets the selected reference string * * @return selected reference or null */ public String getSelectedReference() { final SelectedBlock selectedBlock = getSelectedBlock(); if (selectedBlock.isSelected()) { return getAlignment().getReferenceString(selectedBlock.getFirstCol(), selectedBlock.getLastCol()); } return null; } public void setNamesPanelVisible(boolean namesPanelVisible) { if (namesPanelVisible) { splitPane.setDividerLocation(100); } else { splitPane.setDividerLocation(0); splitPane.setResizeWeight(0); } } private boolean isNamesPanelVisible() { return splitPane.getDividerLocation() > 0; } }
30,693
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SelectedBlock.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/SelectedBlock.java
/* * SelectedBlock.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui; import java.util.LinkedList; /** * selected block in alignment * Daniel Huson, 9.2011 */ public class SelectedBlock { private int firstRow; private int lastRow; private int firstCol; private int lastCol; private int totalRows = 0; private int totalCols = 0; private final LinkedList<ISelectionListener> selectionListeners = new LinkedList<>(); public SelectedBlock() { firstRow = 0; lastRow = -1; firstCol = 0; lastCol = -1; } public int getNumberOfSelectedRows() { return lastRow - firstRow + 1; } public int getNumberOfSelectedCols() { return lastCol - firstCol + 1; } public void selectAll() { firstRow = 0; lastRow = totalRows - 1; firstCol = 0; lastCol = totalCols - 1; } public void clear() { firstRow = 0; lastRow = -1; firstCol = 0; lastCol = -1; fireSelectionChanged(); } public void selectRow(int row) { firstRow = row; lastRow = row; firstCol = 0; lastCol = totalCols - 1; fireSelectionChanged(); } public void selectRows(int firstRow, int lastRow) { this.firstRow = firstRow; this.lastRow = lastRow; firstCol = 0; lastCol = totalCols - 1; fireSelectionChanged(); } public void selectCol(int col, boolean wholeCodon) { firstRow = 0; lastRow = totalRows - 1; if (wholeCodon) { firstCol = Math.max(0, col - (col % 3)); lastCol = firstCol + 2; } else { firstCol = col; lastCol = col; } fireSelectionChanged(); } public void selectCols(int firstCol, int lastCol, boolean wholeCodon) { firstRow = 0; lastRow = totalRows - 1; if (wholeCodon) { this.firstCol = Math.max(0, firstCol - (firstCol % 3)); this.lastCol = Math.min(getTotalCols() - 1, lastCol + 2 - (lastCol % 3)); } else { this.firstCol = firstCol; this.lastCol = lastCol; } fireSelectionChanged(); } public void select(int firstRow, int firstCol, int lastRow, int lastCol, boolean wholeCodon) { this.firstRow = Math.max(0, firstRow); this.lastRow = Math.min(lastRow, getTotalRows() - 1); if (wholeCodon) { this.firstCol = Math.max(0, firstCol - (firstCol % 3)); this.lastCol = Math.min(getTotalCols() - 1, lastCol + 2 - (lastCol % 3)); } else { this.firstCol = Math.max(0, firstCol); this.lastCol = Math.min(lastCol, getTotalCols() - 1); } fireSelectionChanged(); // System.err.println(this); } public String toString() { return "Selection: rows=" + firstRow + " - " + lastRow + ", cols=" + firstCol + " - " + lastCol; } /** * extend a selection * * @param toRow (-1 indicate extend cols only) * @param toCol (-1 indicates extend rows only) */ public void extendSelection(int toRow, int toCol) { if (toRow != -1) { if (toRow > totalRows) toRow = totalRows; if (toRow < firstRow) firstRow = toRow; else if (toRow >= lastRow) lastRow = toRow; } if (toCol != -1) { if (toCol > totalCols) toCol = totalCols; if (toCol < firstCol) firstCol = toCol; else if (toCol >= lastCol) lastCol = toCol; } fireSelectionChanged(); } /** * reduce a selection * * @param toRow (-1 indicates reduce columns only) * @param toCol (-1 indicates reduces rows only) */ public void reduceSelection(int toRow, int toCol) { if (toRow > totalRows) toRow = totalRows; if (toCol > totalCols) toCol = totalCols; boolean firstRowBest = Math.abs(toRow - firstRow) < Math.abs(toRow - lastRow); int bestRowScore = Math.min(Math.abs(toRow - firstRow), Math.abs(toRow - lastRow)); boolean firstColBest = Math.abs(toCol - firstCol) < Math.abs(toCol - lastCol); int bestColScore = Math.min(Math.abs(toCol - firstCol), Math.abs(toCol - lastCol)); if (toRow != -1 && (toCol == -1 || bestRowScore < bestColScore)) { if (firstRowBest) firstRow = toRow; else lastRow = toRow; fireSelectionChanged(); } else if (toCol != -1) { if (firstColBest) firstCol = toCol; else lastCol = toCol; fireSelectionChanged(); } } public boolean isSelected(int row, int col) { return row >= firstRow && row <= lastRow && col >= firstCol && col <= lastCol; } public int getFirstRow() { return firstRow; } public void setFirstRow(int firstRow) { this.firstRow = firstRow; } public int getLastRow() { return lastRow; } public void setLastRow(int lastRow) { this.lastRow = lastRow; } public int getFirstCol() { return firstCol; } public void setFirstCol(int firstCol) { this.firstCol = firstCol; } public int getLastCol() { return lastCol; } public void setLastCol(int lastCol) { this.lastCol = lastCol; } public boolean isSelected() { return firstRow <= lastRow && firstCol <= lastCol; } public boolean contains(int row, int col) { return row >= firstRow && row <= lastRow && col >= firstCol && col <= lastCol; } private int getTotalRows() { return totalRows; } public void setTotalRows(int totalRows) { this.totalRows = totalRows; } private int getTotalCols() { return totalCols; } public void setTotalCols(int totalCols) { this.totalCols = totalCols; } public void addSelectionListener(ISelectionListener selectionListener) { selectionListeners.add(selectionListener); } public void removeSelectionListener(ISelectionListener selectionListener) { selectionListeners.remove(selectionListener); } public void fireSelectionChanged() { for (ISelectionListener selectionListener : selectionListeners) { selectionListener.doSelectionChanged(isSelected(), firstRow, firstCol, lastRow, lastCol); } } public boolean isSelectedCol(int col) { return col >= firstCol && col <= lastCol; } public boolean isSelectedRow(int row) { return row >= firstRow && row <= lastRow; } }
7,619
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
NamesPanel.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/NamesPanel.java
/* * NamesPanel.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui; import jloda.swing.util.Cursors; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Rectangle2D; /** * Names panel * Daniel Huson, 9.2011 */ public class NamesPanel extends BasePanel { private Alignment alignment; /** * constructor */ public NamesPanel(final SelectedBlock selectedBlock) { super(selectedBlock); selectedBlock.addSelectionListener((selected, minRow, minCol, maxRow, maxCol) -> repaint()); MyMouseListener listener = new MyMouseListener(); addMouseListener(listener); addMouseMotionListener(listener); revalidate(); } public Alignment getAlignment() { return alignment; } public void setAlignment(Alignment alignment) { this.alignment = alignment; revalidateGrid(); } /** * paint * */ public void paint(Graphics g) { try { super.paint(g); paintNames(g); paintSelection(g); } catch (Exception ignored) { } } /** * Paints the names of the alignment * * @param g0 the graphics context of the sequence panel */ private void paintNames(Graphics g0) { final Graphics2D g = (Graphics2D) g0; final Rectangle visibleRect = getVisibleRect(); final Rectangle2D drawRect = new Rectangle2D.Double(); g.setColor(Color.WHITE);//new Color(0.93f, 0.97f, 0.96f)); g.fillRect(0, 0, getWidth(), getHeight()); g.setBackground(Color.WHITE); if (sequenceFont.getSize() > 14) sequenceFont = sequenceFont.deriveFont(14.0f); g.setFont(sequenceFont); boolean showText = (sequenceFont.getSize() > 6); if (showText) g.setColor(Color.BLACK); else g.setColor(Color.GRAY); if (alignment != null && !alignment.getRowCompressor().isEnabled()) { int minVisibleRow = (int) Math.max(0, (visibleRect.getY() / cellHeight)); int maxVisibleRow = (int) Math.min(alignment.getNumberOfSequences() - 1, (visibleRect.getY() + visibleRect.getHeight()) / cellHeight); for (int row = minVisibleRow; row <= maxVisibleRow; row++) { String name = alignment.getName(row); int y = (int) Math.round(getY(row)) - 2; if (showText) g.drawString(name, Math.round(getX(0)), y - (int) (cellHeight - sequenceFont.getSize()) / 2); else { drawRect.setRect(0, getY(row) - cellHeight + 2, getX(name.length()), Math.max(1, cellHeight - 1)); g.fill(drawRect); } } } } /** * paint the selection rectangle * */ private void paintSelection(Graphics g0) { Graphics2D g = (Graphics2D) g0; SelectedBlock selectedBlock = getSelectedBlock(); if (selectedBlock.isSelected()) { Rectangle2D rect = new Rectangle2D.Double(0, getY(selectedBlock.getFirstRow() - 1), 0, 0); rect.add(getSize().getWidth(), Math.min(getSize().height, getY(selectedBlock.getLastRow()))); g.setColor(highlightColorSemiTransparent); g.fill(rect); // g.setColor(highlightColor); // g.draw(rect); } } /** * Adapts the grid parameters to the current sequenceFont. It is invoked every time the sequenceFont changes. */ void revalidateGrid() { JScrollPane scrollPane = (JScrollPane) NamesPanel.this.getParent().getParent(); //scrollPane.revalidate(); Dimension bounds = scrollPane.getPreferredSize(); if (alignment != null && !alignment.getRowCompressor().isEnabled()) { int width = (int) Math.max(bounds.width, cellWidth * alignment.getMaxNameLength()); setSize(width, (int) (cellHeight * alignment.getNumberOfSequences() + 0.5) + 3); } setPreferredSize(getSize()); revalidate(); } class MyMouseListener extends MouseAdapter implements MouseListener, MouseMotionListener { private final int inMove = 2; private final int inRubberband = 3; private final int inScrollByMouse = 4; private boolean stillDownWithoutMoving = false; Point mouseDown = null; private boolean paintedRubberband = false; private int current = 0; @Override public void mouseClicked(MouseEvent me) { super.mouseClicked(me); int inClick = 1; current = inClick; if (me.getClickCount() == 1) { if (me.isShiftDown()) { if (selectedBlock.isSelected()) { if (!selectedBlock.isSelectedRow(getRow(me.getPoint()))) selectedBlock.extendSelection(getRow(me.getPoint()), -1); else selectedBlock.reduceSelection(getRow(me.getPoint()), -1); } } else if (!selectedBlock.contains(getRow(me.getPoint()), getCol(me.getPoint()))) { selectedBlock.clear(); } } else if (me.getClickCount() == 2) { if (!me.isAltDown()) selectedBlock.selectRow(getRow(me.getPoint())); } } @Override public void mousePressed(MouseEvent me) { super.mousePressed(me); mouseDown = me.getPoint(); paintedRubberband = false; boolean shiftDown = me.isShiftDown(); if (me.isAltDown() || me.isShiftDown()) { current = inRubberband; setCursor(Cursor.getDefaultCursor()); } else { current = inScrollByMouse; setCursor(Cursors.getClosedHand()); stillDownWithoutMoving = true; final Thread worker = new Thread(new Runnable() { public void run() { try { synchronized (this) { wait(500); } } catch (InterruptedException ignored) { } if (stillDownWithoutMoving) { current = inRubberband; setCursor(Cursor.getDefaultCursor()); } } }); worker.setPriority(Thread.currentThread().getPriority() - 1); worker.start(); } } @Override public void mouseMoved(MouseEvent me) { super.mouseMoved(me); stillDownWithoutMoving = false; setToolTipText(alignment.getToolTip(getRow(me.getPoint()))); } @Override public void mouseDragged(MouseEvent me) { super.mouseDragged(me); stillDownWithoutMoving = false; if (current == inRubberband) { NamesPanel viewer = NamesPanel.this; Graphics2D gc = (Graphics2D) getGraphics(); if (gc != null) { Color color = viewer.getBackground() != null ? viewer.getBackground() : Color.WHITE; gc.setXORMode(color); if (paintedRubberband) paintSelection(gc); else paintedRubberband = true; int firstRow = Math.min(getRow(mouseDown), getRow(me.getPoint())); int firstCol = 0; int lastRow = Math.max(getRow(mouseDown), getRow(me.getPoint())); int lastCol = Integer.MAX_VALUE; getSelectedBlock().select(firstRow, firstCol, lastRow, lastCol, alignment.isTranslate()); paintSelection(gc); } } else if (current == inScrollByMouse) { if (NamesPanel.this.getParent() != null && NamesPanel.this.getParent().getParent() != null && NamesPanel.this.getParent().getParent() instanceof JScrollPane) { JScrollPane scrollPane = (JScrollPane) NamesPanel.this.getParent().getParent(); int dX = me.getX() - mouseDown.x; int dY = me.getY() - mouseDown.y; if (dY != 0) { JScrollBar scrollBar = scrollPane.getVerticalScrollBar(); int amount = Math.round(dY * (scrollBar.getMaximum() - scrollBar.getMinimum()) / getHeight()); if (amount != 0) { scrollBar.setValue(scrollBar.getValue() - amount); } } if (dX != 0) { JScrollBar scrollBar = scrollPane.getHorizontalScrollBar(); int amount = Math.round(dX * (scrollBar.getMaximum() - scrollBar.getMinimum()) / getWidth()); if (amount != 0) { scrollBar.setValue(scrollBar.getValue() - amount); } } } } } @Override public void mouseReleased(MouseEvent me) { super.mouseReleased(me); stillDownWithoutMoving = false; if (current == inRubberband) { if (!me.getPoint().equals(mouseDown)) { int firstRow = Math.min(getRow(mouseDown), getRow(me.getPoint())); int lastRow = Math.max(getRow(mouseDown), getRow(me.getPoint())); getSelectedBlock().selectRows(firstRow, lastRow); } } //AlignmentPanel.this.repaint(); setCursor(Cursor.getDefaultCursor()); current = 0; } } }
10,898
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
Lane.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/Lane.java
/* * Lane.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui; import jloda.seq.SequenceUtils; /** * represents a lane of an alignment * Daniel Huson, 9.2011 */ public class Lane { private final Alignment alignment; private final String name; private int leadingGaps; private String block; private int trailingGaps; private final String unalignedPrefix; private final String unalignedSuffix; private final String toolTip; private final String text; /** * constructor * */ public Lane(Alignment alignment, String name, String text, String toolTip, String sequence) { this(alignment, name, text, toolTip, "", sequence, ""); } /** * constructor * */ public Lane(Alignment alignment, String name, String text, String toolTip, String unalignedPrefix, String sequence, String unalignedSuffix) { this.alignment = alignment; this.name = name; this.text = text; if (toolTip != null) this.toolTip = toolTip; else this.toolTip = name; this.unalignedPrefix = unalignedPrefix; this.unalignedSuffix = unalignedSuffix; int firstNonGapPos = 0; while (firstNonGapPos < sequence.length() && sequence.charAt(firstNonGapPos) == '-') firstNonGapPos++; if (firstNonGapPos == sequence.length()) { leadingGaps = firstNonGapPos; block = ""; trailingGaps = 0; } else { int lastNonGapPos = sequence.length() - 1; while (lastNonGapPos >= 0 && sequence.charAt(lastNonGapPos) == '-') lastNonGapPos--; leadingGaps = firstNonGapPos; setBlock(sequence.substring(firstNonGapPos, lastNonGapPos + 1)); trailingGaps = sequence.length() - lastNonGapPos - 1; } } /** * constructor * * @param leadingGaps number of leading gaps * @param block - block from first to last non-gap symbols * @param trailingGaps number of trailing gaps */ protected Lane(Alignment alignment, String name, String text, String toolTip, String unalignedPrefix, int leadingGaps, String block, int trailingGaps, String unalignedSuffix) { this.alignment = alignment; this.name = name; this.text = text; if (toolTip != null) this.toolTip = toolTip; else this.toolTip = name; this.leadingGaps = leadingGaps; this.unalignedPrefix = unalignedPrefix; setBlock(block); this.unalignedSuffix = unalignedSuffix; this.trailingGaps = trailingGaps; } public String getName() { return name; } public int getLeadingGaps() { return leadingGaps; } /** * get trailing gaps * * @return trailing gaps */ public int getTrailingGaps() { return trailingGaps; } public String getUnalignedPrefix() { return unalignedPrefix; } public String getBlock() { return block; } public String getUnalignedSuffix() { return unalignedSuffix; } public int getFirstNonGapPosition() { return getLeadingGaps(); } public int getLastNonGapPosition() { return getLeadingGaps() + getBlock().length(); } public void setLeadingGaps(int leadingGaps) { this.leadingGaps = leadingGaps; } public void setTrailingGaps(int trailingGaps) { this.trailingGaps = trailingGaps; } public void setBlock(String block) { this.block = block; // don't replace spaces here, will break reference sequence } /** * get the character at the given position * * @return char at position */ public char charAt(int pos) { if (pos < getLeadingGaps() || pos >= getLength() - getTrailingGaps()) return 0; else if (alignment == null || !alignment.isTranslate()) return block.charAt(pos - getLeadingGaps()); else { int which = pos - getLeadingGaps(); if ((which % 3) == 0) { if (which + 2 < block.length()) { return (char) SequenceUtils.getAminoAcid(block.charAt(which), block.charAt(which + 1), block.charAt(which + 2)); } else return block.charAt(which); } else return ' '; } } public String toStringIncludingLeadingAndTrailingGaps() { String buf = "-".repeat(Math.max(0, getLeadingGaps())) + block + "-".repeat(Math.max(0, getTrailingGaps())); return buf; } public String toString() { StringBuilder buf = new StringBuilder(); if (getLeadingGaps() > 0) buf.append("[").append(getLeadingGaps()).append("]"); buf.append(block); if (getTrailingGaps() > 0) buf.append("[").append(getTrailingGaps()).append("]"); return buf.toString(); } public int getLength() { return leadingGaps + trailingGaps + this.block.length(); } /** * is there an unaligned character at this position? * * @return true, if unaligned char available for this position */ public boolean hasUnalignedCharAt(int col) { if (col < getFirstNonGapPosition()) { int firstUnalignedPrefixPos = getFirstNonGapPosition() - unalignedPrefix.length(); return col > firstUnalignedPrefixPos; } else if (col >= getLastNonGapPosition()) { int lastUnalignedSuffixPos = getLastNonGapPosition() + unalignedSuffix.length(); return col < lastUnalignedSuffixPos; } return false; } /** * get the unaligned char at the given position * * @return unaligned char */ public char getUnalignedCharAt(int col) { col--; if (col < getFirstNonGapPosition()) { int firstUnalignedPrefixPos = getFirstNonGapPosition() - unalignedPrefix.length(); if (col >= firstUnalignedPrefixPos) return unalignedPrefix.charAt(col - firstUnalignedPrefixPos); } else if (col >= getLastNonGapPosition() - 1) { return unalignedSuffix.charAt(col - getLastNonGapPosition() + 1); } return '-'; } public String getText() { return text; } public String getToolTip() { return toolTip; } /** * gets the whole aligned sequence with all leading and trailing gaps * * @return sequence */ public String getSequence() { StringBuilder buf = new StringBuilder(); for (int i = 0; i < getLength(); i++) { char ch = charAt(i); if (Character.isLetter(ch) || ch == '?') buf.append(charAt(i)); else buf.append('-'); } return buf.toString(); } public void trimFromEnd(int newLength) { int length = leadingGaps + block.length(); trailingGaps = newLength - length; } }
7,890
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
AxisPanel.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/AxisPanel.java
/* * AxisPanel.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui; import jloda.swing.util.Cursors; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Rectangle2D; import java.util.SortedSet; /** * Axis panel * Daniel Huson, 9.2011 */ public class AxisPanel extends BasePanel { private Alignment alignment; /** * constructor */ public AxisPanel(SelectedBlock selectedBlock) { super(selectedBlock); MyMouseListener listener = new MyMouseListener(); addMouseListener(listener); addMouseMotionListener(listener); revalidate(); } private Alignment getAlignment() { return alignment; } public void setAlignment(Alignment alignment) { this.alignment = alignment; revalidateGrid(); } /** * paint * */ public void paint(Graphics g) { super.paint(g); paintAxis(g); paintSelection(g); } private final Font axisFont = new Font(Font.MONOSPACED, Font.PLAIN, 14); private final FontMetrics axisMetrics = getFontMetrics(axisFont); /** * Paints the axis of the alignment * * @param g0 the graphics context of the sequence panel */ private void paintAxis(Graphics g0) { Graphics2D g = (Graphics2D) g0; Rectangle rec = getVisibleRect(); g.setColor(Color.WHITE);//new Color(0.93f, 0.97f, 0.96f)); g.fillRect(0, 0, getWidth(), getHeight()); g.setBackground(Color.WHITE); g.setFont(axisFont); // g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (alignment != null) { final GapColumnContractor gapColumnContractor = getAlignment().getGapColumnContractor(); { g.setColor(Color.LIGHT_GRAY); SortedSet<Integer> jumpColumns = gapColumnContractor.getJumpPositionsRelativeToLayoutColumns(); for (Integer col : jumpColumns) { // g.setColor(Color.LIGHT_GRAY); // g.fillRect((int) getX(col) - 2,0,4,getSize().height-2); if (cellWidth > 1) { g.setColor(Color.WHITE); g.drawLine((int) getX(col), -1, (int) getX(col), getSize().height); g.setColor(Color.GRAY); // g.drawRect((int) getX(col) - 2,0,4,getSize().height-2); g.drawLine((int) getX(col) - 1, -1, (int) getX(col) - 1, getSize().height); g.drawLine((int) getX(col) + 1, -1, (int) getX(col) + 1, getSize().height); } else { g.drawLine((int) getX(col), -1, (int) getX(col), getSize().height); } } } g.setColor(Color.BLACK); int minVisibleCol = (int) Math.max(0, (rec.getX() / cellWidth)) + gapColumnContractor.getFirstLayoutColumn(); int maxVisibleCol = (int) Math.min(gapColumnContractor.getLastLayoutColumn(), (rec.getX() + rec.getWidth()) / cellWidth); double dashWidth = axisMetrics.getStringBounds("-", g).getWidth(); double maxLabelWidth = axisMetrics.getStringBounds("|" + Math.min(alignment.getLength(), maxVisibleCol), g).getWidth(); int step = 1; for (; step <= 1000000; step *= 10) { if (maxLabelWidth < getX(step) - getX(0)) break; } Integer[] jumpCols = gapColumnContractor.getJumpPositionsRelativeToLayoutColumns().toArray(new Integer[0]); int jc = 0; int jumped = 0; int offsetDueToInsertedPositions = 0; if (alignment.getInsertionsIntoReference().size() > 0) { // need to count all offsets due to insertions into reference: for (int layoutCol = gapColumnContractor.getFirstLayoutColumn(); layoutCol < minVisibleCol; layoutCol++) { while (jc < jumpCols.length && jumpCols[jc] < layoutCol) { jumped += gapColumnContractor.getJumpBeforeLayoutColumn(jumpCols[jc]); jc++; } int trueCol = layoutCol + jumped; if (alignment.getInsertionsIntoReference().contains(trueCol)) offsetDueToInsertedPositions++; } } double lastPos = Float.MIN_VALUE; for (int layoutCol = minVisibleCol; layoutCol <= maxVisibleCol; layoutCol++) { while (jc < jumpCols.length && jumpCols[jc] < layoutCol) { jumped += gapColumnContractor.getJumpBeforeLayoutColumn(jumpCols[jc]); jc++; } int trueCol = layoutCol + jumped; if (alignment.getInsertionsIntoReference().contains(trueCol - 1)) { offsetDueToInsertedPositions++; if (cellWidth > dashWidth) g.drawString("-", (int) (getX(layoutCol - 1) + (cellWidth - dashWidth) / 2), 11); } else { trueCol -= offsetDueToInsertedPositions; // we don't count positions that are insertions into the reference sequence if (trueCol > 0 && ((trueCol) % step) == 0) { double layoutX = getX(layoutCol - 1) - 3; if (lastPos + maxLabelWidth < layoutX) { g.drawString("|" + trueCol, Math.round(layoutX), 11); lastPos = layoutX; } } } } } } /** * paint the selection rectangle * */ private void paintSelection(Graphics g0) { Graphics2D g = (Graphics2D) g0; SelectedBlock selectedBlock = getSelectedBlock(); if (selectedBlock.isSelected()) { Rectangle2D rect = new Rectangle2D.Double(Math.max(0, getX(selectedBlock.getFirstCol())), 0, 0, 0); rect.add(Math.min(getX(selectedBlock.getLastCol() + 1), getSize().getWidth()), getSize().height); g.setColor(highlightColorSemiTransparent); g.fill(rect); } } /** * Adapts the grid parameters to the current sequenceFont. It is invoked every time the sequenceFont changes. */ void revalidateGrid() { JScrollPane scrollPane = (JScrollPane) getParent().getParent(); //scrollPane.revalidate(); Dimension bounds = scrollPane.getPreferredSize(); if (alignment != null) setSize((int) (cellWidth * alignment.getGapColumnContractor().getLayoutLength() + 0.5) + 3, bounds.height - 4); setPreferredSize(getSize()); revalidate(); } class MyMouseListener extends MouseAdapter implements MouseListener, MouseMotionListener { private final int inMove = 2; private final int inRubberband = 3; private final int inScrollByMouse = 4; private boolean stillDownWithoutMoving = false; Point mouseDown = null; private int current = 0; @Override public void mouseClicked(MouseEvent me) { super.mouseClicked(me); int inClick = 1; current = inClick; if (me.getClickCount() == 1) { if (me.isShiftDown()) { if (selectedBlock.isSelected()) { if (!selectedBlock.isSelectedCol(getCol(me.getPoint()))) selectedBlock.extendSelection(-1, getCol(me.getPoint())); else selectedBlock.reduceSelection(-1, getCol(me.getPoint())); } } else { selectedBlock.clear(); } } else if (me.getClickCount() == 2) { selectedBlock.selectCol(getCol(me.getPoint()), alignment.isTranslate()); } } @Override public void mousePressed(MouseEvent me) { super.mousePressed(me); mouseDown = me.getPoint(); boolean shiftDown = me.isShiftDown(); if (me.isAltDown() || me.isShiftDown()) { current = inRubberband; setCursor(Cursor.getDefaultCursor()); } else { current = inScrollByMouse; setCursor(Cursors.getClosedHand()); stillDownWithoutMoving = true; final Thread worker = new Thread(new Runnable() { public void run() { try { synchronized (this) { wait(500); } } catch (InterruptedException ignored) { } if (stillDownWithoutMoving) { current = inRubberband; setCursor(Cursor.getDefaultCursor()); } } }); worker.setPriority(Thread.currentThread().getPriority() - 1); worker.start(); } } @Override public void mouseMoved(MouseEvent me) { super.mouseMoved(me); stillDownWithoutMoving = false; //setToolTipText(); } @Override public void mouseDragged(MouseEvent me) { super.mouseDragged(me); stillDownWithoutMoving = false; if (current == inRubberband) { AxisPanel viewer = AxisPanel.this; Graphics2D gc = (Graphics2D) getGraphics(); if (gc != null) { Color color = viewer.getBackground() != null ? viewer.getBackground() : Color.WHITE; gc.setXORMode(color); int firstRow = 0; int firstCol = Math.min(getCol(mouseDown), getCol(me.getPoint())); int lastRow = Integer.MAX_VALUE; int lastCol = Math.max(getCol(mouseDown), getCol(me.getPoint())); getSelectedBlock().select(firstRow, firstCol, lastRow, lastCol, alignment.isTranslate()); paintSelection(gc); } } else if (current == inScrollByMouse) { if (AxisPanel.this.getParent() != null && AxisPanel.this.getParent().getParent() != null && AxisPanel.this.getParent().getParent() instanceof JScrollPane) { JScrollPane scrollPane = (JScrollPane) AxisPanel.this.getParent().getParent(); int dX = me.getX() - mouseDown.x; int dY = me.getY() - mouseDown.y; if (dY != 0) { JScrollBar scrollBar = scrollPane.getVerticalScrollBar(); int amount = Math.round(dY * (scrollBar.getMaximum() - scrollBar.getMinimum()) / getHeight()); if (amount != 0) { scrollBar.setValue(scrollBar.getValue() - amount); } } if (dX != 0) { JScrollBar scrollBar = scrollPane.getHorizontalScrollBar(); int amount = Math.round(dX * (scrollBar.getMaximum() - scrollBar.getMinimum()) / getWidth()); if (amount != 0) { scrollBar.setValue(scrollBar.getValue() - amount); } } } } } @Override public void mouseReleased(MouseEvent me) { super.mouseReleased(me); stillDownWithoutMoving = false; if (current == inRubberband) { if (!me.getPoint().equals(mouseDown)) { int firstCol = Math.min(getCol(mouseDown), getCol(me.getPoint())); int lastCol = Math.max(getCol(mouseDown), getCol(me.getPoint())); getSelectedBlock().selectCols(firstCol, lastCol, alignment.isTranslate()); } } //AlignmentPanel.this.repaint(); setCursor(Cursor.getDefaultCursor()); current = 0; } } }
13,280
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
RowCompressor.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/RowCompressor.java
/* * RowCompressor.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui; import jloda.util.Pair; import java.util.*; /** * row compressor is used to fit multiple reads into a single row. Is used for mapping visualization of reads, rather than alignment view * Daniel Huson, 1.2011 */ public class RowCompressor { private final Alignment alignment; private final Vector<List<Integer>> compressedRow2Reads = new Vector<>(); private boolean enabled = false; /** * constructor * */ public RowCompressor(Alignment alignment) { this.alignment = alignment; } /** * updates the row to compress row mapping */ public void update() { enabled = true; compressedRow2Reads.clear(); SortedSet<Pair<Integer, Integer>> sortedReads = new TreeSet<>(); int numberOfCompressedRows = 0; int[] ends = new int[alignment.getNumberOfSequences()]; // sort reads by start position for (int read = 0; read < alignment.getNumberOfSequences(); read++) { int start = alignment.getLane(read).getFirstNonGapPosition(); sortedReads.add(new Pair<>(start, read)); } // go through reads by start position and place in compressed rows for (Pair<Integer, Integer> pair : sortedReads) { int read = pair.getSecond(); int start = alignment.getLane(read).getFirstNonGapPosition(); boolean done = false; for (int row = 0; !done && row < numberOfCompressedRows; row++) { if (start > ends[row] + 10) { compressedRow2Reads.get(row).add(read); ends[row] = alignment.getLane(read).getLastNonGapPosition(); done = true; } } if (!done) { ends[numberOfCompressedRows] = alignment.getLane(read).getLastNonGapPosition(); List<Integer> reads = new LinkedList<>(); reads.add(read); compressedRow2Reads.add(numberOfCompressedRows, reads); numberOfCompressedRows++; } } } /** * erase */ public void clear() { compressedRow2Reads.clear(); enabled = false; } /** * gets the number of compressed rows * * @return number of compressed rows */ public int getNumberRows() { if (enabled) return compressedRow2Reads.size(); else return alignment.getNumberOfSequences(); } /** * maps a row to all its reads * * @return reads */ public List<Integer> getCompressedRow2Reads(int compressedRow) { if (enabled && compressedRow < compressedRow2Reads.size()) return compressedRow2Reads.get(compressedRow); else return Collections.singletonList(compressedRow); } /** * gets the original row of the alignment. Is simply the row, in the alignment view, else a read * * @return row if alignment, else read */ public int getRead(int row, int col) { if (enabled && row < compressedRow2Reads.size()) { for (int read : compressedRow2Reads.get(row)) { Lane lane = alignment.getLane(read); if (lane.getFirstNonGapPosition() <= col && lane.getLastNonGapPosition() >= col) return read; } return -1; } else { Lane lane = alignment.getLane(row); if (lane != null && lane.getFirstNonGapPosition() <= col && lane.getLastNonGapPosition() >= col) return row; } return -1; } /** * gets the row for a given read * * @return row */ public int getRow(int readId) { if (enabled) { for (int i = 0; i < compressedRow2Reads.size(); i++) { List<Integer> reads = compressedRow2Reads.elementAt(i); if (reads.contains(readId)) return i; } return -1; } else return readId; } public boolean isEnabled() { return enabled; } /** * move selected rows up * * @return true, if moved up */ public boolean moveUp(int firstRow, int lastRow) { lastRow = Math.min(lastRow, getNumberRows()); if (firstRow <= 0 || firstRow > lastRow) return false; else { List<Integer>[] array = new List[getNumberRows()]; for (int i = 0; i < getNumberRows(); i++) array[i] = getCompressedRow2Reads(i); List<Integer> replaced = array[firstRow - 1]; System.arraycopy(array, firstRow, array, firstRow - 1, lastRow + 1 - firstRow); array[lastRow] = replaced; compressedRow2Reads.clear(); compressedRow2Reads.addAll(Arrays.asList(array)); return true; } } /** * move the selected rows of sequences down one * * @return true, if moved */ public boolean moveDown(int firstRow, int lastRow) { firstRow = Math.max(0, firstRow); if (lastRow >= getNumberRows() - 1) return false; else { List<Integer>[] array = new List[getNumberRows()]; for (int i = 0; i < getNumberRows(); i++) array[i] = getCompressedRow2Reads(i); List<Integer> replaced = array[lastRow + 1]; System.arraycopy(array, firstRow, array, firstRow + 1, lastRow + 1 - firstRow); array[firstRow] = replaced; compressedRow2Reads.clear(); compressedRow2Reads.addAll(Arrays.asList(array)); return true; } } }
6,558
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ConsensusPanel.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/ConsensusPanel.java
/* * ConsensusPanel.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui; import jloda.swing.util.Cursors; import megan.alignment.gui.colors.ColorSchemeText; import megan.alignment.gui.colors.IColorScheme; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Rectangle2D; import java.util.SortedSet; /** * consensus panel * Daniel Huson, 4.2012 */ public class ConsensusPanel extends BasePanel { private Alignment alignment; private IColorScheme colorScheme = new ColorSchemeText(); private boolean showColors = true; /** * constructor */ public ConsensusPanel(SelectedBlock selectedBlock) { super(selectedBlock); MyMouseListener listener = new MyMouseListener(); addMouseListener(listener); addMouseMotionListener(listener); setToolTipText("Consensus sequence"); revalidate(); } private Alignment getAlignment() { return alignment; } public void setAlignment(Alignment alignment) { this.alignment = alignment; revalidateGrid(); } private IColorScheme getColorScheme() { return colorScheme; } public void setColorScheme(IColorScheme colorScheme) { this.colorScheme = colorScheme; } private boolean isShowColors() { return showColors; } public void setShowColors(boolean showColors) { this.showColors = showColors; } /** * paint * */ public void paint(Graphics g) { super.paint(g); paintConsensus(g); paintSelection(g); } /** * Paints the axis of the alignment * * @param g0 the graphics context of the sequence panel */ private void paintConsensus(Graphics g0) { Graphics2D g = (Graphics2D) g0; Rectangle rec = getVisibleRect(); g.setColor(Color.WHITE);//new Color(0.93f, 0.97f, 0.96f)); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.BLACK); g.setBackground(Color.WHITE); g.setFont(sequenceFont); // g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); final Lane consensusSequence = alignment.getConsensus(); if (alignment.getConsensus() != null) { final GapColumnContractor gapColumnContractor = getAlignment().getGapColumnContractor(); int minVisibleCol = (int) Math.max(0, (rec.getX() / cellWidth)) + gapColumnContractor.getFirstOriginalColumn(); int maxVisibleCol = (int) Math.min(gapColumnContractor.getLastOriginalColumn() - 1, (rec.getX() + rec.getWidth()) / cellWidth); if (minVisibleCol - 3 > 0) minVisibleCol -= 3; // just to cover previous codon if ((!alignment.isTranslate() && cellWidth < 1) || cellWidth < 0.5) { final Lane lane = alignment.getConsensus(); int firstLayoutCol = lane.getFirstNonGapPosition(); Integer[] jumpCols = gapColumnContractor.getJumpPositionsRelativeToOriginalColumns().toArray(new Integer[0]); if (jumpCols.length > 0) { int jc = 0; int jumped = 0; while (jc < jumpCols.length && jumpCols[jc] <= firstLayoutCol) { jumped += gapColumnContractor.getJumpBeforeOriginalColumn(jumpCols[jc]); jc++; } firstLayoutCol -= jumped; } int lastLayoutCol = lane.getLastNonGapPosition(); if (jumpCols.length > 0) { int jc = 0; int jumped = 0; while (jc < jumpCols.length && jumpCols[jc] < lastLayoutCol) { jumped += gapColumnContractor.getJumpBeforeOriginalColumn(jumpCols[jc]); jc++; } lastLayoutCol -= jumped; } double firstX = getX(firstLayoutCol); double lastX = getX(lastLayoutCol); if (firstX <= maxVisibleCol && lastX >= minVisibleCol) { g.setColor(Color.GRAY); g.fill(new Rectangle2D.Double(firstX, 0, lastX - firstX, getHeight())); } } else { final Rectangle2D drawRect = new Rectangle2D.Float(); if (isShowColors() && getColorScheme() != null) { // color scheme selected? g.setColor(Color.WHITE); Integer[] jumpCols = gapColumnContractor.getJumpPositionsRelativeToLayoutColumns().toArray(new Integer[0]); int jc = 0; int jumped = 0; int colorStreak = 0; for (int layoutCol = minVisibleCol; layoutCol <= maxVisibleCol; layoutCol++) { while (jc < jumpCols.length && jumpCols[jc] <= layoutCol) { jumped += gapColumnContractor.getJumpBeforeLayoutColumn(jumpCols[jc]); jc++; } int trueCol = layoutCol + jumped; char ch = consensusSequence.charAt(trueCol); // draw colors if (ch == 0 || ch == '-') { g.setColor(Color.WHITE); } else if (ch != ' ') { g.setColor(getColorScheme().getBackground(ch)); colorStreak = 0; } else { // only repeat the same color 3 times (for a codon...) colorStreak++; if (colorStreak == 3) { g.setColor(Color.WHITE); colorStreak = 0; } } if (!g.getColor().equals(Color.WHITE)) { drawRect.setRect(getX(layoutCol) - 1, 0, cellWidth, getSize().height); g.fill(drawRect); } } g.setColor(Color.BLACK); } } if (cellWidth > 4) { Integer[] jumpCols = gapColumnContractor.getJumpPositionsRelativeToLayoutColumns().toArray(new Integer[0]); int jc = 0; int jumped = 0; for (int layoutCol = minVisibleCol; layoutCol <= maxVisibleCol; layoutCol++) { while (jc < jumpCols.length && jumpCols[jc] <= layoutCol) { jumped += gapColumnContractor.getJumpBeforeLayoutColumn(jumpCols[jc]); jc++; } int trueCol = layoutCol + jumped; if (trueCol < gapColumnContractor.getLastOriginalColumn()) { char ch = consensusSequence.charAt(trueCol); if (ch == 0) ch = '-'; // draw colors if (isShowColors() && getColorScheme() != null) { // color scheme selected? g.setColor(Color.BLACK); } g.drawString("" + ch, Math.round(getX(layoutCol)), (int) Math.round(getSize().height - 0.5 * (getSize().height - cellHeight)) - 2); } } } if (cellWidth > 1) { SortedSet<Integer> jumpColumns = gapColumnContractor.getJumpPositionsRelativeToLayoutColumns(); for (Integer col : jumpColumns) { g.setColor(Color.WHITE); g.drawLine((int) getX(col), -1, (int) getX(col), getSize().height); g.setColor(Color.GRAY); g.drawLine((int) getX(col) - 1, -1, (int) getX(col) - 1, getSize().height); g.drawLine((int) getX(col) + 1, -1, (int) getX(col) + 1, getSize().height); } } } } /** * paint the selection rectangle * */ private void paintSelection(Graphics g0) { Graphics2D g = (Graphics2D) g0; SelectedBlock selectedBlock = getSelectedBlock(); if (selectedBlock.isSelected()) { Rectangle2D rect = new Rectangle2D.Double(Math.max(0, getX(selectedBlock.getFirstCol())), 0, 0, 0); rect.add(Math.min(getX(selectedBlock.getLastCol() + 1), getSize().getWidth()), getSize().height); g.setColor(highlightColorSemiTransparent); g.fill(rect); g.setColor(highlightColor); g.draw(rect); } } /** * Adapts the grid parameters to the current sequenceFont. It is invoked every time the sequenceFont changes. */ void revalidateGrid() { if (alignment != null) { setSize((int) (cellWidth * (alignment.getGapColumnContractor().getLayoutLength()) + 0.5) + 3, (int) Math.max(20, cellHeight)); } setPreferredSize(getSize()); revalidate(); } class MyMouseListener extends MouseAdapter implements MouseListener, MouseMotionListener { private final int inMove = 2; private final int inRubberband = 3; private final int inScrollByMouse = 4; private boolean stillDownWithoutMoving = false; Point mouseDown = null; private int current = 0; @Override public void mouseClicked(MouseEvent me) { super.mouseClicked(me); int inClick = 1; current = inClick; if (me.getClickCount() == 1) { if (me.isShiftDown()) { if (selectedBlock.isSelected()) { if (!selectedBlock.isSelectedCol(getCol(me.getPoint()))) selectedBlock.extendSelection(-1, getCol(me.getPoint())); else selectedBlock.reduceSelection(-1, getCol(me.getPoint())); } } else { selectedBlock.clear(); } } else if (me.getClickCount() == 2) { selectedBlock.selectCol(getCol(me.getPoint()), alignment.isTranslate()); } } @Override public void mousePressed(MouseEvent me) { super.mousePressed(me); mouseDown = me.getPoint(); boolean shiftDown = me.isShiftDown(); if (me.isAltDown() || me.isShiftDown()) { current = inRubberband; setCursor(Cursor.getDefaultCursor()); } else { current = inScrollByMouse; setCursor(Cursors.getClosedHand()); stillDownWithoutMoving = true; final Thread worker = new Thread(new Runnable() { public void run() { try { synchronized (this) { wait(500); } } catch (InterruptedException ignored) { } if (stillDownWithoutMoving) { current = inRubberband; setCursor(Cursor.getDefaultCursor()); } } }); worker.setPriority(Thread.currentThread().getPriority() - 1); worker.start(); } } @Override public void mouseMoved(MouseEvent me) { super.mouseMoved(me); stillDownWithoutMoving = false; //setToolTipText(); } @Override public void mouseDragged(MouseEvent me) { super.mouseDragged(me); stillDownWithoutMoving = false; if (current == inRubberband) { ConsensusPanel viewer = ConsensusPanel.this; Graphics2D gc = (Graphics2D) getGraphics(); if (gc != null) { Color color = viewer.getBackground() != null ? viewer.getBackground() : Color.WHITE; gc.setXORMode(color); int firstRow = 0; int firstCol = Math.min(getCol(mouseDown), getCol(me.getPoint())); int lastRow = Integer.MAX_VALUE; int lastCol = Math.max(getCol(mouseDown), getCol(me.getPoint())); getSelectedBlock().select(firstRow, firstCol, lastRow, lastCol, alignment.isTranslate()); paintSelection(gc); } } else if (current == inScrollByMouse) { if (ConsensusPanel.this.getParent() != null && ConsensusPanel.this.getParent().getParent() != null && ConsensusPanel.this.getParent().getParent() instanceof JScrollPane) { JScrollPane scrollPane = (JScrollPane) ConsensusPanel.this.getParent().getParent(); int dX = me.getX() - mouseDown.x; int dY = me.getY() - mouseDown.y; if (dY != 0) { JScrollBar scrollBar = scrollPane.getVerticalScrollBar(); int amount = Math.round(dY * (scrollBar.getMaximum() - scrollBar.getMinimum()) / getHeight()); if (amount != 0) { scrollBar.setValue(scrollBar.getValue() - amount); } } if (dX != 0) { JScrollBar scrollBar = scrollPane.getHorizontalScrollBar(); int amount = Math.round(dX * (scrollBar.getMaximum() - scrollBar.getMinimum()) / getWidth()); if (amount != 0) { scrollBar.setValue(scrollBar.getValue() - amount); } } } } } @Override public void mouseReleased(MouseEvent me) { super.mouseReleased(me); stillDownWithoutMoving = false; if (current == inRubberband) { if (!me.getPoint().equals(mouseDown)) { int firstCol = Math.min(getCol(mouseDown), getCol(me.getPoint())); int lastCol = Math.max(getCol(mouseDown), getCol(me.getPoint())); getSelectedBlock().selectCols(firstCol, lastCol, alignment.isTranslate()); } } //AlignmentPanel.this.repaint(); setCursor(Cursor.getDefaultCursor()); current = 0; } } }
15,673
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ISelectionListener.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/ISelectionListener.java
/* * ISelectionListener.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui; /** * selection listener * Daniel Huson, 9.2011 */ public interface ISelectionListener { void doSelectionChanged(boolean selected, int minRow, int minCol, int maxRow, int maxCol); }
1,033
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
AlignmentSorter.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/AlignmentSorter.java
/* * AlignmentSorter.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui; import jloda.graph.*; import jloda.util.CollectionUtils; import jloda.util.Pair; import java.util.*; /** * sort rows in alignment * Daniel Huson, 9.2011 */ public class AlignmentSorter { /** * sort by original order * */ public static void sortByOriginalOrder(final Alignment alignment) { alignment.resetOrder(); } /** * sort rows alphabetically by name * */ public static void sortByName(final Alignment alignment, final boolean descending) { Integer[] array = new Integer[alignment.getNumberOfSequences()]; for (int i = 0; i < alignment.getNumberOfSequences(); i++) array[i] = alignment.getOrder(i); alignment.resetOrder(); // need this so that getName etc gets the correct name Arrays.sort(array, (a, b) -> { int value = alignment.getName(a).compareTo(alignment.getName(b)); return descending ? -value : value; }); alignment.setOrder(Arrays.asList(array)); } /** * sort rows by start * */ public static void sortByStart(final Alignment alignment, final boolean descending) { Integer[] array = new Integer[alignment.getNumberOfSequences()]; for (int i = 0; i < alignment.getNumberOfSequences(); i++) array[i] = alignment.getOrder(i); alignment.resetOrder(); Arrays.sort(array, (a, b) -> { int sA = alignment.getLane(a).getFirstNonGapPosition(); int sB = alignment.getLane(b).getFirstNonGapPosition(); return descending ? sB - sA : sA - sB; }); alignment.setOrder(Arrays.asList(array)); } /** * sort rows by similarity * */ public static void sortBySimilarity(final Alignment alignment, final boolean descending) { alignment.resetOrder(); final Pair<Integer, Integer>[] list = new Pair[alignment.getNumberOfSequences()]; for (int i = 0; i < alignment.getNumberOfSequences(); i++) { list[i] = new Pair<>(alignment.getLane(i).getFirstNonGapPosition(), i); } Arrays.sort(list, new Pair<>()); // sort by start position float[][] similarity = new float[alignment.getNumberOfSequences()][alignment.getNumberOfSequences()]; for (int il = 0; il < list.length; il++) { final int i = list[il].getSecond(); final int iLast = alignment.getLane(i).getLastNonGapPosition(); for (int jl = il + 1; jl < list.length; jl++) { if (list[jl].getFirst() > iLast) break; // start of read j ist after end of read i final int j = list[jl].getSecond(); similarity[i][j] = similarity[j][i] = computeSimilarity(alignment.getLane(i), alignment.getLane(j)); } } Graph graph = new Graph(); Node[] row2node = new Node[alignment.getNumberOfSequences()]; SortedSet<Edge> edges = new TreeSet<>((e1, e2) -> { Float a1 = (Float) e1.getInfo(); Float a2 = (Float) e2.getInfo(); if (a1 > a2) return -1; else if (a1 < a2) return 1; else return Integer.compare(e1.getId(), e2.getId()); }); for (int i = 0; i < alignment.getNumberOfSequences(); i++) { row2node[i] = graph.newNode(); row2node[i].setInfo(i); } for (int i = 0; i < alignment.getNumberOfSequences(); i++) { for (int j = i + 1; j < alignment.getNumberOfSequences(); j++) { if (similarity[i][j] > 0) { edges.add(graph.newEdge(row2node[i], row2node[j], similarity[i][j])); } } } NodeArray<Node> otherEndOfChain = new NodeArray<>(graph); for (Node v = graph.getFirstNode(); v != null; v = graph.getNextNode(v)) { otherEndOfChain.put(v, v); } EdgeSet selectedEdges = new EdgeSet(graph); for (Edge e : edges) { Node v = e.getSource(); Node w = e.getTarget(); if (otherEndOfChain.get(v) != w && getNumberOfAdjacentSelected(v, selectedEdges) < 2 && getNumberOfAdjacentSelected(w, selectedEdges) < 2) { selectedEdges.add(e); Node ov = otherEndOfChain.get(v); Node ow = otherEndOfChain.get(w); otherEndOfChain.put(ov, ow); otherEndOfChain.put(ow, ov); } } List<List<Node>> chains = new LinkedList<>(); NodeSet used = new NodeSet(graph); for (Node v = graph.getFirstNode(); v != null; v = v.getNext()) { if (!used.contains(v) && getNumberOfAdjacentSelected(v, selectedEdges) == 1) { List<Node> chain = new LinkedList<>(); extractChainRec(v, null, used, chain, selectedEdges); chains.add(chain); } } for (Node v = graph.getFirstNode(); v != null; v = v.getNext()) { if (!used.contains(v)) { List<Node> chain = new LinkedList<>(); chain.add(v); chains.add(chain); } } sortChains(alignment, chains, null); LinkedList<Integer> order = new LinkedList<>(); for (List<Node> chain : chains) { for (Node v : chain) { order.add((Integer) v.getInfo()); } } alignment.setOrder(order); } /** * extract chain of nodes * */ private static void extractChainRec(Node v, Edge e, NodeSet used, List<Node> order, EdgeSet selectedEdges) { if (!used.contains(v)) { used.add(v); order.add(v); for (Edge f = v.getFirstAdjacentEdge(); f != null; f = v.getNextAdjacentEdge(f)) { if (f != e && selectedEdges.contains(f)) extractChainRec(f.getOpposite(v), f, used, order, selectedEdges); } } else throw new RuntimeException("Illegal cycle at: " + v); } /** * get number of adjacent nodes that are selected * * @return selected adjacent */ private static int getNumberOfAdjacentSelected(Node v, EdgeSet selectedEdges) { int count = 0; for (Edge e = v.getFirstAdjacentEdge(); e != null; e = v.getNextAdjacentEdge(e)) { if (selectedEdges.contains(e)) { count++; } } return count; } /** * computes the similarity of two sequences * * @return distance */ private static float computeSimilarity(Lane a, Lane b) { int same = 0; int diff = 0; int firstCoordinate = Math.max(a.getFirstNonGapPosition(), b.getFirstNonGapPosition()); int lastCoordinate = Math.min(a.getLastNonGapPosition(), b.getLastNonGapPosition()); for (int i = firstCoordinate; i <= lastCoordinate; i++) { char cha = a.charAt(i); char chb = b.charAt(i); if (Character.isLetter(cha) && Character.isLetter(chb)) { if (Character.toLowerCase(cha) == Character.toLowerCase((chb))) same++; else diff++; } } return Math.max(same > 0 ? 1 : 0, same - 3 * diff); } /** * sort chains from left to right * */ private static void sortChains(final Alignment alignment, List<List<Node>> chains, final Integer[] array) { // first reverse any chains so that left most sequence occurs first for (List<Node> chain : chains) { Node first = chain.get(0); Node last = chain.get(chain.size() - 1); int a = (Integer) first.getInfo(); int b = (Integer) last.getInfo(); if (alignment.getLane(a).getFirstNonGapPosition() > alignment.getLane(b).getFirstNonGapPosition()) { // need to reverse the chain List<Node> tmp = CollectionUtils.reverseList(chain); chain.clear(); chain.addAll(tmp); } } SortedSet<List<Node>> sorted = new TreeSet<>((listA, listB) -> { Node nodeA = listA.get(0); Node nodeB = listB.get(0); Lane laneA = alignment.getLane((Integer) nodeA.getInfo()); Lane laneB = alignment.getLane((Integer) nodeB.getInfo()); if (laneA.getFirstNonGapPosition() < laneB.getFirstNonGapPosition()) return -1; else if (laneA.getFirstNonGapPosition() > laneB.getFirstNonGapPosition()) return 1; else return Integer.compare(nodeA.getId(), nodeB.getId()); }); sorted.addAll(chains); chains.clear(); chains.addAll(sorted); } /** * move the selected interval of sequences up one * * @return true, if moved */ public static boolean moveUp(Alignment alignment, int firstRow, int lastRow) { lastRow = Math.min(lastRow, alignment.getNumberOfSequences()); if (firstRow <= 0 || firstRow > lastRow) return false; else { Integer[] array = new Integer[alignment.getNumberOfSequences()]; for (int i = 0; i < alignment.getNumberOfSequences(); i++) array[i] = alignment.getOrder(i); int replaced = array[firstRow - 1]; System.arraycopy(array, firstRow, array, firstRow - 1, lastRow + 1 - firstRow); array[lastRow] = replaced; alignment.setOrder(Arrays.asList(array)); return true; } } /** * move the selected interval of sequences down one * * @return true, if moved */ public static boolean moveDown(Alignment alignment, int firstRow, int lastRow) { firstRow = Math.max(0, firstRow); if (lastRow >= alignment.getNumberOfSequences() - 1) return false; else { Integer[] array = new Integer[alignment.getNumberOfSequences()]; for (int i = 0; i < alignment.getNumberOfSequences(); i++) array[i] = alignment.getOrder(i); int replaced = array[lastRow + 1]; System.arraycopy(array, firstRow, array, firstRow + 1, lastRow + 1 - firstRow); array[firstRow] = replaced; alignment.setOrder(Arrays.asList(array)); return true; } } }
11,316
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ColorSchemeAminoAcidsDefault.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/colors/ColorSchemeAminoAcidsDefault.java
/* * ColorSchemeAminoAcidsDefault.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui.colors; import java.awt.*; /** * amino acid color scheme * Daniel Huson, 9.2011 */ public class ColorSchemeAminoAcidsDefault extends ColorSchemeBase implements IColorScheme { /** * gets the background color for the amino-acid * * @return color */ public Color getBackground(int ch) { ch = Character.toUpperCase(ch); return switch (ch) { case 'A' -> getDefinedColor(ch, 0xeee9e9); case 'R' -> getDefinedColor(ch, 0x145AFF); case 'N' -> getDefinedColor(ch, 0x00DCDC); case 'D' -> getDefinedColor(ch, 0xE60A0A); case 'C' -> getDefinedColor(ch, 0xE6E600); case 'Q' -> getDefinedColor(ch, 0x00DCDC); case 'E' -> getDefinedColor(ch, 0xE60A0A); case 'G' -> getDefinedColor(ch, 0xEBEBEB); case 'H' -> getDefinedColor(ch, 0x8282D2); case 'I' -> getDefinedColor(ch, 0x0F820F); case 'L' -> getDefinedColor(ch, 0x0F820F); case 'K' -> getDefinedColor(ch, 0x145AFF); case 'M' -> getDefinedColor(ch, 0xE6E600); case 'F' -> getDefinedColor(ch, 0x3232AA); case 'P' -> getDefinedColor(ch, 0xDC9682); case 'S' -> getDefinedColor(ch, 0xFA9600); case 'T' -> getDefinedColor(ch, 0xFA9600); case 'W' -> getDefinedColor(ch, 0xB45AB4); case 'Y' -> getDefinedColor(ch, 0x3232AA); case 'V' -> getDefinedColor(ch, 0x0F820F); default -> getDefinedColor(ch, 0x778899); // Light Slate Gray }; } }
2,431
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ColorSchemeAminoAcidsZappo.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/colors/ColorSchemeAminoAcidsZappo.java
/* * ColorSchemeAminoAcidsZappo.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui.colors; import java.awt.*; /** * amino acid color scheme * Daniel Huson, 9.2011 */ public class ColorSchemeAminoAcidsZappo extends ColorSchemeBase implements IColorScheme { /** * gets the background color for the amino-acid * http://www.jalview.org/help.html * * @return color */ public Color getBackground(int ch) { ch = Character.toUpperCase(ch); return switch (ch) { case 'I', 'L', 'V', 'A', 'M' -> getDefinedColor(ch, 0xFFAFAF); case 'F', 'Y', 'W' -> getDefinedColor(ch, 0xFFC800); case 'H', 'K', 'R' -> getDefinedColor(ch, 0x6464FF); case 'D', 'E' -> getDefinedColor(ch, 0xFF0000); case 'S', 'T', 'N', 'Q' -> getDefinedColor(ch, 0x00FF00); case 'G', 'P' -> getDefinedColor(ch, 0xFFFFFF); case 'C' -> getDefinedColor(ch, 0xFFFF00); default -> getDefinedColor(ch, 0x778899); // Light Slate Gray }; } }
1,817
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
IColorScheme.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/colors/IColorScheme.java
/* * IColorScheme.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui.colors; import java.awt.*; /** * a color scheme * Daniel Huson, 9.2011 */ public interface IColorScheme { Color getColor(int ch); Color getBackground(int ch); }
1,011
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ColorSchemeAminoAcidsPDNA.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/colors/ColorSchemeAminoAcidsPDNA.java
/* * ColorSchemeAminoAcidsPDNA.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui.colors; import java.awt.*; /** * amino acid color scheme * Daniel Huson, 9.2011 */ public class ColorSchemeAminoAcidsPDNA extends ColorSchemeBase implements IColorScheme { /** * gets the background color for the amino-acid * PDNA groups: LVIMC AGSTP FYW EDNQKRH * * @return color */ public Color getBackground(int ch) { ch = Character.toUpperCase(ch); return switch (ch) { case 'I', 'L', 'V', 'M', 'C' -> getDefinedColor(ch, 0x15C015); //green case 'A', 'G', 'S', 'T', 'P' -> getDefinedColor(ch, 0xF09048); // orange case 'F', 'Y', 'W' -> getDefinedColor(ch, 0x80A0F0); // blue case 'R', 'N', 'D', 'Q', 'E', 'H', 'K' -> getDefinedColor(ch, 0xF01505); // red default -> getDefinedColor(ch, 0x778899); // Light Slate Gray }; } }
1,704
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ColorSchemeBase.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/colors/ColorSchemeBase.java
/* * ColorSchemeBase.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui.colors; import java.awt.*; import java.util.HashMap; import java.util.Map; /** * based class for color scheme * Daniel Huson, 4.2012 */ abstract class ColorSchemeBase { private final Map<Integer, Color> definedColors = new HashMap<>(); /** * get the foreground color * * @return black */ public Color getColor(int ch) { return Color.BLACK; } /** * get the background color for a character * * @return color */ abstract public Color getBackground(int ch); /** * gets the amino acid color for a character * * @param rgb the color to use for this amino acid * @return amino acid color */ Color getDefinedColor(int ch, int rgb) { Color result = definedColors.get(ch); if (result == null) { result = new Color(rgb); definedColors.put(ch, result); } return result; } }
1,776
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ColorSchemeAminoAcids.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/colors/ColorSchemeAminoAcids.java
/* * ColorSchemeAminoAcids.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui.colors; import java.awt.*; import java.util.LinkedList; /** * create a new color scheme * Daniel Huson, 4.2012 */ public class ColorSchemeAminoAcids implements IColorScheme { public enum NAMES { Default, ClustalX, Zappo, CINEMA, MAEditor, PDNA } private final IColorScheme colorScheme; /** * constructor: * */ public ColorSchemeAminoAcids(String name) { NAMES which = NAMES.Default; for (NAMES type : NAMES.values()) { if (type.toString().equalsIgnoreCase(name)) { which = type; break; } } switch (which) { case CINEMA -> colorScheme = new ColorSchemeAminoAcidsCINEMA(); case ClustalX -> colorScheme = new ColorSchemeAminoAcidsClustalX(); case MAEditor -> colorScheme = new ColorSchemeAminoAcidsMAEditor(); case PDNA -> colorScheme = new ColorSchemeAminoAcidsPDNA(); case Zappo -> colorScheme = new ColorSchemeAminoAcidsZappo(); default /*case Default */ -> colorScheme = new ColorSchemeAminoAcidsDefault(); } } /** * get the forground color * * @return color */ public Color getColor(int ch) { return colorScheme.getColor(ch); } /** * get the background color * * @return color */ public Color getBackground(int ch) { return colorScheme.getBackground(ch); } /** * get list of names * * @return names */ public static String[] getNames() { LinkedList<String> names = new LinkedList<>(); for (NAMES type : NAMES.values()) { names.add(type.toString()); } return names.toArray(new String[0]); } }
2,617
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ColorSchemeAminoAcidsClustalX.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/colors/ColorSchemeAminoAcidsClustalX.java
/* * ColorSchemeAminoAcidsClustalX.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui.colors; import java.awt.*; /** * amino acid color scheme * Daniel Huson, 9.2011 */ public class ColorSchemeAminoAcidsClustalX extends ColorSchemeBase implements IColorScheme { /** * gets the background color for the amino-acid * * @return color */ public Color getBackground(int ch) { ch = Character.toUpperCase(ch); // source: http://www.jalview.org/help/html/colourSchemes/clustal.html return switch (ch) { case 'A', 'C', 'I', 'L', 'M', 'F', 'W', 'V' -> getDefinedColor(ch, 0x80A0F0); case 'K', 'R' -> getDefinedColor(ch, 0xF01505); case 'N', 'Q', 'S', 'T' -> getDefinedColor(ch, 0x15C015); case 'D', 'E' -> getDefinedColor(ch, 0xC048C0); case 'G' -> getDefinedColor(ch, 0xF09048); case 'P' -> getDefinedColor(ch, 0xC0C000); case 'H', 'Y' -> getDefinedColor(ch, 0x15A4A4); default -> getDefinedColor(ch, 0x778899); // Light Slate Gray }; } }
1,862
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ColorSchemeNucleotidesDefault.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/colors/ColorSchemeNucleotidesDefault.java
/* * ColorSchemeNucleotidesDefault.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui.colors; import java.awt.*; /** * amino acid color scheme * Daniel Huson, 9.2011 */ public class ColorSchemeNucleotidesDefault extends ColorSchemeBase implements IColorScheme { /** * gets the background color * * @return color */ public Color getBackground(int ch) { return switch (ch) { case 'a', 'A' -> getDefinedColor(ch, 0x64F73F); // green case 'c', 'C' -> getDefinedColor(ch, 0xFFB340); // orange case 'g', 'G' -> getDefinedColor(ch, 0xEB413C); // red case 't', 'T', 'u', 'U' -> getDefinedColor(ch, 0x3C88EE); // blue case '-' -> getDefinedColor(ch, 0x778899); // Light Slate Gray default -> Color.LIGHT_GRAY; }; } }
1,605
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ColorSchemeAminoAcidsMAEditor.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/colors/ColorSchemeAminoAcidsMAEditor.java
/* * ColorSchemeAminoAcidsMAEditor.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui.colors; import java.awt.*; /** * amino acid color scheme * Daniel Huson, 9.2011 */ public class ColorSchemeAminoAcidsMAEditor extends ColorSchemeBase implements IColorScheme { /** * gets the background color for the amino-acid * * @return color */ public Color getBackground(int ch) { ch = Character.toUpperCase(ch); // source: http://www.bioinformatics.nl/~berndb/aacolour.html return switch (ch) { case 'A', 'G' -> getDefinedColor(ch, 0x77DD88); case 'C' -> getDefinedColor(ch, 0x99EE66); case 'D', 'E', 'N', 'Q' -> getDefinedColor(ch, 0x55BB33); case 'I', 'L', 'M', 'V' -> getDefinedColor(ch, 0x66BBFF); case 'F', 'W', 'Y' -> getDefinedColor(ch, 0x9999FF); case 'H' -> getDefinedColor(ch, 0x5555FF); case 'K', 'R' -> getDefinedColor(ch, 0xFFCC77); case 'P' -> getDefinedColor(ch, 0xEEAAAA); case 'S', 'T' -> getDefinedColor(ch, 0xFF4455); default -> getDefinedColor(ch, 0x778899); // Light Slate Gray }; } }
1,953
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ColorSchemeText.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/colors/ColorSchemeText.java
/* * ColorSchemeText.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui.colors; import java.awt.*; /** * text color scheme * Daniel Huson, 9.2011 */ public class ColorSchemeText implements IColorScheme { public Color getColor(int ch) { return Color.BLACK; } public Color getBackground(int ch) { return Color.WHITE; } }
1,124
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ColorSchemeAminoAcidsCINEMA.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/colors/ColorSchemeAminoAcidsCINEMA.java
/* * ColorSchemeAminoAcidsCINEMA.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui.colors; import java.awt.*; /** * amino acid color scheme * Daniel Huson, 9.2011 */ public class ColorSchemeAminoAcidsCINEMA extends ColorSchemeBase implements IColorScheme { /** * gets the background color for the amino-acid * * @return color */ public Color getBackground(int ch) { ch = Character.toUpperCase(ch); // source: http://www.bioinformatics.nl/~berndb/aacolour.html return switch (ch) { case 'H', 'K', 'R' -> getDefinedColor(ch, 0x00FFFF); case 'D', 'E' -> getDefinedColor(ch, 0xFF0000); case 'S', 'T', 'N', 'Q' -> getDefinedColor(ch, 0x00FF00); case 'A', 'V', 'I', 'L', 'M' -> getDefinedColor(ch, 0xBBBBBB); case 'F', 'W', 'Y' -> getDefinedColor(ch, 0xFF00FF); case 'P', 'G' -> getDefinedColor(ch, 0x996600); case 'C' -> getDefinedColor(ch, 0xFFFF00); default -> getDefinedColor(ch, 0x778899); // Light Slate Gray }; } }
1,849
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ColorSchemeNucleotides.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/gui/colors/ColorSchemeNucleotides.java
/* * ColorSchemeNucleotides.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.gui.colors; import java.awt.*; import java.util.LinkedList; /** * create a new color scheme * Daniel Huson, 4.2012 */ public class ColorSchemeNucleotides implements IColorScheme { public enum NAMES { Default } private final IColorScheme colorScheme; /** * constructor: * */ public ColorSchemeNucleotides(String name) { NAMES which = NAMES.Default; for (NAMES type : NAMES.values()) { if (type.toString().equalsIgnoreCase(name)) { break; } } colorScheme = new ColorSchemeNucleotidesDefault(); } /** * get the foreground color * * @return color */ public Color getColor(int ch) { return colorScheme.getColor(ch); } /** * get the background color * * @return color */ public Color getBackground(int ch) { return colorScheme.getBackground(ch); } /** * get list of names * * @return names */ public static String[] getNames() { LinkedList<String> names = new LinkedList<>(); for (NAMES type : NAMES.values()) { names.add(type.toString()); } return names.toArray(new String[0]); } }
2,102
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ShowInsertionsCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ShowInsertionsCommand.java
/* * ShowInsertionsCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.alignment.AlignmentViewer; import javax.swing.*; import java.awt.event.ActionEvent; /** * show insertions command * Daniel Huson, 8.2011 */ public class ShowInsertionsCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { AlignmentViewer viewer = (AlignmentViewer) getViewer(); return viewer.isShowInsertions(); } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set show-insertions="); boolean show = np.getBoolean(); np.matchIgnoreCase(";"); AlignmentViewer viewer = (AlignmentViewer) getViewer(); viewer.setShowInsertions(show); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set show-insertions={true|false};"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { execute("set show-insertions=" + !isSelected() + ";apply;"); } private static final String NAME = "Show Insertions"; public String getName() { return NAME; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Show insertions in reads"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("ShowInsertions16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return true; } }
3,272
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ZoomToSelectionCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ZoomToSelectionCommand.java
/* * ZoomToSelectionCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.alignment.AlignmentViewer; import megan.commands.CommandBase; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; public class ZoomToSelectionCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { executeImmediately("expand axis=both what=selection;"); } public boolean isApplicable() { AlignmentViewer viewer = (AlignmentViewer) getViewer(); return viewer.getSelectedBlock().isSelected(); } final static public String NAME = "Zoom To Selection"; public String getName() { return "Zoom To Selection"; } public ImageIcon getIcon() { return ResourceManager.getIcon("ZoomToSelection16.gif"); } public String getDescription() { return "Zoom to selection"; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } public boolean isCritical() { return true; } }
2,289
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ExportConsensusCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ExportConsensusCommand.java
/* * ExportConsensusCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ChooseFileDialog; import jloda.swing.util.FastaFileFilter; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.swing.window.NotificationsInSwing; import jloda.util.FileUtils; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.alignment.AlignmentViewer; import megan.alignment.gui.Alignment; import megan.alignment.gui.SelectedBlock; import javax.swing.*; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; /** * save data command * Daniel Huson, 11.2010 */ public class ExportConsensusCommand extends CommandBase implements ICommand { public String getSyntax() { return "export consensus file=<filename> [what={all|selection}];"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("export consensus file="); String fileName = np.getAbsoluteFileName(); boolean saveAll = true; if (np.peekMatchIgnoreCase("what")) { np.matchIgnoreCase("what="); saveAll = np.getWordMatchesIgnoringCase("selected all").equalsIgnoreCase("all"); } np.matchIgnoreCase(";"); try { AlignmentViewer viewer = (AlignmentViewer) getViewer(); if (saveAll) { System.err.println("Exporting complete consensus to: " + fileName); Alignment alignment = viewer.getAlignment(); String string = alignment.getConsensus().toStringIncludingLeadingAndTrailingGaps(); Writer w = new FileWriter(fileName); w.write(string); w.write("\n"); w.close(); } else { System.err.println("Exporting selected consensus to: " + fileName); Writer w = new FileWriter(fileName); w.write(viewer.getAlignmentViewerPanel().getSelectedConsensus()); w.write("\n"); w.close(); } } catch (IOException e) { NotificationsInSwing.showError("Export Consensus failed: " + e.getMessage()); } } public void actionPerformed(ActionEvent event) { File lastOpenFile = ProgramProperties.getFile("SaveConsensus"); String fileName = ((AlignmentViewer) getViewer()).getAlignment().getName(); if (fileName == null) fileName = "Untitled"; else fileName = StringUtils.toCleanName(fileName); if (lastOpenFile != null) { fileName = new File(lastOpenFile.getParent(), fileName).getPath(); } fileName = FileUtils.replaceFileSuffix(fileName, "-consensus.fasta"); File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), new File(fileName), new FastaFileFilter(), new FastaFileFilter(), event, "Save consensus file", ".fasta"); if (file != null) { if (FileUtils.getFileSuffix(file.getName()) == null) file = FileUtils.replaceFileSuffix(file, ".txt"); ProgramProperties.put("SaveConsensus", file); SelectedBlock selectedBlock = ((AlignmentViewer) getViewer()).getSelectedBlock(); executeImmediately("export consensus file='" + file.getPath() + "' what=" + (selectedBlock == null || !selectedBlock.isSelected() ? "all" : "Selected") + ";"); } } public boolean isApplicable() { return ((AlignmentViewer) getViewer()).getAlignment().getLength() > 0; } public String getName() { return "Consensus..."; } public String getAltName() { return "Export Consensus..."; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Export16.gif"); } public String getDescription() { return "Export consensus sequence to a file"; } public boolean isCritical() { return false; } public KeyStroke getAcceleratorKey() { return null; } }
4,920
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ShowReferenceCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ShowReferenceCommand.java
/* * ShowReferenceCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.alignment.AlignmentViewer; import javax.swing.*; import java.awt.event.ActionEvent; /** * command * Daniel Huson, 8.2011 */ public class ShowReferenceCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { AlignmentViewer viewer = (AlignmentViewer) getViewer(); return viewer.getAlignmentViewerPanel().isShowReference(); } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set show-reference="); boolean value = np.getBoolean(); np.matchIgnoreCase(";"); AlignmentViewer viewer = (AlignmentViewer) getViewer(); viewer.getAlignmentViewerPanel().setShowReference(value); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set show-reference={true|false};"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { execute("set show-reference=" + !isSelected() + ";"); } private static final String NAME = "Show Reference"; public String getName() { return NAME; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Show reference sequence"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("ShowReferenceSequence16.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() { AlignmentViewer viewer = (AlignmentViewer) getViewer(); return viewer.getAlignment().getReference() != null && viewer.getAlignment().getReference().getLength() > 0; } }
3,462
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
CopyConsensusCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/CopyConsensusCommand.java
/* * CopyConsensusCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.alignment.AlignmentViewer; import megan.commands.clipboard.ClipboardBase; import javax.swing.*; import java.awt.event.ActionEvent; public class CopyConsensusCommand extends ClipboardBase implements ICommand { public String getSyntax() { return null; } public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { AlignmentViewer viewer = (AlignmentViewer) getViewer(); viewer.getAlignmentViewerPanel().copyConsensus(); } public boolean isApplicable() { AlignmentViewer viewer = (AlignmentViewer) getViewer(); return viewer.getSelectedBlock().isSelected(); } public String getName() { return "Copy Consensus"; } public String getDescription() { return "Copy selected consensus sequence to clipboard"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Copy16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
2,065
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/alignment/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.alignment.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; /** * font size * Daniel Huson, 8.2011 */ public class ExpandHorizontalCommand 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) { executeImmediately("expand axis=horizontal what=in;"); } private static final String NAME = "Expand Horizontal"; public String getName() { return NAME; } public String getAltName() { return "Expand Horizontal Alignment"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Expand view horizontally"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("ExpandHorizontal16.gif"); } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_2, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return true; } }
3,002
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ExportAlignmentCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ExportAlignmentCommand.java
/* * ExportAlignmentCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ChooseFileDialog; import jloda.swing.util.FastaFileFilter; import jloda.swing.util.ProgramProperties; import jloda.swing.util.ResourceManager; import jloda.swing.window.NotificationsInSwing; import jloda.util.FileUtils; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.alignment.AlignmentViewer; import megan.alignment.gui.Alignment; import megan.alignment.gui.SelectedBlock; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; /** * save data command * Daniel Huson, 11.2010 */ public class ExportAlignmentCommand extends CommandBase implements ICommand { public String getSyntax() { return "export alignment file=<filename> [what={all|selected}];"; } public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("export alignment file="); String fileName = np.getAbsoluteFileName(); boolean saveAll = true; if (np.peekMatchIgnoreCase("what")) { np.matchIgnoreCase("what="); saveAll = np.getWordMatchesIgnoringCase("selected all").equalsIgnoreCase("all"); } np.matchIgnoreCase(";"); try { AlignmentViewer viewer = (AlignmentViewer) getViewer(); if (saveAll) { System.err.println("Exporting complete alignment to: " + fileName); Alignment alignment = viewer.getAlignment(); String string = alignment.toFastA(); Writer w = new FileWriter(fileName); w.write(string); w.close(); } else { System.err.println("Exporting selected alignment to: " + fileName); Writer w = new FileWriter(fileName); w.write(viewer.getAlignmentViewerPanel().getSelectedAlignment()); w.close(); } } catch (IOException e) { NotificationsInSwing.showError("Export Alignment failed: " + e.getMessage()); } } public void actionPerformed(ActionEvent event) { File lastOpenFile = ProgramProperties.getFile("SaveAlignment"); String fileName = ((AlignmentViewer) getViewer()).getAlignment().getName(); if (fileName == null) fileName = "Untitled"; else fileName = StringUtils.toCleanName(fileName); if (lastOpenFile != null) { fileName = new File(lastOpenFile.getParent(), fileName).getPath(); } fileName = FileUtils.replaceFileSuffix(fileName, "-alignment.fasta"); File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), new File(fileName), new FastaFileFilter(), new FastaFileFilter(), event, "Save alignment file", ".fasta"); if (file != null) { if (FileUtils.getFileSuffix(file.getName()) == null) file = FileUtils.replaceFileSuffix(file, ".txt"); ProgramProperties.put("SaveAlignment", file); SelectedBlock selectedBlock = ((AlignmentViewer) getViewer()).getSelectedBlock(); executeImmediately("export alignment file='" + file.getPath() + "' what=" + (selectedBlock == null || !selectedBlock.isSelected() ? "all" : "selected") + ";"); } } public boolean isApplicable() { return ((AlignmentViewer) getViewer()).getAlignment().getLength() > 0; } public String getName() { return "Alignment..."; } public String getAltName() { return "Export Alignment..."; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Export16.gif"); } public String getDescription() { return "Save alignment to a file"; } public boolean isCritical() { return false; } public KeyStroke getAcceleratorKey() { return KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()); } }
4,938
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ShowAminoAcidsCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ShowAminoAcidsCommand.java
/* * ShowAminoAcidsCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.alignment.AlignmentViewer; import javax.swing.*; import java.awt.event.ActionEvent; /** * command * Daniel Huson, 8.2011 */ public class ShowAminoAcidsCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { AlignmentViewer viewer = (AlignmentViewer) getViewer(); return viewer.isShowAminoAcids(); } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set showAminoAcids="); boolean value = np.getBoolean(); np.matchIgnoreCase(";"); AlignmentViewer viewer = (AlignmentViewer) getViewer(); viewer.setShowAminoAcids(value); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set showAminoAcids={false|true};"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { execute("set showAminoAcids=true;"); } private static final String NAME = "Show Amino Acids"; public String getName() { return NAME; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Show amino-acids in alignment"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("AminoAcids16.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() { AlignmentViewer viewer = (AlignmentViewer) getViewer(); return viewer.isAllowAminoAcids() && !viewer.isShowAminoAcids(); } }
3,350
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
CopyReferenceCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/CopyReferenceCommand.java
/* * CopyReferenceCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.alignment.AlignmentViewer; import megan.commands.clipboard.ClipboardBase; import javax.swing.*; import java.awt.event.ActionEvent; public class CopyReferenceCommand extends ClipboardBase implements ICommand { public String getSyntax() { return null; } public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { AlignmentViewer viewer = (AlignmentViewer) getViewer(); viewer.getAlignmentViewerPanel().copyReference(); } public boolean isApplicable() { AlignmentViewer viewer = (AlignmentViewer) getViewer(); return viewer.getSelectedBlock().isSelected(); } public String getName() { return "Copy Reference"; } public String getDescription() { return "Copy selected reference sequence to clipboard"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/Copy16.gif"); } public boolean isCritical() { return true; } public KeyStroke getAcceleratorKey() { return null; } }
2,065
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/alignment/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.alignment.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.commands.CommandBase; import javax.swing.*; import java.awt.event.ActionEvent; public class ContractHorizontalCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { executeImmediately("expand axis=horizontal what=out;"); } public boolean isApplicable() { return true; } public String getName() { return "Contract Horizontal"; } public String getAltName() { return "Contract Horizontal Alignment"; } public ImageIcon getIcon() { return ResourceManager.getIcon("ContractHorizontal16.gif"); } public String getDescription() { return "Contract view horizontally"; } public boolean isCritical() { return true; } }
1,878
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ZoomCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ZoomCommand.java
/* * ZoomCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.util.parse.NexusStreamParser; import megan.alignment.AlignmentViewer; import javax.swing.*; import java.awt.event.ActionEvent; /** * font size * Daniel Huson, 8.2011 */ public class ZoomCommand extends CommandBase implements ICommand { /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("expand axis="); String axis = np.getWordMatchesIgnoringCase("horizontal vertical both"); np.matchIgnoreCase("what="); String what; if (np.peekMatchAnyTokenIgnoreCase("in out reset selection fit")) what = np.getWordMatchesIgnoringCase("in out reset selection fit"); else what = "" + (float) np.getDouble(); np.matchIgnoreCase(";"); AlignmentViewer viewer = (AlignmentViewer) getViewer(); viewer.getAlignmentViewerPanel().zoom(axis, what, null); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "expand axis={horizontal|vertical|both} what={in|out|reset|selection|fit|<number>};"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { } public String getName() { return "Zoom"; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Zoom"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return true; } }
3,221
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ShowConsensusCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ShowConsensusCommand.java
/* * ShowConsensusCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.alignment.AlignmentViewer; import javax.swing.*; import java.awt.event.ActionEvent; /** * command * Daniel Huson, 8.2011 */ public class ShowConsensusCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { AlignmentViewer viewer = (AlignmentViewer) getViewer(); return viewer.getAlignmentViewerPanel().isShowConsensus(); } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set show-consensus="); boolean value = np.getBoolean(); np.matchIgnoreCase(";"); AlignmentViewer viewer = (AlignmentViewer) getViewer(); viewer.getAlignmentViewerPanel().setShowConsensus(value); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set show-consensus={true|false};"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { execute("set show-consensus=" + !isSelected() + ";"); } private static final String NAME = "Show Consensus"; public String getName() { return NAME; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Show consensus sequence"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return ResourceManager.getIcon("ShowConsensusSequence16.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() { AlignmentViewer viewer = (AlignmentViewer) getViewer(); return viewer.getAlignment().getNumberOfSequences() > 0; } }
3,410
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/alignment/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.alignment.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.commands.CommandBase; import javax.swing.*; import java.awt.event.ActionEvent; public class ContractVerticalCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { executeImmediately("expand axis=vertical what=out;"); } public boolean isApplicable() { return true; } public String getName() { return "Contract Vertical"; } public String getAltName() { return "Contract Vertical Alignment"; } public ImageIcon getIcon() { return ResourceManager.getIcon("ContractVertical16.gif"); } public String getDescription() { return "Contract view vertically"; } public boolean isCritical() { return true; } }
1,864
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
ResetZoomCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/ResetZoomCommand.java
/* * ResetZoomCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.commands; import jloda.swing.commands.ICommand; import jloda.swing.util.ResourceManager; import jloda.util.parse.NexusStreamParser; import megan.commands.CommandBase; import javax.swing.*; import java.awt.event.ActionEvent; public class ResetZoomCommand extends CommandBase implements ICommand { public String getSyntax() { return null; } public void apply(NexusStreamParser np) { } public void actionPerformed(ActionEvent event) { executeImmediately("expand axis=vertical what=fit;"); } public boolean isApplicable() { return true; } public String getName() { return "Reset Zoom"; } public ImageIcon getIcon() { return ResourceManager.getIcon("sun/AlignJustifyHorizontal16.gif"); } public String getDescription() { return "Reset"; } public boolean isCritical() { return true; } }
1,748
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetAminoAcidColorSchemeCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/SetAminoAcidColorSchemeCommand.java
/* * SetAminoAcidColorSchemeCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICommand; import jloda.swing.util.ProgramProperties; import jloda.util.StringUtils; import jloda.util.parse.NexusStreamParser; import megan.alignment.AlignmentViewer; import megan.alignment.gui.colors.ColorSchemeAminoAcids; import javax.swing.*; import java.awt.event.ActionEvent; /** * command * Daniel Huson, 4.2012 */ public class SetAminoAcidColorSchemeCommand extends CommandBase implements ICommand { /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set aminoAcidColors="); String value = np.getWordMatchesIgnoringCase(StringUtils.toString(ColorSchemeAminoAcids.getNames(), " ")); np.matchIgnoreCase(";"); AlignmentViewer viewer = (AlignmentViewer) getViewer(); viewer.setAminoAcidColoringScheme(value); // the following forces re-coloring: viewer.setShowAminoAcids(viewer.isShowAminoAcids()); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set aminoAcidColors=[" + StringUtils.toString(ColorSchemeAminoAcids.getNames(), "|") + "];"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { String choice = ProgramProperties.get("AminoAcidColorScheme", ColorSchemeAminoAcids.NAMES.Default.toString()); String result = (String) JOptionPane.showInputDialog(getViewer().getFrame(), "Choose amino acid color scheme", "Choose colors", JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon(), ColorSchemeAminoAcids.getNames(), choice); if (result != null) { result = result.trim(); if (result.length() > 0) { ProgramProperties.put("AminoAcidColorScheme", result); execute("set aminoAcidColors='" + result + "';"); } } } private static final String NAME = "Set Amino Acid Colors..."; public String getName() { return NAME; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Set the color scheme for amino acids"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return true; } }
3,997
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z
SetColorMatchesVsReferenceCommand.java
/FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/alignment/commands/SetColorMatchesVsReferenceCommand.java
/* * SetColorMatchesVsReferenceCommand.java Copyright (C) 2024 Daniel H. Huson * * (Some files contain contributions from other authors, who are then mentioned separately.) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package megan.alignment.commands; import jloda.swing.commands.CommandBase; import jloda.swing.commands.ICheckBoxCommand; import jloda.swing.util.ProgramProperties; import jloda.util.parse.NexusStreamParser; import megan.alignment.AlignmentViewer; import javax.swing.*; import java.awt.event.ActionEvent; /** * command * Daniel Huson, 8.2011 */ public class SetColorMatchesVsReferenceCommand extends CommandBase implements ICheckBoxCommand { public boolean isSelected() { AlignmentViewer viewer = (AlignmentViewer) getViewer(); return viewer.getAlignmentViewerPanel().getAlignmentPanel().isColorMatchesVsReference(); } /** * parses the given command and executes it */ @Override public void apply(NexusStreamParser np) throws Exception { np.matchIgnoreCase("set colorMatchesVsReference="); boolean value = np.getBoolean(); np.matchIgnoreCase(";"); AlignmentViewer viewer = (AlignmentViewer) getViewer(); viewer.getAlignmentViewerPanel().getAlignmentPanel().setColorMatchesVsReference(value); ProgramProperties.put("ColorMatchesVsReference", value); viewer.repaint(); } /** * get command-line usage description * * @return usage */ @Override public String getSyntax() { return "set colorMatchesVsReference={true|false};"; } /** * action to be performed * */ @Override public void actionPerformed(ActionEvent ev) { execute("set colorMatchesVsReference=" + (!isSelected()) + ";"); } private static final String NAME = "Matches Vs Reference"; public String getName() { return NAME; } /** * get description to be used as a tooltip * * @return description */ public String getDescription() { return "Color letters that match the reference sequence"; } /** * get icon to be used in menu or button * * @return icon */ public ImageIcon getIcon() { return null; } /** * gets the accelerator key to be used in menu * * @return accelerator key */ public KeyStroke getAcceleratorKey() { return null; } /** * is this a critical command that can only be executed when no other command is running? * * @return true, if critical */ public boolean isCritical() { return true; } /** * is the command currently applicable? Used to set enable state of command * * @return true, if command can be applied */ public boolean isApplicable() { return true; } }
3,488
Java
.java
husonlab/megan-ce
62
21
18
2016-05-09T10:55:38Z
2024-02-22T23:23:42Z