diff --git a/.gitattributes b/.gitattributes index 196ded22fd..5228d268be 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,5 @@ # Set the default behavior, in case people don't have core.autocrlf set. +# Set * text=auto # Explicitly declare text files you want to always be normalized and converted diff --git a/README.md b/README.md index 9ff33d976b..bbd8d9b3e8 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,17 @@ If you are using Maven you can add the BioJava repository by adding the followin ``` +### Quick Demo + +on Linux, Mac, or in (git-bash)[https://gitforwindows.org/] run + +```bash + +mvn install +bin/biojava.sh +``` + + ### Snapshot builds To use the latest builds from BioJava, you can add the following config your project's pom.xml: diff --git a/bin/biojava.sh b/bin/biojava.sh new file mode 100755 index 0000000000..b786b11915 --- /dev/null +++ b/bin/biojava.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash + +# this runs any main function in the source tree. +# to change the class to be run +# EXECMAIN=org.biojava.not.demo.main bin/biojava.sh +mkdir -p target/lib/ && { +ln -s 2>/dev/null $PWD/*/target{,/lib}/*jar target/lib +cp 2>/dev/null -as $PWD/*/src/main/resources/* target/ +} + +set -fx +JDIR=$PWD/$(dirname $0)/../ +pushd target +exec java -classpath "$JDIR/target/*:$JDIR/target/lib/*" ${EXECMAIN:=demo.DemoSixFrameTranslation} "$@" +popd \ No newline at end of file diff --git a/biojava-aa-prop/pom.xml b/biojava-aa-prop/pom.xml index c8da170664..2869d2f272 100644 --- a/biojava-aa-prop/pom.xml +++ b/biojava-aa-prop/pom.xml @@ -20,15 +20,7 @@ - - org.apache.maven.plugins - maven-jar-plugin - - - demo/** - - - + org.apache.maven.plugins diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/AminoAcidProperties.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/AminoAcidProperties.java index 896e0cb37a..fb52a2d410 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/AminoAcidProperties.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/AminoAcidProperties.java @@ -43,7 +43,7 @@ public class AminoAcidProperties { * @param aa The one-letter amino acid code * @return true if amino acid is charged */ - public static final boolean isCharged(char aa) { + public static boolean isCharged(char aa) { if (negChargedAAs.contains(String.valueOf(aa))) { return true; } @@ -60,7 +60,7 @@ else if (posChargedAAs.contains(String.valueOf(aa))) { * @param aa The one-letter amino acid code * @return the charge of amino acid (1 if positively charged, -1 if negatively charged, 0 if not charged) */ - public static final int getChargeOfAminoAcid(char aa) { + public static int getChargeOfAminoAcid(char aa) { if (negChargedAAs.contains(String.valueOf(aa))) { return -1; } @@ -76,7 +76,7 @@ else if (posChargedAAs.contains(String.valueOf(aa))) { * @param aa The one-letter amino acid code * @return true if amino acid is polar */ - public static final boolean isPolar(char aa) { + public static boolean isPolar(char aa) { if (polarAAs.contains(String.valueOf(aa))) { return true; } @@ -89,7 +89,7 @@ public static final boolean isPolar(char aa) { * @param aa The one-letter amino acid code * @return the polarity of amino acid (1 if polar, 0 if not polar) */ - public static final int getPolarityOfAminoAcid(char aa) { + public static int getPolarityOfAminoAcid(char aa) { if (polarAAs.contains(String.valueOf(aa))) { return 1; } diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/CommandPrompt.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/CommandPrompt.java index db9d1d7b69..53206e13c3 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/CommandPrompt.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/CommandPrompt.java @@ -31,7 +31,6 @@ import java.io.File; import java.io.FileInputStream; -import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -95,8 +94,8 @@ public static void run(String[] args) throws Exception{ /* * Parse input arguments */ - List propertyList = new ArrayList(); - List specificList = new ArrayList(); + List propertyList = new ArrayList<>(); + List specificList = new ArrayList<>(); String inputLocation = null; String outputLocation = null; String aminoAcidCompositionLocation = null; @@ -179,15 +178,15 @@ private static LinkedHashMap readInputFile(String input } LinkedHashMap ret; if ( inputLocation.toLowerCase().contains(".gb")) { - GenbankReader genbankReader = new GenbankReader( - inStream, new GenericGenbankHeaderParser(), + GenbankReader genbankReader = new GenbankReader<>( + inStream, new GenericGenbankHeaderParser<>(), new ProteinSequenceCreator(set)); ret = genbankReader.process(); } else { - FastaReader fastaReader = new FastaReader( - inStream, new GenericFastaHeaderParser(), + FastaReader fastaReader = new FastaReader<>( + inStream, new GenericFastaHeaderParser<>(), new ProteinSequenceCreator(set)); ret = fastaReader.process(); @@ -198,9 +197,9 @@ private static LinkedHashMap readInputFile(String input public enum PropertyName{MolecularWeight, Absorbance_True, Absorbance_False, ExtinctionCoefficient_True, ExtinctionCoefficient_False, InstabilityIndex, ApliphaticIndex, AverageHydropathyValue, IsoelectricPoint, NetCharge_pH_7, A, R, N, D, C, E, Q, G, H, I, L, - K, M, F, P, S, T, W, Y, V}; + K, M, F, P, S, T, W, Y, V} - private static void printHeader(PrintStream output, List propertyList, List specificList, String delimiter) throws IOException{ + private static void printHeader(PrintStream output, List propertyList, List specificList, String delimiter) { int specificCount = 0; /* * 1 Molecular weight @@ -214,7 +213,7 @@ private static void printHeader(PrintStream output, List propertyList * 9 Composition of the 20 standard amino acid * 0 Composition of the specific amino acid */ - List sList = new ArrayList(); + List sList = new ArrayList<>(); sList.add("SequenceName"); for(Character c:propertyList){ switch(c){ @@ -238,7 +237,7 @@ private static void printHeader(PrintStream output, List propertyList sList.add(PropertyName.T.toString()); sList.add(PropertyName.W.toString()); sList.add(PropertyName.Y.toString()); sList.add(PropertyName.V.toString()); break; - case '0': sList.add("" + specificList.get(specificCount++)); break; + case '0': sList.add(String.valueOf(specificList.get(specificCount++))); break; } } for(int i = 0; i < sList.size(); i++){ @@ -272,19 +271,16 @@ private static void compute(PrintStream output, String header, String sequence, }else{ sequence = Utils.checkSequence(sequence); pSequence = new ProteinSequence(sequence); - aaSet = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + aaSet = AminoAcidCompoundSet.aminoAcidCompoundSet; } IPeptideProperties pp = new PeptidePropertiesImpl(); int specificCount = 0; - List dList = new ArrayList(); + List dList = new ArrayList<>(); for(Character c:propertyList){ switch(c){ case '1': - if(aaTable == null) - dList.add(pp.getMolecularWeight(pSequence)); - else - dList.add(pp.getMolecularWeight(pSequence)); + dList.add(pp.getMolecularWeight(pSequence)); break; case '2': dList.add(pp.getAbsorbance(pSequence, true)); @@ -323,7 +319,7 @@ private static void compute(PrintStream output, String header, String sequence, dList.add(aaCompound2Double.get(Constraints.Y)); dList.add(aaCompound2Double.get(Constraints.V)); break; - case '0': dList.add(pp.getEnrichment(pSequence, aaSet.getCompoundForString("" + specificList.get(specificCount++)))); break; + case '0': dList.add(pp.getEnrichment(pSequence, aaSet.getCompoundForString(String.valueOf(specificList.get(specificCount++))))); break; } } output.print(header.replace(delimiter, "_")); diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Constraints.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Constraints.java index f223eaca23..e300da2e7f 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Constraints.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Constraints.java @@ -41,37 +41,37 @@ * @see IPeptideProperties */ public class Constraints { - private static AminoAcidCompoundSet aaSet = new AminoAcidCompoundSet(); + private static final AminoAcidCompoundSet aaSet = new AminoAcidCompoundSet(); //A, R, N, D, C, E, Q, G, H, I, L, K, M, F, P, S, T, W, Y, V - public static AminoAcidCompound A = aaSet.getCompoundForString("A"); - public static AminoAcidCompound R = aaSet.getCompoundForString("R"); - public static AminoAcidCompound N = aaSet.getCompoundForString("N"); - public static AminoAcidCompound D = aaSet.getCompoundForString("D"); - public static AminoAcidCompound C = aaSet.getCompoundForString("C"); - public static AminoAcidCompound E = aaSet.getCompoundForString("E"); - public static AminoAcidCompound Q = aaSet.getCompoundForString("Q"); - public static AminoAcidCompound G = aaSet.getCompoundForString("G"); - public static AminoAcidCompound H = aaSet.getCompoundForString("H"); - public static AminoAcidCompound I = aaSet.getCompoundForString("I"); - public static AminoAcidCompound L = aaSet.getCompoundForString("L"); - public static AminoAcidCompound K = aaSet.getCompoundForString("K"); - public static AminoAcidCompound M = aaSet.getCompoundForString("M"); - public static AminoAcidCompound F = aaSet.getCompoundForString("F"); - public static AminoAcidCompound P = aaSet.getCompoundForString("P"); - public static AminoAcidCompound S = aaSet.getCompoundForString("S"); - public static AminoAcidCompound T = aaSet.getCompoundForString("T"); - public static AminoAcidCompound W = aaSet.getCompoundForString("W"); - public static AminoAcidCompound Y = aaSet.getCompoundForString("Y"); - public static AminoAcidCompound V = aaSet.getCompoundForString("V"); + public static final AminoAcidCompound A = aaSet.getCompoundForString("A"); + public static final AminoAcidCompound R = aaSet.getCompoundForString("R"); + public static final AminoAcidCompound N = aaSet.getCompoundForString("N"); + public static final AminoAcidCompound D = aaSet.getCompoundForString("D"); + public static final AminoAcidCompound C = aaSet.getCompoundForString("C"); + public static final AminoAcidCompound E = aaSet.getCompoundForString("E"); + public static final AminoAcidCompound Q = aaSet.getCompoundForString("Q"); + public static final AminoAcidCompound G = aaSet.getCompoundForString("G"); + public static final AminoAcidCompound H = aaSet.getCompoundForString("H"); + public static final AminoAcidCompound I = aaSet.getCompoundForString("I"); + public static final AminoAcidCompound L = aaSet.getCompoundForString("L"); + public static final AminoAcidCompound K = aaSet.getCompoundForString("K"); + public static final AminoAcidCompound M = aaSet.getCompoundForString("M"); + public static final AminoAcidCompound F = aaSet.getCompoundForString("F"); + public static final AminoAcidCompound P = aaSet.getCompoundForString("P"); + public static final AminoAcidCompound S = aaSet.getCompoundForString("S"); + public static final AminoAcidCompound T = aaSet.getCompoundForString("T"); + public static final AminoAcidCompound W = aaSet.getCompoundForString("W"); + public static final AminoAcidCompound Y = aaSet.getCompoundForString("Y"); + public static final AminoAcidCompound V = aaSet.getCompoundForString("V"); - public static Map aa2ExtinctionCoefficient = new HashMap(); - public static Map aa2MolecularWeight = new HashMap(); - public static Map aa2Hydrophathicity = new HashMap(); - public static Map aa2PKa = new HashMap(); - public static Map diAA2Instability = new HashMap(); + public static final Map aa2ExtinctionCoefficient = new HashMap<>(); + public static final Map aa2MolecularWeight = new HashMap<>(); + public static final Map aa2Hydrophathicity = new HashMap<>(); + public static final Map aa2PKa = new HashMap<>(); + public static final Map diAA2Instability = new HashMap<>(); - public static Map aa2NTerminalPka = new HashMap(); - public static Map aa2CTerminalPka = new HashMap(); + public static final Map aa2NTerminalPka = new HashMap<>(); + public static final Map aa2CTerminalPka = new HashMap<>(); static{ initMolecularWeight(); @@ -287,7 +287,7 @@ private static void initInstability(){ SingleLetterAACode[] aa = SingleLetterAACode.values(); for(int i = 0; i < aa.length; i++){ for(int j = 0; j < aa.length; j++){ - diAA2Instability.put("" + aa[i] + aa[j], instability[i][j]); + diAA2Instability.put(String.valueOf(aa[i]) + aa[j], instability[i][j]); } } } diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/IPeptideProperties.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/IPeptideProperties.java index babe1e54d8..f8eacb7269 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/IPeptideProperties.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/IPeptideProperties.java @@ -61,7 +61,7 @@ public interface IPeptideProperties{ * @return the total molecular weight of sequence + weight of water molecule * @see ProteinSequence */ - public double getMolecularWeight(ProteinSequence sequence); + double getMolecularWeight(ProteinSequence sequence); /** * Returns the molecular weight of sequence. The sequence argument must be a protein sequence consisting of only non-ambiguous characters. @@ -80,7 +80,7 @@ public interface IPeptideProperties{ * @throws FileNotFoundException * thrown if either elementMassFile or aminoAcidCompositionFile are not found */ - public double getMolecularWeight(ProteinSequence sequence, File aminoAcidCompositionFile) throws JAXBException, FileNotFoundException; + double getMolecularWeight(ProteinSequence sequence, File aminoAcidCompositionFile) throws JAXBException, FileNotFoundException; /** * Returns the molecular weight of sequence. The sequence argument must be a protein sequence consisting of only non-ambiguous characters. @@ -99,7 +99,7 @@ public interface IPeptideProperties{ * @throws FileNotFoundException * thrown if either elementMassFile or aminoAcidCompositionFile are not found */ - public double getMolecularWeight(ProteinSequence sequence, File elementMassFile, File aminoAcidCompositionFile) + double getMolecularWeight(ProteinSequence sequence, File elementMassFile, File aminoAcidCompositionFile) throws JAXBException, FileNotFoundException; /** @@ -114,7 +114,7 @@ public double getMolecularWeight(ProteinSequence sequence, File elementMassFile, * a amino acid composition table obtained by calling IPeptideProperties.obtainAminoAcidCompositionTable * @return the total molecular weight of sequence + weight of water molecule */ - public double getMolecularWeightBasedOnXML(ProteinSequence sequence, AminoAcidCompositionTable aminoAcidCompositionTable); + double getMolecularWeightBasedOnXML(ProteinSequence sequence, AminoAcidCompositionTable aminoAcidCompositionTable); /** * This method would initialize amino acid composition table based on the input xml files and stores the table for usage in future calls to @@ -129,7 +129,7 @@ public double getMolecularWeight(ProteinSequence sequence, File elementMassFile, * @throws FileNotFoundException * thrown if either elementMassFile or aminoAcidCompositionFile are not found */ - public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File aminoAcidCompositionFile) + AminoAcidCompositionTable obtainAminoAcidCompositionTable(File aminoAcidCompositionFile) throws JAXBException, FileNotFoundException; /** @@ -146,7 +146,7 @@ public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File aminoAcidC * @throws FileNotFoundException * thrown if either elementMassFile or aminoAcidCompositionFile are not found */ - public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMassFile, File aminoAcidCompositionFile) + AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMassFile, File aminoAcidCompositionFile) throws JAXBException, FileNotFoundException; /** @@ -166,7 +166,7 @@ public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMas * @return the extinction coefficient of sequence * @see ProteinSequence */ - public double getExtinctionCoefficient(ProteinSequence sequence, boolean assumeCysReduced); + double getExtinctionCoefficient(ProteinSequence sequence, boolean assumeCysReduced); /** * Returns the absorbance (optical density) of sequence. The sequence argument @@ -182,7 +182,7 @@ public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMas * @return the absorbance (optical density) of sequence * @see ProteinSequence */ - public double getAbsorbance(ProteinSequence sequence, boolean assumeCysReduced); + double getAbsorbance(ProteinSequence sequence, boolean assumeCysReduced); /** * Returns the instability index of sequence. The sequence argument must be @@ -196,7 +196,7 @@ public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMas * @return the instability index of sequence * @see ProteinSequence */ - public double getInstabilityIndex(ProteinSequence sequence); + double getInstabilityIndex(ProteinSequence sequence); /** * Returns the apliphatic index of sequence. The sequence argument must be a @@ -213,7 +213,7 @@ public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMas * @return the aliphatic index of sequence * @see ProteinSequence */ - public double getApliphaticIndex(ProteinSequence sequence); + double getApliphaticIndex(ProteinSequence sequence); /** * Returns the average hydropathy value of sequence. The sequence argument @@ -229,7 +229,7 @@ public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMas * @return the average hydropathy value of sequence * @see ProteinSequence */ - public double getAvgHydropathy(ProteinSequence sequence); + double getAvgHydropathy(ProteinSequence sequence); /** * Returns the isoelectric point of sequence. The sequence argument must be @@ -250,9 +250,9 @@ public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMas * @return the isoelectric point of sequence * @see ProteinSequence */ - public double getIsoelectricPoint(ProteinSequence sequence, boolean useExpasyValues); + double getIsoelectricPoint(ProteinSequence sequence, boolean useExpasyValues); - public double getIsoelectricPoint(ProteinSequence seuqence); + double getIsoelectricPoint(ProteinSequence seuqence); /** * Returns the net charge of sequence at pH 7. The sequence argument must be @@ -274,11 +274,11 @@ public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMas * @return the net charge of sequence at given pHPoint * @see ProteinSequence */ - public double getNetCharge(ProteinSequence sequence, boolean useExpasyValues, double pHPoint); + double getNetCharge(ProteinSequence sequence, boolean useExpasyValues, double pHPoint); - public double getNetCharge(ProteinSequence sequence, boolean useExpasyValues); + double getNetCharge(ProteinSequence sequence, boolean useExpasyValues); - public double getNetCharge(ProteinSequence sequence); + double getNetCharge(ProteinSequence sequence); /** * Returns the composition of specified amino acid in the sequence. The @@ -296,7 +296,7 @@ public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMas * @see ProteinSequence * @see AminoAcidCompound */ - public double getEnrichment(ProteinSequence sequence, AminoAcidCompound aminoAcidCode); + double getEnrichment(ProteinSequence sequence, AminoAcidCompound aminoAcidCode); /** * Returns the composition of the 20 standard amino acid in the sequence. @@ -311,5 +311,5 @@ public AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMas * @see ProteinSequence * @see AminoAcidCompound */ - public Map getAAComposition(ProteinSequence sequence); + Map getAAComposition(ProteinSequence sequence); } diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/PeptideProperties.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/PeptideProperties.java index b0918bf559..473022a0a7 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/PeptideProperties.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/PeptideProperties.java @@ -58,13 +58,13 @@ public enum SingleLetterAACode { W, C, M, H, Y, F, Q, N, I, R, D, P, T, K, E, V, /** * Contains the 20 standard AA code in a set */ - public static Set standardAASet; + public static final Set standardAASet; /** * To initialize the standardAASet */ static{ - standardAASet = new HashSet(); + standardAASet = new HashSet<>(); for(SingleLetterAACode c:SingleLetterAACode.values()) standardAASet.add(c.toString().charAt(0)); } @@ -78,7 +78,7 @@ public enum SingleLetterAACode { W, C, M, H, Y, F, Q, N, I, R, D, P, T, K, E, V, * a protein sequence consisting of non-ambiguous characters only * @return the total molecular weight of sequence + weight of water molecule */ - public static final double getMolecularWeight(String sequence){ + public static double getMolecularWeight(String sequence){ sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -109,7 +109,7 @@ public static final double getMolecularWeight(String sequence){ * @throws JAXBException * thrown if unable to properly parse either elementMassFile or aminoAcidCompositionFile */ - public static final double getMolecularWeight(String sequence, File elementMassFile, File aminoAcidCompositionFile) + public static double getMolecularWeight(String sequence, File elementMassFile, File aminoAcidCompositionFile) throws FileNotFoundException, JAXBException{ sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; @@ -140,7 +140,7 @@ public static final double getMolecularWeight(String sequence, File elementMassF * @throws FileNotFoundException * thrown if either elementMassFile or aminoAcidCompositionFile are not found */ - public static final double getMolecularWeight(String sequence, File aminoAcidCompositionFile) throws FileNotFoundException, JAXBException{ + public static double getMolecularWeight(String sequence, File aminoAcidCompositionFile) throws FileNotFoundException, JAXBException{ sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -166,7 +166,7 @@ public static final double getMolecularWeight(String sequence, File aminoAcidCom * @throws FileNotFoundException * thrown if either elementMassFile or aminoAcidCompositionFile are not found */ - public static final AminoAcidCompositionTable obtainAminoAcidCompositionTable(File aminoAcidCompositionFile) + public static AminoAcidCompositionTable obtainAminoAcidCompositionTable(File aminoAcidCompositionFile) throws JAXBException, FileNotFoundException{ IPeptideProperties pp = new PeptidePropertiesImpl(); return pp.obtainAminoAcidCompositionTable(aminoAcidCompositionFile); @@ -186,7 +186,7 @@ public static final AminoAcidCompositionTable obtainAminoAcidCompositionTable(Fi * @throws FileNotFoundException * thrown if either elementMassFile or aminoAcidCompositionFile are not found */ - public static final AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMassFile, File aminoAcidCompositionFile) + public static AminoAcidCompositionTable obtainAminoAcidCompositionTable(File elementMassFile, File aminoAcidCompositionFile) throws JAXBException, FileNotFoundException{ IPeptideProperties pp = new PeptidePropertiesImpl(); return pp.obtainAminoAcidCompositionTable(elementMassFile, aminoAcidCompositionFile); @@ -230,7 +230,7 @@ public static double getMolecularWeightBasedOnXML(String sequence, AminoAcidComp * true if Cys are assumed to be reduced and false if Cys are assumed to form cystines * @return the absorbance (optical density) of sequence */ - public static final double getAbsorbance(String sequence, boolean assumeCysReduced){ + public static double getAbsorbance(String sequence, boolean assumeCysReduced){ sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -259,7 +259,7 @@ public static final double getAbsorbance(String sequence, boolean assumeCysReduc * assumed to form cystines * @return the extinction coefficient of sequence */ - public static final double getExtinctionCoefficient(String sequence, boolean assumeCysReduced) { + public static double getExtinctionCoefficient(String sequence, boolean assumeCysReduced) { sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -283,7 +283,7 @@ public static final double getExtinctionCoefficient(String sequence, boolean ass * a protein sequence consisting of non-ambiguous characters only * @return the instability index of sequence */ - public static final double getInstabilityIndex(String sequence) { + public static double getInstabilityIndex(String sequence) { sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -310,7 +310,7 @@ public static final double getInstabilityIndex(String sequence) { * a protein sequence consisting of non-ambiguous characters only * @return the aliphatic index of sequence */ - public static final double getApliphaticIndex(String sequence) { + public static double getApliphaticIndex(String sequence) { sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -337,7 +337,7 @@ public static final double getApliphaticIndex(String sequence) { * a protein sequence consisting of non-ambiguous characters only * @return the average hydropathy value of sequence */ - public static final double getAvgHydropathy(String sequence) { + public static double getAvgHydropathy(String sequence) { sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -369,7 +369,7 @@ public static final double getAvgHydropathy(String sequence) { * whether to use Expasy values (Default) or Innovagen values * @return the isoelectric point of sequence */ - public static final double getIsoelectricPoint(String sequence, boolean useExpasyValues) { + public static double getIsoelectricPoint(String sequence, boolean useExpasyValues) { sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -382,7 +382,7 @@ public static final double getIsoelectricPoint(String sequence, boolean useExpas return pp.getIsoelectricPoint(pSequence, useExpasyValues); } - public static final double getIsoelectricPoint(String sequence){ + public static double getIsoelectricPoint(String sequence){ return getIsoelectricPoint(sequence, true); } @@ -405,7 +405,7 @@ public static final double getIsoelectricPoint(String sequence){ * the pH value to use for computation of the net charge. Default at 7. * @return the net charge of sequence at given pHPoint */ - public static final double getNetCharge(String sequence, boolean useExpasyValues, double pHPoint){ + public static double getNetCharge(String sequence, boolean useExpasyValues, double pHPoint){ sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -418,11 +418,11 @@ public static final double getNetCharge(String sequence, boolean useExpasyValues return pp.getNetCharge(pSequence, useExpasyValues, pHPoint); } - public static final double getNetCharge(String sequence, boolean useExpasyValues) { + public static double getNetCharge(String sequence, boolean useExpasyValues) { return getNetCharge(sequence, useExpasyValues, 7.0); } - public static final double getNetCharge(String sequence){ + public static double getNetCharge(String sequence){ return getNetCharge(sequence, true); } @@ -441,7 +441,7 @@ public static final double getNetCharge(String sequence){ * @return the composition of specified amino acid in the sequence * @see SingleLetterAACode */ - public static final double getEnrichment(String sequence, SingleLetterAACode aminoAcidCode) { + public static double getEnrichment(String sequence, SingleLetterAACode aminoAcidCode) { return getEnrichment(sequence, aminoAcidCode.toString()); } @@ -459,7 +459,7 @@ public static final double getEnrichment(String sequence, SingleLetterAACode ami * the code of the amino acid to compute * @return the composition of specified amino acid in the sequence */ - public static final double getEnrichment(String sequence, char aminoAcidCode){ + public static double getEnrichment(String sequence, char aminoAcidCode){ return getEnrichment(sequence, aminoAcidCode); } @@ -477,7 +477,7 @@ public static final double getEnrichment(String sequence, char aminoAcidCode){ * the code of the amino acid to compute * @return the composition of specified amino acid in the sequence */ - public static final double getEnrichment(String sequence, String aminoAcidCode){ + public static double getEnrichment(String sequence, String aminoAcidCode){ sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -503,7 +503,7 @@ public static final double getEnrichment(String sequence, String aminoAcidCode){ * @return the composition of the 20 standard amino acid in the sequence * @see AminoAcidCompound */ - public static final Map getAAComposition(String sequence) { + public static Map getAAComposition(String sequence) { sequence = Utils.checkSequence(sequence); ProteinSequence pSequence = null; try { @@ -527,11 +527,11 @@ public static final Map getAAComposition(String seque * a protein sequence consisting of non-ambiguous characters only * @return the composition of the 20 standard amino acid in the sequence */ - public static final Map getAACompositionString(String sequence){ + public static Map getAACompositionString(String sequence){ Map aa2Composition = getAAComposition(sequence); - Map aaString2Composition = new HashMap(); - for(AminoAcidCompound aaCompound:aa2Composition.keySet()){ - aaString2Composition.put(aaCompound.getShortName(), aa2Composition.get(aaCompound)); + Map aaString2Composition = new HashMap<>(); + for(Map.Entry entry : aa2Composition.entrySet()){ + aaString2Composition.put(entry.getKey().getShortName(), entry.getValue()); } return aaString2Composition; } @@ -547,11 +547,11 @@ public static final Map getAACompositionString(String sequence){ * a protein sequence consisting of non-ambiguous characters only * @return the composition of the 20 standard amino acid in the sequence */ - public static final Map getAACompositionChar(String sequence){ + public static Map getAACompositionChar(String sequence){ Map aa2Composition = getAAComposition(sequence); - Map aaChar2Composition = new HashMap(); - for(AminoAcidCompound aaCompound:aa2Composition.keySet()){ - aaChar2Composition.put(aaCompound.getShortName().charAt(0), aa2Composition.get(aaCompound)); + Map aaChar2Composition = new HashMap<>(); + for(Map.Entry entry : aa2Composition.entrySet()){ + aaChar2Composition.put(entry.getKey().getShortName().charAt(0), entry.getValue()); } return aaChar2Composition; } @@ -564,7 +564,7 @@ public static final Map getAACompositionChar(String sequence) * a protein sequence consisting of non-ambiguous characters only * @return the array of charges of amino acids in the protein (1 if amino acid is positively charged, -1 if negatively charged, 0 if not charged) */ - public static final int[] getChargesOfAminoAcids(String sequence) { + public static int[] getChargesOfAminoAcids(String sequence) { int[] charges = new int[sequence.length()]; for ( int i=0; i < sequence.length(); i++ ) { char aa = sequence.toCharArray()[i]; @@ -580,7 +580,7 @@ public static final int[] getChargesOfAminoAcids(String sequence) { * a protein sequence consisting of non-ambiguous characters only * @return the array of polarity of amino acids in the protein (1 if amino acid is polar, 0 if not) */ - public static final int[] getPolarityOfAminoAcids(String sequence) { + public static int[] getPolarityOfAminoAcids(String sequence) { int[] polarity = new int[sequence.length()]; for ( int i=0; i < sequence.length(); i++ ) { char aa = sequence.toCharArray()[i]; diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/PeptidePropertiesImpl.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/PeptidePropertiesImpl.java index 98e14c6a83..fd45f81767 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/PeptidePropertiesImpl.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/PeptidePropertiesImpl.java @@ -210,7 +210,7 @@ private Map getExtinctAACount(ProteinSequence sequen } } AminoAcidCompoundSet aaSet = new AminoAcidCompoundSet(); - Map extinctAA2Count = new HashMap(); + Map extinctAA2Count = new HashMap<>(); //Ignore Case is always true extinctAA2Count.put(aaSet.getCompoundForString("W"), numW + smallW); extinctAA2Count.put(aaSet.getCompoundForString("C"), (int) (numC + smallC)); @@ -352,16 +352,16 @@ private double getIsoelectricPointInnovagen(ProteinSequence sequence){ {3.55, 7.50, 10.00},// Y {3.55, 7.50, 0.0}}; // Z - private final double PH_MIN = 0.0; /* minimum pH value */ - private final double PH_MAX = 14.0; /* maximum pH value */ - private final double MAXLOOP = 2000.0; /* maximum number of iterations */ - private final double EPSI = 0.0001; /* desired precision */ + private static final double PH_MIN = 0.0; /* minimum pH value */ + private static final double PH_MAX = 14.0; /* maximum pH value */ + private static final double MAXLOOP = 2000.0; /* maximum number of iterations */ + private static final double EPSI = 0.0001; /* desired precision */ private double exp10(double pka){ return Math.pow(10, pka); } - private double getIsoelectricPointExpasy(String sequence){ + private double getIsoelectricPointExpasy(CharSequence sequence){ // // Compute the amino-acid composition. // @@ -390,7 +390,7 @@ private double getIsoelectricPointExpasy(String sequence){ double phMax = PH_MAX; double phMid = 0.0; - double charge = 1.0; + double charge; for (int i = 0; i < MAXLOOP && (phMax - phMin) > EPSI; i++){ phMid = phMin + (phMax - phMin) / 2.0; @@ -532,7 +532,7 @@ private Map getChargedAACount(ProteinSequence sequen } } AminoAcidCompoundSet aaSet = new AminoAcidCompoundSet(); - Map chargedAA2Count = new HashMap(); + Map chargedAA2Count = new HashMap<>(); chargedAA2Count.put(aaSet.getCompoundForString("K"), numK); chargedAA2Count.put(aaSet.getCompoundForString("R"), numR); chargedAA2Count.put(aaSet.getCompoundForString("H"), numH); @@ -558,7 +558,7 @@ public double getEnrichment(ProteinSequence sequence, AminoAcidCompound aminoAci @Override public Map getAAComposition(ProteinSequence sequence) { int validLength = 0; - Map aa2Composition = new HashMap(); + Map aa2Composition = new HashMap<>(); AminoAcidCompoundSet aaSet = new AminoAcidCompoundSet(); for(AminoAcidCompound aa:aaSet.getAllCompounds()){ aa2Composition.put(aa, 0.0); diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Utils.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Utils.java index e69b083be7..bea1ab69db 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Utils.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Utils.java @@ -48,7 +48,7 @@ public class Utils { * @return * a value with the given number of decimal places. */ - public final static double roundToDecimals(double d, int c) { + public static double roundToDecimals(double d, int c) { if(c < 0) return d; double p = Math.pow(10,c); d = d * p; @@ -67,7 +67,7 @@ public final static double roundToDecimals(double d, int c) { * @return * true if invalid characters are found, else return false. */ - public final static boolean doesSequenceContainInvalidChar(String sequence, Set cSet){ + public static boolean doesSequenceContainInvalidChar(String sequence, Set cSet){ for(char c:sequence.toCharArray()){ if(!cSet.contains(c)) return true; } @@ -86,7 +86,7 @@ public final static boolean doesSequenceContainInvalidChar(String sequence, Set< * @return * the number of invalid characters in sequence. */ - public final static int getNumberOfInvalidChar(String sequence, Set cSet, boolean ignoreCase){ + public static int getNumberOfInvalidChar(String sequence, Set cSet, boolean ignoreCase){ int total = 0; char[] cArray; if(ignoreCase) cArray = sequence.toUpperCase().toCharArray(); @@ -109,8 +109,8 @@ public final static int getNumberOfInvalidChar(String sequence, Set c * @return * a new sequence with all invalid characters being replaced by '-'. */ - public final static String cleanSequence(String sequence, Set cSet){ - Set invalidCharSet = new HashSet(); + public static String cleanSequence(String sequence, Set cSet){ + Set invalidCharSet = new HashSet<>(); StringBuilder cleanSeq = new StringBuilder(); if(cSet == null) cSet = PeptideProperties.standardAASet; for(char c:sequence.toCharArray()){ @@ -125,7 +125,7 @@ public final static String cleanSequence(String sequence, Set cSet){ // TODO: Should be StringJoiner once JDK8 used StringBuilder stringBuilder = new StringBuilder(); for(char c: invalidCharSet){ - stringBuilder.append("\'" + c + "\'"); + stringBuilder.append("\'").append(c).append("\'"); } stringBuilder.deleteCharAt(stringBuilder.length()-1); stringBuilder.append(" are being replaced with '-'"); @@ -145,7 +145,7 @@ public final static String cleanSequence(String sequence, Set cSet){ * @return * a sequence with no invalid characters. */ - public static final String checkSequence(String sequence){ + public static String checkSequence(String sequence){ return checkSequence(sequence, null); } @@ -162,8 +162,8 @@ public static final String checkSequence(String sequence){ * @return * a sequence with no invalid characters. */ - public static final String checkSequence(String sequence, Set cSet){ - boolean containInvalid = false; + public static String checkSequence(String sequence, Set cSet){ + boolean containInvalid; if(cSet != null){ containInvalid = sequence != null && doesSequenceContainInvalidChar(sequence, cSet); }else{ diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/IProfeatProperties.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/IProfeatProperties.java index 0fab96f94a..e0d3b3d4cb 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/IProfeatProperties.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/IProfeatProperties.java @@ -45,19 +45,22 @@ public interface IProfeatProperties { /** * Enumeration of the seven different attributes */ - public enum ATTRIBUTE {HYDROPHOBICITY, VOLUME, POLARITY, POLARIZABILITY, CHARGE, SECONDARYSTRUCTURE, SOLVENTACCESSIBILITY}; + enum ATTRIBUTE {HYDROPHOBICITY, VOLUME, POLARITY, POLARIZABILITY, CHARGE, SECONDARYSTRUCTURE, SOLVENTACCESSIBILITY} + /** * Enumeration of the three different groupings for each attributes */ - public enum GROUPING {GROUP1, GROUP2, GROUP3}; + enum GROUPING {GROUP1, GROUP2, GROUP3} + /** * Enumeration of the transition between groupA and groupB */ - public enum TRANSITION {BETWEEN_11, BETWEEN_22, BETWEEN_33, BETWEEN_12, BETWEEN_13, BETWEEN_23}; + enum TRANSITION {BETWEEN_11, BETWEEN_22, BETWEEN_33, BETWEEN_12, BETWEEN_13, BETWEEN_23} + /** * Enumeration of the distribution for the first, first 25%, first 50%, first 75% and 100% of the grouping */ - public enum DISTRIBUTION {FIRST, FIRST25, FIRST50, FIRST75, ALL}; + enum DISTRIBUTION {FIRST, FIRST25, FIRST50, FIRST75, ALL} /** * Returns the composition of the specific grouping for the given attribute. @@ -73,11 +76,11 @@ public enum DISTRIBUTION {FIRST, FIRST25, FIRST50, FIRST75, ALL}; * @throws Exception * throws Exception if attribute or group are unknown */ - public double getComposition(ProteinSequence sequence, ATTRIBUTE attribute, GROUPING group) throws Exception; + double getComposition(ProteinSequence sequence, ATTRIBUTE attribute, GROUPING group) throws Exception; - public Map getComposition(ProteinSequence sequence, ATTRIBUTE attribute) throws Exception; + Map getComposition(ProteinSequence sequence, ATTRIBUTE attribute) throws Exception; - public Map> getComposition(ProteinSequence sequence) throws Exception; + Map> getComposition(ProteinSequence sequence) throws Exception; /** * Returns the number of transition between the specified groups for the given attribute with respect to the length of sequence. @@ -93,11 +96,11 @@ public enum DISTRIBUTION {FIRST, FIRST25, FIRST50, FIRST75, ALL}; * @throws Exception * throws Exception if attribute or group are unknown */ - public double getTransition(ProteinSequence sequence, ATTRIBUTE attribute, TRANSITION transition) throws Exception; + double getTransition(ProteinSequence sequence, ATTRIBUTE attribute, TRANSITION transition) throws Exception; - public Map getTransition(ProteinSequence sequence, ATTRIBUTE attribute) throws Exception; + Map getTransition(ProteinSequence sequence, ATTRIBUTE attribute) throws Exception; - public Map> getTransition(ProteinSequence sequence) throws Exception; + Map> getTransition(ProteinSequence sequence) throws Exception; /** * Computes and return the position with respect to the sequence where the given distribution of the grouping can be found.
@@ -120,11 +123,11 @@ public enum DISTRIBUTION {FIRST, FIRST25, FIRST50, FIRST75, ALL}; * @throws Exception * throws Exception if attribute or group are unknown */ - public double getDistributionPosition(ProteinSequence sequence, ATTRIBUTE attribute, GROUPING group, DISTRIBUTION distribution) throws Exception; + double getDistributionPosition(ProteinSequence sequence, ATTRIBUTE attribute, GROUPING group, DISTRIBUTION distribution) throws Exception; - public Map getDistributionPosition(ProteinSequence sequence, ATTRIBUTE attribute, GROUPING group) throws Exception; + Map getDistributionPosition(ProteinSequence sequence, ATTRIBUTE attribute, GROUPING group) throws Exception; - public Map> getDistributionPosition(ProteinSequence sequence, ATTRIBUTE attribute) throws Exception; + Map> getDistributionPosition(ProteinSequence sequence, ATTRIBUTE attribute) throws Exception; - public Map>> getDistributionPosition(ProteinSequence sequence) throws Exception; + Map>> getDistributionPosition(ProteinSequence sequence) throws Exception; } diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/ProfeatPropertiesImpl.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/ProfeatPropertiesImpl.java index 5408c127c5..cad2700a22 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/ProfeatPropertiesImpl.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/ProfeatPropertiesImpl.java @@ -23,7 +23,7 @@ import org.biojava.nbio.aaproperties.profeat.convertor.*; import org.biojava.nbio.core.sequence.ProteinSequence; -import java.util.HashMap; +import java.util.EnumMap; import java.util.Map; public class ProfeatPropertiesImpl implements IProfeatProperties{ @@ -127,35 +127,35 @@ private Convertor getConvertor(ATTRIBUTE attribute) throws Exception{ @Override public Map getComposition(ProteinSequence sequence, ATTRIBUTE attribute) throws Exception { - Map grouping2Composition = new HashMap(); + Map grouping2Composition = new EnumMap<>(GROUPING.class); for(GROUPING group:GROUPING.values()) grouping2Composition.put(group, getComposition(sequence, attribute, group)); return grouping2Composition; } @Override public Map> getComposition(ProteinSequence sequence) throws Exception { - Map> attribute2Grouping2Composition = new HashMap>(); + Map> attribute2Grouping2Composition = new EnumMap<>(ATTRIBUTE.class); for(ATTRIBUTE attribute:ATTRIBUTE.values()) attribute2Grouping2Composition.put(attribute, getComposition(sequence, attribute)); return attribute2Grouping2Composition; } @Override public Map getTransition(ProteinSequence sequence, ATTRIBUTE attribute) throws Exception { - Map transition2Double = new HashMap(); + Map transition2Double = new EnumMap<>(TRANSITION.class); for(TRANSITION transition:TRANSITION.values()) transition2Double.put(transition, getTransition(sequence, attribute, transition)); return transition2Double; } @Override public Map> getTransition(ProteinSequence sequence) throws Exception { - Map> attribute2Transition2Double = new HashMap>(); + Map> attribute2Transition2Double = new EnumMap<>(ATTRIBUTE.class); for(ATTRIBUTE attribute:ATTRIBUTE.values()) attribute2Transition2Double.put(attribute, getTransition(sequence, attribute)); return attribute2Transition2Double; } @Override public Map getDistributionPosition(ProteinSequence sequence, ATTRIBUTE attribute, GROUPING group) throws Exception { - Map distribution2Double = new HashMap(); + Map distribution2Double = new EnumMap<>(DISTRIBUTION.class); for(DISTRIBUTION distribution:DISTRIBUTION.values()) distribution2Double.put(distribution, getDistributionPosition(sequence, attribute, group, distribution)); return distribution2Double; @@ -163,7 +163,7 @@ public Map getDistributionPosition(ProteinSequence sequenc @Override public Map> getDistributionPosition(ProteinSequence sequence, ATTRIBUTE attribute) throws Exception { - Map> grouping2Distribution2Double = new HashMap>(); + Map> grouping2Distribution2Double = new EnumMap<>(GROUPING.class); for(GROUPING group:GROUPING.values()) grouping2Distribution2Double.put(group, getDistributionPosition(sequence, attribute, group)); return grouping2Distribution2Double; @@ -172,7 +172,7 @@ public Map> getDistributionPosition(ProteinS @Override public Map>> getDistributionPosition(ProteinSequence sequence) throws Exception { Map>> attribute2Grouping2Distribution2Double = - new HashMap>>(); + new EnumMap<>(ATTRIBUTE.class); for(ATTRIBUTE attribute:ATTRIBUTE.values()) attribute2Grouping2Distribution2Double.put(attribute, getDistributionPosition(sequence, attribute)); return attribute2Grouping2Distribution2Double; diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Charge.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Charge.java index 5bf4bc76f4..b2beeed2bb 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Charge.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Charge.java @@ -39,7 +39,7 @@ public char convert(char c){ } } - private static String[] subCategory = {"Positive", "Neutral", "Negative"}; + private static final String[] subCategory = {"Positive", "Neutral", "Negative"}; @Override public String[] getGrouping(){return Convert2Charge.subCategory;} @Override diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Hydrophobicity.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Hydrophobicity.java index 105fdec86f..c2810e45dd 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Hydrophobicity.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Hydrophobicity.java @@ -38,7 +38,7 @@ public char convert(char c){ return unknownGroup;//Non-standard AA } } - private static String[] subCategory = {"Polar", "Neutral", "Hydrophobicity"}; + private static final String[] subCategory = {"Polar", "Neutral", "Hydrophobicity"}; @Override public String[] getGrouping(){return subCategory;} @Override diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2NormalizedVanDerWaalsVolume.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2NormalizedVanDerWaalsVolume.java index 4facf925b7..970a93534b 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2NormalizedVanDerWaalsVolume.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2NormalizedVanDerWaalsVolume.java @@ -38,7 +38,7 @@ public char convert(char c){ return unknownGroup;//Non-standard AA } } - private static String[] subCategory = {"Range_0-2.78", "Range_2.95-4.0", "Range_4.03-8.08"}; + private static final String[] subCategory = {"Range_0-2.78", "Range_2.95-4.0", "Range_4.03-8.08"}; @Override public String[] getGrouping(){return subCategory;} @Override diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Polarity.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Polarity.java index 2b1f1bec61..80ecc69183 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Polarity.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Polarity.java @@ -38,7 +38,7 @@ public char convert(char c){ return unknownGroup;//Non-standard AA } } - private static String[] subCategory = {"Value_4.9-6.2", "Value_8.0-9.2", "Value_10.4-13.0"}; + private static final String[] subCategory = {"Value_4.9-6.2", "Value_8.0-9.2", "Value_10.4-13.0"}; @Override public String[] getGrouping(){return subCategory;} @Override diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Polarizability.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Polarizability.java index 1af72b5cc9..7888cf66a5 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Polarizability.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2Polarizability.java @@ -39,7 +39,7 @@ public char convert(char c){ } } - private static String[] subCategory = {"Value_0-0.08", "Value_0.128-0.186", "Value_0.219-0.409"}; + private static final String[] subCategory = {"Value_0-0.08", "Value_0.128-0.186", "Value_0.219-0.409"}; @Override public String[] getGrouping(){return subCategory;} @Override diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2SecondaryStructure.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2SecondaryStructure.java index 70a51daf41..b3321f659f 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2SecondaryStructure.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2SecondaryStructure.java @@ -37,7 +37,7 @@ public char convert(char c){ return unknownGroup;//Non-standard AA } } - private static String[] subCategory = {"Helix", "Strand", "Coil"}; + private static final String[] subCategory = {"Helix", "Strand", "Coil"}; @Override public String[] getGrouping(){return subCategory;} @Override diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2SolventAccessibility.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2SolventAccessibility.java index 27c7676198..c3497e220f 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2SolventAccessibility.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/profeat/convertor/Convert2SolventAccessibility.java @@ -38,7 +38,7 @@ public char convert(char c){ } } - private static String[] subCategory = {"Buried", "Exposed", "Intermediate"}; + private static final String[] subCategory = {"Buried", "Exposed", "Intermediate"}; @Override public String[] getGrouping(){return subCategory;} @Override diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/AminoAcidCompositionTable.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/AminoAcidCompositionTable.java index 4731e90453..5be7ee1c4f 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/AminoAcidCompositionTable.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/AminoAcidCompositionTable.java @@ -83,7 +83,7 @@ private void generatesAminoAcidCompoundSet(){ * Stores the mass of elements and isotopes */ public void computeMolecularWeight(ElementTable eTable){ - this.aaSymbol2MolecularWeight = new HashMap(); + this.aaSymbol2MolecularWeight = new HashMap<>(); for(AminoAcidComposition a:aminoacid){ //Check to ensure that the symbol is of single character if(a.getSymbol().length() != 1){ @@ -91,7 +91,7 @@ public void computeMolecularWeight(ElementTable eTable){ } //Check to ensure that the symbols are not repeated char c = a.getSymbol().charAt(0); - if(this.aaSymbol2MolecularWeight.keySet().contains(c)){ + if(this.aaSymbol2MolecularWeight.containsKey(c)){ throw new Error("Symbol " + c + " is repeated.\r\n" + "Please check AminoAcidComposition XML file to ensure there are no repeated symbols. Note that this is case-insensitive.\r\n" + "This means that having 'A' and 'a' would be repeating."); diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/CaseFreeAminoAcidCompoundSet.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/CaseFreeAminoAcidCompoundSet.java index 9b211ab305..e830453233 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/CaseFreeAminoAcidCompoundSet.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/CaseFreeAminoAcidCompoundSet.java @@ -39,9 +39,9 @@ */ public class CaseFreeAminoAcidCompoundSet implements CompoundSet { - private final Map aminoAcidCompoundCache = new HashMap(); + private final Map aminoAcidCompoundCache = new HashMap<>(); private final Map> equivalentsCache = - new HashMap>(); + new HashMap<>(); public CaseFreeAminoAcidCompoundSet() { aminoAcidCompoundCache.put("A", new AminoAcidCompound(null, "A", "Ala", "Alanine", 71.0788f)); @@ -64,14 +64,14 @@ public CaseFreeAminoAcidCompoundSet() { aminoAcidCompoundCache.put("W", new AminoAcidCompound(null, "W", "Trp", "Tryptophan", 186.2132f)); aminoAcidCompoundCache.put("Y", new AminoAcidCompound(null, "Y", "Tyr", "Tyrosine", 163.1760f)); aminoAcidCompoundCache.put("V", new AminoAcidCompound(null, "V", "Val", "Valine", 99.1326f)); - aminoAcidCompoundCache.put("B", new AminoAcidCompound(null, "B", "Asx", "Asparagine or Aspartic acid", null)); - aminoAcidCompoundCache.put("Z", new AminoAcidCompound(null, "Z", "Glx", "Glutamine or Glutamic acid", null)); - aminoAcidCompoundCache.put("J", new AminoAcidCompound(null, "J", "Xle", "Leucine or Isoleucine", null)); - aminoAcidCompoundCache.put("X", new AminoAcidCompound(null, "X", "Xaa", "Unspecified", null)); - aminoAcidCompoundCache.put("-", new AminoAcidCompound(null, "-", "---", "Unspecified", null)); - aminoAcidCompoundCache.put(".", new AminoAcidCompound(null, ".", "...", "Unspecified", null)); - aminoAcidCompoundCache.put("_", new AminoAcidCompound(null, "_", "___", "Unspecified", null)); - aminoAcidCompoundCache.put("*", new AminoAcidCompound(null, "*", "***", "Stop", null)); + aminoAcidCompoundCache.put("B", new AminoAcidCompound(null, "B", "Asx", "Asparagine or Aspartic acid", Float.NaN)); + aminoAcidCompoundCache.put("Z", new AminoAcidCompound(null, "Z", "Glx", "Glutamine or Glutamic acid", Float.NaN)); + aminoAcidCompoundCache.put("J", new AminoAcidCompound(null, "J", "Xle", "Leucine or Isoleucine", Float.NaN)); + aminoAcidCompoundCache.put("X", new AminoAcidCompound(null, "X", "Xaa", "Unspecified", Float.NaN)); + aminoAcidCompoundCache.put("-", new AminoAcidCompound(null, "-", "---", "Unspecified", Float.NaN)); + aminoAcidCompoundCache.put(".", new AminoAcidCompound(null, ".", "...", "Unspecified", Float.NaN)); + aminoAcidCompoundCache.put("_", new AminoAcidCompound(null, "_", "___", "Unspecified", Float.NaN)); + aminoAcidCompoundCache.put("*", new AminoAcidCompound(null, "*", "***", "Stop", Float.NaN)); //Selenocysteine - this is encoded by UGA with the presence //of a SECIS element (SElenoCysteine Insertion Sequence) in the mRNA @@ -83,9 +83,9 @@ public CaseFreeAminoAcidCompoundSet() { //which then does the actual conversion to Pyl. aminoAcidCompoundCache.put("O", new AminoAcidCompound(null, "O", "Pyl", "Pyrrolysine", 255.3172f)); - Map lowerCaseSet = new HashMap(); - for(String s:this.aminoAcidCompoundCache.keySet()){ - lowerCaseSet.put(s.toLowerCase(), this.aminoAcidCompoundCache.get(s)); + Map lowerCaseSet = new HashMap<>(); + for(Map.Entry entry : this.aminoAcidCompoundCache.entrySet()){ + lowerCaseSet.put(entry.getKey().toLowerCase(), entry.getValue()); } this.aminoAcidCompoundCache.putAll(lowerCaseSet); } @@ -144,7 +144,7 @@ public Set getEquivalentCompounds(AminoAcidCompound compound) addAmbiguousEquivalents("I", "L", "J"); // ambiguous gaps AminoAcidCompound gap1, gap2, gap3; - Set gaps = new HashSet(); + Set gaps = new HashSet<>(); gaps.add(gap1 = aminoAcidCompoundCache.get("-")); gaps.add(gap2 = aminoAcidCompoundCache.get(".")); gaps.add(gap3 = aminoAcidCompoundCache.get("_")); @@ -152,7 +152,7 @@ public Set getEquivalentCompounds(AminoAcidCompound compound) equivalentsCache.put(gap2, gaps); equivalentsCache.put(gap3, gaps); // X is never equivalent, even to itself - equivalentsCache.put(aminoAcidCompoundCache.get("X"), new HashSet()); + equivalentsCache.put(aminoAcidCompoundCache.get("X"), new HashSet<>()); } return equivalentsCache.get(compound); } @@ -162,18 +162,18 @@ private void addAmbiguousEquivalents(String one, String two, String either) { Set equivalents; AminoAcidCompound cOne, cTwo, cEither; - equivalents = new HashSet(); + equivalents = new HashSet<>(); equivalents.add(cOne = aminoAcidCompoundCache.get(one)); equivalents.add(cTwo = aminoAcidCompoundCache.get(two)); equivalents.add(cEither = aminoAcidCompoundCache.get(either)); equivalentsCache.put(cEither, equivalents); - equivalents = new HashSet(); + equivalents = new HashSet<>(); equivalents.add(cOne); equivalents.add(cEither); equivalentsCache.put(cOne, equivalents); - equivalents = new HashSet(); + equivalents = new HashSet<>(); equivalents.add(cTwo); equivalents.add(cEither); equivalentsCache.put(cTwo, equivalents); @@ -185,8 +185,8 @@ public boolean hasCompound(AminoAcidCompound compound) { } @Override - public List getAllCompounds() { - return new ArrayList(aminoAcidCompoundCache.values()); + public Collection getAllCompounds() { + return new ArrayList<>(aminoAcidCompoundCache.values()); } diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/Element.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/Element.java index b03d15d1ac..1a9f15bb28 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/Element.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/Element.java @@ -120,7 +120,7 @@ public List getIsotopes() { public void setIsotopes(List isotopes) { this.isotope = isotopes; - this.name2Isotope = new HashMap(); + this.name2Isotope = new HashMap<>(); if(isotopes != null){ for(Isotope i:isotopes){ name2Isotope.put(i.getName(), i); diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/ElementTable.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/ElementTable.java index efac678f23..05b54c7014 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/ElementTable.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/ElementTable.java @@ -58,8 +58,8 @@ public void setElement(List eList){ * Populate the Maps for quick retrieval */ public void populateMaps(){ - this.elementName2Element = new HashMap(); - this.isotopeName2Isotope = new HashMap(); + this.elementName2Element = new HashMap<>(); + this.isotopeName2Isotope = new HashMap<>(); if(this.element != null){ for(Element e:this.element){ this.elementName2Element.put(e.getName(), e); diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/ModifiedAminoAcidCompoundSet.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/ModifiedAminoAcidCompoundSet.java index d9c11c7e66..82061e14e6 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/ModifiedAminoAcidCompoundSet.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/ModifiedAminoAcidCompoundSet.java @@ -28,7 +28,7 @@ public class ModifiedAminoAcidCompoundSet implements CompoundSet { - private final Map aminoAcidCompoundCache = new HashMap(); + private final Map aminoAcidCompoundCache = new HashMap<>(); public ModifiedAminoAcidCompoundSet(List aaList, Map aaSymbol2MolecularWeight) { this.aminoAcidCompoundCache.put("-", new AminoAcidCompound(null, "-", "", "", 0.0f)); @@ -83,8 +83,8 @@ public boolean hasCompound(AminoAcidCompound compound) { } @Override - public List getAllCompounds() { - return new ArrayList(aminoAcidCompoundCache.values()); + public Collection getAllCompounds() { + return new ArrayList<>(aminoAcidCompoundCache.values()); } @Override diff --git a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/SchemaGenerator.java b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/SchemaGenerator.java index 8005bf3bac..b5cfea39c2 100644 --- a/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/SchemaGenerator.java +++ b/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/xml/SchemaGenerator.java @@ -27,7 +27,7 @@ import java.io.IOException; public class SchemaGenerator extends SchemaOutputResolver{ - private String fileName; + private final String fileName; public SchemaGenerator(String filename){ this.fileName = filename; diff --git a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/CommandPromptTest.java b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/CommandPromptTest.java index 58ed18dc16..bf37136610 100644 --- a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/CommandPromptTest.java +++ b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/CommandPromptTest.java @@ -20,7 +20,6 @@ */ package org.biojava.nbio.aaproperties; -import org.biojava.nbio.aaproperties.CommandPrompt; import org.junit.Test; import java.io.File; diff --git a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/CookBookTest.java b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/CookBookTest.java index 25ebf3abed..aa51ac3876 100644 --- a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/CookBookTest.java +++ b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/CookBookTest.java @@ -20,7 +20,6 @@ */ package org.biojava.nbio.aaproperties; -import org.biojava.nbio.aaproperties.PeptideProperties; import org.biojava.nbio.aaproperties.xml.AminoAcidCompositionTable; import org.junit.Test; import org.slf4j.Logger; @@ -74,8 +73,8 @@ public void shortExample4(){ //Enrichment of a list of amino acid types Map composition = PeptideProperties.getAACompositionString(sequence); - for(String aa:composition.keySet()){ - logger.debug("Composition of {}: {}", aa, composition.get(aa)); + for(Map.Entry entry : composition.entrySet()){ + logger.debug("Composition of {}: {}", entry.getKey(), entry.getValue()); } } diff --git a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/GenbankCommandPromptTest.java b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/GenbankCommandPromptTest.java index d76acd34c0..15261ae05c 100644 --- a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/GenbankCommandPromptTest.java +++ b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/GenbankCommandPromptTest.java @@ -20,7 +20,6 @@ */ package org.biojava.nbio.aaproperties; -import org.biojava.nbio.aaproperties.CommandPrompt; import org.junit.Test; import java.io.File; @@ -33,8 +32,8 @@ public void testAdvancedXMLExample() throws Exception{ //-i BondFeature.gb -a String[] args = new String[11]; args[0] = "-i"; - args[1] = "./src/test/resources/BondFeature.gb";; - args[2] = "-x"; + args[1] = "./src/test/resources/BondFeature.gb"; + args[2] = "-x"; args[3] = "./src/main/resources/AdvancedAminoAcidComposition.xml"; args[4] = "-0"; args[5] = "0"; @@ -53,8 +52,8 @@ public void testExample1() throws Exception{ //-i BondFeature.gb -a String[] args = new String[7]; args[0] = "-i"; - args[1] = "./src/test/resources/BondFeature.gb";; - args[2] = "-a"; + args[1] = "./src/test/resources/BondFeature.gb"; + args[2] = "-a"; args[3] = "-o"; args[4] = output.toString(); args[5] = "-f"; @@ -69,8 +68,8 @@ public void testExample1WithCSV() throws Exception{ //-i BondFeature.gb -a String[] args = new String[7]; args[0] = "-i"; - args[1] = "./src/test/resources/BondFeature.gb";; - args[2] = "-a"; + args[1] = "./src/test/resources/BondFeature.gb"; + args[2] = "-a"; args[3] = "-o"; args[4] = output.toString(); args[5] = "-f"; diff --git a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/PeptidePropertiesImplTest.java b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/PeptidePropertiesImplTest.java index 6220ea0b28..ae82803012 100644 --- a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/PeptidePropertiesImplTest.java +++ b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/PeptidePropertiesImplTest.java @@ -20,8 +20,6 @@ */ package org.biojava.nbio.aaproperties; -import org.biojava.nbio.aaproperties.PeptideProperties; -import org.biojava.nbio.aaproperties.Utils; import org.biojava.nbio.aaproperties.xml.AminoAcidCompositionTable; import org.junit.Test; import org.slf4j.Logger; @@ -345,7 +343,7 @@ public void testNetCharge(){ logger.debug(p); logger.debug("pH\tInnovagen\tExpasy\tdiff"); for ( int i = 1; i < 15; i++) { - double phPoint = (new Double(i)).doubleValue(); + double phPoint = i; double chrgInnovagen = PeptideProperties.getNetCharge(p,false,phPoint); double chrgExpasy = PeptideProperties.getNetCharge(p,true,phPoint); logger.debug(String.format("%2.1f\t%2.2f\t%2.2f\t%2.2f", phPoint, chrgInnovagen, diff --git a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/profeat/CookBookTest.java b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/profeat/CookBookTest.java index b68370cfc9..51f9735488 100644 --- a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/profeat/CookBookTest.java +++ b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/profeat/CookBookTest.java @@ -24,13 +24,13 @@ import org.biojava.nbio.aaproperties.profeat.IProfeatProperties.DISTRIBUTION; import org.biojava.nbio.aaproperties.profeat.IProfeatProperties.GROUPING; import org.biojava.nbio.aaproperties.profeat.IProfeatProperties.TRANSITION; -import org.biojava.nbio.aaproperties.profeat.ProfeatProperties; -//import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; +//import org.junit.Test; + public class CookBookTest { private final static Logger logger = LoggerFactory.getLogger(CookBookTest.class); @@ -43,11 +43,11 @@ public void shortExample1() throws Exception{ */ String sequence = "QIKDLLVSSSTDLDTTLVLVNAIYFKGMWKTAFNAEDTREMPFHVTKQESKPVQMMCMNNSFNVATLPAE"; Map> attribute2Grouping2Double = ProfeatProperties.getComposition(sequence); - for(ATTRIBUTE a:attribute2Grouping2Double.keySet()){ - logger.info("======={}=======", a); - logger.info("GROUP1 = {}", attribute2Grouping2Double.get(a).get(GROUPING.GROUP1)); - logger.info("GROUP2 = {}", attribute2Grouping2Double.get(a).get(GROUPING.GROUP2)); - logger.info("GROUP3 = {}", attribute2Grouping2Double.get(a).get(GROUPING.GROUP3)); + for(Map.Entry> entry : attribute2Grouping2Double.entrySet()){ + logger.info("======={}=======", entry.getKey()); + logger.info("GROUP1 = {}", entry.getValue().get(GROUPING.GROUP1)); + logger.info("GROUP2 = {}", entry.getValue().get(GROUPING.GROUP2)); + logger.info("GROUP3 = {}", entry.getValue().get(GROUPING.GROUP3)); } } @@ -58,14 +58,14 @@ public void shortExample2() throws Exception{ */ String sequence = "QIKDLLVSSSTDLDTTLVLVNAIYFKGMWKTAFNAEDTREMPFHVTKQESKPVQMMCMNNSFNVATLPAE"; Map> attribute2Transition2Double = ProfeatProperties.getTransition(sequence); - for(ATTRIBUTE a:attribute2Transition2Double.keySet()){ - logger.info("======={}=======", a); - logger.info("1<=>1 = {}", attribute2Transition2Double.get(a).get(TRANSITION.BETWEEN_11)); - logger.info("2<=>2 = {}", attribute2Transition2Double.get(a).get(TRANSITION.BETWEEN_22)); - logger.info("3<=>3 = {}", attribute2Transition2Double.get(a).get(TRANSITION.BETWEEN_33)); - logger.info("1<=>2 = {}", attribute2Transition2Double.get(a).get(TRANSITION.BETWEEN_12)); - logger.info("1<=>3 = {}", attribute2Transition2Double.get(a).get(TRANSITION.BETWEEN_13)); - logger.info("2<=>3 = {}", attribute2Transition2Double.get(a).get(TRANSITION.BETWEEN_23)); + for(Map.Entry> entry : attribute2Transition2Double.entrySet()){ + logger.info("======={}=======", entry.getKey()); + logger.info("1<=>1 = {}", entry.getValue().get(TRANSITION.BETWEEN_11)); + logger.info("2<=>2 = {}", entry.getValue().get(TRANSITION.BETWEEN_22)); + logger.info("3<=>3 = {}", entry.getValue().get(TRANSITION.BETWEEN_33)); + logger.info("1<=>2 = {}", entry.getValue().get(TRANSITION.BETWEEN_12)); + logger.info("1<=>3 = {}", entry.getValue().get(TRANSITION.BETWEEN_13)); + logger.info("2<=>3 = {}", entry.getValue().get(TRANSITION.BETWEEN_23)); } } @@ -76,11 +76,11 @@ public void shortExample3() throws Exception{ */ String sequence = "QIKDLLVSSSTDLDTTLVLVNAIYFKGMWKTAFNAEDTREMPFHVTKQESKPVQMMCMNNSFNVATLPAE"; Map>> attribute2Grouping2Distribution2Double = ProfeatProperties.getDistributionPosition(sequence); - for(ATTRIBUTE a:attribute2Grouping2Distribution2Double.keySet()){ - logger.info("======={}=======", a); - logger.info("GROUP1 = {}", attribute2Grouping2Distribution2Double.get(a).get(GROUPING.GROUP1)); - logger.info("GROUP2 = {}", attribute2Grouping2Distribution2Double.get(a).get(GROUPING.GROUP2)); - logger.info("GROUP3 = {}", attribute2Grouping2Distribution2Double.get(a).get(GROUPING.GROUP3)); + for(Map.Entry>> entry : attribute2Grouping2Distribution2Double.entrySet()){ + logger.info("======={}=======", entry.getKey()); + logger.info("GROUP1 = {}", entry.getValue().get(GROUPING.GROUP1)); + logger.info("GROUP2 = {}", entry.getValue().get(GROUPING.GROUP2)); + logger.info("GROUP3 = {}", entry.getValue().get(GROUPING.GROUP3)); } } } diff --git a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/AminoAcidTest.java b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/AminoAcidTest.java index 528192dcb4..e2fa5e3bea 100644 --- a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/AminoAcidTest.java +++ b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/AminoAcidTest.java @@ -133,35 +133,35 @@ public void readXml() throws JAXBException, IOException{ @Test public void generateXml() throws JAXBException, IOException{ - List elementList = new ArrayList(); + List elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 3)); elementList.add(new Name2Count("Hydrogen", 5)); elementList.add(new Name2Count("Nitrogen", 1)); elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition alanine = new AminoAcidComposition("A", "Ala", "Alanine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 6)); elementList.add(new Name2Count("Hydrogen", 12)); elementList.add(new Name2Count("Nitrogen", 4)); elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition arginine = new AminoAcidComposition("R", "Arg", "Arginine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 4)); elementList.add(new Name2Count("Hydrogen", 6)); elementList.add(new Name2Count("Nitrogen", 2)); elementList.add(new Name2Count("Oxygen", 2)); AminoAcidComposition asparagine = new AminoAcidComposition("N", "Asn", "Asparagine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 4)); elementList.add(new Name2Count("Hydrogen", 5)); elementList.add(new Name2Count("Nitrogen", 1)); elementList.add(new Name2Count("Oxygen", 3)); AminoAcidComposition asparticAcid = new AminoAcidComposition("D", "Asp", "Aspartic Acid", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 3)); elementList.add(new Name2Count("Hydrogen", 5)); @@ -170,7 +170,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Sulfur", 1)); AminoAcidComposition cysteine = new AminoAcidComposition("C", "Cys", "Cysteine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 5)); elementList.add(new Name2Count("Hydrogen", 7)); @@ -178,7 +178,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 3)); AminoAcidComposition glutamicAcid = new AminoAcidComposition("E", "Glu", "Glutamic Acid", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 5)); elementList.add(new Name2Count("Hydrogen", 8)); @@ -186,7 +186,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 2)); AminoAcidComposition glutamine = new AminoAcidComposition("Q", "Gln", "Glutamine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 2)); elementList.add(new Name2Count("Hydrogen", 3)); @@ -194,7 +194,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition glycine = new AminoAcidComposition("G", "Gly", "Glycine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 6)); elementList.add(new Name2Count("Hydrogen", 7)); @@ -202,7 +202,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition histidine = new AminoAcidComposition("H", "His", "Histidine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 6)); elementList.add(new Name2Count("Hydrogen", 11)); @@ -210,7 +210,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition isoleucine = new AminoAcidComposition("I", "Ile", "Isoleucine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 6)); elementList.add(new Name2Count("Hydrogen", 11)); @@ -218,7 +218,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition leucine = new AminoAcidComposition("L", "Leu", "Leucine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 6)); elementList.add(new Name2Count("Hydrogen", 12)); @@ -226,7 +226,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition lysine = new AminoAcidComposition("K", "Lys", "Lysine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 5)); elementList.add(new Name2Count("Hydrogen", 9)); @@ -235,7 +235,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Sulfur", 1)); AminoAcidComposition methionine = new AminoAcidComposition("M", "Met", "Methionine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 9)); elementList.add(new Name2Count("Hydrogen", 9)); @@ -243,7 +243,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition phenylalanine = new AminoAcidComposition("F", "Phe", "Phenylalanine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 5)); elementList.add(new Name2Count("Hydrogen", 7)); @@ -251,7 +251,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition proline = new AminoAcidComposition("P", "Pro", "Proline", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 3)); elementList.add(new Name2Count("Hydrogen", 5)); @@ -259,7 +259,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 2)); AminoAcidComposition serine = new AminoAcidComposition("S", "Ser", "Serine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 4)); elementList.add(new Name2Count("Hydrogen", 7)); @@ -267,7 +267,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 2)); AminoAcidComposition threonine = new AminoAcidComposition("T", "Thr", "Threonine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 11)); elementList.add(new Name2Count("Hydrogen", 10)); @@ -275,7 +275,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition tryptophan = new AminoAcidComposition("W", "Trp", "Tryptophan", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 9)); elementList.add(new Name2Count("Hydrogen", 9)); @@ -283,7 +283,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 2)); AminoAcidComposition tyrosine = new AminoAcidComposition("Y", "Tyr", "Tyrosine", elementList, null); - elementList = new ArrayList(); + elementList = new ArrayList<>(); elementList.add(new Name2Count("Carbon", 5)); elementList.add(new Name2Count("Hydrogen", 9)); @@ -291,7 +291,7 @@ public void generateXml() throws JAXBException, IOException{ elementList.add(new Name2Count("Oxygen", 1)); AminoAcidComposition valine = new AminoAcidComposition("V", "Val", "Valine", elementList, null); - List aList = new ArrayList(); + List aList = new ArrayList<>(); aList.add(alanine); aList.add(arginine); aList.add(asparagine); diff --git a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/ElementTest.java b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/ElementTest.java index 37376b6bd0..801f4f28d7 100644 --- a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/ElementTest.java +++ b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/ElementTest.java @@ -20,10 +20,6 @@ */ package org.biojava.nbio.aaproperties.xml; -import org.biojava.nbio.aaproperties.xml.Element; -import org.biojava.nbio.aaproperties.xml.ElementTable; -import org.biojava.nbio.aaproperties.xml.Isotope; -import org.biojava.nbio.aaproperties.xml.SchemaGenerator; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -62,98 +58,98 @@ public void readXml() throws JAXBException, IOException{ @Test public void generateXml() throws JAXBException, IOException { - List iList = new ArrayList(); + List iList = new ArrayList<>(); Element hydrogen = new Element("Hydrogen", "H", 1, null, 1.00794); iList.add(new Isotope("Hydrogen", 1, 1.00782503207)); iList.add(new Isotope("Deuterium", 2, 2.0141017778)); iList.add(new Isotope("Tritium", 3, 3.0160492777)); hydrogen.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element helium = new Element("Helium", "He", 2, null, 4.002602); iList.add(new Isotope("Helium-3", 3, 3.0160293191)); iList.add(new Isotope("Helium-4", 4, 4.00260325415)); helium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element lithium = new Element("Lithium", "Li", 3, null, 6.941); iList.add(new Isotope("Lithium-6", 6, 6.015122795)); iList.add(new Isotope("Lithium-7", 7, 7.01600455)); lithium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element beryllium = new Element("Beryllium", "Be", 4, null, 9.012182); iList.add(new Isotope("Beryllium-9", 9, 9.0121822)); beryllium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element boron = new Element("Boron", "B", 5, null, 10.811); iList.add(new Isotope("Boron-10", 10, 10.012937)); iList.add(new Isotope("Boron-11", 11, 11.0093054)); boron.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element carbon = new Element("Carbon", "C", 6, null, 12.0107); iList.add(new Isotope("Carbon-12", 12, 12.0)); iList.add(new Isotope("Carbon-13", 13, 13.0033548378)); iList.add(new Isotope("Carbon-14", 14, 14.003241989)); carbon.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element nitrogen = new Element("Nitrogen", "N", 7, null, 14.0067); iList.add(new Isotope("Nitrogen-14", 14, 14.0030740048)); iList.add(new Isotope("Nitrogen-15", 15, 15.0001088982)); nitrogen.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element oxygen = new Element("Oxygen", "O", 8, null, 15.9994); iList.add(new Isotope("Oxygen-16", 16, 15.99491461956)); iList.add(new Isotope("Oxygen-17", 17, 16.9991317)); iList.add(new Isotope("Oxygen-18", 18, 17.999161)); oxygen.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element fluorine = new Element("Fluorine", "F", 9, null, 18.9984032); iList.add(new Isotope("Fluorine-19", 19, 18.99840322)); fluorine.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element neon = new Element("Neon", "Ne", 10, null, 20.1797); iList.add(new Isotope("Neon-20", 20, 19.9924401754)); iList.add(new Isotope("Neon-21", 21, 20.99384668)); iList.add(new Isotope("Neon-22", 22, 21.991385114)); neon.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element sodium = new Element("Sodium", "Na", 11, null, 22.98976928); iList.add(new Isotope("Sodium-23", 23, 22.9897692809)); sodium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element magnesium = new Element("Magnesium", "Mg", 12, null, 24.305); iList.add(new Isotope("Magnesium-24", 24, 23.9850417)); iList.add(new Isotope("Magnesium-25", 25, 24.98583692)); iList.add(new Isotope("Magnesium-26", 26, 25.982592929)); magnesium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element aluminium = new Element("Aluminium", "Al", 13, null, 26.9815386); iList.add(new Isotope("Aluminium-27", 27, 26.98153863)); aluminium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element silicon = new Element("Silicon", "Si", 14, null, 28.0855); iList.add(new Isotope("Silicon-28", 28, 27.9769265325)); iList.add(new Isotope("Silicon-29", 29, 28.9764947)); iList.add(new Isotope("Silicon-30", 30, 29.97377017)); silicon.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element phosphorus = new Element("Phosphorus", "P", 15, null, 30.973762); iList.add(new Isotope("Phosphorus-31", 31, 30.97376163)); phosphorus.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element sulfur = new Element("Sulfur", "S", 16, null, 32.065); iList.add(new Isotope("Sulfur-32", 32, 31.972071)); iList.add(new Isotope("Sulfur-33", 33, 32.97145876)); @@ -161,27 +157,27 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Sulfur-36", 36, 35.96708076)); sulfur.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element chlorine = new Element("Chlorine", "Cl", 17, null, 35.453); iList.add(new Isotope("Chlorine-35", 35, 34.96885268)); iList.add(new Isotope("Chlorine-37", 37, 36.96590259)); chlorine.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element argon = new Element("Argon", "Ar", 18, null, 39.948); iList.add(new Isotope("Argon-36", 36, 35.967545106)); iList.add(new Isotope("Argon-38", 38, 37.9627324)); iList.add(new Isotope("Argon-40", 40, 39.9623831225)); argon.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element potassium = new Element("Potassium", "K", 19, null, 39.0983); iList.add(new Isotope("Potassium-39", 39, 38.96370668)); iList.add(new Isotope("Potassium-40", 40, 39.96399848)); iList.add(new Isotope("Potassium-41", 41, 40.96182576)); potassium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element calcium = new Element("Calcium", "Ca", 20, null, 40.078); iList.add(new Isotope("Calcium-40", 40, 39.96259098)); iList.add(new Isotope("Calcium-42", 42, 41.95861801)); @@ -191,12 +187,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Calcium-48", 48, 47.952534)); calcium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element scandium = new Element("Scandium", "Sc", 21, null, 44.955912); iList.add(new Isotope("Scandium-45", 45, 44.9559119)); scandium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element titanium = new Element("Titanium", "Ti", 22, null, 47.867); iList.add(new Isotope("Titanium-46", 46, 45.9526316)); iList.add(new Isotope("Titanium-47", 47, 46.9517631)); @@ -205,13 +201,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Titanium-50", 50, 49.9447912)); titanium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element vanadium = new Element("Vanadium", "V", 23, null, 50.9415); iList.add(new Isotope("Vanadium-50", 50, 49.9471585)); iList.add(new Isotope("Vanadium-51", 51, 50.9439595)); vanadium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element chromium = new Element("Chromium", "Cr", 24, null, 51.9961); iList.add(new Isotope("Chromium-50", 50, 49.9460442)); iList.add(new Isotope("Chromium-52", 52, 51.9405075)); @@ -219,12 +215,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Chromium-54", 54, 53.9388804)); chromium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element manganese = new Element("Manganese", "Mn", 25, null, 54.938045); iList.add(new Isotope("Manganese-55", 55, 54.9380451)); manganese.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element iron = new Element("Iron", "Fe", 26, null, 55.845); iList.add(new Isotope("Iron-54", 54, 53.9396105)); iList.add(new Isotope("Iron-56", 56, 55.9349375)); @@ -232,12 +228,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Iron-58", 58, 57.9332756)); iron.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element cobalt = new Element("Cobalt", "Co", 27, null, 58.933195); iList.add(new Isotope("Cobalt-59", 59, 58.933195)); cobalt.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element nickel = new Element("Nickel", "Ni", 28, null, 58.6934); iList.add(new Isotope("Nickel-58", 58, 57.9353429)); iList.add(new Isotope("Nickel-60", 60, 59.9307864)); @@ -246,13 +242,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Nickel-64", 64, 63.927966)); nickel.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element copper = new Element("Copper", "Cu", 29, null, 63.546); iList.add(new Isotope("Copper-63", 63, 62.9295975)); iList.add(new Isotope("Copper-65", 65, 64.9277895)); copper.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element zinc = new Element("Zinc", "Zn", 30, null, 65.38); iList.add(new Isotope("Zinc-64", 64, 63.9291422)); iList.add(new Isotope("Zinc-66", 66, 65.9260334)); @@ -261,13 +257,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Zinc-70", 70, 69.9253193)); zinc.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element gallium = new Element("Gallium", "Ga", 31, null, 69.723); iList.add(new Isotope("Gallium-69", 69, 68.9255736)); iList.add(new Isotope("Gallium-71", 71, 70.9247013)); gallium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element germanium = new Element("Germanium", "Ge", 32, null, 72.64); iList.add(new Isotope("Germanium-70", 70, 69.9242474)); iList.add(new Isotope("Germanium-72", 72, 71.9220758)); @@ -276,12 +272,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Germanium-76", 76, 75.9214026)); germanium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element arsenic = new Element("Arsenic", "As", 33, null, 74.9216); iList.add(new Isotope("Arsenic-75", 75, 74.9215965)); arsenic.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element selenium = new Element("Selenium", "Se", 34, null, 78.96); iList.add(new Isotope("Selenium-74", 74, 73.9224764)); iList.add(new Isotope("Selenium-76", 76, 75.9192136)); @@ -291,13 +287,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Selenium-82", 82, 81.9166994)); selenium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element bromine = new Element("Bromine", "Br", 35, null, 79.904); iList.add(new Isotope("Bromine-79", 79, 78.9183371)); iList.add(new Isotope("Bromine-81", 81, 80.9162906)); bromine.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element krypton = new Element("Krypton", "Kr", 36, null, 83.798); iList.add(new Isotope("Krypton-78", 78, 77.9203648)); iList.add(new Isotope("Krypton-80", 80, 79.916379)); @@ -307,13 +303,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Krypton-86", 86, 85.91061073)); krypton.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element rubidium = new Element("Rubidium", "Rb", 37, null, 85.4678); iList.add(new Isotope("Rubidium-85", 85, 84.911789738)); iList.add(new Isotope("Rubidium-87", 87, 86.909180527)); rubidium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element strontium = new Element("Strontium", "Sr", 38, null, 87.62); iList.add(new Isotope("Strontium-84", 84, 83.913425)); iList.add(new Isotope("Strontium-86", 86, 85.9092602)); @@ -321,12 +317,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Strontium-88", 88, 87.9056121)); strontium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element yttrium = new Element("Yttrium", "Y", 39, null, 88.90585); iList.add(new Isotope("Yttrium-89", 89, 88.9058483)); yttrium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element zirconium = new Element("Zirconium", "Zr", 40, null, 91.224); iList.add(new Isotope("Zirconium-90", 90, 89.9047044)); iList.add(new Isotope("Zirconium-91", 91, 90.9056458)); @@ -335,12 +331,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Zirconium-96", 96, 95.9082734)); zirconium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element niobium = new Element("Niobium", "Nb", 41, null, 92.90638); iList.add(new Isotope("Niobium-93", 93, 92.9063781)); niobium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element molybdenum = new Element("Molybdenum", "Mo", 42, null, 95.96); iList.add(new Isotope("Molybdenum-92", 92, 91.906811)); iList.add(new Isotope("Molybdenum-94", 94, 93.9050883)); @@ -351,14 +347,14 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Molybdenum-100", 100, 99.907477)); molybdenum.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element technetium = new Element("Technetium", "Tc", 43, null, 98.0); iList.add(new Isotope("Technetium-97", 97, 96.906365)); iList.add(new Isotope("Technetium-98", 98, 97.907216)); iList.add(new Isotope("Technetium-99", 99, 98.9062547)); technetium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element ruthenium = new Element("Ruthenium", "Ru", 44, null, 101.07); iList.add(new Isotope("Ruthenium-96", 96, 95.907598)); iList.add(new Isotope("Ruthenium-98", 98, 97.905287)); @@ -369,12 +365,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Ruthenium-104", 104, 103.905433)); ruthenium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element rhodium = new Element("Rhodium", "Rh", 45, null, 102.9055); iList.add(new Isotope("Rhodium-103", 103, 102.905504)); rhodium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element palladium = new Element("Palladium", "Pd", 46, null, 106.42); iList.add(new Isotope("Palladium-102", 102, 101.905609)); iList.add(new Isotope("Palladium-104", 104, 103.904036)); @@ -384,13 +380,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Palladium-110", 110, 109.905153)); palladium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element silver = new Element("Silver", "Ag", 47, null, 107.8682); iList.add(new Isotope("Silver-107", 107, 106.905097)); iList.add(new Isotope("Silver-109", 109, 108.904752)); silver.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element cadmium = new Element("Cadmium", "Cd", 48, null, 112.411); iList.add(new Isotope("Cadmium-106", 106, 105.906459)); iList.add(new Isotope("Cadmium-108", 108, 107.904184)); @@ -402,13 +398,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Cadmium-116", 116, 115.904756)); cadmium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element indium = new Element("Indium", "In", 49, null, 114.818); iList.add(new Isotope("Indium-113", 113, 112.904058)); iList.add(new Isotope("Indium-115", 115, 114.903878)); indium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element tin = new Element("Tin", "Sn", 50, null, 118.71); iList.add(new Isotope("Tin-112", 112, 111.904818)); iList.add(new Isotope("Tin-114", 114, 113.902779)); @@ -422,13 +418,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Tin-124", 124, 123.9052739)); tin.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element antimony = new Element("Antimony", "Sb", 51, null, 121.76); iList.add(new Isotope("Antimony-121", 121, 120.9038157)); iList.add(new Isotope("Antimony-123", 123, 122.904214)); antimony.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element tellurium = new Element("Tellurium", "Te", 52, null, 127.6); iList.add(new Isotope("Tellurium-120", 120, 119.90402)); iList.add(new Isotope("Tellurium-122", 122, 121.9030439)); @@ -440,12 +436,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Tellurium-130", 130, 129.9062244)); tellurium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element iodine = new Element("Iodine", "I", 53, null, 126.90447); iList.add(new Isotope("Iodine-127", 127, 126.904473)); iodine.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element xenon = new Element("Xenon", "Xe", 54, null, 131.293); iList.add(new Isotope("Xenon-124", 124, 123.905893)); iList.add(new Isotope("Xenon-126", 126, 125.904274)); @@ -458,12 +454,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Xenon-136", 136, 135.907219)); xenon.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element caesium = new Element("Caesium", "Cs", 55, null, 132.9054519); iList.add(new Isotope("Caesium-133", 133, 132.905451933)); caesium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element barium = new Element("Barium", "Ba", 56, null, 137.327); iList.add(new Isotope("Barium-130", 130, 129.9063208)); iList.add(new Isotope("Barium-132", 132, 131.9050613)); @@ -474,13 +470,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Barium-138", 138, 137.9052472)); barium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element lanthanum = new Element("Lanthanum", "La", 57, null, 138.90547); iList.add(new Isotope("Lanthanum-138", 138, 137.907112)); iList.add(new Isotope("Lanthanum-139", 139, 138.9063533)); lanthanum.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element cerium = new Element("Cerium", "Ce", 58, null, 140.116); iList.add(new Isotope("Cerium-136", 136, 135.907172)); iList.add(new Isotope("Cerium-138", 138, 137.905991)); @@ -488,12 +484,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Cerium-142", 142, 141.909244)); cerium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element praseodymium = new Element("Praseodymium", "Pr", 59, null, 140.90765); iList.add(new Isotope("Praseodymium-141", 141, 140.9076528)); praseodymium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element neodymium = new Element("Neodymium", "Nd", 60, null, 144.242); iList.add(new Isotope("Neodymium-142", 142, 141.9077233)); iList.add(new Isotope("Neodymium-143", 143, 142.9098143)); @@ -504,13 +500,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Neodymium-150", 150, 149.920891)); neodymium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element promethium = new Element("Promethium", "Pm", 61, null, 145.0); iList.add(new Isotope("Promethium-145", 145, 144.912749)); iList.add(new Isotope("Promethium-147", 147, 146.9151385)); promethium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element samarium = new Element("Samarium", "Sm", 62, null, 150.36); iList.add(new Isotope("Samarium-144", 144, 143.911999)); iList.add(new Isotope("Samarium-147", 147, 146.9148979)); @@ -521,13 +517,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Samarium-154", 154, 153.9222093)); samarium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element europium = new Element("Europium", "Eu", 63, null, 151.964); iList.add(new Isotope("Europium-151", 151, 150.9198502)); iList.add(new Isotope("Europium-153", 153, 152.9212303)); europium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element gadolinium = new Element("Gadolinium", "Gd", 64, null, 157.25); iList.add(new Isotope("Gadolinium-152", 152, 151.919791)); iList.add(new Isotope("Gadolinium-154", 154, 153.9208656)); @@ -538,12 +534,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Gadolinium-160", 160, 159.9270541)); gadolinium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element terbium = new Element("Terbium", "Tb", 65, null, 158.92535); iList.add(new Isotope("Terbium-159", 159, 158.9253468)); terbium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element dysprosium = new Element("Dysprosium", "Dy", 66, null, 162.5); iList.add(new Isotope("Dysprosium-156", 156, 155.924283)); iList.add(new Isotope("Dysprosium-158", 158, 157.924409)); @@ -554,12 +550,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Dysprosium-164", 164, 163.9291748)); dysprosium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element holmium = new Element("Holmium", "Ho", 67, null, 164.93032); iList.add(new Isotope("Holmium-165", 165, 164.9303221)); holmium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element erbium = new Element("Erbium", "Er", 68, null, 167.259); iList.add(new Isotope("Erbium-162", 162, 161.928778)); iList.add(new Isotope("Erbium-164", 164, 163.9292)); @@ -569,12 +565,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Erbium-170", 170, 169.9354643)); erbium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element thulium = new Element("Thulium", "Tm", 69, null, 168.93421); iList.add(new Isotope("Thulium-169", 169, 168.9342133)); thulium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element ytterbium = new Element("Ytterbium", "Yb", 70, null, 173.054); iList.add(new Isotope("Ytterbium-168", 168, 167.933897)); iList.add(new Isotope("Ytterbium-170", 170, 169.9347618)); @@ -585,13 +581,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Ytterbium-176", 176, 175.9425717)); ytterbium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element lutetium = new Element("Lutetium", "Lu", 71, null, 174.9668); iList.add(new Isotope("Lutetium-175", 175, 174.9407718)); iList.add(new Isotope("Lutetium-176", 176, 175.9426863)); lutetium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element hafnium = new Element("Hafnium", "Hf", 72, null, 178.49); iList.add(new Isotope("Hafnium-174", 174, 173.940046)); iList.add(new Isotope("Hafnium-176", 176, 175.9414086)); @@ -601,13 +597,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Hafnium-180", 180, 179.94655)); hafnium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element tantalum = new Element("Tantalum", "Ta", 73, null, 180.94788); iList.add(new Isotope("Tantalum-180", 180, 179.9474648)); iList.add(new Isotope("Tantalum-181", 181, 180.9479958)); tantalum.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element tungsten = new Element("Tungsten", "W", 74, null, 183.84); iList.add(new Isotope("Tungsten-180", 180, 179.946704)); iList.add(new Isotope("Tungsten-182", 182, 181.9482042)); @@ -616,13 +612,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Tungsten-186", 186, 185.9543641)); tungsten.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element rhenium = new Element("Rhenium", "Re", 75, null, 186.207); iList.add(new Isotope("Rhenium-185", 185, 184.952955)); iList.add(new Isotope("Rhenium-187", 187, 186.9557531)); rhenium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element osmium = new Element("Osmium", "Os", 76, null, 190.23); iList.add(new Isotope("Osmium-184", 184, 183.9524891)); iList.add(new Isotope("Osmium-186", 186, 185.9538382)); @@ -633,13 +629,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Osmium-192", 192, 191.9614807)); osmium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element iridium = new Element("Iridium", "Ir", 77, null, 192.217); iList.add(new Isotope("Iridium-191", 191, 190.960594)); iList.add(new Isotope("Iridium-193", 193, 192.9629264)); iridium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element platinum = new Element("Platinum", "Pt", 78, null, 195.084); iList.add(new Isotope("Platinum-190", 190, 189.959932)); iList.add(new Isotope("Platinum-192", 192, 191.961038)); @@ -649,12 +645,12 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Platinum-198", 198, 197.967893)); platinum.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element gold = new Element("Gold", "Au", 79, null, 196.966569); iList.add(new Isotope("Gold-197", 197, 196.9665687)); gold.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element mercury = new Element("Mercury", "Hg", 80, null, 200.59); iList.add(new Isotope("Mercury-196", 196, 195.965833)); iList.add(new Isotope("Mercury-198", 198, 197.966769)); @@ -665,13 +661,13 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Mercury-204", 204, 203.9734939)); mercury.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element thallium = new Element("Thallium", "Tl", 81, null, 204.3833); iList.add(new Isotope("Thallium-203", 203, 202.9723442)); iList.add(new Isotope("Thallium-205", 205, 204.9744275)); thallium.setIsotopes(iList); - iList = new ArrayList(); + iList = new ArrayList<>(); Element lead = new Element("Lead", "Pb", 82, null, 207.2); iList.add(new Isotope("Lead-204", 204, 203.9730436)); iList.add(new Isotope("Lead-206", 206, 205.9744653)); @@ -679,7 +675,7 @@ public void generateXml() throws JAXBException, IOException { iList.add(new Isotope("Lead-208", 208, 207.9766521)); lead.setIsotopes(iList); - List eList = new ArrayList(); + List eList = new ArrayList<>(); eList.add(hydrogen); eList.add(helium); eList.add(lithium); diff --git a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/GenerateJavaCodesFromTextTest.java b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/GenerateJavaCodesFromTextTest.java index 45515d9b11..ab2df5fec7 100644 --- a/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/GenerateJavaCodesFromTextTest.java +++ b/biojava-aa-prop/src/test/java/org/biojava/nbio/aaproperties/xml/GenerateJavaCodesFromTextTest.java @@ -43,7 +43,7 @@ public class GenerateJavaCodesFromTextTest { //@Test public void generateCodes() throws IOException{ BufferedReader input = new BufferedReader(new FileReader("./src/test/resources/Symbol2Name.txt")); - Map symbol2Name = new HashMap(); + Map symbol2Name = new HashMap<>(); String line = input.readLine();//Header line is not required while((line = input.readLine()) != null){ String[] sA = line.split("\t"); @@ -52,10 +52,10 @@ public void generateCodes() throws IOException{ input.close(); input = new BufferedReader(new FileReader("./src/test/resources/Symbol2Weight.txt")); - List elementNameList = new ArrayList(); + List elementNameList = new ArrayList<>(); String elementName = null; String elementNameLower = null; - Double elementMass = null; + double elementMass; while((line = input.readLine()) != null){ String[] sA = line.split("\t"); if(sA[0].length() > 0){ @@ -90,7 +90,7 @@ public void generateCodes() throws IOException{ } private double cleanNumber(String s){ - int index = s.indexOf("("); + int index = s.indexOf('('); if(index != -1) s = s.substring(0, index); return Double.parseDouble(s.replace(" ", "").replace("[", "").replace("]", "")); } diff --git a/biojava-alignment/pom.xml b/biojava-alignment/pom.xml index 092dbc3d0b..494856db16 100644 --- a/biojava-alignment/pom.xml +++ b/biojava-alignment/pom.xml @@ -26,15 +26,7 @@ - - org.apache.maven.plugins - maven-jar-plugin - - - demo/** - - - +
diff --git a/biojava-alignment/src/main/java/demo/CookbookMSA.java b/biojava-alignment/src/main/java/demo/CookbookMSA.java index d2952bbeac..c617745539 100644 --- a/biojava-alignment/src/main/java/demo/CookbookMSA.java +++ b/biojava-alignment/src/main/java/demo/CookbookMSA.java @@ -43,7 +43,7 @@ public static void main(String[] args) throws Exception { } private static void multipleSequenceAlignment(String[] ids) throws Exception { - List lst = new ArrayList(); + List lst = new ArrayList<>(); for (String id : ids) { lst.add(getSequenceForId(id)); } diff --git a/biojava-alignment/src/main/java/demo/DemoAlignProteins.java b/biojava-alignment/src/main/java/demo/DemoAlignProteins.java index 079dab8409..9aef5ed5fa 100644 --- a/biojava-alignment/src/main/java/demo/DemoAlignProteins.java +++ b/biojava-alignment/src/main/java/demo/DemoAlignProteins.java @@ -23,9 +23,9 @@ import org.biojava.nbio.alignment.Alignments; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; import org.biojava.nbio.alignment.SimpleGapPenalty; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.alignment.template.PairwiseSequenceAligner; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SequencePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.ProteinSequence; diff --git a/biojava-alignment/src/main/java/demo/DemoDistanceTree.java b/biojava-alignment/src/main/java/demo/DemoDistanceTree.java index c9f82d39f7..cddbe85b01 100644 --- a/biojava-alignment/src/main/java/demo/DemoDistanceTree.java +++ b/biojava-alignment/src/main/java/demo/DemoDistanceTree.java @@ -20,9 +20,6 @@ */ package demo; -import java.io.InputStream; -import java.util.LinkedHashMap; - import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.MultipleSequenceAlignment; @@ -32,15 +29,14 @@ import org.biojava.nbio.core.sequence.io.FastaReader; import org.biojava.nbio.core.sequence.io.GenericFastaHeaderParser; import org.biojava.nbio.core.sequence.io.ProteinSequenceCreator; -import org.biojava.nbio.phylo.DistanceMatrixCalculator; -import org.biojava.nbio.phylo.DistanceTreeEvaluator; -import org.biojava.nbio.phylo.ForesterWrapper; -import org.biojava.nbio.phylo.TreeConstructor; -import org.biojava.nbio.phylo.TreeConstructorType; +import org.biojava.nbio.phylo.*; import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix; import org.forester.evoinference.matrix.distance.DistanceMatrix; import org.forester.phylogeny.Phylogeny; +import java.io.InputStream; +import java.util.LinkedHashMap; + /** * This demo contains the CookBook example to create a phylogenetic tree from a * multiple sequence alignment (MSA). @@ -57,12 +53,11 @@ public static void main(String[] args) throws Exception { InputStream inStream = TreeConstructor.class .getResourceAsStream("/PF00104_small.fasta"); - FastaReader fastaReader = - new FastaReader( - inStream, - new GenericFastaHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet - .getAminoAcidCompoundSet())); + FastaReader fastaReader = + new FastaReader<>( + inStream, + new GenericFastaHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap proteinSequences = fastaReader.process(); @@ -70,7 +65,7 @@ public static void main(String[] args) throws Exception { inStream.close(); MultipleSequenceAlignment msa = - new MultipleSequenceAlignment(); + new MultipleSequenceAlignment<>(); for (ProteinSequence proteinSequence : proteinSequences.values()) { msa.addAlignedSequence(proteinSequence); diff --git a/biojava-alignment/src/main/java/demo/TestDNANeedlemanWunsch.java b/biojava-alignment/src/main/java/demo/TestDNANeedlemanWunsch.java index c94e22d934..07ad2cda69 100644 --- a/biojava-alignment/src/main/java/demo/TestDNANeedlemanWunsch.java +++ b/biojava-alignment/src/main/java/demo/TestDNANeedlemanWunsch.java @@ -23,9 +23,9 @@ import org.biojava.nbio.alignment.Alignments; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; import org.biojava.nbio.alignment.SimpleGapPenalty; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.alignment.template.PairwiseSequenceAligner; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SequencePair; import org.biojava.nbio.core.sequence.DNASequence; import org.biojava.nbio.core.sequence.compound.AmbiguityDNACompoundSet; diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/Alignments.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/Alignments.java index 4ed72d0979..33967f0221 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/Alignments.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/Alignments.java @@ -23,12 +23,12 @@ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.template.ProfilePair; -import org.biojava.nbio.core.alignment.template.SequencePair; +import org.biojava.nbio.alignment.template.*; import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.Profile; +import org.biojava.nbio.core.alignment.template.ProfilePair; +import org.biojava.nbio.core.alignment.template.SequencePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; -import org.biojava.nbio.alignment.template.*; import org.biojava.nbio.core.sequence.compound.AmbiguityDNACompoundSet; import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; import org.biojava.nbio.core.sequence.compound.DNACompoundSet; @@ -58,7 +58,7 @@ public class Alignments { /** * List of implemented sequence pair in a profile scoring routines. */ - public static enum PairInProfileScorerType { + public enum PairInProfileScorerType { IDENTITIES, // similar to MUSCLE SIMILARITIES } @@ -66,7 +66,7 @@ public static enum PairInProfileScorerType { /** * List of implemented pairwise sequence alignment routines. */ - public static enum PairwiseSequenceAlignerType { + public enum PairwiseSequenceAlignerType { GLOBAL, // Needleman-Wunsch/Gotoh GLOBAL_LINEAR_SPACE, // Guan-Uberbacher LOCAL, // Smith-Waterman/Gotoh @@ -76,7 +76,7 @@ public static enum PairwiseSequenceAlignerType { /** * List of implemented pairwise sequence scoring routines. */ - public static enum PairwiseSequenceScorerType { + public enum PairwiseSequenceScorerType { GLOBAL, GLOBAL_IDENTITIES, // similar to CLUSTALW and CLUSTALW2 GLOBAL_SIMILARITIES, @@ -90,7 +90,7 @@ public static enum PairwiseSequenceScorerType { /** * List of implemented profile-profile alignment routines. */ - public static enum ProfileProfileAlignerType { + public enum ProfileProfileAlignerType { GLOBAL, // similar to MUSCLE and KALIGN GLOBAL_LINEAR_SPACE, // similar to CLUSTALW and CLUSTALW2 GLOBAL_CONSENSUS, // similar to CLUSTAL @@ -102,7 +102,7 @@ public static enum ProfileProfileAlignerType { /** * List of implemented profile refinement routines. */ - public static enum RefinerType { + public enum RefinerType { PARTITION_SINGLE, // similar to CLUSTALW2 PARTITION_SINGLE_ALL, // similar to CLUSTALW2 PARTITION_TREE, // similar to MUSCLE @@ -150,7 +150,7 @@ public static , C extends Compound> Profile getMulti PairwiseSequenceScorerType ps = PairwiseSequenceScorerType.GLOBAL_IDENTITIES; GapPenalty gapPenalty = new SimpleGapPenalty(); SubstitutionMatrix subMatrix = null; - if (cs == AminoAcidCompoundSet.getAminoAcidCompoundSet()) { + if (cs == AminoAcidCompoundSet.aminoAcidCompoundSet) { @SuppressWarnings("unchecked") // compound types must be equal since compound sets are equal SubstitutionMatrix temp = (SubstitutionMatrix) SubstitutionMatrixHelper.getBlosum62(); subMatrix = temp; @@ -189,7 +189,7 @@ public static , C extends Compound> Profile getMulti runPairwiseScorers(scorers); // stage 2: hierarchical clustering into a guide tree - GuideTree tree = new GuideTree(sequences, scorers); + GuideTree tree = new GuideTree<>(sequences, scorers); scorers = null; // stage 3: progressive alignment @@ -233,7 +233,7 @@ public static , C extends Compound> SequencePair get static , C extends Compound> List> getAllPairsAligners( List sequences, PairwiseSequenceAlignerType type, GapPenalty gapPenalty, SubstitutionMatrix subMatrix) { - List> allPairs = new ArrayList>(); + List> allPairs = new ArrayList<>(); for (int i = 0; i < sequences.size(); i++) { for (int j = i+1; j < sequences.size(); j++) { allPairs.add(getPairwiseAligner(sequences.get(i), sequences.get(j), type, gapPenalty, subMatrix)); @@ -256,7 +256,7 @@ static , C extends Compound> List, C extends Compound> List> getAllPairsScorers( List sequences, PairwiseSequenceScorerType type, GapPenalty gapPenalty, SubstitutionMatrix subMatrix) { - List> allPairs = new ArrayList>(); + List> allPairs = new ArrayList<>(); for (int i = 0; i < sequences.size(); i++) { for (int j = i+1; j < sequences.size(); j++) { allPairs.add(getPairwiseScorer(sequences.get(i), sequences.get(j), type, gapPenalty, subMatrix)); @@ -291,7 +291,7 @@ public static , C extends Compound> double[] getAllPairsSc * @return calculated elements */ static List getListFromFutures(List> futures) { - List list = new ArrayList(); + List list = new ArrayList<>(); for (Future f : futures) { // TODO when added to ConcurrencyTools, log completions and exceptions instead of printing stack traces try { @@ -326,9 +326,9 @@ public static , C extends Compound> PairwiseSequenceAligne switch (type) { default: case GLOBAL: - return new NeedlemanWunsch(query, target, gapPenalty, subMatrix); + return new NeedlemanWunsch<>(query, target, gapPenalty, subMatrix); case LOCAL: - return new SmithWaterman(query, target, gapPenalty, subMatrix); + return new SmithWaterman<>(query, target, gapPenalty, subMatrix); case GLOBAL_LINEAR_SPACE: case LOCAL_LINEAR_SPACE: // TODO other alignment options (Myers-Miller, Thompson) @@ -374,18 +374,18 @@ static , C extends Compound> PairwiseSequenceScorer case GLOBAL: return getPairwiseAligner(query, target, PairwiseSequenceAlignerType.GLOBAL, gapPenalty, subMatrix); case GLOBAL_IDENTITIES: - return new FractionalIdentityScorer(getPairwiseAligner(query, target, + return new FractionalIdentityScorer<>(getPairwiseAligner(query, target, PairwiseSequenceAlignerType.GLOBAL, gapPenalty, subMatrix)); case GLOBAL_SIMILARITIES: - return new FractionalSimilarityScorer(getPairwiseAligner(query, target, + return new FractionalSimilarityScorer<>(getPairwiseAligner(query, target, PairwiseSequenceAlignerType.GLOBAL, gapPenalty, subMatrix)); case LOCAL: return getPairwiseAligner(query, target, PairwiseSequenceAlignerType.LOCAL, gapPenalty, subMatrix); case LOCAL_IDENTITIES: - return new FractionalIdentityScorer(getPairwiseAligner(query, target, + return new FractionalIdentityScorer<>(getPairwiseAligner(query, target, PairwiseSequenceAlignerType.LOCAL, gapPenalty, subMatrix)); case LOCAL_SIMILARITIES: - return new FractionalSimilarityScorer(getPairwiseAligner(query, target, + return new FractionalSimilarityScorer<>(getPairwiseAligner(query, target, PairwiseSequenceAlignerType.LOCAL, gapPenalty, subMatrix)); case KMERS: case WU_MANBER: @@ -413,7 +413,7 @@ static , C extends Compound> ProfileProfileAligner g switch (type) { default: case GLOBAL: - return new SimpleProfileProfileAligner(profile1, profile2, gapPenalty, subMatrix); + return new SimpleProfileProfileAligner<>(profile1, profile2, gapPenalty, subMatrix); case GLOBAL_LINEAR_SPACE: case GLOBAL_CONSENSUS: case LOCAL: @@ -443,7 +443,7 @@ static , C extends Compound> ProfileProfileAligner g switch (type) { default: case GLOBAL: - return new SimpleProfileProfileAligner(profile1, profile2, gapPenalty, subMatrix); + return new SimpleProfileProfileAligner<>(profile1, profile2, gapPenalty, subMatrix); case GLOBAL_LINEAR_SPACE: case GLOBAL_CONSENSUS: case LOCAL: @@ -473,7 +473,7 @@ static , C extends Compound> ProfileProfileAligner g switch (type) { default: case GLOBAL: - return new SimpleProfileProfileAligner(profile1, profile2, gapPenalty, subMatrix); + return new SimpleProfileProfileAligner<>(profile1, profile2, gapPenalty, subMatrix); case GLOBAL_LINEAR_SPACE: case GLOBAL_CONSENSUS: case LOCAL: @@ -503,7 +503,7 @@ static , C extends Compound> ProfileProfileAligner g switch (type) { default: case GLOBAL: - return new SimpleProfileProfileAligner(profile1, profile2, gapPenalty, subMatrix); + return new SimpleProfileProfileAligner<>(profile1, profile2, gapPenalty, subMatrix); case GLOBAL_LINEAR_SPACE: case GLOBAL_CONSENSUS: case LOCAL: @@ -550,7 +550,7 @@ public static , C extends Compound> Profile getProgr ProfileProfileAlignerType type, GapPenalty gapPenalty, SubstitutionMatrix subMatrix) { // find inner nodes in post-order traversal of tree (each leaf node has a single sequence profile) - List> innerNodes = new ArrayList>(); + List> innerNodes = new ArrayList<>(); for (GuideTreeNode n : tree) { if (n.getProfile() == null) { innerNodes.add(n); @@ -567,7 +567,7 @@ public static , C extends Compound> Profile getProgr getProfileProfileAligner(p1, pf2, type, gapPenalty, subMatrix)) : ((p2 != null) ? getProfileProfileAligner(pf1, p2, type, gapPenalty, subMatrix) : getProfileProfileAligner(pf1, pf2, type, gapPenalty, subMatrix)); - n.setProfileFuture(ConcurrencyTools.submit(new CallableProfileProfileAligner(aligner), String.format( + n.setProfileFuture(ConcurrencyTools.submit(new CallableProfileProfileAligner<>(aligner), String.format( "Aligning pair %d of %d", i++, all))); } @@ -599,9 +599,9 @@ public static , C extends Compound> Profile getProgr static , C extends Compound> List> runPairwiseAligners(List> aligners) { int n = 1, all = aligners.size(); - List>> futures = new ArrayList>>(); + List>> futures = new ArrayList<>(); for (PairwiseSequenceAligner aligner : aligners) { - futures.add(ConcurrencyTools.submit(new CallablePairwiseSequenceAligner(aligner), + futures.add(ConcurrencyTools.submit(new CallablePairwiseSequenceAligner<>(aligner), String.format("Aligning pair %d of %d", n++, all))); } return getListFromFutures(futures); @@ -619,9 +619,9 @@ public static , C extends Compound> Profile getProgr public static , C extends Compound> double[] runPairwiseScorers( List> scorers) { int n = 1, all = scorers.size(); - List> futures = new ArrayList>(); + List> futures = new ArrayList<>(); for (PairwiseSequenceScorer scorer : scorers) { - futures.add(ConcurrencyTools.submit(new CallablePairwiseSequenceScorer(scorer), + futures.add(ConcurrencyTools.submit(new CallablePairwiseSequenceScorer<>(scorer), String.format("Scoring pair %d of %d", n++, all))); } List results = getListFromFutures(futures); @@ -644,9 +644,9 @@ public static , C extends Compound> double[] runPairwiseSc static , C extends Compound> List> runProfileAligners(List> aligners) { int n = 1, all = aligners.size(); - List>> futures = new ArrayList>>(); + List>> futures = new ArrayList<>(); for (ProfileProfileAligner aligner : aligners) { - futures.add(ConcurrencyTools.submit(new CallableProfileProfileAligner(aligner), + futures.add(ConcurrencyTools.submit(new CallableProfileProfileAligner<>(aligner), String.format("Aligning pair %d of %d", n++, all))); } return getListFromFutures(futures); diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalIdentityInProfileScorer.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalIdentityInProfileScorer.java index c84ea753d9..5d0006ba0d 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalIdentityInProfileScorer.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalIdentityInProfileScorer.java @@ -23,9 +23,9 @@ package org.biojava.nbio.alignment; +import org.biojava.nbio.alignment.template.PairInProfileScorer; import org.biojava.nbio.core.alignment.SimpleSequencePair; import org.biojava.nbio.core.alignment.template.AlignedSequence; -import org.biojava.nbio.alignment.template.PairInProfileScorer; import org.biojava.nbio.core.alignment.template.Profile; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; @@ -41,7 +41,7 @@ public class FractionalIdentityInProfileScorer, C extends Compound> extends FractionalIdentityScorer implements PairInProfileScorer { - private Profile profile; + private final Profile profile; /** * Creates a fractional identity scorer for an aligned pair of sequences in the given alignment profile. @@ -51,7 +51,7 @@ public class FractionalIdentityInProfileScorer, C extends * @param target index in the profile of the second sequence of the pair */ public FractionalIdentityInProfileScorer(Profile profile, int query, int target) { - super(new SimpleSequencePair(profile.getAlignedSequence(query), profile.getAlignedSequence(target))); + super(new SimpleSequencePair<>(profile.getAlignedSequence(query), profile.getAlignedSequence(target))); this.profile = profile; } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalIdentityScorer.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalIdentityScorer.java index 4b494db779..538f7a97ec 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalIdentityScorer.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalIdentityScorer.java @@ -23,8 +23,10 @@ package org.biojava.nbio.alignment; +import org.biojava.nbio.alignment.template.AbstractScorer; +import org.biojava.nbio.alignment.template.PairwiseSequenceAligner; +import org.biojava.nbio.alignment.template.PairwiseSequenceScorer; import org.biojava.nbio.core.alignment.template.SequencePair; -import org.biojava.nbio.alignment.template.*; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; @@ -40,7 +42,8 @@ public class FractionalIdentityScorer, C extends Compound> implements PairwiseSequenceScorer { // always stored - private S query, target; + private final S query; + private final S target; private int max, score; // optional cached input field diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalSimilarityInProfileScorer.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalSimilarityInProfileScorer.java index ecd975d459..de826a6d4c 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalSimilarityInProfileScorer.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalSimilarityInProfileScorer.java @@ -23,9 +23,9 @@ package org.biojava.nbio.alignment; +import org.biojava.nbio.alignment.template.PairInProfileScorer; import org.biojava.nbio.core.alignment.SimpleSequencePair; import org.biojava.nbio.core.alignment.template.AlignedSequence; -import org.biojava.nbio.alignment.template.PairInProfileScorer; import org.biojava.nbio.core.alignment.template.Profile; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; @@ -41,7 +41,7 @@ public class FractionalSimilarityInProfileScorer, C extends Compound> extends FractionalSimilarityScorer implements PairInProfileScorer { - private Profile profile; + private final Profile profile; /** * Creates a fractional similarity scorer for an aligned pair of sequences in the given alignment profile. @@ -51,7 +51,7 @@ public class FractionalSimilarityInProfileScorer, C extend * @param target index in the profile of the second sequence of the pair */ public FractionalSimilarityInProfileScorer(Profile profile, int query, int target) { - super(new SimpleSequencePair(profile.getAlignedSequence(query), profile.getAlignedSequence(target))); + super(new SimpleSequencePair<>(profile.getAlignedSequence(query), profile.getAlignedSequence(target))); this.profile = profile; } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalSimilarityScorer.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalSimilarityScorer.java index 05911367f8..df59360b1b 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalSimilarityScorer.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/FractionalSimilarityScorer.java @@ -23,8 +23,10 @@ package org.biojava.nbio.alignment; +import org.biojava.nbio.alignment.template.AbstractScorer; +import org.biojava.nbio.alignment.template.PairwiseSequenceAligner; +import org.biojava.nbio.alignment.template.PairwiseSequenceScorer; import org.biojava.nbio.core.alignment.template.SequencePair; -import org.biojava.nbio.alignment.template.*; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; @@ -40,7 +42,8 @@ public class FractionalSimilarityScorer, C extends Compoun implements PairwiseSequenceScorer { // always stored - private S query, target; + private final S query; + private final S target; private int max, score; // optional cached input field diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/GuideTree.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/GuideTree.java index ecbcf66e79..a1fdddc364 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/GuideTree.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/GuideTree.java @@ -23,9 +23,9 @@ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.SimpleProfile; import org.biojava.nbio.alignment.template.GuideTreeNode; import org.biojava.nbio.alignment.template.PairwiseSequenceScorer; +import org.biojava.nbio.core.alignment.SimpleProfile; import org.biojava.nbio.core.alignment.template.Profile; import org.biojava.nbio.core.alignment.template.ProfilePair; import org.biojava.nbio.core.sequence.AccessionID; @@ -39,7 +39,6 @@ import org.forester.phylogeny.PhylogenyNode; import javax.swing.tree.TreeNode; - import java.util.*; import java.util.concurrent.Future; @@ -54,11 +53,11 @@ */ public class GuideTree, C extends Compound> implements Iterable> { - private List sequences; - private List> scorers; - private BasicSymmetricalDistanceMatrix distances; - private String newick; - private Node root; + private final List sequences; + private final List> scorers; + private final BasicSymmetricalDistanceMatrix distances; + private final String newick; + private final Node root; /** * Creates a guide tree for use during progressive multiple sequence alignment. @@ -170,10 +169,13 @@ public String toString() { */ public class Node implements GuideTreeNode { - private GuideTreeNode parent, child1, child2; - private double distance; - private String name; - private boolean isLeaf, isVisited; + private final GuideTreeNode parent; + private GuideTreeNode child1; + private GuideTreeNode child2; + private final double distance; + private final String name; + private final boolean isLeaf; + private boolean isVisited; private Profile profile; private Future> profileFuture; @@ -182,7 +184,7 @@ private Node(PhylogenyNode node, Node parent) { distance = node.getDistanceToParent(); name = node.getName(); if(isLeaf = node.isExternal()) { - profile = new SimpleProfile(sequences.get(distances.getIndex(name))); + profile = new SimpleProfile<>(sequences.get(distances.getIndex(name))); } else { child1 = new Node(node.getChildNode1(), this); child2 = new Node(node.getChildNode2(), this); @@ -237,7 +239,7 @@ public void setProfileFuture(Future> profileFuture) { @Override public Enumeration> children() { - Vector> children = new Vector>(); + Vector> children = new Vector<>(); children.add(getChild1()); children.add(getChild2()); return children.elements(); @@ -301,11 +303,11 @@ private void visit() { // helper class that defines the default post-order (leaves to root) traversal private class PostOrderIterator implements Iterator> { - private Stack nodes; + private final Stack nodes; private PostOrderIterator() { getRoot().clearVisited(); - nodes = new Stack(); + nodes = new Stack<>(); nodes.push(getRoot()); } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/NeedlemanWunsch.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/NeedlemanWunsch.java index 81fc49d803..1f9aeefa21 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/NeedlemanWunsch.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/NeedlemanWunsch.java @@ -24,8 +24,8 @@ package org.biojava.nbio.alignment; import org.biojava.nbio.alignment.routines.AnchoredPairwiseSequenceAligner; -import org.biojava.nbio.core.alignment.template.AlignedSequence; import org.biojava.nbio.alignment.template.GapPenalty; +import org.biojava.nbio.core.alignment.template.AlignedSequence; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SimpleGapPenalty.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SimpleGapPenalty.java index d45c2a1bc8..54e0e0f967 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SimpleGapPenalty.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SimpleGapPenalty.java @@ -23,10 +23,10 @@ package org.biojava.nbio.alignment; -import java.io.Serializable; - import org.biojava.nbio.alignment.template.GapPenalty; +import java.io.Serializable; + /** * Implements a data structure for the gap penalties used during a sequence alignment routine. * diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SimpleProfileProfileAligner.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SimpleProfileProfileAligner.java index 73579ab8f4..fb4c3011e0 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SimpleProfileProfileAligner.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SimpleProfileProfileAligner.java @@ -23,12 +23,14 @@ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.template.ProfilePair; -import org.biojava.nbio.core.alignment.template.Profile; -import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; +import org.biojava.nbio.alignment.template.AbstractProfileProfileAligner; +import org.biojava.nbio.alignment.template.Aligner; +import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.core.alignment.SimpleProfilePair; -import org.biojava.nbio.alignment.template.*; import org.biojava.nbio.core.alignment.template.AlignedSequence.Step; +import org.biojava.nbio.core.alignment.template.Profile; +import org.biojava.nbio.core.alignment.template.ProfilePair; +import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; @@ -110,7 +112,7 @@ public SimpleProfileProfileAligner(Future> query, Profile sx, List sy) { - profile = pair = new SimpleProfilePair(getQuery(), getTarget(), sx, sy); + profile = pair = new SimpleProfilePair<>(getQuery(), getTarget(), sx, sy); } } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SmithWaterman.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SmithWaterman.java index 7d7e017694..6317a6341a 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SmithWaterman.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SmithWaterman.java @@ -23,11 +23,11 @@ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.SimpleSequencePair; import org.biojava.nbio.alignment.template.AbstractPairwiseSequenceAligner; +import org.biojava.nbio.alignment.template.GapPenalty; +import org.biojava.nbio.core.alignment.SimpleSequencePair; import org.biojava.nbio.core.alignment.template.AlignedSequence; import org.biojava.nbio.core.alignment.template.AlignedSequence.Step; -import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; @@ -69,7 +69,7 @@ public SmithWaterman(S query, S target, GapPenalty gapPenalty, SubstitutionMatri @Override protected void setProfile(List sx, List sy) { - profile = pair = new SimpleSequencePair(getQuery(), getTarget(), sx, xyStart[0], + profile = pair = new SimpleSequencePair<>(getQuery(), getTarget(), sx, xyStart[0], getQuery().getLength() - xyMax[0], sy, xyStart[1], getTarget().getLength() - xyMax[1]); } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/StandardRescoreRefiner.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/StandardRescoreRefiner.java index 40c8dc1e76..e0e7d553fb 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/StandardRescoreRefiner.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/StandardRescoreRefiner.java @@ -26,16 +26,16 @@ import org.biojava.nbio.alignment.Alignments.PairInProfileScorerType; import org.biojava.nbio.alignment.Alignments.ProfileProfileAlignerType; import org.biojava.nbio.alignment.template.AbstractScorer; -import org.biojava.nbio.core.alignment.template.Profile; import org.biojava.nbio.alignment.template.RescoreRefiner; +import org.biojava.nbio.core.alignment.template.Profile; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; public class StandardRescoreRefiner, C extends Compound> extends AbstractScorer implements RescoreRefiner { - private PairInProfileScorerType pips; - private ProfileProfileAlignerType ppa; + private final PairInProfileScorerType pips; + private final ProfileProfileAlignerType ppa; public StandardRescoreRefiner(PairInProfileScorerType pips, ProfileProfileAlignerType ppa) { this.pips = pips; diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SubstitutionMatrixScorer.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SubstitutionMatrixScorer.java index a903ebd1ce..a2a531c8ad 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SubstitutionMatrixScorer.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/SubstitutionMatrixScorer.java @@ -40,8 +40,8 @@ public class SubstitutionMatrixScorer, C extends Compound> private final SubstitutionMatrix matrix; - private S query; - private S target; + private final S query; + private final S target; private double score; public SubstitutionMatrixScorer(SequencePair pair, SubstitutionMatrix matrix) { diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmFileAnnotation.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmFileAnnotation.java index ddeb03b451..7e5cbfa325 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmFileAnnotation.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmFileAnnotation.java @@ -125,7 +125,7 @@ public void setRefLocation(String refLocation) { private Set dbReferences; private StringBuffer refComment; /**TODO When implementing toString(), the function should loop on the vector */ - private Vector references = new Vector(); + private Vector references = new Vector<>(); private StringBuffer keywords; private CharSequence comment; private StringBuffer pfamAccession; @@ -137,7 +137,7 @@ public void setRefLocation(String refLocation) { private float falseDiscoveryRate; public StockholmFileAnnotation() { - embTrees = new HashMap>(); + embTrees = new HashMap<>(); } public StringBuffer getDbComment() { @@ -164,7 +164,7 @@ public void setDbReferences(Set dbReferences) { */ public void addDBReference(String dbReferenceRepresentingString) { if (this.dbReferences == null) { - this.dbReferences = new HashSet(); + this.dbReferences = new HashSet<>(); } dbReferences.add(new DatabaseReference(dbReferenceRepresentingString)); } @@ -492,7 +492,7 @@ public void setGFMembership(String membership) { public void addGFNewHampshire(String newHampshire) { List hampshireTree = embTrees.get(TREE_DEFAULT_ID); if (hampshireTree == null) { - hampshireTree = new ArrayList(); + hampshireTree = new ArrayList<>(); } hampshireTree.add(newHampshire); embTrees.put(TREE_DEFAULT_ID, hampshireTree); diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmFileParser.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmFileParser.java index eb92301be9..5180bf1dbb 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmFileParser.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmFileParser.java @@ -356,7 +356,7 @@ public List parse(InputStream inStream, int max) throws IOEx if (internalScanner == null) { internalScanner = new Scanner(inStream); } - ArrayList structures = new ArrayList(); + ArrayList structures = new ArrayList<>(); while (max != INFINITY && max-- > 0) { StockholmStructure structure = parse(internalScanner); if (structure != null) { @@ -399,7 +399,7 @@ StockholmStructure parse(Scanner scanner) throws ParserException, IOException { throw new IllegalArgumentException("No Scanner defined"); } } - String line = null; + String line; int linesCount = 0; try { while (scanner.hasNextLine()) { @@ -507,9 +507,8 @@ StockholmStructure parse(Scanner scanner) throws ParserException, IOException { if (structure != null) { int length = -1; Map sequences = structure.getSequences(); - for (String sequencename : sequences.keySet()) { - StringBuffer sequence = sequences.get(sequencename); - if (length == -1) { + for (StringBuffer sequence : sequences.values()) { + if (length == -1) { length = sequence.length(); } else if (length != sequence.length()) { throw new RuntimeException("Sequences have different lengths"); @@ -544,79 +543,114 @@ private void handleSequenceLine(String line) throws ParserException { * the line to be parsed */ private void handleFileAnnotation(String featureName, String value) { - if (featureName.equals(GF_ACCESSION_NUMBER)) { - stockholmStructure.getFileAnnotation().setGFAccessionNumber(value); - } else if (featureName.equals(GF_IDENTIFICATION)) { - stockholmStructure.getFileAnnotation().setGFIdentification(value); - } else if (featureName.equals(GF_DB_REFERENCE)) { - stockholmStructure.getFileAnnotation().addDBReference(value); - } else if (featureName.equals(GF_DEFINITION)) { - stockholmStructure.getFileAnnotation().setGFDefinition(value); - } else if (featureName.equals(GF_AUTHOR)) { - stockholmStructure.getFileAnnotation().setGFAuthors(value); - } else if (featureName.equals(GF_ALIGNMENT_METHOD)) { - stockholmStructure.getFileAnnotation().setAlignmentMethod(value); - } else if (featureName.equals(GF_BUILD_METHOD)) { - stockholmStructure.getFileAnnotation().addGFBuildMethod(value); - } else if (featureName.equals(GF_SEARCH_METHOD)) { - stockholmStructure.getFileAnnotation().setGFSearchMethod(value); - } else if (featureName.equals(GF_SOURCE_SEED)) { - stockholmStructure.getFileAnnotation().setGFSourceSeed(value); - } else if (featureName.equals(GF_SOURCE_STRUCTURE)) { - stockholmStructure.getFileAnnotation().setGFSourceStructure(value); - } else if (featureName.equals(GF_GATHERING_THRESHOLD)) { - stockholmStructure.getFileAnnotation().setGFGatheringThreshs(value); - } else if (featureName.equals(GF_TRUSTED_CUTOFF)) { - stockholmStructure.getFileAnnotation().setGFTrustedCutoffs(value); - } else if (featureName.equals(GF_NOISE_CUTOFF)) { - stockholmStructure.getFileAnnotation().setGFNoiseCutoffs(value); - } else if (featureName.equals(GF_TYPE_FIELD)) { - stockholmStructure.getFileAnnotation().setGFTypeField(value); - } else if (featureName.equals(GF_PREVIOUS_IDS)) { - stockholmStructure.getFileAnnotation().setGFPreviousIDs(value); - } else if (featureName.equals(GF_SEQUENCE)) { - // status = STATUS_IN_SEQUENCE; - stockholmStructure.getFileAnnotation().setGFNumSequences(value); - } else if (featureName.equals(GF_DB_COMMENT)) { - stockholmStructure.getFileAnnotation().setGFDBComment(value); - // } else if (featureName.equals(GF_DB_REFERENCE)) { - // stockholmStructure.getFileAnnotation().addDBReference(value); - } else if (featureName.equals(GF_REFERENCE_COMMENT)) { - stockholmStructure.getFileAnnotation().setGFRefComment(value); - } else if (featureName.equals(GF_REFERENCE_NUMBER)) { - StockholmFileAnnotationReference reference = new StockholmFileAnnotationReference(); - stockholmStructure.getFileAnnotation().getReferences().add(reference); - } else if (featureName.equals(GF_REFERENCE_MEDLINE)) { - stockholmStructure.getFileAnnotation().getReferences().lastElement().setRefMedline(value); - } else if (featureName.equals(GF_REFERENCE_TITLE)) { - stockholmStructure.getFileAnnotation().getReferences().lastElement().addToRefTitle(value); - } else if (featureName.equals(GF_REFERENCE_AUTHOR)) { - stockholmStructure.getFileAnnotation().getReferences().lastElement().addToRefAuthor(value); - } else if (featureName.equals(GF_REFERENCE_LOCALTION)) { - stockholmStructure.getFileAnnotation().getReferences().lastElement().setRefLocation(value); - } else if (featureName.equals(GF_KEYWORDS)) { - stockholmStructure.getFileAnnotation().setGFKeywords(value); - } else if (featureName.equals(GF_COMMENT)) { - stockholmStructure.getFileAnnotation().addToGFComment(value); - } else if (featureName.equals(GF_PFAM_ACCESSION)) { - stockholmStructure.getFileAnnotation().setGFPfamAccession(value); - } else if (featureName.equals(GF_LOCATION)) { - stockholmStructure.getFileAnnotation().setGFLocation(value); - } else if (featureName.equals(GF_WIKIPEDIA_LINK)) { - stockholmStructure.getFileAnnotation().setGFWikipediaLink(value); - } else if (featureName.equals(GF_CLAN)) { - stockholmStructure.getFileAnnotation().setGFClan(value); - } else if (featureName.equals(GF_MEMBERSHIP)) { - stockholmStructure.getFileAnnotation().setGFMembership(value); - } else if (featureName.equals(GF_NEW_HAMPSHIRE)) { - stockholmStructure.getFileAnnotation().addGFNewHampshire(value); - } else if (featureName.equals(GF_TREE_ID)) { - stockholmStructure.getFileAnnotation().addGFTreeID(value); - } else if (featureName.equals(GF_FALSE_DISCOVERY_RATE)) { - stockholmStructure.getFileAnnotation().addGFFalseDiscoveryRate(value); - } else { - // unknown feature - logger.warn("Unknown File Feature [{}].\nPlease contact the Biojava team.", featureName); + switch (featureName) { + case GF_ACCESSION_NUMBER: + stockholmStructure.getFileAnnotation().setGFAccessionNumber(value); + break; + case GF_IDENTIFICATION: + stockholmStructure.getFileAnnotation().setGFIdentification(value); + break; + case GF_DB_REFERENCE: + stockholmStructure.getFileAnnotation().addDBReference(value); + break; + case GF_DEFINITION: + stockholmStructure.getFileAnnotation().setGFDefinition(value); + break; + case GF_AUTHOR: + stockholmStructure.getFileAnnotation().setGFAuthors(value); + break; + case GF_ALIGNMENT_METHOD: + stockholmStructure.getFileAnnotation().setAlignmentMethod(value); + break; + case GF_BUILD_METHOD: + stockholmStructure.getFileAnnotation().addGFBuildMethod(value); + break; + case GF_SEARCH_METHOD: + stockholmStructure.getFileAnnotation().setGFSearchMethod(value); + break; + case GF_SOURCE_SEED: + stockholmStructure.getFileAnnotation().setGFSourceSeed(value); + break; + case GF_SOURCE_STRUCTURE: + stockholmStructure.getFileAnnotation().setGFSourceStructure(value); + break; + case GF_GATHERING_THRESHOLD: + stockholmStructure.getFileAnnotation().setGFGatheringThreshs(value); + break; + case GF_TRUSTED_CUTOFF: + stockholmStructure.getFileAnnotation().setGFTrustedCutoffs(value); + break; + case GF_NOISE_CUTOFF: + stockholmStructure.getFileAnnotation().setGFNoiseCutoffs(value); + break; + case GF_TYPE_FIELD: + stockholmStructure.getFileAnnotation().setGFTypeField(value); + break; + case GF_PREVIOUS_IDS: + stockholmStructure.getFileAnnotation().setGFPreviousIDs(value); + break; + case GF_SEQUENCE: + // status = STATUS_IN_SEQUENCE; + stockholmStructure.getFileAnnotation().setGFNumSequences(value); + break; + case GF_DB_COMMENT: + stockholmStructure.getFileAnnotation().setGFDBComment(value); + // } else if (featureName.equals(GF_DB_REFERENCE)) { + // stockholmStructure.getFileAnnotation().addDBReference(value); + break; + case GF_REFERENCE_COMMENT: + stockholmStructure.getFileAnnotation().setGFRefComment(value); + break; + case GF_REFERENCE_NUMBER: + StockholmFileAnnotationReference reference = new StockholmFileAnnotationReference(); + stockholmStructure.getFileAnnotation().getReferences().add(reference); + break; + case GF_REFERENCE_MEDLINE: + stockholmStructure.getFileAnnotation().getReferences().lastElement().setRefMedline(value); + break; + case GF_REFERENCE_TITLE: + stockholmStructure.getFileAnnotation().getReferences().lastElement().addToRefTitle(value); + break; + case GF_REFERENCE_AUTHOR: + stockholmStructure.getFileAnnotation().getReferences().lastElement().addToRefAuthor(value); + break; + case GF_REFERENCE_LOCALTION: + stockholmStructure.getFileAnnotation().getReferences().lastElement().setRefLocation(value); + break; + case GF_KEYWORDS: + stockholmStructure.getFileAnnotation().setGFKeywords(value); + break; + case GF_COMMENT: + stockholmStructure.getFileAnnotation().addToGFComment(value); + break; + case GF_PFAM_ACCESSION: + stockholmStructure.getFileAnnotation().setGFPfamAccession(value); + break; + case GF_LOCATION: + stockholmStructure.getFileAnnotation().setGFLocation(value); + break; + case GF_WIKIPEDIA_LINK: + stockholmStructure.getFileAnnotation().setGFWikipediaLink(value); + break; + case GF_CLAN: + stockholmStructure.getFileAnnotation().setGFClan(value); + break; + case GF_MEMBERSHIP: + stockholmStructure.getFileAnnotation().setGFMembership(value); + break; + case GF_NEW_HAMPSHIRE: + stockholmStructure.getFileAnnotation().addGFNewHampshire(value); + break; + case GF_TREE_ID: + stockholmStructure.getFileAnnotation().addGFTreeID(value); + break; + case GF_FALSE_DISCOVERY_RATE: + stockholmStructure.getFileAnnotation().addGFFalseDiscoveryRate(value); + break; + default: + // unknown feature + logger.warn("Unknown File Feature [{}].\nPlease contact the Biojava team.", featureName); + break; } } @@ -630,33 +664,47 @@ private void handleFileAnnotation(String featureName, String value) { * the line to be parsed. */ private void handleConsensusAnnotation(String featureName, String value) { - if (featureName.equals(GC_SECONDARY_STRUCTURE)) { - stockholmStructure.getConsAnnotation().setSecondaryStructure(value); - } else if (featureName.equals(GC_SEQUENSE_CONSENSUS)) { - stockholmStructure.getConsAnnotation().setSequenceConsensus(value); - } else if (featureName.equals(GC_SURFACE_ACCESSIBILITY)) { - stockholmStructure.getConsAnnotation().setSurfaceAccessibility(value); - } else if (featureName.equals(GC_TRANS_MEMBRANE)) { - stockholmStructure.getConsAnnotation().setTransMembrane(value); - } else if (featureName.equals(GC_POSTERIOR_PROBABILITY)) { - stockholmStructure.getConsAnnotation().setPosteriorProbability(value); - } else if (featureName.equals(GC_LIGAND_BINDING)) { - stockholmStructure.getConsAnnotation().setLigandBinding(value); - } else if (featureName.equals(GC_ACTIVE_SITE)) { - stockholmStructure.getConsAnnotation().setActiveSite(value); - } else if (featureName.equals(GC_AS_PFAM_PREDICTED)) { - stockholmStructure.getConsAnnotation().setAsPFamPredicted(value); - } else if (featureName.equals(GC_AS_SWISSPROT)) { - stockholmStructure.getConsAnnotation().setAsSwissProt(value); - } else if (featureName.equals(GC_INTRON)) { - stockholmStructure.getConsAnnotation().setIntron(value); - } else if (featureName.equals(GC_REFERENCE_ANNOTATION)) { - stockholmStructure.getConsAnnotation().setReferenceAnnotation(value); - } else if (featureName.equals(GC_MODEL_MASK)) { - stockholmStructure.getConsAnnotation().setModelMask(value); - } else { - // unknown feature - logger.warn("Unknown Consensus Feature [{}].\nPlease contact the Biojava team.", featureName); + switch (featureName) { + case GC_SECONDARY_STRUCTURE: + stockholmStructure.getConsAnnotation().setSecondaryStructure(value); + break; + case GC_SEQUENSE_CONSENSUS: + stockholmStructure.getConsAnnotation().setSequenceConsensus(value); + break; + case GC_SURFACE_ACCESSIBILITY: + stockholmStructure.getConsAnnotation().setSurfaceAccessibility(value); + break; + case GC_TRANS_MEMBRANE: + stockholmStructure.getConsAnnotation().setTransMembrane(value); + break; + case GC_POSTERIOR_PROBABILITY: + stockholmStructure.getConsAnnotation().setPosteriorProbability(value); + break; + case GC_LIGAND_BINDING: + stockholmStructure.getConsAnnotation().setLigandBinding(value); + break; + case GC_ACTIVE_SITE: + stockholmStructure.getConsAnnotation().setActiveSite(value); + break; + case GC_AS_PFAM_PREDICTED: + stockholmStructure.getConsAnnotation().setAsPFamPredicted(value); + break; + case GC_AS_SWISSPROT: + stockholmStructure.getConsAnnotation().setAsSwissProt(value); + break; + case GC_INTRON: + stockholmStructure.getConsAnnotation().setIntron(value); + break; + case GC_REFERENCE_ANNOTATION: + stockholmStructure.getConsAnnotation().setReferenceAnnotation(value); + break; + case GC_MODEL_MASK: + stockholmStructure.getConsAnnotation().setModelMask(value); + break; + default: + // unknown feature + logger.warn("Unknown Consensus Feature [{}].\nPlease contact the Biojava team.", featureName); + break; } } @@ -667,21 +715,29 @@ private void handleConsensusAnnotation(String featureName, String value) { * the line to be parsed */ private void handleSequenceAnnotation(String seqName, String featureName, String value) { - if (featureName.equals(GS_ACCESSION_NUMBER)) { - stockholmStructure.addGSAccessionNumber(seqName, value); - } else if (featureName.equals(GS_DESCRIPTION)) { - stockholmStructure.addGSDescription(seqName, value); - } else if (featureName.equals(GS_DATABASE_REFERENCE)) { - stockholmStructure.addGSdbReference(seqName, value); - } else if (featureName.equals(GS_ORGANISM_SPECIES)) { - stockholmStructure.addGSOrganismSpecies(seqName, value); - } else if (featureName.equals(GS_ORGANISM_CLASSIFICATION)) { - stockholmStructure.addGSOrganismClassification(seqName, value); - } else if (featureName.equals(GS_LOOK)) { - stockholmStructure.addGSLook(seqName, value); - } else { - // unknown feature - logger.warn("Unknown Sequence Feature [{}].\nPlease contact the Biojava team.", featureName); + switch (featureName) { + case GS_ACCESSION_NUMBER: + stockholmStructure.addGSAccessionNumber(seqName, value); + break; + case GS_DESCRIPTION: + stockholmStructure.addGSDescription(seqName, value); + break; + case GS_DATABASE_REFERENCE: + stockholmStructure.addGSdbReference(seqName, value); + break; + case GS_ORGANISM_SPECIES: + stockholmStructure.addGSOrganismSpecies(seqName, value); + break; + case GS_ORGANISM_CLASSIFICATION: + stockholmStructure.addGSOrganismClassification(seqName, value); + break; + case GS_LOOK: + stockholmStructure.addGSLook(seqName, value); + break; + default: + // unknown feature + logger.warn("Unknown Sequence Feature [{}].\nPlease contact the Biojava team.", featureName); + break; } } @@ -693,27 +749,38 @@ private void handleSequenceAnnotation(String seqName, String featureName, String */ private void handleResidueAnnotation(String seqName, String featureName, String value) { - if (featureName.equals(GR_SURFACE_ACCESSIBILITY)) { - stockholmStructure.addSurfaceAccessibility(seqName, value); - } else if (featureName.equals(GR_TRANS_MEMBRANE)) { - stockholmStructure.addTransMembrane(seqName, value); - } else if (featureName.equals(GR_POSTERIOR_PROBABILITY)) { - stockholmStructure.addPosteriorProbability(seqName, value); - } else if (featureName.equals(GR_LIGAND_BINDING)) { - stockholmStructure.addLigandBinding(seqName, value); - } else if (featureName.equals(GR_ACTIVE_SITE)) { - stockholmStructure.addActiveSite(seqName, value); - } else if (featureName.equals(GR_AS_PFAM_PREDICTED)) { - stockholmStructure.addASPFamPredicted(seqName, value); - } else if (featureName.equals(GR_AS_SWISSPROT)) { - stockholmStructure.addASSwissProt(seqName, value); - } else if (featureName.equals(GR_INTRON)) { - stockholmStructure.addIntron(seqName, value); - } else if (featureName.equals(GR_SECONDARY_STRUCTURE)) { - stockholmStructure.addSecondaryStructure(seqName, value); - } else { - // unknown feature - logger.warn("Unknown Residue Feature [{}].\nPlease contact the Biojava team.", featureName); + switch (featureName) { + case GR_SURFACE_ACCESSIBILITY: + stockholmStructure.addSurfaceAccessibility(seqName, value); + break; + case GR_TRANS_MEMBRANE: + stockholmStructure.addTransMembrane(seqName, value); + break; + case GR_POSTERIOR_PROBABILITY: + stockholmStructure.addPosteriorProbability(seqName, value); + break; + case GR_LIGAND_BINDING: + stockholmStructure.addLigandBinding(seqName, value); + break; + case GR_ACTIVE_SITE: + stockholmStructure.addActiveSite(seqName, value); + break; + case GR_AS_PFAM_PREDICTED: + stockholmStructure.addASPFamPredicted(seqName, value); + break; + case GR_AS_SWISSPROT: + stockholmStructure.addASSwissProt(seqName, value); + break; + case GR_INTRON: + stockholmStructure.addIntron(seqName, value); + break; + case GR_SECONDARY_STRUCTURE: + stockholmStructure.addSecondaryStructure(seqName, value); + break; + default: + // unknown feature + logger.warn("Unknown Residue Feature [{}].\nPlease contact the Biojava team.", featureName); + break; } } } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmSequenceAnnotation.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmSequenceAnnotation.java index 9044c3a34c..0bf25c1a4a 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmSequenceAnnotation.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmSequenceAnnotation.java @@ -74,7 +74,7 @@ public void setDbReferences(Set dbReferences) { */ public void addDBReference(String dbReferenceRepresentingString) { if (this.dbReferences == null) { - this.dbReferences = new HashSet(); + this.dbReferences = new HashSet<>(); } dbReferences.add(new DatabaseReference(dbReferenceRepresentingString)); } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmStructure.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmStructure.java index 494d8290a2..692f26d8bc 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmStructure.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/io/StockholmStructure.java @@ -94,9 +94,9 @@ public class StockholmStructure { public StockholmStructure() { fileAnnotation = new StockholmFileAnnotation(); consAnnotation = new StockholmConsensusAnnotation(); - sequences = new HashMap(); - seqsAnnotation = new HashMap(); - resAnnotation = new HashMap(); + sequences = new HashMap<>(); + seqsAnnotation = new HashMap<>(); + resAnnotation = new HashMap<>(); } public StockholmFileAnnotation getFileAnnotation() { @@ -235,10 +235,11 @@ public List> getBioSequences(boolea if (forcedSequenceType != null && !(forcedSequenceType.equals(PFAM) || forcedSequenceType.equals(RFAM))) { throw new IllegalArgumentException("Illegal Argument " + forcedSequenceType); } - List> seqs = new ArrayList>(); - for (String sequencename : sequences.keySet()) { - AbstractSequence seq = null; - String sequence = sequences.get(sequencename).toString(); + List> seqs = new ArrayList<>(); + for (Map.Entry entry : sequences.entrySet()) { + String sequencename = entry.getKey(); + AbstractSequence seq; + String sequence = entry.getValue().toString(); if (ignoreCase) { sequence = sequence.toUpperCase(); } @@ -256,9 +257,8 @@ else if (forcedSequenceType.equals(PFAM)) } String[] seqDetails = splitSeqName(sequencename); seq.setDescription(seqDetails[0]); - seq.setBioBegin((seqDetails[1] == null || seqDetails[1].trim().equals("") ? null : new Integer( - seqDetails[1]))); - seq.setBioEnd((seqDetails[2] == null || seqDetails[2].trim().equals("") ? null : new Integer(seqDetails[2]))); + seq.setBioBegin((seqDetails[1] == null || seqDetails[1].trim().isEmpty() ? null : Integer.valueOf(seqDetails[1]))); + seq.setBioEnd((seqDetails[2] == null || seqDetails[2].trim().isEmpty() ? null : Integer.valueOf(seqDetails[2]))); seqs.add(seq); } @@ -308,22 +308,22 @@ private String[] splitSeqName(String sequenceName) { @Override public String toString() { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); List> bioSeqs = getBioSequences(false); int sequenceLength = -1; for (AbstractSequence sequence : bioSeqs) { String sequenceAsString = sequence.getSequenceAsString(); sequenceLength = sequenceAsString.length(); if (sequenceLength > 50) { - result.append(sequenceAsString.substring(0, 40)); + result.append(sequenceAsString, 0, 40); result.append("..."); - result.append(sequenceAsString.substring(sequenceLength - 3, sequenceLength)); + result.append(sequenceAsString, sequenceLength - 3, sequenceLength); } else { result.append(sequenceAsString); } - result.append(" " + sequence.getDescription() + "\n"); + result.append(" ").append(sequence.getDescription()).append("\n"); } - result.append("Alignment with " + bioSeqs.size() + " rows and " + sequenceLength + " columns"); + result.append("Alignment with ").append(bioSeqs.size()).append(" rows and ").append(sequenceLength).append(" columns"); return result.toString(); } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/AlignerHelper.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/AlignerHelper.java index edba157916..bb7aeaa16f 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/AlignerHelper.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/AlignerHelper.java @@ -62,8 +62,11 @@ public enum Last { */ public static class Cut { - private int queryIndex; - private int[][] targetIndices, tiLast, ti1, ti2; + private final int queryIndex; + private int[][] targetIndices; + private int[][] tiLast; + private final int[][] ti1; + private final int[][] ti2; public Cut(int queryIndex, int[] dim) { this.queryIndex = queryIndex; @@ -171,7 +174,7 @@ public static int addAnchors(Cut[] cuts, int[] scores, boolean addScore, int[] a for (Cut c : cuts) { anchors[c.getQueryIndex()] = c.getTargetIndex(zMax); } - return addScore ? (int) subscore : 0; + return addScore ? subscore : 0; } public static Cut[] getCuts(int k, Subproblem subproblem, int[] dim, boolean anchor0) { @@ -244,11 +247,11 @@ public int getQueryStartIndex() { public boolean isStartAnchored() { return isAnchored; } - private int queryStartIndex; // [0] - private int targetStartIndex; // [1] - private int queryEndIndex; // [2] - private int targetEndIndex; // [3] - private boolean isAnchored; + private final int queryStartIndex; // [0] + private final int targetStartIndex; // [1] + private final int queryEndIndex; // [2] + private final int targetEndIndex; // [3] + private final boolean isAnchored; public Subproblem(int queryStartIndex, int targetStartIndex, int queryEndIndex, int targetEndIndex) { this(queryStartIndex, targetStartIndex, queryEndIndex, targetEndIndex, false); } @@ -267,8 +270,8 @@ public Subproblem(int queryStartIndex, int targetStartIndex, int queryEndIndex, * @return list alignment subproblems */ public static List getSubproblems(List anchors, int querySequenceLength, int targetSequenceLength) { - Collections.sort(anchors, new Anchor.QueryIndexComparator()); - List list = new ArrayList(); + anchors.sort(new Anchor.QueryIndexComparator()); + List list = new ArrayList<>(); Anchor last = new Anchor(-1, -1); // sentinal anchor boolean isAnchored = false; for (int i = 0; i < anchors.size(); i++) { diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/AnchoredPairwiseSequenceAligner.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/AnchoredPairwiseSequenceAligner.java index 41b9502782..64b32ff317 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/AnchoredPairwiseSequenceAligner.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/AnchoredPairwiseSequenceAligner.java @@ -23,17 +23,18 @@ package org.biojava.nbio.alignment.routines; -import org.biojava.nbio.core.alignment.SimpleSequencePair; import org.biojava.nbio.alignment.routines.AlignerHelper.Anchor; import org.biojava.nbio.alignment.template.AbstractPairwiseSequenceAligner; +import org.biojava.nbio.alignment.template.GapPenalty; +import org.biojava.nbio.core.alignment.SimpleSequencePair; import org.biojava.nbio.core.alignment.template.AlignedSequence; import org.biojava.nbio.core.alignment.template.AlignedSequence.Step; -import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; /** @@ -96,9 +97,7 @@ public AnchoredPairwiseSequenceAligner(S query, S target, GapPenalty gapPenalty, */ public int[] getAnchors() { int[] anchor = new int[getScoreMatrixDimensions()[0] - 1]; - for (int i = 0; i < anchor.length; i++) { - anchor[i] = -1; - } + Arrays.fill(anchor, -1); for (int i = 0; i < anchors.size(); i++) { anchor[anchors.get(i).getQueryIndex()] = anchors.get(i).getTargetIndex(); } @@ -111,7 +110,7 @@ public int[] getAnchors() { * @param anchors list of points that are tied to the given indices in the target */ public void setAnchors(int[] anchors) { - super.anchors = new ArrayList(); + super.anchors = new ArrayList<>(); if (anchors != null) { for (int i = 0; i < anchors.length; i++) { if (anchors[i] >= 0) { @@ -133,7 +132,7 @@ public void addAnchor(int queryIndex, int targetIndex) { @Override protected void setProfile(List sx, List sy) { - profile = pair = new SimpleSequencePair(getQuery(), getTarget(), sx, sy); + profile = pair = new SimpleSequencePair<>(getQuery(), getTarget(), sx, sy); } } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/GuanUberbacher.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/GuanUberbacher.java index 3ff44d8a8c..e1471ffab4 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/GuanUberbacher.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/routines/GuanUberbacher.java @@ -23,8 +23,8 @@ package org.biojava.nbio.alignment.routines; -import org.biojava.nbio.core.alignment.template.AlignedSequence; import org.biojava.nbio.alignment.template.GapPenalty; +import org.biojava.nbio.core.alignment.template.AlignedSequence; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; @@ -42,7 +42,7 @@ */ public class GuanUberbacher, C extends Compound> extends AnchoredPairwiseSequenceAligner { - private static int defaultCutsPerSection = 10; + private static final int defaultCutsPerSection = 10; /** * Sets the default number of cuts added to each section during each pass. diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractMatrixAligner.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractMatrixAligner.java index b5e6f6188c..4fbd047a58 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractMatrixAligner.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractMatrixAligner.java @@ -23,12 +23,12 @@ package org.biojava.nbio.alignment.template; -import org.biojava.nbio.core.alignment.template.Profile; -import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.alignment.routines.AlignerHelper.Anchor; import org.biojava.nbio.alignment.routines.AlignerHelper.Last; import org.biojava.nbio.alignment.routines.AlignerHelper.Subproblem; import org.biojava.nbio.core.alignment.template.AlignedSequence.Step; +import org.biojava.nbio.core.alignment.template.Profile; +import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.CompoundSet; import org.biojava.nbio.core.sequence.template.Sequence; @@ -55,7 +55,7 @@ public abstract class AbstractMatrixAligner, C extends Com protected GapPenalty gapPenalty; private SubstitutionMatrix subMatrix; private boolean local, storingScoreMatrix; - protected List anchors = new ArrayList(); + protected List anchors = new ArrayList<>(); protected int cutsPerSection; // output fields @@ -218,8 +218,8 @@ private String scoreMatrixToString(int[][][] scores) { CompoundSet compoundSet = getCompoundSet(); int lengthCompound = compoundSet.getMaxSingleCompoundStringLength(), lengthRest = Math.max(Math.max(Integer.toString(min).length(), Integer.toString(max).length()), lengthCompound) + 1; - String padCompound = "%" + Integer.toString(lengthCompound) + "s", - padRest = "%" + Integer.toString(lengthRest); + String padCompound = "%" + lengthCompound + "s", + padRest = "%" + lengthRest; List query = getCompoundsOfQuery(), target = getCompoundsOfTarget(); for (int type = 0; type < scores[0][0].length; type++) { if (type > 0) { @@ -312,8 +312,10 @@ protected void align() { } boolean linear = (gapPenalty.getType() == GapPenalty.Type.LINEAR); Last[][][] traceback = new Last[dim[0]][][]; - List sx = new ArrayList(), sy = new ArrayList(); + List sx = new ArrayList<>(), sy = new ArrayList<>(); + int extensionPenalty = gapPenalty.getExtensionPenalty(); + int openPenalty = gapPenalty.getOpenPenalty(); if (!local) { xyMax = new int[] { dim[0] - 1, dim[1] - 1 }; xyStart = new int[] { 0, 0 }; @@ -324,12 +326,11 @@ protected void align() { Subproblem subproblem = problems.get(i); for (int x = subproblem.getQueryStartIndex(); x <= subproblem.getQueryEndIndex(); x++) { - traceback[x] = - - linear ? - setScoreVector(x, subproblem, gapPenalty.getExtensionPenalty(), getSubstitutionScoreVector(x, subproblem), storingScoreMatrix, scores) : + int[] scoreVector = getSubstitutionScoreVector(x, subproblem); - setScoreVector(x, subproblem, gapPenalty.getOpenPenalty(), gapPenalty.getExtensionPenalty(), getSubstitutionScoreVector(x, subproblem), storingScoreMatrix, scores); + traceback[x] = linear ? + setScoreVector(x, subproblem, extensionPenalty, scoreVector, storingScoreMatrix, scores) : + setScoreVector(x, subproblem, openPenalty, extensionPenalty, scoreVector, storingScoreMatrix, scores); } } setSteps(traceback, scores, sx, sy); @@ -341,25 +342,20 @@ protected void align() { } else { for (int x = 0; x < dim[0]; x++) { - traceback[x] = - - linear ? - setScoreVector(x, gapPenalty.getExtensionPenalty(), getSubstitutionScoreVector(x), storingScoreMatrix, scores, xyMax, score) : - - setScoreVector(x, gapPenalty.getOpenPenalty(), gapPenalty.getExtensionPenalty(), getSubstitutionScoreVector(x), storingScoreMatrix, scores, xyMax, score); - - if (xyMax[0] == x) { - score = scores[x][xyMax[1]][0]; - } + int[] score = getSubstitutionScoreVector(x); + traceback[x] = linear ? + setScoreVector(x, extensionPenalty, score, storingScoreMatrix, scores, xyMax, this.score) : + setScoreVector(x, openPenalty, extensionPenalty, score, storingScoreMatrix, scores, xyMax, this.score); + if (xyMax[0] == x) + this.score = scores[x][xyMax[1]][0]; } xyStart = local ? setSteps(traceback, xyMax, sx, sy) : setSteps(traceback, scores, sx, sy); } setProfile(sx, sy); - if (!storingScoreMatrix) { + if (!storingScoreMatrix) scores = null; - } time = System.nanoTime() - timeStart; } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractPairwiseSequenceAligner.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractPairwiseSequenceAligner.java index 8c86470608..abd765b089 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractPairwiseSequenceAligner.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractPairwiseSequenceAligner.java @@ -137,12 +137,12 @@ protected CompoundSet getCompoundSet() { @Override protected List getCompoundsOfQuery() { - return (query == null) ? new ArrayList() : query.getAsList(); + return (query == null) ? new ArrayList<>() : query.getAsList(); } @Override protected List getCompoundsOfTarget() { - return (target == null) ? new ArrayList() : target.getAsList(); + return (target == null) ? new ArrayList<>() : target.getAsList(); } @Override @@ -176,7 +176,7 @@ protected void reset() { maxt += getSubstitutionMatrix().getValue(c, c); } max = Math.max(maxq, maxt); - score = min = isLocal() ? 0 : (int) (2 * getGapPenalty().getOpenPenalty() + (query.getLength() + + score = min = isLocal() ? 0 : (2 * getGapPenalty().getOpenPenalty() + (query.getLength() + target.getLength()) * getGapPenalty().getExtensionPenalty()); } } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractProfileProfileAligner.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractProfileProfileAligner.java index 01cba48463..95af0ea5ff 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractProfileProfileAligner.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/AbstractProfileProfileAligner.java @@ -23,10 +23,10 @@ package org.biojava.nbio.alignment.template; -import org.biojava.nbio.core.alignment.template.ProfilePair; +import org.biojava.nbio.alignment.template.GapPenalty.Type; import org.biojava.nbio.core.alignment.template.Profile; +import org.biojava.nbio.core.alignment.template.ProfilePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; -import org.biojava.nbio.alignment.template.GapPenalty.Type; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.CompoundSet; import org.biojava.nbio.core.sequence.template.Sequence; @@ -189,13 +189,13 @@ protected CompoundSet getCompoundSet() { @Override protected List getCompoundsOfQuery() { // TODO replace with consensus sequence - return (query == null) ? new ArrayList() : query.getAlignedSequence(1).getAsList(); + return (query == null) ? new ArrayList<>() : query.getAlignedSequence(1).getAsList(); } @Override protected List getCompoundsOfTarget() { // TODO replace with consensus sequence - return (target == null) ? new ArrayList() : target.getAlignedSequence(1).getAsList(); + return (target == null) ? new ArrayList<>() : target.getAlignedSequence(1).getAsList(); } @Override @@ -236,7 +236,7 @@ protected void reset() { if (query != null && target != null && getGapPenalty() != null && getSubstitutionMatrix() != null && query.getCompoundSet().equals(target.getCompoundSet())) { int maxq = 0, maxt = 0; - cslist = query.getCompoundSet().getAllCompounds(); + cslist = new ArrayList(query.getCompoundSet().getAllCompounds()); qfrac = new float[query.getLength()][]; for (int i = 0; i < qfrac.length; i++) { qfrac[i] = query.getCompoundWeightsAt(i + 1, cslist); @@ -248,24 +248,27 @@ protected void reset() { maxt += getSubstitutionScore(tfrac[i], tfrac[i]); } max = Math.max(maxq, maxt); - score = min = isLocal() ? 0 : (int) (2 * getGapPenalty().getOpenPenalty() + (query.getLength() + + score = min = isLocal() ? 0 : (2 * getGapPenalty().getOpenPenalty() + (query.getLength() + target.getLength()) * getGapPenalty().getExtensionPenalty()); } } // helper method that scores alignment of two column vectors private int getSubstitutionScore(float[] qv, float[] tv) { - float score = 0.0f; + double score = 0.0; + SubstitutionMatrix s = getSubstitutionMatrix(); for (int q = 0; q < qv.length; q++) { - if (qv[q] > 0.0f) { + float qvq = qv[q]; + if (qvq > 0.0) { + C cq = cslist.get(q); for (int t = 0; t < tv.length; t++) { - if (tv[t] > 0.0f) { - score += qv[q]*tv[t]*getSubstitutionMatrix().getValue(cslist.get(q), cslist.get(t)); - } + float tvt = tv[t]; + if (tvt > 0.0) + score += qvq * tvt * s.getValue(cq, cslist.get(t)); } } } - return Math.round(score); + return (int) Math.round(score); //TODO return double? } } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallablePairwiseSequenceAligner.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallablePairwiseSequenceAligner.java index e1c4616620..6725a47f5f 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallablePairwiseSequenceAligner.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallablePairwiseSequenceAligner.java @@ -39,7 +39,7 @@ public class CallablePairwiseSequenceAligner, C extends Compound> implements Callable> { - private PairwiseSequenceAligner psa; + private final PairwiseSequenceAligner psa; /** * Creates a pairwise sequence alignment task for simplified parallel execution. diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallablePairwiseSequenceScorer.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallablePairwiseSequenceScorer.java index d5d3d4b243..4d8d833bcd 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallablePairwiseSequenceScorer.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallablePairwiseSequenceScorer.java @@ -37,7 +37,7 @@ */ public class CallablePairwiseSequenceScorer, C extends Compound> implements Callable { - private PairwiseSequenceScorer pss; + private final PairwiseSequenceScorer pss; /** * Creates a pairwise sequence scoring task for simplified parallel execution. diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallableProfileProfileAligner.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallableProfileProfileAligner.java index 063426a91a..27a0c812d3 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallableProfileProfileAligner.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/CallableProfileProfileAligner.java @@ -39,7 +39,7 @@ public class CallableProfileProfileAligner, C extends Compound> implements Callable> { - private ProfileProfileAligner ppa; + private final ProfileProfileAligner ppa; /** * Creates a profile-profile alignment task for simplified parallel execution. diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/GapPenalty.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/GapPenalty.java index 1c3aab1978..ef8fe96133 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/GapPenalty.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/GapPenalty.java @@ -39,9 +39,9 @@ public interface GapPenalty { *
  • DYNAMIC, if penalty values change during alignment * */ - enum Type {CONSTANT, LINEAR, AFFINE, DYNAMIC}; + enum Type {CONSTANT, LINEAR, AFFINE, DYNAMIC} - /** + /** * Returns penalty given when an already open gap elongates by a single element * * @return gap extension penalty diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/GuideTreeNode.java b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/GuideTreeNode.java index 76b16261e6..a212fac464 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/GuideTreeNode.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/alignment/template/GuideTreeNode.java @@ -23,8 +23,8 @@ package org.biojava.nbio.alignment.template; -import org.biojava.nbio.core.alignment.template.ProfilePair; import org.biojava.nbio.core.alignment.template.Profile; +import org.biojava.nbio.core.alignment.template.ProfilePair; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/Comparison.java b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/Comparison.java index dc8ead79a7..f5081a04f6 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/Comparison.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/Comparison.java @@ -44,12 +44,12 @@ public class Comparison { * SequenceI * @return float */ - public final static float PID(String seq1, String seq2) { + public static float PID(String seq1, String seq2) { return PID(seq1, seq2, 0, seq1.length()); } // Another pid with region specification - public final static float PID(String seq1, String seq2, int start, int end) { + public static float PID(String seq1, String seq2, int start, int end) { int s1len = seq1.length(); int s2len = seq2.length(); @@ -100,8 +100,8 @@ public final static float PID(String seq1, String seq2, int start, int end) { * * @return true if it is a gap, false otherwise */ - public static final boolean isGap(char c) { - return (c == '-' || c == '.' || c == ' ') ? true : false; + public static boolean isGap(char c) { + return c == '-' || c == '.' || c == ' '; } } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/DistanceMatrixCalculator.java b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/DistanceMatrixCalculator.java index d0464bae8b..f8fd3bb1fc 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/DistanceMatrixCalculator.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/DistanceMatrixCalculator.java @@ -20,8 +20,6 @@ */ package org.biojava.nbio.phylo; -import java.io.IOException; -import java.util.List; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.MultipleSequenceAlignment; import org.biojava.nbio.core.sequence.template.Compound; @@ -33,6 +31,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.util.List; + /** * The DistanceMatrixCalculator methods generate a {@link DistanceMatrix} from a * {@link MultipleSequenceAlignment} or other indirect distance infomation (RMSD). diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/DistanceTreeEvaluator.java b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/DistanceTreeEvaluator.java index ec9e274ab6..8a7d649949 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/DistanceTreeEvaluator.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/DistanceTreeEvaluator.java @@ -66,8 +66,8 @@ private DistanceTreeEvaluator() { public static double evaluate(Phylogeny tree, DistanceMatrix matrix) { int numSequences = matrix.getSize(); List externalNodes = tree.getExternalNodes(); - HashMap externalNodesHashMap = new HashMap(); - Set path = new HashSet(); + HashMap externalNodesHashMap = new HashMap<>(); + Set path = new HashSet<>(); for (PhylogenyNode node : externalNodes) { externalNodesHashMap.put(node.getName(), node); diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/ForesterWrapper.java b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/ForesterWrapper.java index 74cdf2e2f4..34acacc00b 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/ForesterWrapper.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/ForesterWrapper.java @@ -20,12 +20,8 @@ */ package org.biojava.nbio.phylo; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; import org.biojava.nbio.core.sequence.MultipleSequenceAlignment; import org.biojava.nbio.core.sequence.io.FastaWriter; -import org.biojava.nbio.core.sequence.io.template.FastaHeaderFormatInterface; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix; @@ -34,6 +30,10 @@ import org.forester.msa.Msa; import org.forester.phylogeny.Phylogeny; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; + /** * This class contains wrapper methods for communication between BioJava and * forester (e.g, Data Structure conversion). @@ -64,14 +64,9 @@ public static , D extends Compound> Msa convert( // Convert the biojava MSA to a FASTA String OutputStream os = new ByteArrayOutputStream(); - FastaWriter fastaW = new FastaWriter(os, + FastaWriter fastaW = new FastaWriter<>(os, msa.getAlignedSequences(), - new FastaHeaderFormatInterface() { - @Override - public String getHeader(C sequence) { - return sequence.getAccession().toString(); - }; - }); + sequence -> sequence.getAccession().toString()); fastaW.process(); String fastaMSA = os.toString(); diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/TreeConstructorType.java b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/TreeConstructorType.java index d3f632046b..ba12f8251c 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/TreeConstructorType.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/TreeConstructorType.java @@ -38,5 +38,5 @@ public enum TreeConstructorType { UPGMA, /** What does this stand for? (Aleix: Nov 2015) */ - AV; + AV } diff --git a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/TreeType.java b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/TreeType.java index 1f2896e923..d380219465 100644 --- a/biojava-alignment/src/main/java/org/biojava/nbio/phylo/TreeType.java +++ b/biojava-alignment/src/main/java/org/biojava/nbio/phylo/TreeType.java @@ -41,7 +41,7 @@ public enum TreeType { /** Description name of the Tree Type */ protected final String name; - private TreeType(String name){ + TreeType(String name){ this.name = name; } } diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignAllGlobal.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignAllGlobal.java index 9deee78c08..8d5d3f2543 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignAllGlobal.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignAllGlobal.java @@ -20,8 +20,8 @@ */ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; +import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; import org.biojava.nbio.core.alignment.template.SequencePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.ProteinSequence; @@ -45,7 +45,7 @@ public static void main(String[] args) { } private static void alignAllGlobal(String[] ids) throws Exception { - List lst = new ArrayList(); + List lst = new ArrayList<>(); for (String id : ids) { lst.add(getSequenceForId(id)); } diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignAllLocal.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignAllLocal.java index a56463159e..888a1e6cc5 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignAllLocal.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignAllLocal.java @@ -20,8 +20,8 @@ */ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; +import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; import org.biojava.nbio.core.alignment.template.SequencePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.ProteinSequence; @@ -45,7 +45,7 @@ public static void main(String[] args) { } private static void alignAllLocal(String[] ids) throws Exception { - List lst = new ArrayList(); + List lst = new ArrayList<>(); for (String id : ids) { lst.add(getSequenceForId(id)); } diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignPairGlobal.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignPairGlobal.java index e93dc28b07..a56961a395 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignPairGlobal.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignPairGlobal.java @@ -20,8 +20,8 @@ */ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; +import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; import org.biojava.nbio.core.alignment.template.SequencePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.ProteinSequence; diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignPairLocal.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignPairLocal.java index 40ff627d29..c5a8a0ff1c 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignPairLocal.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookAlignPairLocal.java @@ -20,8 +20,8 @@ */ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; +import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; import org.biojava.nbio.core.alignment.template.SequencePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.ProteinSequence; diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookMSA.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookMSA.java index cfe3fcc05e..24085e698d 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookMSA.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookMSA.java @@ -42,7 +42,7 @@ public static void main(String[] args) { } private static void multipleSequenceAlignment(String[] ids) throws Exception { - List lst = new ArrayList(); + List lst = new ArrayList<>(); for (String id : ids) { lst.add(getSequenceForId(id)); } diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookMSAProfiler.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookMSAProfiler.java index 55a4c7d0ec..a290ff09b1 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookMSAProfiler.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/CookbookMSAProfiler.java @@ -20,11 +20,11 @@ */ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceScorerType; import org.biojava.nbio.alignment.Alignments.ProfileProfileAlignerType; import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.alignment.template.PairwiseSequenceScorer; +import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; import org.biojava.nbio.core.alignment.template.Profile; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.sequence.ProteinSequence; @@ -81,8 +81,7 @@ public static void main(String[] args) throws Exception { Profiler profiler = new Profiler(); System.out.printf("Loading sequences from %s... ", args[0]); - List list = new ArrayList(); - list.addAll(FastaReaderHelper.readFastaProteinSequence(new File(args[0])).values()); + List list = new ArrayList<>(FastaReaderHelper.readFastaProteinSequence(new File(args[0])).values()); if (args.length > 1 && Integer.parseInt(args[1]) < list.size()) { System.out.printf("%s/%d", args[1], list.size()); list = list.subList(0, Integer.parseInt(args[1])); @@ -106,7 +105,7 @@ public static void main(String[] args) throws Exception { profiler.setCheckpoint(); System.out.print("Stage 2: hierarchical clustering into a guide tree... "); - GuideTree tree = new GuideTree(list, + GuideTree tree = new GuideTree<>(list, scorers); scorers = null; System.out.printf("%d ms using %d kB%n%n%s%n%n", profiler.getTimeSinceCheckpoint()/1000000, diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/FractionalIdentityScorerTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/FractionalIdentityScorerTest.java index 08bf9c73f8..5528155d8e 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/FractionalIdentityScorerTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/FractionalIdentityScorerTest.java @@ -23,9 +23,9 @@ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.alignment.template.PairwiseSequenceScorer; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.ProteinSequence; @@ -52,20 +52,20 @@ public void setup() throws CompoundNotFoundException { target = new ProteinSequence("RDG"); gaps = new SimpleGapPenalty((short) 10, (short) 1); blosum62 = SubstitutionMatrixHelper.getBlosum62(); - alignment = new NeedlemanWunsch(query, target, gaps, blosum62); - self = new NeedlemanWunsch(query, query, gaps, blosum62); - scorer1 = new FractionalIdentityScorer(alignment); - scorer2 = new FractionalIdentityScorer(self); + alignment = new NeedlemanWunsch<>(query, target, gaps, blosum62); + self = new NeedlemanWunsch<>(query, query, gaps, blosum62); + scorer1 = new FractionalIdentityScorer<>(alignment); + scorer2 = new FractionalIdentityScorer<>(self); } @Test public void testFractionalIdentityScorerPairwiseSequenceAlignerOfSC() { - assertNotNull(new FractionalIdentityScorer(alignment)); + assertNotNull(new FractionalIdentityScorer<>(alignment)); } @Test public void testFractionalIdentityScorerSequencePairOfSC() { - assertNotNull(new FractionalIdentityScorer(alignment.getPair())); + assertNotNull(new FractionalIdentityScorer<>(alignment.getPair())); } @Test diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/FractionalSimilarityScorerTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/FractionalSimilarityScorerTest.java index 26d7615d44..5f03604f26 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/FractionalSimilarityScorerTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/FractionalSimilarityScorerTest.java @@ -24,9 +24,9 @@ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.alignment.template.PairwiseSequenceScorer; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.ProteinSequence; @@ -53,20 +53,20 @@ public void setup() throws CompoundNotFoundException { target = new ProteinSequence("RADG"); gaps = new SimpleGapPenalty((short) 2, (short) 1); blosum62 = SubstitutionMatrixHelper.getBlosum62(); - alignment = new NeedlemanWunsch(query, target, gaps, blosum62); - self = new NeedlemanWunsch(query, query, gaps, blosum62); - scorer1 = new FractionalSimilarityScorer(alignment); - scorer2 = new FractionalSimilarityScorer(self); + alignment = new NeedlemanWunsch<>(query, target, gaps, blosum62); + self = new NeedlemanWunsch<>(query, query, gaps, blosum62); + scorer1 = new FractionalSimilarityScorer<>(alignment); + scorer2 = new FractionalSimilarityScorer<>(self); } @Test public void testFractionalSimilarityScorerPairwiseSequenceAlignerOfSC() { - assertNotNull(new FractionalSimilarityScorer(alignment)); + assertNotNull(new FractionalSimilarityScorer<>(alignment)); } @Test public void testFractionalSimilarityScorerSequencePairOfSC() { - assertNotNull(new FractionalSimilarityScorer(alignment.getPair())); + assertNotNull(new FractionalSimilarityScorer<>(alignment.getPair())); } @Test diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/GuideTreeTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/GuideTreeTest.java index 08adf113ec..a9ba7f6c78 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/GuideTreeTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/GuideTreeTest.java @@ -23,11 +23,11 @@ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceScorerType; import org.biojava.nbio.alignment.Alignments.ProfileProfileAlignerType; import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.alignment.template.GuideTreeNode; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.ProteinSequence; @@ -49,11 +49,11 @@ public class GuideTreeTest { @Before public void setup() throws CompoundNotFoundException { - proteins = Arrays.asList(new ProteinSequence[] {new ProteinSequence("ARND"), new ProteinSequence("ARND"), - new ProteinSequence("HILK"), new ProteinSequence("ANDR")}); + proteins = Arrays.asList(new ProteinSequence("ARND"), new ProteinSequence("ARND"), + new ProteinSequence("HILK"), new ProteinSequence("ANDR")); gaps = new SimpleGapPenalty((short) 2, (short) 1); blosum62 = SubstitutionMatrixHelper.getBlosum62(); - tree = new GuideTree(proteins, Alignments.getAllPairsScorers(proteins, + tree = new GuideTree<>(proteins, Alignments.getAllPairsScorers(proteins, PairwiseSequenceScorerType.GLOBAL_IDENTITIES, gaps, blosum62)); } @@ -112,12 +112,13 @@ public void testIterator() { switch (i++) { case 0: assertEquals(n.getName(), "1"); break; case 1: assertEquals(n.getName(), "2"); break; - case 2: assertEquals(n.getName(), ""); break; + case 2: + case 6: + case 4: + assertEquals(n.getName(), ""); break; case 3: assertEquals(n.getName(), "3"); break; - case 4: assertEquals(n.getName(), ""); break; - case 5: assertEquals(n.getName(), "4"); break; - case 6: assertEquals(n.getName(), ""); break; - } + case 5: assertEquals(n.getName(), "4"); break; + } } } diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/LocalAlignmentTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/LocalAlignmentTest.java index c4d88ebddb..c99d59b945 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/LocalAlignmentTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/LocalAlignmentTest.java @@ -22,9 +22,9 @@ */ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; import org.biojava.nbio.alignment.template.PairwiseSequenceAligner; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.DNASequence; diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/NeedlemanWunschTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/NeedlemanWunschTest.java index 5b44fc25f4..2cc98c4315 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/NeedlemanWunschTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/NeedlemanWunschTest.java @@ -23,10 +23,10 @@ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.alignment.template.PairwiseSequenceAligner; +import org.biojava.nbio.core.alignment.matrices.SimpleSubstitutionMatrix; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.DNASequence; @@ -38,9 +38,7 @@ import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; public class NeedlemanWunschTest { @@ -57,15 +55,15 @@ public void setup() throws CompoundNotFoundException { target = new ProteinSequence("RDG"); gaps = new SimpleGapPenalty(10, 1); blosum62 = SubstitutionMatrixHelper.getBlosum62(); - alignment = new NeedlemanWunsch(query, target, gaps, blosum62); - self = new NeedlemanWunsch(query, query, gaps, blosum62); + alignment = new NeedlemanWunsch<>(query, target, gaps, blosum62); + self = new NeedlemanWunsch<>(query, query, gaps, blosum62); } @Test public void testComplex() throws Exception { short match = 2, gop = -5, gep = -3; // 2, 5, and 3 are coprime; -2 is the mismatch score - SimpleSubstitutionMatrix mx = new SimpleSubstitutionMatrix(new DNACompoundSet(), match, (short)-match); + SimpleSubstitutionMatrix mx = new SimpleSubstitutionMatrix<>(new DNACompoundSet(), match, (short) -match); DNASequence a = new DNASequence("CGTAT ATATCGCGCGCGCGATATATATATCT TCTCTAAAAAAA".replaceAll(" ", "")); DNASequence b = new DNASequence("GGTATATATATCGCGCGCACGAT TATATATCTCTCTCTAAAAAAA".replaceAll(" ", "")); @@ -88,7 +86,7 @@ public void testComplex() throws Exception { @Test public void testNeedlemanWunsch() { NeedlemanWunsch nw = - new NeedlemanWunsch(); + new NeedlemanWunsch<>(); nw.setQuery(query); nw.setTarget(target); nw.setGapPenalty(gaps); @@ -229,7 +227,7 @@ public void testGetPair() { public void should_align_all_anchored() throws CompoundNotFoundException { DNASequence query = new DNASequence("ACG", AmbiguityDNACompoundSet.getDNACompoundSet()); DNASequence target = new DNASequence("CGT", AmbiguityDNACompoundSet.getDNACompoundSet()); - NeedlemanWunsch aligner = new NeedlemanWunsch(query, target, new SimpleGapPenalty((short)0, (short)10), SubstitutionMatrixHelper.getNuc4_4()); + NeedlemanWunsch aligner = new NeedlemanWunsch<>(query, target, new SimpleGapPenalty((short) 0, (short) 10), SubstitutionMatrixHelper.getNuc4_4()); aligner.setAnchors(new int[] { 0, 1, 2} ); assertEquals(String.format("ACG%nCGT%n"), aligner.getPair().toString()); } @@ -241,7 +239,7 @@ public void should_align_all_anchored() throws CompoundNotFoundException { public void should_align_starting_anchor() throws CompoundNotFoundException { DNASequence query = new DNASequence("AAT", AmbiguityDNACompoundSet.getDNACompoundSet()); DNASequence target = new DNASequence("AATT", AmbiguityDNACompoundSet.getDNACompoundSet()); - NeedlemanWunsch aligner = new NeedlemanWunsch(query, target, new SimpleGapPenalty((short)0, (short)10), SubstitutionMatrixHelper.getNuc4_4()); + NeedlemanWunsch aligner = new NeedlemanWunsch<>(query, target, new SimpleGapPenalty((short) 0, (short) 10), SubstitutionMatrixHelper.getNuc4_4()); aligner.setAnchors(new int[] { 1, -1, -1} ); assertEquals(String.format("-AAT%nAATT%n"), aligner.getPair().toString()); } @@ -253,7 +251,7 @@ public void should_align_starting_anchor() throws CompoundNotFoundException { public void should_align_ending_anchor() throws CompoundNotFoundException { DNASequence query = new DNASequence("AAG", AmbiguityDNACompoundSet.getDNACompoundSet()); DNASequence target = new DNASequence("AATT", AmbiguityDNACompoundSet.getDNACompoundSet()); - NeedlemanWunsch aligner = new NeedlemanWunsch(query, target, new SimpleGapPenalty((short)0, (short)10), SubstitutionMatrixHelper.getNuc4_4()); + NeedlemanWunsch aligner = new NeedlemanWunsch<>(query, target, new SimpleGapPenalty((short) 0, (short) 10), SubstitutionMatrixHelper.getNuc4_4()); aligner.addAnchor(2, 3); assertEquals(String.format("AA-G%nAATT%n"), aligner.getPair().toString()); } @@ -265,7 +263,7 @@ public void should_align_ending_anchor() throws CompoundNotFoundException { public void should_align_middle_anchor() throws CompoundNotFoundException { DNASequence query = new DNASequence("ACTTT", AmbiguityDNACompoundSet.getDNACompoundSet()); DNASequence target = new DNASequence("ACGTTT", AmbiguityDNACompoundSet.getDNACompoundSet()); - NeedlemanWunsch aligner = new NeedlemanWunsch(query, target, new SimpleGapPenalty((short)0, (short)10), SubstitutionMatrixHelper.getNuc4_4()); + NeedlemanWunsch aligner = new NeedlemanWunsch<>(query, target, new SimpleGapPenalty((short) 0, (short) 10), SubstitutionMatrixHelper.getNuc4_4()); aligner.setAnchors(new int[] { -1, 2, -1} ); assertEquals(String.format("A-CTTT%nACGTTT%n"), aligner.getPair().toString()); } @@ -277,7 +275,7 @@ public void should_align_middle_anchor() throws CompoundNotFoundException { public void should_align_multiple_anchors() throws CompoundNotFoundException { DNASequence query = new DNASequence("ACGT", AmbiguityDNACompoundSet.getDNACompoundSet()); DNASequence target = new DNASequence("ATACGT", AmbiguityDNACompoundSet.getDNACompoundSet()); - NeedlemanWunsch aligner = new NeedlemanWunsch(query, target, new SimpleGapPenalty((short)0, (short)10), SubstitutionMatrixHelper.getNuc4_4()); + NeedlemanWunsch aligner = new NeedlemanWunsch<>(query, target, new SimpleGapPenalty((short) 0, (short) 10), SubstitutionMatrixHelper.getNuc4_4()); aligner.addAnchor(0, 0); aligner.addAnchor(1, 1); aligner.addAnchor(2, 2); @@ -292,8 +290,8 @@ public void should_align_multiple_anchors() throws CompoundNotFoundException { public void anchors_should_not_change_score() throws CompoundNotFoundException { DNASequence query = new DNASequence("ACGT", AmbiguityDNACompoundSet.getDNACompoundSet()); DNASequence target = new DNASequence("ACGT", AmbiguityDNACompoundSet.getDNACompoundSet()); - NeedlemanWunsch aligner = new NeedlemanWunsch(query, target, new SimpleGapPenalty((short)5, (short)10), SubstitutionMatrixHelper.getNuc4_4()); - NeedlemanWunsch anchored = new NeedlemanWunsch(query, target, new SimpleGapPenalty((short)5, (short)10), SubstitutionMatrixHelper.getNuc4_4()); + NeedlemanWunsch aligner = new NeedlemanWunsch<>(query, target, new SimpleGapPenalty((short) 5, (short) 10), SubstitutionMatrixHelper.getNuc4_4()); + NeedlemanWunsch anchored = new NeedlemanWunsch<>(query, target, new SimpleGapPenalty((short) 5, (short) 10), SubstitutionMatrixHelper.getNuc4_4()); anchored.addAnchor(0, 0); anchored.addAnchor(1, 1); anchored.addAnchor(2, 2); @@ -308,7 +306,7 @@ public void anchors_should_not_change_score() throws CompoundNotFoundException { public void testAnchoredDNAAlignment() throws CompoundNotFoundException { DNASequence query = new DNASequence( "ACGTACCGGTTTT", DNACompoundSet.getDNACompoundSet()); DNASequence target = new DNASequence("TACGTCCGGTTACGTACGTT", DNACompoundSet.getDNACompoundSet()); - NeedlemanWunsch aligner = new NeedlemanWunsch(query, target, new SimpleGapPenalty((short)5, (short)2), SubstitutionMatrixHelper.getNuc4_4()); + NeedlemanWunsch aligner = new NeedlemanWunsch<>(query, target, new SimpleGapPenalty((short) 5, (short) 2), SubstitutionMatrixHelper.getNuc4_4()); assertEquals(String.format("-ACGTACCGGTT-------TT%nTACGT-CCGGTTACGTACGTT%n"), aligner.getPair().toString()); } @@ -335,7 +333,7 @@ public void testIntOverflowBug() throws CompoundNotFoundException { AmbiguityDNACompoundSet.getDNACompoundSet()); NeedlemanWunsch aligner = - new NeedlemanWunsch(query, target, gap, matrix); + new NeedlemanWunsch<>(query, target, gap, matrix); //System.out.println("getScore: " + aligner.getScore()); diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleProfilePairTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleProfilePairTest.java index 5d4e9acd53..3e3c887ede 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleProfilePairTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleProfilePairTest.java @@ -23,9 +23,10 @@ package org.biojava.nbio.alignment; +import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.core.alignment.SimpleProfilePair; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.AlignedSequence.Step; -import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.core.alignment.template.Profile; import org.biojava.nbio.core.alignment.template.ProfilePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; @@ -36,9 +37,6 @@ import org.junit.Test; import java.util.Arrays; -import org.biojava.nbio.alignment.NeedlemanWunsch; -import org.biojava.nbio.alignment.SimpleGapPenalty; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import static org.junit.Assert.assertEquals; @@ -57,34 +55,31 @@ public void setup() throws CompoundNotFoundException { protein4 = new ProteinSequence("ANDR"); gaps = new SimpleGapPenalty((short) 2, (short) 1); blosum62 = SubstitutionMatrixHelper.getBlosum62(); - pair1 = new NeedlemanWunsch(protein1, protein2, gaps, blosum62).getPair(); - pair2 = new NeedlemanWunsch(protein3, protein4, gaps, blosum62).getPair(); + pair1 = new NeedlemanWunsch<>(protein1, protein2, gaps, blosum62).getPair(); + pair2 = new NeedlemanWunsch<>(protein3, protein4, gaps, blosum62).getPair(); } @Test public void testSimpleProfilePair() { ProfilePair all = - new SimpleProfilePair(pair1, pair2, Arrays.asList(new Step[] { - Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.GAP}), Arrays.asList( - new Step[] {Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND})); + new SimpleProfilePair<>(pair1, pair2, Arrays.asList(Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.GAP), Arrays.asList( + Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND)); assertEquals(all.toString(), String.format("ARND--%nARND--%n--HILK%nA-ND-R%n")); } @Test public void testGetQuery() { ProfilePair all = - new SimpleProfilePair(pair1, pair2, Arrays.asList(new Step[] { - Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.GAP}), Arrays.asList( - new Step[] {Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND})); + new SimpleProfilePair<>(pair1, pair2, Arrays.asList(Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.GAP), Arrays.asList( + Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND)); assertEquals(all.getQuery(), pair1); } @Test public void testGetTarget() { ProfilePair all = - new SimpleProfilePair(pair1, pair2, Arrays.asList(new Step[] { - Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.GAP}), Arrays.asList( - new Step[] {Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND})); + new SimpleProfilePair<>(pair1, pair2, Arrays.asList(Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.GAP), Arrays.asList( + Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND)); assertEquals(all.getTarget(), pair2); } diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleProfileProfileAlignerTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleProfileProfileAlignerTest.java index 625e954730..de3f91694e 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleProfileProfileAlignerTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleProfileProfileAlignerTest.java @@ -56,22 +56,22 @@ public void setup() throws CompoundNotFoundException { protein4 = new ProteinSequence("ANDR"); gaps = new SimpleGapPenalty(2, 1); blosum62 = SubstitutionMatrixHelper.getBlosum62(); - prof1 = new SimpleProfile(protein1); - prof2 = new SimpleProfile(protein2); - prof3 = new SimpleProfile(protein3); - prof4 = new SimpleProfile(protein4); - sppa1 = new SimpleProfileProfileAligner(prof1, prof2, gaps, blosum62); + prof1 = new SimpleProfile<>(protein1); + prof2 = new SimpleProfile<>(protein2); + prof3 = new SimpleProfile<>(protein3); + prof4 = new SimpleProfile<>(protein4); + sppa1 = new SimpleProfileProfileAligner<>(prof1, prof2, gaps, blosum62); pp1 = sppa1.getPair(); - sppa2 = new SimpleProfileProfileAligner(prof3, prof4, gaps, blosum62); + sppa2 = new SimpleProfileProfileAligner<>(prof3, prof4, gaps, blosum62); pp2 = sppa2.getPair(); - sppa3 = new SimpleProfileProfileAligner(pp1, pp2, gaps, blosum62); + sppa3 = new SimpleProfileProfileAligner<>(pp1, pp2, gaps, blosum62); all = sppa3.getPair(); } @Test public void testSimpleProfileProfileAligner() { SimpleProfileProfileAligner alig = - new SimpleProfileProfileAligner(); + new SimpleProfileProfileAligner<>(); alig.setQuery(prof1); alig.setTarget(prof2); alig.setGapPenalty(gaps); diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleSubstitutionMatrixTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleSubstitutionMatrixTest.java index 72ed4137d7..30150e5483 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleSubstitutionMatrixTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SimpleSubstitutionMatrixTest.java @@ -42,7 +42,7 @@ public class SimpleSubstitutionMatrixTest { @Test(expected=FileNotFoundException.class) public void testSimpleSubstitutionMatrixNotFound() throws FileNotFoundException { - new SimpleSubstitutionMatrix(AminoAcidCompoundSet.getAminoAcidCompoundSet(), + new SimpleSubstitutionMatrix<>(AminoAcidCompoundSet.aminoAcidCompoundSet, new File("blosum63.txt")); } @@ -51,7 +51,7 @@ public void test() throws CompoundNotFoundException { NucleotideCompound A = new DNASequence("A").getCompoundAt(1); NucleotideCompound a = new DNASequence("a").getCompoundAt(1); NucleotideCompound c = new DNASequence("c").getCompoundAt(1); - SubstitutionMatrix matrix = new SimpleSubstitutionMatrix(DNACompoundSet.getDNACompoundSet(), (short)1, (short)0); + SubstitutionMatrix matrix = new SimpleSubstitutionMatrix<>(DNACompoundSet.getDNACompoundSet(), (short) 1, (short) 0); assertEquals(1, (matrix.getValue(A, A))); assertEquals(1, (matrix.getValue(a, a))); assertEquals(1, (matrix.getValue(A, a))); @@ -61,7 +61,7 @@ public void test() throws CompoundNotFoundException { @Test() public void testSimpleSubstitutionMatrix() { SubstitutionMatrix matrix = SimpleSubstitutionMatrix.getBlosum62(); - assertEquals(matrix.getCompoundSet(), AminoAcidCompoundSet.getAminoAcidCompoundSet()); + assertEquals(matrix.getCompoundSet(), AminoAcidCompoundSet.aminoAcidCompoundSet); assertEquals(matrix.getName(), "blosum62"); assertEquals(matrix.getMaxValue(), 11); assertEquals(matrix.getMinValue(), -4); @@ -70,7 +70,7 @@ public void testSimpleSubstitutionMatrix() { @Test public void testSimpleSubstitutionMatrixCompoundSetOfCStringString() { DNACompoundSet dnacs = DNACompoundSet.getDNACompoundSet(); - SubstitutionMatrix dnaTest = new SimpleSubstitutionMatrix(dnacs, + SubstitutionMatrix dnaTest = new SimpleSubstitutionMatrix<>(dnacs, "# Test\nA C G T\nA 5 0 0 0\nC 0 5 0 0\nG 0 0 5 0\nT 0 0 0 1\n", "DNA Test"); short[][] matrix = dnaTest.getMatrix(); assertEquals(matrix[1][1], 5); @@ -83,8 +83,8 @@ public void testSimpleSubstitutionMatrixCompoundSetOfCStringString() { @Test public void testSimpleSubstitutionMatrixCompoundSetOfCShortShort() { - SubstitutionMatrix matrix = new SimpleSubstitutionMatrix( - AminoAcidCompoundSet.getAminoAcidCompoundSet(), (short) 5, (short) 1); + SubstitutionMatrix matrix = new SimpleSubstitutionMatrix<>( + AminoAcidCompoundSet.aminoAcidCompoundSet, (short) 5, (short) 1); assertEquals(matrix.getName(), "IDENTITY_5_1"); } @@ -106,7 +106,7 @@ public void testSetName() { @Test public void testToString() { - SubstitutionMatrix matrix = new SimpleSubstitutionMatrix( + SubstitutionMatrix matrix = new SimpleSubstitutionMatrix<>( DNACompoundSet.getDNACompoundSet(), "# Test\nA C G T\nA 5 0 0 0\nC 0 5 0 0 \nG 0 0 5 0\n T 0 0 0 1\n", "DNAtest"); assertEquals(matrix.toString().substring(0,6), "# Test"); @@ -119,7 +119,7 @@ public void testToString() { @Test public void testCaseEquivalence() { DNACompoundSet dnacs = DNACompoundSet.getDNACompoundSet(); - SubstitutionMatrix dnaTest = new SimpleSubstitutionMatrix(dnacs, + SubstitutionMatrix dnaTest = new SimpleSubstitutionMatrix<>(dnacs, "# Test\nA C G T\nA 5 0 0 0\nC 0 5 0 0\nG 0 0 5 0\nT 0 0 0 1\n", "DNA Test"); @SuppressWarnings("unused") short[][] matrix = dnaTest.getMatrix(); diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SmithWatermanTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SmithWatermanTest.java index a3335b500e..cb3e94a349 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SmithWatermanTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/SmithWatermanTest.java @@ -23,8 +23,8 @@ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.template.GapPenalty; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.ProteinSequence; @@ -49,14 +49,14 @@ public void setup() throws CompoundNotFoundException { target = new ProteinSequence("ERDNKGFPS"); gaps = new SimpleGapPenalty((short) 2, (short) 1); blosum62 = SubstitutionMatrixHelper.getBlosum62(); - alignment = new SmithWaterman(query, target, gaps, blosum62); - self = new SmithWaterman(query, query, gaps, blosum62); + alignment = new SmithWaterman<>(query, target, gaps, blosum62); + self = new SmithWaterman<>(query, query, gaps, blosum62); } @Test public void testSmithWaterman() { SmithWaterman alig = - new SmithWaterman(); + new SmithWaterman<>(); alig.setQuery(query); alig.setTarget(target); alig.setGapPenalty(gaps); diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/TestDNAAlignment.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/TestDNAAlignment.java index a50d8c4cde..6d7312dd33 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/TestDNAAlignment.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/TestDNAAlignment.java @@ -23,9 +23,9 @@ */ package org.biojava.nbio.alignment; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; import org.biojava.nbio.alignment.template.PairwiseSequenceAligner; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.Profile; import org.biojava.nbio.core.alignment.template.SequencePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; @@ -57,7 +57,7 @@ public void testDNAAlignment() { Profile profile = Alignments.getMultipleSequenceAlignment(lst); - Assert.assertTrue(profile.getSize() == 10); + Assert.assertEquals(10, profile.getSize()); Assert.assertTrue(profile.getAlignedSequence(1).getSequenceAsString().length() > 50); @@ -74,15 +74,10 @@ public void testDNAAlignment() { private static List getDNAFASTAFile() throws Exception { - InputStream inStream = TestDNAAlignment.class.getResourceAsStream(String.format("/dna-fasta.txt")); + InputStream inStream = TestDNAAlignment.class.getResourceAsStream("/dna-fasta.txt"); LinkedHashMap fastas = FastaReaderHelper.readFastaDNASequence(inStream); - List sequences = new ArrayList(); - - for (String key : fastas.keySet()) { - DNASequence seq = fastas.get(key); - sequences.add(seq); - } + List sequences = new ArrayList<>(fastas.values()); return sequences; } @@ -96,7 +91,7 @@ public void testDNAMultipleAlignmentWithMixedCompoundSets() throws CompoundNotFo DNASequence target = new DNASequence("ACTGACGTGTAGCTGACTGA", DNACompoundSet.getDNACompoundSet()); DNASequence query = new DNASequence("ACTGACGTGTAGCTGACTGTA", AmbiguityDNACompoundSet.getDNACompoundSet()); - List lst = new ArrayList(); + List lst = new ArrayList<>(); lst.add(target); lst.add(query); @@ -163,6 +158,6 @@ public void testLinearAlignment() throws CompoundNotFoundException { SubstitutionMatrix matrix = SubstitutionMatrixHelper.getNuc4_4(); SimpleGapPenalty gapP = new SimpleGapPenalty((short)0, (short)3); PairwiseSequenceAligner aligner = Alignments.getPairwiseAligner(query, target, PairwiseSequenceAlignerType.GLOBAL, gapP, matrix); - Assert.assertEquals(String.format("GTAAAA-G----------%nG-AAAACGTTTTTTTTTT%n"), aligner.getPair().toString());; + Assert.assertEquals(String.format("GTAAAA-G----------%nG-AAAACGTTTTTTTTTT%n"), aligner.getPair().toString()); } } diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/TestSubOptimalMSA.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/TestSubOptimalMSA.java index 13a14120a5..11c68570dc 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/TestSubOptimalMSA.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/TestSubOptimalMSA.java @@ -20,8 +20,6 @@ */ package org.biojava.nbio.alignment; -import static org.junit.Assert.*; - import org.biojava.nbio.core.alignment.template.Profile; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.DNASequence; @@ -34,9 +32,11 @@ import java.util.ArrayList; import java.util.List; +import static org.junit.Assert.assertEquals; + public class TestSubOptimalMSA { - private List sequences = new ArrayList(); + private final List sequences = new ArrayList<>(); @Before public void setUp() { diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/aaindex/TestAAINDEXLoading.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/aaindex/TestAAINDEXLoading.java index 1dbcc8cfcf..91c16b1aa3 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/aaindex/TestAAINDEXLoading.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/aaindex/TestAAINDEXLoading.java @@ -63,7 +63,7 @@ public void testSDMmatrix(){ SubstitutionMatrix sdm = SubstitutionMatrixHelper.getMatrixFromAAINDEX(matrixName); - int scale = 1; + int scale; if ( sdm instanceof ScaledSubstitutionMatrix) { ScaledSubstitutionMatrix scaledSDM = (ScaledSubstitutionMatrix)sdm; scale = scaledSDM.getScale(); @@ -71,7 +71,7 @@ public void testSDMmatrix(){ } - AminoAcidCompoundSet aas = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet aas = AminoAcidCompoundSet.aminoAcidCompoundSet; AminoAcidCompound v = aas.getCompoundForString("V"); AminoAcidCompound w = aas.getCompoundForString("W"); @@ -149,7 +149,7 @@ public void testOVEJ920104(){ Assert.assertEquals(1000, scale); } - AminoAcidCompoundSet aas = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet aas = AminoAcidCompoundSet.aminoAcidCompoundSet; AminoAcidCompound minus = aas.getCompoundForString("-"); diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/io/TestStockholmParser.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/io/TestStockholmParser.java index 2e888705bf..67ac48522a 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/io/TestStockholmParser.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/io/TestStockholmParser.java @@ -78,10 +78,10 @@ public void testPiwi(){ StockholmStructure data = fileParser.parse(inStream); - Assert.assertTrue("Did not get enough sequences!", data.getBioSequences(false).size() == 20); + Assert.assertEquals("Did not get enough sequences!", 20, data.getBioSequences(false).size()); AbstractSequence seq = data.getBioSequences(false).get(0); - Assert.assertTrue(seq != null); + Assert.assertNotNull(seq); Assert.assertTrue(seq.getSequenceAsString().length() > 20); diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/routines/AlignerHelperTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/routines/AlignerHelperTest.java index 9d12abb897..ae3308ac6c 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/routines/AlignerHelperTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/routines/AlignerHelperTest.java @@ -28,8 +28,7 @@ import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.*; /** * @@ -62,7 +61,7 @@ public void getCuts_should_return_spaced_cuts_when_query_interval_larger_than_cu } @Test public void getSubproblems_should_return_score_indicies_of_alignment_subproblems() { - List anchors = new ArrayList(); + List anchors = new ArrayList<>(); anchors.add(new Anchor(1, 2)); anchors.add(new Anchor(5, 5)); List problems = AlignerHelper.Subproblem.getSubproblems(anchors, 10, 15); @@ -82,18 +81,18 @@ public void getSubproblems_should_return_score_indicies_of_alignment_subproblems } @Test public void getSubproblems_should_allow_zero_anchors() { - List anchors = new ArrayList(); + List anchors = new ArrayList<>(); List problems = AlignerHelper.Subproblem.getSubproblems(anchors, 10, 15); assertEquals(1, problems.size()); assertEquals(0, problems.get(0).getQueryStartIndex()); assertEquals(0, problems.get(0).getTargetStartIndex()); assertEquals(10, problems.get(0).getQueryEndIndex()); assertEquals(15, problems.get(0).getTargetEndIndex()); - assertEquals(false, problems.get(0).isStartAnchored()); + assertFalse(problems.get(0).isStartAnchored()); } @Test public void getSubproblems_should_allow_start_and_end_anchors() { - List anchors = new ArrayList(); + List anchors = new ArrayList<>(); anchors.add(new Anchor(0, 0)); anchors.add(new Anchor(9, 14)); List problems = AlignerHelper.Subproblem.getSubproblems(anchors, 10, 15); @@ -102,21 +101,21 @@ public void getSubproblems_should_allow_start_and_end_anchors() { assertEquals(0, problems.get(0).getTargetStartIndex()); assertEquals(0, problems.get(0).getQueryEndIndex()); assertEquals(0, problems.get(0).getTargetEndIndex()); - assertEquals(false, problems.get(0).isStartAnchored()); + assertFalse(problems.get(0).isStartAnchored()); assertEquals(1, problems.get(1).getQueryStartIndex()); assertEquals(1, problems.get(1).getTargetStartIndex()); assertEquals(9, problems.get(1).getQueryEndIndex()); assertEquals(14, problems.get(1).getTargetEndIndex()); - assertEquals(true, problems.get(1).isStartAnchored()); + assertTrue(problems.get(1).isStartAnchored()); assertEquals(10, problems.get(2).getQueryStartIndex()); assertEquals(15, problems.get(2).getTargetStartIndex()); assertEquals(10, problems.get(2).getQueryEndIndex()); assertEquals(15, problems.get(2).getTargetEndIndex()); - assertEquals(true, problems.get(2).isStartAnchored()); + assertTrue(problems.get(2).isStartAnchored()); } @Test public void getSubproblems_should_allow_adjacent_anchors() { - List anchors = new ArrayList(); + List anchors = new ArrayList<>(); anchors.add(new Anchor(1, 1)); anchors.add(new Anchor(2, 3)); List problems = AlignerHelper.Subproblem.getSubproblems(anchors, 10, 15); @@ -132,14 +131,14 @@ public void getSubproblems_should_allow_adjacent_anchors() { } @Test(expected=IllegalArgumentException.class) public void getSubproblems_should_not_allow_repeated_anchors() { - List anchors = new ArrayList(); + List anchors = new ArrayList<>(); anchors.add(new Anchor(1, 1)); anchors.add(new Anchor(1, 2)); AlignerHelper.Subproblem.getSubproblems(anchors, 10, 15); } @Test(expected=IllegalArgumentException.class) public void getSubproblems_should_not_allow_unalignable_anchors() { - List anchors = new ArrayList(); + List anchors = new ArrayList<>(); anchors.add(new Anchor(1, 2)); anchors.add(new Anchor(2, 1)); AlignerHelper.Subproblem.getSubproblems(anchors, 10, 15); diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/routines/GuanUberbacherTest.java b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/routines/GuanUberbacherTest.java index 5ecb525231..03447629be 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/alignment/routines/GuanUberbacherTest.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/alignment/routines/GuanUberbacherTest.java @@ -24,8 +24,8 @@ package org.biojava.nbio.alignment.routines; import org.biojava.nbio.alignment.SimpleGapPenalty; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.template.GapPenalty; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.DNASequence; @@ -54,14 +54,14 @@ public void setup() throws CompoundNotFoundException { target = new ProteinSequence("RDG"); gaps = new SimpleGapPenalty(10, 1); blosum62 = SubstitutionMatrixHelper.getBlosum62(); - alignment = new GuanUberbacher(query, target, gaps, blosum62); - self = new GuanUberbacher(query, query, gaps, blosum62); + alignment = new GuanUberbacher<>(query, target, gaps, blosum62); + self = new GuanUberbacher<>(query, query, gaps, blosum62); } @Test public void testGuanUberbacher() { GuanUberbacher gu = - new GuanUberbacher(); + new GuanUberbacher<>(); gu.setQuery(query); gu.setTarget(target); gu.setGapPenalty(gaps); @@ -111,7 +111,7 @@ public void testGetPair() { public void should_align_shorter_query() throws CompoundNotFoundException { DNASequence query = new DNASequence("A", AmbiguityDNACompoundSet.getDNACompoundSet()); DNASequence target = new DNASequence("AT", AmbiguityDNACompoundSet.getDNACompoundSet()); - GuanUberbacher aligner = new GuanUberbacher(query, target, new SimpleGapPenalty((short)5, (short)2), SubstitutionMatrixHelper.getNuc4_4()); + GuanUberbacher aligner = new GuanUberbacher<>(query, target, new SimpleGapPenalty((short) 5, (short) 2), SubstitutionMatrixHelper.getNuc4_4()); assertEquals(String.format("A-%nAT%n"), aligner.getPair().toString()); } /** @@ -121,7 +121,7 @@ public void should_align_shorter_query() throws CompoundNotFoundException { public void should_align_shorter_target() throws CompoundNotFoundException { DNASequence query = new DNASequence("AT", AmbiguityDNACompoundSet.getDNACompoundSet()); DNASequence target = new DNASequence("A", AmbiguityDNACompoundSet.getDNACompoundSet()); - GuanUberbacher aligner = new GuanUberbacher(query, target, new SimpleGapPenalty((short)5, (short)2), SubstitutionMatrixHelper.getNuc4_4()); + GuanUberbacher aligner = new GuanUberbacher<>(query, target, new SimpleGapPenalty((short) 5, (short) 2), SubstitutionMatrixHelper.getNuc4_4()); assertEquals(String.format("AT%nA-%n"), aligner.getPair().toString()); } /** @@ -131,7 +131,7 @@ public void should_align_shorter_target() throws CompoundNotFoundException { public void should_align_multiple_cuts() throws CompoundNotFoundException { DNASequence query = new DNASequence("AAT", AmbiguityDNACompoundSet.getDNACompoundSet()); DNASequence target = new DNASequence("AATG", AmbiguityDNACompoundSet.getDNACompoundSet()); - GuanUberbacher aligner = new GuanUberbacher(query, target, new SimpleGapPenalty((short)0, (short)2), SubstitutionMatrixHelper.getNuc4_4()); + GuanUberbacher aligner = new GuanUberbacher<>(query, target, new SimpleGapPenalty((short) 0, (short) 2), SubstitutionMatrixHelper.getNuc4_4()); aligner.setCutsPerSection(2); // 3 bases with 2 cuts assertEquals(String.format("AAT-%nAATG%n"), aligner.getPair().toString()); } diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/phylo/TestDistanceTreeEvaluator.java b/biojava-alignment/src/test/java/org/biojava/nbio/phylo/TestDistanceTreeEvaluator.java index 3c129e0c22..ddb841d7d5 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/phylo/TestDistanceTreeEvaluator.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/phylo/TestDistanceTreeEvaluator.java @@ -24,7 +24,7 @@ import org.forester.phylogeny.Phylogeny; import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; /** * Test for the evaluation of distance trees. @@ -35,7 +35,7 @@ public class TestDistanceTreeEvaluator { @Test - public void testErrorFree() throws Exception { + public void testErrorFree() { // Create a perfect additive distance matrix BasicSymmetricalDistanceMatrix DM = new BasicSymmetricalDistanceMatrix( @@ -44,7 +44,7 @@ public void testErrorFree() throws Exception { // dAB = 0.8, dBC = 0.4, dAC = 0.8 for (int i = 0; i < 3; i++) { char id = (char) ('A' + i); - DM.setIdentifier(i, id + ""); + DM.setIdentifier(i, String.valueOf(id)); for (int j = i; j < 3; j++) { if (i == j) { DM.setValue(i, j, 0.0); @@ -66,7 +66,7 @@ public void testErrorFree() throws Exception { } @Test - public void testErrorEstimation() throws Exception { + public void testErrorEstimation() { // Matrix taken from forester test BasicSymmetricalDistanceMatrix m = new BasicSymmetricalDistanceMatrix(4); diff --git a/biojava-alignment/src/test/java/org/biojava/nbio/phylo/TestForesterWrapper.java b/biojava-alignment/src/test/java/org/biojava/nbio/phylo/TestForesterWrapper.java index c4fe468852..3fa5e7c20d 100644 --- a/biojava-alignment/src/test/java/org/biojava/nbio/phylo/TestForesterWrapper.java +++ b/biojava-alignment/src/test/java/org/biojava/nbio/phylo/TestForesterWrapper.java @@ -20,11 +20,6 @@ */ package org.biojava.nbio.phylo; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.LinkedHashMap; - import org.biojava.nbio.core.sequence.MultipleSequenceAlignment; import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; @@ -33,11 +28,15 @@ import org.biojava.nbio.core.sequence.io.FastaWriter; import org.biojava.nbio.core.sequence.io.GenericFastaHeaderParser; import org.biojava.nbio.core.sequence.io.ProteinSequenceCreator; -import org.biojava.nbio.core.sequence.io.template.FastaHeaderFormatInterface; import org.forester.msa.Msa; import org.junit.Test; -import static org.junit.Assert.*; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.LinkedHashMap; + +import static org.junit.Assert.assertEquals; /** * Test the BioJava-forester wrapper methods. @@ -54,12 +53,11 @@ public void testMSAconversion() throws Exception { InputStream inStream = TestForesterWrapper.class .getResourceAsStream("/1u6d_symm.fasta"); - FastaReader fastaReader = - new FastaReader( - inStream, - new GenericFastaHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet - .getAminoAcidCompoundSet())); + FastaReader fastaReader = + new FastaReader<>( + inStream, + new GenericFastaHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap proteinSequences = fastaReader .process(); @@ -67,7 +65,7 @@ public void testMSAconversion() throws Exception { inStream.close(); MultipleSequenceAlignment msa = - new MultipleSequenceAlignment(); + new MultipleSequenceAlignment<>(); String expected = ""; for (ProteinSequence proteinSequence : proteinSequences.values()) { @@ -79,14 +77,9 @@ public void testMSAconversion() throws Exception { // Convert the biojava MSA to a FASTA String OutputStream os = new ByteArrayOutputStream(); FastaWriter fastaW = - new FastaWriter(os, - msa.getAlignedSequences(), - new FastaHeaderFormatInterface() { - @Override - public String getHeader(ProteinSequence sequence) { - return sequence.getAccession().toString(); - }; - }); + new FastaWriter<>(os, + msa.getAlignedSequences(), + sequence -> sequence.getAccession().toString()); fastaW.process(); String biojava = os.toString(); @@ -95,8 +88,8 @@ public String getHeader(ProteinSequence sequence) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < fMsa.getNumberOfSequences(); i++) { - sb.append(">" + fMsa.getIdentifier(i) + System.lineSeparator()); - sb.append(fMsa.getSequenceAsString(i) + System.lineSeparator()); + sb.append(">").append(fMsa.getIdentifier(i)).append(System.lineSeparator()); + sb.append(fMsa.getSequenceAsString(i)).append(System.lineSeparator()); } String forester = sb.toString(); diff --git a/biojava-core/pom.xml b/biojava-core/pom.xml index b465a40a36..ed5fd10f82 100644 --- a/biojava-core/pom.xml +++ b/biojava-core/pom.xml @@ -26,15 +26,7 @@ - - org.apache.maven.plugins - maven-jar-plugin - - - demo/** - - - + @@ -62,6 +54,15 @@ org.apache.logging.log4j log4j-core + + + + + com.squareup.okhttp3 + okhttp + 3.14.7 + + diff --git a/biojava-core/src/main/java/demo/DemoSixFrameTranslation.java b/biojava-core/src/main/java/demo/DemoSixFrameTranslation.java index 354e0bea26..ae98073d1a 100644 --- a/biojava-core/src/main/java/demo/DemoSixFrameTranslation.java +++ b/biojava-core/src/main/java/demo/DemoSixFrameTranslation.java @@ -106,9 +106,9 @@ public static void main(String[] args){ CompoundSet nucleotideCompoundSet = AmbiguityRNACompoundSet.getRNACompoundSet(); FastaReader proxy = - new FastaReader( + new FastaReader<>( stream, - new GenericFastaHeaderParser(), + new GenericFastaHeaderParser<>(), new DNASequenceCreator(ambiguityDNACompoundSet)); // has only one entry in this example, but could be easily extended to parse a FASTA file with multiple sequences diff --git a/biojava-core/src/main/java/demo/ParseFastaFileDemo.java b/biojava-core/src/main/java/demo/ParseFastaFileDemo.java index 5951ed3ad6..ec1ad49772 100644 --- a/biojava-core/src/main/java/demo/ParseFastaFileDemo.java +++ b/biojava-core/src/main/java/demo/ParseFastaFileDemo.java @@ -21,9 +21,6 @@ package demo; -import java.io.File; -import java.io.InputStream; -import java.util.LinkedHashMap; import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; @@ -32,6 +29,11 @@ import org.biojava.nbio.core.sequence.io.ProteinSequenceCreator; import org.biojava.nbio.core.util.InputStreamProvider; +import java.io.File; +import java.io.InputStream; +import java.util.LinkedHashMap; +import java.util.Map; + /** * Created by andreas on 6/17/15. @@ -94,19 +96,19 @@ public static void main(String[] args) throws Exception { InputStream inStream = isp.getInputStream(f); - FastaReader fastaReader = new FastaReader( + FastaReader fastaReader = new FastaReader<>( inStream, - new GenericFastaHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + new GenericFastaHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap b; int nrSeq = 0; while ((b = fastaReader.process(100)) != null) { - for (String key : b.keySet()) { + for (Map.Entry entry : b.entrySet()) { nrSeq++; - System.out.println(nrSeq + " : " + key + " " + b.get(key)); + System.out.println(nrSeq + " : " + entry.getKey() + " " + entry.getValue()); if ( nrSeq % 100000 == 0) System.out.println(nrSeq ); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleAlignedSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleAlignedSequence.java index 8980fdad7b..27bf026225 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleAlignedSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleAlignedSequence.java @@ -54,8 +54,10 @@ public class SimpleAlignedSequence, C extends Compound> im // always stored private AlignedSequence prev; - private S original; - private int length, numBefore, numAfter; + private final S original; + private final int length; + private int numBefore; + private int numAfter; private Location location; // cached (lazily initialized) @@ -266,8 +268,9 @@ public boolean isGap(int alignmentIndex) { // methods for Sequence + @SafeVarargs @Override - public int countCompounds(C... compounds) { + public final int countCompounds(C... compounds) { int count = 0; List search = Arrays.asList(compounds); for (C compound : getAsList()) { @@ -285,7 +288,7 @@ public AccessionID getAccession() { @Override public List getAsList() { - List compounds = new ArrayList(); + List compounds = new ArrayList<>(); for (int i = 1; i <= length; i++) { compounds.add(getCompoundAt(i)); } @@ -294,7 +297,7 @@ public List getAsList() { @Override public boolean equals(Object o){ - + if (this == o) return true; if(! Equals.classEqual(this, o)) { return false; } @@ -382,7 +385,7 @@ public String toString() { // helper method to initialize the location private void setLocation(List steps) { - List sublocations = new ArrayList(); + List sublocations = new ArrayList<>(); int start = 0, step = 0, oStep = numBefore+numAfter, oMax = this.original.getLength(), pStep = 0, pMax = (prev == null) ? 0 : prev.getLength(); boolean inGap = true; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleProfile.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleProfile.java index 7cd7ef1bf5..d7438af53d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleProfile.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleProfile.java @@ -57,7 +57,7 @@ public class SimpleProfile, C extends Compound> implements private List> list; private List originals; - private int length; + private final int length; /** * Creates a pair profile for the given already aligned sequences. @@ -70,11 +70,11 @@ protected SimpleProfile(AlignedSequence query, AlignedSequence targe if (query.getLength() != target.getLength()) { throw new IllegalArgumentException("Aligned sequences differ in size"); } - list = new ArrayList>(); + list = new ArrayList<>(); list.add(query); list.add(target); list = Collections.unmodifiableList(list); - originals = new ArrayList(); + originals = new ArrayList<>(); originals.add(query.getOriginalSequence()); originals.add(target.getOriginalSequence()); originals = Collections.unmodifiableList(originals); @@ -87,14 +87,14 @@ protected SimpleProfile(AlignedSequence query, AlignedSequence targe * @param sequence sequence to seed profile */ public SimpleProfile(S sequence) { - List s = new ArrayList(); + List s = new ArrayList<>(); for (int i = 0; i < sequence.getLength(); i++) { s.add(Step.COMPOUND); } - list = new ArrayList>(); - list.add(new SimpleAlignedSequence(sequence, s)); + list = new ArrayList<>(); + list.add(new SimpleAlignedSequence<>(sequence, s)); list = Collections.unmodifiableList(list); - originals = new ArrayList(); + originals = new ArrayList<>(); originals.add(sequence); originals = Collections.unmodifiableList(originals); length = sequence.getLength(); @@ -117,11 +117,11 @@ protected SimpleProfile(S query, S target, List sx, int xb, int xa, List>(); - list.add(new SimpleAlignedSequence(query, sx, xb, xa)); - list.add(new SimpleAlignedSequence(target, sy, yb, ya)); + list = new ArrayList<>(); + list.add(new SimpleAlignedSequence<>(query, sx, xb, xa)); + list.add(new SimpleAlignedSequence<>(target, sy, yb, ya)); list = Collections.unmodifiableList(list); - originals = new ArrayList(); + originals = new ArrayList<>(); originals.add(query); originals.add(target); originals = Collections.unmodifiableList(originals); @@ -141,15 +141,15 @@ protected SimpleProfile(Profile query, Profile target, List sx if (sx.size() != sy.size()) { throw new IllegalArgumentException("Alignments differ in size"); } - list = new ArrayList>(); + list = new ArrayList<>(); for (AlignedSequence s : query) { - list.add(new SimpleAlignedSequence(s, sx)); + list.add(new SimpleAlignedSequence<>(s, sx)); } for (AlignedSequence s : target) { - list.add(new SimpleAlignedSequence(s, sy)); + list.add(new SimpleAlignedSequence<>(s, sy)); } list = Collections.unmodifiableList(list); - originals = new ArrayList(); + originals = new ArrayList<>(); originals.addAll(query.getOriginalSequences()); originals.addAll(target.getOriginalSequences()); originals = Collections.unmodifiableList(originals); @@ -163,8 +163,8 @@ protected SimpleProfile(Profile query, Profile target, List sx * collection is empty. */ public SimpleProfile(Collection> alignedSequences) { - list = new ArrayList>(); - originals = new ArrayList(); + list = new ArrayList<>(); + originals = new ArrayList<>(); Iterator> itr = alignedSequences.iterator(); if(!itr.hasNext()) { @@ -213,16 +213,17 @@ public List> getAlignedSequences() { @Override public List> getAlignedSequences(int... listIndices) { - List> tempList = new ArrayList>(); + List> tempList = new ArrayList<>(); for (int i : listIndices) { tempList.add(getAlignedSequence(i)); } return Collections.unmodifiableList(tempList); } + @SafeVarargs @Override - public List> getAlignedSequences(S... sequences) { - List> tempList = new ArrayList>(); + public final List> getAlignedSequences(S... sequences) { + List> tempList = new ArrayList<>(); for (S s : sequences) { tempList.add(getAlignedSequence(s)); } @@ -242,17 +243,18 @@ public C getCompoundAt(S sequence, int alignmentIndex) { @Override public int[] getCompoundCountsAt(int alignmentIndex) { - return getCompoundCountsAt(alignmentIndex, getCompoundSet().getAllCompounds()); + return getCompoundCountsAt(alignmentIndex, new ArrayList(getCompoundSet().getAllCompounds())); } @Override public int[] getCompoundCountsAt(int alignmentIndex, List compounds) { int[] counts = new int[compounds.size()]; - C gap = getCompoundSet().getCompoundForString("-"); + CompoundSet s = getCompoundSet(); + C gap = s.getCompoundForString("-"); int igap = compounds.indexOf(gap); for (C compound : getCompoundsAt(alignmentIndex)) { int i = compounds.indexOf(compound); - if (i >= 0 && i != igap && !getCompoundSet().compoundsEquivalent(compound, gap)) { + if (i >= 0 && i != igap && !s.compoundsEquivalent(compound, gap)) { counts[i]++; } } @@ -262,7 +264,7 @@ public int[] getCompoundCountsAt(int alignmentIndex, List compounds) { @Override public List getCompoundsAt(int alignmentIndex) { // TODO handle circular alignments - List column = new ArrayList(); + List column = new ArrayList<>(); for (AlignedSequence s : list) { column.add(s.getCompoundAt(alignmentIndex)); } @@ -276,19 +278,20 @@ public CompoundSet getCompoundSet() { @Override public float[] getCompoundWeightsAt(int alignmentIndex) { - return getCompoundWeightsAt(alignmentIndex, getCompoundSet().getAllCompounds()); + return getCompoundWeightsAt(alignmentIndex, new ArrayList(getCompoundSet().getAllCompounds())); } @Override public float[] getCompoundWeightsAt(int alignmentIndex, List compounds) { - float[] weights = new float[compounds.size()]; + int N = compounds.size(); + float[] weights = new float[N]; int[] counts = getCompoundCountsAt(alignmentIndex, compounds); float total = 0.0f; - for (int i : counts) { + for (int i : counts) total += i; - } + if (total > 0.0f) { - for (int i = 0; i < weights.length; i++) { + for (int i = 0; i < N; i++) { weights[i] = counts[i]/total; } } @@ -351,9 +354,10 @@ public ProfileView getSubProfile(Location location) { @Override public boolean hasGap(int alignmentIndex) { - C gap = getCompoundSet().getCompoundForString("-"); + CompoundSet s = getCompoundSet(); + C gap = s.getCompoundForString("-"); for (C compound : getCompoundsAt(alignmentIndex)) { - if (getCompoundSet().compoundsEquivalent(compound, gap)) { + if (s.compoundsEquivalent(compound, gap)) { return true; } } @@ -565,7 +569,7 @@ private void printConservation(StringBuilder s, String idFormat, int seqIndexPad protected static final SubstitutionMatrix matrix = SubstitutionMatrixHelper.getBlosum65(); private boolean isSimilar(char c1, char c2) { - AminoAcidCompoundSet set = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet set = AminoAcidCompoundSet.aminoAcidCompoundSet; AminoAcidCompound aa1 = set.getCompoundForString(String.valueOf(c1)); AminoAcidCompound aa2 = set.getCompoundForString(String.valueOf(c2)); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleProfilePair.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleProfilePair.java index 8d1479bacf..5c5296228c 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleProfilePair.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/SimpleProfilePair.java @@ -46,7 +46,8 @@ public class SimpleProfilePair, C extends Compound> extend private static final long serialVersionUID = 1L; - private Profile query, target; + private final Profile query; + private final Profile target; /** * Creates a pair profile for the given profiles. diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/AAIndexFileParser.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/AAIndexFileParser.java index 6e2e5bff56..7b60bb3bc2 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/AAIndexFileParser.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/AAIndexFileParser.java @@ -38,7 +38,7 @@ public class AAIndexFileParser { int scale = -1; - Map> matrices; + final Map> matrices; ScaledSubstitutionMatrix currentMatrix; String currentRows; @@ -53,7 +53,7 @@ public class AAIndexFileParser { public AAIndexFileParser(){ - matrices = new HashMap>(); + matrices = new HashMap<>(); } /** parse an inputStream that points to an AAINDEX database file @@ -71,7 +71,7 @@ public void parse(InputStream inputStream) throws IOException { inMatrix = false; BufferedReader buf = new BufferedReader (new InputStreamReader (inputStream)); - String line = null; + String line; line = buf.readLine(); while ( line != null ) { @@ -125,10 +125,10 @@ private void processScores(String line) { } - Float score = Float.parseFloat(values[i]); + float score = Float.parseFloat(values[i]); score = scale * score; - Short s = (short) Math.round(score); + short s = (short) Math.round(score); matrix[currentRowPos][i] = s; @@ -150,7 +150,7 @@ private void processScores(String line) { } } - private int determineScale(String value) { + private static int determineScale(String value) { String[] spl = value.split("\\."); @@ -177,12 +177,12 @@ private void initMatrix(String line) { matrix = new short[nrRows][nrCols]; - rows = new ArrayList(); - cols = new ArrayList(); + rows = new ArrayList<>(); + cols = new ArrayList<>(); //System.out.println(">" + currentRows+"<"); - AminoAcidCompoundSet compoundSet = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet compoundSet = AminoAcidCompoundSet.aminoAcidCompoundSet; for ( int i = 0 ; i < currentRows.length() ; i ++){ char c = currentRows.charAt(i); AminoAcidCompound aa = compoundSet.getCompoundForString(String.valueOf(c)); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/AAIndexProvider.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/AAIndexProvider.java index 32b5994c60..9eecd9580d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/AAIndexProvider.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/AAIndexProvider.java @@ -26,5 +26,5 @@ public interface AAIndexProvider { - public SubstitutionMatrix getMatrix(String matrixName); + SubstitutionMatrix getMatrix(String matrixName); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/DefaultAAIndexProvider.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/DefaultAAIndexProvider.java index d9119ed7e8..f105cc4ba1 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/DefaultAAIndexProvider.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/DefaultAAIndexProvider.java @@ -38,7 +38,7 @@ public class DefaultAAIndexProvider implements AAIndexProvider { private final static Logger logger = LoggerFactory.getLogger(DefaultAAIndexProvider.class); - Map> matrices; + final Map> matrices; public DefaultAAIndexProvider(){ @@ -65,7 +65,7 @@ public SubstitutionMatrix getMatrix(String matrixName) { } public InputStream getInputStreamToAAindexFile(){ - return SubstitutionMatrixHelper.class.getResourceAsStream(String.format("/matrices/AAINDEX.txt")); + return SubstitutionMatrixHelper.class.getResourceAsStream("/matrices/AAINDEX.txt"); } } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/ScaledSubstitutionMatrix.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/ScaledSubstitutionMatrix.java index ee26384bfa..c1cf9e51f8 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/ScaledSubstitutionMatrix.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/ScaledSubstitutionMatrix.java @@ -52,14 +52,14 @@ public class ScaledSubstitutionMatrix implements private String description, name; private short[][] matrix; private short max, min; - private AminoAcidCompoundSet compoundSet; + private final AminoAcidCompoundSet compoundSet; private List rows, cols; private int scale; public ScaledSubstitutionMatrix(){ - compoundSet = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + compoundSet = AminoAcidCompoundSet.aminoAcidCompoundSet; } @@ -164,8 +164,8 @@ public String getMatrixAsString() { int lengthCompound = compoundSet.getMaxSingleCompoundStringLength(), lengthRest = Math.max(Math.max(Short.toString(min).length(), Short.toString(max).length()), lengthCompound) + 1; - String padCompound = "%" + Integer.toString(lengthCompound) + "s", - padRest = "%" + Integer.toString(lengthRest); + String padCompound = "%" + lengthCompound + "s", + padRest = "%" + lengthRest; for (int i = 0; i < lengthCompound; i++) { s.append(" "); @@ -216,7 +216,7 @@ public SubstitutionMatrix normalizeMatrix(short scale) { @Override public Map getRow(AminoAcidCompound row) { int rowIndex = rows.indexOf(row); - Map map = new HashMap(); + Map map = new HashMap<>(); for (int colIndex = 0; colIndex < matrix[rowIndex].length; colIndex++) { map.put(cols.get(colIndex), matrix[rowIndex][colIndex]); } @@ -226,7 +226,7 @@ public Map getRow(AminoAcidCompound row) { @Override public Map getColumn(AminoAcidCompound column) { int colIndex = cols.indexOf(column); - Map map = new HashMap(); + Map map = new HashMap<>(); for (int i = 0; i < matrix.length; i++) { map.put(rows.get(i), matrix[i][colIndex]); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/SimpleSubstitutionMatrix.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/SimpleSubstitutionMatrix.java index 8eb897219e..9f56bc31e9 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/SimpleSubstitutionMatrix.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/SimpleSubstitutionMatrix.java @@ -50,14 +50,15 @@ public class SimpleSubstitutionMatrix implements Substitutio private static final String comment = "#"; - private CompoundSet compoundSet; + private final CompoundSet compoundSet; private String description, name; - private short[][] matrix; + private final short[][] matrix; private short max, min; - private List rows, cols; + private final List rows; + private final List cols; public static SubstitutionMatrix getBlosum62() { - return new SimpleSubstitutionMatrix(AminoAcidCompoundSet.getAminoAcidCompoundSet(), new InputStreamReader( + return new SimpleSubstitutionMatrix<>(AminoAcidCompoundSet.aminoAcidCompoundSet, new InputStreamReader( SimpleSubstitutionMatrix.class.getResourceAsStream("/matrices/blosum62.txt")), "blosum62"); } @@ -107,10 +108,11 @@ public SimpleSubstitutionMatrix(CompoundSet compoundSet, short match, short r name = "IDENTITY_" + match + "_" + replace; max = (match > replace) ? match : replace; min = (match < replace) ? match : replace; - rows = cols = compoundSet.getAllCompounds(); - matrix = new short[rows.size()][cols.size()]; - for (int r = 0; r < rows.size(); r++) { - for (int c = 0; c < cols.size(); c++) { + rows = cols = new ArrayList<>(compoundSet.getAllCompounds()); + int N = rows.size(); + matrix = new short[N][N]; + for (int r = 0; r < N; r++) { + for (int c = 0; c < N; c++) { try { matrix[r][c] = (compoundSet.compoundsEquivalent(rows.get(r), cols.get(c))) ? match : replace; } catch (UnsupportedOperationException e) { @@ -126,10 +128,10 @@ private SimpleSubstitutionMatrix(CompoundSet compoundSet, Scanner input, Stri this.name = name; max = Short.MIN_VALUE; min = Short.MAX_VALUE; - rows = new ArrayList(); - cols = new ArrayList(); + rows = new ArrayList<>(); + cols = new ArrayList<>(); StringBuilder descriptionIn = new StringBuilder(); - List matrixIn = new ArrayList(); + List matrixIn = new ArrayList<>(); while(input.hasNextLine()) { String line = input.nextLine(); if (line.startsWith(comment)) { @@ -184,8 +186,8 @@ public String getMatrixAsString() { StringBuilder s = new StringBuilder(); int lengthCompound = compoundSet.getMaxSingleCompoundStringLength(), lengthRest = Math.max(Math.max(Short.toString(min).length(), Short.toString(max).length()), lengthCompound) + 1; - String padCompound = "%" + Integer.toString(lengthCompound) + "s", - padRest = "%" + Integer.toString(lengthRest); + String padCompound = "%" + lengthCompound + "s", + padRest = "%" + lengthRest; for (int i = 0; i < lengthCompound; i++) { s.append(" "); } @@ -229,7 +231,8 @@ public String getName() { private static int getIndexOfCompound(List list, C compound) { int index = list.indexOf(compound); if (index == -1) { - for (int i = 0; i < list.size(); i++) { + int N = list.size(); + for (int i = 0; i < N; i++) { if (compound.equalsIgnoreCase(list.get(i))) { index = i; break; @@ -240,14 +243,16 @@ private static int getIndexOfCompound(List list, C compo } @Override public short getValue(C from, C to) { - int row = getIndexOfCompound(rows, from), col = getIndexOfCompound(cols, to); - if (row == -1 || col == -1) { - row = getIndexOfCompound(cols, from); - col = getIndexOfCompound(rows, to); - if (row == -1 || col == -1) { + int row, col; + if ((row=getIndexOfCompound(rows, from)) == -1 || (col = getIndexOfCompound(cols, to)) == -1) { + + if ((row = getIndexOfCompound(cols, from)) == -1) + return min; + + if ((col = getIndexOfCompound(rows, to)) == -1) return min; - } } + return matrix[row][col]; } @@ -288,8 +293,9 @@ public String toString() { @Override public Map getRow(C row) { int rowIndex = rows.indexOf(row); - Map map = new HashMap(); - for (int colIndex = 0; colIndex < matrix[rowIndex].length; colIndex++) { + Map map = new HashMap<>(); + int N = matrix[rowIndex].length; + for (int colIndex = 0; colIndex < N; colIndex++) { map.put(cols.get(colIndex), matrix[rowIndex][colIndex]); } return map; @@ -298,7 +304,7 @@ public Map getRow(C row) { @Override public Map getColumn(C column) { int colIndex = cols.indexOf(column); - Map map = new HashMap(); + Map map = new HashMap<>(); for (int i = 0; i < matrix.length; i++) { map.put(rows.get(i), matrix[i][colIndex]); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/SubstitutionMatrixHelper.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/SubstitutionMatrixHelper.java index 7b629e7352..ad37e92e37 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/SubstitutionMatrixHelper.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/matrices/SubstitutionMatrixHelper.java @@ -48,10 +48,10 @@ public class SubstitutionMatrixHelper implements Serializable { */ private static final long serialVersionUID = 148491724604653225L; - private static Map> aminoAcidMatrices = - new HashMap>(); - private static Map> nucleotideMatrices = - new HashMap>(); + private static final Map> aminoAcidMatrices = + new HashMap<>(); + private static final Map> nucleotideMatrices = + new HashMap<>(); // prevents instantiation private SubstitutionMatrixHelper() { } @@ -251,8 +251,8 @@ public static SubstitutionMatrix getAminoAcidSubstitutionMatr // reads in an amino acid substitution matrix, if necessary private static SubstitutionMatrix getAminoAcidMatrix(String file) { if (!aminoAcidMatrices.containsKey(file)) { - aminoAcidMatrices.put(file, new SimpleSubstitutionMatrix( - AminoAcidCompoundSet.getAminoAcidCompoundSet(), getReader(file), file)); + aminoAcidMatrices.put(file, new SimpleSubstitutionMatrix<>( + AminoAcidCompoundSet.aminoAcidCompoundSet, getReader(file), file)); } return aminoAcidMatrices.get(file); } @@ -260,7 +260,7 @@ private static SubstitutionMatrix getAminoAcidMatrix(String f // reads in a nucleotide substitution matrix, if necessary private static SubstitutionMatrix getNucleotideMatrix(String file) { if (!nucleotideMatrices.containsKey(file)) { - nucleotideMatrices.put(file, new SimpleSubstitutionMatrix( + nucleotideMatrices.put(file, new SimpleSubstitutionMatrix<>( AmbiguityDNACompoundSet.getDNACompoundSet(), getReader(file), file)); } return nucleotideMatrices.get(file); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableAlignedSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableAlignedSequence.java index cfe85f7d33..1291eda8ad 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableAlignedSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableAlignedSequence.java @@ -23,7 +23,6 @@ package org.biojava.nbio.core.alignment.template; -import org.biojava.nbio.core.alignment.template.AlignedSequence; import org.biojava.nbio.core.sequence.location.template.Location; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableProfile.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableProfile.java index eed30626de..522896c774 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableProfile.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableProfile.java @@ -23,8 +23,6 @@ package org.biojava.nbio.core.alignment.template; -import org.biojava.nbio.core.alignment.template.Profile; -import org.biojava.nbio.core.alignment.template.AlignedSequence; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableProfilePair.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableProfilePair.java index 70bd1d6410..3d63b0fd39 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableProfilePair.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableProfilePair.java @@ -23,8 +23,6 @@ package org.biojava.nbio.core.alignment.template; -import org.biojava.nbio.core.alignment.template.ProfilePair; -import org.biojava.nbio.core.alignment.template.Profile; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableSequencePair.java b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableSequencePair.java index 86304b7448..78480912c4 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableSequencePair.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/alignment/template/MutableSequencePair.java @@ -23,8 +23,6 @@ package org.biojava.nbio.core.alignment.template; -import org.biojava.nbio.core.alignment.template.SequencePair; -import org.biojava.nbio.core.alignment.template.AlignedSequence; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/exceptions/CompoundNotFoundException.java b/biojava-core/src/main/java/org/biojava/nbio/core/exceptions/CompoundNotFoundException.java index 4a16546a68..be5b6c5e7f 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/exceptions/CompoundNotFoundException.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/exceptions/CompoundNotFoundException.java @@ -25,7 +25,9 @@ */ package org.biojava.nbio.core.exceptions; -public class CompoundNotFoundException extends Exception { +import java.io.IOException; + +public class CompoundNotFoundException extends IOException { /** * */ diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Hit.java b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Hit.java index bf5ee54c69..0a3ba9cae4 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Hit.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Hit.java @@ -20,11 +20,12 @@ */ package org.biojava.nbio.core.search.io; +import org.biojava.nbio.core.sequence.template.Sequence; + import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; - -import org.biojava.nbio.core.sequence.template.Sequence; +import java.util.Objects; /** * This class models a search Hit. @@ -47,7 +48,7 @@ public abstract class Hit implements Iterable{ */ private final int hitLen; private final List hsps; - private Sequence hitSequence; + private final Sequence hitSequence; @@ -85,7 +86,7 @@ public boolean equals(Object obj) { if (this.hitLen != other.hitLen) { return false; } - if (this.hsps != other.hsps && (this.hsps == null || !this.hsps.equals(other.hsps))) { + if (!Objects.equals(this.hsps, other.hsps)) { return false; } return true; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Hsp.java b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Hsp.java index 8245c635c3..a94f8c29fc 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Hsp.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Hsp.java @@ -20,8 +20,6 @@ */ package org.biojava.nbio.core.search.io; -import java.util.ArrayList; -import java.util.List; import org.biojava.nbio.core.alignment.SimpleAlignedSequence; import org.biojava.nbio.core.alignment.SimpleSequencePair; import org.biojava.nbio.core.alignment.template.AlignedSequence.Step; @@ -37,6 +35,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + /** * This class models a search Hsp. * You will retrieve a list of this using iterator of a Hit @@ -51,25 +53,25 @@ public abstract class Hsp , C extends Compound> { private static final Logger logger = LoggerFactory.getLogger(Hsp.class); - private Integer hspNum; - private Double hspBitScore; - private Integer hspScore; - private Double hspEvalue; - private Integer hspQueryFrom; - private Integer hspQueryTo; - private Integer hspHitFrom; - private Integer hspHitTo; - private Integer hspQueryFrame; - private Integer hspHitFrame; + private final Integer hspNum; + private final Double hspBitScore; + private final Integer hspScore; + private final Double hspEvalue; + private final Integer hspQueryFrom; + private final Integer hspQueryTo; + private final Integer hspHitFrom; + private final Integer hspHitTo; + private final Integer hspQueryFrame; + private final Integer hspHitFrame; private Integer hspIdentity; - private Integer hspPositive; - private Integer hspGaps; + private final Integer hspPositive; + private final Integer hspGaps; private Integer hspAlignLen; - private String hspQseq; - private String hspHseq; - private String hspIdentityString; - private Double percentageIdentity = null; - private Integer mismatchCount = null; + private final String hspQseq; + private final String hspHseq; + private final String hspIdentityString; + private final Double percentageIdentity; + private final Integer mismatchCount; private SimpleSequencePair returnAln; @Override @@ -98,13 +100,13 @@ public boolean equals(Object obj) { return false; } final Hsp other = (Hsp) obj; - if ((this.hspQseq == null) ? (other.hspQseq != null) : !this.hspQseq.equals(other.hspQseq)) { + if (!Objects.equals(this.hspQseq, other.hspQseq)) { return false; } - if ((this.hspHseq == null) ? (other.hspHseq != null) : !this.hspHseq.equals(other.hspHseq)) { + if (!Objects.equals(this.hspHseq, other.hspHseq)) { return false; } - if ((this.hspIdentityString == null) ? (other.hspIdentityString != null) : !this.hspIdentityString.equals(other.hspIdentityString)) { + if (!Objects.equals(this.hspIdentityString, other.hspIdentityString)) { return false; } return true; @@ -115,17 +117,15 @@ public SequencePair getAlignment(){ SimpleAlignedSequence alignedQuery, alignedHit; // queryFrom e hitTo? - int numBefore, numAfter; +// int numBefore, numAfter; alignedQuery = new SimpleAlignedSequence(getSequence(hspQseq), getAlignmentsSteps(hspQseq)); alignedHit = new SimpleAlignedSequence(getSequence(hspHseq), getAlignmentsSteps(hspHseq)); - returnAln = new SimpleSequencePair(alignedQuery, alignedHit); - - return returnAln; + return returnAln = new SimpleSequencePair<>(alignedQuery, alignedHit); } - private Sequence getSequence(String gappedSequenceString){ + private static Sequence getSequence(String gappedSequenceString){ if (gappedSequenceString == null) return null; Sequence returnSeq = null; @@ -137,7 +137,7 @@ private Sequence getSequence(String gappedSequenceString){ else if (sequenceString.matches("^[ACUG]+$")) returnSeq = new RNASequence(sequenceString, DNACompoundSet.getDNACompoundSet()); else - returnSeq = new ProteinSequence(sequenceString, AminoAcidCompoundSet.getAminoAcidCompoundSet()); + returnSeq = new ProteinSequence(sequenceString, AminoAcidCompoundSet.aminoAcidCompoundSet); } catch (CompoundNotFoundException ex) { logger.error("Unexpected error, could not find compound when creating Sequence object from Hsp", ex); } @@ -145,7 +145,7 @@ else if (sequenceString.matches("^[ACUG]+$")) } private List getAlignmentsSteps(String gappedSequenceString){ - List returnList = new ArrayList(); + List returnList = new ArrayList<>(); for (char c: gappedSequenceString.toCharArray()){ if (c=='-') returnList.add(Step.GAP); else returnList.add(Step.COMPOUND); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Result.java b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Result.java index aa1b432b57..aeab300342 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Result.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/Result.java @@ -20,14 +20,10 @@ */ package org.biojava.nbio.core.search.io; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.NoSuchElementException; - import org.biojava.nbio.core.sequence.template.Sequence; +import java.util.*; + /** * This class models a search result. * You will find one of this for every query sequence specified in the run. @@ -41,20 +37,20 @@ */ public abstract class Result implements Iterable{ - private String program; - private String version; - private String reference; - private String dbFile; + private final String program; + private final String version; + private final String reference; + private final String dbFile; - private HashMap programSpecificParameters; + private final HashMap programSpecificParameters; - private int iterationNumber; - private String queryID; - private String queryDef; - private int queryLength; - private Sequence querySequence; - private List hits; - private int hitCounter = -1; + private final int iterationNumber; + private final String queryID; + private final String queryDef; + private final int queryLength; + private final Sequence querySequence; + private final List hits; + private final int hitCounter = -1; public Result(String program, String version, String reference, String dbFile, HashMap programSpecificParameters, int iterationNumber, String queryID, String queryDef, int queryLength, List hits, Sequence querySequence) { this.program = program; @@ -87,6 +83,7 @@ public int hashCode() { */ @Override public boolean equals(Object obj) { + if (this == obj) return true; if (obj == null) { return false; } @@ -94,16 +91,9 @@ public boolean equals(Object obj) { return false; } final Result other = (Result) obj; - if ((this.queryID == null) ? (other.queryID != null) : !this.queryID.equals(other.queryID)) { - return false; - } - if ((this.queryDef == null) ? (other.queryDef != null) : !this.queryDef.equals(other.queryDef)) { - return false; - } - if (this.hits != other.hits && (this.hits == null || !this.hits.equals(other.hits))) { - return false; - } - return true; + return Objects.equals(this.queryID, other.queryID) && + Objects.equals(this.queryDef, other.queryDef) && + Objects.equals(this.hits, other.hits); } public int getIterationNumber() { diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/ResultFactory.java b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/ResultFactory.java index 479df1ac4d..5e2693b997 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/ResultFactory.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/ResultFactory.java @@ -20,11 +20,12 @@ */ package org.biojava.nbio.core.search.io; +import org.biojava.nbio.core.sequence.template.Sequence; + import java.io.File; import java.io.IOException; import java.text.ParseException; import java.util.List; -import org.biojava.nbio.core.sequence.template.Sequence; /** * Designed by Paolo Pavan. @@ -59,7 +60,7 @@ public interface ResultFactory { * @param results * @throws Exception */ - void storeObjects(List results) throws IOException, ParseException; + void storeObjects(List results); /** * Specify the collection of sequences objects used as queries in the Search run. diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/SearchIO.java b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/SearchIO.java index 52654720d9..ce41e1c248 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/SearchIO.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/SearchIO.java @@ -23,11 +23,7 @@ import java.io.File; import java.io.IOException; import java.text.ParseException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.ServiceLoader; -import java.util.NoSuchElementException; +import java.util.*; /** * Designed by Paolo Pavan. @@ -55,7 +51,7 @@ public class SearchIO implements Iterable{ */ private List results; - private final String NOT_SUPPORTED_FILE_EXCEPTION = + private static final String NOT_SUPPORTED_FILE_EXCEPTION = "This extension is not associated with any parser. You can try to specify a ResultFactory object."; /** @@ -140,7 +136,7 @@ public void writeResults() throws IOException, ParseException { */ private ResultFactory guessFactory(File f){ if (extensionFactoryAssociation == null){ - extensionFactoryAssociation = new HashMap(); + extensionFactoryAssociation = new HashMap<>(); ServiceLoader impl = ServiceLoader.load(ResultFactory.class); for (ResultFactory loadedImpl : impl) { List fileExtensions = loadedImpl.getFileExtensions(); @@ -149,7 +145,7 @@ private ResultFactory guessFactory(File f){ } String filename = f.getAbsolutePath(); - int extensionPos = filename.lastIndexOf("."); + int extensionPos = filename.lastIndexOf('.'); String extension = filename.substring(extensionPos + 1); if (extensionFactoryAssociation.get(extension) == null) throw new UnsupportedOperationException(NOT_SUPPORTED_FILE_EXCEPTION diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastHitBuilder.java b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastHitBuilder.java index f227e9a68b..ba2e8b5232 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastHitBuilder.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastHitBuilder.java @@ -22,9 +22,10 @@ import org.biojava.nbio.core.search.io.Hsp; -import java.util.List; import org.biojava.nbio.core.sequence.template.Sequence; +import java.util.List; + /** * Designed by Paolo Pavan. * You may want to find my contacts on Github and LinkedIn for code info diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastResult.java b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastResult.java index bcacdde20d..00a2340455 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastResult.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastResult.java @@ -22,9 +22,10 @@ import org.biojava.nbio.core.search.io.Hit; import org.biojava.nbio.core.search.io.Result; +import org.biojava.nbio.core.sequence.template.Sequence; + import java.util.HashMap; import java.util.List; -import org.biojava.nbio.core.sequence.template.Sequence; /** * This class models a Blast/Blast plus result. diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastResultBuilder.java b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastResultBuilder.java index 8d7e06a89e..95a5891cb7 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastResultBuilder.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastResultBuilder.java @@ -21,9 +21,10 @@ package org.biojava.nbio.core.search.io.blast; import org.biojava.nbio.core.search.io.Hit; +import org.biojava.nbio.core.sequence.template.Sequence; + import java.util.HashMap; import java.util.List; -import org.biojava.nbio.core.sequence.template.Sequence; /** * Designed by Paolo Pavan. diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastTabularParser.java b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastTabularParser.java index 410fad0fce..0f408c0ef0 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastTabularParser.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastTabularParser.java @@ -20,16 +20,6 @@ */ package org.biojava.nbio.core.search.io.blast; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.LineNumberReader; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Scanner; import org.biojava.nbio.core.search.io.Hit; import org.biojava.nbio.core.search.io.Hsp; import org.biojava.nbio.core.search.io.Result; @@ -38,6 +28,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.*; +import java.text.ParseException; +import java.util.*; + /** * Designed by Paolo Pavan. * You may want to find my contacts on Github and LinkedIn for code info @@ -48,7 +42,7 @@ */ public class BlastTabularParser implements ResultFactory { - private final String blastReference = + private static final String blastReference = "Zheng Zhang, Scott Schwartz, Lukas Wagner, and Webb Miller (2000), A greedy algorithm for aligning DNA sequences", J Comput Biol 2000; 7(1-2):203-14."; /** * Tries to define a different level of consistency during parsing. @@ -71,7 +65,7 @@ private enum PARSING_CONSISTENCY { // data imported private: int queryIdNumber = 0; - HashMap queryIdMapping = new HashMap(); + final Map queryIdMapping = new HashMap<>(); String programName=null, queryName = null, databaseFile = null; private String queryId ; private String subjectId ; @@ -89,7 +83,7 @@ private enum PARSING_CONSISTENCY { @Override public List getFileExtensions() { - List l = new ArrayList(); + List l = new ArrayList<>(); l.add("blasttabular"); l.add("blasttxt"); return l; @@ -102,7 +96,7 @@ public void setFile(File f) { @Override public List createObjects(double maxEScore) throws IOException, ParseException { - List results = new ArrayList(); + List results = new ArrayList<>(); log.info("Query for hits"); LineNumberReader lnr = new LineNumberReader(new FileReader(targetFile)); @@ -126,33 +120,33 @@ public List createObjects(double maxEScore) throws IOException, ParseExc .setQueryDef(queryName) .setReference(blastReference); - List hits = new ArrayList(); + List hits = new ArrayList<>(); String currentQueryId = queryId; while (currentQueryId.equals(queryId) && lineNumber < fileLinesCount){ BlastHitBuilder hitBuilder = new BlastHitBuilder(); - List hsps = new ArrayList(); + List hsps = new ArrayList<>(); String currentSubjectId=subjectId; while (currentSubjectId.equals(subjectId) && lineNumber < fileLinesCount){ - if (new Double(evalue) > maxEScore) { + if (Double.parseDouble(evalue) > maxEScore) { line = fetchData(scanner); lineNumber++; continue; } BlastHspBuilder hspBuilder = new BlastHspBuilder(); hspBuilder - .setHspAlignLen(new Integer(alnLength)) - .setHspGaps(new Integer(gapOpenCount)) - .setHspQueryFrom(new Integer(queryStart)) - .setHspQueryTo(new Integer(queryEnd)) - .setHspHitFrom(new Integer(subjectStart)) - .setHspHitTo(new Integer(subjectEnd)) - .setHspEvalue(new Double(evalue)) - .setHspBitScore(new Double(bitScore)) - .setPercentageIdentity(new Double(percIdentity)/100) - .setMismatchCount(new Integer(mismatchCount)); + .setHspAlignLen(Integer.parseInt(alnLength)) + .setHspGaps(Integer.parseInt(gapOpenCount)) + .setHspQueryFrom(Integer.parseInt(queryStart)) + .setHspQueryTo(Integer.parseInt(queryEnd)) + .setHspHitFrom(Integer.parseInt(subjectStart)) + .setHspHitTo(Integer.parseInt(subjectEnd)) + .setHspEvalue(Double.parseDouble(evalue)) + .setHspBitScore(Double.parseDouble(bitScore)) + .setPercentageIdentity(Double.parseDouble(percIdentity)/100) + .setMismatchCount(Integer.parseInt(mismatchCount)); hsps.add(hspBuilder.createBlastHsp()); if (scanner.hasNext()) line = fetchData(scanner); lineNumber++; @@ -172,7 +166,7 @@ private String fetchData(Scanner scanner){ String[] split; line = scanner.nextLine(); - while (line.startsWith("#")){ + while (line.charAt(0) == '#'){ // blast tabular with header options contains some more informations if (line.matches("#\\s.?BLAST.+")) programName = line.replace("#\\s",""); if (line.startsWith("# Query:")) queryName = line.replace("# Query: ",""); @@ -203,13 +197,10 @@ private String fetchData(Scanner scanner){ // blast tabular reports only the first word of the query name. // If it was specified in the header it is better to use that definition if (parsingConsistency == PARSING_CONSISTENCY.IMPROVED && headerFound) { - if (queryIdMapping.get(queryId)==null) { - queryIdNumber ++; - queryIdMapping.put(queryId,"Query_" + queryIdNumber); - } + // If a complete definition of the query name was readed, than we can use // a queryID schema that is consistent with blast xml report - queryId = queryIdMapping.get(queryId); + queryId = queryIdMapping.computeIfAbsent(queryId, x -> "Query_" + (++queryIdNumber)); } if (!headerFound) queryName = queryId; @@ -217,7 +208,7 @@ private String fetchData(Scanner scanner){ } @Override - public void storeObjects(List results) throws IOException, ParseException { + public void storeObjects(List results) { throw new UnsupportedOperationException("Not supported yet."); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastXMLParser.java b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastXMLParser.java index 1b30639b80..25efda84cd 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastXMLParser.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/search/io/blast/BlastXMLParser.java @@ -25,6 +25,15 @@ import org.biojava.nbio.core.search.io.Hsp; import org.biojava.nbio.core.search.io.Result; import org.biojava.nbio.core.search.io.ResultFactory; +import org.biojava.nbio.core.sequence.template.Sequence; +import org.biojava.nbio.core.util.XMLHelper; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.xpath.XPathException; import java.io.File; import java.io.IOException; import java.text.ParseException; @@ -32,14 +41,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.xpath.XPathException; -import org.biojava.nbio.core.sequence.template.Sequence; -import org.biojava.nbio.core.util.XMLHelper; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.xml.sax.SAXException; /** * Re-designed by Paolo Pavan on the footprint of: @@ -102,10 +103,10 @@ public List createObjects(double maxEScore) throws IOException, ParseExc String dbFile = XMLHelper.selectSingleElement(blastDoc.getDocumentElement(),"BlastOutput_db").getTextContent(); logger.info("Query for hits in "+ targetFile); - ArrayList IterationsList = XMLHelper.selectElements(blastDoc.getDocumentElement(), "BlastOutput_iterations/Iteration[Iteration_hits]"); + List IterationsList = XMLHelper.selectElements(blastDoc.getDocumentElement(), "BlastOutput_iterations/Iteration[Iteration_hits]"); logger.info(IterationsList.size() + " results"); - resultsCollection = new ArrayList(); + resultsCollection = new ArrayList<>(); for (Element element : IterationsList) { BlastResultBuilder resultBuilder = new BlastResultBuilder(); // will add BlastOutput* key sections in the result object @@ -117,10 +118,10 @@ public List createObjects(double maxEScore) throws IOException, ParseExc // Iteration* section keys: resultBuilder - .setIterationNumber(new Integer(XMLHelper.selectSingleElement(element,"Iteration_iter-num").getTextContent())) + .setIterationNumber(Integer.parseInt(XMLHelper.selectSingleElement(element, "Iteration_iter-num").getTextContent())) .setQueryID(XMLHelper.selectSingleElement(element,"Iteration_query-ID").getTextContent()) .setQueryDef(XMLHelper.selectSingleElement(element, "Iteration_query-def").getTextContent()) - .setQueryLength(new Integer(XMLHelper.selectSingleElement(element,"Iteration_query-len").getTextContent())); + .setQueryLength(Integer.parseInt(XMLHelper.selectSingleElement(element, "Iteration_query-len").getTextContent())); if (queryReferences != null) resultBuilder.setQuerySequence(queryReferencesMap.get( XMLHelper.selectSingleElement(element,"Iteration_query-ID").getTextContent() @@ -128,48 +129,49 @@ public List createObjects(double maxEScore) throws IOException, ParseExc + hitsCollection = new ArrayList<>(); + Element iterationHitsElement = XMLHelper.selectSingleElement(element, "Iteration_hits"); - ArrayList hitList = XMLHelper.selectElements(iterationHitsElement, "Hit"); + List hitList = XMLHelper.selectElements(iterationHitsElement, "Hit"); - hitsCollection = new ArrayList(); for (Element hitElement : hitList) { BlastHitBuilder blastHitBuilder = new BlastHitBuilder(); blastHitBuilder - .setHitNum(new Integer(XMLHelper.selectSingleElement(hitElement, "Hit_num").getTextContent())) + .setHitNum(Integer.parseInt(XMLHelper.selectSingleElement(hitElement, "Hit_num").getTextContent())) .setHitId(XMLHelper.selectSingleElement(hitElement, "Hit_id").getTextContent()) .setHitDef(XMLHelper.selectSingleElement(hitElement, "Hit_def").getTextContent()) .setHitAccession(XMLHelper.selectSingleElement(hitElement, "Hit_accession").getTextContent()) - .setHitLen(new Integer(XMLHelper.selectSingleElement(hitElement, "Hit_len").getTextContent())); + .setHitLen(Integer.parseInt(XMLHelper.selectSingleElement(hitElement, "Hit_len").getTextContent())); if (databaseReferences != null) blastHitBuilder.setHitSequence(databaseReferencesMap.get( XMLHelper.selectSingleElement(hitElement, "Hit_id").getTextContent() )); Element hithspsElement = XMLHelper.selectSingleElement(hitElement, "Hit_hsps"); - ArrayList hspList = XMLHelper.selectElements(hithspsElement, "Hsp"); + List hspList = XMLHelper.selectElements(hithspsElement, "Hsp"); - hspsCollection = new ArrayList(); + hspsCollection = new ArrayList<>(); for (Element hspElement : hspList) { - Double evalue = new Double(XMLHelper.selectSingleElement(hspElement, "Hsp_evalue").getTextContent()); + double evalue = new Double(XMLHelper.selectSingleElement(hspElement, "Hsp_evalue").getTextContent()); // add the new hsp only if it pass the specified threshold. It can save lot of memory and some parsing time if (evalue <= maxEScore) { BlastHspBuilder blastHspBuilder = new BlastHspBuilder(); blastHspBuilder - .setHspNum(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_num").getTextContent())) + .setHspNum(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_num").getTextContent())) .setHspBitScore(new Double(XMLHelper.selectSingleElement(hspElement, "Hsp_bit-score").getTextContent())) - .setHspScore(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_score").getTextContent())) + .setHspScore(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_score").getTextContent())) .setHspEvalue(evalue) - .setHspQueryFrom(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_query-from").getTextContent())) - .setHspQueryTo(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_query-to").getTextContent())) - .setHspHitFrom(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_hit-from").getTextContent())) - .setHspHitTo(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_hit-to").getTextContent())) - .setHspQueryFrame(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_query-frame").getTextContent())) - .setHspHitFrame(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_hit-frame").getTextContent())) - .setHspIdentity(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_identity").getTextContent())) - .setHspPositive(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_positive").getTextContent())) - .setHspGaps(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_gaps").getTextContent())) - .setHspAlignLen(new Integer(XMLHelper.selectSingleElement(hspElement, "Hsp_align-len").getTextContent())) + .setHspQueryFrom(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_query-from").getTextContent())) + .setHspQueryTo(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_query-to").getTextContent())) + .setHspHitFrom(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_hit-from").getTextContent())) + .setHspHitTo(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_hit-to").getTextContent())) + .setHspQueryFrame(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_query-frame").getTextContent())) + .setHspHitFrame(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_hit-frame").getTextContent())) + .setHspIdentity(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_identity").getTextContent())) + .setHspPositive(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_positive").getTextContent())) + .setHspGaps(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_gaps").getTextContent())) + .setHspAlignLen(Integer.parseInt(XMLHelper.selectSingleElement(hspElement, "Hsp_align-len").getTextContent())) .setHspQseq(XMLHelper.selectSingleElement(hspElement, "Hsp_qseq").getTextContent()) .setHspHseq(XMLHelper.selectSingleElement(hspElement, "Hsp_hseq").getTextContent()) .setHspIdentityString(XMLHelper.selectSingleElement(hspElement, "Hsp_midline").getTextContent()); @@ -195,7 +197,7 @@ public List createObjects(double maxEScore) throws IOException, ParseExc @Override public List getFileExtensions(){ - ArrayList extensions = new ArrayList(1); + ArrayList extensions = new ArrayList<>(1); extensions.add("blastxml"); return extensions; } @@ -215,25 +217,23 @@ public void setDatabaseReferences(List sequences) { */ private void mapIds() { if (queryReferences != null) { - queryReferencesMap = new HashMap(queryReferences.size()); + queryReferencesMap = new HashMap<>(queryReferences.size()); for (int counter=0; counter < queryReferences.size() ; counter ++){ - String id = "Query_"+(counter+1); - queryReferencesMap.put(id, queryReferences.get(counter)); + queryReferencesMap.put("Query_"+(counter+1), queryReferences.get(counter)); } } if (databaseReferences != null) { - databaseReferencesMap = new HashMap(databaseReferences.size()); + databaseReferencesMap = new HashMap<>(databaseReferences.size()); for (int counter=0; counter < databaseReferences.size() ; counter ++){ // this is strange: while Query_id are 1 based, Hit (database) id are 0 based - String id = "gnl|BL_ORD_ID|"+(counter); - databaseReferencesMap.put(id, databaseReferences.get(counter)); + databaseReferencesMap.put("gnl|BL_ORD_ID|"+(counter), databaseReferences.get(counter)); } } } @Override - public void storeObjects(List results) throws IOException, ParseException { + public void storeObjects(List results) { throw new UnsupportedOperationException("This parser does not support writing yet."); } } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/AccessionID.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/AccessionID.java index c54c6930a8..c929fc6015 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/AccessionID.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/AccessionID.java @@ -25,6 +25,8 @@ import org.biojava.nbio.core.util.Equals; import org.biojava.nbio.core.util.Hashcoder; +import java.util.Objects; + /** * Used in Sequences as the unique indentifier. If possible, set the {@link DataSource} to know the * source of the id. This allows a SequenceProxy to gather features or related sequences @@ -36,7 +38,7 @@ */ public class AccessionID { - private String id = null; + private final String id; private DataSource source = DataSource.LOCAL; private Integer version; private String identifier = null; @@ -93,13 +95,14 @@ public DataSource getDataSource() { @Override public boolean equals(Object o) { + if (this == o) return true; boolean equals = false; if (Equals.classEqual(this, o)) { AccessionID l = (AccessionID) o; - equals = (Equals.equal(getID(), l.getID()) - && Equals.equal(getDataSource(), l.getDataSource()) - && Equals.equal(getIdentifier(), l.getIdentifier()) - && Equals.equal(getVersion(), l.getVersion())); + equals = (Objects.equals(getID(), l.getID()) + && Objects.equals(getDataSource(), l.getDataSource()) + && Objects.equals(getIdentifier(), l.getIdentifier()) + && Objects.equals(getVersion(), l.getVersion())); } return equals; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/CDSSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/CDSSequence.java index 5973dd386e..e240327ffa 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/CDSSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/CDSSequence.java @@ -37,8 +37,8 @@ public class CDSSequence extends DNASequence { //private static final Logger log = Logger.getLogger(CDSSequence.class.getName()); - Integer phase = 0; // 0, 1, 2 - TranscriptSequence parentTranscriptSequence; + final Integer phase; // 0, 1, 2 + final TranscriptSequence parentTranscriptSequence; /** * diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/ChromosomeSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/ChromosomeSequence.java index f53c539137..eeae4281a4 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/ChromosomeSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/ChromosomeSequence.java @@ -37,7 +37,7 @@ public class ChromosomeSequence extends DNASequence { private int chromosomeNumber; - private LinkedHashMap geneSequenceHashMap = new LinkedHashMap(); + private final LinkedHashMap geneSequenceHashMap = new LinkedHashMap<>(); /** * Empty constructor used by tools that need a proper Bean that allows the actual diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/DNASequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/DNASequence.java index a8d072b4a1..9f77194fce 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/DNASequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/DNASequence.java @@ -136,14 +136,14 @@ public int getGCCount() { * Returns a Sequence which runs in the current reverse order */ public SequenceView getReverse() { - return new ReversedSequenceView(this); + return new ReversedSequenceView<>(this); } /** * Returns a Sequence which will complement every base */ public SequenceView getComplement() { - return new ComplementSequenceView(this); + return new ComplementSequenceView<>(this); } /** @@ -172,7 +172,7 @@ public static void main(String[] args) throws Exception { logger.info("DNA Sequence: {}", dnaSequence.toString()); StringProxySequenceReader sequenceStringProxyLoader = - new StringProxySequenceReader("GCTA", DNACompoundSet.getDNACompoundSet()); + new StringProxySequenceReader<>("GCTA", DNACompoundSet.getDNACompoundSet()); DNASequence dnaSequenceFromProxy = new DNASequence(sequenceStringProxyLoader); logger.info("DNA Sequence from Proxy: {}", dnaSequenceFromProxy.toString()); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/GeneSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/GeneSequence.java index db1f4fd26f..05a040344a 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/GeneSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/GeneSequence.java @@ -30,7 +30,6 @@ import org.slf4j.LoggerFactory; import java.util.ArrayList; -import java.util.Collections; import java.util.LinkedHashMap; /** @@ -41,14 +40,14 @@ public class GeneSequence extends DNASequence { private final static Logger logger = LoggerFactory.getLogger(GeneSequence.class); - private final LinkedHashMap transcriptSequenceHashMap = new LinkedHashMap(); - private final LinkedHashMap intronSequenceHashMap = new LinkedHashMap(); - private final LinkedHashMap exonSequenceHashMap = new LinkedHashMap(); - private final ArrayList intronSequenceList = new ArrayList(); - private final ArrayList exonSequenceList = new ArrayList(); + private final LinkedHashMap transcriptSequenceHashMap = new LinkedHashMap<>(); + private final LinkedHashMap intronSequenceHashMap = new LinkedHashMap<>(); + private final LinkedHashMap exonSequenceHashMap = new LinkedHashMap<>(); + private final ArrayList intronSequenceList = new ArrayList<>(); + private final ArrayList exonSequenceList = new ArrayList<>(); boolean intronAdded = false; // need to deal with the problem that typically introns are not added when validating the list and adding in introns as the regions not included in exons private Strand strand = Strand.UNDEFINED; - private ChromosomeSequence chromosomeSequence; + private final ChromosomeSequence chromosomeSequence; /** * A class that keeps track of the details of a GeneSequence which is difficult to properly model. Two important concepts that is difficult @@ -102,7 +101,7 @@ public void addIntronsUsingExons() throws Exception { } ExonComparator exonComparator = new ExonComparator(); //sort based on start position and sense; - Collections.sort(exonSequenceList, exonComparator); + exonSequenceList.sort(exonComparator); int shift = -1; if (getStrand() == Strand.NEGATIVE) { shift = 1; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/MultipleSequenceAlignment.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/MultipleSequenceAlignment.java index 1ab060d23e..bc30122aea 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/MultipleSequenceAlignment.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/MultipleSequenceAlignment.java @@ -42,7 +42,7 @@ */ public class MultipleSequenceAlignment, C extends Compound> implements LightweightProfile { - private List sequences = new ArrayList(); + private final List sequences = new ArrayList<>(); private Integer length = null; /** @@ -98,7 +98,7 @@ public List getAlignedSequences() { */ @Override public List getCompoundsAt(int alignmentIndex) { - List column = new ArrayList(); + List column = new ArrayList<>(); for (S s : sequences) { column.add(s.getCompoundAt(alignmentIndex)); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/ProteinSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/ProteinSequence.java index e3abbea6bd..f58cbf04b9 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/ProteinSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/ProteinSequence.java @@ -25,6 +25,7 @@ import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.compound.*; import org.biojava.nbio.core.sequence.features.FeatureInterface; +import org.biojava.nbio.core.sequence.features.Qualifier; import org.biojava.nbio.core.sequence.io.DNASequenceCreator; import org.biojava.nbio.core.sequence.io.FastaReader; import org.biojava.nbio.core.sequence.io.PlainFastaHeaderParser; @@ -34,6 +35,7 @@ import org.biojava.nbio.core.sequence.template.AbstractSequence; import org.biojava.nbio.core.sequence.template.CompoundSet; import org.biojava.nbio.core.sequence.template.ProxySequenceReader; +import org.biojava.nbio.core.util.Download; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,7 +44,6 @@ import java.net.URL; import java.util.LinkedHashMap; import java.util.List; -import org.biojava.nbio.core.sequence.features.Qualifier; /** * The representation of a ProteinSequence @@ -67,7 +68,7 @@ public class ProteinSequence extends AbstractSequence { * @throws CompoundNotFoundException */ public ProteinSequence(String seqString) throws CompoundNotFoundException { - this(seqString, AminoAcidCompoundSet.getAminoAcidCompoundSet()); + this(seqString, AminoAcidCompoundSet.aminoAcidCompoundSet); } /** @@ -89,7 +90,7 @@ public ProteinSequence(String seqString, CompoundSet compound * @param proxyLoader */ public ProteinSequence(ProxySequenceReader proxyLoader) { - this(proxyLoader, AminoAcidCompoundSet.getAminoAcidCompoundSet()); + this(proxyLoader, AminoAcidCompoundSet.aminoAcidCompoundSet); } /** @@ -156,15 +157,13 @@ private DNASequence getRawParentSequence(String accessId) throws IOException { String seqUrlTemplate = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nuccore&id=%s&rettype=fasta&retmode=text"; URL url = new URL(String.format(seqUrlTemplate, accessId)); - logger.trace("Getting parent DNA sequence from URL: {}", url.toString()); + logger.trace("Getting parent DNA sequence from URL: {}", url); - InputStream is = url.openConnection().getInputStream(); + InputStream is = Download.stream(url); //url.openConnection().getInputStream(); - FastaReader parentReader - = new FastaReader(is, - new PlainFastaHeaderParser(), - new DNASequenceCreator(AmbiguityDNACompoundSet.getDNACompoundSet())); - LinkedHashMap seq = parentReader.process(); + LinkedHashMap seq = new FastaReader(is, + new PlainFastaHeaderParser<>(), + new DNASequenceCreator(AmbiguityDNACompoundSet.getDNACompoundSet())).process(); DNASequence parentSeq = null; if (seq.size() == 1) { @@ -203,7 +202,7 @@ public static void main(String[] args) throws Exception { ProteinSequence proteinSequence = new ProteinSequence("ARNDCEQGHILKMFPSTWYVBZJX"); logger.info("Protein Sequence: {}", proteinSequence.toString()); - StringProxySequenceReader sequenceStringProxyLoader = new StringProxySequenceReader("XRNDCEQGHILKMFPSTWYVBZJA", AminoAcidCompoundSet.getAminoAcidCompoundSet()); + StringProxySequenceReader sequenceStringProxyLoader = new StringProxySequenceReader<>("XRNDCEQGHILKMFPSTWYVBZJA", AminoAcidCompoundSet.aminoAcidCompoundSet); ProteinSequence proteinSequenceFromProxy = new ProteinSequence(sequenceStringProxyLoader); logger.info("Protein Sequence from Proxy: {}", proteinSequenceFromProxy.toString()); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/RNASequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/RNASequence.java index e44e884552..fb6f602d5e 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/RNASequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/RNASequence.java @@ -86,7 +86,7 @@ public RNASequence(ProxySequenceReader proxyLoader, * @return */ public SequenceView getReverseComplement() { - return new ComplementSequenceView(getInverse()); + return new ComplementSequenceView<>(getInverse()); } /** @@ -97,7 +97,7 @@ public SequenceView getReverseComplement() { */ @Override public SequenceView getInverse() { - return new ReversedSequenceView(this); + return new ReversedSequenceView<>(this); } /** @@ -105,7 +105,7 @@ public SequenceView getInverse() { * @return */ public SequenceView getComplement() { - return new ComplementSequenceView(this); + return new ComplementSequenceView<>(this); } /** diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/SequenceOptimizationHints.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/SequenceOptimizationHints.java index 0fab276028..6e7c131902 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/SequenceOptimizationHints.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/SequenceOptimizationHints.java @@ -68,13 +68,13 @@ public static void setSequenceCollection(SequenceCollection aSequenceColection) public enum SequenceUsage { - FULL_SEQUENCE_DATA, SUB_SEQUENCE_DATA, MINIMAL_SEQUENCE_DATA; - } + FULL_SEQUENCE_DATA, SUB_SEQUENCE_DATA, MINIMAL_SEQUENCE_DATA + } public enum SequenceCollection { - ALL_SEQUENCES, VARIABLE_SEQUENCES, MINIMINAL_SEQUENCES; - } + ALL_SEQUENCES, VARIABLE_SEQUENCES, MINIMINAL_SEQUENCES + } static private SequenceUsage sequenceUsage = SequenceUsage.FULL_SEQUENCE_DATA; static private SequenceCollection sequenceCollection = SequenceCollection.ALL_SEQUENCES; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/StartCodonSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/StartCodonSequence.java index eb3d37674a..f900ea3d2d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/StartCodonSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/StartCodonSequence.java @@ -29,7 +29,7 @@ * @author Scooter Willis */ public class StartCodonSequence extends DNASequence { -public DNASequence parentGeneSequence = null; +public final DNASequence parentGeneSequence; public StartCodonSequence(TranscriptSequence parentGeneSequence, int begin, int end){ diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/StopCodonSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/StopCodonSequence.java index 636d8548e0..990a1d09ab 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/StopCodonSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/StopCodonSequence.java @@ -30,7 +30,7 @@ */ public class StopCodonSequence extends DNASequence { -public DNASequence parentGeneSequence = null; +public final DNASequence parentGeneSequence; public StopCodonSequence(TranscriptSequence parentGeneSequence, int begin, int end){ diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/Strand.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/Strand.java index f4816adf7a..032983893d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/Strand.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/Strand.java @@ -33,7 +33,7 @@ public enum Strand { private final String stringRepresentation; private final int numericRepresentation; - private Strand(String stringRepresentation, int numericRepresentation) { + Strand(String stringRepresentation, int numericRepresentation) { this.stringRepresentation = stringRepresentation; this.numericRepresentation = numericRepresentation; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/TaxonomyID.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/TaxonomyID.java index 64784727bd..b83755bc98 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/TaxonomyID.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/TaxonomyID.java @@ -30,8 +30,8 @@ public class TaxonomyID { - private String id = null; - DataSource dataSource = DataSource.UNKNOWN; + private final String id; + final DataSource dataSource; public TaxonomyID(String id, DataSource dataSource) { this.id = id; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/TranscriptSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/TranscriptSequence.java index 29e6e60140..cf26496582 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/TranscriptSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/TranscriptSequence.java @@ -29,7 +29,6 @@ import org.slf4j.LoggerFactory; import java.util.ArrayList; -import java.util.Collections; import java.util.LinkedHashMap; /** @@ -41,11 +40,11 @@ public class TranscriptSequence extends DNASequence { private final static Logger logger = LoggerFactory.getLogger(TranscriptSequence.class); - private final ArrayList cdsSequenceList = new ArrayList(); - private final LinkedHashMap cdsSequenceHashMap = new LinkedHashMap(); + private final ArrayList cdsSequenceList = new ArrayList<>(); + private final LinkedHashMap cdsSequenceHashMap = new LinkedHashMap<>(); private StartCodonSequence startCodonSequence = null; private StopCodonSequence stopCodonSequence = null; - private GeneSequence parentGeneSequence = null; + private final GeneSequence parentGeneSequence; /** * @@ -113,7 +112,7 @@ public CDSSequence addCDS(AccessionID accession, int begin, int end, int phase) CDSSequence cdsSequence = new CDSSequence(this, begin, end, phase); //sense should be the same as parent cdsSequence.setAccession(accession); cdsSequenceList.add(cdsSequence); - Collections.sort(cdsSequenceList, new CDSComparator()); + cdsSequenceList.sort(new CDSComparator()); cdsSequenceHashMap.put(accession.getID(), cdsSequence); return cdsSequence; } @@ -137,16 +136,16 @@ public CDSSequence addCDS(AccessionID accession, int begin, int end, int phase) * @return */ public ArrayList getProteinCDSSequences() { - ArrayList proteinSequenceList = new ArrayList(); + ArrayList proteinSequenceList = new ArrayList<>(); for (int i = 0; i < cdsSequenceList.size(); i++) { CDSSequence cdsSequence = cdsSequenceList.get(i); String codingSequence = cdsSequence.getCodingSequence(); // logger.debug("CDS {} {} = {}", getStrand(), cdsSequence.getPhase(), codingSequence); if (this.getStrand() == Strand.NEGATIVE) { if (cdsSequence.phase == 1) { - codingSequence = codingSequence.substring(1, codingSequence.length()); + codingSequence = codingSequence.substring(1); } else if (cdsSequence.phase == 2) { - codingSequence = codingSequence.substring(2, codingSequence.length()); + codingSequence = codingSequence.substring(2); } if (i < cdsSequenceList.size() - 1) { CDSSequence nextCDSSequence = cdsSequenceList.get(i + 1); @@ -160,9 +159,9 @@ public ArrayList getProteinCDSSequences() { } } else { if (cdsSequence.phase == 1) { - codingSequence = codingSequence.substring(1, codingSequence.length()); + codingSequence = codingSequence.substring(1); } else if (cdsSequence.phase == 2) { - codingSequence = codingSequence.substring(2, codingSequence.length()); + codingSequence = codingSequence.substring(2); } if (i < cdsSequenceList.size() - 1) { CDSSequence nextCDSSequence = cdsSequenceList.get(i + 1); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AmbiguityDNACompoundSet.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AmbiguityDNACompoundSet.java index d803c642cd..bc8a7ecc03 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AmbiguityDNACompoundSet.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AmbiguityDNACompoundSet.java @@ -33,7 +33,7 @@ private static class InitaliseOnDemand { } public static AmbiguityDNACompoundSet getDNACompoundSet() { - return InitaliseOnDemand.INSTANCE; + return InitaliseOnDemand.INSTANCE; } public AmbiguityDNACompoundSet() { diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AminoAcidCompound.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AminoAcidCompound.java index b1906b81a3..6be60ed5aa 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AminoAcidCompound.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AminoAcidCompound.java @@ -23,75 +23,76 @@ package org.biojava.nbio.core.sequence.compound; -import java.io.Serializable; - import org.biojava.nbio.core.sequence.template.AbstractCompound; -import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.CompoundSet; +import java.io.Serializable; + /** * Used to describe an Amino Acid. + * * @author Richard Holland * @author Scooter Willis * @author Andy Yates */ public class AminoAcidCompound extends AbstractCompound implements Serializable { - /** - * - */ -private static final long serialVersionUID = -1955116496725902319L; -private final AminoAcidCompoundSet compoundSet; + /** + * + */ + private static final long serialVersionUID = -1955116496725902319L; + private final AminoAcidCompoundSet compoundSet; - public AminoAcidCompound(AminoAcidCompoundSet compoundSet, String shortName, - String longName, String description, Float molecularWeight) { - super(shortName); - setShortName(shortName); - setLongName(longName); - setDescription(description); - setMolecularWeight(molecularWeight); - this.compoundSet = compoundSet; - } + public AminoAcidCompound(AminoAcidCompoundSet compoundSet, String shortName, + String longName, String description, float molecularWeight) { + super(shortName); + setShortName(shortName); + setLongName(longName); + setDescription(description); + this.molecularWeight = molecularWeight; + this.compoundSet = compoundSet; + } - // TODO need to allow for modified name; that's not equality though is it? - @Override -public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj instanceof AminoAcidCompound)) { - return false; - } - AminoAcidCompound them = (AminoAcidCompound) obj; - if (toString().equals(them.toString())) { - return true; - } - return getLongName().equals(them.getLongName()); +// // TODO need to allow for modified name; that's not equality though is it? +// @Override +// public boolean equals(Object obj) { +// if (obj == null) { +// return false; +// } +// if (!(obj instanceof AminoAcidCompound)) { +// return false; +// } +// AminoAcidCompound them = (AminoAcidCompound) obj; +// if (toString().equals(them.toString())) { +// return true; +// } +// return getLongName().equals(them.getLongName()); +// +// } - } - @Override -public int hashCode() { - return toString().hashCode(); - } +// @Override +// public int hashCode() { +// return toString().hashCode(); +// } - @Override -public boolean equalsIgnoreCase(Compound compound) { - if (compound == null) { - return false; - } - if (!(compound instanceof AminoAcidCompound)) { - return false; - } - AminoAcidCompound them = (AminoAcidCompound) compound; - if (toString().equalsIgnoreCase(them.toString())) { - return true; - } - return getLongName().equalsIgnoreCase(them.getLongName()); - } +// @Override +// public boolean equalsIgnoreCase(Compound compound) { +// if (compound == null) { +// return false; +// } +// if (!(compound instanceof AminoAcidCompound)) { +// return false; +// } +// AminoAcidCompound them = (AminoAcidCompound) compound; +// if (toString().equalsIgnoreCase(them.toString())) { +// return true; +// } +// return getLongName().equalsIgnoreCase(them.getLongName()); +// } - public CompoundSet getCompoundSet() { - return compoundSet; - } + public CompoundSet getCompoundSet() { + return compoundSet; + } } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AminoAcidCompoundSet.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AminoAcidCompoundSet.java index 8252f27198..a59a9557b2 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AminoAcidCompoundSet.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/AminoAcidCompoundSet.java @@ -44,11 +44,11 @@ public class AminoAcidCompoundSet implements CompoundSet, Ser * */ private static final long serialVersionUID = 4000344194364133456L; - private final Map aminoAcidCompoundCache = new HashMap(); - private final Map aminoAcidCompoundCache3Letter = new HashMap(); + private final Map aminoAcidCompoundCache = new HashMap<>(); + private final Map aminoAcidCompoundCache3Letter = new HashMap<>(); private final Map> equivalentsCache = - new HashMap>(); + new HashMap<>(); public AminoAcidCompoundSet() { aminoAcidCompoundCache.put("A", new AminoAcidCompound(this, "A", "Ala", "Alanine", 71.0788f)); @@ -71,14 +71,14 @@ public AminoAcidCompoundSet() { aminoAcidCompoundCache.put("W", new AminoAcidCompound(this, "W", "Trp", "Tryptophan", 186.2132f)); aminoAcidCompoundCache.put("Y", new AminoAcidCompound(this, "Y", "Tyr", "Tyrosine", 163.1760f)); aminoAcidCompoundCache.put("V", new AminoAcidCompound(this, "V", "Val", "Valine", 99.1326f)); - aminoAcidCompoundCache.put("B", new AminoAcidCompound(this, "B", "Asx", "Asparagine or Aspartic acid", null)); - aminoAcidCompoundCache.put("Z", new AminoAcidCompound(this, "Z", "Glx", "Glutamine or Glutamic acid", null)); - aminoAcidCompoundCache.put("J", new AminoAcidCompound(this, "J", "Xle", "Leucine or Isoleucine", null)); - aminoAcidCompoundCache.put("X", new AminoAcidCompound(this, "X", "Xaa", "Unspecified", null)); - aminoAcidCompoundCache.put("-", new AminoAcidCompound(this, "-", "---", "Unspecified", null)); - aminoAcidCompoundCache.put(".", new AminoAcidCompound(this, ".", "...", "Unspecified", null)); - aminoAcidCompoundCache.put("_", new AminoAcidCompound(this, "_", "___", "Unspecified", null)); - aminoAcidCompoundCache.put("*", new AminoAcidCompound(this, "*", "***", "Stop", null)); + aminoAcidCompoundCache.put("B", new AminoAcidCompound(this, "B", "Asx", "Asparagine or Aspartic acid", Float.NaN)); + aminoAcidCompoundCache.put("Z", new AminoAcidCompound(this, "Z", "Glx", "Glutamine or Glutamic acid", Float.NaN)); + aminoAcidCompoundCache.put("J", new AminoAcidCompound(this, "J", "Xle", "Leucine or Isoleucine", Float.NaN)); + aminoAcidCompoundCache.put("X", new AminoAcidCompound(this, "X", "Xaa", "Unspecified", Float.NaN)); + aminoAcidCompoundCache.put("-", new AminoAcidCompound(this, "-", "---", "Unspecified", Float.NaN)); + aminoAcidCompoundCache.put(".", new AminoAcidCompound(this, ".", "...", "Unspecified", Float.NaN)); + aminoAcidCompoundCache.put("_", new AminoAcidCompound(this, "_", "___", "Unspecified", Float.NaN)); + aminoAcidCompoundCache.put("*", new AminoAcidCompound(this, "*", "***", "Stop", Float.NaN)); //Selenocysteine - this is encoded by UGA with the presence //of a SECIS element (SElenoCysteine Insertion Sequence) in the mRNA @@ -90,11 +90,8 @@ public AminoAcidCompoundSet() { //which then does the actual conversion to Pyl. aminoAcidCompoundCache.put("O", new AminoAcidCompound(this, "O", "Pyl", "Pyrrolysine", 255.3172f)); - for(String oneLtr : aminoAcidCompoundCache.keySet()) { - AminoAcidCompound aa = aminoAcidCompoundCache.get(oneLtr); - String threeLtr = aa.getLongName().toUpperCase(); - aminoAcidCompoundCache3Letter.put(threeLtr, aa); - } + for(AminoAcidCompound aa : aminoAcidCompoundCache.values()) + aminoAcidCompoundCache3Letter.put(aa.getLongName().toUpperCase(), aa); } @Override @@ -104,15 +101,13 @@ public String getStringForCompound(AminoAcidCompound compound) { @Override public AminoAcidCompound getCompoundForString(String string) { - if (string.length() == 0) { + int sl = string.length(); + if (sl == 0) return null; - } - if (string.length() == 3) { + if (sl == 3) return this.aminoAcidCompoundCache3Letter.get(string.toUpperCase()); - } - if (string.length() > this.getMaxSingleCompoundStringLength()) { + if (sl > this.getMaxSingleCompoundStringLength()) throw new IllegalArgumentException("String supplied ("+string+") is too long. Max is "+getMaxSingleCompoundStringLength()); - } return this.aminoAcidCompoundCache.get(string.toUpperCase()); } @@ -127,11 +122,7 @@ public boolean isCompoundStringLengthEqual() { return true; } - private final static AminoAcidCompoundSet aminoAcidCompoundSet = new AminoAcidCompoundSet(); - - public static AminoAcidCompoundSet getAminoAcidCompoundSet() { - return aminoAcidCompoundSet; - } + public final static AminoAcidCompoundSet aminoAcidCompoundSet = new AminoAcidCompoundSet(); @Override public boolean compoundsEquivalent(AminoAcidCompound compoundOne, AminoAcidCompound compoundTwo) { @@ -154,7 +145,7 @@ public Set getEquivalentCompounds(AminoAcidCompound compound) addAmbiguousEquivalents("I", "L", "J"); // ambiguous gaps AminoAcidCompound gap1, gap2, gap3; - Set gaps = new HashSet(); + Set gaps = new HashSet<>(3); gaps.add(gap1 = aminoAcidCompoundCache.get("-")); gaps.add(gap2 = aminoAcidCompoundCache.get(".")); gaps.add(gap3 = aminoAcidCompoundCache.get("_")); @@ -162,7 +153,7 @@ public Set getEquivalentCompounds(AminoAcidCompound compound) equivalentsCache.put(gap2, gaps); equivalentsCache.put(gap3, gaps); // X is never equivalent, even to itself - equivalentsCache.put(aminoAcidCompoundCache.get("X"), new HashSet()); + equivalentsCache.put(aminoAcidCompoundCache.get("X"), Collections.EMPTY_SET); } return equivalentsCache.get(compound); } @@ -172,18 +163,18 @@ private void addAmbiguousEquivalents(String one, String two, String either) { Set equivalents; AminoAcidCompound cOne, cTwo, cEither; - equivalents = new HashSet(); + equivalents = new HashSet<>(3); equivalents.add(cOne = aminoAcidCompoundCache.get(one)); equivalents.add(cTwo = aminoAcidCompoundCache.get(two)); equivalents.add(cEither = aminoAcidCompoundCache.get(either)); equivalentsCache.put(cEither, equivalents); - equivalents = new HashSet(); + equivalents = new HashSet<>(2); equivalents.add(cOne); equivalents.add(cEither); equivalentsCache.put(cOne, equivalents); - equivalents = new HashSet(); + equivalents = new HashSet<>(2); equivalents.add(cTwo); equivalents.add(cEither); equivalentsCache.put(cTwo, equivalents); @@ -197,16 +188,19 @@ public boolean hasCompound(AminoAcidCompound compound) { @Override public boolean isValidSequence(Sequence sequence) { for (AminoAcidCompound compound: sequence) { - if (!hasCompound(compound)) { + if (!hasCompound(compound)) return false; - } } return true; } @Override - public List getAllCompounds() { - return new ArrayList(aminoAcidCompoundCache.values()); + public Collection getAllCompounds() { + return + //new ArrayList<>( + Collections.unmodifiableCollection( + aminoAcidCompoundCache.values() + ); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/CodonCompound.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/CodonCompound.java index d78b307b42..35180fa4ef 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/CodonCompound.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/CodonCompound.java @@ -1,139 +1,138 @@ -/* - * BioJava development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public Licence. This should - * be distributed with the code. If you do not have a copy, - * see: - * - * http://www.gnu.org/copyleft/lesser.html - * - * Copyright for this code is held jointly by the individual - * authors. These should be listed in @author doc comments. - * - * For more information on the BioJava project and its aims, - * or to join the biojava-l mailing list, visit the home page - * at: - * - * http://www.biojava.org/ - * - * Created on 01-21-2010 - */ -package org.biojava.nbio.core.sequence.compound; - -import org.biojava.nbio.core.sequence.template.AbstractCompound; -import org.biojava.nbio.core.sequence.template.Compound; -/** - * Define a codon - * @author Andy Yates - */ -public class CodonCompound extends AbstractCompound { - - private final NucleotideCompound one; - private final NucleotideCompound two; - private final NucleotideCompound three; - private final boolean start; - - public CodonCompound(NucleotideCompound one, NucleotideCompound two, - NucleotideCompound three, boolean start) { - super(one.toString()+two.toString()+three.toString()); - this.one = one; - this.two = two; - this.three = three; - this.start = start; - } - - @Override -public boolean equalsIgnoreCase(Compound compound) { - if (compound == null) { - return false; - } - if (!(compound instanceof CodonCompound)) { - return false; - } - CodonCompound them = (CodonCompound) compound; - return toString().equalsIgnoreCase(them.toString()); - } - - @Override -public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj instanceof CodonCompound)) { - return false; - } - CodonCompound them = (CodonCompound)obj; - return toString().equals(them.toString()); - } - - @Override -public int hashCode() { - return toString().hashCode(); - } - - public NucleotideCompound getOne() { - return one; - } - - public NucleotideCompound getTwo() { - return two; - } - - public NucleotideCompound getThree() { - return three; - } - - public boolean isStart() { - return start; - } - - @Override -public String getDescription() { - // TODO Auto-generated method stub - return null; - } - - @Override -public String getLongName() { - // TODO Auto-generated method stub - return null; - } - - @Override -public Float getMolecularWeight() { - // TODO Auto-generated method stub - return null; - } - - @Override -public String getShortName() { - // TODO Auto-generated method stub - return null; - } - - @Override -public void setDescription(String description) { - // TODO Auto-generated method stub - - } - - @Override -public void setLongName(String longName) { - // TODO Auto-generated method stub - - } - - @Override -public void setMolecularWeight(Float molecularWeight) { - // TODO Auto-generated method stub - - } - - @Override -public void setShortName(String shortName) { - // TODO Auto-generated method stub - - } - -} +///* +// * BioJava development code +// * +// * This code may be freely distributed and modified under the +// * terms of the GNU Lesser General Public Licence. This should +// * be distributed with the code. If you do not have a copy, +// * see: +// * +// * http://www.gnu.org/copyleft/lesser.html +// * +// * Copyright for this code is held jointly by the individual +// * authors. These should be listed in @author doc comments. +// * +// * For more information on the BioJava project and its aims, +// * or to join the biojava-l mailing list, visit the home page +// * at: +// * +// * http://www.biojava.org/ +// * +// * Created on 01-21-2010 +// */ +//package org.biojava.nbio.core.sequence.compound; +// +//import org.biojava.nbio.core.sequence.template.AbstractCompound; +//import org.biojava.nbio.core.sequence.template.Compound; +///** +// * Define a codon +// * @author Andy Yates +// */ +//public class CodonCompound extends AbstractCompound { +// +// private final NucleotideCompound one; +// private final NucleotideCompound two; +// private final NucleotideCompound three; +// private final boolean start; +// +// public CodonCompound(NucleotideCompound one, NucleotideCompound two, +// NucleotideCompound three, boolean start) { +// super(one.toString()+two.toString()+three.toString()); +// this.one = one; +// this.two = two; +// this.three = three; +// this.start = start; +// } +// +// @Override +//public boolean equalsIgnoreCase(Compound compound) { +// if (compound == null) { +// return false; +// } +// if (!(compound instanceof CodonCompound)) { +// return false; +// } +// CodonCompound them = (CodonCompound) compound; +// return toString().equalsIgnoreCase(them.toString()); +// } +// +// @Override +//public boolean equals(Object obj) { +// if (obj == null) { +// return false; +// } +// if (!(obj instanceof CodonCompound)) { +// return false; +// } +// CodonCompound them = (CodonCompound)obj; +// return toString().equals(them.toString()); +// } +// +// @Override +//public int hashCode() { +// return toString().hashCode(); +// } +// +// public NucleotideCompound getOne() { +// return one; +// } +// +// public NucleotideCompound getTwo() { +// return two; +// } +// +// public NucleotideCompound getThree() { +// return three; +// } +// +// public boolean isStart() { +// return start; +// } +// +// @Override +//public String getDescription() { +// // TODO Auto-generated method stub +// return null; +// } +// +// @Override +//public String getLongName() { +// // TODO Auto-generated method stub +// return null; +// } +// +// @Override +//public Float getMolecularWeight() { +// // TODO Auto-generated method stub +// return null; +// } +// +// @Override +//public String getShortName() { +// // TODO Auto-generated method stub +// return null; +// } +// +// @Override +//public void setDescription(String description) { +// // TODO Auto-generated method stub +// +// } +// +// @Override +//public void setLongName(String longName) { +// // TODO Auto-generated method stub +// +// } +// +// public void setMolecularWeight(Float molecularWeight) { +// // TODO Auto-generated method stub +// +// } +// +// @Override +//public void setShortName(String shortName) { +// // TODO Auto-generated method stub +// +// } +// +//} diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/NucleotideCompound.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/NucleotideCompound.java index 786c79f812..48d6e31a59 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/NucleotideCompound.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/compound/NucleotideCompound.java @@ -27,9 +27,9 @@ import org.biojava.nbio.core.sequence.template.AbstractCompound; import org.biojava.nbio.core.sequence.template.ComplementCompound; -import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.CompoundSet; +import java.util.Collections; import java.util.HashSet; import java.util.Set; @@ -51,14 +51,14 @@ public NucleotideCompound(String base, CompoundSet compoundS super(base); this.compoundSet = compoundSet; this.complementStr = complementStr; - this.constituents = unmodifiableSet(new HashSet(asList(this))); + this.constituents = unmodifiableSet(new HashSet<>(Collections.singletonList(this))); } public NucleotideCompound(String base, CompoundSet compoundSet, String complementStr, NucleotideCompound[] constituents) { super(base); this.compoundSet = compoundSet; this.complementStr = complementStr; - this.constituents = unmodifiableSet(new HashSet(asList(constituents))); + this.constituents = unmodifiableSet(new HashSet<>(asList(constituents))); } @Override @@ -70,35 +70,35 @@ public String getShortName() { public ComplementCompound getComplement() { return compoundSet.getCompoundForString(complementStr); } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj instanceof NucleotideCompound)) { - return false; - } - NucleotideCompound them = (NucleotideCompound) obj; - return toString().equals(them.toString()); - } - - @Override - public int hashCode() { - return toString().hashCode(); - } - - @Override - public boolean equalsIgnoreCase(Compound compound) { - if (compound == null) { - return false; - } - if (!(compound instanceof NucleotideCompound)) { - return false; - } - NucleotideCompound them = (NucleotideCompound) compound; - return toString().equalsIgnoreCase(them.toString()); - } +// +// @Override +// public boolean equals(Object obj) { +// if (obj == null) { +// return false; +// } +// if (!(obj instanceof NucleotideCompound)) { +// return false; +// } +// NucleotideCompound them = (NucleotideCompound) obj; +// return toString().equals(them.toString()); +// } +// +// @Override +// public int hashCode() { +// return toString().hashCode(); +// } +// +// @Override +// public boolean equalsIgnoreCase(Compound compound) { +// if (compound == null) { +// return false; +// } +// if (!(compound instanceof NucleotideCompound)) { +// return false; +// } +// NucleotideCompound them = (NucleotideCompound) compound; +// return toString().equalsIgnoreCase(them.toString()); +// } public Set getConstituents() { return constituents; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/edits/Edit.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/edits/Edit.java index 19923effed..2279df647e 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/edits/Edit.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/edits/Edit.java @@ -58,7 +58,7 @@ public interface Edit { * with a target Sequence. These ends can be of 0 length but conceptionally * they can still exist. */ - public static abstract class AbstractEdit implements Edit { + abstract class AbstractEdit implements Edit { private final static Logger logger = LoggerFactory.getLogger(AbstractEdit.class); @@ -78,15 +78,15 @@ public static abstract class AbstractEdit implements Edit @Override public Sequence edit(Sequence editingSequence) { Sequence targetSequence = getTargetSequence(editingSequence); - List> sequences = new ArrayList>(); + List> sequences = new ArrayList<>(); sequences.add(getFivePrime(editingSequence)); sequences.add(targetSequence); sequences.add(getThreePrime(editingSequence)); - return new JoiningSequenceReader(sequences); + return new JoiningSequenceReader<>(sequences); } - private int start = -1; + private final int start; private int end = -1; private String stringSequence; private Sequence sequence; @@ -119,8 +119,8 @@ protected void setSequence(Sequence sequence) { public Sequence getTargetSequence(Sequence editingSequence) { if (sequence == null && stringSequence != null) { try { - sequence = new BasicSequence( - stringSequence, editingSequence.getCompoundSet()); + sequence = new BasicSequence<>( + stringSequence, editingSequence.getCompoundSet()); } catch (CompoundNotFoundException e) { // TODO is there a better way to handle this exception? logger.error("Problem setting sequence, some unrecognised compounds: {}", e.getMessage()); @@ -136,7 +136,7 @@ public Sequence getTargetSequence(Sequence editingSequence) { protected Sequence getEmptySequence(Sequence editingSequence) { Sequence s = null; try { - s = new BasicSequence("", editingSequence.getCompoundSet()); + s = new BasicSequence<>("", editingSequence.getCompoundSet()); } catch (CompoundNotFoundException e) { // should not happen logger.error("Could not construct empty sequence. {}. This is most likely a bug.", e.getMessage()); @@ -156,7 +156,7 @@ public int getEnd() { /** * Implementation which allows for the deletion of bases from a Sequence */ - public static class Delete extends AbstractEdit { + class Delete extends AbstractEdit { public Delete(int position) { this(position, position); @@ -209,7 +209,7 @@ protected Sequence getThreePrime(Sequence editingSequence) { * The code will raise exceptions if you attempt a single base edit * with an insertion. */ - public static class Insert extends AbstractEdit { + class Insert extends AbstractEdit { private final boolean singlePosition; @@ -285,7 +285,7 @@ protected Sequence getThreePrime(Sequence editingSequence) { * presence of a CompoundSet to parse a String (if given) which means * the eventual length of a Sequence is a lazy operation. */ - public static class Substitute extends AbstractEdit { + class Substitute extends AbstractEdit { public Substitute(String sequence, int position) { super(position); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/AbstractFeature.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/AbstractFeature.java index d601c573b0..41f94eb72f 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/AbstractFeature.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/AbstractFeature.java @@ -26,11 +26,7 @@ import org.biojava.nbio.core.sequence.template.AbstractSequence; import org.biojava.nbio.core.sequence.template.Compound; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; /** * A feature is currently any descriptive item that can be associated with a sequence position(s) @@ -40,15 +36,15 @@ */ public abstract class AbstractFeature, C extends Compound> implements FeatureInterface { - List> childrenFeatures = new ArrayList>(); + List> childrenFeatures = new ArrayList<>(); FeatureInterface parentFeature; AbstractLocation sequenceLocation; - String type = ""; - String source = ""; + String type; + String source; private String description = ""; private String shortDescription = ""; private Object userObject = null; - private Map> Qualifiers = new HashMap>(); + private Map> Qualifiers = new HashMap<>(); /** * A feature has a type and a source @@ -196,28 +192,19 @@ public void setShortDescription(String shortDescription) { * of overlapping features so they are delivered in a proper order. */ - public static final Comparator> LOCATION_LENGTH = new Comparator>() { - - @Override - public int compare(FeatureInterface e1, FeatureInterface e2) { - double v1 = e1.getLocations().getStart().getPosition(); - double v2 = e2.getLocations().getStart().getPosition(); - if (v1 < v2) { - return -1; - } else if (v1 > v2) { - return 1; - } else { - double end1 = e1.getLocations().getEnd().getPosition(); - double end2 = e2.getLocations().getEnd().getPosition(); - if(end1 > end2) - return -1; - else if(end1 < end2) - return 1; - else - return 0; - } - + public static final Comparator> LOCATION_LENGTH = (e1, e2) -> { + double v1 = e1.getLocations().getStart().getPosition(); + double v2 = e2.getLocations().getStart().getPosition(); + if (v1 < v2) { + return -1; + } else if (v1 > v2) { + return 1; + } else { + double end1 = e1.getLocations().getEnd().getPosition(); + double end2 = e2.getLocations().getEnd().getPosition(); + return Double.compare(end2, end1); } + }; /** @@ -225,33 +212,17 @@ else if(end1 < end2) * */ - static public final Comparator> LENGTH = new Comparator>() { - - @Override - public int compare(FeatureInterface e1, FeatureInterface e2) { - double v1 = Math.abs(e1.getLocations().getEnd().getPosition()- e1.getLocations().getStart().getPosition()); - double v2 = Math.abs(e2.getLocations().getEnd().getPosition() - e2.getLocations().getStart().getPosition()); - if (v1 < v2) { - return -1; - } else if (v1 > v2) { - return 1; - } else { - return 0; - } + static public final Comparator> LENGTH = (e1, e2) -> { + double v1 = Math.abs(e1.getLocations().getEnd().getPosition()- e1.getLocations().getStart().getPosition()); + double v2 = Math.abs(e2.getLocations().getEnd().getPosition() - e2.getLocations().getStart().getPosition()); + return Double.compare(v1, v2); - } }; /** * Sort features by type */ - public static final Comparator> TYPE = new Comparator>() { - - @Override - public int compare(FeatureInterface o1, FeatureInterface o2) { - return o1.getType().compareTo(o2.getType()); - } - }; + public static final Comparator> TYPE = Comparator.comparing(FeatureInterface::getType); /** * @return the userObject @@ -292,7 +263,7 @@ public void addQualifier(String key, Qualifier qualifier) { vals.add(qualifier); Qualifiers.put(key, vals); } else { - List vals = new ArrayList(); + List vals = new ArrayList<>(); vals.add(qualifier); Qualifiers.put(key, vals); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/DBReferenceInfo.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/DBReferenceInfo.java index ce8793c561..28b14712ca 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/DBReferenceInfo.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/DBReferenceInfo.java @@ -37,9 +37,9 @@ * @author Paolo Pavan */ public class DBReferenceInfo extends Qualifier { - private LinkedHashMap properties = new LinkedHashMap(); - private String database = ""; - private String id = ""; + private LinkedHashMap properties = new LinkedHashMap<>(); + private String database; + private String id; /** * The source database and id diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/DatabaseReferenceInterface.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/DatabaseReferenceInterface.java index 0cb3ea5d8c..ceb6e34509 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/DatabaseReferenceInterface.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/DatabaseReferenceInterface.java @@ -32,5 +32,5 @@ */ public interface DatabaseReferenceInterface { - public LinkedHashMap> getDatabaseReferences(); + LinkedHashMap> getDatabaseReferences(); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeatureDbReferenceInfo.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeatureDbReferenceInfo.java index c270cc74e7..3b49341d22 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeatureDbReferenceInfo.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeatureDbReferenceInfo.java @@ -46,11 +46,11 @@ public class FeatureDbReferenceInfo, C extends Com private AbstractLocation location; private FeatureInterface parentFeature; - private List> childrenFeatures = new ArrayList>(); + private List> childrenFeatures = new ArrayList<>(); private String description = ""; private String shortDescription = ""; private Object userObject; - private Map> qualifiers = new HashMap>(); + private Map> qualifiers = new HashMap<>(); public FeatureDbReferenceInfo(String database, String id) { @@ -150,7 +150,7 @@ public void setQualifiers(Map> qualifiers) { @Override public void addQualifier(String key, Qualifier qualifier) { if (qualifiers == null) { - qualifiers = new HashMap>(); + qualifiers = new HashMap<>(); } // Check for key. Update list of values if (qualifiers.containsKey(key)){ @@ -158,7 +158,7 @@ public void addQualifier(String key, Qualifier qualifier) { vals.add(qualifier); qualifiers.put(key, vals); } else { - List vals = new ArrayList(); + List vals = new ArrayList<>(); vals.add(qualifier); qualifiers.put(key, vals); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeatureInterface.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeatureInterface.java index 47564bcefa..0c1d26e478 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeatureInterface.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeatureInterface.java @@ -21,13 +21,13 @@ package org.biojava.nbio.core.sequence.features; -import java.util.List; -import java.util.Map; - import org.biojava.nbio.core.sequence.location.template.AbstractLocation; import org.biojava.nbio.core.sequence.template.AbstractSequence; import org.biojava.nbio.core.sequence.template.Compound; +import java.util.List; +import java.util.Map; + /** * Interface class to handle describing arbitrary features. A feature can be found at multiple locations in a sequence such as * the surface of a protein where different sequence positions make up that feature. Ligand binding pocket is another example. @@ -47,21 +47,21 @@ public interface FeatureInterface, C extends Compo * @return */ - public String getShortDescription(); + String getShortDescription(); /** * Set the short description that can be used to describe the feature * @param shortDescription */ - public void setShortDescription(String shortDescription); + void setShortDescription(String shortDescription); /** * Get the description that can be used to describe the feature * @return */ - public String getDescription(); + String getDescription(); /** @@ -69,7 +69,7 @@ public interface FeatureInterface, C extends Compo * @return */ - public void setDescription(String description); + void setDescription(String description); /** * The location(s) of this feature where the location should contain a reference to parent and sequence etc. @@ -80,7 +80,7 @@ public interface FeatureInterface, C extends Compo * * @return a Location anchoring this feature */ - public AbstractLocation getLocations(); + AbstractLocation getLocations(); /** * The new location for this feature. @@ -93,14 +93,14 @@ public interface FeatureInterface, C extends Compo * @param loc the new Location for this feature * */ - public void setLocation(AbstractLocation loc); + void setLocation(AbstractLocation loc); /** * The type of the feature. * * @return the type of this sequence */ - public String getType(); + String getType(); /** * Change the type of this feature. @@ -108,7 +108,7 @@ public interface FeatureInterface, C extends Compo * @param type new type String * */ - public void setType(String type); + void setType(String type); /** @@ -116,7 +116,7 @@ public interface FeatureInterface, C extends Compo * * @return the source, or generator */ - public String getSource(); + String getSource(); /** * Change the source of the FeatureInterface. @@ -124,46 +124,46 @@ public interface FeatureInterface, C extends Compo * @param source the new source String * */ - public void setSource(String source); + void setSource(String source); /** * Set the parent feature * @param feature */ - public void setParentFeature(FeatureInterface feature); + void setParentFeature(FeatureInterface feature); /** * Get the parent feature * @return */ - public FeatureInterface getParentFeature(); + FeatureInterface getParentFeature(); /** * Get the features contained by this feature * @return */ - public List> getChildrenFeatures(); + List> getChildrenFeatures(); /** * Set the children features * @param features */ - public void setChildrenFeatures(List> features); + void setChildrenFeatures(List> features); /** * @return the userObject */ - public Object getUserObject(); + Object getUserObject(); /** * @param userObject the userObject to set */ - public void setUserObject(Object userObject); + void setUserObject(Object userObject); /** @@ -171,19 +171,19 @@ public interface FeatureInterface, C extends Compo * @return */ - public Map> getQualifiers(); + Map> getQualifiers(); /** * Set the qualifiers * @param qualifiers */ - public void setQualifiers(Map> qualifiers); + void setQualifiers(Map> qualifiers); /** * Add a qualifier * @param qualifier */ - public void addQualifier(String key, Qualifier qualifier); + void addQualifier(String key, Qualifier qualifier); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeatureRetriever.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeatureRetriever.java index bd2d48afee..fd47c00a44 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeatureRetriever.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeatureRetriever.java @@ -23,12 +23,13 @@ package org.biojava.nbio.core.sequence.features; import java.util.ArrayList; -import java.util.HashMap; +import java.util.Map; + /** * If a SequenceProxyReader implements this interface then that external source * has a list features * @author @author Paolo Pavan */ public interface FeatureRetriever { - HashMap> getFeatures(); + Map> getFeatures(); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeaturesKeyWordInterface.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeaturesKeyWordInterface.java index 9674d1abee..e8b62432b1 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeaturesKeyWordInterface.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/FeaturesKeyWordInterface.java @@ -22,7 +22,7 @@ package org.biojava.nbio.core.sequence.features; -import java.util.ArrayList; +import java.util.List; /** * Models the keywords that are annotated for a protein sequence at Uniprot. If a ProxySequenceReader @@ -36,5 +36,5 @@ public interface FeaturesKeyWordInterface { * * @return */ - public ArrayList getKeyWords() ; + List getKeyWords() ; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/QualityFeature.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/QualityFeature.java index 7eec33a62a..0e7da9a97b 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/QualityFeature.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/QualityFeature.java @@ -37,7 +37,7 @@ */ public class QualityFeature, C extends Compound> extends AbstractFeature { - private List qualities = new ArrayList(); + private List qualities = new ArrayList<>(); /** * @param type diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/QuantityFeature.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/QuantityFeature.java index bce00e2729..524bdfdaa3 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/QuantityFeature.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/features/QuantityFeature.java @@ -35,7 +35,7 @@ */ public class QuantityFeature, C extends Compound> extends AbstractFeature { - private List quantities = new ArrayList(); + private List quantities = new ArrayList<>(); /** * diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/ABITrace.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/ABITrace.java index d2cebd7cd1..8b7fdc65a8 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/ABITrace.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/ABITrace.java @@ -22,23 +22,15 @@ package org.biojava.nbio.core.sequence.io; -import java.io.IOException; -import java.io.File; -import java.io.BufferedInputStream; -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; -import java.io.DataInputStream; -import java.io.ByteArrayInputStream; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.image.BufferedImage; -import java.net.URL; -import java.io.InputStream; - +import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.compound.ABITracerCompoundSet; import org.biojava.nbio.core.sequence.compound.NucleotideCompound; import org.biojava.nbio.core.sequence.template.AbstractSequence; -import org.biojava.nbio.core.exceptions.CompoundNotFoundException; + +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.*; +import java.net.URL; /** * Title: ABITrace

    @@ -55,7 +47,12 @@ public class ABITrace { //the next three lines are the important persistent data private String sequence; - private int A[], G[], C[], T[], baseCalls[], qCalls[]; + private int[] A; + private int[] G; + private int[] C; + private int[] T; + private int[] baseCalls; + private int[] qCalls; private int traceLength, seqLength; //This is the actual file data. @@ -110,7 +107,7 @@ public ABITrace( URL ABIFile ) throws IOException * @throws IOException if there is a problem reading from the BufferedInputStream */ private void ABITraceInit(BufferedInputStream bis) throws IOException{ - byte[] bytes = null; + byte[] bytes; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int b; while ((b = bis.read()) >= 0) @@ -191,16 +188,17 @@ public AbstractSequence getSequence() throws CompoundNotFoun * @throws CompoundNotFoundException if the base is not valid */ public int[] getTrace (String base) throws CompoundNotFoundException { - if (base.equals("A")) { - return A; - } else if (base.equals("C")) { - return C; - } else if (base.equals("G")) { - return G; - } else if (base.equals("T")) { - return T; - } else { - throw new CompoundNotFoundException("Don't know base: " + base); + switch (base) { + case "A": + return A; + case "C": + return C; + case "G": + return G; + case "T": + return T; + default: + throw new CompoundNotFoundException("Don't know base: " + base); } } @@ -320,9 +318,9 @@ private int transmute(int ya, int height, double scale) { * @return - scaling factor */ private double calculateScale(int height) { - double newScale = 0.0; - double max = (double) getMaximum(); - double ht = (double) height; + double newScale; + double max = getMaximum(); + double ht = height; newScale = ((ht - 50.0)) / max; return newScale; } @@ -366,9 +364,9 @@ private void initData(byte[] fileData) { * traces into their arrays. */ private void setTraces() { - int pointers[] = new int[4]; //alphabetical, 0=A, 1=C, 2=G, 3=T - int datas[] = new int[4]; - char order[] = new char[4]; + int[] pointers = new int[4]; //alphabetical, 0=A, 1=C, 2=G, 3=T + int[] datas = new int[4]; + char[] order = new char[4]; datas[0] = DATA9; datas[1] = DATA10; @@ -413,10 +411,10 @@ private void setTraces() { DataInputStream dis = new DataInputStream(new ByteArrayInputStream(qq)); for (int x = 0; x <= traceLength - 1; x++) { try { - if (i == 0) A[x] = (int) dis.readShort(); - if (i == 1) C[x] = (int) dis.readShort(); - if (i == 2) G[x] = (int) dis.readShort(); - if (i == 3) T[x] = (int) dis.readShort(); + if (i == 0) A[x] = dis.readShort(); + if (i == 1) C[x] = dis.readShort(); + if (i == 2) G[x] = dis.readShort(); + if (i == 3) T[x] = dis.readShort(); } catch (IOException e)//This shouldn't happen. If it does something must be seriously wrong. { throw new IllegalStateException("Unexpected IOException encountered while manipulating internal streams."); @@ -430,7 +428,7 @@ private void setTraces() { * Fetch the sequence from the trace data. */ private void setSeq() { - char tempseq[] = new char[seqLength]; + char[] tempseq = new char[seqLength]; for (int x = 0; x <= seqLength - 1; ++x) { tempseq[x] = (char) traceData[PBAS2 + x]; } @@ -447,7 +445,7 @@ private void setQcalls() { DataInputStream dis = new DataInputStream(new ByteArrayInputStream(qq)); for (int i = 0; i <= seqLength - 1; ++i) { try { - qCalls[i] = (int) dis.readByte(); + qCalls[i] = dis.readByte(); } catch (IOException e)//This shouldn't happen. If it does something must be seriously wrong. { throw new IllegalStateException("Unexpected IOException encountered while manipulating internal streams."); @@ -465,7 +463,7 @@ private void setBasecalls() { DataInputStream dis = new DataInputStream(new ByteArrayInputStream(qq)); for (int i = 0; i <= seqLength - 1; ++i) { try { - baseCalls[i] = (int) dis.readShort(); + baseCalls[i] = dis.readShort(); } catch (IOException e)//This shouldn't happen. If it does something must be seriously wrong. { throw new IllegalStateException("Unexpected IOException encountered while manipulating internal streams."); @@ -540,7 +538,7 @@ private void setIndex() { * @return - int beginning at pointer in trace array */ private int getIntAt(int pointer) { - int out = 0; + int out; byte[] temp = new byte[4]; getSubArray(temp, pointer); try { @@ -560,9 +558,7 @@ private int getIntAt(int pointer) { * @param traceDataOffset - starting point */ private void getSubArray(byte[] b, int traceDataOffset) { - for (int x = 0; x <= b.length - 1; x++) { - b[x] = traceData[traceDataOffset + x]; - } + System.arraycopy(traceData, traceDataOffset + 0, b, 0, b.length - 1 + 1); } /** @@ -573,7 +569,7 @@ private void getSubArray(byte[] b, int traceDataOffset) { * @return - if format of ABI file is correct */ private boolean isABI() { - char ABI[] = new char[4]; + char[] ABI = new char[4]; for (int i = 0; i <= 2; i++) { ABI[i] = (char) traceData[i]; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/BufferedReaderBytesRead.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/BufferedReaderBytesRead.java index e8b56ba29b..fc5a9b0bad 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/BufferedReaderBytesRead.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/BufferedReaderBytesRead.java @@ -76,8 +76,12 @@ public class BufferedReaderBytesRead extends Reader { private boolean skipLF = false; /** The skipLF flag when the mark was set */ private boolean markedSkipLF = false; - private static int defaultCharBufferSize = 8192; - private static int defaultExpectedLineLength = 80; + + private static final int defaultCharBufferSize = + 16 * 1024; + //8192; + + private static final int defaultExpectedLineLength = 80; long bytesRead = 0; /** @@ -146,16 +150,14 @@ private void fill() throws IOException { if (readAheadLimit <= cb.length) { /* Shuffle in the current buffer */ System.arraycopy(cb, markedChar, cb, 0, delta); - markedChar = 0; - dst = delta; } else { /* Reallocate buffer to accommodate read-ahead limit */ char[] ncb = new char[readAheadLimit]; System.arraycopy(cb, markedChar, ncb, 0, delta); cb = ncb; - markedChar = 0; - dst = delta; } + markedChar = 0; + dst = delta; nextChar = nChars = delta; } } @@ -415,7 +417,7 @@ private String readLine(boolean ignoreLF) throws IOException { public String readLine() throws IOException { String line = readLine(false); if (line != null) { - bytesRead = bytesRead + line.length(); + bytesRead += line.length(); } return line; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/CasePreservingProteinSequenceCreator.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/CasePreservingProteinSequenceCreator.java index 54865cb132..13a8ce7f1a 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/CasePreservingProteinSequenceCreator.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/CasePreservingProteinSequenceCreator.java @@ -92,7 +92,7 @@ public AbstractSequence getSequence(String sequence, public AbstractSequence getSequence( List list) { AbstractSequence seq =super.getSequence(list); - Collection strCase = new ArrayList(seq.getLength()); + Collection strCase = new ArrayList<>(seq.getLength()); for(int i=0;i getSequence( * This list contains only Booleans. */ private static List getStringCase(String str) { - List types = new ArrayList(str.length()); + List types = new ArrayList<>(str.length()); for(int i=0;i getStringCase(String str) { } public static void main(String[] args) throws Exception { - CasePreservingProteinSequenceCreator creator = new CasePreservingProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet()); + CasePreservingProteinSequenceCreator creator = new CasePreservingProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet); AbstractSequence seq = creator.getSequence("aaAA",0); logger.info("Sequence: {}", seq.getSequenceAsString()); //"AAAA" logger.info("User Collection: {}", seq.getUserCollection()); //"[false, false, true, true]" diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/DNASequenceCreator.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/DNASequenceCreator.java index 48eab7cb23..78a5dd4832 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/DNASequenceCreator.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/DNASequenceCreator.java @@ -83,7 +83,7 @@ public AbstractSequence getSequence( @Override public AbstractSequence getSequence( List list) { - ArrayListProxySequenceReader store = new ArrayListProxySequenceReader(); + ArrayListProxySequenceReader store = new ArrayListProxySequenceReader<>(); store.setCompoundSet(compoundSet); store.setContents(list); return new DNASequence(store); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaGeneWriter.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaGeneWriter.java index 741bc2c26f..c7351a526e 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaGeneWriter.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaGeneWriter.java @@ -42,11 +42,11 @@ public class FastaGeneWriter { private final static Logger logger = LoggerFactory.getLogger(FastaGeneWriter.class); - boolean showExonUppercase = false; - OutputStream os; - Collection sequences; - FastaHeaderFormatInterface headerFormat; - private int lineLength = 60; + final boolean showExonUppercase; + final OutputStream os; + final Collection sequences; + final FastaHeaderFormatInterface headerFormat; + private int lineLength; /** * * @param os @@ -86,7 +86,7 @@ public void process() throws Exception { os.write(lineSep); int compoundCount = 0; - String seq = ""; + String seq; //GeneSequence currently has a strand attribute to indicate direction seq = sequence.getSequence5PrimeTo3Prime().getSequenceAsString(); @@ -95,8 +95,8 @@ public void process() throws Exception { int geneBioBegin = sequence.getBioBegin(); int geneBioEnd = sequence.getBioEnd(); for (ExonSequence exonSequence : sequence.getExonSequences()) { - int featureBioBegin = 0; - int featureBioEnd = 0; + int featureBioBegin; + int featureBioEnd; if (sequence.getStrand() != Strand.NEGATIVE) { featureBioBegin = exonSequence.getBioBegin() - geneBioBegin; featureBioEnd = exonSequence.getBioEnd() - geneBioBegin; @@ -156,7 +156,7 @@ public void setLineLength(int lineLength) { public static void main(String[] args) { try { - ArrayList sequences = new ArrayList(); + ArrayList sequences = new ArrayList<>(); ChromosomeSequence seq1 = new ChromosomeSequence("ATATATATATATATATATATATATATATATATACGCGCGCGCGCGCGCGCGCGCGCGCGCGCGCATATATATATATATATATATATACGCGCGCGCGCGCGCGCATATATATATATATATATATATATATATATATACGCGCGCGCGCGCGCGCGCGCGCGCGCGCGCATATATATATATATATATATATACGCGCGCGCGCGCGCGC"); GeneSequence gene1 = seq1.addGene(new AccessionID("gene1"), 1, 20, Strand.POSITIVE); @@ -170,7 +170,7 @@ public static void main(String[] args) { sequences.add(gene2); - FastaGeneWriter fastaWriter = new FastaGeneWriter(System.out, sequences, new GenericFastaHeaderFormat(), true); + FastaGeneWriter fastaWriter = new FastaGeneWriter(System.out, sequences, new GenericFastaHeaderFormat<>(), true); fastaWriter.process(); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaReader.java index 4ad7dbeb9c..fa1d1bf323 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaReader.java @@ -35,6 +35,7 @@ import java.io.*; import java.util.HashMap; import java.util.LinkedHashMap; +import java.util.Map; /** * Use FastaReaderHelper as an example of how to use this class where FastaReaderHelper should be the @@ -46,7 +47,7 @@ public class FastaReader, C extends Compound> { private final static Logger logger = LoggerFactory.getLogger(FastaReader.class); SequenceCreatorInterface sequenceCreator; - SequenceHeaderParserInterface headerParser; + final SequenceHeaderParserInterface headerParser; BufferedReaderBytesRead br; InputStreamReader isr; FileInputStream fi = null; @@ -148,7 +149,7 @@ public LinkedHashMap process(int max) throws IOException { boolean keepGoing = true; - LinkedHashMap sequences = new LinkedHashMap(); + LinkedHashMap sequences = new LinkedHashMap<>(); do { line = line.trim(); // nice to have but probably not needed @@ -189,11 +190,12 @@ public LinkedHashMap process(int max) throws IOException { if (line == null) { //i.e. EOF - if ( sb.length() == 0 && header.length() != 0 ) { + int sbl = sb.length(); + if ( sbl == 0 && header.length() != 0 ) { logger.warn("Can't parse sequence {}. Got sequence of length 0!", sequenceIndex); logger.warn("header: {}", header); header = null; - } else if ( sb.length() > 0 ) { + } else if ( sbl > 0 ) { //logger.info("Sequence index=" + sequenceIndex + " " + fileIndex ); try { @SuppressWarnings("unchecked") @@ -238,7 +240,7 @@ public static void main(String[] args) { if ( is == null) System.err.println("Could not get input file " + inputFile); - FastaReader fastaReader = new FastaReader(is, new GenericFastaHeaderParser(), new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + FastaReader fastaReader = new FastaReader<>(is, new GenericFastaHeaderParser<>(), new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap proteinSequences = fastaReader.process(); is.close(); @@ -247,20 +249,20 @@ public static void main(String[] args) { File file = new File(inputFile); FastaReader fastaProxyReader = - new FastaReader( + new FastaReader<>( file, - new GenericFastaHeaderParser(), + new GenericFastaHeaderParser<>(), new FileProxyProteinSequenceCreator( file, - AminoAcidCompoundSet.getAminoAcidCompoundSet(), + AminoAcidCompoundSet.aminoAcidCompoundSet, new FastaSequenceParser() ) ); LinkedHashMap proteinProxySequences = fastaProxyReader.process(); - for(String key : proteinProxySequences.keySet()){ - ProteinSequence proteinSequence = proteinProxySequences.get(key); - logger.info("Protein Proxy Sequence Key: {}", key); + for(Map.Entry entry : proteinProxySequences.entrySet()){ + ProteinSequence proteinSequence = entry.getValue(); + logger.info("Protein Proxy Sequence Key: {}", entry.getKey()); // if(key.equals("Q98SJ1_CHICK/15-61")){ // int dummy = 1; // } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaReaderHelper.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaReaderHelper.java index 4338ff5375..ab882378cb 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaReaderHelper.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaReaderHelper.java @@ -24,11 +24,7 @@ import org.biojava.nbio.core.sequence.DNASequence; import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.RNASequence; -import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; -import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; -import org.biojava.nbio.core.sequence.compound.DNACompoundSet; -import org.biojava.nbio.core.sequence.compound.NucleotideCompound; -import org.biojava.nbio.core.sequence.compound.RNACompoundSet; +import org.biojava.nbio.core.sequence.compound.*; import java.io.File; import java.io.FileInputStream; @@ -57,15 +53,15 @@ public static LinkedHashMap readFastaDNASequence(File file, } FastaReader fastaProxyReader = - new FastaReader( + new FastaReader<>( file, - new GenericFastaHeaderParser(), + new GenericFastaHeaderParser<>(), new FileProxyDNASequenceCreator( file, DNACompoundSet.getDNACompoundSet(), new FastaSequenceParser() - ) - ); + ) + ); return fastaProxyReader.process(); } @@ -85,15 +81,15 @@ public static LinkedHashMap readFastaRNASequence(File file, } FastaReader fastaProxyReader = - new FastaReader( + new FastaReader<>( file, - new GenericFastaHeaderParser(), + new GenericFastaHeaderParser<>(), new FileProxyRNASequenceCreator( file, RNACompoundSet.getRNACompoundSet(), new FastaSequenceParser() - ) - ); + ) + ); return fastaProxyReader.process(); } @@ -124,10 +120,10 @@ public static LinkedHashMap readFastaProteinSequence( */ public static LinkedHashMap readFastaProteinSequence( InputStream inStream) throws IOException { - FastaReader fastaReader = new FastaReader( + FastaReader fastaReader = new FastaReader<>( inStream, - new GenericFastaHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + new GenericFastaHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); return fastaReader.process(); } @@ -139,9 +135,9 @@ public static LinkedHashMap readFastaProteinSequence( */ public static LinkedHashMap readFastaDNASequence( InputStream inStream) throws IOException { - FastaReader fastaReader = new FastaReader( + FastaReader fastaReader = new FastaReader<>( inStream, - new GenericFastaHeaderParser(), + new GenericFastaHeaderParser<>(), new DNASequenceCreator(DNACompoundSet.getDNACompoundSet())); return fastaReader.process(); } @@ -168,9 +164,9 @@ public static LinkedHashMap readFastaDNASequence( */ public static LinkedHashMap readFastaRNASequence( InputStream inStream) throws IOException { - FastaReader fastaReader = new FastaReader( + FastaReader fastaReader = new FastaReader<>( inStream, - new GenericFastaHeaderParser(), + new GenericFastaHeaderParser<>(), new RNASequenceCreator(RNACompoundSet.getRNACompoundSet())); return fastaReader.process(); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaWriter.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaWriter.java index 5bdc0df018..248e21ad52 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaWriter.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaWriter.java @@ -30,11 +30,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.BufferedOutputStream; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; +import java.io.*; import java.util.Collection; import java.util.LinkedHashMap; @@ -50,9 +46,9 @@ public class FastaWriter, C extends Compound> { private final static Logger logger = LoggerFactory.getLogger(FastaWriter.class); - OutputStream os; - Collection sequences; - FastaHeaderFormatInterface headerFormat; + final OutputStream os; + final Collection sequences; + final FastaHeaderFormatInterface headerFormat; private int lineLength = 60; byte[] lineSep = System.getProperty("line.separator").getBytes(); /** @@ -103,7 +99,7 @@ public void process() throws IOException { os.write(lineSep); int compoundCount = 0; - String seq = ""; + String seq; seq = sequence.getSequenceAsString(); @@ -133,7 +129,7 @@ public static void main(String[] args) { FileInputStream is = new FileInputStream("/Users/Scooter/scripps/dyadic/c1-454Scaffolds.faa"); - FastaReader fastaReader = new FastaReader(is, new GenericFastaHeaderParser(), new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + FastaReader fastaReader = new FastaReader<>(is, new GenericFastaHeaderParser<>(), new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap proteinSequences = fastaReader.process(); is.close(); @@ -144,7 +140,7 @@ public static void main(String[] args) { BufferedOutputStream bo = new BufferedOutputStream(fileOutputStream); long start = System.currentTimeMillis(); - FastaWriter fastaWriter = new FastaWriter(bo, proteinSequences.values(), new GenericFastaHeaderFormat()); + FastaWriter fastaWriter = new FastaWriter<>(bo, proteinSequences.values(), new GenericFastaHeaderFormat<>()); fastaWriter.process(); bo.close(); long end = System.currentTimeMillis(); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaWriterHelper.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaWriterHelper.java index 966d723728..1e3ec619cf 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaWriterHelper.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FastaWriterHelper.java @@ -71,9 +71,9 @@ public static void writeProteinSequence(File file, public static void writeProteinSequence(OutputStream outputStream, Collection proteinSequences) throws Exception { - FastaWriter fastaWriter = new FastaWriter( + FastaWriter fastaWriter = new FastaWriter<>( outputStream, proteinSequences, - new GenericFastaHeaderFormat()); + new GenericFastaHeaderFormat<>()); fastaWriter.process(); } @@ -103,7 +103,7 @@ public static void writeGeneSequence(File file, Collection geneSeq public static void writeGeneSequence(OutputStream outputStream, Collection geneSequences,boolean showExonUppercase) throws Exception { FastaGeneWriter fastaWriter = new FastaGeneWriter( outputStream, geneSequences, - new GenericFastaHeaderFormat(),showExonUppercase); + new GenericFastaHeaderFormat<>(),showExonUppercase); fastaWriter.process(); } @@ -132,9 +132,9 @@ public static void writeNucleotideSequence(File file, Collection dn */ public static void writeNucleotideSequence(OutputStream outputStream, Collection dnaSequences) throws Exception { - FastaWriter fastaWriter = new FastaWriter( + FastaWriter fastaWriter = new FastaWriter<>( outputStream, dnaSequences, - new GenericFastaHeaderFormat()); + new GenericFastaHeaderFormat<>()); fastaWriter.process(); } @@ -170,7 +170,7 @@ public static void writeSequence(OutputStream outputStream, Sequence sequence */ private static Collection> singleSeqToCollection(Sequence sequence) { - Collection> sequences = new ArrayList>(); + Collection> sequences = new ArrayList<>(); sequences.add(sequence); return sequences; } @@ -188,19 +188,11 @@ public static void writeSequences(OutputStream outputStream, Collection> sequences) throws Exception { FastaHeaderFormatInterface, Compound> fhfi = - new FastaHeaderFormatInterface, Compound>() { - - @Override - public String getHeader(Sequence sequence) { - return sequence.getAccession().toString(); - } - - ; - }; + sequence -> sequence.getAccession().toString(); FastaWriter, Compound> fastaWriter = - new FastaWriter, Compound>(outputStream, - sequences, fhfi); + new FastaWriter<>(outputStream, + sequences, fhfi); fastaWriter.process(); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyDNASequenceCreator.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyDNASequenceCreator.java index fb89f1c4e3..a23ddce00b 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyDNASequenceCreator.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyDNASequenceCreator.java @@ -50,9 +50,9 @@ public class FileProxyDNASequenceCreator implements SequenceCreatorInterface { - CompoundSet compoundSet = null; - File file = null; - SequenceParserInterface sequenceParser; + final CompoundSet compoundSet; + final File file; + final SequenceParserInterface sequenceParser; /** * Need File so that we can store full path name in SequenceFileProxyLoader for Random File access as a quick read @@ -78,7 +78,7 @@ public FileProxyDNASequenceCreator(File file, */ @Override public AbstractSequence getSequence(String sequence, long index ) throws CompoundNotFoundException, IOException { - SequenceFileProxyLoader sequenceFileProxyLoader = new SequenceFileProxyLoader( + SequenceFileProxyLoader sequenceFileProxyLoader = new SequenceFileProxyLoader<>( file, sequenceParser, index, diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyProteinSequenceCreator.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyProteinSequenceCreator.java index 7db550683f..f9749302b8 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyProteinSequenceCreator.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyProteinSequenceCreator.java @@ -49,9 +49,9 @@ */ public class FileProxyProteinSequenceCreator implements SequenceCreatorInterface { - CompoundSet compoundSet; - File file; - SequenceParserInterface sequenceParser; + final CompoundSet compoundSet; + final File file; + final SequenceParserInterface sequenceParser; /** * Need File so that we can store full path name in SequenceFileProxyLoader for Random File access as a quick read @@ -76,13 +76,13 @@ public FileProxyProteinSequenceCreator(File file, CompoundSet @Override public AbstractSequence getSequence(String sequence, long index) throws CompoundNotFoundException, IOException { SequenceFileProxyLoader sequenceFileProxyLoader = - new SequenceFileProxyLoader( + new SequenceFileProxyLoader<>( file, sequenceParser, index, sequence.length(), compoundSet - ); + ); return new ProteinSequence(sequenceFileProxyLoader, compoundSet); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyRNASequenceCreator.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyRNASequenceCreator.java index 4be68696fb..bc6c4f7941 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyRNASequenceCreator.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/FileProxyRNASequenceCreator.java @@ -50,9 +50,9 @@ public class FileProxyRNASequenceCreator implements SequenceCreatorInterface { - CompoundSet compoundSet = null; - File file = null; - SequenceParserInterface sequenceParser; + final CompoundSet compoundSet; + final File file; + final SequenceParserInterface sequenceParser; /** * Need File so that we can store full path name in SequenceFileProxyLoader for Random File access as a quick read @@ -78,7 +78,7 @@ public FileProxyRNASequenceCreator(File file, */ @Override public AbstractSequence getSequence(String sequence, long index ) throws CompoundNotFoundException, IOException { - SequenceFileProxyLoader sequenceFileProxyLoader = new SequenceFileProxyLoader( + SequenceFileProxyLoader sequenceFileProxyLoader = new SequenceFileProxyLoader<>( file, sequenceParser, index, diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankReader.java index 951cce40c0..b8c69f9311 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankReader.java @@ -36,13 +36,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; +import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; @@ -55,9 +49,9 @@ */ public class GenbankReader, C extends Compound> { - private SequenceCreatorInterface sequenceCreator; - private GenbankSequenceParser genbankParser; - private BufferedReader bufferedReader; + private final SequenceCreatorInterface sequenceCreator; + private final GenbankSequenceParser genbankParser; + private final BufferedReader bufferedReader; private boolean closed; private final Logger logger = LoggerFactory.getLogger(this.getClass()); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankReaderHelper.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankReaderHelper.java index 51c1f7593b..38d4eb408d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankReaderHelper.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankReaderHelper.java @@ -24,11 +24,7 @@ import org.biojava.nbio.core.sequence.DNASequence; import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.RNASequence; -import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; -import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; -import org.biojava.nbio.core.sequence.compound.DNACompoundSet; -import org.biojava.nbio.core.sequence.compound.NucleotideCompound; -import org.biojava.nbio.core.sequence.compound.RNACompoundSet; +import org.biojava.nbio.core.sequence.compound.*; import org.biojava.nbio.core.sequence.template.AbstractSequence; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -61,15 +57,15 @@ public static LinkedHashMap readGenbankDNASequence(File fil } GenbankReader GenbankProxyReader = - new GenbankReader( + new GenbankReader<>( file, - new GenericGenbankHeaderParser(), + new GenericGenbankHeaderParser<>(), new FileProxyDNASequenceCreator( file, DNACompoundSet.getDNACompoundSet(), new GenbankSequenceParser, NucleotideCompound>() - ) - ); + ) + ); return GenbankProxyReader.process(); } @@ -88,16 +84,16 @@ public static LinkedHashMap readGenbankProteinSequence( return readGenbankProteinSequence(file); } - GenbankReader GenbankProxyReader = - new GenbankReader( + GenbankReader GenbankProxyReader = + new GenbankReader<>( file, - new GenericGenbankHeaderParser(), + new GenericGenbankHeaderParser<>(), new FileProxyProteinSequenceCreator( file, - AminoAcidCompoundSet.getAminoAcidCompoundSet(), + AminoAcidCompoundSet.aminoAcidCompoundSet, new GenbankSequenceParser, AminoAcidCompound>() - ) - ); + ) + ); return GenbankProxyReader.process(); } @@ -117,15 +113,15 @@ public static LinkedHashMap readGenbankRNASequence(File fil } GenbankReader GenbankProxyReader = - new GenbankReader( + new GenbankReader<>( file, - new GenericGenbankHeaderParser(), + new GenericGenbankHeaderParser<>(), new FileProxyRNASequenceCreator( file, RNACompoundSet.getRNACompoundSet(), new GenbankSequenceParser, NucleotideCompound>() - ) - ); + ) + ); return GenbankProxyReader.process(); } @@ -156,10 +152,10 @@ public static LinkedHashMap readGenbankProteinSequence( */ public static LinkedHashMap readGenbankProteinSequence( InputStream inStream) throws Exception { - GenbankReader GenbankReader = new GenbankReader( + GenbankReader GenbankReader = new GenbankReader<>( inStream, - new GenericGenbankHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + new GenericGenbankHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); return GenbankReader.process(); } @@ -171,9 +167,9 @@ public static LinkedHashMap readGenbankProteinSequence( */ public static LinkedHashMap readGenbankDNASequence( InputStream inStream) throws Exception { - GenbankReader GenbankReader = new GenbankReader( + GenbankReader GenbankReader = new GenbankReader<>( inStream, - new GenericGenbankHeaderParser(), + new GenericGenbankHeaderParser<>(), new DNASequenceCreator(DNACompoundSet.getDNACompoundSet())); return GenbankReader.process(); } @@ -199,9 +195,9 @@ public static LinkedHashMap readGenbankDNASequence( */ public static LinkedHashMap readGenbankRNASequence( InputStream inStream) throws Exception { - GenbankReader GenbankReader = new GenbankReader( + GenbankReader GenbankReader = new GenbankReader<>( inStream, - new GenericGenbankHeaderParser(), + new GenericGenbankHeaderParser<>(), new RNASequenceCreator(RNACompoundSet.getRNACompoundSet())); return GenbankReader.process(); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankSequenceParser.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankSequenceParser.java index 9641a38894..bdcc7bf05c 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankSequenceParser.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankSequenceParser.java @@ -44,7 +44,6 @@ import org.biojava.nbio.core.sequence.io.template.SequenceParserInterface; import org.biojava.nbio.core.sequence.location.InsdcParser; import org.biojava.nbio.core.sequence.location.template.AbstractLocation; -import org.biojava.nbio.core.sequence.location.template.Location; import org.biojava.nbio.core.sequence.reference.GenbankReference; import org.biojava.nbio.core.sequence.template.AbstractSequence; import org.biojava.nbio.core.sequence.template.Compound; @@ -75,7 +74,7 @@ public class GenbankSequenceParser, C extends Comp */ private HashMap> featureCollection; - private Logger log = LoggerFactory.getLogger(getClass()); + private final Logger log = LoggerFactory.getLogger(getClass()); // this is a compoundset parsed from header. private CompoundSet compoundType; @@ -138,180 +137,191 @@ public class GenbankSequenceParser, C extends Comp private String parse(BufferedReader bufferedReader) { - String sectionKey = null; + String sectionKey; List section; // Get an ordered list of key->value pairs in array-tuples do { section = this.readSection(bufferedReader); - sectionKey = section.get(0)[0]; + String[] s0 = section.get(0); + sectionKey = s0[0]; if (sectionKey == null) { //if we reach the end of the file, section contains empty strings - if(section.get(0)[1]==null || section.get(0)[1]=="" || - section.get(0)[1].length()==0) { + if(s0[1]==null || s0[1].isEmpty() || + s0[1].length()==0) { throw new ParserException(Messages.ENDOFFILE); } throw new ParserException(Messages.SECTIONKEYNULL); } // process section-by-section - if (sectionKey.equals(LOCUS_TAG)) { - String loc = section.get(0)[1]; - header = loc; - Matcher m = lp.matcher(loc); - if (m.matches()) { - headerParser.setName(m.group(1)); - headerParser.setAccession(m.group(1)); // default if no accession found - - String lengthUnits = m.group(2); - String type = m.group(5); - - if (lengthUnits.equalsIgnoreCase("aa")) { - compoundType = AminoAcidCompoundSet.getAminoAcidCompoundSet(); - } else if (lengthUnits.equalsIgnoreCase("bp")) { - if (type != null) { - if (type.contains("RNA")) { - compoundType = RNACompoundSet.getRNACompoundSet(); + switch (sectionKey) { + case LOCUS_TAG: { + String loc = s0[1]; + header = loc; + Matcher m = lp.matcher(loc); + if (m.matches()) { + headerParser.setName(m.group(1)); + headerParser.setAccession(m.group(1)); // default if no accession found + + String lengthUnits = m.group(2); + String type = m.group(5); + + if (lengthUnits.equalsIgnoreCase("aa")) { + compoundType = AminoAcidCompoundSet.aminoAcidCompoundSet; + } else if (lengthUnits.equalsIgnoreCase("bp")) { + if (type != null) { + if (type.contains("RNA")) { //HACK + compoundType = RNACompoundSet.getRNACompoundSet(); + } else { + compoundType = DNACompoundSet.getDNACompoundSet(); + } } else { compoundType = DNACompoundSet.getDNACompoundSet(); } - } else { - compoundType = DNACompoundSet.getDNACompoundSet(); } - } - log.debug("compound type: {}", compoundType.getClass().getSimpleName()); + //log.debug("compound type: {}", compoundType.getClass().getSimpleName()); - } else { - throw new ParserException("Bad locus line"); - } - } else if (sectionKey.equals(DEFINITION_TAG)) { - headerParser.setDescription(section.get(0)[1]); - } else if (sectionKey.equals(ACCESSION_TAG)) { - // if multiple accessions, store only first as accession, - // and store rest in annotation - String[] accs = section.get(0)[1].split("\\s+"); - accession = accs[0].trim(); - headerParser.setAccession(accession); - } else if (sectionKey.equals(VERSION_TAG)) { - String ver = section.get(0)[1]; - Matcher m = vp.matcher(ver); - if (m.matches()) { - String verAcc = m.group(1); - if (!accession.equals(verAcc)) { - // the version refers to a different accession! - // believe the version line, and store the original - // accession away in the additional accession set - accession = verAcc; - } - if (m.group(3) != null) { - headerParser.setVersion(Integer.parseInt(m.group(3))); - } - if (m.group(5) != null) { - headerParser.setIdentifier(m.group(5)); + } else { + throw new ParserException("Bad locus line"); } - } else { - throw new ParserException("Bad version line"); + break; } - } else if (sectionKey.equals(KEYWORDS_TAG)) { - } else if (sectionKey.equals(SOURCE_TAG)) { - // ignore - can get all this from the first feature - } else if (sectionKey.equals(REFERENCE_TAG)) { - if (!section.isEmpty()) { - GenbankReference genbankReference = new GenbankReference(); - for (String[] ref : section) { - if (ref[0].equals(AUTHORS_TAG)) { - genbankReference.setAuthors(ref[1]); - } else if (ref[0].equals(TITLE_TAG)) { - genbankReference.setTitle(ref[1]); - } else if (ref[0].equals(JOURNAL_TAG)) { - genbankReference.setJournal(ref[1]); + case DEFINITION_TAG: + headerParser.setDescription(s0[1]); + break; + case ACCESSION_TAG: + // if multiple accessions, store only first as accession, + // and store rest in annotation + String[] accs = s0[1].split("\\s+"); + accession = accs[0].trim(); + headerParser.setAccession(accession); + break; + case VERSION_TAG: { + String ver = s0[1]; + Matcher m = vp.matcher(ver); + if (m.matches()) { + String verAcc = m.group(1); + if (!accession.equals(verAcc)) { + // the version refers to a different accession! + // believe the version line, and store the original + // accession away in the additional accession set + accession = verAcc; + } + if (m.group(3) != null) { + headerParser.setVersion(Integer.parseInt(m.group(3))); + } + if (m.group(5) != null) { + headerParser.setIdentifier(m.group(5)); } + } else { + throw new ParserException("Bad version line"); } - headerParser.addReference(genbankReference); + break; } - } else if (sectionKey.equals(COMMENT_TAG)) { - // Set up some comments - headerParser.setComment(section.get(0)[1]); - } else if (sectionKey.equals(FEATURE_TAG)) { - // starting from second line of input, start a new feature whenever we come across - // a key that does not start with / - AbstractFeature gbFeature = null; - for (int i = 1; i < section.size(); i++) { - String key = section.get(i)[0]; - String val = section.get(i)[1]; - if (key.startsWith("/")) { - if (gbFeature == null) { - throw new ParserException("Malformed GenBank file: found a qualifier without feature."); - } - key = key.substring(1); // strip leading slash - val = val.replaceAll("\\s*[\\n\\r]+\\s*", " ").trim(); - if (val.endsWith("\"")) { - val = val.substring(1, val.length() - 1); // strip quotes + case KEYWORDS_TAG: + break; + case SOURCE_TAG: + // ignore - can get all this from the first feature + break; + case REFERENCE_TAG: + if (!section.isEmpty()) { + GenbankReference genbankReference = new GenbankReference(); + for (String[] ref : section) { + switch (ref[0]) { + case AUTHORS_TAG: + genbankReference.setAuthors(ref[1]); + break; + case TITLE_TAG: + genbankReference.setTitle(ref[1]); + break; + case JOURNAL_TAG: + genbankReference.setJournal(ref[1]); + break; + } } - // parameter on old feature - if (key.equals("db_xref")) { - Matcher m = dbxp.matcher(val); - if (m.matches()) { - String dbname = m.group(1); - String raccession = m.group(2); - Qualifier xref = new DBReferenceInfo(dbname, raccession); - gbFeature.addQualifier(key, xref); - - ArrayList listDBEntry = new ArrayList(); - listDBEntry.add((DBReferenceInfo) xref); - mapDB.put(key, listDBEntry); - } else { - throw new ParserException("Bad dbxref"); + headerParser.addReference(genbankReference); + } + break; + case COMMENT_TAG: + // Set up some comments + headerParser.setComment(s0[1]); + break; + case FEATURE_TAG: + // starting from second line of input, start a new feature whenever we come across + // a key that does not start with / + AbstractFeature gbFeature = null; + for (int i = 1; i < section.size(); i++) { + String[] si = section.get(i); + String key = si[0]; + String val = si[1]; + if (key.startsWith("/")) { + if (gbFeature == null) { + throw new ParserException("Malformed GenBank file: found a qualifier without feature."); } - } else if (key.equalsIgnoreCase("organism")) { - Qualifier q = new Qualifier(key, val.replace('\n', ' ')); - gbFeature.addQualifier(key, q); - } else { - if (key.equalsIgnoreCase("translation")) { - // strip spaces from sequence - val = val.replaceAll("\\s+", ""); - Qualifier q = new Qualifier(key, val); + key = key.substring(1); // strip leading slash + val = val.replaceAll("\\s*[\\n\\r]+\\s*", " ").trim(); + if (val.endsWith("\"")) { + val = val.substring(1, val.length() - 1); // strip quotes + } + // parameter on old feature + if (key.equals("db_xref")) { + Matcher m = dbxp.matcher(val); + if (m.matches()) { + String dbname = m.group(1); + String raccession = m.group(2); + DBReferenceInfo xref = new DBReferenceInfo(dbname, raccession); + gbFeature.addQualifier(key, xref); + + ArrayList listDBEntry = new ArrayList<>(1); + listDBEntry.add(xref); + mapDB.put(key, listDBEntry); + } else { + throw new ParserException("Bad dbxref"); + } + } else if (key.equalsIgnoreCase("organism")) { + Qualifier q = new Qualifier(key, val.replace('\n', ' ')); gbFeature.addQualifier(key, q); } else { - Qualifier q = new Qualifier(key, val); - gbFeature.addQualifier(key, q); + if (key.equalsIgnoreCase("translation")) { + // strip spaces from sequence + val = val.replaceAll("\\s+", ""); + } + gbFeature.addQualifier(key, new Qualifier(key, val)); } + } else { + // new feature! + gbFeature = new TextFeature(key, val, key, key); + gbFeature.setLocation((AbstractLocation) locationParser.parse(val)); + + featureCollection.computeIfAbsent(key, (x)->new ArrayList<>(1)).add(gbFeature); } - } else { - // new feature! - gbFeature = new TextFeature(key, val, key, key); - Location l = - locationParser.parse(val); - gbFeature.setLocation((AbstractLocation)l); - - if (!featureCollection.containsKey(key)) { - featureCollection.put(key, new ArrayList()); - } - featureCollection.get(key).add(gbFeature); } - } - } else if (sectionKey.equals(BASE_COUNT_TAG)) { - // ignore - can calculate from sequence content later if needed - } else if (sectionKey.equals(START_SEQUENCE_TAG)) { - // our first line is ignorable as it is the ORIGIN tag - // the second line onwards conveniently have the number as - // the [0] tuple, and sequence string as [1] so all we have - // to do is concat the [1] parts and then strip out spaces, - // and replace '.' and '~' with '-' for our parser. - StringBuffer seq = new StringBuffer(); - for (int i = 1; i < section.size(); i++) { - seq.append(section.get(i)[1]); - } - seqData = seq.toString().replaceAll("\\s+", "").replaceAll("[\\.|~]", "-").toUpperCase(); - } else if(sectionKey.equals(DBSOURCE)) { - //TODO - } else if(sectionKey.equals(PRIMARY)) { - //TODO - } else if(sectionKey.equals(DBLINK)) { - //TODO - } else { - if(!sectionKey.equals(END_SEQUENCE_TAG)) { - log.info("found unknown section key: "+sectionKey); - } + break; + case BASE_COUNT_TAG: + // ignore - can calculate from sequence content later if needed + break; + case START_SEQUENCE_TAG: + // our first line is ignorable as it is the ORIGIN tag + // the second line onwards conveniently have the number as + // the [0] tuple, and sequence string as [1] so all we have + // to do is concat the [1] parts and then strip out spaces, + // and replace '.' and '~' with '-' for our parser. + StringBuilder seq = new StringBuilder(); + for (int i = 1; i < section.size(); i++) { + seq.append(section.get(i)[1]); + } + seqData = seq.toString().replaceAll("\\s+", "").replaceAll("[\\.|~]", "-").toUpperCase(); + break; + case DBSOURCE: + case DBLINK: + case PRIMARY: + //TODO + break; + default: + if (!sectionKey.equals(END_SEQUENCE_TAG)) { + log.info("found unknown section key: " + sectionKey); + } + break; } } while (!sectionKey.equals(END_SEQUENCE_TAG)); return seqData; @@ -326,8 +336,8 @@ private String parse(BufferedReader bufferedReader) { // reads an indented section, combining split lines and creating a list of // key->value tuples private List readSection(BufferedReader bufferedReader) { - List section = new ArrayList(); - String line = ""; + List section = new ArrayList<>(); + String line; String currKey = null; StringBuffer currVal = new StringBuffer(); @@ -345,8 +355,7 @@ private List readSection(BufferedReader bufferedReader) { // having only white space characters continue; } - if (line == null - || (!line.startsWith(" ") && linecount++ > 0 && (!firstSecKey + if (line == null || (!line.startsWith(" ") && linecount++ > 0 && (!firstSecKey .equals(START_SEQUENCE_TAG) || line .startsWith(END_SEQUENCE_TAG)))) { // dump out last part of section @@ -385,23 +394,21 @@ private List readSection(BufferedReader bufferedReader) { } } } - } catch (IOException e) { - throw new ParserException(e.getMessage()); - } catch (RuntimeException e) { + } catch (IOException | RuntimeException e) { throw new ParserException(e.getMessage()); } return section; } @Override - public String getSequence(BufferedReader bufferedReader, int sequenceLength) throws IOException { - featureCollection = new HashMap>(); - mapDB = new LinkedHashMap>(); - headerParser = new GenericGenbankHeaderParser(); + public String getSequence(BufferedReader bufferedReader, int sequenceLength) { + featureCollection = new HashMap<>(); + mapDB = new LinkedHashMap<>(); + headerParser = new GenericGenbankHeaderParser<>(); try { parse(bufferedReader); } catch (ParserException e) { - if(e.getMessage().equalsIgnoreCase(Messages.ENDOFFILE)) return null; + if (e.getMessage().equalsIgnoreCase(Messages.ENDOFFILE)) return null; else throw new ParserException(e.getMessage()); } @@ -421,7 +428,7 @@ public LinkedHashMap> getDatabaseReferences() } public ArrayList getKeyWords() { - return new ArrayList(featureCollection.keySet()); + return new ArrayList<>(featureCollection.keySet()); } public ArrayList getFeatures(String keyword) { @@ -432,8 +439,8 @@ public HashMap> getFeatures() { } public void parseFeatures(AbstractSequence sequence) { - for (String k: featureCollection.keySet()) - for (AbstractFeature f: featureCollection.get(k)) + for (ArrayList abstractFeatures : featureCollection.values()) + for (AbstractFeature f: abstractFeatures) sequence.addFeature(f); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankWriter.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankWriter.java index cab8d23db1..819e785df0 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankWriter.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankWriter.java @@ -38,11 +38,11 @@ * */ public class GenbankWriter, C extends Compound> { - int SEQUENCE_INDENT = 9; + final int SEQUENCE_INDENT = 9; - OutputStream os; - Collection sequences; - GenbankHeaderFormatInterface headerFormat; + final OutputStream os; + final Collection sequences; + final GenbankHeaderFormatInterface headerFormat; private int lineLength = 60; // byte[] lineSep = System.getProperty("line.separator").getBytes(); @@ -85,7 +85,7 @@ public GenbankWriter(OutputStream os, Collection sequences, * @param lineSeparator */ - public void process() throws Exception { + public void process() { // Loosely based on code from Howard Salis // TODO - Force lower case? // boolean closeit = false; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankWriterHelper.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankWriterHelper.java index 19e26bd3a7..dc2a2768ec 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankWriterHelper.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenbankWriterHelper.java @@ -70,16 +70,15 @@ public static void writeProteinSequence(File file, * * @param outputStream * @param proteinSequences - * @throws Exception - */ + */ public static void writeProteinSequence(OutputStream outputStream, - Collection proteinSequences) throws Exception { + Collection proteinSequences) { - GenbankWriter genbankWriter = new GenbankWriter( + GenbankWriter genbankWriter = new GenbankWriter<>( outputStream, proteinSequences, - new GenericGenbankHeaderFormat()); + new GenericGenbankHeaderFormat<>()); genbankWriter.process(); } @@ -106,11 +105,10 @@ public static void writeNucleotideSequence(File file, * * @param outputStream * @param dnaSequences - * @throws Exception - */ + */ public static void writeNucleotideSequence(OutputStream outputStream, - Collection dnaSequences) throws Exception { + Collection dnaSequences) { writeNucleotideSequence(outputStream, dnaSequences, LINEAR_DNA); } @@ -120,16 +118,14 @@ public static void writeNucleotideSequence(OutputStream outputStream, * @param outputStream * @param dnaSequences * @param seqType - * @throws Exception - */ + */ public static void writeNucleotideSequence(OutputStream outputStream, - Collection dnaSequences, String seqType) - throws Exception { - GenericGenbankHeaderFormat genericGenbankHeaderFormat = new GenericGenbankHeaderFormat( + Collection dnaSequences, String seqType) { + GenericGenbankHeaderFormat genericGenbankHeaderFormat = new GenericGenbankHeaderFormat<>( seqType); // genericGenbankHeaderFormat.setLineSeparator(lineSep); - GenbankWriter genbankWriter = new GenbankWriter( + GenbankWriter genbankWriter = new GenbankWriter<>( outputStream, dnaSequences, genericGenbankHeaderFormat); // genbankWriter.setLineSeparator(lineSep); genbankWriter.process(); @@ -156,10 +152,9 @@ public static void writeSequence(File file, Sequence sequence) * * @param outputStream * @param sequence - * @throws Exception - */ + */ public static void writeSequence(OutputStream outputStream, - Sequence sequence) throws Exception { + Sequence sequence) { writeSequences(outputStream, singleSeqToCollection(sequence)); } @@ -171,7 +166,7 @@ public static void writeSequence(OutputStream outputStream, private static Collection> singleSeqToCollection( Sequence sequence) { - Collection> sequences = new ArrayList>(); + Collection> sequences = new ArrayList<>(); sequences.add(sequence); return sequences; } @@ -185,23 +180,13 @@ private static Collection> singleSeqToCollection( * Stream to write to; can be System.out * @param sequences * The sequences to write out - * @throws Exception - * Thrown normally thanks to IO problems - */ + */ public static void writeSequences(OutputStream outputStream, - Collection> sequences) throws Exception { - - GenbankHeaderFormatInterface, Compound> fhfi = new GenbankHeaderFormatInterface, Compound>() { - - @Override - public String getHeader(Sequence sequence) { - return sequence.getAccession().toString(); - } + Collection> sequences) { - ; - }; + GenbankHeaderFormatInterface, Compound> fhfi = sequence -> sequence.getAccession().toString(); - GenbankWriter, Compound> genbankWriter = new GenbankWriter, Compound>( + GenbankWriter, Compound> genbankWriter = new GenbankWriter<>( outputStream, sequences, fhfi); genbankWriter.process(); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericFastaHeaderParser.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericFastaHeaderParser.java index 1a83dee701..e13f06d7ba 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericFastaHeaderParser.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericFastaHeaderParser.java @@ -71,8 +71,8 @@ public class GenericFastaHeaderParser, C extends C */ private String[] getHeaderValues(String header) { String[] data = new String[0]; - ArrayList values = new ArrayList(); - StringBuffer sb = new StringBuffer(); + ArrayList values = new ArrayList<>(); + StringBuilder sb = new StringBuilder(); //commented out 1/11/2012 to resolve an issue where headers do contain a length= at the end that are not recognized //if(header.indexOf("length=") != -1){ // data = new String[1]; @@ -152,7 +152,7 @@ public void parseHeader(String header, S sequence) { String[] pdbe = data[0].split(" "); String[] pdbaccession = pdbe[0].split(":"); sequence.setAccession(new AccessionID(pdbaccession[1], DataSource.PDBe)); - } else if (data[0].indexOf(":") != -1 && data.length > 1 && data[1].equals("PDBID")) { + } else if (data[0].contains(":") && data.length > 1 && data[1].equals("PDBID")) { sequence.setAccession(new AccessionID(data[0], DataSource.PDB2)); } else if (data[0].equalsIgnoreCase("pat")) { sequence.setAccession(new AccessionID(data[2], DataSource.PATENTS)); @@ -178,7 +178,7 @@ public void parseHeader(String header, S sequence) { public static void main(String[] args) { logger.info("parseHeader"); - String header = ""; + String header; ProteinSequence sequence = null; try { sequence = new ProteinSequence(""); @@ -187,7 +187,7 @@ public static void main(String[] args) { logger.error("Could not create empty protein sequence. Error: {}. This is most likely a bug.",e.getMessage()); } GenericFastaHeaderParser instance = - new GenericFastaHeaderParser(); + new GenericFastaHeaderParser<>(); header = "gi|gi-number|gb|accession|locus"; instance.parseHeader(header, sequence); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericGenbankHeaderFormat.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericGenbankHeaderFormat.java index a19c9f648c..902c50bfa6 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericGenbankHeaderFormat.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericGenbankHeaderFormat.java @@ -36,7 +36,7 @@ public class GenericGenbankHeaderFormat, C extends GenbankHeaderFormatInterface { private static final int HEADER_WIDTH = 12; private static final String lineSep = "%n"; - private String seqType = null; + private final String seqType; public GenericGenbankHeaderFormat() { seqType = null; @@ -169,8 +169,8 @@ private String _write_the_first_line(S sequence) { + " is too long"); } - String units = ""; - String mol_type = ""; + String units; + String mol_type; if (sequence.getCompoundSet() instanceof DNACompoundSet) { units = "bp"; mol_type = "DNA"; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericGenbankHeaderParser.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericGenbankHeaderParser.java index 7c828b54f2..279c0cdbfc 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericGenbankHeaderParser.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericGenbankHeaderParser.java @@ -25,6 +25,7 @@ import org.biojava.nbio.core.exceptions.ParserException; import org.biojava.nbio.core.sequence.AccessionID; +import org.biojava.nbio.core.sequence.DataSource; import org.biojava.nbio.core.sequence.io.template.SequenceHeaderParserInterface; import org.biojava.nbio.core.sequence.reference.AbstractReference; import org.biojava.nbio.core.sequence.template.AbstractSequence; @@ -33,8 +34,6 @@ import java.util.ArrayList; import java.util.List; -import org.biojava.nbio.core.sequence.DataSource; - public class GenericGenbankHeaderParser, C extends Compound> implements SequenceHeaderParserInterface { private String accession = null; @@ -43,8 +42,8 @@ public class GenericGenbankHeaderParser, C extends @SuppressWarnings("unused") private int version; private boolean versionSeen; - private ArrayList comments = new ArrayList<>(); - private List references = new ArrayList<>(); + private final ArrayList comments = new ArrayList<>(); + private final List references = new ArrayList<>(); /** * Parse the header and set the values in the sequence diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericInsdcHeaderFormat.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericInsdcHeaderFormat.java index 97e37f30cd..870e526c43 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericInsdcHeaderFormat.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/GenericInsdcHeaderFormat.java @@ -32,11 +32,7 @@ import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.util.StringManipulationHelper; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Formatter; -import java.util.List; -import java.util.Locale; +import java.util.*; /** * @author mckeee1 @@ -56,7 +52,7 @@ public class GenericInsdcHeaderFormat, C extends C * @param quote */ private String _write_feature_qualifier(String key, String value, boolean quote) { - String line = ""; + String line; if(null == value) { line = QUALIFIER_INDENT_STR + "/" + key + lineSep; return line; @@ -70,7 +66,7 @@ private String _write_feature_qualifier(String key, String value, boolean quote) return line + lineSep; } String goodlines = ""; - while(!"".equals(line.replaceAll("^\\s+", ""))) { + while(!line.replaceAll("^\\s+", "").isEmpty()) { if(line.length() <= MAX_WIDTH) { goodlines += line + lineSep; break; @@ -101,7 +97,7 @@ private String _wrap_location(String location) { if(location.length() <= length) { return location; } - int index = location.substring(length).lastIndexOf(","); + int index = location.substring(length).lastIndexOf(','); if(-1 == index) { //No good place to split (!) return location; @@ -195,7 +191,7 @@ private String _insdc_feature_location_string(FeatureInterface locations = new ArrayList(); + ArrayList locations = new ArrayList<>(); for(FeatureInterface, C> f : feature.getChildrenFeatures()) { locations.add(_insdc_location_string_ignoring_strand_and_subfeatures(f.getLocations(), record_length)); } @@ -208,7 +204,7 @@ private String _insdc_feature_location_string(FeatureInterface locations = new ArrayList(); + ArrayList locations = new ArrayList<>(); for(FeatureInterface, C> f : feature.getChildrenFeatures()) { locations.add(_insdc_location_string_ignoring_strand_and_subfeatures(f.getLocations(), record_length)); } @@ -340,14 +336,14 @@ raise ValueError("Expected a SeqFeature position object.") */ protected ArrayList _split_multi_line(String text, int max_len) { // TODO Auto-generated method stub - ArrayList output = new ArrayList(); + ArrayList output = new ArrayList<>(); text = text.trim(); if(text.length() <= max_len) { output.add(text); return output; } - ArrayList words = new ArrayList(); + ArrayList words = new ArrayList<>(); Collections.addAll(words, text.split("\\s+")); while(!words.isEmpty()) { text = words.remove(0); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/IUPACParser.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/IUPACParser.java index 8f1b449283..51c10918dd 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/IUPACParser.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/IUPACParser.java @@ -86,7 +86,7 @@ public static IUPACParser getInstance() { public static final String IUPAC_LOCATION = "org/biojava/nbio/core/sequence/iupac.txt"; - private InputStream is; + private final InputStream is; private List tables; private Map nameLookup; private Map idLookup; @@ -134,8 +134,8 @@ public IUPACTable getTable(Integer id) { private void populateLookups() { if(nameLookup == null) { - nameLookup = new HashMap(); - idLookup = new HashMap(); + nameLookup = new HashMap<>(); + idLookup = new HashMap<>(); for(IUPACTable t: getTables()) { nameLookup.put(t.getName(), t); idLookup.put(t.getId(), t); @@ -144,7 +144,7 @@ private void populateLookups() { } private List parseTables() { - List localTables = new ArrayList(); + List localTables = new ArrayList<>(); List lines = IOUtils.getList(is); Integer id = null; String name, aa, starts, baseone, basetwo, basethree; @@ -158,24 +158,26 @@ private List parseTables() { } else { String[] keyValue = line.split("\\s*=\\s*"); - if (keyValue[0].equals("AAs")) { - aa = keyValue[1]; - } - else if (keyValue[0].equals("Starts")) { - starts = keyValue[1]; - } - else if (keyValue[0].equals("Base1")) { - baseone = keyValue[1]; - } - else if (keyValue[0].equals("Base2")) { - basetwo = keyValue[1]; - } - else if (keyValue[0].equals("Base3")) { - basethree = keyValue[1]; - } - else { - name = keyValue[0]; - id = Integer.parseInt(keyValue[1]); + switch (keyValue[0]) { + case "AAs": + aa = keyValue[1]; + break; + case "Starts": + starts = keyValue[1]; + break; + case "Base1": + baseone = keyValue[1]; + break; + case "Base2": + basetwo = keyValue[1]; + break; + case "Base3": + basethree = keyValue[1]; + break; + default: + name = keyValue[0]; + id = Integer.parseInt(keyValue[1]); + break; } } } @@ -198,7 +200,7 @@ public static class IUPACTable implements Table { private final String baseTwo; private final String baseThree; - private final List codons = new ArrayList(); + private final List codons = new ArrayList<>(); private CompoundSet compounds = null; public IUPACTable(String name, int id, String aminoAcidString, @@ -328,7 +330,7 @@ public CompoundSet getCodonCompoundSet( } private List> codonStrings() { - List> codons = new ArrayList>(); + List> codons = new ArrayList<>(); for (int i = 0; i < baseOne.length(); i++) { List codon = Arrays.asList(Character .toString(baseOne.charAt(i)), @@ -348,7 +350,7 @@ private List startCodons() { } private List split(String string) { - List split = new ArrayList(); + List split = new ArrayList<>(); for (int i = 0; i < string.length(); i++) { split.add(Character.toString(string.charAt(i))); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/ProteinSequenceCreator.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/ProteinSequenceCreator.java index c40e3efa2a..fe9e7cba9d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/ProteinSequenceCreator.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/ProteinSequenceCreator.java @@ -42,7 +42,7 @@ public class ProteinSequenceCreator implements SequenceCreatorInterface { - private CompoundSet compoundSet; + private final CompoundSet compoundSet; /** * * @param compoundSet @@ -70,7 +70,7 @@ public AbstractSequence getSequence(String sequence, @Override public AbstractSequence getSequence( List list) { - ArrayListProxySequenceReader store = new ArrayListProxySequenceReader(); + ArrayListProxySequenceReader store = new ArrayListProxySequenceReader<>(); store.setCompoundSet(compoundSet); store.setContents(list); return new ProteinSequence(store); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/RNASequenceCreator.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/RNASequenceCreator.java index 96abe9cd35..32d20da1ee 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/RNASequenceCreator.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/RNASequenceCreator.java @@ -78,7 +78,7 @@ public AbstractSequence getSequence( @Override public AbstractSequence getSequence(List list) { ArrayListProxySequenceReader store = - new ArrayListProxySequenceReader(); + new ArrayListProxySequenceReader<>(); store.setCompoundSet(compoundSet); store.setContents(list); return new RNASequence(store); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/embl/EmblReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/embl/EmblReader.java index 45e50cd9ea..18f2db965e 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/embl/EmblReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/embl/EmblReader.java @@ -21,7 +21,10 @@ package org.biojava.nbio.core.sequence.io.embl; -import java.io.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; import java.util.Arrays; import java.util.LinkedList; @@ -46,7 +49,7 @@ public class EmblReader { public static EmblRecord process(File file) throws IOException { EmblRecord emblRecord = new EmblRecord(); - StringBuilder sequence = new StringBuilder(""); + StringBuilder sequence = new StringBuilder(); LinkedList emblReferences = new LinkedList<>(); EmblReference emblReference = new EmblReference(); LinkedList accessionNumber = new LinkedList<>(); @@ -59,13 +62,13 @@ public static EmblRecord process(File file) throws IOException { throw new IllegalArgumentException("the file can't be a directory"); try (FileReader fileReader = new FileReader(file)) { - String line = ""; + String line; String lineIdentifier; String lineInfo; try (BufferedReader bufferedReader = new BufferedReader(fileReader)) { while ((line = bufferedReader.readLine()) != null) { if (line.length() > 1) { - lineInfo = line.substring(2, line.length()).trim(); + lineInfo = line.substring(2).trim(); lineIdentifier = line.substring(0, 2); if (lineIdentifier.equals("ID")) emblRecord.setEmblId(populateID(lineInfo)); @@ -129,22 +132,30 @@ private static void populateSequence(String line, StringBuilder sequence) { private static void populateEmblReferences(String lineIdentifier, String lineInfo, EmblReference emblReference , LinkedList emblReferences) { - if (lineIdentifier.equals("RN")) - emblReference.setReferenceNumber(lineInfo); - else if (lineIdentifier.equals("RP")) - emblReference.setReferencePosition(lineInfo); - else if (lineIdentifier.equals("RX")) - emblReference.setReferenceCrossReference(lineInfo); - else if (lineIdentifier.equals("RG")) - emblReference.setReferenceGroup(lineInfo); - else if (lineIdentifier.equals("RA")) - emblReference.setReferenceAuthor(lineInfo); - else if (lineIdentifier.equals("RT")) - emblReference.setReferenceTitle(lineInfo); - else if (lineIdentifier.equals("RL")) { - emblReference.setReferenceLocation(lineInfo); - emblReferences.add(emblReference.copyEmblReference(emblReference)); - } + switch (lineIdentifier) { + case "RN": + emblReference.setReferenceNumber(lineInfo); + break; + case "RP": + emblReference.setReferencePosition(lineInfo); + break; + case "RX": + emblReference.setReferenceCrossReference(lineInfo); + break; + case "RG": + emblReference.setReferenceGroup(lineInfo); + break; + case "RA": + emblReference.setReferenceAuthor(lineInfo); + break; + case "RT": + emblReference.setReferenceTitle(lineInfo); + break; + case "RL": + emblReference.setReferenceLocation(lineInfo); + emblReferences.add(emblReference.copyEmblReference(emblReference)); + break; + } } private static void populateAccessionNumber(String line, LinkedList accessionNumber) { diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/FastaHeaderFormatInterface.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/FastaHeaderFormatInterface.java index a0bb6af6d3..5b1937a2d5 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/FastaHeaderFormatInterface.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/FastaHeaderFormatInterface.java @@ -35,5 +35,5 @@ public interface FastaHeaderFormatInterface, C extends Com * @param sequence * @return */ - public String getHeader(S sequence); + String getHeader(S sequence); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/GenbankHeaderFormatInterface.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/GenbankHeaderFormatInterface.java index 5e08a424bf..6556845f08 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/GenbankHeaderFormatInterface.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/GenbankHeaderFormatInterface.java @@ -36,8 +36,8 @@ public interface GenbankHeaderFormatInterface, C extends C * @param sequence * @return */ - public static final String UNKNOWN_DNA = "UNK"; + String UNKNOWN_DNA = "UNK"; - public String getHeader(S sequence); + String getHeader(S sequence); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceCreatorInterface.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceCreatorInterface.java index 9ec26dc225..0f9730decd 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceCreatorInterface.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceCreatorInterface.java @@ -43,7 +43,7 @@ public interface SequenceCreatorInterface { * @throws CompoundNotFoundException * @throws IOException */ - public AbstractSequence getSequence(String sequence, long index) throws CompoundNotFoundException, IOException; + AbstractSequence getSequence(String sequence, long index) throws CompoundNotFoundException, IOException; /** * @@ -51,13 +51,13 @@ public interface SequenceCreatorInterface { * @param index * @return */ - public AbstractSequence getSequence(ProxySequenceReader proxyLoader, long index); + AbstractSequence getSequence(ProxySequenceReader proxyLoader, long index); /** * * @param list * @return */ - public AbstractSequence getSequence(List list); + AbstractSequence getSequence(List list); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceHeaderParserInterface.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceHeaderParserInterface.java index dba9d7ca3d..f501543176 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceHeaderParserInterface.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceHeaderParserInterface.java @@ -35,5 +35,5 @@ public interface SequenceHeaderParserInterface, C extends * @param header * @param sequence */ - public void parseHeader(String header, S sequence); + void parseHeader(String header, S sequence); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceParserInterface.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceParserInterface.java index fd536e2802..af982f4846 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceParserInterface.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/template/SequenceParserInterface.java @@ -37,5 +37,5 @@ public interface SequenceParserInterface { * @return * @throws Exception */ - public String getSequence(BufferedReader bufferedReader,int sequenceLength) throws IOException; + String getSequence(BufferedReader bufferedReader, int sequenceLength) throws IOException; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/util/IOUtils.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/util/IOUtils.java index a798fcc6c3..19547a7ba8 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/util/IOUtils.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/io/util/IOUtils.java @@ -70,7 +70,7 @@ public static void close(Closeable c) { public static void copy(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[BUFFER]; - int n = 0; + int n; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); } @@ -110,13 +110,8 @@ public static void processReader(BufferedReader br, ReaderProcessor processor) t * @throws ParserException Can throw this if we cannot parse the given reader */ public static List getList(BufferedReader br) throws ParserException { - final List list = new ArrayList(); - processReader(br, new ReaderProcessor() { - @Override - public void process(String line) { - list.add(line); - } - }); + final List list = new ArrayList<>(); + processReader(br, list::add); return list; } @@ -183,8 +178,8 @@ public static InputStream openFile(File file) throws IOException { * * @author ayates */ - public static interface ReaderProcessor { - void process(String line) throws IOException; + public interface ReaderProcessor { + void process(String line); } /** @@ -330,15 +325,10 @@ public static String getPDBLegend() { * @throws IOException If any I/O exception occurs while printing; this method does not catch any exceptions */ public static void print(String string, File file) throws IOException { - PrintWriter out = null; - try { - out = new PrintWriter(new BufferedWriter(new FileWriter(file))); + try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)))) { out.print(string); out.flush(); - out.close(); - } finally { - if (out != null) out.close(); - } + } } } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/GenbankProxySequenceReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/GenbankProxySequenceReader.java index 2b74f9cacd..0e9b6b5ad1 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/GenbankProxySequenceReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/GenbankProxySequenceReader.java @@ -32,32 +32,22 @@ import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; import org.biojava.nbio.core.sequence.compound.DNACompoundSet; import org.biojava.nbio.core.sequence.compound.NucleotideCompound; -import org.biojava.nbio.core.sequence.features.AbstractFeature; -import org.biojava.nbio.core.sequence.features.DBReferenceInfo; -import org.biojava.nbio.core.sequence.features.DatabaseReferenceInterface; -import org.biojava.nbio.core.sequence.features.FeatureRetriever; -import org.biojava.nbio.core.sequence.features.FeaturesKeyWordInterface; +import org.biojava.nbio.core.sequence.features.*; import org.biojava.nbio.core.sequence.io.GenbankSequenceParser; import org.biojava.nbio.core.sequence.io.GenericGenbankHeaderParser; import org.biojava.nbio.core.sequence.template.AbstractSequence; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.CompoundSet; +import org.biojava.nbio.core.util.Download; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.BufferedInputStream; import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; import java.net.URL; -import java.net.URLConnection; import java.util.ArrayList; -import java.util.HashMap; import java.util.LinkedHashMap; +import java.util.Map; /** * @author Karl Nicholas @@ -68,36 +58,49 @@ public class GenbankProxySequenceReader extends StringProxyS private static final Logger logger = LoggerFactory.getLogger(GenbankProxySequenceReader.class); private static final String eutilBaseURL = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/"; // - private String genbankDirectoryCache = null; - private GenbankSequenceParser, C> genbankParser; - private GenericGenbankHeaderParser, C> headerParser; - private String header; - private HashMap> features; +// logger.trace("Loading: {}", genbankURL); +// URL genbank = new URL(genbankURL); +// inStream1 = new BufferedInputStream(genbank.openConnection().getInputStream()); +// } + // private String genbankDirectoryCache = null; + private final GenbankSequenceParser, C> genbankParser = new GenbankSequenceParser<>(); + private final GenericGenbankHeaderParser, C> headerParser; + private final String header; + private final Map> features; /** * - * @throws InterruptedException * @throws IOException * @throws CompoundNotFoundException */ - public GenbankProxySequenceReader( - String genbankDirectoryCache, - String accessionID, - CompoundSet compoundSet ) throws IOException, InterruptedException, CompoundNotFoundException { + public GenbankProxySequenceReader(String accessionID, CompoundSet compoundSet) throws IOException, CompoundNotFoundException { - setGenbankDirectoryCache(genbankDirectoryCache); +// setGenbankDirectoryCache(genbankDirectoryCache); setCompoundSet(compoundSet); String db = compoundSet instanceof AminoAcidCompoundSet ? "protein" : "nuccore"; - InputStream inStream = getBufferedInputStream(accessionID, db); - genbankParser = new GenbankSequenceParser, C>(); +// BufferedInputStream inStream1; +// if (genbankDirectoryCache != null && genbankDirectoryCache.length() > 0) { +// File f = new File(genbankDirectoryCache + File.separatorChar + accessionID + ".gb"); +// if (f.exists()) { +// logger.debug("Reading: {}", f.toString()); +// inStream1 = new BufferedInputStream(new FileInputStream(f)); +// } else { +// InputStream in = getEutilsInputStream(accessionID, db); +// copyInputStreamToFile(in, f); +// inStream1 = new BufferedInputStream(new FileInputStream(f)); +// } +// } else { + String genbankURL = eutilBaseURL + "efetch.fcgi?db=" + db + "&id=" + accessionID + "&rettype=gb&retmode=text"; - setContents(genbankParser.getSequence(new BufferedReader(new InputStreamReader(inStream)), 0)); - headerParser = genbankParser.getSequenceHeaderParser(); - header = genbankParser.getHeader(); - features = genbankParser.getFeatures(); + try (BufferedReader r = Download.bufferedReader(new URL(genbankURL))) { + setContents(genbankParser.getSequence(r, 0)); + headerParser = genbankParser.getSequenceHeaderParser(); + header = genbankParser.getHeader(); + features = genbankParser.getFeatures(); + } if (compoundSet.getClass().equals(AminoAcidCompoundSet.class)) { if (!genbankParser.getCompoundType().equals(compoundSet)) { @@ -105,74 +108,46 @@ public GenbankProxySequenceReader( throw new IOException("Wrong declared compound type for: " + accessionID); } } - - inStream.close(); - } - - private BufferedInputStream getBufferedInputStream(String accessionID, String db) throws IOException, InterruptedException { - BufferedInputStream inStream = null; - if (genbankDirectoryCache != null && genbankDirectoryCache.length() > 0) { - File f = new File(genbankDirectoryCache + File.separatorChar + accessionID + ".gb"); - if (f.exists()) { - logger.debug("Reading: {}", f.toString()); - inStream = new BufferedInputStream(new FileInputStream(f)); - } else { - InputStream in = getEutilsInputStream(accessionID, db); - copyInputStreamToFile(in, f); - inStream = new BufferedInputStream(new FileInputStream(f)); - } - } else { - inStream = new BufferedInputStream(getEutilsInputStream(accessionID, db)); - } - return inStream; - } - - private void copyInputStreamToFile(InputStream in, File f) throws IOException, InterruptedException { - FileOutputStream out = new FileOutputStream(f); - byte[] buffer = new byte[1024]; - int len = in.read(buffer); - while (len != -1) { - out.write(buffer, 0, len); - len = in.read(buffer); - if (Thread.interrupted()) { - in.close(); - out.close(); - throw new InterruptedException(); - } - } - in.close(); - out.close(); - } - - private InputStream getEutilsInputStream(String accessionID, String db) throws IOException { - String genbankURL = eutilBaseURL + "efetch.fcgi?db=" + db + "&id=" + accessionID + "&rettype=gb&retmode=text"; - logger.trace("Loading: {}", genbankURL); - URL genbank = new URL(genbankURL); - URLConnection genbankConnection = genbank.openConnection(); - return genbankConnection.getInputStream(); } - /** - * Local directory cache of Genbank that can be downloaded - * - * @return the uniprotDirectoryCache - */ - public String getGenbankDirectoryCache() { - return genbankDirectoryCache; - } - - /** - * @param genbankDirectoryCache - */ - public void setGenbankDirectoryCache(String genbankDirectoryCache) { - if (genbankDirectoryCache != null) { - File f = new File(genbankDirectoryCache); - if (!f.exists()) { - f.mkdirs(); - } - } - this.genbankDirectoryCache = genbankDirectoryCache; - } +// private void copyInputStreamToFile(InputStream in, File f) throws IOException, InterruptedException { +// FileOutputStream out = new FileOutputStream(f); +// byte[] buffer = new byte[1024]; +// int len = in.read(buffer); +// while (len != -1) { +// out.write(buffer, 0, len); +// len = in.read(buffer); +// if (Thread.interrupted()) { +// in.close(); +// out.close(); +// throw new InterruptedException(); +// } +// } +// in.close(); +// out.close(); +// } + + // /** +// * Local directory cache of Genbank that can be downloaded +// * +// * @return the uniprotDirectoryCache +// */ +// public String getGenbankDirectoryCache() { +// return genbankDirectoryCache; +// } +// +// /** +// * @param genbankDirectoryCache +// */ +// public void setGenbankDirectoryCache(String genbankDirectoryCache) { +// if (genbankDirectoryCache != null) { +// File f = new File(genbankDirectoryCache); +// if (!f.exists()) { +// f.mkdirs(); +// } +// } +// this.genbankDirectoryCache = genbankDirectoryCache; +// } public String getHeader() { return header; @@ -182,7 +157,7 @@ public GenericGenbankHeaderParser, C> getHeaderParser() { return headerParser; } @Override - public HashMap> getFeatures() { + public Map> getFeatures() { return features; } @@ -198,8 +173,8 @@ public ArrayList getKeyWords() { public static void main(String[] args) throws Throwable { - GenbankProxySequenceReader genbankProteinReader - = new GenbankProxySequenceReader("/tmp", "NP_000257", AminoAcidCompoundSet.getAminoAcidCompoundSet()); + GenbankProxySequenceReader genbankProteinReader + = new GenbankProxySequenceReader<>("NP_000257", AminoAcidCompoundSet.aminoAcidCompoundSet); ProteinSequence proteinSequence = new ProteinSequence(genbankProteinReader); genbankProteinReader.getHeaderParser().parseHeader(genbankProteinReader.getHeader(), proteinSequence); logger.info("Sequence ({},{})={}...", proteinSequence.getAccession(), proteinSequence.getLength(), proteinSequence.getSequenceAsString().substring(0, 10)); @@ -208,16 +183,18 @@ public static void main(String[] args) throws Throwable { proteinSequence.getFeatures(); GenbankProxySequenceReader genbankDNAReader - = new GenbankProxySequenceReader("/tmp", "NM_001126", DNACompoundSet.getDNACompoundSet()); + = new GenbankProxySequenceReader<>("NM_001126", DNACompoundSet.getDNACompoundSet()); DNASequence dnaSequence = new DNASequence(genbankDNAReader); genbankDNAReader.getHeaderParser().parseHeader(genbankDNAReader.getHeader(), dnaSequence); dnaSequence.setAccession(new AccessionID("NM_001126")); - logger.info("Sequence ({},{})={}...", dnaSequence.getAccession(), dnaSequence.getLength(), dnaSequence.getSequenceAsString().substring(0, 10)); - logger.info("Keywords: {}", genbankDNAReader.getKeyWords()); - logger.info("DatabaseReferences: {}", genbankDNAReader.getDatabaseReferences()); + if (logger.isInfoEnabled()) { + logger.info("Sequence ({},{})={}...", dnaSequence.getAccession(), dnaSequence.getLength(), dnaSequence.getSequenceAsString().substring(0, 10)); + logger.info("Keywords: {}", genbankDNAReader.getKeyWords()); + logger.info("DatabaseReferences: {}", genbankDNAReader.getDatabaseReferences()); + } genbankDNAReader - = new GenbankProxySequenceReader("/tmp", "NM_000266", DNACompoundSet.getDNACompoundSet()); + = new GenbankProxySequenceReader<>("NM_000266", DNACompoundSet.getDNACompoundSet()); dnaSequence = new DNASequence(genbankDNAReader); genbankDNAReader.getHeaderParser().parseHeader(genbankDNAReader.getHeader(), dnaSequence); logger.info("Sequence ({},{})={}...", dnaSequence.getAccession(), dnaSequence.getLength(), dnaSequence.getSequenceAsString().substring(0, 10)); @@ -225,7 +202,7 @@ public static void main(String[] args) throws Throwable { logger.info("DatabaseReferences: {}", genbankDNAReader.getDatabaseReferences()); genbankDNAReader - = new GenbankProxySequenceReader("/tmp", "AV254721", DNACompoundSet.getDNACompoundSet()); + = new GenbankProxySequenceReader<>("AV254721", DNACompoundSet.getDNACompoundSet()); dnaSequence = new DNASequence(genbankDNAReader); genbankDNAReader.getHeaderParser().parseHeader(genbankDNAReader.getHeader(), dnaSequence); logger.info("Sequence ({},{})={}...", dnaSequence.getAccession(), dnaSequence.getLength(), dnaSequence.getSequenceAsString().substring(0, 10)); @@ -233,7 +210,7 @@ public static void main(String[] args) throws Throwable { logger.info("DatabaseReferences: {}", genbankDNAReader.getDatabaseReferences()); genbankDNAReader - = new GenbankProxySequenceReader("/tmp", "AV254721.2", DNACompoundSet.getDNACompoundSet()); + = new GenbankProxySequenceReader<>("AV254721.2", DNACompoundSet.getDNACompoundSet()); dnaSequence = new DNASequence(genbankDNAReader); genbankDNAReader.getHeaderParser().parseHeader(genbankDNAReader.getHeader(), dnaSequence); logger.info("Sequence ({},{})={}...", dnaSequence.getAccession(), dnaSequence.getLength(), dnaSequence.getSequenceAsString().substring(0, 10)); @@ -241,7 +218,7 @@ public static void main(String[] args) throws Throwable { logger.info("DatabaseReferences: {}", genbankDNAReader.getDatabaseReferences()); genbankDNAReader - = new GenbankProxySequenceReader("/tmp", "U49845", DNACompoundSet.getDNACompoundSet()); + = new GenbankProxySequenceReader<>("U49845", DNACompoundSet.getDNACompoundSet()); dnaSequence = new DNASequence(genbankDNAReader); genbankDNAReader.getHeaderParser().parseHeader(genbankDNAReader.getHeader(), dnaSequence); logger.info("Sequence ({},{})={}...", dnaSequence.getAccession(), dnaSequence.getLength(), dnaSequence.getSequenceAsString().substring(0, 10)); @@ -249,7 +226,7 @@ public static void main(String[] args) throws Throwable { logger.info("DatabaseReferences: {}", genbankDNAReader.getDatabaseReferences()); genbankDNAReader - = new GenbankProxySequenceReader("/tmp", "GI:1293613", DNACompoundSet.getDNACompoundSet()); + = new GenbankProxySequenceReader<>("GI:1293613", DNACompoundSet.getDNACompoundSet()); dnaSequence = new DNASequence(genbankDNAReader); genbankDNAReader.getHeaderParser().parseHeader(genbankDNAReader.getHeader(), dnaSequence); logger.info("Sequence ({},{})={}...", dnaSequence.getAccession(), dnaSequence.getLength(), dnaSequence.getSequenceAsString().substring(0, 10)); @@ -257,7 +234,7 @@ public static void main(String[] args) throws Throwable { logger.info("DatabaseReferences: {}", genbankDNAReader.getDatabaseReferences()); genbankDNAReader - = new GenbankProxySequenceReader("/tmp", "14109166", DNACompoundSet.getDNACompoundSet()); + = new GenbankProxySequenceReader<>("14109166", DNACompoundSet.getDNACompoundSet()); dnaSequence = new DNASequence(genbankDNAReader); genbankDNAReader.getHeaderParser().parseHeader(genbankDNAReader.getHeader(), dnaSequence); logger.info("Sequence ({},{})={}...", dnaSequence.getAccession(), dnaSequence.getLength(), dnaSequence.getSequenceAsString().substring(0, 10)); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/SequenceFileProxyLoader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/SequenceFileProxyLoader.java index 78c08b7795..61b605c1fb 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/SequenceFileProxyLoader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/SequenceFileProxyLoader.java @@ -55,12 +55,12 @@ */ public class SequenceFileProxyLoader implements ProxySequenceReader { - SequenceParserInterface sequenceParser; + final SequenceParserInterface sequenceParser; private CompoundSet compoundSet; - private List parsedCompounds = new ArrayList(); - File file; - long sequenceStartIndex = -1; - int sequenceLength = -1; + private final List parsedCompounds = new ArrayList<>(); + final File file; + final long sequenceStartIndex; + final int sequenceLength; //private boolean initialized = false; /** @@ -97,7 +97,7 @@ public void setCompoundSet(CompoundSet compoundSet) { * Load the sequence * @return */ - private boolean init() throws IOException, CompoundNotFoundException { + private boolean init() throws IOException { BufferedReader br = new BufferedReader(new FileReader(file)); br.skip(sequenceStartIndex); @@ -204,7 +204,7 @@ public String getSequenceAsString() { */ public String getSequenceAsString(Integer bioBegin, Integer bioEnd, Strand strand) { - SequenceAsStringHelper sequenceAsStringHelper = new SequenceAsStringHelper(); + SequenceAsStringHelper sequenceAsStringHelper = new SequenceAsStringHelper<>(); return sequenceAsStringHelper.getSequenceAsString(this.parsedCompounds, compoundSet, bioBegin, bioEnd, strand); } @@ -260,7 +260,7 @@ public int hashCode(){ @Override public SequenceView getSubSequence(final Integer bioBegin, final Integer bioEnd) { - return new SequenceProxyView(SequenceFileProxyLoader.this, bioBegin, bioEnd); + return new SequenceProxyView<>(SequenceFileProxyLoader.this, bioBegin, bioEnd); } /** @@ -296,8 +296,9 @@ public AccessionID getAccession() { * @param compounds * @return */ + @SafeVarargs @Override - public int countCompounds(C... compounds) { + public final int countCompounds(C... compounds) { return SequenceMixin.countCompounds(this, compounds); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/StringProxySequenceReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/StringProxySequenceReader.java index 57c793ddc1..f643c0335d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/StringProxySequenceReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/StringProxySequenceReader.java @@ -46,7 +46,7 @@ public class StringProxySequenceReader implements ProxySeque private String sequence; private CompoundSet compoundSet; - private List parsedCompounds = new ArrayList(); + private final List parsedCompounds = new ArrayList<>(); public StringProxySequenceReader() {} @@ -63,11 +63,15 @@ public void setCompoundSet(CompoundSet compoundSet) { @Override public void setContents(String sequence) throws CompoundNotFoundException { + if (sequence == null) + throw new CompoundNotFoundException("null sequence: " + sequence); + // Horrendously inefficient - pretty much the way the old BJ did things. // TODO Should be optimised. this.sequence = sequence; this.parsedCompounds.clear(); - for (int i = 0; i < sequence.length();) { + int l = sequence.length(); + for (int i = 0; i < l;) { String compoundStr = null; C compound = null; for (int compoundStrLength = 1; compound == null && compoundStrLength <= compoundSet.getMaxSingleCompoundStringLength(); compoundStrLength++) { @@ -126,13 +130,13 @@ public List getAsList() { public String getSequenceAsString(Integer bioBegin, Integer bioEnd,Strand strand) { - SequenceAsStringHelper sequenceAsStringHelper = new SequenceAsStringHelper(); + SequenceAsStringHelper sequenceAsStringHelper = new SequenceAsStringHelper<>(); return sequenceAsStringHelper.getSequenceAsString(this.parsedCompounds, compoundSet, bioBegin, bioEnd, strand); } @Override public SequenceView getSubSequence(final Integer bioBegin, final Integer bioEnd) { - return new SequenceProxyView(StringProxySequenceReader.this,bioBegin,bioEnd); + return new SequenceProxyView<>(StringProxySequenceReader.this, bioBegin, bioEnd); } @Override @@ -152,8 +156,9 @@ public AccessionID getAccession() { } + @SafeVarargs @Override - public int countCompounds(C... compounds) { + public final int countCompounds(C... compounds) { throw new UnsupportedOperationException("Not supported yet."); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/UniprotProxySequenceReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/UniprotProxySequenceReader.java index f7f51d89bb..05ab1c8c5f 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/UniprotProxySequenceReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/loader/UniprotProxySequenceReader.java @@ -50,10 +50,7 @@ import java.net.HttpURLConnection; import java.net.URL; import java.rmi.RemoteException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; +import java.util.*; import java.util.regex.Pattern; /** @@ -82,7 +79,7 @@ public class UniprotProxySequenceReader implements ProxySequ private static String uniprotDirectoryCache = null; private String sequence; private CompoundSet compoundSet; - private List parsedCompounds = new ArrayList(); + private final List parsedCompounds = new ArrayList<>(); Document uniprotDoc; /** @@ -128,7 +125,7 @@ public UniprotProxySequenceReader(Document document, CompoundSet compoundSet) public static UniprotProxySequenceReader parseUniprotXMLString(String xml, CompoundSet compoundSet) { try { Document document = XMLHelper.inputStreamToDocument(new ByteArrayInputStream(xml.getBytes())); - return new UniprotProxySequenceReader(document, compoundSet); + return new UniprotProxySequenceReader<>(document, compoundSet); } catch (Exception e) { logger.error("Exception on xml parse of: {}", xml); } @@ -284,7 +281,7 @@ public SequenceView getInverse() { * @return */ public String getSequenceAsString(Integer bioBegin, Integer bioEnd, Strand strand) { - SequenceAsStringHelper sequenceAsStringHelper = new SequenceAsStringHelper(); + SequenceAsStringHelper sequenceAsStringHelper = new SequenceAsStringHelper<>(); return sequenceAsStringHelper.getSequenceAsString(this.parsedCompounds, compoundSet, bioBegin, bioEnd, strand); } @@ -296,7 +293,7 @@ public String getSequenceAsString(Integer bioBegin, Integer bioEnd, Strand stran */ @Override public SequenceView getSubSequence(final Integer bioBegin, final Integer bioEnd) { - return new SequenceProxyView(UniprotProxySequenceReader.this, bioBegin, bioEnd); + return new SequenceProxyView<>(UniprotProxySequenceReader.this, bioBegin, bioEnd); } /** @@ -344,14 +341,13 @@ public AccessionID getAccession() { * @throws XPathExpressionException */ public ArrayList getAccessions() throws XPathExpressionException { - ArrayList accessionList = new ArrayList(); + ArrayList accessionList = new ArrayList<>(); if (uniprotDoc == null) { return accessionList; } Element uniprotElement = uniprotDoc.getDocumentElement(); Element entryElement = XMLHelper.selectSingleElement(uniprotElement, "entry"); - ArrayList keyWordElementList = XMLHelper.selectElements(entryElement, "accession"); - for (Element element : keyWordElementList) { + for (Element element : XMLHelper.selectElements(entryElement, "accession")) { AccessionID accessionID = new AccessionID(element.getTextContent(), DataSource.UNIPROT); accessionList.add(accessionID); } @@ -366,75 +362,71 @@ public ArrayList getAccessions() throws XPathExpressionException { * @return * @throws XPathExpressionException */ - public ArrayList getAliases() throws XPathExpressionException { + public List getAliases() throws XPathExpressionException { return getProteinAliases(); } + /** * Pull uniprot protein aliases associated with this sequence * @return * @throws XPathExpressionException */ - public ArrayList getProteinAliases() throws XPathExpressionException { - ArrayList aliasList = new ArrayList(); - if (uniprotDoc == null) { - return aliasList; - } + public List getProteinAliases() throws XPathExpressionException { + if (uniprotDoc == null) + return Collections.EMPTY_LIST; + + ArrayList a = new ArrayList<>(); + Element uniprotElement = uniprotDoc.getDocumentElement(); Element entryElement = XMLHelper.selectSingleElement(uniprotElement, "entry"); Element proteinElement = XMLHelper.selectSingleElement(entryElement, "protein"); - ArrayList keyWordElementList; - getProteinAliasesFromNameGroup(aliasList, proteinElement); + + getProteinAliasesFromNameGroup(a, proteinElement); - keyWordElementList = XMLHelper.selectElements(proteinElement, "component"); - for (Element element : keyWordElementList) { - getProteinAliasesFromNameGroup(aliasList, element); + + for (Element element : XMLHelper.selectElements(proteinElement, "component")) { + getProteinAliasesFromNameGroup(a, element); } - keyWordElementList = XMLHelper.selectElements(proteinElement, "domain"); - for (Element element : keyWordElementList) { - getProteinAliasesFromNameGroup(aliasList, element); + for (Element element : XMLHelper.selectElements(proteinElement, "domain")) { + getProteinAliasesFromNameGroup(a, element); } - keyWordElementList = XMLHelper.selectElements(proteinElement, "submittedName"); - for (Element element : keyWordElementList) { - getProteinAliasesFromNameGroup(aliasList, element); + for (Element element : XMLHelper.selectElements(proteinElement, "submittedName")) { + getProteinAliasesFromNameGroup(a, element); } - keyWordElementList = XMLHelper.selectElements(proteinElement, "cdAntigenName"); - for (Element element : keyWordElementList) { + for (Element element : XMLHelper.selectElements(proteinElement, "cdAntigenName")) { String cdAntigenName = element.getTextContent(); if(null != cdAntigenName && !cdAntigenName.trim().isEmpty()) { - aliasList.add(cdAntigenName); + a.add(cdAntigenName); } } - - keyWordElementList = XMLHelper.selectElements(proteinElement, "innName"); - for (Element element : keyWordElementList) { + + for (Element element : XMLHelper.selectElements(proteinElement, "innName")) { String cdAntigenName = element.getTextContent(); if(null != cdAntigenName && !cdAntigenName.trim().isEmpty()) { - aliasList.add(cdAntigenName); + a.add(cdAntigenName); } } - keyWordElementList = XMLHelper.selectElements(proteinElement, "biotechName"); - for (Element element : keyWordElementList) { + for (Element element : XMLHelper.selectElements(proteinElement, "biotechName")) { String cdAntigenName = element.getTextContent(); if(null != cdAntigenName && !cdAntigenName.trim().isEmpty()) { - aliasList.add(cdAntigenName); + a.add(cdAntigenName); } } - keyWordElementList = XMLHelper.selectElements(proteinElement, "allergenName"); - for (Element element : keyWordElementList) { + for (Element element : XMLHelper.selectElements(proteinElement, "allergenName")) { String cdAntigenName = element.getTextContent(); if(null != cdAntigenName && !cdAntigenName.trim().isEmpty()) { - aliasList.add(cdAntigenName); + a.add(cdAntigenName); } } - return aliasList; + return a; } /** @@ -444,15 +436,11 @@ public ArrayList getProteinAliases() throws XPathExpressionException { */ private void getProteinAliasesFromNameGroup(ArrayList aliasList, Element proteinElement) throws XPathExpressionException { - ArrayList keyWordElementList = XMLHelper.selectElements(proteinElement, "alternativeName"); - for (Element element : keyWordElementList) { - getProteinAliasesFromElement(aliasList, element); - } - - keyWordElementList = XMLHelper.selectElements(proteinElement, "recommendedName"); - for (Element element : keyWordElementList) { - getProteinAliasesFromElement(aliasList, element); - } + for (Element e : XMLHelper.selectElements(proteinElement, "alternativeName")) + getProteinAliasesFromElement(aliasList, e); + + for (Element e : XMLHelper.selectElements(proteinElement, "recommendedName")) + getProteinAliasesFromElement(aliasList, e); } /** @@ -479,15 +467,15 @@ private void getProteinAliasesFromElement(ArrayList aliasList, Element e * @throws XPathExpressionException */ public ArrayList getGeneAliases() throws XPathExpressionException { - ArrayList aliasList = new ArrayList(); + ArrayList aliasList = new ArrayList<>(); if (uniprotDoc == null) { return aliasList; } Element uniprotElement = uniprotDoc.getDocumentElement(); Element entryElement = XMLHelper.selectSingleElement(uniprotElement, "entry"); - ArrayList proteinElements = XMLHelper.selectElements(entryElement, "gene"); + List proteinElements = XMLHelper.selectElements(entryElement, "gene"); for(Element proteinElement : proteinElements) { - ArrayList keyWordElementList = XMLHelper.selectElements(proteinElement, "name"); + List keyWordElementList = XMLHelper.selectElements(proteinElement, "name"); for (Element element : keyWordElementList) { aliasList.add(element.getTextContent()); } @@ -500,8 +488,9 @@ public ArrayList getGeneAliases() throws XPathExpressionException { * @param compounds * @return */ + @SafeVarargs @Override - public int countCompounds(C... compounds) { + public final int countCompounds(C... compounds) { throw new UnsupportedOperationException("Not supported yet."); } @@ -511,7 +500,7 @@ public int countCompounds(C... compounds) { * @return * @throws IOException */ - private Document getUniprotXML(String accession) throws IOException, CompoundNotFoundException { + private Document getUniprotXML(String accession) throws IOException { StringBuilder sb = new StringBuilder(); // try in cache if (uniprotDirectoryCache != null && uniprotDirectoryCache.length() > 0) { @@ -538,9 +527,7 @@ private Document getUniprotXML(String accession) throws IOException, CompoundNot // logger.debug(sb.toString()); Document document = XMLHelper.inputStreamToDocument(new ByteArrayInputStream(sb.toString().getBytes())); return document; - } catch (SAXException e) { - logger.error("Exception on xml parse of: {}", sb.toString()); - } catch (ParserConfigurationException e) { + } catch (SAXException | ParserConfigurationException e) { logger.error("Exception on xml parse of: {}", sb.toString()); } return null; @@ -609,12 +596,12 @@ private static HttpURLConnection openURLConnection(URL url) throws IOException { } private StringBuilder fetchUniprotXML(String uniprotURL) - throws IOException, CompoundNotFoundException { + throws IOException { StringBuilder sb = new StringBuilder(); URL uniprot = new URL(uniprotURL); int attempt = 5; - List errorCodes = new ArrayList(); + List errorCodes = new ArrayList<>(); while(attempt > 0) { HttpURLConnection uniprotConnection = openURLConnection(uniprot); int statusCode = uniprotConnection.getResponseCode(); @@ -722,7 +709,7 @@ public static void setUniprotDirectoryCache(String aUniprotDirectoryCache) { public static void main(String[] args) { try { - UniprotProxySequenceReader uniprotSequence = new UniprotProxySequenceReader("YA745_GIBZE", AminoAcidCompoundSet.getAminoAcidCompoundSet()); + UniprotProxySequenceReader uniprotSequence = new UniprotProxySequenceReader<>("YA745_GIBZE", AminoAcidCompoundSet.aminoAcidCompoundSet); ProteinSequence proteinSequence = new ProteinSequence(uniprotSequence); logger.info("Accession: {}", proteinSequence.getAccession().getID()); logger.info("Sequence: {}", proteinSequence.getSequenceAsString()); @@ -790,22 +777,21 @@ public String getOrganismName() { * @return */ @Override - public ArrayList getKeyWords() { - ArrayList keyWordsList = new ArrayList(); - if (uniprotDoc == null) { - return keyWordsList; - } + public List getKeyWords() { + if (uniprotDoc == null) + return Collections.EMPTY_LIST; + + ArrayList keyWordsList = new ArrayList<>(); try { Element uniprotElement = uniprotDoc.getDocumentElement(); Element entryElement = XMLHelper.selectSingleElement(uniprotElement, "entry"); - ArrayList keyWordElementList = XMLHelper.selectElements(entryElement, "keyword"); - for (Element element : keyWordElementList) { + for (Element element : XMLHelper.selectElements(entryElement, "keyword")) keyWordsList.add(element.getTextContent()); - } + } catch (XPathExpressionException e) { logger.error("Problems while parsing keywords in UniProt XML: {}. No keywords will be available.",e.getMessage()); - return new ArrayList(); + return new ArrayList<>(); } return keyWordsList; @@ -817,7 +803,7 @@ public ArrayList getKeyWords() { */ @Override public LinkedHashMap> getDatabaseReferences() { - LinkedHashMap> databaseReferencesHashMap = new LinkedHashMap>(); + LinkedHashMap> databaseReferencesHashMap = new LinkedHashMap<>(); if (uniprotDoc == null) { return databaseReferencesHashMap; } @@ -825,28 +811,21 @@ public LinkedHashMap> getDatabaseReferences() try { Element uniprotElement = uniprotDoc.getDocumentElement(); Element entryElement = XMLHelper.selectSingleElement(uniprotElement, "entry"); - ArrayList dbreferenceElementList = XMLHelper.selectElements(entryElement, "dbReference"); - for (Element element : dbreferenceElementList) { + for (Element element : XMLHelper.selectElements(entryElement, "dbReference")) { String type = element.getAttribute("type"); String id = element.getAttribute("id"); - ArrayList idlist = databaseReferencesHashMap.get(type); - if (idlist == null) { - idlist = new ArrayList(); - databaseReferencesHashMap.put(type, idlist); - } + ArrayList idlist = databaseReferencesHashMap.computeIfAbsent(type, k -> new ArrayList<>()); DBReferenceInfo dbreferenceInfo = new DBReferenceInfo(type, id); - ArrayList propertyElementList = XMLHelper.selectElements(element, "property"); - for (Element propertyElement : propertyElementList) { - String propertyType = propertyElement.getAttribute("type"); - String propertyValue = propertyElement.getAttribute("value"); - dbreferenceInfo.addProperty(propertyType, propertyValue); - } + List propertyElementList = XMLHelper.selectElements(element, "property"); + + for (Element pe : propertyElementList) + dbreferenceInfo.addProperty(pe.getAttribute("type"), pe.getAttribute("value")); idlist.add(dbreferenceInfo); } } catch (XPathExpressionException e) { logger.error("Problems while parsing db references in UniProt XML: {}. No db references will be available.",e.getMessage()); - return new LinkedHashMap>(); + return new LinkedHashMap<>(); } return databaseReferencesHashMap; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/FuzzyPoint.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/FuzzyPoint.java index 7a97c7ad1c..ea3ccad87d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/FuzzyPoint.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/FuzzyPoint.java @@ -25,6 +25,8 @@ import org.biojava.nbio.core.util.Equals; import org.biojava.nbio.core.util.Hashcoder; +import java.util.Objects; + /** * Implementation for resolving fuzzy locations. Caches the calculated * value. @@ -36,32 +38,17 @@ public class FuzzyPoint extends SimplePoint { /** * Always uses the min point to resolve a location */ - public static final Resolver MIN_RESOLVER = new Resolver() { - @Override - public int resolve(FuzzyPoint point) { - return point.getMin(); - } - }; + public static final Resolver MIN_RESOLVER = FuzzyPoint::getMin; /** * Always uses the max point to resolve a location */ - public static final Resolver MAX_RESOLVER = new Resolver() { - @Override - public int resolve(FuzzyPoint point) { - return point.getMax(); - } - }; + public static final Resolver MAX_RESOLVER = FuzzyPoint::getMax; /** * Combines min and max and then gets the mean of it */ - public static final Resolver MEAN_RESOLVER = new Resolver() { - @Override - public int resolve(FuzzyPoint point) { - return (point.getMin() + point.getMax()) / 2; - } - }; + public static final Resolver MEAN_RESOLVER = point -> (point.getMin() + point.getMax()) / 2; private final int min; private final int max; @@ -85,11 +72,14 @@ public FuzzyPoint(int minPoint, int maxPoint, Resolver resolver, boo } @Override - public Integer getPosition() { - if(super.getPosition() == -1) { - super.setPosition(getResolver().resolve(this)); - } - return super.getPosition(); + public int getPosition() { + int prevPos = super.getPosition(); + if(prevPos == -1) { + int nextPos = getResolver().resolve(this); + super.setPosition(nextPos); + return nextPos; + } else + return prevPos; } protected Integer getMax() { @@ -121,13 +111,14 @@ public Point offset(int distance) { @Override public boolean equals(Object obj) { + if (this == obj) return true; boolean equals = false; if (Equals.classEqual(this, obj)) { FuzzyPoint p = (FuzzyPoint) obj; - equals = (Equals.equal(getMin(), p.getMin()) - && Equals.equal(getMax(), p.getMax()) - && Equals.equal(isUnknown(), p.isUnknown()) - && Equals.equal(isUncertain(), p.isUncertain()) + equals = (Objects.equals(getMin(), p.getMin()) + && Objects.equals(getMax(), p.getMax()) + && isUnknown() == p.isUnknown() + && isUncertain() == p.isUncertain() ); } return equals; @@ -145,6 +136,7 @@ public int hashCode() { @Override public int compareTo(Point point) { + if (this == point) return 0; //If we can assign this to a FuzzyPoint then work with a bit more info if(FuzzyPoint.class.isAssignableFrom(point.getClass())) { FuzzyPoint fuzzy = (FuzzyPoint)point; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/InsdcParser.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/InsdcParser.java index 2e8217ea43..53028b338b 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/InsdcParser.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/InsdcParser.java @@ -32,7 +32,6 @@ import org.biojava.nbio.core.sequence.template.AbstractSequence; import org.biojava.nbio.core.sequence.template.Compound; -import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; @@ -59,7 +58,7 @@ public class InsdcParser , C extends Compound>{ //protected static final Pattern singleLocationPattern = Pattern.compile("(?:[A-Z]([A-Za-z\\.0-9_]*?):)?(?)(\\d+)?(>?)?"); // fixed issue #254 - protected static final Pattern singleLocationPattern = Pattern.compile("(?:([A-Za-z\\.0-9_]*?):)?(?)(\\d+)?(>?)?"); + protected static final Pattern singleLocationPattern = Pattern.compile("(?:([A-Za-z.0-9_]*?):)?(?)(\\d+)?(>?)?"); /** * Decodes a split pattern. Split patterns are a composition of multiple * locationsString qualified by actions: join(location,location, ... @@ -96,11 +95,11 @@ public class InsdcParser , C extends Compound>{ protected Integer featureGlobalStart, featureGlobalEnd; //private S referenceSequence = new org.biojava.nbio.core.sequence.DNASequence(); - private AbstractSequence referenceSequence = new DNASequence(); + private final AbstractSequence referenceSequence = new DNASequence(); enum complexFeaturesAppendEnum { - FLATTEN, HIERARCHICAL; + FLATTEN, HIERARCHICAL } /** * define the mode in which complex features should be appended in FLATTEN @@ -160,17 +159,16 @@ public Location parse(String locationString) throws ParserException { * @param reader The source of the data; assumes that end of the reader * stream is the end of the location string to parse * @return The parsed location - * @throws IOException Thrown with any reader error * @throws ParserException Thrown with any error with parsing locations */ - public List parse(Reader reader) throws IOException, ParserException { + public List parse(Reader reader) throws ParserException { // use parse(String s) instead! return null; } private List parseLocationString(String string, int versus) throws ParserException { Matcher m; - List boundedLocationsCollection = new ArrayList(); + List boundedLocationsCollection = new ArrayList<>(); //String[] tokens = string.split(locationSplitPattern); List tokens = splitString(string); @@ -229,7 +227,7 @@ private List parseLocationString(String string, int versus) throws Par String accession = m.group(1); Strand s = versus == 1 ? Strand.POSITIVE : Strand.NEGATIVE; int start = Integer.parseInt(m.group(3)); - int end = m.group(6) == null ? start : new Integer(m.group(6)); + int end = m.group(6) == null ? start : Integer.parseInt(m.group(6)); if (featureGlobalStart > start) { featureGlobalStart = start; @@ -253,7 +251,7 @@ private List parseLocationString(String string, int versus) throws Par l.setPartialOn3prime(true); } - if (!(accession == null || "".equals(accession))) l.setAccession(new AccessionID(accession)); + if (!(accession == null || accession.isEmpty())) l.setAccession(new AccessionID(accession)); boundedLocationsCollection.add(l); @@ -265,7 +263,7 @@ private List parseLocationString(String string, int versus) throws Par private List splitString(String input) { - List result = new ArrayList(); + List result = new ArrayList<>(); int start = 0; int openedParenthesis = 0; for (int current = 0; current < input.length(); current++) { diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/LocationHelper.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/LocationHelper.java index efb02f6c64..e2a405badf 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/LocationHelper.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/LocationHelper.java @@ -153,7 +153,7 @@ public static Location circularLocation(int start, int end, Strand strand, int l end = (length * (numberOfPasses + 1)) + modEnd; } - List locations = new ArrayList(); + List locations = new ArrayList<>(); locations.add(new SimpleLocation(modStart, length, strand)); for (int i = 0; i < numberOfPasses; i++) { locations.add(new SimpleLocation(1, length, strand)); @@ -163,7 +163,7 @@ public static Location circularLocation(int start, int end, Strand strand, int l new SimplePoint(end), strand, true, false, locations); } - private static interface LocationPredicate { + private interface LocationPredicate { boolean accept(Location previous, Location current); } @@ -172,12 +172,9 @@ private static interface LocationPredicate { * lowest start */ public static Location getMin(List locations) { - return scanLocations(locations, new LocationPredicate() { - @Override - public boolean accept(Location previous, Location current) { - int res = current.getStart().compareTo(previous.getStart()); - return res < 0; - } + return scanLocations(locations, (previous, current) -> { + int res = current.getStart().compareTo(previous.getStart()); + return res < 0; }); } @@ -186,12 +183,9 @@ public boolean accept(Location previous, Location current) { * highest end */ public static Location getMax(List locations) { - return scanLocations(locations, new LocationPredicate() { - @Override - public boolean accept(Location previous, Location current) { - int res = current.getEnd().compareTo(previous.getEnd()); - return res > 0; - } + return scanLocations(locations, (previous, current) -> { + int res = current.getEnd().compareTo(previous.getEnd()); + return res > 0; }); } @@ -283,7 +277,7 @@ public static boolean detectCicular(List subLocations) { * @return Returns a boolean indicating if this is consistently accessioned */ public static boolean consistentAccessions(List subLocations) { - Set set = new HashSet(); + Set set = new HashSet<>(); for(Location sub: subLocations) { set.add(sub.getAccession()); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/SimpleLocation.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/SimpleLocation.java index 2175ba4282..f0bdd8a438 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/SimpleLocation.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/SimpleLocation.java @@ -61,7 +61,7 @@ public SimpleLocation(int start, int end, Strand strand, List subLocat public SimpleLocation(Point start, Point end, Strand strand) { - super(start, end, strand, false, false, new ArrayList()); + super(start, end, strand, false, false, new ArrayList<>()); } public SimpleLocation(Point start, Point end, Strand strand, AccessionID accession) { diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/SimplePoint.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/SimplePoint.java index 69c3aea801..c4ccb8510f 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/SimplePoint.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/SimplePoint.java @@ -21,12 +21,12 @@ */ package org.biojava.nbio.core.sequence.location; -import java.io.Serializable; - import org.biojava.nbio.core.sequence.location.template.Point; import org.biojava.nbio.core.util.Equals; import org.biojava.nbio.core.util.Hashcoder; +import java.io.Serializable; + /** * Basic implementation of the Point interface. * @@ -56,7 +56,7 @@ public SimplePoint(int position, boolean unknown, boolean uncertain) { } @Override - public Integer getPosition() { + public int getPosition() { return position; } @@ -100,12 +100,13 @@ protected int reverse(int position, int length) { @Override public boolean equals(Object obj) { + if (this == obj) return true; boolean equals = false; if (Equals.classEqual(this, obj)) { SimplePoint p = (SimplePoint) obj; - equals = (Equals.equal(getPosition(), p.getPosition()) - && Equals.equal(isUncertain(), p.isUncertain()) - && Equals.equal(isUnknown(), p.isUnknown())); + equals = (getPosition() == p.getPosition() + && isUncertain() == p.isUncertain() + && isUnknown() == p.isUnknown()); } return equals; } @@ -125,8 +126,9 @@ public String toString() { } @Override - public int compareTo(Point o) { - return getPosition().compareTo(o.getPosition()); + public int compareTo(Point point) { + if (this == point) return 0; + return Integer.compare(getPosition(), point.getPosition()); } @Override diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/AbstractLocation.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/AbstractLocation.java index 10ee98d1e8..10de177683 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/AbstractLocation.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/AbstractLocation.java @@ -33,14 +33,10 @@ import org.biojava.nbio.core.util.Hashcoder; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; +import java.util.*; import static java.lang.String.format; import static org.biojava.nbio.core.util.Equals.classEqual; -import static org.biojava.nbio.core.util.Equals.equal; /** * Base abstraction of a location which encodes for the majority of important @@ -224,7 +220,7 @@ public Iterator iterator() { list = getSubLocations(); } else { - list = new ArrayList(); + list = new ArrayList<>(); list.add(this); } return list.iterator(); @@ -244,13 +240,12 @@ public List getRelevantSubLocations() { /** * Here to allow for recursion */ - private List getAllSubLocations(Location location) { - List flatSubLocations = new ArrayList(); + private static List getAllSubLocations(Location location) { + List flatSubLocations = new ArrayList<>(); for (Location l : location.getSubLocations()) { if (l.isComplex()) { flatSubLocations.addAll(getAllSubLocations(l)); - } - else { + } else { flatSubLocations.add(l); } } @@ -260,16 +255,18 @@ private List getAllSubLocations(Location location) { @Override public boolean equals(Object obj) { + if (this == obj) return true; + boolean equals = false; if (classEqual(this, obj)) { AbstractLocation l = (AbstractLocation) obj; - equals = (equal(getStart(), l.getStart()) - && equal(getEnd(), l.getEnd()) - && equal(getStrand(), l.getStrand()) - && equal(isCircular(), l.isCircular()) - && equal(isBetweenCompounds(), l.isBetweenCompounds()) - && equal(getSubLocations(), l.getSubLocations()) - && equal(getAccession(), l.getAccession())); + equals = (Objects.equals(getStart(), l.getStart()) + && Objects.equals(getEnd(), l.getEnd()) + && Objects.equals(getStrand(), l.getStrand()) + && isCircular() == l.isCircular() + && isBetweenCompounds() == l.isBetweenCompounds() + && Objects.equals(getSubLocations(), l.getSubLocations()) + && Objects.equals(getAccession(), l.getAccession())); } return equals; } @@ -311,11 +308,11 @@ public boolean isBetweenCompounds() { @Override public Sequence getSubSequence(Sequence sequence) { if(isCircular()) { - List> sequences = new ArrayList>(); + List> sequences = new ArrayList<>(); for(Location l: this) { sequences.add(l.getSubSequence(sequence)); } - return new JoiningSequenceReader(sequence.getCompoundSet(), sequences); + return new JoiningSequenceReader<>(sequence.getCompoundSet(), sequences); } return reverseSequence(sequence.getSubSequence( getStart().getPosition(), getEnd().getPosition())); @@ -327,11 +324,11 @@ public Sequence getSubSequence(Sequence sequence) { @Override public Sequence getRelevantSubSequence(Sequence sequence) { - List> sequences = new ArrayList>(); + List> sequences = new ArrayList<>(); for(Location l: getRelevantSubLocations()) { sequences.add(l.getSubSequence(sequence)); } - return new JoiningSequenceReader(sequence.getCompoundSet(), sequences); + return new JoiningSequenceReader<>(sequence.getCompoundSet(), sequences); } /** @@ -345,12 +342,12 @@ protected Sequence reverseSequence(Sequence sequence) return sequence; } - Sequence reversed = new ReversedSequenceView(sequence); + Sequence reversed = new ReversedSequenceView<>(sequence); // "safe" operation as we have tried to check this if(canComplement(sequence)) { Sequence casted = (Sequence) reversed; ComplementSequenceView complement = - new ComplementSequenceView(casted); + new ComplementSequenceView<>(casted); return (Sequence)complement; } return reversed; @@ -360,7 +357,7 @@ protected Sequence reverseSequence(Sequence sequence) * Uses the Sequence's CompoundSet to decide if a compound can * be assgined to ComplementCompound meaning it can complement */ - protected boolean canComplement(Sequence sequence) { + protected static boolean canComplement(Sequence sequence) { CompoundSet compoundSet = sequence.getCompoundSet(); Compound c = compoundSet.getAllCompounds().iterator().next(); return ComplementCompound.class.isAssignableFrom(c.getClass()); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/Location.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/Location.java index 25cdf48f05..d57cab35dd 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/Location.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/Location.java @@ -45,7 +45,7 @@ public interface Location extends Iterable, Accessioned { * Basic location which is set to the minimum and maximum bounds of * {@link Integer}. {@link Strand} is set to {@link Strand#UNDEFINED}. */ - public static final Location EMPTY = + Location EMPTY = new SimpleLocation(Integer.MIN_VALUE, Integer.MAX_VALUE, Strand.UNDEFINED); /** @@ -128,7 +128,7 @@ public interface Location extends Iterable, Accessioned { * Helper methods for use with the Location classes. Taking its * inspiration from the RichSequence.Tools class from the old BioJava */ - public static class Tools { + class Tools { /** * Used for building a location from a series of sub-locations @@ -206,7 +206,7 @@ public static Location circularLocation(int start, int end, Strand strand, int l end = (length * (numberOfPasses + 1)) + modEnd; } - List locations = new ArrayList(); + List locations = new ArrayList<>(); locations.add(new SimpleLocation(modStart, length, strand)); for (int i = 0; i < numberOfPasses; i++) { locations.add(new SimpleLocation(1, length, strand)); @@ -216,7 +216,7 @@ public static Location circularLocation(int start, int end, Strand strand, int l new SimplePoint(end), strand, true, false, locations); } - private static interface LocationPredicate { + private interface LocationPredicate { boolean accept(Location previous, Location current); } @@ -226,13 +226,9 @@ private static interface LocationPredicate { * lowest start */ public static Location getMin(List locations) { - return scanLocations(locations, new LocationPredicate() { - - @Override - public boolean accept(Location previous, Location current) { - int res = current.getStart().compareTo(previous.getStart()); - return res < 0; - } + return scanLocations(locations, (previous, current) -> { + int res = current.getStart().compareTo(previous.getStart()); + return res < 0; }); } @@ -241,13 +237,9 @@ public boolean accept(Location previous, Location current) { * highest end */ public static Location getMax(List locations) { - return scanLocations(locations, new LocationPredicate() { - - @Override - public boolean accept(Location previous, Location current) { - int res = current.getEnd().compareTo(previous.getEnd()); - return res > 0; - } + return scanLocations(locations, (previous, current) -> { + int res = current.getEnd().compareTo(previous.getEnd()); + return res > 0; }); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/Point.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/Point.java index 52cefa711e..2319570917 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/Point.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/template/Point.java @@ -29,14 +29,14 @@ public interface Point extends Comparable { /** * Used to resolve a position about a point */ - public interface Resolver { + interface Resolver { int resolve(T point); } /** * Returns the position held by this object */ - Integer getPosition(); + int getPosition(); /** * Returns true if the current position is unknown but is diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/ArrayListSequenceReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/ArrayListSequenceReader.java index 48ecb8aff4..3c7e4c9a79 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/ArrayListSequenceReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/ArrayListSequenceReader.java @@ -35,6 +35,7 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.Objects; /** * Stores a Sequence as a collection of compounds in an ArrayList @@ -44,7 +45,7 @@ public class ArrayListSequenceReader implements SequenceReader { private CompoundSet compoundSet; - private ArrayList parsedCompounds = new ArrayList(); + private final ArrayList parsedCompounds = new ArrayList<>(); private volatile Integer hashcode = null; @@ -95,7 +96,7 @@ public String getSequenceAsString() { */ public String getSequenceAsString(Integer begin, Integer end, Strand strand) { // TODO Optimise/cache. - SequenceAsStringHelper sequenceAsStringHelper = new SequenceAsStringHelper(); + SequenceAsStringHelper sequenceAsStringHelper = new SequenceAsStringHelper<>(); return sequenceAsStringHelper.getSequenceAsString(this.parsedCompounds, compoundSet, begin, end, strand); } @@ -182,15 +183,14 @@ public CompoundSet getCompoundSet() { public void setContents(String sequence) throws CompoundNotFoundException { // Horrendously inefficient - pretty much the way the old BJ did things. // TODO Should be optimised. - this.parsedCompounds.clear(); - hashcode = null; - int maxCompoundLength = compoundSet.getMaxSingleCompoundStringLength(); - boolean maxCompundLengthEqual1 = true; - if (maxCompoundLength > 1) { - maxCompundLengthEqual1 = false; - } int length = sequence.length(); + parsedCompounds.clear(); parsedCompounds.ensureCapacity(length); //get the array size correct + + hashcode = null; + int maxCompoundLength = compoundSet.getMaxSingleCompoundStringLength(); + boolean maxCompundLengthEqual1 = maxCompoundLength <= 1; + for (int i = 0; i < length;) { String compoundStr = null; C compound = null; @@ -219,9 +219,7 @@ public void setContents(String sequence) throws CompoundNotFoundException { */ public void setContents(List list) { parsedCompounds.clear(); - for (C c : list) { - parsedCompounds.add(c); - } + parsedCompounds.addAll(list); } /** @@ -232,7 +230,7 @@ public void setContents(List list) { */ @Override public SequenceView getSubSequence(final Integer bioBegin, final Integer bioEnd) { - return new SequenceProxyView(ArrayListSequenceReader.this, bioBegin, bioEnd); + return new SequenceProxyView<>(ArrayListSequenceReader.this, bioBegin, bioEnd); } /** @@ -249,8 +247,9 @@ public AccessionID getAccession() { * @param compounds * @return */ + @SafeVarargs @Override - public int countCompounds(C... compounds) { + public final int countCompounds(C... compounds) { return SequenceMixin.countCompounds(this, compounds); } @@ -279,8 +278,8 @@ public int hashCode() { public boolean equals(Object o) { if(Equals.classEqual(this, o)) { ArrayListSequenceReader that = (ArrayListSequenceReader)o; - return Equals.equal(parsedCompounds, that.parsedCompounds) && - Equals.equal(compoundSet, that.compoundSet); + return Objects.equals(parsedCompounds, that.parsedCompounds) && + Objects.equals(compoundSet, that.compoundSet); } return false; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/BitSequenceReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/BitSequenceReader.java index 326c8589c8..608e95c53b 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/BitSequenceReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/BitSequenceReader.java @@ -20,16 +20,13 @@ */ package org.biojava.nbio.core.sequence.storage; -import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.AccessionID; import org.biojava.nbio.core.sequence.compound.NucleotideCompound; import org.biojava.nbio.core.sequence.template.*; import org.biojava.nbio.core.util.Equals; import org.biojava.nbio.core.util.Hashcoder; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.util.*; /** * An implementation of the popular bit encodings. This class provides the @@ -75,15 +72,16 @@ public void setCompoundSet(CompoundSet compoundSet) { * Class is immutable & so this is unsupported */ @Override - public void setContents(String sequence) throws CompoundNotFoundException { + public void setContents(String sequence) { throw new UnsupportedOperationException(getClass().getSimpleName() + " is an immutable data structure; cannot reset contents"); } /** * Counts the number of times a compound appears in this sequence store */ + @SafeVarargs @Override - public int countCompounds(C... compounds) { + public final int countCompounds(C... compounds) { return SequenceMixin.countCompounds(this, compounds); } @@ -193,8 +191,8 @@ public boolean equals(Object o) { if(Equals.classEqual(this, o)) { @SuppressWarnings("unchecked") BitSequenceReader that = (BitSequenceReader)o; - return Equals.equal(this.accession, that.accession) && - Equals.equal(this.worker, that.worker); + return Objects.equals(this.accession, that.accession) && + Objects.equals(this.worker, that.worker); } return false; } @@ -287,9 +285,8 @@ public int seqArraySize(int length) { */ public void populate(Sequence sequence) { int position = 1; - for (C c : sequence) { + for (C c : sequence) setCompoundAt(c, position++); - } } /** @@ -460,9 +457,9 @@ public int hashCode() { public boolean equals(Object o) { if(Equals.classEqual(this, o)) { BitArrayWorker that = (BitArrayWorker)o; - return Equals.equal(compoundSet, that.compoundSet) && - Equals.equal(indexToCompoundsLookup, that.indexToCompoundsLookup) && - Equals.equal(sequence, that.sequence); + return Objects.equals(compoundSet, that.compoundSet) && + Objects.equals(indexToCompoundsLookup, that.indexToCompoundsLookup) && + Arrays.equals(sequence, that.sequence); } return false; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/FourBitSequenceReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/FourBitSequenceReader.java index 83f4c5dfd2..86bb3039a9 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/FourBitSequenceReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/FourBitSequenceReader.java @@ -43,7 +43,7 @@ public class FourBitSequenceReader extends BitSequenceReader { public FourBitSequenceReader(Sequence sequence) { - super(new FourBitArrayWorker(sequence), sequence.getAccession()); + super(new FourBitArrayWorker<>(sequence), sequence.getAccession()); } public FourBitSequenceReader(String sequence, CompoundSet compoundSet) { @@ -51,7 +51,7 @@ public FourBitSequenceReader(String sequence, CompoundSet compoundSet) { } public FourBitSequenceReader(String sequence, CompoundSet compoundSet, AccessionID accession) { - super(new FourBitArrayWorker(sequence, compoundSet), accession); + super(new FourBitArrayWorker<>(sequence, compoundSet), accession); } public FourBitSequenceReader(FourBitArrayWorker worker) { @@ -114,7 +114,7 @@ protected int compoundsPerDatatype() { @Override protected Map generateCompoundsToIndex() { final CompoundSet cs = getCompoundSet(); - Map map = new HashMap(); + Map map = new HashMap<>(); int index = 0; for (C currentCompound : sortedCompounds(cs)) { C upperCasedCompound = getOptionalUpperCasedCompound(currentCompound, cs); @@ -132,7 +132,7 @@ protected Map generateCompoundsToIndex() { } private C getOptionalUpperCasedCompound(C currentCompound, CompoundSet cs) { - C upperCasedCompound = null; + C upperCasedCompound; String upperCasedString = cs.getStringForCompound(currentCompound).toUpperCase(); if (cs.getCompoundForString(upperCasedString) == null) { upperCasedCompound = currentCompound; @@ -143,16 +143,11 @@ private C getOptionalUpperCasedCompound(C currentCompound, CompoundSet cs) { } private List sortedCompounds(final CompoundSet cs) { - List compounds = new ArrayList(cs.getAllCompounds()); - Collections.sort(compounds, new Comparator() { - - - @Override - public int compare(C o1, C o2) { - String s1 = cs.getStringForCompound(o1); - String s2 = cs.getStringForCompound(o2); - return s1.compareTo(s2); - } + List compounds = new ArrayList<>(cs.getAllCompounds()); + compounds.sort((o1, o2) -> { + String s1 = cs.getStringForCompound(o1); + String s2 = cs.getStringForCompound(o2); + return s1.compareTo(s2); }); return compounds; } @@ -165,7 +160,7 @@ public int compare(C o1, C o2) { protected List generateIndexToCompounds() { CompoundSet cs = getCompoundSet(); Map lookup = getCompoundsToIndexLookup(); - Map tempMap = new HashMap(); + Map tempMap = new HashMap<>(); //First get the reverse lookup working for (C compound : lookup.keySet()) { C upperCasedCompound = getOptionalUpperCasedCompound(compound, cs); @@ -174,8 +169,8 @@ protected List generateIndexToCompounds() { } //Then populate the results by going back through the sorted integer keys - List compounds = new ArrayList(); - List keys = new ArrayList(tempMap.keySet()); + List compounds = new ArrayList<>(); + List keys = new ArrayList<>(tempMap.keySet()); Collections.sort(keys); for (Integer key : keys) { compounds.add(tempMap.get(key)); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/JoiningSequenceReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/JoiningSequenceReader.java index 5c5a3999d9..eaa2c15dc5 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/JoiningSequenceReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/JoiningSequenceReader.java @@ -20,7 +20,6 @@ */ package org.biojava.nbio.core.sequence.storage; -import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.AccessionID; import org.biojava.nbio.core.sequence.template.*; import org.biojava.nbio.core.util.Equals; @@ -61,6 +60,7 @@ public class JoiningSequenceReader implements ProxySequenceR * available during construction otherwise we will throw an illegal * state exception). */ + @SafeVarargs public JoiningSequenceReader(Sequence... sequences) { this(Arrays.asList(sequences)); } @@ -76,6 +76,7 @@ public JoiningSequenceReader(List> sequences) { this.compoundSet = grepCompoundSet(); } + @SafeVarargs public JoiningSequenceReader(CompoundSet compoundSet, Sequence... sequences) { this(compoundSet, Arrays.asList(sequences)); } @@ -86,7 +87,7 @@ public JoiningSequenceReader(CompoundSet compoundSet, List> seque } private List> grepSequences(List> sequences) { - List> seqs = new ArrayList>(); + List> seqs = new ArrayList<>(); for (Sequence s : sequences) { if (s.getLength() != 0) { seqs.add(s); @@ -277,13 +278,14 @@ public void setCompoundSet(CompoundSet compoundSet) { @Override - public void setContents(String sequence) throws CompoundNotFoundException { + public void setContents(String sequence) { throw new UnsupportedOperationException(); } + @SafeVarargs @Override - public int countCompounds(C... compounds) { + public final int countCompounds(C... compounds) { return SequenceMixin.countCompounds(this, compounds); } @@ -301,7 +303,7 @@ public List getAsList() { @Override public boolean equals(Object o) { - + if (this == o) return true; if(! Equals.classEqual(this, o)) { return false; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/SingleCompoundSequenceReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/SingleCompoundSequenceReader.java index 554b7b8361..d523e1f817 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/SingleCompoundSequenceReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/SingleCompoundSequenceReader.java @@ -20,7 +20,6 @@ */ package org.biojava.nbio.core.sequence.storage; -import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.AccessionID; import org.biojava.nbio.core.sequence.template.*; import org.biojava.nbio.core.util.Equals; @@ -28,6 +27,7 @@ import java.util.Iterator; import java.util.List; +import java.util.Objects; /** * An implementation of the SequenceReader interface which for every @@ -74,7 +74,7 @@ public void setCompoundSet(CompoundSet compoundSet) { */ @Override - public void setContents(String sequence) throws CompoundNotFoundException { + public void setContents(String sequence) { throw new UnsupportedOperationException("Not supported."); } @@ -146,7 +146,7 @@ public List getAsList() { @Override public SequenceView getSubSequence(Integer start, Integer end) { - return new SequenceProxyView(this, start, end); + return new SequenceProxyView<>(this, start, end); } /** @@ -171,8 +171,9 @@ public AccessionID getAccession() { * Delegates to {@link SequenceMixin#countCompounds(org.biojava.nbio.core.sequence.template.Sequence, C[]) } */ + @SafeVarargs @Override - public int countCompounds(C... compounds) { + public final int countCompounds(C... compounds) { return SequenceMixin.countCompounds(this, compounds); } @@ -182,7 +183,7 @@ public int countCompounds(C... compounds) { @Override public Iterator iterator() { - return new SequenceMixin.SequenceIterator(this); + return new SequenceMixin.SequenceIterator<>(this); } @Override @@ -204,9 +205,9 @@ public int hashCode() { public boolean equals(Object o) { if(Equals.classEqual(this, o)) { SingleCompoundSequenceReader that = (SingleCompoundSequenceReader)o; - return Equals.equal(compound, that.compound) && - Equals.equal(compoundSet, that.compoundSet) && - Equals.equal(length, that.length); + return Objects.equals(compound, that.compound) && + Objects.equals(compoundSet, that.compoundSet) && + length == that.length; } return false; } @@ -214,9 +215,9 @@ public boolean equals(Object o) { public boolean equals(Sequence o) { if(Equals.classEqual(this, o)) { SingleCompoundSequenceReader that = (SingleCompoundSequenceReader)o; - return Equals.equal(compound, that.compound) && - Equals.equal(compoundSet, that.compoundSet) && - Equals.equal(length, that.length); + return Objects.equals(compound, that.compound) && + Objects.equals(compoundSet, that.compoundSet) && + length == that.length; } return false; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/TwoBitSequenceReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/TwoBitSequenceReader.java index c73482d04b..c17a634309 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/TwoBitSequenceReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/storage/TwoBitSequenceReader.java @@ -50,7 +50,7 @@ public class TwoBitSequenceReader extends BitSequenceReader { public TwoBitSequenceReader(Sequence sequence) { - super(new TwoBitArrayWorker(sequence), sequence.getAccession()); + super(new TwoBitArrayWorker<>(sequence), sequence.getAccession()); } public TwoBitSequenceReader(String sequence, CompoundSet compoundSet) { @@ -58,7 +58,7 @@ public TwoBitSequenceReader(String sequence, CompoundSet compoundSet) { } public TwoBitSequenceReader(String sequence, CompoundSet compoundSet, AccessionID accession) { - super(new TwoBitArrayWorker(sequence, compoundSet), accession); + super(new TwoBitArrayWorker<>(sequence, compoundSet), accession); } public TwoBitSequenceReader(TwoBitArrayWorker worker) { @@ -138,7 +138,7 @@ protected Map generateCompoundsToIndex() { @Override protected List generateIndexToCompounds() { CompoundSet cs = getCompoundSet(); - List result = new ArrayList(); + List result = new ArrayList<>(); result.add( cs.getCompoundForString("T")); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompound.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompound.java index b548f1b5ce..6a9ea1843b 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompound.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompound.java @@ -24,108 +24,90 @@ /** * The details of a Compound + * * @author Andy Yates */ public abstract class AbstractCompound implements Compound { - private final String base; - private final String upperedBase; - private String shortName = null; - private String longName = null; - private String description = null; - private Float molecularWeight = null; - - - // Added an empty constructor for Serialization - public AbstractCompound(){ - this.base = null; - this.upperedBase = null; - } - - public AbstractCompound(String base) { - this.base = base; - this.upperedBase = base.toUpperCase(); - } - - public String getBase() { - return base; - } - - public String getUpperedBase() { - return upperedBase; - } - - @Override -public String getDescription() { - return description; - } - - @Override -public void setDescription(String description) { - this.description = description; - } - - @Override -public String getShortName() { - return shortName; - } - - @Override -public void setShortName(String shortName) { - this.shortName = shortName; - } - - @Override -public String getLongName() { - return longName; - } - - @Override -public void setLongName(String longName) { - this.longName = longName; - } - - @Override -public Float getMolecularWeight() { - return molecularWeight; - } - - @Override -public void setMolecularWeight(Float molecularWeight) { - this.molecularWeight = molecularWeight; - } - - @Override - public String toString() { - return base; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj instanceof AbstractCompound)) { - return false; - } - AbstractCompound them = (AbstractCompound) obj; - return this.base.equals(them.base); - } - - @Override - public int hashCode() { - return this.base.hashCode(); - } - - @Override - public boolean equalsIgnoreCase(Compound compound) { - if (compound == null) { - return false; - } - if (!(compound instanceof AbstractCompound)) { - return false; - } - AbstractCompound them = (AbstractCompound) compound; - return this.base.equalsIgnoreCase(them.base); - } + private final String base; + private final String upperedBase; + private String shortName = null; + private String longName = null; + private String description = null; + protected float molecularWeight = Float.NaN; + final int hash; + + protected AbstractCompound(String base) { + this.base = base; + this.upperedBase = base.toUpperCase(); + this.hash = base.hashCode(); + } + + public String getBase() { + return base; + } + + public String getUpperedBase() { + return upperedBase; + } + + @Override + public String getDescription() { + return description; + } + + @Override + public void setDescription(String description) { + this.description = description; + } + + @Override + public String getShortName() { + return shortName; + } + + @Override + public void setShortName(String shortName) { + this.shortName = shortName; + } + + @Override + public String getLongName() { + return longName; + } + + @Override + public void setLongName(String longName) { + this.longName = longName; + } + + @Override + public final float getMolecularWeight() { + return molecularWeight; + } + + @Override + public final String toString() { + return base; + } + + @Override + public final boolean equals(Object obj) { + return obj == this || (obj instanceof AbstractCompound && this.base.equals(((AbstractCompound) obj).base)); + } + + @Override + public final int hashCode() { + return hash; + } + + @Override + public final boolean equalsIgnoreCase(Compound compound) { + if (this == compound) return true; + if (!(compound instanceof AbstractCompound)) { + return false; + } + AbstractCompound them = (AbstractCompound) compound; + return this.base.equalsIgnoreCase(them.base); + } } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompoundSet.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompoundSet.java index 579153a2fd..edc8bd1096 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompoundSet.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompoundSet.java @@ -39,11 +39,11 @@ public abstract class AbstractCompoundSet implements Compoun private final static Logger logger = LoggerFactory.getLogger(AbstractCompoundSet.class); - private Map charSeqToCompound = new HashMap(); + private final Map charSeqToCompound = new HashMap<>(); private int maxCompoundCharSequenceLength = -1; private Boolean compoundStringLengthEqual = null; - Map> equivalentsMap = new HashMap>(); + final Map> equivalentsMap = new HashMap<>(); protected void addCompound(C compound, C lowerCasedCompound, Iterable equivalents) { addCompound(compound); @@ -60,18 +60,15 @@ protected void addCompound(C compound, C lowerCasedCompound, Iterable equival } } - protected void addCompound(C compound, C lowerCasedCompound, C... equivalents) { - List equiv = new ArrayList(equivalents.length); + @SafeVarargs + protected final void addCompound(C compound, C lowerCasedCompound, C... equivalents) { + List equiv = new ArrayList<>(equivalents.length); equiv.addAll(Arrays.asList(equivalents)); addCompound(compound, lowerCasedCompound, equiv); } protected void addEquivalent(C compound, C equivalent) { - Set s = equivalentsMap.get(compound); - if ( s == null){ - s = new HashSet(); - equivalentsMap.put(compound, s); - } + Set s = equivalentsMap.computeIfAbsent(compound, k -> new HashSet<>()); s.add( equivalent); } @@ -158,19 +155,22 @@ public boolean compoundsEqual(C compoundOne, C compoundTwo) { @Override public boolean isValidSequence(Sequence sequence) { - for (C compound: sequence) { - if (!hasCompound(compound)) { - return false; - } - } - return true; + for (C compound: sequence) { + if (!hasCompound(compound)) + return false; + } + return true; } @Override -public List getAllCompounds() { - return new ArrayList(charSeqToCompound.values()); + public Collection getAllCompounds() { + return + Collections.unmodifiableCollection( + //new ArrayList<>( + charSeqToCompound.values() + ); } private void assertCompound(C compound) { @@ -200,11 +200,12 @@ public int hashCode() { @Override @SuppressWarnings("unchecked") public boolean equals(Object o) { + if (this == o) return true; if (! (o instanceof AbstractCompoundSet)) return false; if(Equals.classEqual(this, o)) { AbstractCompoundSet that = (AbstractCompoundSet)o; - return Equals.equal(charSeqToCompound, that.charSeqToCompound) && - Equals.equal(equivalentsMap, that.equivalentsMap); + return Objects.equals(charSeqToCompound, that.charSeqToCompound) && + Objects.equals(equivalentsMap, that.equivalentsMap); } return false; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompoundTranslator.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompoundTranslator.java index e11af2b1de..cdfde5944f 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompoundTranslator.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractCompoundTranslator.java @@ -37,7 +37,7 @@ public abstract class AbstractCompoundTranslator creator, CompoundSet fromCompoundSet, CompoundSet toCompoundSet) { this.creator = creator; - this.mapper = new HashMap>(); + this.mapper = new HashMap<>(); this.fromCompoundSet = fromCompoundSet; this.toCompoundSet = toCompoundSet; } @@ -62,14 +62,11 @@ protected void addStrings(String source, String... targets) { } } - protected void addCompounds(F source, T... targets) { + @SafeVarargs + protected final void addCompounds(F source, T... targets) { - List l = mapper.get(source); - if ( l == null) { - l = new ArrayList(); - mapper.put(source, l); - } - l.addAll(Arrays.asList(targets)); + List l = mapper.computeIfAbsent(source, k -> new ArrayList<>()); + l.addAll(Arrays.asList(targets)); } @Override @@ -97,7 +94,7 @@ else if (compounds.size() > 1) { @Override public List> createSequences(Sequence originalSequence) { - List> workingList = new ArrayList>(); + List> workingList = new ArrayList<>(); for (F source : originalSequence) { List compounds = translateMany(source); @@ -126,7 +123,7 @@ public List> createSequences(Sequence originalSequence) { protected void addCompoundsToList(List compounds, List> workingList) { int size = compounds.size(); - List> currentWorkingList = new ArrayList>(); + List> currentWorkingList = new ArrayList<>(); for (int i = 0; i < size; i++) { boolean last = (i == (size - 1)); // If last run we add the compound to the top set of lists & then @@ -147,7 +144,7 @@ protected void addCompoundsToList(List compounds, List> workingList) } protected List> workingListToSequences(List> workingList) { - List> sequences = new ArrayList>(); + List> sequences = new ArrayList<>(); for (List seqList : workingList) { sequences.add(getCreator().getSequence(seqList)); } @@ -155,9 +152,9 @@ protected List> workingListToSequences(List> workingList) { } private List> duplicateList(List> incoming) { - List> outgoing = new ArrayList>(); + List> outgoing = new ArrayList<>(); for (List current : incoming) { - outgoing.add(new ArrayList(current)); + outgoing.add(new ArrayList<>(current)); } return outgoing; } @@ -165,7 +162,7 @@ private List> duplicateList(List> incoming) { protected void addCompoundToLists(List> list, T compound) { if (list.isEmpty()) { - list.add(new ArrayList()); + list.add(new ArrayList<>()); } for (List current : list) { diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractNucleotideCompoundSet.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractNucleotideCompoundSet.java index cb682ef347..26a0a983a4 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractNucleotideCompoundSet.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractNucleotideCompoundSet.java @@ -45,7 +45,7 @@ protected void addNucleotideCompound(String base, String complement, String... e C upper = newNucleotideCompound(base.toUpperCase(), complement.toUpperCase(), upperEquivalents); C lower = newNucleotideCompound(base.toLowerCase(), complement.toLowerCase(), lowerEquivalents); - List equivalentCompounds = new ArrayList(); + List equivalentCompounds = new ArrayList<>(equivalents.length*2); for(int i=0; i> equivalentsMap = new HashMap>(); + Map> equivalentsMap = new HashMap<>(); - List ambiguousCompounds = new ArrayList(); + List ambiguousCompounds = new ArrayList<>(); for(NucleotideCompound compound: getAllCompounds()) { - if (!compound.isAmbiguous()) { + if (!compound.isAmbiguous()) continue; - } ambiguousCompounds.add(compound); } @@ -101,8 +100,9 @@ protected void calculateIndirectAmbiguities() { //And once it's all done start adding them to the equivalents map - for ( NucleotideCompound key: equivalentsMap.keySet()){ - List vals = equivalentsMap.get(key); + for (Map.Entry> entry : equivalentsMap.entrySet()){ + NucleotideCompound key = entry.getKey(); + List vals = entry.getValue(); for (NucleotideCompound value: vals){ addEquivalent((C)key,(C)value); addEquivalent((C)value,(C)key); @@ -116,12 +116,8 @@ private void checkAdd( NucleotideCompound value) { - List listS = equivalentsMap.get(key); - if ( listS == null){ - listS = new ArrayList(); - equivalentsMap.put(key, listS); - } - listS.add(value); + List listS = equivalentsMap.computeIfAbsent(key, k -> new ArrayList<>()); + listS.add(value); } @@ -139,7 +135,7 @@ private NucleotideCompound toLowerCase(NucleotideCompound compound) { * @return The ambiguity symbol which represents this set of nucleotides best */ public NucleotideCompound getAmbiguity(NucleotideCompound... compounds) { - Set settedCompounds = new HashSet(); + Set settedCompounds = new HashSet<>(); for(NucleotideCompound compound: compounds) { for(NucleotideCompound subCompound: compound.getConstituents()) { settedCompounds.add(getCompoundForString(subCompound.getBase().toUpperCase())); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractSequence.java index 7e0228a976..87f0ef34dd 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/AbstractSequence.java @@ -35,6 +35,7 @@ import org.biojava.nbio.core.sequence.loader.UniprotProxySequenceReader; import org.biojava.nbio.core.sequence.location.SequenceLocation; import org.biojava.nbio.core.sequence.location.SimpleLocation; +import org.biojava.nbio.core.sequence.location.template.AbstractLocation; import org.biojava.nbio.core.sequence.location.template.Location; import org.biojava.nbio.core.sequence.reference.AbstractReference; import org.biojava.nbio.core.sequence.storage.ArrayListSequenceReader; @@ -65,15 +66,15 @@ public abstract class AbstractSequence implements Sequence parentSequence = null; private String source = null; - private ArrayList notesList = new ArrayList(); + private ArrayList notesList = new ArrayList<>(); private Double sequenceScore = null; private FeaturesKeyWordInterface featuresKeyWord = null; private DatabaseReferenceInterface databaseReferences = null; private FeatureRetriever featureRetriever = null; - private ArrayList, C>> features = - new ArrayList, C>>(); - private LinkedHashMap, C>>> groupedFeatures = - new LinkedHashMap, C>>>(); + private final ArrayList, C>> features = + new ArrayList<>(); + private final LinkedHashMap, C>>> groupedFeatures = + new LinkedHashMap<>(); private List comments = new ArrayList<>(); private List references; @@ -88,7 +89,7 @@ public AbstractSequence() { */ public AbstractSequence(String seqString, CompoundSet compoundSet) throws CompoundNotFoundException { setCompoundSet(compoundSet); - sequenceStorage = new ArrayListSequenceReader(); + sequenceStorage = new ArrayListSequenceReader<>(); sequenceStorage.setCompoundSet(this.getCompoundSet()); sequenceStorage.setContents(seqString); } @@ -126,9 +127,9 @@ public void setProxySequenceReader(SequenceReader proxyLoader) { if (proxyLoader instanceof FeatureRetriever) { this.setFeatureRetriever((FeatureRetriever) sequenceStorage); - HashMap> ff = getFeatureRetriever().getFeatures(); - for (String k: ff.keySet()){ - for (AbstractFeature f: ff.get(k)){ + Map> ff = getFeatureRetriever().getFeatures(); + for (ArrayList abstractFeatures : ff.values()){ + for (AbstractFeature f: abstractFeatures){ this.addFeature(f); } } @@ -153,11 +154,7 @@ public SequenceReader getProxySequenceReader() { * @return the bioBegin */ public Integer getBioBegin() { - if (bioBegin == null) { - return 1; - } else { - return bioBegin; - } + return bioBegin == null ? 1 : bioBegin; } /** @@ -171,11 +168,7 @@ public void setBioBegin(Integer bioBegin) { * @return the bioEnd */ public Integer getBioEnd() { - if (bioEnd == null) { - return this.getLength(); - } else { - return bioEnd; - } + return bioEnd == null ? this.getLength() : bioEnd; } /** @@ -265,13 +258,10 @@ public void setParentSequence(AbstractSequence parentSequence) { * @return the source */ public String getSource() { - if (source != null) { + if (source != null) return source; - } - if (parentSequence != null) { - return parentSequence.getSource(); - } - return null; + else + return parentSequence != null ? parentSequence.getSource() : null; } /** @@ -349,11 +339,12 @@ public void setReferences(List references) { */ public List, C>> getFeatures(String featureType, int bioSequencePosition) { ArrayList, C>> featureHits = - new ArrayList, C>>(); + new ArrayList<>(); List, C>> features = getFeaturesByType(featureType); if (features != null) { for (FeatureInterface, C> feature : features) { - if (bioSequencePosition >= feature.getLocations().getStart().getPosition() && bioSequencePosition <= feature.getLocations().getEnd().getPosition()) { + AbstractLocation locs = feature.getLocations(); + if (bioSequencePosition >= locs.getStart().getPosition() && bioSequencePosition <= locs.getEnd().getPosition()) { featureHits.add(feature); } } @@ -368,7 +359,7 @@ public List, C>> getFeatures(String feature */ public List, C>> getFeatures(int bioSequencePosition) { ArrayList, C>> featureHits = - new ArrayList, C>>(); + new ArrayList<>(); if (features != null) { for (FeatureInterface, C> feature : features) { if (bioSequencePosition >= feature.getLocations().getStart().getPosition() && bioSequencePosition <= feature.getLocations().getEnd().getPosition()) { @@ -396,7 +387,7 @@ public List, C>> getFeatures() { */ public void addFeature(int bioStart, int bioEnd, FeatureInterface, C> feature) { SequenceLocation, C> sequenceLocation = - new SequenceLocation, C>(bioStart, bioEnd, this); + new SequenceLocation<>(bioStart, bioEnd, this); feature.setLocation(sequenceLocation); addFeature(feature); } @@ -409,14 +400,10 @@ public void addFeature(int bioStart, int bioEnd, FeatureInterface, C> feature) { features.add(feature); - ArrayList, C>> featureList = groupedFeatures.get(feature.getType()); - if (featureList == null) { - featureList = new ArrayList, C>>(); - groupedFeatures.put(feature.getType(), featureList); - } + ArrayList, C>> featureList = groupedFeatures.computeIfAbsent(feature.getType(), k -> new ArrayList<>()); featureList.add(feature); - Collections.sort(features, AbstractFeature.LOCATION_LENGTH); - Collections.sort(featureList, AbstractFeature.LOCATION_LENGTH); + features.sort(AbstractFeature.LOCATION_LENGTH); + featureList.sort(AbstractFeature.LOCATION_LENGTH); } /** @@ -442,7 +429,7 @@ public void removeFeature(FeatureInterface, C> feature) { public List, C>> getFeaturesByType(String type) { List, C>> features = groupedFeatures.get(type); if (features == null) { - features = new ArrayList, C>>(); + features = new ArrayList<>(); } return features; } @@ -503,7 +490,7 @@ public void setFeatureRetriever(FeatureRetriever featureRetriever) { public enum AnnotationType { - CURATED, PREDICTED, UNKNOWN; + CURATED, PREDICTED, UNKNOWN } /** @@ -558,7 +545,7 @@ public void setCompoundSet(CompoundSet compoundSet) { @Override public boolean equals(Object o){ - + if (this == o) return true; if(! Equals.classEqual(this, o)) { return false; } @@ -604,7 +591,7 @@ private SequenceReader getSequenceStorage() { //return parentSequence.getSequenceStorage(); if ( this.compoundSet.equals(parentSequence.getCompoundSet())){ - sequenceStorage = new ArrayListSequenceReader(); + sequenceStorage = new ArrayListSequenceReader<>(); sequenceStorage.setCompoundSet(this.getCompoundSet()); try { sequenceStorage.setContents(parentSequence.getSequenceAsString()); @@ -701,7 +688,7 @@ public int getLength() { */ @Override public SequenceView getSubSequence(final Integer bioStart, final Integer bioEnd) { - return new SequenceProxyView(this, bioStart, bioEnd); + return new SequenceProxyView<>(this, bioStart, bioEnd); } /** @@ -718,8 +705,9 @@ public Iterator iterator() { * @param compounds * @return */ + @SafeVarargs @Override - public int countCompounds(C... compounds) { + public final int countCompounds(C... compounds) { return SequenceMixin.countCompounds(this, compounds); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/ComplementCompound.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/ComplementCompound.java index 66b0e29e32..74873d286d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/ComplementCompound.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/ComplementCompound.java @@ -29,5 +29,5 @@ public interface ComplementCompound extends Compound { - public ComplementCompound getComplement(); + ComplementCompound getComplement(); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/Compound.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/Compound.java index 6dbeda2208..113fc05736 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/Compound.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/Compound.java @@ -28,21 +28,21 @@ public interface Compound { - public boolean equalsIgnoreCase(Compound compound); + boolean equalsIgnoreCase(Compound compound); - public String getDescription(); + String getDescription(); - public void setDescription(String description); + void setDescription(String description); - public String getShortName(); + String getShortName(); - public void setShortName(String shortName); + void setShortName(String shortName); - public String getLongName(); + String getLongName(); - public void setLongName(String longName); + void setLongName(String longName); - public Float getMolecularWeight(); + float getMolecularWeight(); - public void setMolecularWeight(Float molecularWeight); +// void setMolecularWeight(Float molecularWeight); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/CompoundSet.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/CompoundSet.java index 2dbc40603a..a0a6e91ab1 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/CompoundSet.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/CompoundSet.java @@ -25,7 +25,7 @@ */ package org.biojava.nbio.core.sequence.template; -import java.util.List; +import java.util.Collection; import java.util.Set; @@ -34,31 +34,31 @@ public interface CompoundSet { /** * Returns the maximum size of a compound String this set holds */ - public int getMaxSingleCompoundStringLength(); + int getMaxSingleCompoundStringLength(); /** * Returns true if all String representations of Compounds are of the * same length. */ - public boolean isCompoundStringLengthEqual(); + boolean isCompoundStringLengthEqual(); /** * Return null if not recognised. Throw IllegalArgumentException if string * is longer than maximum allowed by {@link #getStringForCompound(Compound)}. */ - public C getCompoundForString(String string); + C getCompoundForString(String string); - public String getStringForCompound(C compound); + String getStringForCompound(C compound); - public boolean compoundsEquivalent(C compoundOne, C compoundTwo); + boolean compoundsEquivalent(C compoundOne, C compoundTwo); - public boolean isValidSequence(Sequence sequence); + boolean isValidSequence(Sequence sequence); - public Set getEquivalentCompounds(C compound); + Set getEquivalentCompounds(C compound); - public boolean hasCompound(C compound); + boolean hasCompound(C compound); - public List getAllCompounds(); + Collection getAllCompounds(); boolean isComplementable(); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/Sequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/Sequence.java index f05ed60ec7..da15aabb68 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/Sequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/Sequence.java @@ -41,7 +41,7 @@ public interface Sequence extends Iterable, Accessioned { /** * Returns the length of the Sequence */ - public int getLength(); + int getLength(); /** * Returns the Compound at the given biological index @@ -49,7 +49,7 @@ public interface Sequence extends Iterable, Accessioned { * @param position Biological index (1 to n) * @return Compound at the specified position */ - public C getCompoundAt(int position); + C getCompoundAt(int position); /** * Scans through the Sequence looking for the first occurrence of the given @@ -58,7 +58,7 @@ public interface Sequence extends Iterable, Accessioned { * @param compound Compounds to look for * @return Index of the first position of the compound in the sequence (1 to n) */ - public int getIndexOf(C compound); + int getIndexOf(C compound); /** * Scans through the Sequence looking for the last occurrence of the given @@ -67,17 +67,17 @@ public interface Sequence extends Iterable, Accessioned { * @param compound Compounds to look for * @return Index of the last position of the compound in the sequence (1 to n) */ - public int getLastIndexOf(C compound); +int getLastIndexOf(C compound); /** * Returns the String representation of the Sequence */ - public String getSequenceAsString(); + String getSequenceAsString(); /** * Returns the Sequence as a List of compounds */ - public List getAsList(); + List getAsList(); /** * Returns a portion of the sequence from the different positions. This is @@ -87,12 +87,12 @@ public interface Sequence extends Iterable, Accessioned { * @param end Biological end; must be less than length + 1 * @return A SequenceView of the offset */ - public SequenceView getSubSequence(Integer start, Integer end); + SequenceView getSubSequence(Integer start, Integer end); /** * Gets the compound set used to back this Sequence */ - public CompoundSet getCompoundSet(); + CompoundSet getCompoundSet(); /** * Returns the number of times we found a compound in the Sequence @@ -100,12 +100,12 @@ public interface Sequence extends Iterable, Accessioned { * @param compounds Vargs of the compounds to count * @return Number of times a compound was found */ - public int countCompounds(C... compounds); + int countCompounds(C... compounds); /** * Does the right thing to get the inverse of the current * Sequence. This means either reversing the Sequence and optionally * complementing the Sequence. */ - public SequenceView getInverse(); + SequenceView getInverse(); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceMixin.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceMixin.java index d6efc03817..979f29278a 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceMixin.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceMixin.java @@ -59,6 +59,7 @@ public class SequenceMixin { * @param The type of compound we are looking for * @return The number of times the given compounds appear in this Sequence */ + @SafeVarargs public static int countCompounds( Sequence sequence, C... compounds) { int count = 0; @@ -113,7 +114,7 @@ public static int countAT(Sequence sequence) { * sequence. Any compound not in the Map will return a fraction of 0. */ public static Map getDistribution(Sequence sequence) { - Map results = new HashMap(); + Map results = new HashMap<>(); Map composition = getComposition(sequence); double length = sequence.getLength(); for (Map.Entry entry : composition.entrySet()) { @@ -133,7 +134,7 @@ public static Map getDistribution(Sequence se * @return Counts for the instances of all compounds in the sequence */ public static Map getComposition(Sequence sequence) { - Map results = new HashMap(); + Map results = new HashMap<>(); for (C currentCompound : sequence) { Integer currentInteger = results.get(currentCompound); @@ -187,7 +188,7 @@ public static String toString(Sequence sequence) { * the Compounds of that {@link Sequence}. */ public static List toList(Sequence sequence) { - List list = new ArrayList(sequence.getLength()); + List list = new ArrayList<>(sequence.getLength()); for (C compound : sequence) { list.add(compound); } @@ -218,7 +219,7 @@ public static int indexOf(Sequence sequence, */ public static int lastIndexOf(Sequence sequence, C compound) { - int index = indexOf(new ReversedSequenceView(sequence), compound); + int index = indexOf(new ReversedSequenceView<>(sequence), compound); return (sequence.getLength() - index)+1; } @@ -229,7 +230,7 @@ public static int lastIndexOf(Sequence sequence, */ public static Iterator createIterator( Sequence sequence) { - return new SequenceIterator(sequence); + return new SequenceIterator<>(sequence); } /** @@ -237,7 +238,7 @@ public static Iterator createIterator( */ public static SequenceView createSubSequence( Sequence sequence, int start, int end) { - return new SequenceProxyView(sequence, start, end); + return new SequenceProxyView<>(sequence, start, end); } /** @@ -250,7 +251,7 @@ public static SequenceView createSubSequence( public static Sequence shuffle(Sequence sequence) { List compounds = sequence.getAsList(); Collections.shuffle(compounds); - return new ArrayListSequenceReader(compounds, + return new ArrayListSequenceReader<>(compounds, sequence.getCompoundSet()); } @@ -275,8 +276,8 @@ public static String checksum(Sequence sequence) { * @return The list of non-overlapping K-mers */ public static List> nonOverlappingKmers(Sequence sequence, int kmer) { - List> l = new ArrayList>(); - WindowedSequence w = new WindowedSequence(sequence, kmer); + List> l = new ArrayList<>(); + WindowedSequence w = new WindowedSequence<>(sequence, kmer); for(SequenceView view: w) { l.add(view); } @@ -293,17 +294,17 @@ public static List> nonOverlappingKmers(Seq * @return The list of overlapping K-mers */ public static List> overlappingKmers(Sequence sequence, int kmer) { - List> l = new ArrayList>(); + List> l = new ArrayList<>(); List>> windows - = new ArrayList>>(); + = new ArrayList<>(); for(int i=1; i<=kmer; i++) { if(i == 1) { - windows.add(new WindowedSequence(sequence, kmer).iterator()); + windows.add(new WindowedSequence<>(sequence, kmer).iterator()); } else { SequenceView sv = sequence.getSubSequence(i, sequence.getLength()); - windows.add(new WindowedSequence(sv, kmer).iterator()); + windows.add(new WindowedSequence<>(sv, kmer).iterator()); } } @@ -333,7 +334,7 @@ public static List> overlappingKmers(Sequen */ @SuppressWarnings({ "unchecked" }) public static SequenceView inverse(Sequence sequence) { - SequenceView reverse = new ReversedSequenceView(sequence); + SequenceView reverse = new ReversedSequenceView<>(sequence); if(sequence.getCompoundSet().isComplementable()) { return new ComplementSequenceView(reverse); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceProxyView.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceProxyView.java index f6e51dfad7..15100c8cf5 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceProxyView.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceProxyView.java @@ -74,7 +74,7 @@ public List getAsList() { @Override public boolean equals(Object o) { - + if (this == o) return true; if(! Equals.classEqual(this, o)) { return false; } @@ -117,12 +117,12 @@ public CompoundSet getCompoundSet() { @Override public SequenceView getSubSequence(final Integer bioStart, final Integer bioEnd) { - return new SequenceProxyView(this, bioStart, bioEnd); + return new SequenceProxyView<>(this, bioStart, bioEnd); } @Override public Iterator iterator() { - return new SequenceMixin.SequenceIterator(this); + return new SequenceMixin.SequenceIterator<>(this); } @Override @@ -175,8 +175,9 @@ public void setBioEnd(Integer bioEnd) { this.bioEnd = bioEnd; } + @SafeVarargs @Override - public int countCompounds(C... compounds) { + public final int countCompounds(C... compounds) { return SequenceMixin.countCompounds(this, compounds); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceReader.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceReader.java index 48eb728a94..e8380598b3 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceReader.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceReader.java @@ -29,7 +29,7 @@ public interface SequenceReader extends Sequence { - public void setCompoundSet(CompoundSet compoundSet); + void setCompoundSet(CompoundSet compoundSet); - public void setContents(String sequence) throws CompoundNotFoundException; + void setContents(String sequence) throws CompoundNotFoundException; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceView.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceView.java index 4f98899355..7c2228e17f 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceView.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/template/SequenceView.java @@ -28,15 +28,15 @@ public interface SequenceView extends Sequence { - public Sequence getViewedSequence(); + Sequence getViewedSequence(); /** * 1-indexed, inclusive. */ - public Integer getBioStart(); + Integer getBioStart(); /** * 1-indexed, inclusive. */ - public Integer getBioEnd(); + Integer getBioEnd(); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/CaseInsensitiveCompound.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/CaseInsensitiveCompound.java index 5c00b511d6..af2adba614 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/CaseInsensitiveCompound.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/CaseInsensitiveCompound.java @@ -1,115 +1,115 @@ -/* - * BioJava development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public Licence. This should - * be distributed with the code. If you do not have a copy, - * see: - * - * http://www.gnu.org/copyleft/lesser.html - * - * Copyright for this code is held jointly by the individual - * authors. These should be listed in @author doc comments. - * - * For more information on the BioJava project and its aims, - * or to join the biojava-l mailing list, visit the home page - * at: - * - * http://www.biojava.org/ - * - * Created on 01-21-2010 - */ -package org.biojava.nbio.core.sequence.transcription; - -import org.biojava.nbio.core.sequence.compound.NucleotideCompound; -import org.biojava.nbio.core.sequence.template.Compound; - -/** - * Attempts to wrap compounds so it is possible to view them - * in a case insensitive manner - */ -public class CaseInsensitiveCompound implements Compound { - - private final NucleotideCompound compound; - - public CaseInsensitiveCompound(NucleotideCompound compound) { - this.compound = compound; - } - - @Override -public boolean equalsIgnoreCase(Compound compound) { - if (compound == null) { - return false; - } - if (!(compound instanceof CaseInsensitiveCompound)) { - return false; - } - CaseInsensitiveCompound them = (CaseInsensitiveCompound) compound; - return toString().equalsIgnoreCase(them.toString()); - } - - @Override -public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj instanceof CaseInsensitiveCompound)) { - return false; - } - return equalsIgnoreCase((Compound)obj); - } - - @Override -public int hashCode() { - return toString().toUpperCase().hashCode(); - } - - public NucleotideCompound getUnderlyingCompound() { - return this.compound; - } - - @Override -public String getDescription() { - return getUnderlyingCompound().getDescription(); - } - - @Override -public String getLongName() { - return getUnderlyingCompound().getLongName(); - } - - @Override -public Float getMolecularWeight() { - return getUnderlyingCompound().getMolecularWeight(); - } - - @Override -public String getShortName() { - return getUnderlyingCompound().getShortName(); - } - - @Override -public String toString() { - return getUnderlyingCompound().toString(); - } - - @Override -public void setDescription(String description) { - //Nothing - } - - @Override -public void setLongName(String longName) { - //Nothing - } - - @Override -public void setMolecularWeight(Float molecularWeight) { - //Nothing - } - - @Override -public void setShortName(String shortName) { - //Nothing - } -} +///* +// * BioJava development code +// * +// * This code may be freely distributed and modified under the +// * terms of the GNU Lesser General Public Licence. This should +// * be distributed with the code. If you do not have a copy, +// * see: +// * +// * http://www.gnu.org/copyleft/lesser.html +// * +// * Copyright for this code is held jointly by the individual +// * authors. These should be listed in @author doc comments. +// * +// * For more information on the BioJava project and its aims, +// * or to join the biojava-l mailing list, visit the home page +// * at: +// * +// * http://www.biojava.org/ +// * +// * Created on 01-21-2010 +// */ +//package org.biojava.nbio.core.sequence.transcription; +// +//import org.biojava.nbio.core.sequence.compound.NucleotideCompound; +//import org.biojava.nbio.core.sequence.template.Compound; +// +///** +// * Attempts to wrap compounds so it is possible to view them +// * in a case insensitive manner +// */ +//public class CaseInsensitiveCompound implements Compound { +// +// private final NucleotideCompound compound; +// +// public CaseInsensitiveCompound(NucleotideCompound compound) { +// this.compound = compound; +// } +// +// @Override +//public boolean equalsIgnoreCase(Compound compound) { +// if (compound == null) { +// return false; +// } +// if (!(compound instanceof CaseInsensitiveCompound)) { +// return false; +// } +// CaseInsensitiveCompound them = (CaseInsensitiveCompound) compound; +// return toString().equalsIgnoreCase(them.toString()); +// } +// +// @Override +//public boolean equals(Object obj) { +// if (obj == null) { +// return false; +// } +// if (!(obj instanceof CaseInsensitiveCompound)) { +// return false; +// } +// return equalsIgnoreCase((Compound)obj); +// } +// +// @Override +//public int hashCode() { +// return toString().toUpperCase().hashCode(); +// } +// +// public NucleotideCompound getUnderlyingCompound() { +// return this.compound; +// } +// +// @Override +//public String getDescription() { +// return getUnderlyingCompound().getDescription(); +// } +// +// @Override +//public String getLongName() { +// return getUnderlyingCompound().getLongName(); +// } +// +// @Override +//public Float getMolecularWeight() { +// return getUnderlyingCompound().getMolecularWeight(); +// } +// +// @Override +//public String getShortName() { +// return getUnderlyingCompound().getShortName(); +// } +// +// @Override +//public String toString() { +// return getUnderlyingCompound().toString(); +// } +// +// @Override +//public void setDescription(String description) { +// //Nothing +// } +// +// @Override +//public void setLongName(String longName) { +// //Nothing +// } +// +// @Override +//public void setMolecularWeight(Float molecularWeight) { +// //Nothing +// } +// +// @Override +//public void setShortName(String shortName) { +// //Nothing +// } +//} diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/DNAToRNATranslator.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/DNAToRNATranslator.java index 0016c86507..baafa9419d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/DNAToRNATranslator.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/DNAToRNATranslator.java @@ -65,7 +65,7 @@ public DNAToRNATranslator(SequenceCreatorInterface rnaCreato @Override public List> createSequences(Sequence originalSequence) { if(shortCutTranslation) { - List> result = new ArrayList>(1); + List> result = new ArrayList<>(1); result.add(wrapToRna(originalSequence)); return result; } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/Frame.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/Frame.java index 8f35c0eb03..c60695015e 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/Frame.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/Frame.java @@ -42,7 +42,7 @@ public enum Frame { private final boolean reverse; private final int start; - private Frame(int start, boolean reverse) { + Frame(int start, boolean reverse) { this.start = start; this.reverse = reverse; } @@ -83,7 +83,7 @@ public static Frame[] getAllFrames() { public Sequence wrap(Sequence incoming) { Sequence reversed; if(reverse) { - reversed = new ComplementSequenceView(new ReversedSequenceView(incoming)); + reversed = new ComplementSequenceView<>(new ReversedSequenceView<>(incoming)); } else { reversed = incoming; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/RNAToAminoAcidTranslator.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/RNAToAminoAcidTranslator.java index e748b41387..56ee596811 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/RNAToAminoAcidTranslator.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/RNAToAminoAcidTranslator.java @@ -81,20 +81,16 @@ public RNAToAminoAcidTranslator( this.initMetOnly = initMetOnly; this.translateNCodons = translateNCodons; - quickLookup = new HashMap(codons + quickLookup = new HashMap<>(codons .getAllCompounds().size()); - aminoAcidToCodon = new HashMap>(); + aminoAcidToCodon = new HashMap<>(); List codonList = table.getCodons(nucleotides, aminoAcids); for (Codon codon : codonList) { quickLookup.put(codon.getTriplet(), codon); codonArray[codon.getTriplet().intValue()] = codon; - List codonL = aminoAcidToCodon.get(codon.getAminoAcid()); - if (codonL == null) { - codonL = new ArrayList(); - aminoAcidToCodon.put(codon.getAminoAcid(), codonL); - } + List codonL = aminoAcidToCodon.computeIfAbsent(codon.getAminoAcid(), k -> new ArrayList<>()); codonL.add(codon); } @@ -114,9 +110,9 @@ public RNAToAminoAcidTranslator( public List> createSequences( Sequence originalSequence) { - List> workingList = new ArrayList>(); + List> workingList = new ArrayList<>(); - Iterable> iter = new WindowedSequence( + Iterable> iter = new WindowedSequence<>( originalSequence, 3); boolean first = true; @@ -132,7 +128,7 @@ public List> createSequences( element.getCompoundAt(i++), element.getCompoundAt(i++), element.getCompoundAt(i++)); - Codon target = null; + Codon target; target = quickLookup.get(triplet); @@ -152,7 +148,7 @@ public List> createSequences( } } - addCompoundsToList(Arrays.asList(aminoAcid), workingList); + addCompoundsToList(Collections.singletonList(aminoAcid), workingList); } if (doTranslate && stopAtStopCodons && target.isStop()) { diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/Table.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/Table.java index 7d75a10d6a..f765c6ea2e 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/Table.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/Table.java @@ -30,6 +30,7 @@ import org.biojava.nbio.core.util.Hashcoder; import java.util.List; +import java.util.Objects; /** * Provides a way of separating us from the specific {@link IUPACTable} even @@ -64,7 +65,7 @@ CompoundSet getCodonCompoundSet( * @author ayates * */ - public static class Codon implements Compound { + class Codon implements Compound { private final CaseInsensitiveTriplet triplet; private final boolean start; @@ -114,14 +115,15 @@ public CaseInsensitiveTriplet getTriplet() { } @Override - public boolean equals(Object obj) { + public boolean equals(Object o) { + if (this == o) return true; boolean equals = false; - if(Equals.classEqual(this, obj)) { - Codon casted = (Codon) obj; - equals = Equals.equal(getTriplet(), casted.getTriplet()) && - Equals.equal(isStart(), casted.isStart()) && - Equals.equal(isStop(), casted.isStop()) && - Equals.equal(getAminoAcid(), casted.getAminoAcid()); + if(Equals.classEqual(this, o)) { + Codon casted = (Codon) o; + equals = Objects.equals(getTriplet(), casted.getTriplet()) && + isStart() == casted.isStart() && + isStop() == casted.isStop() && + Objects.equals(getAminoAcid(), casted.getAminoAcid()); } return equals; } @@ -157,7 +159,7 @@ public String getLongName() { } @Override - public Float getMolecularWeight() { + public float getMolecularWeight() { throw new UnsupportedOperationException("Not supported"); } @@ -176,10 +178,10 @@ public void setLongName(String longName) { throw new UnsupportedOperationException("Not supported"); } - @Override - public void setMolecularWeight(Float molecularWeight) { - throw new UnsupportedOperationException("Not supported"); - } +// @Override +// public void setMolecularWeight(Float molecularWeight) { +// throw new UnsupportedOperationException("Not supported"); +// } @Override public void setShortName(String shortName) { @@ -191,7 +193,7 @@ public void setShortName(String shortName) { * Class used to hold three nucleotides together and allow for equality * to be assessed in a case insensitive manner. */ - public static class CaseInsensitiveTriplet { + class CaseInsensitiveTriplet { private final NucleotideCompound one; private final NucleotideCompound two; @@ -199,7 +201,7 @@ public static class CaseInsensitiveTriplet { private transient boolean hashSet = false; private transient int hash; - private transient boolean stringSet = false; + private final transient boolean stringSet = false; private transient String stringify; public CaseInsensitiveTriplet(NucleotideCompound one, @@ -223,10 +225,11 @@ public NucleotideCompound getThree() { } @Override - public boolean equals(Object obj) { + public boolean equals(Object o) { + if (this == o) return true; boolean equals = false; - if(Equals.classEqual(this, obj)) { - CaseInsensitiveTriplet casted = (CaseInsensitiveTriplet) obj; + if(Equals.classEqual(this, o)) { + CaseInsensitiveTriplet casted = (CaseInsensitiveTriplet) o; return toString().equals(casted.toString()); } return equals; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/TranscriptionEngine.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/TranscriptionEngine.java index 0ca5bc6f1a..0ee18cdb66 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/TranscriptionEngine.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/transcription/TranscriptionEngine.java @@ -125,7 +125,7 @@ public Sequence translate( */ public Map> multipleFrameTranslation( Sequence dna, Frame... frames) { - Map> results = new EnumMap>( + Map> results = new EnumMap<>( Frame.class); for (Frame frame : frames) { Sequence rna = getDnaRnaTranslator() @@ -327,8 +327,8 @@ private CompoundSet getAminoAcidCompounds() { if (aminoAcidCompounds != null) { return aminoAcidCompounds; } - return AminoAcidCompoundSet.getAminoAcidCompoundSet(); - } + return AminoAcidCompoundSet.aminoAcidCompoundSet; + } private DNAToRNATranslator getDnaRnaTranslator() { if (dnaRnaTranslator != null) { diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/views/RnaSequenceView.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/views/RnaSequenceView.java index b0c00d6a60..05eb1a86d8 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/views/RnaSequenceView.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/views/RnaSequenceView.java @@ -23,7 +23,6 @@ */ package org.biojava.nbio.core.sequence.views; -import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.compound.NucleotideCompound; import org.biojava.nbio.core.sequence.compound.RNACompoundSet; import org.biojava.nbio.core.sequence.template.*; @@ -39,7 +38,7 @@ */ public class RnaSequenceView extends SequenceProxyView implements ProxySequenceReader { - private CompoundSet rnaCompounds; + private final CompoundSet rnaCompounds; private Map dnaToRna = null; private Map rnaToDna = null; @@ -90,9 +89,9 @@ public Map getDnaToRna() { protected void buildTranslators() { Map localDnaToRna = - new HashMap(); + new HashMap<>(); Map localRnaToDna = - new HashMap(); + new HashMap<>(); NucleotideCompound thymine = getViewedSequence().getCompoundSet().getCompoundForString("T"); @@ -124,7 +123,7 @@ public void setCompoundSet(CompoundSet compoundSet) { } @Override - public void setContents(String sequence) throws CompoundNotFoundException { + public void setContents(String sequence) { throw new UnsupportedOperationException("Unsupported operation; create a new viewed sequence"); } } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/views/WindowedSequence.java b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/views/WindowedSequence.java index 72e2111407..9b21da105a 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/sequence/views/WindowedSequence.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/sequence/views/WindowedSequence.java @@ -115,7 +115,7 @@ public SequenceView get(int index) { */ @Override public Iterator> iterator() { - return new WindowedSequenceIterator(this); + return new WindowedSequenceIterator<>(this); } /** diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/CRC64Checksum.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/CRC64Checksum.java index 3e99fec10b..81e0a9339d 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/CRC64Checksum.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/CRC64Checksum.java @@ -81,7 +81,7 @@ public long getValue() { */ @Override public String toString() { - StringBuffer builder = new StringBuffer(); + StringBuilder builder = new StringBuilder(); builder.append(Long.toHexString(crc >>> 4)); builder.append(Long.toHexString(crc & 0xF)); for (int i = 16 - builder.length(); i > 0; --i) diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/ConcurrencyTools.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/ConcurrencyTools.java index 3e849a38a4..303da24403 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/ConcurrencyTools.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/ConcurrencyTools.java @@ -94,7 +94,7 @@ public static void setThreadPoolSingle() { public static void setThreadPoolSize(int threads) { setThreadPool( new ThreadPoolExecutor(threads, threads, 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue())); + new LinkedBlockingQueue<>())); } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/Download.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/Download.java new file mode 100644 index 0000000000..6f48381bec --- /dev/null +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/Download.java @@ -0,0 +1,374 @@ +/** + * BioJava development code + * + * This code may be freely distributed and modified under the terms of the GNU + * Lesser General Public Licence. This should be distributed with the code. If + * you do not have a copy, see: + * + * http://www.gnu.org/copyleft/lesser.html + * + * Copyright for this code is held jointly by the individual authors. These + * should be listed in @author doc comments. + * + * For more information on the BioJava project and its aims, or to join the + * biojava-l mailing list, visit the home page at: + * + * http://www.biojava.org/ + * + * Created on Feb 23, 2012 Created by Andreas Prlic + * + * @since 3.0.2 + */ +package org.biojava.nbio.core.util; + +import okhttp3.*; + +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; +import java.nio.channels.FileChannel; +import java.nio.file.*; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.concurrent.TimeUnit; +import java.util.zip.GZIPInputStream; + +public class Download { + + //private static final Logger logger = LoggerFactory.getLogger(Download.class); + private static final int DOWNLOAD_TIMEOUT_MS_DEFAULT = 60000; + + /** + * Copy the content of file src to dst TODO since java 1.7 this is provided + * in java.nio.file.Files + * + * @param src + * @param dst + * @throws IOException + */ + @SuppressWarnings("resource") + public static void copy(File src, File dst) throws IOException { + + // Took following recipe from + // http://stackoverflow.com/questions/106770/standard-concise-way-to-copy-a-file-in-java + // The nio package seems to be the most efficient way to copy a file + + try (FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dst).getChannel()) { + // we need the supress warnings here (the warning that the stream is not closed is harmless) + // see http://stackoverflow.com/questions/12970407/does-filechannel-close-close-the-underlying-stream + destination.transferFrom(source, 0, source.size()); + } + } + + public static String getFileExtension(File f) { + String fileName = f.getName(); + return fileName.substring(fileName.lastIndexOf('.') + 1); + } + + public static String getFilePrefix(File f) { + String fileName = f.getName(); + return fileName.substring(0, fileName.indexOf('.')); + } + + static final OkHttpClient.Builder clients; + static { + /** https://square.github.io/okhttp/recipes/#response-caching-kt-java */ + int cacheSize = 512 * 1024 * 1024; //512m + OkHttpClient.Builder bb = new OkHttpClient.Builder(); + bb.followRedirects(true); + bb.followSslRedirects(true); + bb.retryOnConnectionFailure(true); + +// try { + File cacheDir = Paths.get(System.getProperty("java.io.tmpdir"), "biojava").toFile(); + cacheDir.mkdirs(); + Cache cache = new Cache(cacheDir, cacheSize); + bb.cache(cache); + +// } catch (IOException e) { +// e.printStackTrace(); +// } + clients = bb; + } + + +// /** +// * Converts path to Unix convention and adds a terminating slash if it was +// * omitted +// * +// * @param path original platform dependent path +// * @return path in Unix convention +// * @author Peter Rose +// * @since 3.2 +// */ +// public static String toUnixPath(String path) { +// String uPath = path; +// if (uPath.contains("\\")) { +// uPath = uPath.replaceAll("\\\\", "/"); +// } +// // this should be removed, it's need since "\" is added AtomCache code +// if (uPath.endsWith("//")) { +// uPath = uPath.substring(0, uPath.length() - 1); +// } +// if (!uPath.endsWith("/")) { +// uPath = uPath + "/"; +// } +// return uPath; +// } + + /** + * Expands ~ in paths to the user's home directory. + * + *

    + * This does not work for some special cases for paths: Other users' homes + * (~user/...), and Tilde expansion within the path (/.../~/...) + * + * @param file + * @return + */ + public static String expandUserHome(String file) { + if (file.startsWith("~" + File.separator)) { + file = System.getProperty("user.home") + file.substring(1); + } + return file; + } + + /** + * Pings a HTTP URL. This effectively sends a HEAD request and returns + * true if the response code is in the 200-399 range. + * + * @param url The HTTP URL to be pinged. + * @param timeout The timeout in millis for both the connection timeout and + * the response read timeout. Note that the total timeout is effectively two + * times the given timeout. + * @return true if the given HTTP URL has returned response + * code 200-399 on a HEAD request within the given timeout, otherwise + * false. + * @author BalusC, + * http://stackoverflow.com/questions/3584210/preferred-java-way-to-ping-a-http-url-for-availability + */ + public static boolean ping(String url, int timeout) { + //url = url.replaceFirst("https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates. + + try { + HttpURLConnection connection = (HttpURLConnection) prepareURLConnection(url, timeout); + connection.setRequestMethod("HEAD"); + int responseCode = connection.getResponseCode(); + return (200 <= responseCode && responseCode <= 399); + } catch (IOException exception) { + return false; + } + } + + /** + * Prepare {@link URLConnection} with customised timeouts. + * + * @param url The URL + * @param timeout The timeout in millis for both the connection timeout and + * the response read timeout. Note that the total timeout is effectively two + * times the given timeout. + * + *

    + * Example of code. + * UrlConnection conn = prepareURLConnection("http://www.google.com/", 20000); + * conn.connect(); + * conn.getInputStream(); + * + *

    + * + * NB. User should execute connect() method before getting input + * stream. + * @return + * @throws IOException + * @author Jacek Grzebyta + */ + private static URLConnection prepareURLConnection(String url, int timeout) throws IOException { + URLConnection connection = new URL(url).openConnection(); + connection.setReadTimeout(timeout); + connection.setConnectTimeout(timeout); + return connection; + } + + /** + * Recursively delete a folder & contents + * + * @param dir directory to delete + */ + public static void deleteDirectory(Path dir) throws IOException { + if(dir == null || !Files.exists(dir)) + return; + Files.walkFileTree(dir, new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Files.delete(file); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { + if (e != null) + throw e; + Files.delete(dir); + return FileVisitResult.CONTINUE; + } + }); + } + + public static InputStream stream(URL url) throws IOException { + return stream(url, DOWNLOAD_TIMEOUT_MS_DEFAULT); + } + + /** + * Open a URL and return an InputStream to it + * if acceptGzipEncoding == true, use GZIPEncoding to + * compress communication. + *

    + * The caller is responsible to close the returned InputStream not to cause + * resource leaks. + * @param url the input URL to be read + * @param timeoutMS + * @return an {@link InputStream} of response + * @throws IOException due to an error opening the URL + */ + public static InputStream stream(URL url, int timeoutMS) throws IOException { +// InputStream inStream; +// URLConnection huc = URLConnectionTools.openURLConnection(url,timeout); +// +// if ( acceptGzipEncoding) huc.setRequestProperty("Accept-Encoding", "gzip"); +// +// String contentEncoding = huc.getContentEncoding(); +// +// inStream = huc.getInputStream(); + + OkHttpClient client = clients.build(); //TODO ThreadLocal + + Call c = client.newCall(new Request.Builder().url(url) + //.cacheControl(CacheControl.FORCE_CACHE) + .build()); + + c.timeout().deadline(timeoutMS, TimeUnit.MILLISECONDS); + + try (Response r = c.execute()) { + InputStream inStream; + ResponseBody b = r.body(); + if (!r.isSuccessful()) { + //throw new IOException("Unexpected code " + r); + inStream = new ByteArrayInputStream(new byte[] { } ); //HACK + } else { + inStream = + //b.byteStream(); + new ByteArrayInputStream(b.bytes()); //b.byteStream(); + } + + if (b.contentType().toString().contains("-gzip")) + return new GZIPInputStream(inStream); + + return inStream; + } + + + } + + /** + * Download the content provided at URL url and store the result to a local + * file, using a temp file to cache the content in case something goes wrong + * in download + * + * @param url + * @param destination + * @throws IOException + */ + public static void downloadFile(URL url, File destination) throws IOException { + + + OkHttpClient client = clients.build(); //TODO ThreadLocal + + try (Response r = client.newCall(new Request.Builder().url(url).build()).execute()) { + if (!r.isSuccessful()) { + //throw new IOException("Unexpected code " + r); + return; + } + + ResponseBody b = r.body(); + + FileChannel dst = new FileOutputStream(destination).getChannel(); + dst.transferFrom(b.source(), 0, b.contentLength()); + + System.out.println("Response 1 response: " + r); + System.out.println("Response 1 cache response: " + r.cacheResponse()); + System.out.println("Response 1 network response: " + r.networkResponse()); + } + + +// int count = 0; +// int maxTries = 10; +// int timeout = 60000; //60 sec +// +// File tempFile = File.createTempFile(getFilePrefix(destination), "." + getFileExtension(destination)); +// +// // Took following recipe from stackoverflow: +// // http://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java +// // It seems to be the most efficient way to transfer a file +// // See: http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html +// ReadableByteChannel rbc = null; +// FileOutputStream fos = null; +// while (true) { +// try { +// URLConnection connection = prepareURLConnection(url.toString(), timeout); +// connection.connect(); +// +// rbc = Channels.newChannel(connection.getInputStream()); +// fos = new FileOutputStream(tempFile); +// fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); +// break; +// } catch (SocketTimeoutException e) { +// if (++count == maxTries) throw e; +// } finally { +// if (rbc != null) { +// rbc.close(); +// } +// if (fos != null) { +// fos.close(); +// } +// } +// } +// +// logger.debug("Copying temp file {} to final location {}", tempFile, destination); +// copy(tempFile, destination); +// +// // delete the tmp file +// tempFile.delete(); + + } + + public static BufferedReader bufferedReader(URL u) throws IOException { + return new BufferedReader(new InputStreamReader(stream(u))); + } + + + +// /** +// * Recursively delete a folder & contents +// * +// * @param dir directory to delete +// */ +// public static void deleteDirectory(String dir) throws IOException { +// deleteDirectory(Paths.get(dir)); +// } +// +// +// public static void main(String[] args) { +// String url; +// url = "http://scop.mrc-lmb.cam.ac.uk/scop/parse/"; +// System.out.format("%s\t%s%n", ping(url, 200), url); +// url = "http://scop.mrc-lmb.cam.ac.uk/scop/parse/foo"; +// System.out.format("%s\t%s%n", ping(url, 200), url); +// url = "http://scopzzz.mrc-lmb.cam.ac.uk/scop/parse/"; +// System.out.format("%s\t%s%n", ping(url, 200), url); +// url = "scop.mrc-lmb.cam.ac.uk"; +// System.out.format("%s\t%s%n", ping(url, 200), url); +// url = "http://scop.mrc-lmb.cam.ac.uk"; +// System.out.format("%s\t%s%n", ping(url, 200), url); +// } + +} diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/Equals.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/Equals.java index 85beddf1de..b335791b7f 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/Equals.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/Equals.java @@ -30,26 +30,6 @@ */ public class Equals { - public static boolean equal(int one, int two) { - return one == two; - } - - public static boolean equal(long one, long two) { - return (one == two); - } - - public static boolean equal(boolean one, boolean two) { - return one == two; - } - - /** - * Does not compare class types. - * @see #classEqual(Object, Object) - */ - public static boolean equal(Object one, Object two) { - return one == null && two == null || !(one == null || two == null) && (one == two || one.equals(two)); - } - /** * This method should be called before beginning any equals methods. In order * to return true the method: @@ -82,6 +62,7 @@ public static boolean equal(Object one, Object two) { * equal at the class level */ public static boolean classEqual(Object one, Object two) { - return one == two || !(one == null || two == null) && one.getClass() == two.getClass(); + return one == two || + (!(one == null || two == null) && one.getClass() == two.getClass()); } } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/FileDownloadUtils.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/FileDownloadUtils.java deleted file mode 100644 index 2fd6f3f9e0..0000000000 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/FileDownloadUtils.java +++ /dev/null @@ -1,299 +0,0 @@ -/** - * BioJava development code - * - * This code may be freely distributed and modified under the terms of the GNU - * Lesser General Public Licence. This should be distributed with the code. If - * you do not have a copy, see: - * - * http://www.gnu.org/copyleft/lesser.html - * - * Copyright for this code is held jointly by the individual authors. These - * should be listed in @author doc comments. - * - * For more information on the BioJava project and its aims, or to join the - * biojava-l mailing list, visit the home page at: - * - * http://www.biojava.org/ - * - * Created on Feb 23, 2012 Created by Andreas Prlic - * - * @since 3.0.2 - */ -package org.biojava.nbio.core.util; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.SocketTimeoutException; -import java.net.URL; -import java.net.URLConnection; -import java.nio.channels.Channels; -import java.nio.channels.FileChannel; -import java.nio.channels.ReadableByteChannel; -import java.nio.file.FileVisitResult; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.attribute.BasicFileAttributes; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class FileDownloadUtils { - - private static final Logger logger = LoggerFactory.getLogger(FileDownloadUtils.class); - - /** - * Copy the content of file src to dst TODO since java 1.7 this is provided - * in java.nio.file.Files - * - * @param src - * @param dst - * @throws IOException - */ - @SuppressWarnings("resource") - public static void copy(File src, File dst) throws IOException { - - // Took following recipe from - // http://stackoverflow.com/questions/106770/standard-concise-way-to-copy-a-file-in-java - // The nio package seems to be the most efficient way to copy a file - FileChannel source = null; - FileChannel destination = null; - - try { - // we need the supress warnings here (the warning that the stream is not closed is harmless) - // see http://stackoverflow.com/questions/12970407/does-filechannel-close-close-the-underlying-stream - source = new FileInputStream(src).getChannel(); - destination = new FileOutputStream(dst).getChannel(); - destination.transferFrom(source, 0, source.size()); - } finally { - if (source != null) { - source.close(); - } - if (destination != null) { - destination.close(); - } - } - } - - public static String getFileExtension(File f) { - String fileName = f.getName(); - String ext = ""; - int mid = fileName.lastIndexOf("."); - ext = fileName.substring(mid + 1, fileName.length()); - return ext; - } - - public static String getFilePrefix(File f) { - String fileName = f.getName(); - String fname = ""; - - int mid = fileName.indexOf("."); - fname = fileName.substring(0, mid); - - return fname; - } - - /** - * Download the content provided at URL url and store the result to a local - * file, using a temp file to cache the content in case something goes wrong - * in download - * - * @param url - * @param destination - * @throws IOException - */ - public static void downloadFile(URL url, File destination) throws IOException { - int count = 0; - int maxTries = 10; - int timeout = 60000; //60 sec - - File tempFile = File.createTempFile(getFilePrefix(destination), "." + getFileExtension(destination)); - - // Took following recipe from stackoverflow: - // http://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java - // It seems to be the most efficient way to transfer a file - // See: http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html - ReadableByteChannel rbc = null; - FileOutputStream fos = null; - while (true) { - try { - URLConnection connection = prepareURLConnection(url.toString(), timeout); - connection.connect(); - InputStream inputStream = connection.getInputStream(); - - rbc = Channels.newChannel(inputStream); - fos = new FileOutputStream(tempFile); - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - break; - } catch (SocketTimeoutException e) { - if (++count == maxTries) throw e; - } finally { - if (rbc != null) { - rbc.close(); - } - if (fos != null) { - fos.close(); - } - } - } - - logger.debug("Copying temp file {} to final location {}", tempFile, destination); - copy(tempFile, destination); - - // delete the tmp file - tempFile.delete(); - - } - - /** - * Converts path to Unix convention and adds a terminating slash if it was - * omitted - * - * @param path original platform dependent path - * @return path in Unix convention - * @author Peter Rose - * @since 3.2 - */ - public static String toUnixPath(String path) { - String uPath = path; - if (uPath.contains("\\")) { - uPath = uPath.replaceAll("\\\\", "/"); - } - // this should be removed, it's need since "\" is added AtomCache code - if (uPath.endsWith("//")) { - uPath = uPath.substring(0, uPath.length() - 1); - } - if (!uPath.endsWith("/")) { - uPath = uPath + "/"; - } - return uPath; - } - - /** - * Expands ~ in paths to the user's home directory. - * - *

    - * This does not work for some special cases for paths: Other users' homes - * (~user/...), and Tilde expansion within the path (/.../~/...) - * - * @param file - * @return - */ - public static String expandUserHome(String file) { - if (file.startsWith("~" + File.separator)) { - file = System.getProperty("user.home") + file.substring(1); - } - return file; - } - - /** - * Pings a HTTP URL. This effectively sends a HEAD request and returns - * true if the response code is in the 200-399 range. - * - * @param url The HTTP URL to be pinged. - * @param timeout The timeout in millis for both the connection timeout and - * the response read timeout. Note that the total timeout is effectively two - * times the given timeout. - * @return true if the given HTTP URL has returned response - * code 200-399 on a HEAD request within the given timeout, otherwise - * false. - * @author BalusC, - * http://stackoverflow.com/questions/3584210/preferred-java-way-to-ping-a-http-url-for-availability - */ - public static boolean ping(String url, int timeout) { - //url = url.replaceFirst("https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates. - - try { - HttpURLConnection connection = (HttpURLConnection) prepareURLConnection(url, timeout); - connection.setRequestMethod("HEAD"); - int responseCode = connection.getResponseCode(); - return (200 <= responseCode && responseCode <= 399); - } catch (IOException exception) { - return false; - } - } - - /** - * Prepare {@link URLConnection} with customised timeouts. - * - * @param url The URL - * @param timeout The timeout in millis for both the connection timeout and - * the response read timeout. Note that the total timeout is effectively two - * times the given timeout. - * - *

    - * Example of code. - * UrlConnection conn = prepareURLConnection("http://www.google.com/", 20000); - * conn.connect(); - * conn.getInputStream(); - * - *

    - * - * NB. User should execute connect() method before getting input - * stream. - * @return - * @throws IOException - * @author Jacek Grzebyta - */ - public static URLConnection prepareURLConnection(String url, int timeout) throws IOException { - URLConnection connection = new URL(url).openConnection(); - connection.setReadTimeout(timeout); - connection.setConnectTimeout(timeout); - return connection; - } - - /** - * Recursively delete a folder & contents - * - * @param dir directory to delete - */ - public static void deleteDirectory(Path dir) throws IOException { - if(dir == null || !Files.exists(dir)) - return; - Files.walkFileTree(dir, new SimpleFileVisitor() { - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - Files.delete(file); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { - if (e != null) { - throw e; - } - Files.delete(dir); - return FileVisitResult.CONTINUE; - } - }); - } - /** - * Recursively delete a folder & contents - * - * @param dir directory to delete - */ - public static void deleteDirectory(String dir) throws IOException { - deleteDirectory(Paths.get(dir)); - } - - - public static void main(String[] args) { - String url; - url = "http://scop.mrc-lmb.cam.ac.uk/scop/parse/"; - System.out.format("%s\t%s%n", ping(url, 200), url); - url = "http://scop.mrc-lmb.cam.ac.uk/scop/parse/foo"; - System.out.format("%s\t%s%n", ping(url, 200), url); - url = "http://scopzzz.mrc-lmb.cam.ac.uk/scop/parse/"; - System.out.format("%s\t%s%n", ping(url, 200), url); - url = "scop.mrc-lmb.cam.ac.uk"; - System.out.format("%s\t%s%n", ping(url, 200), url); - url = "http://scop.mrc-lmb.cam.ac.uk"; - System.out.format("%s\t%s%n", ping(url, 200), url); - } - -} diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/FlatFileCache.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/FlatFileCache.java index e8feeec8ac..0ca9f46c3e 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/FlatFileCache.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/FlatFileCache.java @@ -44,7 +44,7 @@ public class FlatFileCache { /** * The cache singleton. */ - private static SoftHashMap cache = new SoftHashMap(0); + private static final SoftHashMap cache = new SoftHashMap<>(0); // no public constructor; @@ -73,7 +73,7 @@ public static void addToCache(String key, File fileToCache){ // Read in the bytes int offset = 0; - int numRead = 0; + int numRead; while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { offset += numRead; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/InputStreamProvider.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/InputStreamProvider.java index f129dedb0b..8b7731ae5c 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/InputStreamProvider.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/InputStreamProvider.java @@ -100,7 +100,7 @@ public InputStream getInputStream(String pathToFile) * @return the magic number * @throws IOException */ - private int getMagicNumber(InputStream in) + private static int getMagicNumber(InputStream in) throws IOException { @@ -118,7 +118,7 @@ private int getMagicNumber(InputStream in) public InputStream getInputStream(URL u) throws IOException{ - int magic = 0; + int magic; InputStream inStream = u.openStream(); @@ -160,7 +160,7 @@ public InputStream getInputStream(File f) // use the magic numbers to determine the compression type, // use file extension only as 2nd choice - int magic = 0; + int magic; InputStream test = getInputStreamFromFile(f); @@ -168,7 +168,7 @@ public InputStream getInputStream(File f) test.close(); - InputStream inputStream = null; + InputStream inputStream; String fileName = f.getName(); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/PrettyXMLWriter.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/PrettyXMLWriter.java index 0027dbc7b4..eeca840485 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/PrettyXMLWriter.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/PrettyXMLWriter.java @@ -34,17 +34,17 @@ */ public class PrettyXMLWriter implements XMLWriter { - private int indentUnit = 2; + private final int indentUnit = 2; - private PrintWriter writer; + private final PrintWriter writer; private boolean isOpeningTag = false; private boolean afterNewline = true; private int indent = 0; - private Map namespacePrefixes = new HashMap(); + private final Map namespacePrefixes = new HashMap<>(); private int namespaceSeed = 0; - private LinkedList> namespaceBindings = new LinkedList>(); - private List namespacesDeclared = new ArrayList(); + private final LinkedList> namespaceBindings = new LinkedList<>(); + private final List namespacesDeclared = new ArrayList<>(); public PrettyXMLWriter(PrintWriter writer) { this.writer = writer; @@ -64,10 +64,9 @@ public void declareNamespace(String nsURI, String prefixHint) } } - private void handleDeclaredNamespaces() - throws IOException + private void handleDeclaredNamespaces() throws IOException { - if (namespacesDeclared.size() == 0) { + if (namespacesDeclared.size() > 0) { for (Iterator nsi = namespacesDeclared.iterator(); nsi.hasNext(); ) { String nsURI = nsi.next(); if (!namespacePrefixes.containsKey(nsURI)) { @@ -79,17 +78,13 @@ private void handleDeclaredNamespaces() } } - protected void writeIndent() - throws IOException - { + protected void writeIndent() { for (int i = 0; i < indent * indentUnit; ++i) { writer.write(' '); } } - private void _openTag() - throws IOException - { + private void _openTag() { if (isOpeningTag) { writer.println('>'); afterNewline = true; @@ -108,7 +103,7 @@ private String allocPrefix(String nsURI) { namespacePrefixes.put(nsURI, prefix); List bindings = namespaceBindings.getLast(); if (bindings == null) { - bindings = new ArrayList(); + bindings = new ArrayList<>(); namespaceBindings.removeLast(); namespaceBindings.add(bindings); } @@ -226,9 +221,7 @@ public void closeTag(String nsURI, String localName) } @Override - public void closeTag(String qName) - throws IOException - { + public void closeTag(String qName) { indent--; if (isOpeningTag) { @@ -245,9 +238,7 @@ public void closeTag(String qName) } @Override - public void println(String data) - throws IOException - { + public void println(String data) { if (isOpeningTag) { writer.println('>'); isOpeningTag = false; @@ -258,9 +249,7 @@ public void println(String data) } @Override - public void print(String data) - throws IOException - { + public void print(String data) { if (isOpeningTag) { writer.print('>'); isOpeningTag = false; @@ -270,15 +259,11 @@ public void print(String data) } @Override - public void printRaw(String data) - throws IOException - { + public void printRaw(String data) { writer.println(data); } - protected void printChars(String data) - throws IOException - { + protected void printChars(String data) { if (data == null) { printChars("null"); return; @@ -294,9 +279,7 @@ protected void printChars(String data) } } - protected void printAttributeValue(String data) - throws IOException - { + protected void printAttributeValue(String data) { if (data == null) { printAttributeValue("null"); return; @@ -312,18 +295,14 @@ protected void printAttributeValue(String data) } } - protected void numericalEntity(char c) - throws IOException - { + protected void numericalEntity(char c) { writer.print("&#"); writer.print((int) c); writer.print(';'); } @Override - public void close() - throws IOException - { + public void close() { writer.close(); } } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/SingleLinkageClusterer.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/SingleLinkageClusterer.java index ca58257f48..1a62a232bb 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/SingleLinkageClusterer.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/SingleLinkageClusterer.java @@ -38,11 +38,11 @@ public class SingleLinkageClusterer { private static final Logger logger = LoggerFactory.getLogger(SingleLinkageClusterer.class); - private class LinkedPair { + private static class LinkedPair { - private int first; - private int second; - private double closestDistance; + private final int first; + private final int second; + private final double closestDistance; public LinkedPair(int first, int second, double minDistance) { this.first = first; @@ -65,7 +65,7 @@ public double getClosestDistance() { @Override public String toString() { - String closestDistStr = null; + String closestDistStr; if (closestDistance==Double.MAX_VALUE) { closestDistStr = String.format("%6s", "inf"); } else { @@ -77,11 +77,11 @@ public String toString() { } - private double[][] matrix; + private final double[][] matrix; - private boolean isScoreMatrix; + private final boolean isScoreMatrix; - private int numItems; + private final int numItems; private LinkedPair[] dendrogram; @@ -135,7 +135,7 @@ private void clusterIt() { dendrogram = new LinkedPair[numItems-1]; - logger.debug("Initial matrix: \n"+matrixToString()); + //logger.debug("Initial matrix: \n"+matrixToString()); for (int m=0;m(numItems); + indicesToCheck = new ArrayList<>(numItems); for (int i=0;i=max) { max = matrix[i][j]; - closestPair = new LinkedPair(i,j,max); + closestPair = new LinkedPair(i, j, max); } } @@ -229,7 +225,7 @@ private LinkedPair getClosestPair() { if (matrix[i][j]<=min) { min = matrix[i][j]; - closestPair = new LinkedPair(i,j,min); + closestPair = new LinkedPair(i, j, min); } } @@ -250,7 +246,7 @@ public Map> getClusters(double cutoff) { clusterIt(); } - Map> clusters = new TreeMap>(); + Map> clusters = new TreeMap<>(); int clusterId = 1; @@ -276,7 +272,7 @@ public Map> getClusters(double cutoff) { if (firstClusterId==-1 && secondClusterId==-1) { // neither member is in a cluster yet, let's assign a new cluster and put them both in - Set members = new TreeSet(); + Set members = new TreeSet<>(); members.add(dendrogram[i].getFirst()); members.add(dendrogram[i].getSecond()); clusters.put(clusterId, members); @@ -293,36 +289,32 @@ public Map> getClusters(double cutoff) { Set firstCluster = clusters.get(firstClusterId); Set secondCluster = clusters.get(secondClusterId); if (firstCluster.size()> finalClusters = new TreeMap>(); + Map> finalClusters = new TreeMap<>(); int newClusterId = 1; - for (int oldClusterId:clusters.keySet()) { - finalClusters.put(newClusterId, clusters.get(oldClusterId)); + for (Set integers : clusters.values()) { + finalClusters.put(newClusterId, integers); newClusterId++; } @@ -336,7 +328,7 @@ public Map> getClusters(double cutoff) { } } if (!isAlreadyClustered) { - Set members = new TreeSet(); + Set members = new TreeSet<>(); members.add(i); finalClusters.put(newClusterId, members); newClusterId++; @@ -344,7 +336,7 @@ public Map> getClusters(double cutoff) { } - logger.debug("Clusters: \n"+clustersToString(finalClusters)); + //logger.debug("Clusters: \n"+clustersToString(finalClusters)); return finalClusters; } @@ -367,9 +359,9 @@ private boolean isWithinCutoff(int i, double cutoff) { private String clustersToString(Map> finalClusters) { StringBuilder sb = new StringBuilder(); - for (int cId:finalClusters.keySet()) { - sb.append(cId).append(": "); - for (int member:finalClusters.get(cId)) { + for (Map.Entry> entry : finalClusters.entrySet()) { + sb.append((int) entry.getKey()).append(": "); + for (int member: entry.getValue()) { sb.append(member).append(" "); } sb.append("\n"); diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/SoftHashMap.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/SoftHashMap.java index b13c246baa..48eaca4409 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/SoftHashMap.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/SoftHashMap.java @@ -37,11 +37,11 @@ public class SoftHashMap extends AbstractMap { private final static Logger logger = LoggerFactory.getLogger(SoftHashMap.class); - public static final int DEFAULT_LIMIT = 1; + //public static final int DEFAULT_LIMIT = 1; /** The internal HashMap that stores SoftReference to actual data. */ - private final Map> map = new HashMap>(); + private final Map> map = new HashMap<>(); /** Maximum Number of references you dont want GC to collect. */ @@ -49,11 +49,11 @@ public class SoftHashMap extends AbstractMap { /** The FIFO list of hard references, order of last access. */ - private final LinkedList hardCache = new LinkedList(); + private final LinkedList hardCache = new LinkedList<>(); /** Reference queue for cleared SoftReference objects. */ - private final ReferenceQueue queue = new ReferenceQueue(); + private final ReferenceQueue queue = new ReferenceQueue<>(); public SoftHashMap() { @@ -215,7 +215,7 @@ public synchronized V put(K key, V value) { logger.debug("Putting {} on cache. size: {}", key, size()); - map.put(key, new SoftValue(value, key, queue)); + map.put(key, new SoftValue<>(value, key, queue)); return value; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/StringManipulationHelper.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/StringManipulationHelper.java index f8aef6b35e..bd30662768 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/StringManipulationHelper.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/StringManipulationHelper.java @@ -75,7 +75,7 @@ public static String convertStreamToString(InputStream stream) { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder sb = new StringBuilder(); - String line = null; + String line; try { while ((line = reader.readLine()) != null) { @@ -136,24 +136,18 @@ public static boolean equalsToIgnoreEndline(String expected, String actual) { public static boolean equalsToXml(String expected, String actual) { - Document expectedDocument=null; - Document actualDocument=null; + Document expectedDocument; + Document actualDocument; try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); expectedDocument = documentBuilder.parse(new ByteArrayInputStream(expected.getBytes())); actualDocument = documentBuilder.parse(new ByteArrayInputStream(actual.getBytes())); - } catch (ParserConfigurationException e) { - logger.error("Exception: ", e); - throw new RuntimeException("Couldn't Parse XML", e); - } catch (SAXException e) { - logger.error("Exception: ", e); - throw new RuntimeException("Couldn't Parse XML", e); - } catch (IOException e) { + } catch (ParserConfigurationException | IOException | SAXException e) { logger.error("Exception: ", e); throw new RuntimeException("Couldn't Parse XML", e); } - final DocumentType doctype1 = expectedDocument.getDoctype(); + final DocumentType doctype1 = expectedDocument.getDoctype(); final DocumentType doctype2 = actualDocument.getDoctype(); if (doctype1==null ^ doctype2 == null) { return false; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/UncompressInputStream.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/UncompressInputStream.java index 07708f0f4d..98cc49fa26 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/UncompressInputStream.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/UncompressInputStream.java @@ -176,7 +176,7 @@ public synchronized int read(byte[] buf, int off, int len) // empty stack if stuff still left int s_size = l_stack.length - l_stackp; if (s_size > 0) { - int num = (s_size >= len) ? len : s_size; + int num = Math.min(s_size, len); System.arraycopy(l_stack, l_stackp, buf, off, num); off += num; len -= num; @@ -304,7 +304,7 @@ public synchronized int read(byte[] buf, int off, int len) // And put them out in forward order s_size = l_stack.length - l_stackp; - int num = (s_size >= len) ? len : s_size; + int num = Math.min(s_size, len); System.arraycopy(l_stack, l_stackp, buf, off, num); off += num; len -= num; diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/XMLHelper.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/XMLHelper.java index 7d9e1cad63..0a58829228 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/XMLHelper.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/XMLHelper.java @@ -40,6 +40,8 @@ import javax.xml.xpath.XPathFactory; import java.io.*; import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import static org.biojava.nbio.core.sequence.io.util.IOUtils.close; import static org.biojava.nbio.core.sequence.io.util.IOUtils.openFile; @@ -76,9 +78,12 @@ static public Document loadXML(String fileName) throws SAXException, IOException static public Document inputStreamToDocument(InputStream inputStream) throws SAXException, IOException, ParserConfigurationException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setIgnoringComments(true); + dbf.setIgnoringElementContentWhitespace(true); DocumentBuilder db = dbf.newDocumentBuilder(); + Document doc = db.parse(inputStream); doc.getDocumentElement().normalize(); @@ -123,13 +128,13 @@ static public Element selectParentElement(Element element, String parentName) { } static public Element selectSingleElement(Element element, String xpathExpression) throws XPathExpressionException { - if (xpathExpression.indexOf("/") == -1) { + if (!xpathExpression.contains("/")) { NodeList nodeList = element.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { + int nn = nodeList.getLength(); + for (int i = 0; i < nn; i++) { Node node = nodeList.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(xpathExpression)) { + if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(xpathExpression)) return (Element) node; - } } // NodeList nodes = element.getElementsByTagName(xpathExpression); // if (nodes.getLength() > 0) { @@ -139,34 +144,34 @@ static public Element selectSingleElement(Element element, String xpathExpressio // } } else { XPath xpath = XPathFactory.newInstance().newXPath(); - Element node = (Element) xpath.evaluate(xpathExpression, element, XPathConstants.NODE); - return node; + return (Element) xpath.evaluate(xpathExpression, element, XPathConstants.NODE); } } - static public ArrayList selectElements(Element element, String xpathExpression) throws XPathExpressionException { - ArrayList resultVector = new ArrayList(); + static public List selectElements(Element element, String xpathExpression) throws XPathExpressionException { if (element == null) { - return resultVector; + return Collections.EMPTY_LIST; } - if (xpathExpression.indexOf("/") == -1) { + ArrayList r = new ArrayList<>(); + if (!xpathExpression.contains("/")) { NodeList nodeList = element.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { + int nn = nodeList.getLength(); + for (int i = 0; i < nn; i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(xpathExpression)) { - resultVector.add((Element) node); + r.add((Element) node); } } } else { XPath xpath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xpath.evaluate(xpathExpression, element, XPathConstants.NODESET); - - for (int i = 0; i < nodes.getLength(); i++) { - Node node = nodes.item(i); - resultVector.add((Element) node); - } + int nn = nodes.getLength(); + for (int i = 0; i < nn; i++) + r.add((Element) nodes.item(i)); } - return resultVector; + return r.isEmpty() ? + Collections.EMPTY_LIST : + r; } } diff --git a/biojava-core/src/main/java/org/biojava/nbio/core/util/XMLWriter.java b/biojava-core/src/main/java/org/biojava/nbio/core/util/XMLWriter.java index b6d51d1f25..3a448292b0 100644 --- a/biojava-core/src/main/java/org/biojava/nbio/core/util/XMLWriter.java +++ b/biojava-core/src/main/java/org/biojava/nbio/core/util/XMLWriter.java @@ -38,7 +38,7 @@ public interface XMLWriter { * @param s a string of data to include verbatim in the XML stream */ - public void printRaw(String s) throws IOException; + void printRaw(String s); /** * Open a new namespace-qualified XML tag. @@ -47,7 +47,7 @@ public interface XMLWriter { * @param localName The name of the tag */ - public void openTag(String nsURI, String localName) throws IOException; + void openTag(String nsURI, String localName) throws IOException; /** * Open a new unqualified XML tag. This may also be used if you want @@ -56,7 +56,7 @@ public interface XMLWriter { * @param name The name of the tag. */ - public void openTag(String name) throws IOException; + void openTag(String name) throws IOException; /** * Add an attribute to an element. This will throw an exception if it's not @@ -67,7 +67,7 @@ public interface XMLWriter { * @param value The textual value of the attribute */ - public void attribute(String nsURI, String localName, String value) throws IOException; + void attribute(String nsURI, String localName, String value) throws IOException; /** * Add an un-qualified attribute to an element. This will throw an exception if it's not @@ -77,19 +77,19 @@ public interface XMLWriter { * @param value The textual value of the attribute */ - public void attribute(String qName, String value) throws IOException; + void attribute(String qName, String value) throws IOException; /** * Prints some textual content in an element. */ - public void print(String data) throws IOException; + void print(String data); /** * Prints some textual content, terminated with a newline character. */ - public void println(String data) throws IOException; + void println(String data); /** * Closes an element @@ -98,7 +98,7 @@ public interface XMLWriter { * @param qName The name of the tag */ - public void closeTag(String nsURI, String qName) throws IOException; + void closeTag(String nsURI, String qName) throws IOException; /** * Closes an un-qualified element. @@ -106,7 +106,7 @@ public interface XMLWriter { * @param name The tag name */ - public void closeTag(String name) throws IOException; + void closeTag(String name); /** * Hints that a namespace is going to be used in a sub-tree. Use this method @@ -121,7 +121,7 @@ public interface XMLWriter { * @param prefixHint A suggested prefix-string for this namespace. */ - public void declareNamespace(String nsURI, String prefixHint) throws IOException; + void declareNamespace(String nsURI, String prefixHint) throws IOException; /** * Close this XMLWriter, and it's underlying stream. @@ -129,5 +129,5 @@ public interface XMLWriter { * @since 1.4 */ - public void close() throws IOException; + void close(); } diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/TestAmbiguityCompoundSet.java b/biojava-core/src/test/java/org/biojava/nbio/core/TestAmbiguityCompoundSet.java index 56abb5d802..9ce712581a 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/TestAmbiguityCompoundSet.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/TestAmbiguityCompoundSet.java @@ -20,7 +20,6 @@ */ package org.biojava.nbio.core; -import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.DNASequence; import org.biojava.nbio.core.sequence.RNASequence; import org.biojava.nbio.core.sequence.compound.AmbiguityDNACompoundSet; diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleAlignedSequenceTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleAlignedSequenceTest.java index 8bbc64c182..aba01a2820 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleAlignedSequenceTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleAlignedSequenceTest.java @@ -49,32 +49,29 @@ public class SimpleAlignedSequenceTest { public void setup() throws CompoundNotFoundException { go = new ProteinSequence("ARND"); lo = new ProteinSequence("CEQGHILKM"); - global = new SimpleAlignedSequence(go, Arrays.asList(new Step[] { - Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.GAP})); - local = new SimpleAlignedSequence(lo, Arrays.asList(new Step[] { - Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.GAP, Step.COMPOUND, Step.GAP, Step.COMPOUND, - Step.COMPOUND}), 1, 3); - local2 = new SimpleAlignedSequence(go, Arrays.asList(new Step[] { - Step.COMPOUND, Step.COMPOUND, Step.COMPOUND}), 1, 0); - cs = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + global = new SimpleAlignedSequence<>(go, Arrays.asList(Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.GAP)); + local = new SimpleAlignedSequence<>(lo, Arrays.asList(Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.GAP, Step.COMPOUND, Step.GAP, Step.COMPOUND, + Step.COMPOUND), 1, 3); + local2 = new SimpleAlignedSequence<>(go, Arrays.asList(Step.COMPOUND, Step.COMPOUND, Step.COMPOUND), 1, 0); + cs = AminoAcidCompoundSet.aminoAcidCompoundSet; } @Test(expected=IllegalArgumentException.class) public void testSimpleAlignedSequenceLocal() { - new SimpleAlignedSequence(lo, Arrays.asList(new Step[] {Step.COMPOUND, - Step.COMPOUND, Step.GAP, Step.GAP, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND})); + new SimpleAlignedSequence<>(lo, Arrays.asList(Step.COMPOUND, + Step.COMPOUND, Step.GAP, Step.GAP, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND)); } @Test(expected=IllegalArgumentException.class) public void testSimpleAlignedSequenceLong() { - new SimpleAlignedSequence(go, Arrays.asList(new Step[] {Step.GAP, - Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP})); + new SimpleAlignedSequence<>(go, Arrays.asList(Step.GAP, + Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP)); } @Test(expected=IllegalArgumentException.class) public void testSimpleAlignedSequenceShort() { - new SimpleAlignedSequence(go, Arrays.asList(new Step[] {Step.GAP, - Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.GAP})); + new SimpleAlignedSequence<>(go, Arrays.asList(Step.GAP, + Step.COMPOUND, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.GAP)); } @Test @@ -120,9 +117,9 @@ public void testGetAlignmentIndexAtOutOfBounds4() { @Test public void testGetEnd() { - assertEquals(global.getEnd().getPosition(), Integer.valueOf(6)); - assertEquals(local.getEnd().getPosition(), Integer.valueOf(8)); - assertEquals(local2.getEnd().getPosition(), Integer.valueOf(3)); + assertEquals(6, global.getEnd().getPosition()); + assertEquals(8, local.getEnd().getPosition()); + assertEquals(3, local2.getEnd().getPosition()); } @Test @@ -214,9 +211,9 @@ public void testGetSequenceIndexAtOutOfBounds4() { @Test public void testGetStart() { - assertEquals(global.getStart().getPosition(), Integer.valueOf(2)); - assertEquals(local.getStart().getPosition(), Integer.valueOf(1)); - assertEquals(local2.getStart().getPosition(), Integer.valueOf(1)); + assertEquals(2, global.getStart().getPosition()); + assertEquals(1, local.getStart().getPosition()); + assertEquals(1, local2.getStart().getPosition()); } @Test diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleProfileTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleProfileTest.java index cfd857ac29..60e58cd002 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleProfileTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleProfileTest.java @@ -52,20 +52,17 @@ public void setup() throws CompoundNotFoundException { target = new ProteinSequence("RDG"); query.setAccession(new AccessionID("Query")); target.setAccession(new AccessionID("Target")); - global = new SimpleProfile(query, target, Arrays.asList(new Step[] { - Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP}), 0, 0, Arrays.asList( - new Step[] {Step.GAP, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND}), 0, 0); - local = new SimpleProfile(query, target, Arrays.asList(new Step[] { - Step.COMPOUND, Step.COMPOUND, Step.COMPOUND}), 1, 0, Arrays.asList(new Step[] { Step.COMPOUND, - Step.GAP, Step.COMPOUND}), 0, 1); - single = new SimpleProfile(query); + global = new SimpleProfile<>(query, target, Arrays.asList(Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP), 0, 0, Arrays.asList( + Step.GAP, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND), 0, 0); + local = new SimpleProfile<>(query, target, Arrays.asList(Step.COMPOUND, Step.COMPOUND, Step.COMPOUND), 1, 0, Arrays.asList(Step.COMPOUND, + Step.GAP, Step.COMPOUND), 0, 1); + single = new SimpleProfile<>(query); } @Test(expected=IllegalArgumentException.class) public void testSimpleProfile() { - new SimpleProfile(query, target, Arrays.asList(new Step[] { - Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP}), 0, 0, Arrays.asList( - new Step[] {Step.GAP, Step.COMPOUND, Step.GAP, Step.COMPOUND}), 0, 0); + new SimpleProfile<>(query, target, Arrays.asList(Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP), 0, 0, Arrays.asList( + Step.GAP, Step.COMPOUND, Step.GAP, Step.COMPOUND), 0, 0); } @Test @@ -264,9 +261,9 @@ public void testGetCompoundAtSIntOutOfBounds5() { @Test public void testGetCompoundSet() { - assertEquals(global.getCompoundSet(), AminoAcidCompoundSet.getAminoAcidCompoundSet()); - assertEquals(local.getCompoundSet(), AminoAcidCompoundSet.getAminoAcidCompoundSet()); - assertEquals(single.getCompoundSet(), AminoAcidCompoundSet.getAminoAcidCompoundSet()); + assertEquals(global.getCompoundSet(), AminoAcidCompoundSet.aminoAcidCompoundSet); + assertEquals(local.getCompoundSet(), AminoAcidCompoundSet.aminoAcidCompoundSet); + assertEquals(single.getCompoundSet(), AminoAcidCompoundSet.aminoAcidCompoundSet); } @Test @@ -316,7 +313,7 @@ public void testGetCompoundsAtOutOfBounds6() { @Test public void testGetIndexOf() { - AminoAcidCompoundSet cs = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet cs = AminoAcidCompoundSet.aminoAcidCompoundSet; assertEquals(global.getIndexOf(cs.getCompoundForString("A")), 1); assertEquals(global.getIndexOf(cs.getCompoundForString("R")), 2); assertEquals(global.getIndexOf(cs.getCompoundForString("N")), 3); @@ -384,7 +381,7 @@ public void testGetIndicesAtOutOfBounds6() { @Test public void testGetLastIndexOf() { - AminoAcidCompoundSet cs = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet cs = AminoAcidCompoundSet.aminoAcidCompoundSet; assertEquals(global.getLastIndexOf(cs.getCompoundForString("A")), 1); assertEquals(global.getLastIndexOf(cs.getCompoundForString("R")), 2); assertEquals(global.getLastIndexOf(cs.getCompoundForString("N")), 3); diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleSequencePairTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleSequencePairTest.java index 2c9aedfa91..9cea8140bf 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleSequencePairTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/alignment/SimpleSequencePairTest.java @@ -44,12 +44,9 @@ public class SimpleSequencePairTest { public void setup() throws CompoundNotFoundException { query = new ProteinSequence("ARND"); target = new ProteinSequence("RDG"); - global = new SimpleSequencePair(query, target, Arrays.asList(new Step[] { - Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP}), Arrays.asList(new Step[] { - Step.GAP, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND})); - local = new SimpleSequencePair(query, target, Arrays.asList(new Step[] { - Step.COMPOUND, Step.COMPOUND, Step.COMPOUND}), 1, 0, Arrays.asList(new Step[] { Step.COMPOUND, - Step.GAP, Step.COMPOUND}), 0, 1); + global = new SimpleSequencePair<>(query, target, Arrays.asList(Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.COMPOUND, Step.GAP), Arrays.asList(Step.GAP, Step.COMPOUND, Step.GAP, Step.COMPOUND, Step.COMPOUND)); + local = new SimpleSequencePair<>(query, target, Arrays.asList(Step.COMPOUND, Step.COMPOUND, Step.COMPOUND), 1, 0, Arrays.asList(Step.COMPOUND, + Step.GAP, Step.COMPOUND), 0, 1); } @Test diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/fasta/TestFASTAReader.java b/biojava-core/src/test/java/org/biojava/nbio/core/fasta/TestFASTAReader.java index 75992962d1..6f8263fd91 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/fasta/TestFASTAReader.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/fasta/TestFASTAReader.java @@ -20,12 +20,6 @@ */ package org.biojava.nbio.core.fasta; -import java.io.InputStream; -import java.util.LinkedHashMap; - -import static org.junit.Assert.* ; -import static org.hamcrest.CoreMatchers.* ; - import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; @@ -35,6 +29,12 @@ import org.biojava.nbio.core.sequence.io.util.ClasspathResource; import org.junit.Test; +import java.io.InputStream; +import java.util.LinkedHashMap; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.assertThat; + public class TestFASTAReader { @@ -42,10 +42,10 @@ private void testProcessAll(String path) throws Exception { ClasspathResource r = new ClasspathResource(path); FastaReader fastaReader = null ; try( InputStream inStream = r.getInputStream() ) { - fastaReader = new FastaReader( + fastaReader = new FastaReader<>( inStream, - new GenericFastaHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + new GenericFastaHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap sequences = fastaReader.process(); assertThat(sequences,is(notNullValue())); assertThat(sequences.size(),is(1)); @@ -82,10 +82,10 @@ private void testProcess1(String path) throws Exception { ClasspathResource r = new ClasspathResource(path); FastaReader fastaReader = null ; try( InputStream inStream = r.getInputStream() ) { - fastaReader = new FastaReader( + fastaReader = new FastaReader<>( inStream, - new GenericFastaHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + new GenericFastaHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap out1 = fastaReader.process(1); assertThat(out1,is(notNullValue())); assertThat(out1.size(),is(1)); @@ -124,10 +124,10 @@ private void testProcess2(String path) throws Exception { ClasspathResource r = new ClasspathResource(path); FastaReader fastaReader = null ; try( InputStream inStream = r.getInputStream() ) { - fastaReader = new FastaReader( + fastaReader = new FastaReader<>( inStream, - new GenericFastaHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + new GenericFastaHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap out1 = fastaReader.process(1); assertThat(out1,is(notNullValue())); assertThat(out1.size(),is(1)); diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/search/io/HspTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/search/io/HspTest.java index 0dcaae2c33..0da89818a2 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/search/io/HspTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/search/io/HspTest.java @@ -24,12 +24,9 @@ import org.biojava.nbio.core.search.io.blast.BlastHspBuilder; import org.biojava.nbio.core.sequence.DNASequence; import org.biojava.nbio.core.sequence.compound.NucleotideCompound; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import static org.junit.Assert.*; +import org.junit.*; + +import static org.junit.Assert.assertEquals; /** * @author Paolo Pavan @@ -37,7 +34,7 @@ public class HspTest { - Hsp hspImpl = new BlastHspBuilder() + final Hsp hspImpl = new BlastHspBuilder() .setHspNum(1) .setHspBitScore(377.211) .setHspEvalue(8.04143e-093) @@ -55,7 +52,7 @@ public class HspTest { .setHspIdentityString("||||||||| |||||||||||||||||| ||||||||| |||||||||||||||||||||||| |||||||| ||||||||||||||||||||||| ||||||| |||||||||||||||||||||||||||||||||||| |||||||||||||||||||||||||||||||||| ||||||||| ||||||| |||||||||||||||||||||||| |||||") .createBlastHsp(); - Hsp uncompleteHsp = new BlastHspBuilder() + final Hsp uncompleteHsp = new BlastHspBuilder() .setPercentageIdentity(100.00/100) .setHspAlignLen(48) .setMismatchCount(0) diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/search/io/SearchIOTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/search/io/SearchIOTest.java index a49dae544a..3f5a344c43 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/search/io/SearchIOTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/search/io/SearchIOTest.java @@ -20,15 +20,13 @@ */ package org.biojava.nbio.core.search.io; +import org.biojava.nbio.core.search.io.blast.BlastXMLParser; +import org.junit.*; + import java.io.File; import java.net.URL; -import org.biojava.nbio.core.search.io.blast.BlastXMLParser; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import static org.junit.Assert.*; + +import static org.junit.Assert.fail; /** * Designed by Paolo Pavan. diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/search/io/blast/BlastTabularParserTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/search/io/blast/BlastTabularParserTest.java index c8343b3060..6c4f94926f 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/search/io/blast/BlastTabularParserTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/search/io/blast/BlastTabularParserTest.java @@ -20,19 +20,17 @@ */ package org.biojava.nbio.core.search.io.blast; +import org.biojava.nbio.core.search.io.Hit; +import org.biojava.nbio.core.search.io.Hsp; +import org.biojava.nbio.core.search.io.Result; +import org.junit.*; + import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; -import org.biojava.nbio.core.search.io.Hit; -import org.biojava.nbio.core.search.io.Hsp; -import org.biojava.nbio.core.search.io.Result; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import static org.junit.Assert.*; + +import static org.junit.Assert.assertEquals; /** * @@ -67,7 +65,7 @@ public void testGetFileExtensions() { System.out.println("getFileExtensions"); BlastTabularParser instance = new BlastTabularParser(); - List expResult = new ArrayList(); + List expResult = new ArrayList<>(); expResult.add("blasttabular"); expResult.add("blasttxt"); @@ -143,7 +141,7 @@ public void testCreateObjects() throws Exception { .setHspBitScore(2894) .createBlastHsp(); - List hsplist = new ArrayList(); + List hsplist = new ArrayList<>(); hsplist.add(hsp1Hit1Res1); hsplist.add(hsp1Hit1Res2); @@ -151,7 +149,7 @@ public void testCreateObjects() throws Exception { .setHitDef("CP000411") .setHsps(hsplist) .createBlastHit(); - List hitlist = new ArrayList(); + List hitlist = new ArrayList<>(); hitlist.add(hit1Res1); BlastResult res1 = new BlastResultBuilder() diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/search/io/blast/BlastXMLParserTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/search/io/blast/BlastXMLParserTest.java index 45de0dbd19..ba107fe34e 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/search/io/blast/BlastXMLParserTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/search/io/blast/BlastXMLParserTest.java @@ -20,20 +20,17 @@ */ package org.biojava.nbio.core.search.io.blast; +import org.biojava.nbio.core.search.io.Hit; +import org.biojava.nbio.core.search.io.Hsp; +import org.biojava.nbio.core.search.io.Result; +import org.junit.*; + import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; -import org.biojava.nbio.core.search.io.Hit; -import org.biojava.nbio.core.search.io.Hsp; -import org.biojava.nbio.core.search.io.Result; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; + import static org.junit.Assert.*; -import org.junit.Ignore; /** * @@ -120,7 +117,7 @@ public void testCreateObjects() throws Exception { .setHspHseq("TTAAATTGAGAGTTTGATCCTGGCTCAGGATGAACGCTGGTGGCGTGCCTAATACATGCAAGTCGTACGCTAGCCGCTGAATTGATCCTTCGGGTGAAGTGAGGCAATGACTAGAGTGGCGAACTGGTGAGTAACACGTAAGAAACCTGCCCTTTAGTGGGGGATAACATTTGGAAACAGATGCTAATACCGCGTAACAACAAATCACACATGTGATCTGTTTGAAAGGTCCTTTTGGATCGCTAGAGGATGGTCTTGCGGCGTATTAGCTTGTTGGTAGGGTAGAAGCCTACCAAGGCAATGATGCGTAGCCGAGTTGAGAGACTGGCCGGCCACATTGGGACTGAGACACTGCCCAAACTCCTACGGGAGGCTGCAGTAGGGAATTTTCCGCAATGCACGAAAGTGTGACGGAGCGACGCCGCGTGTGTGATGAAGGCTTTCGGGTCGTAAAGCACTGTTGTAAGGGAAGAATAACTGAATTCAGAGAAAGTTTTCAGCTTGACGGTACCTTACCAGAAAGGGATGGCTAAATACGTGCCAGCAGCCGCGGTAATACGTATGTCCCGAGCGTTATCCGGATTTATTGGGCGTAAAGCGAGCGCAGACGGTTTATTAAGTCTGATGTGAAATCCCGAGGCCCAACCTCGGAACTGCATTGGAAACTGATTTACTTGAGTGCGATAGAGGCAAGTGGAACTCCATGTGTAGCGGTGAAATGCGTAGATATGTGGAAGAACACCAGTGGCGAAAGCGGCTTGCTAGATCGTAACTGACGTTGAGGCTCGAAAGTATGGGTAGCAAACGGGATTAGATACCCCGGTAGTCCATACCGTAAACGATGGGTGCTAGTTGTTAAGAGGTTTCCGCCTCCTAGTGACGTAGCAAACGCATTAAGCACCCCGCCTGAGGAGTACGGCCGCAAGGCTAAAACTTAAAGGAATTGACGGGGACCCGCACAAGCGGTGGAGCATGTGGTTTAATTCGAAGATACGCGAAAAACCTTACCAGGTCTTGACATACCAATGATCGCTTTTGTAATGAAAGCTTTTCTTCGGAACATTGGATACAGGTGGTGCATGGTCGTCGTCAGCTCGTGTCGTGAGATGTTGGGTTAAGTCCCGCAACGAGCGCAACCCTTGTTATTAGTTGCCAGCATTTAGTTGGGCACTCTAATGAGACTGCCGGTGATAAACCGGAGGAAGGTGGGGACGACGTCAGATCATCATGCCCCTTATGACCTGGGCAACACACGTGCTACAATGGGAAGTACAACGAGTCGCAAACCGGCGACGGTAAGCTAATCTCTTAAAACTTCTCTCAGTTCGGACTGGAGTCTGCAACTCGACTCCACGAAGGCGGAATCGCTAGTAATCGCGAATCAGCATGTCGCGGTGAATACGTTCCCGGGTCTTGTACACACCGCCCGTCAAATCATGGGAGTCGGAAGTACCCAAAGTCGCTTGGCTAACTTTTAGAGGCCGGTGCCTAAGGTAAAATCGATGACTGGGATTAAGTCGTAACAAGGTAGCCGTAGGAGAACCTGCGGCTGGATCACCTCCTTTCT") .setHspIdentityString("|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||") .createBlastHsp(); - List hsplist = new ArrayList(); + List hsplist = new ArrayList<>(); hsplist.add(hsp1hit1res1); hsplist.add(hsp1hit1res1); @@ -133,7 +130,7 @@ public void testCreateObjects() throws Exception { .setHsps(hsplist) .createBlastHit(); - List hitlist = new ArrayList(); + List hitlist = new ArrayList<>(); hitlist.add(hit1res1); BlastResult res1 = new BlastResultBuilder() @@ -200,7 +197,7 @@ public void testGetFileExtensions() { * Test of storeObjects method, of class BlastXMLParser. */ @Test - public void testStoreObjects() throws Exception { + public void testStoreObjects() { // not implemented yet } } diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/DNATest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/DNATest.java index f112284740..e2190ce7db 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/DNATest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/DNATest.java @@ -43,8 +43,8 @@ public class DNATest { - private DNACompoundSet set = new DNACompoundSet(); - private AmbiguityDNACompoundSet ambiguity = new AmbiguityDNACompoundSet(); + private final DNACompoundSet set = new DNACompoundSet(); + private final AmbiguityDNACompoundSet ambiguity = new AmbiguityDNACompoundSet(); @Test public void reverseComplement() throws CompoundNotFoundException { @@ -54,17 +54,17 @@ public void reverseComplement() throws CompoundNotFoundException { @Test public void complement() throws CompoundNotFoundException { - String s = new ComplementSequenceView(getSeq()).getSequenceAsString(); + String s = new ComplementSequenceView<>(getSeq()).getSequenceAsString(); assertThat("Complemented sequence not as expected", s, is("TACG")); } @Test public void reverse() throws CompoundNotFoundException { - SequenceView r = new ReversedSequenceView(getSeq()); + SequenceView r = new ReversedSequenceView<>(getSeq()); assertThat("Reversed sequence not as expected", r.getSequenceAsString(), is("CGTA")); assertThat("Base at 2 not right", r.getCompoundAt(2).toString(), is("G")); - List actual = new ArrayList(); + List actual = new ArrayList<>(); List expected = Arrays.asList("C", "G", "T", "A"); for (NucleotideCompound c : r) { actual.add(c.toString()); @@ -165,11 +165,11 @@ public void twoBit() throws CompoundNotFoundException { String expected = "ATGCAACTGA"; DNASequence seq = getSeq(expected); SequenceReader twoBitFromSeq = - new TwoBitSequenceReader(seq); + new TwoBitSequenceReader<>(seq); //being cheeky here & getting compound set from seq SequenceReader twoBitFromString = - new TwoBitSequenceReader(expected, seq.getCompoundSet()); + new TwoBitSequenceReader<>(expected, seq.getCompoundSet()); assertThat("TwoBit from Sequence not as expected", twoBitFromSeq.getSequenceAsString(), is(expected)); assertThat("TwoBit from String not as expected", twoBitFromString.getSequenceAsString(), is(expected)); @@ -180,11 +180,11 @@ public void fourBit() throws CompoundNotFoundException { String expected = "ATGCAACTGA"; DNASequence seq = getSeq(expected); SequenceReader bitFromSeq = - new FourBitSequenceReader(seq); + new FourBitSequenceReader<>(seq); //being cheeky here & getting compound set from seq SequenceReader bitFromString = - new FourBitSequenceReader(expected, seq.getCompoundSet()); + new FourBitSequenceReader<>(expected, seq.getCompoundSet()); assertThat("FourBit from Sequence not as expected", bitFromSeq.getSequenceAsString(), is(expected)); assertThat("FourBit from String not as expected", bitFromString.getSequenceAsString(), is(expected)); @@ -193,7 +193,7 @@ public void fourBit() throws CompoundNotFoundException { @Test(expected = IllegalStateException.class) public void badTwoBit() throws CompoundNotFoundException { DNASequence seq = getSeq(); - new TwoBitSequenceReader("ATNGC", seq.getCompoundSet()); + new TwoBitSequenceReader<>("ATNGC", seq.getCompoundSet()); } @Test @@ -203,7 +203,7 @@ public void singleCompoundSequence() { NucleotideCompound n = cs.getCompoundForString("N"); int length = 1000; - ProxySequenceReader sr = new SingleCompoundSequenceReader(n, cs, length); + ProxySequenceReader sr = new SingleCompoundSequenceReader<>(n, cs, length); DNASequence seq = new DNASequence(sr); int intCount = 0; @@ -268,8 +268,8 @@ public void sequenceEquality() throws CompoundNotFoundException { assertTrue("Asserting sequences are identical ignoring case & case different", SequenceMixin.sequenceEqualityIgnoreCase(d, getSeq("aTgC"))); assertFalse("Sequence lengths differ", SequenceMixin.sequenceEquality(d, getSeq("ATG"))); - DNASequence bsr = new DNASequence(new TwoBitSequenceReader("ATGC", DNACompoundSet.getDNACompoundSet())); - DNASequence bsrCI = new DNASequence(new TwoBitSequenceReader("ATGc", DNACompoundSet.getDNACompoundSet())); + DNASequence bsr = new DNASequence(new TwoBitSequenceReader<>("ATGC", DNACompoundSet.getDNACompoundSet())); + DNASequence bsrCI = new DNASequence(new TwoBitSequenceReader<>("ATGc", DNACompoundSet.getDNACompoundSet())); assertTrue("Asserting sequences are identical; backing stores differ", SequenceMixin.sequenceEquality(d, bsr)); assertTrue("Asserting sequences are identical ignoring case; backing stores differ", SequenceMixin.sequenceEqualityIgnoreCase(d, bsrCI)); diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/JoiningSequenceReaderTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/JoiningSequenceReaderTest.java index 899247ebc6..353daaed51 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/JoiningSequenceReaderTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/JoiningSequenceReaderTest.java @@ -34,13 +34,13 @@ public class JoiningSequenceReaderTest { @Test public void canScan() throws CompoundNotFoundException { JoiningSequenceReader seq = - new JoiningSequenceReader( - new DNASequence("AAAA"), - new DNASequence("GGG"), - new JoiningSequenceReader(new DNASequence("A"), new DNASequence("C")), - new DNASequence("TT"), - new DNASequence("C") - ); + new JoiningSequenceReader<>( + new DNASequence("AAAA"), + new DNASequence("GGG"), + new JoiningSequenceReader<>(new DNASequence("A"), new DNASequence("C")), + new DNASequence("TT"), + new DNASequence("C") + ); String expected = "AAAAGGGACTTC"; @@ -59,12 +59,12 @@ public void canScan() throws CompoundNotFoundException { @Test public void empty() throws CompoundNotFoundException { JoiningSequenceReader seq = - new JoiningSequenceReader( - new DNASequence(""), - new DNASequence(""), - new DNASequence("A"), - new DNASequence("") - ); + new JoiningSequenceReader<>( + new DNASequence(""), + new DNASequence(""), + new DNASequence("A"), + new DNASequence("") + ); assertEquals("Testing empty sequences", "A", seq.getSequenceAsString()); } } diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/MultipleSequenceAlignmentTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/MultipleSequenceAlignmentTest.java index 20acfc2cd2..145e226ff4 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/MultipleSequenceAlignmentTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/MultipleSequenceAlignmentTest.java @@ -43,11 +43,11 @@ public class MultipleSequenceAlignmentTest { @Before public void setup() throws CompoundNotFoundException { - msaProteins = new MultipleSequenceAlignment(); + msaProteins = new MultipleSequenceAlignment<>(); for (int i = 0; i < 8; i++) { msaProteins.addAlignedSequence(new ProteinSequence("ARNDCEQGHILKMFPSTWYVBZJX")); } - msaDNA = new MultipleSequenceAlignment(); + msaDNA = new MultipleSequenceAlignment<>(); for (int i = 0; i < 7; i++) { msaDNA.addAlignedSequence(new DNASequence("ATCGATCGATCGATCG")); } @@ -55,14 +55,14 @@ public void setup() throws CompoundNotFoundException { @Test public void testGetCompoundsAt() { - AminoAcidCompound aminoAcid = AminoAcidCompoundSet.getAminoAcidCompoundSet().getCompoundForString("N"); - List colProteins = new ArrayList(); + AminoAcidCompound aminoAcid = AminoAcidCompoundSet.aminoAcidCompoundSet.getCompoundForString("N"); + List colProteins = new ArrayList<>(); for (int i = 0; i < 8; i++) { colProteins.add(aminoAcid); } assertEquals(msaProteins.getCompoundsAt(3), colProteins); NucleotideCompound nucleotide = DNACompoundSet.getDNACompoundSet().getCompoundForString("C"); - List colDNA = new ArrayList(); + List colDNA = new ArrayList<>(); for (int i = 0; i < 7; i++) { colDNA.add(nucleotide); } diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/TestSequenceEquals.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/TestSequenceEquals.java index 5fe57374d1..d3bac9e212 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/TestSequenceEquals.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/TestSequenceEquals.java @@ -22,7 +22,8 @@ import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; /** * Created by yana on 3/27/17. @@ -39,23 +40,23 @@ public void testSameCompounds() throws Exception{ ProteinSequence seq2 = new ProteinSequence("ARNDCEQGHILKMFPSTWYVBZJXARNDCEQGHILKMFPSTWYVBZJX"); - assertFalse(seq1.equals(seq2)); + assertNotEquals(seq1, seq2); - assertTrue(seq1.equals(seq1)); + assertEquals(seq1, seq1); - assertTrue(seq2.equals(seq2)); + assertEquals(seq2, seq2); ProteinSequence seq3 = new ProteinSequence("ARNDCEQGHILKMFPSTWYVBZJX"); - assertTrue(seq3.equals(seq1)); + assertEquals(seq3, seq1); - assertFalse(seq2.equals(seq3)); + assertNotEquals(seq2, seq3); DNASequence dnaSeq = new DNASequence("ATGGCGGCGCTGAGCGGT"); - assertFalse(seq1.equals(dnaSeq)); + assertNotEquals(seq1, dnaSeq); diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/TranslationTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/TranslationTest.java index 00c520d586..a4abf15e7f 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/TranslationTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/TranslationTest.java @@ -51,9 +51,9 @@ public class TranslationTest { private final static Logger logger = LoggerFactory.getLogger(TranslationTest.class); - private static DNACompoundSet dnaCs = DNACompoundSet.getDNACompoundSet(); - private static AminoAcidCompoundSet aaCs = AminoAcidCompoundSet.getAminoAcidCompoundSet(); - private static DNASequence brca2Dna; + private static final DNACompoundSet dnaCs = DNACompoundSet.getDNACompoundSet(); + private static final AminoAcidCompoundSet aaCs = AminoAcidCompoundSet.aminoAcidCompoundSet; + private static DNASequence brca2Dna; private static Sequence brca2Pep; private static Sequence volvoxDna; private static Sequence volvoxPep; @@ -70,20 +70,20 @@ public static void parseSequences() { "org/biojava/nbio/core/sequence/volvox-peptide.fasta").getInputStream(); try { - FastaReader dnaReader = new FastaReader(cdsIs, - new GenericFastaHeaderParser(), new DNASequenceCreator(dnaCs)); + FastaReader dnaReader = new FastaReader<>(cdsIs, + new GenericFastaHeaderParser<>(), new DNASequenceCreator(dnaCs)); brca2Dna = dnaReader.process().values().iterator().next(); - FastaReader pReader = new FastaReader( - pepIs, new GenericFastaHeaderParser(), new ProteinSequenceCreator( - aaCs)); + FastaReader pReader = new FastaReader<>( + pepIs, new GenericFastaHeaderParser<>(), new ProteinSequenceCreator( + aaCs)); brca2Pep = pReader.process().values().iterator().next(); - FastaReader volvoxDnaReader = new FastaReader(volDnaIs, - new GenericFastaHeaderParser(), new DNASequenceCreator(dnaCs)); + FastaReader volvoxDnaReader = new FastaReader<>(volDnaIs, + new GenericFastaHeaderParser<>(), new DNASequenceCreator(dnaCs)); volvoxDna = volvoxDnaReader.process().values().iterator().next(); - FastaReader volvoxPepReader = new FastaReader( - volPepIs, new GenericFastaHeaderParser(), new ProteinSequenceCreator( - aaCs)); + FastaReader volvoxPepReader = new FastaReader<>( + volPepIs, new GenericFastaHeaderParser<>(), new ProteinSequenceCreator( + aaCs)); volvoxPep = volvoxPepReader.process().values().iterator().next(); } catch (IOException e) { diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/compound/AmbiguityDNACompoundTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/compound/AmbiguityDNACompoundTest.java index ce0cee1691..bcc3e09c2a 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/compound/AmbiguityDNACompoundTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/compound/AmbiguityDNACompoundTest.java @@ -29,7 +29,7 @@ public class AmbiguityDNACompoundTest { - private AmbiguityDNACompoundSet set = AmbiguityDNACompoundSet.getDNACompoundSet(); + private final AmbiguityDNACompoundSet set = AmbiguityDNACompoundSet.getDNACompoundSet(); @Test public void testAmbiguity() { @@ -44,7 +44,7 @@ public void testBasicAmbiguity() { } private NucleotideCompound[] getCompounds(String... compoundStrings) { - List c = new ArrayList(); + List c = new ArrayList<>(); for(String s: compoundStrings) { c.add(set.getCompoundForString(s)); } diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/ABITracerTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/ABITracerTest.java index 89aef23cbb..b27907b79b 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/ABITracerTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/ABITracerTest.java @@ -21,10 +21,11 @@ package org.biojava.nbio.core.sequence.io; +import org.junit.*; + import java.awt.image.BufferedImage; import java.io.File; import java.net.URL; -import org.junit.*; /** * Test file 3730.ab1 is from https://github.com/biopython/biopython/blob/master/Tests/Abi/3730.ab1 @@ -32,19 +33,19 @@ */ public class ABITracerTest { - private String sequence = "GGGCGAGCKYYAYATTTTGGCAAGAATTGAGCTCTATGGCCACAACCATGGTGAGCAAGGGCGAGGAGGATAACATGGCCATCATCAAGGAGTTCATGCGCTTCAAGGTGCACATGGAGGGCTCCGTGAACGGCCACGAGTTCGAGATCGAGGGCGAGGGCGAGGGCCGCCCCTACGAGGGCACCCAGACCGCCAAGCTGAAGGTGACCAAGGGTGGCCCCCTGCCCTTCGCCTGGGACATCCTGTCCCCTCAGTTCATGTACGGCTCCAAGGCCTACGTGAAGCACCCCGCCGACATCCCCGACTACTTGAAGCTGTCCTTCCCCGAGGGCTTCAAGTGGGAGCGCGTGATGAACTTCGAGGACGGCGGCGTGGTGACCGTGACCCAGGACTCCTCCCTGCAGGACGGCGAGTTCATCTACAAGGTGAAGCTGCGCGGCACCAACTTCCCCTCCGACGGCCCCGTAATGCAGAAGAAGACCATGGGCTGGGAGGCCTCCTCCGAGCGGATGTACCCCGAGGACGGCGCCCTGAAGGGCGAGATCAAGCAGAGGCTGAAGCTGAAGGACGGCGGCCACTACGACGCTGAGGTCAAGACCACCTACAAGGCCAAGAAGCCCGTGCAGCTGCCCGGCGCCTACAACGTCAACATCAAGTTGGACATCACCTCCCACAACGAGGACTACACCATCGTGGAACAGTACGAACGCGCCGAGGGCCGCCACTCCACCGGCGGCATGGACGAGCTGTACAAGGGCGGCAGCGGCATGGTGAGCAAGGGCGAGGAGCTGTTCACCGGGGTGGTGCCCATCCTGGTCGAGCTGGACGGCGACGTAAACGGCCACAAGTTCAGCGTGTCCGGCGAGGGCGAGGGCGATGCCACCTACGGCAAGCTGACCCTGAAGTTCATCTGCACCACCGGCAAGCTGCCCGTGCCCTGGCCCACCCTCGTGACCACCCTGACCTACGGCGTGCAGTGCTTCAGCCGCTACCCCGACCACATGAAGCAGCACGACTTCTTCAAGTCCGCCATGCCCGAAGGCTACGTCCAGGAGCGCACCATCTTCTTCAAGGACGACGGCAACTACAARACCCGCGCCGAGGTGAARTTCGAGGGCGACACCCTGGTGAACCGCATCGAGCTGAAAGGGGCAYCGCACCTTTC"; - private int[] qual = {20, 3, 4, 4, 4, 6, 4, 4, 0, 0, 0, 6, 0, 10, 20, 26, 22, 17, 21, 31, 29, 32, 28, 18, 23, 17, 19, 35, 36, 50, 39, 50, 50, 50, 50, 50, 25, 35, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 35, 39, 33, 20, 35, 31, 50, 50, 50, 50, 50, 50, 50, 50, 50, 31, 50, 35, 31, 23, 28, 31, 21, 43, 39, 35, 24, 30, 26, 35, 31, 50, 50, 50, 50, 50, 50, 50, 50, 50, 39, 31, 24, 39, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 31, 31, 43, 43, 50, 50, 50, 50, 50, 31, 31, 31, 31, 50, 50, 50, 50, 50, 50, 50, 50, 31, 31, 35, 50, 50, 50, 50, 31, 36, 55, 55, 55, 55, 36, 55, 55, 55, 55, 55, 36, 55, 55, 55, 55, 55, 36, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 40, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 36, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 40, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 43, 43, 50, 43, 43, 50, 43, 43, 50, 43, 43, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 43, 43, 50, 43, 43, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 28, 28, 35, 28, 28, 35, 28, 28, 35, 28, 28, 35, 28, 28, 35, 28, 21, 28, 35, 28, 28, 35, 35, 35, 35, 35, 37, 38, 21, 28, 35, 28, 28, 35, 35, 35, 35, 35, 35, 35, 36, 36, 21, 39, 35, 35, 35, 39, 35, 37, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 28, 28, 35, 35, 28, 28, 35, 35, 35, 36, 36, 22, 39, 35, 35, 35, 35, 35, 35, 37, 38, 28, 35, 21, 36, 36, 37, 35, 35, 20, 39, 39, 35, 35, 35, 35, 37, 38, 28, 35, 37, 34, 35, 24, 24, 27, 25, 20, 24, 37, 35, 27, 21, 20, 21, 27, 17, 20, 24, 32, 26, 20, 12, 20, 10, 20, 24, 25, 23, 20, 32, 24, 24, 23, 20, 24, 23, 18, 34, 34, 34, 22, 26, 24, 24, 18, 22, 22, 23, 25, 20, 12, 20, 24, 23, 24, 23, 22, 20, 20, 0, 20, 24, 23, 20, 8, 10, 4, 20, 20, 3, 7, 19, 20, 4, 4, 7, 7, 0, 7, 11, 18, 8, 3, 23, 23, 20, 11, 4, 20, 18, 12, 20, 20, 20, 4, 20, 4, 2, 3, 21, 21, 21, 21, 10, 15, 14, 15, 19, 2, 4, 3, 6, 11, 3, 4, 6, 21, 16, 20, 11, 1, 4, 12, 0, 15, 8, 1, 3, 3, 12, 1, 11, 20, 4}; - private int[] base = {2, 13, 38, 51, 67, 78, 92, 118, 138, 162, 181, 191, 210, 222, 239, 253, 266, 280, 288, 304, 317, 333, 347, 359, 375, 386, 394, 406, 418, 433, 444, 457, 472, 482, 496, 506, 519, 529, 544, 557, 569, 579, 590, 601, 614, 626, 638, 649, 663, 673, 686, 706, 715, 731, 740, 753, 765, 777, 787, 799, 813, 826, 838, 854, 863, 876, 892, 901, 913, 929, 937, 948, 960, 970, 981, 993, 1004, 1017, 1034, 1045, 1056, 1068, 1080, 1091, 1103, 1115, 1126, 1138, 1148, 1160, 1177, 1187, 1199, 1211, 1222, 1232, 1243, 1254, 1268, 1279, 1294, 1307, 1319, 1330, 1341, 1352, 1362, 1374, 1388, 1398, 1411, 1422, 1433, 1444, 1456, 1466, 1479, 1497, 1506, 1519, 1531, 1543, 1556, 1567, 1578, 1589, 1604, 1614, 1630, 1641, 1651, 1662, 1675, 1688, 1700, 1711, 1721, 1732, 1748, 1758, 1772, 1784, 1795, 1806, 1820, 1830, 1844, 1855, 1866, 1877, 1892, 1902, 1914, 1926, 1939, 1950, 1965, 1974, 1986, 1999, 2011, 2023, 2037, 2047, 2059, 2072, 2084, 2096, 2107, 2120, 2132, 2144, 2156, 2169, 2180, 2191, 2202, 2217, 2227, 2239, 2251, 2264, 2275, 2286, 2297, 2309, 2321, 2332, 2347, 2358, 2369, 2381, 2394, 2406, 2417, 2429, 2439, 2452, 2465, 2476, 2490, 2501, 2512, 2524, 2536, 2546, 2560, 2570, 2581, 2593, 2605, 2616, 2628, 2640, 2653, 2664, 2676, 2688, 2700, 2712, 2723, 2735, 2748, 2759, 2772, 2784, 2795, 2808, 2820, 2831, 2842, 2854, 2866, 2878, 2888, 2901, 2913, 2927, 2936, 2947, 2958, 2970, 2982, 2994, 3005, 3019, 3030, 3041, 3053, 3064, 3077, 3088, 3099, 3110, 3123, 3135, 3146, 3157, 3168, 3179, 3192, 3203, 3214, 3226, 3238, 3251, 3263, 3275, 3286, 3297, 3308, 3320, 3331, 3344, 3356, 3368, 3380, 3391, 3402, 3415, 3426, 3440, 3451, 3462, 3474, 3485, 3496, 3508, 3520, 3532, 3543, 3556, 3569, 3580, 3593, 3604, 3615, 3626, 3638, 3650, 3661, 3673, 3684, 3698, 3709, 3721, 3732, 3744, 3756, 3767, 3779, 3792, 3803, 3814, 3827, 3838, 3850, 3862, 3873, 3885, 3897, 3909, 3920, 3932, 3943, 3955, 3966, 3980, 3990, 4002, 4014, 4026, 4038, 4050, 4061, 4072, 4083, 4095, 4107, 4119, 4131, 4143, 4156, 4167, 4179, 4191, 4203, 4215, 4227, 4238, 4252, 4262, 4274, 4287, 4298, 4310, 4321, 4333, 4345, 4356, 4370, 4381, 4393, 4406, 4417, 4428, 4440, 4453, 4464, 4477, 4489, 4500, 4513, 4524, 4536, 4548, 4560, 4573, 4583, 4595, 4607, 4620, 4631, 4645, 4655, 4667, 4679, 4690, 4702, 4714, 4728, 4739, 4750, 4762, 4774, 4786, 4798, 4810, 4821, 4833, 4845, 4857, 4869, 4880, 4892, 4905, 4916, 4927, 4940, 4952, 4963, 4977, 4988, 5000, 5012, 5023, 5034, 5045, 5057, 5069, 5081, 5093, 5104, 5115, 5127, 5139, 5151, 5163, 5176, 5188, 5199, 5211, 5223, 5235, 5247, 5259, 5272, 5283, 5296, 5308, 5320, 5331, 5343, 5354, 5366, 5378, 5390, 5402, 5414, 5426, 5438, 5450, 5462, 5474, 5486, 5497, 5510, 5521, 5532, 5544, 5557, 5569, 5581, 5592, 5604, 5617, 5629, 5641, 5652, 5663, 5676, 5687, 5699, 5712, 5724, 5735, 5748, 5760, 5771, 5784, 5794, 5806, 5817, 5829, 5841, 5853, 5866, 5879, 5891, 5903, 5916, 5928, 5941, 5952, 5964, 5976, 5988, 6000, 6012, 6024, 6036, 6048, 6060, 6072, 6085, 6096, 6109, 6121, 6133, 6146, 6157, 6168, 6180, 6192, 6203, 6215, 6227, 6239, 6251, 6265, 6276, 6289, 6302, 6313, 6325, 6337, 6349, 6361, 6374, 6386, 6398, 6410, 6422, 6436, 6448, 6459, 6471, 6483, 6495, 6507, 6520, 6532, 6545, 6555, 6567, 6579, 6591, 6603, 6615, 6627, 6640, 6652, 6664, 6676, 6688, 6700, 6713, 6726, 6738, 6749, 6761, 6774, 6786, 6799, 6811, 6823, 6835, 6848, 6859, 6871, 6883, 6895, 6907, 6920, 6933, 6945, 6956, 6968, 6980, 6992, 7005, 7016, 7030, 7042, 7053, 7066, 7079, 7091, 7104, 7115, 7128, 7140, 7152, 7163, 7175, 7187, 7200, 7212, 7224, 7235, 7248, 7260, 7272, 7285, 7297, 7309, 7321, 7333, 7345, 7358, 7370, 7382, 7394, 7406, 7419, 7431, 7443, 7455, 7468, 7480, 7492, 7505, 7517, 7530, 7542, 7554, 7566, 7578, 7591, 7603, 7615, 7628, 7640, 7653, 7666, 7677, 7690, 7702, 7714, 7727, 7738, 7750, 7762, 7775, 7786, 7799, 7812, 7823, 7836, 7848, 7859, 7871, 7884, 7896, 7909, 7921, 7933, 7946, 7958, 7971, 7984, 7996, 8007, 8019, 8032, 8044, 8056, 8069, 8081, 8094, 8107, 8119, 8131, 8143, 8155, 8167, 8179, 8192, 8205, 8218, 8230, 8244, 8255, 8267, 8279, 8291, 8303, 8315, 8328, 8340, 8353, 8366, 8378, 8392, 8404, 8417, 8431, 8443, 8455, 8467, 8479, 8492, 8504, 8516, 8529, 8543, 8555, 8567, 8580, 8593, 8606, 8619, 8632, 8644, 8658, 8670, 8683, 8695, 8708, 8721, 8733, 8746, 8759, 8771, 8783, 8795, 8808, 8821, 8833, 8845, 8858, 8871, 8885, 8898, 8910, 8923, 8936, 8949, 8960, 8973, 8986, 9000, 9012, 9025, 9038, 9051, 9064, 9076, 9089, 9102, 9114, 9126, 9139, 9151, 9164, 9177, 9191, 9204, 9217, 9230, 9243, 9255, 9268, 9281, 9294, 9307, 9320, 9333, 9345, 9358, 9371, 9384, 9398, 9412, 9424, 9437, 9450, 9462, 9475, 9488, 9501, 9514, 9528, 9542, 9554, 9567, 9581, 9593, 9606, 9619, 9632, 9645, 9658, 9671, 9682, 9695, 9708, 9721, 9735, 9749, 9762, 9776, 9789, 9802, 9815, 9828, 9842, 9855, 9867, 9880, 9893, 9906, 9920, 9933, 9947, 9960, 9974, 9987, 10000, 10014, 10027, 10040, 10054, 10067, 10081, 10095, 10107, 10120, 10134, 10148, 10161, 10175, 10188, 10201, 10214, 10228, 10241, 10254, 10267, 10280, 10294, 10309, 10322, 10335, 10348, 10362, 10374, 10387, 10401, 10415, 10428, 10441, 10455, 10469, 10482, 10497, 10510, 10523, 10537, 10551, 10565, 10579, 10593, 10606, 10621, 10634, 10647, 10661, 10675, 10689, 10704, 10719, 10732, 10746, 10760, 10774, 10788, 10802, 10815, 10829, 10843, 10856, 10871, 10884, 10898, 10913, 10927, 10940, 10955, 10970, 10984, 10999, 11013, 11027, 11042, 11056, 11071, 11086, 11100, 11114, 11128, 11142, 11158, 11171, 11186, 11200, 11213, 11228, 11241, 11255, 11270, 11284, 11299, 11314, 11328, 11342, 11356, 11370, 11385, 11399, 11413, 11429, 11445, 11460, 11474, 11489, 11503, 11518, 11533, 11549, 11563, 11577, 11592, 11607, 11621, 11637, 11651, 11665, 11680, 11694, 11708, 11725, 11740, 11754, 11768, 11784, 11798, 11813, 11828, 11843, 11858, 11874, 11888, 11904, 11920, 11933, 11948, 11964, 11979, 11993, 12009, 12024, 12041, 12058, 12071, 12087, 12102, 12117, 12132, 12148, 12165, 12179, 12195, 12210, 12226, 12241, 12256, 12273, 12288, 12304, 12320, 12335, 12350, 12365, 12382, 12398, 12414, 12430, 12446, 12462, 12478, 12495, 12511, 12525, 12541, 12556, 12575, 12591, 12605, 12622, 12638, 12653, 12671, 12686, 12705, 12721, 12739, 12756, 12772, 12788, 12806, 12822, 12839, 12855, 12873, 12890, 12908, 12923, 12941, 12960, 12975, 12992, 13009, 13024, 13040, 13059, 13076, 13092, 13109, 13128, 13145, 13161, 13179, 13194, 13216, 13233, 13249, 13266, 13287, 13303, 13322, 13337, 13357, 13375, 13392, 13410, 13424, 13446, 13465, 13480, 13499, 13517, 13533, 13559, 13575, 13595, 13612, 13632, 13650, 13670, 13687, 13706, 13726, 13744, 13765, 13783, 13803, 13822, 13841, 13860, 13879, 13897, 13917, 13936, 13960, 13979, 13996, 14019, 14040, 14057, 14077, 14102, 14122, 14141, 14163, 14184, 14202, 14225, 14244, 14265, 14287, 14312, 14336, 14356, 14375, 14393, 14420, 14438, 14465, 14483, 14500, 14536, 14555, 14575, 14604, 14619, 14648, 14668, 14691, 14725, 14748, 14770, 14788, 14818, 14840, 14862, 14888, 14921, 14939, 14969, 14996, 15022, 15051, 15075, 15098, 15130, 15149, 15167, 15218, 15237, 15276, 15297, 15333, 15356, 15379, 15418, 15447, 15481, 15508, 15530, 15574, 15599, 15643, 15680, 15697, 15743, 15759, 15775, 15813, 15845, 15877, 15911, 15931, 15968, 16014, 16049, 16077, 16088, 16138, 16149, 16185, 16200, 16241, 16280, 16296}; + private final String sequence = "GGGCGAGCKYYAYATTTTGGCAAGAATTGAGCTCTATGGCCACAACCATGGTGAGCAAGGGCGAGGAGGATAACATGGCCATCATCAAGGAGTTCATGCGCTTCAAGGTGCACATGGAGGGCTCCGTGAACGGCCACGAGTTCGAGATCGAGGGCGAGGGCGAGGGCCGCCCCTACGAGGGCACCCAGACCGCCAAGCTGAAGGTGACCAAGGGTGGCCCCCTGCCCTTCGCCTGGGACATCCTGTCCCCTCAGTTCATGTACGGCTCCAAGGCCTACGTGAAGCACCCCGCCGACATCCCCGACTACTTGAAGCTGTCCTTCCCCGAGGGCTTCAAGTGGGAGCGCGTGATGAACTTCGAGGACGGCGGCGTGGTGACCGTGACCCAGGACTCCTCCCTGCAGGACGGCGAGTTCATCTACAAGGTGAAGCTGCGCGGCACCAACTTCCCCTCCGACGGCCCCGTAATGCAGAAGAAGACCATGGGCTGGGAGGCCTCCTCCGAGCGGATGTACCCCGAGGACGGCGCCCTGAAGGGCGAGATCAAGCAGAGGCTGAAGCTGAAGGACGGCGGCCACTACGACGCTGAGGTCAAGACCACCTACAAGGCCAAGAAGCCCGTGCAGCTGCCCGGCGCCTACAACGTCAACATCAAGTTGGACATCACCTCCCACAACGAGGACTACACCATCGTGGAACAGTACGAACGCGCCGAGGGCCGCCACTCCACCGGCGGCATGGACGAGCTGTACAAGGGCGGCAGCGGCATGGTGAGCAAGGGCGAGGAGCTGTTCACCGGGGTGGTGCCCATCCTGGTCGAGCTGGACGGCGACGTAAACGGCCACAAGTTCAGCGTGTCCGGCGAGGGCGAGGGCGATGCCACCTACGGCAAGCTGACCCTGAAGTTCATCTGCACCACCGGCAAGCTGCCCGTGCCCTGGCCCACCCTCGTGACCACCCTGACCTACGGCGTGCAGTGCTTCAGCCGCTACCCCGACCACATGAAGCAGCACGACTTCTTCAAGTCCGCCATGCCCGAAGGCTACGTCCAGGAGCGCACCATCTTCTTCAAGGACGACGGCAACTACAARACCCGCGCCGAGGTGAARTTCGAGGGCGACACCCTGGTGAACCGCATCGAGCTGAAAGGGGCAYCGCACCTTTC"; + private final int[] qual = {20, 3, 4, 4, 4, 6, 4, 4, 0, 0, 0, 6, 0, 10, 20, 26, 22, 17, 21, 31, 29, 32, 28, 18, 23, 17, 19, 35, 36, 50, 39, 50, 50, 50, 50, 50, 25, 35, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 35, 39, 33, 20, 35, 31, 50, 50, 50, 50, 50, 50, 50, 50, 50, 31, 50, 35, 31, 23, 28, 31, 21, 43, 39, 35, 24, 30, 26, 35, 31, 50, 50, 50, 50, 50, 50, 50, 50, 50, 39, 31, 24, 39, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 31, 31, 43, 43, 50, 50, 50, 50, 50, 31, 31, 31, 31, 50, 50, 50, 50, 50, 50, 50, 50, 31, 31, 35, 50, 50, 50, 50, 31, 36, 55, 55, 55, 55, 36, 55, 55, 55, 55, 55, 36, 55, 55, 55, 55, 55, 36, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 40, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 36, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 40, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 43, 43, 50, 43, 43, 50, 43, 43, 50, 43, 43, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 43, 43, 50, 43, 43, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 28, 28, 35, 28, 28, 35, 28, 28, 35, 28, 28, 35, 28, 28, 35, 28, 21, 28, 35, 28, 28, 35, 35, 35, 35, 35, 37, 38, 21, 28, 35, 28, 28, 35, 35, 35, 35, 35, 35, 35, 36, 36, 21, 39, 35, 35, 35, 39, 35, 37, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 28, 28, 35, 35, 28, 28, 35, 35, 35, 36, 36, 22, 39, 35, 35, 35, 35, 35, 35, 37, 38, 28, 35, 21, 36, 36, 37, 35, 35, 20, 39, 39, 35, 35, 35, 35, 37, 38, 28, 35, 37, 34, 35, 24, 24, 27, 25, 20, 24, 37, 35, 27, 21, 20, 21, 27, 17, 20, 24, 32, 26, 20, 12, 20, 10, 20, 24, 25, 23, 20, 32, 24, 24, 23, 20, 24, 23, 18, 34, 34, 34, 22, 26, 24, 24, 18, 22, 22, 23, 25, 20, 12, 20, 24, 23, 24, 23, 22, 20, 20, 0, 20, 24, 23, 20, 8, 10, 4, 20, 20, 3, 7, 19, 20, 4, 4, 7, 7, 0, 7, 11, 18, 8, 3, 23, 23, 20, 11, 4, 20, 18, 12, 20, 20, 20, 4, 20, 4, 2, 3, 21, 21, 21, 21, 10, 15, 14, 15, 19, 2, 4, 3, 6, 11, 3, 4, 6, 21, 16, 20, 11, 1, 4, 12, 0, 15, 8, 1, 3, 3, 12, 1, 11, 20, 4}; + private final int[] base = {2, 13, 38, 51, 67, 78, 92, 118, 138, 162, 181, 191, 210, 222, 239, 253, 266, 280, 288, 304, 317, 333, 347, 359, 375, 386, 394, 406, 418, 433, 444, 457, 472, 482, 496, 506, 519, 529, 544, 557, 569, 579, 590, 601, 614, 626, 638, 649, 663, 673, 686, 706, 715, 731, 740, 753, 765, 777, 787, 799, 813, 826, 838, 854, 863, 876, 892, 901, 913, 929, 937, 948, 960, 970, 981, 993, 1004, 1017, 1034, 1045, 1056, 1068, 1080, 1091, 1103, 1115, 1126, 1138, 1148, 1160, 1177, 1187, 1199, 1211, 1222, 1232, 1243, 1254, 1268, 1279, 1294, 1307, 1319, 1330, 1341, 1352, 1362, 1374, 1388, 1398, 1411, 1422, 1433, 1444, 1456, 1466, 1479, 1497, 1506, 1519, 1531, 1543, 1556, 1567, 1578, 1589, 1604, 1614, 1630, 1641, 1651, 1662, 1675, 1688, 1700, 1711, 1721, 1732, 1748, 1758, 1772, 1784, 1795, 1806, 1820, 1830, 1844, 1855, 1866, 1877, 1892, 1902, 1914, 1926, 1939, 1950, 1965, 1974, 1986, 1999, 2011, 2023, 2037, 2047, 2059, 2072, 2084, 2096, 2107, 2120, 2132, 2144, 2156, 2169, 2180, 2191, 2202, 2217, 2227, 2239, 2251, 2264, 2275, 2286, 2297, 2309, 2321, 2332, 2347, 2358, 2369, 2381, 2394, 2406, 2417, 2429, 2439, 2452, 2465, 2476, 2490, 2501, 2512, 2524, 2536, 2546, 2560, 2570, 2581, 2593, 2605, 2616, 2628, 2640, 2653, 2664, 2676, 2688, 2700, 2712, 2723, 2735, 2748, 2759, 2772, 2784, 2795, 2808, 2820, 2831, 2842, 2854, 2866, 2878, 2888, 2901, 2913, 2927, 2936, 2947, 2958, 2970, 2982, 2994, 3005, 3019, 3030, 3041, 3053, 3064, 3077, 3088, 3099, 3110, 3123, 3135, 3146, 3157, 3168, 3179, 3192, 3203, 3214, 3226, 3238, 3251, 3263, 3275, 3286, 3297, 3308, 3320, 3331, 3344, 3356, 3368, 3380, 3391, 3402, 3415, 3426, 3440, 3451, 3462, 3474, 3485, 3496, 3508, 3520, 3532, 3543, 3556, 3569, 3580, 3593, 3604, 3615, 3626, 3638, 3650, 3661, 3673, 3684, 3698, 3709, 3721, 3732, 3744, 3756, 3767, 3779, 3792, 3803, 3814, 3827, 3838, 3850, 3862, 3873, 3885, 3897, 3909, 3920, 3932, 3943, 3955, 3966, 3980, 3990, 4002, 4014, 4026, 4038, 4050, 4061, 4072, 4083, 4095, 4107, 4119, 4131, 4143, 4156, 4167, 4179, 4191, 4203, 4215, 4227, 4238, 4252, 4262, 4274, 4287, 4298, 4310, 4321, 4333, 4345, 4356, 4370, 4381, 4393, 4406, 4417, 4428, 4440, 4453, 4464, 4477, 4489, 4500, 4513, 4524, 4536, 4548, 4560, 4573, 4583, 4595, 4607, 4620, 4631, 4645, 4655, 4667, 4679, 4690, 4702, 4714, 4728, 4739, 4750, 4762, 4774, 4786, 4798, 4810, 4821, 4833, 4845, 4857, 4869, 4880, 4892, 4905, 4916, 4927, 4940, 4952, 4963, 4977, 4988, 5000, 5012, 5023, 5034, 5045, 5057, 5069, 5081, 5093, 5104, 5115, 5127, 5139, 5151, 5163, 5176, 5188, 5199, 5211, 5223, 5235, 5247, 5259, 5272, 5283, 5296, 5308, 5320, 5331, 5343, 5354, 5366, 5378, 5390, 5402, 5414, 5426, 5438, 5450, 5462, 5474, 5486, 5497, 5510, 5521, 5532, 5544, 5557, 5569, 5581, 5592, 5604, 5617, 5629, 5641, 5652, 5663, 5676, 5687, 5699, 5712, 5724, 5735, 5748, 5760, 5771, 5784, 5794, 5806, 5817, 5829, 5841, 5853, 5866, 5879, 5891, 5903, 5916, 5928, 5941, 5952, 5964, 5976, 5988, 6000, 6012, 6024, 6036, 6048, 6060, 6072, 6085, 6096, 6109, 6121, 6133, 6146, 6157, 6168, 6180, 6192, 6203, 6215, 6227, 6239, 6251, 6265, 6276, 6289, 6302, 6313, 6325, 6337, 6349, 6361, 6374, 6386, 6398, 6410, 6422, 6436, 6448, 6459, 6471, 6483, 6495, 6507, 6520, 6532, 6545, 6555, 6567, 6579, 6591, 6603, 6615, 6627, 6640, 6652, 6664, 6676, 6688, 6700, 6713, 6726, 6738, 6749, 6761, 6774, 6786, 6799, 6811, 6823, 6835, 6848, 6859, 6871, 6883, 6895, 6907, 6920, 6933, 6945, 6956, 6968, 6980, 6992, 7005, 7016, 7030, 7042, 7053, 7066, 7079, 7091, 7104, 7115, 7128, 7140, 7152, 7163, 7175, 7187, 7200, 7212, 7224, 7235, 7248, 7260, 7272, 7285, 7297, 7309, 7321, 7333, 7345, 7358, 7370, 7382, 7394, 7406, 7419, 7431, 7443, 7455, 7468, 7480, 7492, 7505, 7517, 7530, 7542, 7554, 7566, 7578, 7591, 7603, 7615, 7628, 7640, 7653, 7666, 7677, 7690, 7702, 7714, 7727, 7738, 7750, 7762, 7775, 7786, 7799, 7812, 7823, 7836, 7848, 7859, 7871, 7884, 7896, 7909, 7921, 7933, 7946, 7958, 7971, 7984, 7996, 8007, 8019, 8032, 8044, 8056, 8069, 8081, 8094, 8107, 8119, 8131, 8143, 8155, 8167, 8179, 8192, 8205, 8218, 8230, 8244, 8255, 8267, 8279, 8291, 8303, 8315, 8328, 8340, 8353, 8366, 8378, 8392, 8404, 8417, 8431, 8443, 8455, 8467, 8479, 8492, 8504, 8516, 8529, 8543, 8555, 8567, 8580, 8593, 8606, 8619, 8632, 8644, 8658, 8670, 8683, 8695, 8708, 8721, 8733, 8746, 8759, 8771, 8783, 8795, 8808, 8821, 8833, 8845, 8858, 8871, 8885, 8898, 8910, 8923, 8936, 8949, 8960, 8973, 8986, 9000, 9012, 9025, 9038, 9051, 9064, 9076, 9089, 9102, 9114, 9126, 9139, 9151, 9164, 9177, 9191, 9204, 9217, 9230, 9243, 9255, 9268, 9281, 9294, 9307, 9320, 9333, 9345, 9358, 9371, 9384, 9398, 9412, 9424, 9437, 9450, 9462, 9475, 9488, 9501, 9514, 9528, 9542, 9554, 9567, 9581, 9593, 9606, 9619, 9632, 9645, 9658, 9671, 9682, 9695, 9708, 9721, 9735, 9749, 9762, 9776, 9789, 9802, 9815, 9828, 9842, 9855, 9867, 9880, 9893, 9906, 9920, 9933, 9947, 9960, 9974, 9987, 10000, 10014, 10027, 10040, 10054, 10067, 10081, 10095, 10107, 10120, 10134, 10148, 10161, 10175, 10188, 10201, 10214, 10228, 10241, 10254, 10267, 10280, 10294, 10309, 10322, 10335, 10348, 10362, 10374, 10387, 10401, 10415, 10428, 10441, 10455, 10469, 10482, 10497, 10510, 10523, 10537, 10551, 10565, 10579, 10593, 10606, 10621, 10634, 10647, 10661, 10675, 10689, 10704, 10719, 10732, 10746, 10760, 10774, 10788, 10802, 10815, 10829, 10843, 10856, 10871, 10884, 10898, 10913, 10927, 10940, 10955, 10970, 10984, 10999, 11013, 11027, 11042, 11056, 11071, 11086, 11100, 11114, 11128, 11142, 11158, 11171, 11186, 11200, 11213, 11228, 11241, 11255, 11270, 11284, 11299, 11314, 11328, 11342, 11356, 11370, 11385, 11399, 11413, 11429, 11445, 11460, 11474, 11489, 11503, 11518, 11533, 11549, 11563, 11577, 11592, 11607, 11621, 11637, 11651, 11665, 11680, 11694, 11708, 11725, 11740, 11754, 11768, 11784, 11798, 11813, 11828, 11843, 11858, 11874, 11888, 11904, 11920, 11933, 11948, 11964, 11979, 11993, 12009, 12024, 12041, 12058, 12071, 12087, 12102, 12117, 12132, 12148, 12165, 12179, 12195, 12210, 12226, 12241, 12256, 12273, 12288, 12304, 12320, 12335, 12350, 12365, 12382, 12398, 12414, 12430, 12446, 12462, 12478, 12495, 12511, 12525, 12541, 12556, 12575, 12591, 12605, 12622, 12638, 12653, 12671, 12686, 12705, 12721, 12739, 12756, 12772, 12788, 12806, 12822, 12839, 12855, 12873, 12890, 12908, 12923, 12941, 12960, 12975, 12992, 13009, 13024, 13040, 13059, 13076, 13092, 13109, 13128, 13145, 13161, 13179, 13194, 13216, 13233, 13249, 13266, 13287, 13303, 13322, 13337, 13357, 13375, 13392, 13410, 13424, 13446, 13465, 13480, 13499, 13517, 13533, 13559, 13575, 13595, 13612, 13632, 13650, 13670, 13687, 13706, 13726, 13744, 13765, 13783, 13803, 13822, 13841, 13860, 13879, 13897, 13917, 13936, 13960, 13979, 13996, 14019, 14040, 14057, 14077, 14102, 14122, 14141, 14163, 14184, 14202, 14225, 14244, 14265, 14287, 14312, 14336, 14356, 14375, 14393, 14420, 14438, 14465, 14483, 14500, 14536, 14555, 14575, 14604, 14619, 14648, 14668, 14691, 14725, 14748, 14770, 14788, 14818, 14840, 14862, 14888, 14921, 14939, 14969, 14996, 15022, 15051, 15075, 15098, 15130, 15149, 15167, 15218, 15237, 15276, 15297, 15333, 15356, 15379, 15418, 15447, 15481, 15508, 15530, 15574, 15599, 15643, 15680, 15697, 15743, 15759, 15775, 15813, 15845, 15877, 15911, 15931, 15968, 16014, 16049, 16077, 16088, 16138, 16149, 16185, 16200, 16241, 16280, 16296}; public ABITracerTest() { } @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { } @AfterClass - public static void tearDownClass() throws Exception { + public static void tearDownClass() { } @Before @@ -84,7 +85,7 @@ public void testLocal() throws Exception { Assert.assertEquals(1165, tracer.getSequenceLength()); //Test sequence of tracer for file 3730.ab1 - Assert.assertTrue(sequence.equals(tracer.getSequence().getSequenceAsString())); + Assert.assertEquals(sequence, tracer.getSequence().getSequenceAsString()); //Test array that represents the quality of tracer for file 3730.ab1 Assert.assertArrayEquals(qual, tracer.getQcalls()); //Test array that represents the baseline of tracer for file 3730.ab1 diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/CasePreservingProteinSequenceCreatorTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/CasePreservingProteinSequenceCreatorTest.java index 42a11ff7cb..88be79397f 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/CasePreservingProteinSequenceCreatorTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/CasePreservingProteinSequenceCreatorTest.java @@ -33,7 +33,7 @@ public class CasePreservingProteinSequenceCreatorTest { @Test public void testConstructor() throws CompoundNotFoundException { - CasePreservingProteinSequenceCreator creator = new CasePreservingProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet()); + CasePreservingProteinSequenceCreator creator = new CasePreservingProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet); String seq = "aCDEfgHI-Jkl"; ProteinSequence prot = (ProteinSequence) creator.getSequence(seq, 0); diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/FastaReaderTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/FastaReaderTest.java index 0222b54c47..6df7f1c31b 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/FastaReaderTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/FastaReaderTest.java @@ -30,7 +30,6 @@ import java.io.IOException; import java.io.InputStream; import java.util.LinkedHashMap; -import java.util.logging.Level; /** * @@ -44,11 +43,11 @@ public FastaReaderTest() { } @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { } @AfterClass - public static void tearDownClass() throws Exception { + public static void tearDownClass() { } @Before @@ -69,7 +68,7 @@ public void testProcess() throws Exception { Assert.assertNotNull(inStream); - FastaReader fastaReader = new FastaReader(inStream, new GenericFastaHeaderParser(), new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + FastaReader fastaReader = new FastaReader<>(inStream, new GenericFastaHeaderParser<>(), new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap proteinSequences = fastaReader.process(); inStream.close(); @@ -78,9 +77,8 @@ public void testProcess() throws Exception { Assert.assertEquals(proteinSequences.size(), 283); int seqNum = 0; - for(String id:proteinSequences.keySet()) { - ProteinSequence proteinSequence = proteinSequences.get(id); - switch(seqNum) { + for(ProteinSequence proteinSequence : proteinSequences.values()) { + switch(seqNum) { case 0: Assert.assertEquals(proteinSequence.getAccession().getID(), "A2D504_ATEGE/1-46"); Assert.assertEquals(proteinSequence.getSequenceAsString(), "-----------------FK-N----LP-LED----------------Q----ITL--IQY-----------SWM----------------------CL-SSFA------LSWRSYK---HTNSQFLYFAPDLVF-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------"); @@ -106,7 +104,7 @@ public void processIntTest() throws Exception { logger.info("process(int)"); InputStream inStream = this.getClass().getResourceAsStream("/PF00104_small.fasta"); Assert.assertNotNull(inStream); - FastaReader fastaReader = new FastaReader(inStream, new GenericFastaHeaderParser(), new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + FastaReader fastaReader = new FastaReader<>(inStream, new GenericFastaHeaderParser<>(), new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap proteinSequences = fastaReader.process(200); //Should have 200 sequences @@ -114,9 +112,8 @@ public void processIntTest() throws Exception { Assert.assertEquals(proteinSequences.size(), 200); int seqNum = 0; - for(String id:proteinSequences.keySet()) { - ProteinSequence proteinSequence = proteinSequences.get(id); - switch(seqNum) { + for(ProteinSequence proteinSequence : proteinSequences.values()) { + switch(seqNum) { case 0: Assert.assertEquals(proteinSequence.getAccession().getID(), "A2D504_ATEGE/1-46"); Assert.assertEquals(proteinSequence.getSequenceAsString(), "-----------------FK-N----LP-LED----------------Q----ITL--IQY-----------SWM----------------------CL-SSFA------LSWRSYK---HTNSQFLYFAPDLVF-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------"); @@ -134,9 +131,8 @@ public void processIntTest() throws Exception { proteinSequences = fastaReader.process(200); Assert.assertEquals(proteinSequences.size(), 83); seqNum = 0; - for(String id:proteinSequences.keySet()) { - ProteinSequence proteinSequence = proteinSequences.get(id); - switch(seqNum) { + for(ProteinSequence proteinSequence : proteinSequences.values()) { + switch(seqNum) { case 0: Assert.assertEquals(proteinSequence.getAccession().getID(), "RARA_CANFA/233-413"); Assert.assertEquals(proteinSequence.getSequenceAsString(), "TKCIIKTVEFAKQL-PGFT-T----LT-IAD----------------Q----ITL--LKA-----------ACL----------------------DI-LILR------ICTRYTP---EQDTMTFSEGLTLN-------------------------------------------------------------------------------------------------------------------------------------------------------------RTQMHKAGFGPLTDLVFAFA-NQL-LPL-E-MDDAET--------------------GLLSA-ICLI-CGDRQD-------------------------------------------LEQP--DRVDMLQEPLLEALKV-Y-----VRK---------RR---PS----------------------------RP------H--------MFP-KMLMKITD-LRSIS-----------------AKG-AERV--ITLKMEIPG--SMP--PLI-------QEM---"); @@ -164,10 +160,10 @@ public void testSmallFasta() throws IOException { InputStream inStream = this.getClass().getResourceAsStream("/test.fasta"); - FastaReader fastaReader = new FastaReader( + FastaReader fastaReader = new FastaReader<>( inStream, - new GenericFastaHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + new GenericFastaHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); LinkedHashMap b; @@ -192,10 +188,10 @@ public void testSmallFasta2() throws IOException { InputStream inStream = this.getClass().getResourceAsStream("/test.fasta"); - FastaReader fastaReader = new FastaReader( + FastaReader fastaReader = new FastaReader<>( inStream, - new GenericFastaHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet())); + new GenericFastaHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet)); int nrSeq = 0; diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankCookbookTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankCookbookTest.java index d6018a5eaf..77580fbaf8 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankCookbookTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankCookbookTest.java @@ -46,11 +46,11 @@ public GenbankCookbookTest() { } @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { } @AfterClass - public static void tearDownClass() throws Exception { + public static void tearDownClass() { } @Before @@ -70,14 +70,14 @@ public void testProcess() throws Throwable { * Method 1: With the GenbankProxySequenceReader */ //Try with the GenbankProxySequenceReader - GenbankProxySequenceReader genbankProteinReader - = new GenbankProxySequenceReader(System.getProperty("java.io.tmpdir"), "NP_000257", AminoAcidCompoundSet.getAminoAcidCompoundSet()); + GenbankProxySequenceReader genbankProteinReader + = new GenbankProxySequenceReader<>("NP_000257", AminoAcidCompoundSet.aminoAcidCompoundSet); ProteinSequence proteinSequence = new ProteinSequence(genbankProteinReader); genbankProteinReader.getHeaderParser().parseHeader(genbankProteinReader.getHeader(), proteinSequence); //logger.info("Sequence({},{}) = {}...", proteinSequence.getAccession(), proteinSequence.getLength(), proteinSequence.getSequenceAsString().substring(0, 10)); GenbankProxySequenceReader genbankDNAReader - = new GenbankProxySequenceReader(System.getProperty("java.io.tmpdir"), "NM_001126", DNACompoundSet.getDNACompoundSet()); + = new GenbankProxySequenceReader<>("NM_001126", DNACompoundSet.getDNACompoundSet()); DNASequence dnaSequence = new DNASequence(genbankDNAReader); genbankDNAReader.getHeaderParser().parseHeader(genbankDNAReader.getHeader(), dnaSequence); //logger.info("Sequence({},{}) = {}...", dnaSequence.getAccession(), dnaSequence.getLength(), dnaSequence.getSequenceAsString().substring(0, 10)); @@ -104,9 +104,9 @@ public void testProcess() throws Throwable { */ //Try reading with the GanbankReader - GenbankReader dnaReader = new GenbankReader( + GenbankReader dnaReader = new GenbankReader<>( dnaResource.getInputStream(), - new GenericGenbankHeaderParser(), + new GenericGenbankHeaderParser<>(), new DNASequenceCreator(DNACompoundSet.getDNACompoundSet()) ); dnaSequences = dnaReader.process(); @@ -114,10 +114,10 @@ public void testProcess() throws Throwable { logger.debug("DNA Sequence: {}", dnaSequences); - GenbankReader protReader = new GenbankReader( + GenbankReader protReader = new GenbankReader<>( protResource.getInputStream(), - new GenericGenbankHeaderParser(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet()) + new GenericGenbankHeaderParser<>(), + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet) ); protSequences = protReader.process(); diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankReaderTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankReaderTest.java index 5bcbecf672..899a5633b9 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankReaderTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankReaderTest.java @@ -20,43 +20,25 @@ */ package org.biojava.nbio.core.sequence.io; -import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.DNASequence; -import org.biojava.nbio.core.sequence.RNASequence; import org.biojava.nbio.core.sequence.ProteinSequence; -import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; -import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; -import org.biojava.nbio.core.sequence.compound.DNACompoundSet; -import org.biojava.nbio.core.sequence.compound.RNACompoundSet; -import org.biojava.nbio.core.sequence.compound.NucleotideCompound; +import org.biojava.nbio.core.sequence.RNASequence; +import org.biojava.nbio.core.sequence.compound.*; import org.biojava.nbio.core.sequence.features.FeatureInterface; import org.biojava.nbio.core.sequence.features.Qualifier; import org.biojava.nbio.core.sequence.template.AbstractSequence; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; +import java.io.*; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; /** * @@ -72,11 +54,11 @@ public GenbankReaderTest() { } @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { } @AfterClass - public static void tearDownClass() throws Exception { + public static void tearDownClass() { } @Before @@ -97,11 +79,11 @@ public void testProcess() throws Exception { InputStream inStream = this.getClass().getResourceAsStream("/BondFeature.gb"); assertNotNull(inStream); - GenbankReader genbankProtein + GenbankReader genbankProtein = new GenbankReader<>( inStream, new GenericGenbankHeaderParser<>(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet()) + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet) ); LinkedHashMap proteinSequences = genbankProtein.process(); @@ -169,7 +151,7 @@ public void testProcess() throws Exception { * The underlying {@link InputStream} should remain open until the last call. */ @Test - public void testPartialProcess() throws IOException, CompoundNotFoundException, NoSuchFieldException { + public void testPartialProcess() throws IOException { CheckableInputStream inStream = new CheckableInputStream(this.getClass().getResourceAsStream("/two-dnaseqs.gb")); GenbankReader genbankDNA @@ -207,17 +189,17 @@ public void CDStest() throws Exception { CheckableInputStream inStream = new CheckableInputStream(this.getClass().getResourceAsStream("/BondFeature.gb")); assertNotNull(inStream); - GenbankReader GenbankProtein + GenbankReader GenbankProtein = new GenbankReader<>( inStream, new GenericGenbankHeaderParser<>(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet()) + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet) ); LinkedHashMap proteinSequences = GenbankProtein.process(); assertTrue(inStream.isclosed()); - Assert.assertTrue(proteinSequences.size() == 1); + assertEquals(1, proteinSequences.size()); logger.debug("protein sequences: {}", proteinSequences); ProteinSequence protein = new ArrayList<>(proteinSequences.values()).get(0); @@ -228,13 +210,13 @@ public void CDStest() throws Exception { List dbrefs = quals.get("db_xref"); Assert.assertNotNull(codedBy); - Assert.assertTrue(!codedBy.isEmpty()); + assertFalse(codedBy.isEmpty()); assertEquals(codedBy, "NM_000266.2:503..904"); assertEquals(5, dbrefs.size()); } - private DNASequence readGenbankResource(final String resource) throws IOException, CompoundNotFoundException { + private DNASequence readGenbankResource(final String resource) throws IOException { InputStream inputStream = getClass().getResourceAsStream(resource); GenbankReader genbankDNA = new GenbankReader<>( @@ -246,7 +228,7 @@ private DNASequence readGenbankResource(final String resource) throws IOExceptio return dnaSequences.values().iterator().next(); } - private RNASequence readGenbankRNAResource(final String resource) throws IOException, CompoundNotFoundException { + private RNASequence readGenbankRNAResource(final String resource) throws IOException { InputStream inputStream = getClass().getResourceAsStream(resource); GenbankReader genbankRNA = new GenbankReader<>( @@ -258,19 +240,19 @@ private RNASequence readGenbankRNAResource(final String resource) throws IOExcep return rnaSequences.values().iterator().next(); } - private ProteinSequence readGenbankProteinResource(final String resource) throws IOException, CompoundNotFoundException { + private ProteinSequence readGenbankProteinResource(final String resource) throws IOException { InputStream inputStream = getClass().getResourceAsStream(resource); - GenbankReader genbankProtein + GenbankReader genbankProtein = new GenbankReader<>( inputStream, new GenericGenbankHeaderParser<>(), - new ProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet()) + new ProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet) ); LinkedHashMap proteinSequences = genbankProtein.process(); return proteinSequences.values().iterator().next(); } - private AbstractSequence readUnknownGenbankResource(final String resource) throws IOException, CompoundNotFoundException { + private AbstractSequence readUnknownGenbankResource(final String resource) throws IOException { InputStream inputStream = getClass().getResourceAsStream(resource); GenbankSequenceParser genbankParser = new GenbankSequenceParser(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); @@ -287,7 +269,7 @@ private AbstractSequence readUnknownGenbankResource(final String resource) th } @Test - public void testNcbiExpandedAccessionFormats() throws IOException, CompoundNotFoundException { + public void testNcbiExpandedAccessionFormats() throws IOException { DNASequence header0 = readGenbankResource("/empty_header0.gb"); assertEquals("CP032762 5868661 bp DNA circular BCT 15-OCT-2018", header0.getOriginalHeader()); @@ -299,7 +281,7 @@ public void testNcbiExpandedAccessionFormats() throws IOException, CompoundNotFo } @Test - public void testLegacyLocusCompatable() throws IOException, CompoundNotFoundException { + public void testLegacyLocusCompatable() throws IOException { // Testing opening a genbank file with uppercase units, strand and topology AbstractSequence header0 = readUnknownGenbankResource("/org/biojava/nbio/core/sequence/io/uppercase_locus0.gb"); @@ -353,7 +335,7 @@ public void testLegacyLocusCompatable() throws IOException, CompoundNotFoundExce /** * Helper class to be able to verify the closed state of the input stream. */ - private class CheckableInputStream extends BufferedInputStream { + private static class CheckableInputStream extends BufferedInputStream { private boolean closed; diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankWriterTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankWriterTest.java index 6b54346226..33bfaced9c 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankWriterTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenbankWriterTest.java @@ -49,10 +49,7 @@ public void testProcess() throws Exception { //File dnaFile = new File("src/test/resources/NM_000266.gb"); LinkedHashMap dnaSequences = GenbankReaderHelper.readGenbankDNASequence( inStream ); ByteArrayOutputStream fragwriter = new ByteArrayOutputStream(); - ArrayList seqs = new ArrayList(); - for(DNASequence seq : dnaSequences.values()) { - seqs.add(seq); - } + ArrayList seqs = new ArrayList<>(dnaSequences.values()); GenbankWriterHelper.writeNucleotideSequence(fragwriter, seqs, GenbankWriterHelper.LINEAR_DNA); //System.out.println(fragwriter.toString()); diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenericFastaHeaderParserTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenericFastaHeaderParserTest.java index 1d41e734ac..13d27418f9 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenericFastaHeaderParserTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/io/GenericFastaHeaderParserTest.java @@ -42,11 +42,11 @@ public GenericFastaHeaderParserTest() { } @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { } @AfterClass - public static void tearDownClass() throws Exception { + public static void tearDownClass() { } @Before @@ -78,9 +78,9 @@ public void tearDown() { @Test public void testParseHeader() throws CompoundNotFoundException { logger.info("parseHeader"); - String header = ""; + String header; ProteinSequence sequence = new ProteinSequence(""); - GenericFastaHeaderParser instance = new GenericFastaHeaderParser(); + GenericFastaHeaderParser instance = new GenericFastaHeaderParser<>(); header = "gi|gi-number|gb|accession|locus"; instance.parseHeader(header, sequence); diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/loader/GenbankProxySequenceReaderTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/loader/GenbankProxySequenceReaderTest.java index 647d86df4d..046730c938 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/loader/GenbankProxySequenceReaderTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/loader/GenbankProxySequenceReaderTest.java @@ -20,7 +20,6 @@ */ package org.biojava.nbio.core.sequence.loader; -import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; @@ -55,7 +54,7 @@ @RunWith(Parameterized.class) public class GenbankProxySequenceReaderTest { - private String gi; + private final String gi; private final static Logger logger = LoggerFactory.getLogger(GenbankProxySequenceReaderTest.class); public GenbankProxySequenceReaderTest(String gi) { @@ -82,14 +81,13 @@ public static Collection getExamples() { * In {@link GenbankProxySequenceReader} there is a check to see if the requested files are already in the temp * directory before attempting to retrieve them from the remote server. so simply copying the test files to the temp * directory avoids calling out to the server and hitting a 429 status code from the server which fails the build. - * @throws IOException */ @Before - public void copyTestFiles() throws IOException { - Collection accessorIds = getExamples(); - for (String[] arr: accessorIds) { - copyTestFileToWorkingDirectory(arr[0]+".gb"); - } + public void copyTestFiles() { +// Collection accessorIds = getExamples(); +// for (String[] arr: accessorIds) { +// copyTestFileToWorkingDirectory(arr[0]+".gb"); +// } } /** @@ -122,12 +120,12 @@ private void copyTestFileToWorkingDirectory(String filename) throws IOException @Test - public void testFeatures() throws IOException, InterruptedException, CompoundNotFoundException { + public void testFeatures() throws IOException, InterruptedException { logger.info("run test for protein: {}", gi); GenbankProxySequenceReader genbankReader - = new GenbankProxySequenceReader<>(System.getProperty("java.io.tmpdir"), + = new GenbankProxySequenceReader<>( this.gi, - AminoAcidCompoundSet.getAminoAcidCompoundSet()); + AminoAcidCompoundSet.aminoAcidCompoundSet); // why only tests on protein sequences? ProteinSequence seq = new ProteinSequence(genbankReader); @@ -166,7 +164,7 @@ so it should be done here (manualy). logger.info("CDS: {}", CDS); String codedBy = CDS.getQualifiers().get("coded_by").get(0).getValue(); Assert.assertNotNull(codedBy); - Assert.assertTrue(!codedBy.isEmpty()); + Assert.assertFalse(codedBy.isEmpty()); logger.info("\t\tcoded_by: {}", codedBy); } @@ -180,9 +178,9 @@ public void testProteinSequenceFactoring() throws Exception { logger.info("create protein sequence test for target {}", gi); GenbankProxySequenceReader genbankReader - = new GenbankProxySequenceReader<>(System.getProperty("java.io.tmpdir"), + = new GenbankProxySequenceReader<>( this.gi, - AminoAcidCompoundSet.getAminoAcidCompoundSet()); + AminoAcidCompoundSet.aminoAcidCompoundSet); ProteinSequence seq = new ProteinSequence(genbankReader); @@ -205,7 +203,7 @@ public void testProteinSequenceFactoring() throws Exception { That test is always failed */ //Assert.assertTrue(parentSeq.getAccession()); - Assert.assertTrue(!parentSeq.getSequenceAsString().isEmpty()); + Assert.assertFalse(parentSeq.getSequenceAsString().isEmpty()); } } } else { diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/loader/SimpleGenbankProxySequenceReaderTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/loader/SimpleGenbankProxySequenceReaderTest.java index 4150e90ffc..ecfc518b14 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/loader/SimpleGenbankProxySequenceReaderTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/loader/SimpleGenbankProxySequenceReaderTest.java @@ -20,7 +20,6 @@ */ package org.biojava.nbio.core.sequence.loader; -import java.io.IOException; import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; @@ -28,6 +27,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; + /** * Testing example for issue #834 @@ -47,10 +48,8 @@ public void testWrongSequence() throws Exception { String wrongGi = "34567"; - GenbankProxySequenceReader genbankReader - = new GenbankProxySequenceReader(System.getProperty("java.io.tmpdir"), - wrongGi, - AminoAcidCompoundSet.getAminoAcidCompoundSet()); + GenbankProxySequenceReader genbankReader + = new GenbankProxySequenceReader<>(wrongGi, AminoAcidCompoundSet.aminoAcidCompoundSet); ProteinSequence seq = new ProteinSequence(genbankReader); } diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/InsdcParserTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/InsdcParserTest.java index 01094c84ba..144aba0058 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/InsdcParserTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/InsdcParserTest.java @@ -20,8 +20,6 @@ */ package org.biojava.nbio.core.sequence.location; -import java.util.Arrays; -import java.util.Collection; import org.biojava.nbio.core.sequence.DataSource; import org.biojava.nbio.core.sequence.location.template.Location; import org.junit.Assert; @@ -31,6 +29,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Arrays; +import java.util.Collection; + /** * * @author Jacek Grzebyta @@ -38,9 +39,9 @@ @RunWith(Parameterized.class) public class InsdcParserTest { - private Logger log = LoggerFactory.getLogger(getClass()); - private String data; - private String expected; + private final Logger log = LoggerFactory.getLogger(getClass()); + private final String data; + private final String expected; public InsdcParserTest(String data, String expected) { this.data = data; @@ -58,10 +59,9 @@ public static Collection data() { /** * Test for issue #254 * - * @throws Exception */ @Test - public void extractAccessionTest() throws Exception { + public void extractAccessionTest() { log.info("test accession"); log.debug("data: '{}' expected: '{}'", data, expected); diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/LocationParserTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/LocationParserTest.java index 3c562498b5..14cf3ebaaa 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/LocationParserTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/LocationParserTest.java @@ -54,7 +54,7 @@ public class LocationParserTest { public static final InsdcParser PARSER = new InsdcParser(); - private Logger log = LoggerFactory.getLogger(getClass()); + private final Logger log = LoggerFactory.getLogger(getClass()); @Test @Ignore diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/TargetedLocationParserTest.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/TargetedLocationParserTest.java index 6ea7c9f869..1681619b3e 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/TargetedLocationParserTest.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/location/TargetedLocationParserTest.java @@ -40,10 +40,10 @@ @RunWith(Parameterized.class) public class TargetedLocationParserTest { - private Data request; + private final Data request; public static class Data { - private String Insdc; + private final String Insdc; /** * Parser data input. Based on that input it should be able to identity the origin and wanted target @@ -55,17 +55,17 @@ public static class Data { public Data(String gi, CompoundSet originType, String Insdc, CompoundSet compound) { this.Insdc = Insdc; } - }; + } @Parameterized.Parameters - public static Collection getLocations() throws Exception { + public static Collection getLocations() { - Data[][] out = new Data[][]{ - {new Data("7525057", AminoAcidCompoundSet.getAminoAcidCompoundSet(), + Data[][] out = new Data[][]{ + {new Data("7525057", AminoAcidCompoundSet.aminoAcidCompoundSet, "join(complement(NC_000932.1:69611..69724),NC_000932.1:139856..140087,NC_000932.1:140625..140650)", DNACompoundSet.getDNACompoundSet())}, - {new Data("7525059", AminoAcidCompoundSet.getAminoAcidCompoundSet(), + {new Data("7525059", AminoAcidCompoundSet.aminoAcidCompoundSet, "NC_000932.1:72371..73897", DNACompoundSet.getDNACompoundSet())}, {new Data("7525073", DNACompoundSet.getDNACompoundSet() , @@ -85,7 +85,7 @@ public TargetedLocationParserTest(Data request) { @Test - public void locationTest() throws Exception { + public void locationTest() { InsdcParser parser = new InsdcParser(DataSource.GENBANK); Location loc = parser.parse(request.Insdc); diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/views/WindowViewTests.java b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/views/WindowViewTests.java index 90d4da3a01..e27962adb4 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/sequence/views/WindowViewTests.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/sequence/views/WindowViewTests.java @@ -38,7 +38,7 @@ public class WindowViewTests { @Test public void basicWindow() throws CompoundNotFoundException { RNASequence rna = new RNASequence("AUGCCU"); - WindowedSequence window = new WindowedSequence(rna, 3); + WindowedSequence window = new WindowedSequence<>(rna, 3); Iterator> iter = window.iterator(); assertTrue("hasNext() returns true", iter.hasNext()); @@ -57,8 +57,8 @@ public void basicWindow() throws CompoundNotFoundException { @Test public void reaminderWindow() throws CompoundNotFoundException { RNASequence rna = new RNASequence("AUGCC"); - WindowedSequence window = new WindowedSequence(rna, 3); - List> list = new ArrayList>(); + WindowedSequence window = new WindowedSequence<>(rna, 3); + List> list = new ArrayList<>(); for(SequenceView c: window) { list.add(c); } diff --git a/biojava-core/src/test/java/org/biojava/nbio/core/util/TestUncompressInputStream.java b/biojava-core/src/test/java/org/biojava/nbio/core/util/TestUncompressInputStream.java index 470eacfbbf..008d57e600 100644 --- a/biojava-core/src/test/java/org/biojava/nbio/core/util/TestUncompressInputStream.java +++ b/biojava-core/src/test/java/org/biojava/nbio/core/util/TestUncompressInputStream.java @@ -20,13 +20,14 @@ */ package org.biojava.nbio.core.util; -import java.io.BufferedInputStream; +import org.junit.Assert; import org.junit.Test; -import static org.junit.Assert.*; +import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; -import org.junit.Assert; + +import static org.junit.Assert.assertEquals; public class TestUncompressInputStream { @@ -60,7 +61,7 @@ public void testUncompression() throws Exception { ByteArrayOutputStream obaos = new ByteArrayOutputStream(); try (BufferedInputStream oin = new BufferedInputStream( this.getClass().getClassLoader() - .getResourceAsStream(ORIG_OF_BIGGER_TEST_FILE));) { + .getResourceAsStream(ORIG_OF_BIGGER_TEST_FILE))) { byte[] buf = new byte[100000]; int len; while ((len = oin.read(buf)) >= 0) diff --git a/biojava-genome/pom.xml b/biojava-genome/pom.xml index bd67b30190..d0ef1e08ae 100644 --- a/biojava-genome/pom.xml +++ b/biojava-genome/pom.xml @@ -21,7 +21,7 @@ biojava-maven-repo BioJava repository - http://www.biojava.org/download/maven/ + https://www.biojava.org/download/maven/ true @@ -35,15 +35,7 @@ - - org.apache.maven.plugins - maven-jar-plugin - - - demo/** - - - + org.apache.maven.plugins diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/GeneFeatureHelper.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/GeneFeatureHelper.java index 7f7294801e..b8828a99cd 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/GeneFeatureHelper.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/GeneFeatureHelper.java @@ -20,18 +20,15 @@ */ package org.biojava.nbio.genome; -import org.biojava.nbio.genome.parsers.gff.*; import org.biojava.nbio.core.sequence.*; import org.biojava.nbio.core.sequence.io.FastaReaderHelper; +import org.biojava.nbio.genome.parsers.gff.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileWriter; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; +import java.util.*; /** * @@ -42,13 +39,13 @@ public class GeneFeatureHelper { private static final Logger logger = LoggerFactory.getLogger(GeneFeatureHelper.class); static public LinkedHashMap loadFastaAddGeneFeaturesFromUpperCaseExonFastaFile(File fastaSequenceFile, File uppercaseFastaFile, boolean throwExceptionGeneNotFound) throws Exception { - LinkedHashMap chromosomeSequenceList = new LinkedHashMap(); + LinkedHashMap chromosomeSequenceList = new LinkedHashMap<>(); LinkedHashMap dnaSequenceList = FastaReaderHelper.readFastaDNASequence(fastaSequenceFile); - for (String accession : dnaSequenceList.keySet()) { - DNASequence contigSequence = dnaSequenceList.get(accession); + for (Map.Entry entry : dnaSequenceList.entrySet()) { + DNASequence contigSequence = entry.getValue(); ChromosomeSequence chromsomeSequence = new ChromosomeSequence(contigSequence.getSequenceAsString()); chromsomeSequence.setAccession(contigSequence.getAccession()); - chromosomeSequenceList.put(accession, chromsomeSequence); + chromosomeSequenceList.put(entry.getKey(), chromsomeSequence); } @@ -91,7 +88,7 @@ static public LinkedHashMap loadFastaAddGeneFeatures dnaSequence.getAccession().toString(), contigDNASequence.getAccession().toString(), bioStart, bioEnd, strand); ChromosomeSequence chromosomeSequence = chromosomeSequenceList.get(accession); - ArrayList exonBoundries = new ArrayList(); + ArrayList exonBoundries = new ArrayList<>(); //look for transitions from lowercase to upper case for (int i = 0; i < geneSequence.length(); i++) { @@ -314,12 +311,12 @@ static public void addGeneIDGFF2GeneFeatures(LinkedHashMap getChromosomeSequenceFromDNASequence(LinkedHashMap dnaSequenceList) { - LinkedHashMap chromosomeSequenceList = new LinkedHashMap(); - for (String key : dnaSequenceList.keySet()) { - DNASequence dnaSequence = dnaSequenceList.get(key); + LinkedHashMap chromosomeSequenceList = new LinkedHashMap<>(); + for (Map.Entry entry : dnaSequenceList.entrySet()) { + DNASequence dnaSequence = entry.getValue(); ChromosomeSequence chromosomeSequence = new ChromosomeSequence(dnaSequence.getProxySequenceReader()); //we want the underlying sequence but don't need storage chromosomeSequence.setAccession(dnaSequence.getAccession()); - chromosomeSequenceList.put(key, chromosomeSequence); + chromosomeSequenceList.put(entry.getKey(), chromosomeSequence); } return chromosomeSequenceList; } @@ -361,10 +358,10 @@ static public void addGmodGFF3GeneFeatures(LinkedHashMap getProteinSequences(Collection chromosomeSequences) throws Exception { - LinkedHashMap proteinSequenceHashMap = new LinkedHashMap(); + static public LinkedHashMap getProteinSequences(Collection chromosomeSequences) { + LinkedHashMap proteinSequenceHashMap = new LinkedHashMap<>(); for (ChromosomeSequence dnaSequence : chromosomeSequences) { for (GeneSequence geneSequence : dnaSequence.getGeneSequences().values()) { for (TranscriptSequence transcriptSequence : geneSequence.getTranscripts().values()) { @@ -864,8 +861,8 @@ static public LinkedHashMap getProteinSequences(Collect return proteinSequenceHashMap; } - static public LinkedHashMap getGeneSequences(Collection chromosomeSequences) throws Exception { - LinkedHashMap geneSequenceHashMap = new LinkedHashMap(); + static public LinkedHashMap getGeneSequences(Collection chromosomeSequences) { + LinkedHashMap geneSequenceHashMap = new LinkedHashMap<>(); for (ChromosomeSequence chromosomeSequence : chromosomeSequences) { for (GeneSequence geneSequence : chromosomeSequence.getGeneSequences().values()) { geneSequenceHashMap.put(geneSequence.getAccession().getID(), geneSequence); @@ -875,7 +872,7 @@ static public LinkedHashMap getGeneSequences(Collection chromosomeSequenceList = GeneFeatureHelper.loadFastaAddGeneFeaturesFromGeneMarkGTF(new File("Scaffolds.fna"), new File("genemark_hmm.gtf")); LinkedHashMap proteinSequenceList = GeneFeatureHelper.getProteinSequences(chromosomeSequenceList.values()); diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/homology/BlastHomologyHits.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/homology/BlastHomologyHits.java index 88881b37eb..831a8875bc 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/homology/BlastHomologyHits.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/homology/BlastHomologyHits.java @@ -25,6 +25,7 @@ import java.io.File; import java.util.ArrayList; import java.util.LinkedHashMap; +import java.util.Map; /** * @@ -33,13 +34,13 @@ public class BlastHomologyHits { static public LinkedHashMap> getMatches(File xmlBlastHits, double ecutoff) throws Exception { - LinkedHashMap> homologyHits = new LinkedHashMap>(); + LinkedHashMap> homologyHits = new LinkedHashMap<>(); BlastXMLQuery blastXMLQuery = new BlastXMLQuery(xmlBlastHits.getAbsolutePath()); LinkedHashMap> hits = blastXMLQuery.getHitsQueryDef(ecutoff); - for (String accessionid : hits.keySet()) { - String[] data = accessionid.split(" "); // deal with notes/comments in blast results + for (Map.Entry> entry : hits.entrySet()) { + String[] data = entry.getKey().split(" "); // deal with notes/comments in blast results String id = data[0]; - ArrayList uniprotProteinHits = hits.get(accessionid); + ArrayList uniprotProteinHits = entry.getValue(); homologyHits.put(id, uniprotProteinHits); } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/homology/GFF3FromUniprotBlastHits.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/homology/GFF3FromUniprotBlastHits.java index 0910b6b68d..4a51dfebc8 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/homology/GFF3FromUniprotBlastHits.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/homology/GFF3FromUniprotBlastHits.java @@ -20,7 +20,6 @@ */ package org.biojava.nbio.genome.homology; -import org.biojava.nbio.genome.GeneFeatureHelper; import org.biojava.nbio.alignment.Alignments; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; import org.biojava.nbio.alignment.SimpleGapPenalty; @@ -33,6 +32,7 @@ import org.biojava.nbio.core.sequence.features.DatabaseReferenceInterface; import org.biojava.nbio.core.sequence.features.FeaturesKeyWordInterface; import org.biojava.nbio.core.sequence.loader.UniprotProxySequenceReader; +import org.biojava.nbio.genome.GeneFeatureHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,27 +41,33 @@ import java.io.OutputStream; import java.util.ArrayList; import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; /** * * @author Scooter Willis * @author Mark Chapman + * + * TODO test + * */ public class GFF3FromUniprotBlastHits { private static final Logger logger = LoggerFactory.getLogger(GFF3FromUniprotBlastHits.class); - public void process(File xmlBlastHits, double ecutoff, LinkedHashMap geneSequenceHashMap, OutputStream gff3Output) throws Exception { - LinkedHashMap> hits = BlastHomologyHits.getMatches(xmlBlastHits, ecutoff); - process(hits, geneSequenceHashMap, gff3Output); - } +// public void process(File xmlBlastHits, double ecutoff, LinkedHashMap geneSequenceHashMap, OutputStream gff3Output) throws Exception { +// LinkedHashMap> hits = BlastHomologyHits.getMatches(xmlBlastHits, ecutoff); +// process(hits, geneSequenceHashMap, gff3Output); +// } - public void process(LinkedHashMap> hits, LinkedHashMap geneSequenceHashMap, OutputStream gff3Output) throws Exception { + public void process(LinkedHashMap> hits, LinkedHashMap geneSequenceHashMap, OutputStream gff3Output) { int size = hits.size(); int index = 0; // HashMap scaffoldsReferencedHashMap = new HashMap(); - for (String accessionid : hits.keySet()) { - index++; + for (Map.Entry> stringArrayListEntry : hits.entrySet()) { + String accessionid = stringArrayListEntry.getKey(); + index++; if (index == 12) { index = 12; } @@ -75,9 +81,9 @@ public void process(LinkedHashMap> hits, LinkedHashMap logger.error("Not found " + id); continue; } - ArrayList uniprotProteinHits = hits.get(accessionid); + ArrayList uniprotProteinHits = stringArrayListEntry.getValue(); String uniprotBestHit = uniprotProteinHits.get(0); - UniprotProxySequenceReader uniprotSequence = new UniprotProxySequenceReader(uniprotBestHit, AminoAcidCompoundSet.getAminoAcidCompoundSet()); + UniprotProxySequenceReader uniprotSequence = new UniprotProxySequenceReader<>(uniprotBestHit, AminoAcidCompoundSet.aminoAcidCompoundSet); ProteinSequence proteinSequence = new ProteinSequence(uniprotSequence); String hitSequence = proteinSequence.getSequenceAsString(); @@ -87,18 +93,20 @@ public void process(LinkedHashMap> hits, LinkedHashMap String predictedProteinSequence = transcriptSequence.getProteinSequence().getSequenceAsString(); ArrayList cdsProteinList = transcriptSequence.getProteinCDSSequences(); - ArrayList cdsSequenceList = new ArrayList(transcriptSequence.getCDSSequences().values()); + ArrayList cdsSequenceList = new ArrayList<>(transcriptSequence.getCDSSequences().values()); String testSequence = ""; for (ProteinSequence cdsProteinSequence : cdsProteinList) { testSequence = testSequence + cdsProteinSequence.getSequenceAsString(); } if (!testSequence.equals(predictedProteinSequence) && (!predictedProteinSequence.equals(testSequence.substring(0, testSequence.length() - 1)))) { DNASequence codingSequence = transcriptSequence.getDNACodingSequence(); - logger.info("Coding Sequence: {}", codingSequence.getSequenceAsString()); - logger.info("Sequence agreement error"); - logger.info("CDS seq={}", testSequence); - logger.info("PRE seq={}", predictedProteinSequence); - logger.info("UNI seq={}", hitSequence); + if (logger.isInfoEnabled()) { + logger.info("Coding Sequence: {}", codingSequence.getSequenceAsString()); + logger.info("Sequence agreement error"); + logger.info("CDS seq={}", testSequence); + logger.info("PRE seq={}", predictedProteinSequence); + logger.info("UNI seq={}", hitSequence); + } // throw new Exception("Protein Sequence compare error " + id); } @@ -112,35 +120,31 @@ PairwiseSequenceAlignerType.LOCAL, new SimpleGapPenalty(), // System.out.println(new Pair().format(alignment)); int proteinIndex = 0; int gff3Index = 0; - for (int i = 0; i < cdsProteinList.size(); i++) { + int cdsProteins = cdsProteinList.size(); + for (int i = 0; i < cdsProteins; i++) { ProteinSequence peptideSequence = cdsProteinList.get(i); - String seq = peptideSequence.getSequenceAsString(); - Integer startIndex = null; + final String seq = peptideSequence.getSequenceAsString(); + int startIndex; int offsetStartIndex = 0; - for (int s = 0; s < seq.length(); s++) { - startIndex = alignment.getIndexInTargetForQueryAt(proteinIndex + s); - if (startIndex != null) { - startIndex = startIndex + 1; - offsetStartIndex = s; - break; - } - } - Integer endIndex = null; + int seqLen = seq.length(); + //for (int s = 0; s < seqLen; s++) { + startIndex = alignment.getIndexInTargetForQueryAt(proteinIndex); + startIndex = startIndex + 1; +// offsetStartIndex = 0; + //} + int endIndex; int offsetEndIndex = 0; - for (int e = 0; e < seq.length(); e++) { - endIndex = alignment.getIndexInTargetForQueryAt(proteinIndex + seq.length() - 1 - e); - if (endIndex != null) { - endIndex = endIndex + 1; - offsetEndIndex = e; - break; - } - } - - proteinIndex = proteinIndex + seq.length(); - if (startIndex != null && endIndex != null && startIndex != endIndex) { +// for (int e = 0; e < seqLen; e++) { + endIndex = alignment.getIndexInTargetForQueryAt(proteinIndex + seqLen - 1); + endIndex = endIndex + 1; +// offsetEndIndex = 0; +// } + + proteinIndex = proteinIndex + seqLen; + if (startIndex != endIndex) { CDSSequence cdsSequence = cdsSequenceList.get(i); - String hitLabel = ""; + String hitLabel; if (transcriptSequence.getStrand() == Strand.POSITIVE) { hitLabel = uniprotBestHit + "_" + startIndex + "_" + endIndex; } else { @@ -160,19 +164,20 @@ PairwiseSequenceAlignerType.LOCAL, new SimpleGapPenalty(), FeaturesKeyWordInterface featureKeyWords = proteinSequence.getFeaturesKeyWord(); String notes = ""; if (featureKeyWords != null) { - ArrayList keyWords = featureKeyWords.getKeyWords(); + List keyWords = featureKeyWords.getKeyWords(); if (keyWords.size() > 0) { notes = ";Note="; for (String note : keyWords) { - if (note.equals("Complete proteome")) { - continue; - } - if (note.equals("Direct protein sequencing")) { - continue; - } + switch (note) { + case "Complete proteome": + case "Direct protein sequencing": + continue; + default: + notes = notes + " " + note; + geneSequence.addNote(note); // add note/keyword which can be output in fasta header if needed + break; - notes = notes + " " + note; - geneSequence.addNote(note); // add note/keyword which can be output in fasta header if needed + } } } @@ -180,7 +185,7 @@ PairwiseSequenceAlignerType.LOCAL, new SimpleGapPenalty(), DatabaseReferenceInterface databaseReferences = proteinSequence.getDatabaseReferences(); if (databaseReferences != null) { - LinkedHashMap> databaseReferenceHashMap = databaseReferences.getDatabaseReferences(); + Map> databaseReferenceHashMap = databaseReferences.getDatabaseReferences(); ArrayList pfamList = databaseReferenceHashMap.get("Pfam"); ArrayList cazyList = databaseReferenceHashMap.get("CAZy"); ArrayList goList = databaseReferenceHashMap.get("GO"); @@ -227,15 +232,14 @@ PairwiseSequenceAlignerType.LOCAL, new SimpleGapPenalty(), notes = notes + " " + note.getId(); geneSequence.addNote(note.getId()); // add note/keyword which can be output in fasta header if needed LinkedHashMap properties = note.getProperties(); - for (String propertytype : properties.keySet()) { - if (propertytype.equals("evidence")) { + for (Map.Entry entry : properties.entrySet()) { + if (entry.getKey().equals("evidence")) continue; - } - String property = properties.get(propertytype); - if (property.startsWith("C:")) { + String property = entry.getValue(); + if (property.startsWith("C:")) continue; // skip over the location - } + if (property.endsWith("...")) { property = property.substring(0, property.length() - 3); } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/AbstractFastqReader.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/AbstractFastqReader.java index 17ca61205c..3fe2767711 100755 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/AbstractFastqReader.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/AbstractFastqReader.java @@ -26,7 +26,7 @@ import java.io.*; import java.net.URL; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.List; /** @@ -100,7 +100,7 @@ public final Iterable read(final URL url) throws IOException Collect collect = new Collect(); try { - reader = Resources.asCharSource(url, Charset.forName("UTF-8")).openBufferedStream(); + reader = Resources.asCharSource(url, StandardCharsets.UTF_8).openBufferedStream(); stream(reader, collect); } finally diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/AbstractFastqWriter.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/AbstractFastqWriter.java index 5df7443995..305977f633 100755 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/AbstractFastqWriter.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/AbstractFastqWriter.java @@ -20,14 +20,7 @@ */ package org.biojava.nbio.genome.io.fastq; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; - +import java.io.*; import java.util.Arrays; /** @@ -100,27 +93,11 @@ public final void write(final File file, final Iterable fastq) throws IOE { throw new IllegalArgumentException("fastq must not be null"); } - Writer writer = null; - try - { - writer = new BufferedWriter(new FileWriter(file)); - append(writer, fastq); - } - finally - { - if (writer != null) - { - try - { - writer.close(); - } - catch (IOException e) - { - // ignore - } - } - } - } + try (Writer writer = new BufferedWriter(new FileWriter(file))) { + append(writer, fastq); + } + // ignore + } @Override public final void write(final OutputStream outputStream, final Fastq... fastq) throws IOException diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/Fastq.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/Fastq.java index 2de9e05713..75fb3d4054 100755 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/Fastq.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/Fastq.java @@ -141,7 +141,7 @@ public Fastq convertTo(final FastqVariant variant) * * @return a new FastqBuilder */ - public static final FastqBuilder builder() + public static FastqBuilder builder() { return new FastqBuilder(); } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqParser.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqParser.java index 52f5141df2..1ba652c669 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqParser.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqParser.java @@ -63,7 +63,7 @@ static void parse(final Readable readable, final ParseListener listener) /** * FASTQ formatted sequence parser line processor. */ - private static final class FastqParserLineProcessor implements LineProcessor + private static final class FastqParserLineProcessor implements LineProcessor { /** Parser state. */ private State state = State.DESCRIPTION; @@ -114,22 +114,22 @@ private void setState(final State state) } @Override - public Object getResult() + public Void getResult() { return null; } @Override - public boolean processLine(final String line) throws IOException + public boolean processLine(String line) throws IOException { - String sequence = null; - String quality = null; + line = line.trim(); + switch (state) { case DESCRIPTION: if (line.startsWith("@")) { - listener.description(line.substring(1).trim()); + listener.description(line.substring(1)); state = State.SEQUENCE; } else @@ -138,28 +138,25 @@ public boolean processLine(final String line) throws IOException } break; case SEQUENCE: - sequence = line.trim(); - listener.sequence(sequence); - sequenceLength = sequence.length(); + listener.sequence(line); + sequenceLength = line.length(); state = State.REPEAT_DESCRIPTION; break; case REPEAT_DESCRIPTION: if (line.startsWith("+")) { - listener.repeatDescription(line.substring(1).trim()); + listener.repeatDescription(line.substring(1)); state = State.QUALITY; } else { - sequence = line.trim(); - listener.appendSequence(sequence); - sequenceLength += sequence.length(); + listener.appendSequence(line); + sequenceLength += line.length(); } break; case QUALITY: - quality = line.trim(); - listener.quality(quality); - qualityLength = quality.length(); + listener.quality(line); + qualityLength = line.length(); state = State.COMPLETE; break; case COMPLETE: @@ -169,7 +166,7 @@ public boolean processLine(final String line) throws IOException if (line.startsWith("@")) { - listener.description(line.substring(1).trim()); + listener.description(line.substring(1)); state = State.SEQUENCE; } else @@ -179,9 +176,8 @@ public boolean processLine(final String line) throws IOException } else { - quality = line.trim(); - listener.appendQuality(quality); - qualityLength += quality.length(); + listener.appendQuality(line); + qualityLength += line.length(); } break; default: @@ -192,7 +188,7 @@ public boolean processLine(final String line) throws IOException } /** Parser state. */ - private static enum State + private enum State { /** Description parser state. */ DESCRIPTION, @@ -207,6 +203,6 @@ private static enum State QUALITY, /** Complete parser state. */ - COMPLETE; - }; + COMPLETE + } } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqTools.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqTools.java index 437d7bd435..78191a7655 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqTools.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqTools.java @@ -133,7 +133,7 @@ public static QualityFeature, NucleotideCom { throw new IllegalArgumentException("fastq must not be null"); } - QualityFeature, NucleotideCompound> qualityScores = new QualityFeature, NucleotideCompound>("qualityScores", "sequencing"); + QualityFeature, NucleotideCompound> qualityScores = new QualityFeature<>("qualityScores", "sequencing"); qualityScores.setQualities(toList(qualityScores(fastq))); return qualityScores; } @@ -153,7 +153,7 @@ public static QuantityFeature, NucleotideCo { throw new IllegalArgumentException("fastq must not be null"); } - QuantityFeature, NucleotideCompound> errorProbabilities = new QuantityFeature, NucleotideCompound>("errorProbabilities", "sequencing"); + QuantityFeature, NucleotideCompound> errorProbabilities = new QuantityFeature<>("errorProbabilities", "sequencing"); errorProbabilities.setQuantities(toList(errorProbabilities(fastq))); return errorProbabilities; } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqVariant.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqVariant.java index efffbf4f78..8df5972166 100755 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqVariant.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/FastqVariant.java @@ -186,7 +186,7 @@ public double errorProbability(final int qualityScore) /** Map of FASTQ sequence format variants keyed by name and lowercase-with-dashes name. */ - private static final Map FASTQ_VARIANTS = new HashMap(6); + private static final Map FASTQ_VARIANTS = new HashMap<>(6); static { @@ -206,7 +206,7 @@ public double errorProbability(final int qualityScore) * * @param description description of this FASTQ sequence format variant, must not be null */ - private FastqVariant(final String description) + FastqVariant(final String description) { if (description == null) { diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/ParseListener.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/ParseListener.java index f03f77fc92..14890b9ead 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/ParseListener.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/ParseListener.java @@ -33,9 +33,8 @@ public interface ParseListener * Notify this parse listener of a description line. * * @param description description line - * @throws IOException if an I/O error occurs - */ - void description(String description) throws IOException; + */ + void description(String description); /** * Notify this parse listener of a sequence line. @@ -47,9 +46,8 @@ public interface ParseListener *

    * * @param sequence sequence line - * @throws IOException if an I/O error occurs - */ - void sequence(String sequence) throws IOException; + */ + void sequence(String sequence); /** * Notify this parse listener of an additional sequence line. @@ -60,9 +58,8 @@ public interface ParseListener *

    * * @param sequence additional sequence line - * @throws IOException if an I/O error occurs - */ - void appendSequence(String sequence) throws IOException; + */ + void appendSequence(String sequence); /** * Notify this parse listener of a repeat description line. diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/StreamingFastqParser.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/StreamingFastqParser.java index a0455381ed..c22db24fc7 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/StreamingFastqParser.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/io/fastq/StreamingFastqParser.java @@ -58,20 +58,17 @@ static void stream(final Readable readable, final FastqVariant variant, final St FastqParser.parse(readable, new ParseListener() { @Override - public void description(final String description) throws IOException - { + public void description(final String description) { builder.withDescription(description); } @Override - public void sequence(final String sequence) throws IOException - { + public void sequence(final String sequence) { builder.withSequence(sequence); } @Override - public void appendSequence(final String sequence) throws IOException - { + public void appendSequence(final String sequence) { builder.appendSequence(sequence); } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/cytoband/CytobandParser.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/cytoband/CytobandParser.java index 560566b0b2..5655976e2f 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/cytoband/CytobandParser.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/cytoband/CytobandParser.java @@ -52,11 +52,10 @@ public static void main(String[] args) { try { SortedSet cytobands = me.getAllCytobands(new URL( DEFAULT_LOCATION)); - SortedSet types = new TreeSet(); + SortedSet types = new TreeSet<>(); for (Cytoband c : cytobands) { logger.info("Cytoband: {}", c); - if (!types.contains(c.getType())) - types.add(c.getType()); + types.add(c.getType()); } logger.info("Strain Type: {}", types); } catch (Exception e) { @@ -76,8 +75,8 @@ public SortedSet getAllCytobands(InputStream instream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader( instream)); - String line = null; - SortedSet cytobands = new TreeSet(); + String line; + SortedSet cytobands = new TreeSet<>(); while ((line = reader.readLine()) != null) { String[] spl = line.split("\t"); if (spl.length != 5) { diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/geneid/GeneIDXMLReader.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/geneid/GeneIDXMLReader.java index a573a7062d..d2559768bf 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/geneid/GeneIDXMLReader.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/geneid/GeneIDXMLReader.java @@ -31,8 +31,8 @@ import org.w3c.dom.Element; import java.io.File; -import java.util.ArrayList; import java.util.LinkedHashMap; +import java.util.List; /** * @@ -42,7 +42,7 @@ public class GeneIDXMLReader { private static final Logger logger = LoggerFactory.getLogger(GeneIDXMLReader.class); - Document geneidDoc = null; + Document geneidDoc; public GeneIDXMLReader(String geneidXMLFile) throws Exception { logger.info("Start read of {}", geneidXMLFile); @@ -51,8 +51,8 @@ public GeneIDXMLReader(String geneidXMLFile) throws Exception { } public LinkedHashMap getProteinSequences() throws Exception { - LinkedHashMap proteinSequenceList = new LinkedHashMap(); - ArrayList elementList = XMLHelper.selectElements(geneidDoc.getDocumentElement(), "prediction/gene/protein"); + LinkedHashMap proteinSequenceList = new LinkedHashMap<>(); + List elementList = XMLHelper.selectElements(geneidDoc.getDocumentElement(), "prediction/gene/protein"); logger.info("{} hits", elementList.size()); for (Element proteinElement : elementList) { @@ -68,11 +68,9 @@ public LinkedHashMap getProteinSequences() throws Excep } public LinkedHashMap getDNACodingSequences() throws Exception { - LinkedHashMap dnaSequenceList = new LinkedHashMap(); - ArrayList elementList = XMLHelper.selectElements(geneidDoc.getDocumentElement(), "prediction/gene/cDNA"); - logger.info("{} hits", elementList.size()); + LinkedHashMap dnaSequenceList = new LinkedHashMap<>(); - for (Element dnaElement : elementList) { + for (Element dnaElement : XMLHelper.selectElements(geneidDoc.getDocumentElement(), "prediction/gene/cDNA")) { Element geneElement = (Element) dnaElement.getParentNode(); String sequence = dnaElement.getTextContent().replaceAll("\\W",""); DNASequence dnaSequence = new DNASequence(sequence); diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/genename/GeneChromosomePosition.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/genename/GeneChromosomePosition.java index 51e6657b5a..71a76e2a4e 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/genename/GeneChromosomePosition.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/genename/GeneChromosomePosition.java @@ -38,7 +38,9 @@ public class GeneChromosomePosition implements Comparable exonStarts; + /** TODO int[] */ private List exonEnds; public String getGeneName() { diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/genename/GeneChromosomePositionParser.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/genename/GeneChromosomePositionParser.java index df6a1a4373..f1416e5683 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/genename/GeneChromosomePositionParser.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/genename/GeneChromosomePositionParser.java @@ -23,8 +23,8 @@ package org.biojava.nbio.genome.parsers.genename; -import org.biojava.nbio.genome.App; import org.biojava.nbio.core.util.InputStreamProvider; +import org.biojava.nbio.genome.App; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -66,22 +66,15 @@ public static void main(String[] args){ } public static List getChromosomeMappings() throws IOException { - - URL url = new URL(DEFAULT_MAPPING_URL); - - InputStreamProvider prov = new InputStreamProvider(); - - InputStream inStream = prov.getInputStream(url); - - return getChromosomeMappings(inStream); + return getChromosomeMappings(new InputStreamProvider().getInputStream(new URL(DEFAULT_MAPPING_URL))); } public static List getChromosomeMappings(InputStream inStream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(inStream)); - ArrayList gcps = new ArrayList(); + ArrayList gcps = new ArrayList<>(1024); - String line = null; + String line; while ((line = reader.readLine()) != null) { GeneChromosomePosition gcp = getGeneChromosomePosition(line); if ( gcp != null) @@ -94,8 +87,7 @@ public static List getChromosomeMappings(InputStream inS } private static GeneChromosomePosition getGeneChromosomePosition(String line) { - if ( line == null) - return null; + String[] spl = line.split("\t"); if ( spl.length != 11) { @@ -114,10 +106,8 @@ private static GeneChromosomePosition getGeneChromosomePosition(String line) { g.setCdsStart(Integer.parseInt(spl[6])); g.setCdsEnd(Integer.parseInt(spl[7])); g.setExonCount(Integer.parseInt(spl[8])); - String exonStarts = spl[9]; - String exonEnds = spl[10]; - g.setExonStarts(getIntegerList(exonStarts)); - g.setExonEnds(getIntegerList(exonEnds)); + g.setExonStarts(getIntegerList(spl[9])); + g.setExonEnds(getIntegerList(spl[10])); //System.out.println(line); //System.out.println(Arrays.asList(spl) + " " + spl.length); @@ -126,11 +116,9 @@ private static GeneChromosomePosition getGeneChromosomePosition(String line) { private static List getIntegerList(String lst){ String[] spl = lst.split(","); - ArrayList l = new ArrayList(); - for (String s : spl){ + ArrayList l = new ArrayList<>(spl.length); + for (String s : spl) l.add(Integer.parseInt(s)); - } - l.trimToSize(); return l; } } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/genename/GeneNamesParser.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/genename/GeneNamesParser.java index e9158c015a..1e13df5107 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/genename/GeneNamesParser.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/genename/GeneNamesParser.java @@ -92,7 +92,7 @@ public static List getGeneNames() throws IOException{ */ public static List getGeneNames(InputStream inStream) throws IOException{ - ArrayList geneNames = new ArrayList(); + ArrayList geneNames = new ArrayList<>(); BufferedReader reader = new BufferedReader(new InputStreamReader(inStream)); // skip reading first line (it is the legend) diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/Feature.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/Feature.java index 9d750f850e..7457f7048d 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/Feature.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/Feature.java @@ -51,8 +51,6 @@ public String seqname() { return mSeqname; } - ; - /** * Get source (aka method). (GFF field 2). This is often the name of * the program or procedure that created the features. @@ -63,8 +61,6 @@ public String source() { return mSource; } - ; - /** * Get feature type, such as "exon" or "CDS". (GFF field 3). * @@ -75,8 +71,6 @@ public String type() { return mType; } - ; - /** * Get location of feature. Note that feature objects have * no link or reference to the actual sequence object to which @@ -98,8 +92,6 @@ public double score() { return mScore; } - ; - /** * Get frame (aka phase). (GFF field 8). Specifies the offset of the * first nucleotide of the first in-frame codon, assuming this feature @@ -113,8 +105,6 @@ public int frame() { return mFrame; } - ; - /** * Get the string of key/value attributes. (GFF field 9). The format and * meaning of this field varies from flavor to flavor of GFF/GTF. This method @@ -127,13 +117,11 @@ public String attributes() { return mAttributes; } - ; - @SuppressWarnings("unused") private Feature() { } - ; //unavailable + //unavailable /** * Make a copy of the specified feature. The mappings in the userMap() HashMap @@ -153,7 +141,7 @@ public Feature(Feature feature) { mFrame = feature.mFrame; mAttributes = feature.mAttributes; initAttributeHashMap(); - mUserMap = new HashMap(feature.mUserMap); + mUserMap = new HashMap<>(feature.mUserMap); } /** @@ -177,7 +165,7 @@ public Feature(String seqname, String source, String type, Location location, Do mFrame = frame; mAttributes = attributes; initAttributeHashMap(); - mUserMap = new HashMap(); + mUserMap = new HashMap<>(); } @@ -199,13 +187,13 @@ public HashMap userData() { return mUserMap; } - HashMap attributeHashMap = new HashMap(); + final HashMap attributeHashMap = new HashMap<>(); private void initAttributeHashMap(){ String[] values = mAttributes.split(";"); for(String attribute : values){ attribute = attribute.trim(); - int equalindex = attribute.indexOf("="); + int equalindex = attribute.indexOf('='); String splitData = "="; if(equalindex == -1) //gtf uses space and gff3 uses = splitData = " "; @@ -300,7 +288,7 @@ public String toString() { s += mType + '\t'; s += mLocation.start() + "\t"; s += mLocation.end() + "\t"; - s += Double.toString(mScore) + "\t"; + s += mScore + "\t"; if (mFrame == -1) { s += ".\t"; diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureHelper.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureHelper.java index 1383276ce2..bcdc0bc32b 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureHelper.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureHelper.java @@ -38,7 +38,7 @@ public class FeatureHelper { */ static public LinkedHashMap buildFeatureAtrributeIndex(String attribute,FeatureList list){ - LinkedHashMap featureHashMap = new LinkedHashMap(); + LinkedHashMap featureHashMap = new LinkedHashMap<>(); FeatureList featureList = list.selectByAttribute(attribute); for(FeatureI feature : featureList){ String value = feature.getAttribute(attribute); diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureI.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureI.java index 9fa7c02061..0e9c35359e 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureI.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureI.java @@ -36,7 +36,7 @@ public interface FeatureI * * @return The location. */ - public Location location(); + Location location(); /** * Get the group id of the feature. The group id is defined in the GFF1 @@ -50,21 +50,21 @@ public interface FeatureI * * @return The group id. This may be an empty string. */ - public String group(); + String group(); /** * Get the feature type, for example, "exon", "CDS", etc. * * @return The type. */ - public String type(); + String type(); /** * Get the sequence name. * * @return Sequence name. */ - public String seqname(); + String seqname(); /** * Get the attribute value for this key. @@ -72,7 +72,7 @@ public interface FeatureI * @param key The key. * @return The corresponding value. Null if the key has no value defined . */ - public String getAttribute( String key ); + String getAttribute(String key); /** @@ -81,7 +81,7 @@ public interface FeatureI * @param key The key. * @return True if a value is defined for this key. */ - public boolean hasAttribute( String key ); + boolean hasAttribute(String key); /** * Check if the feature attributes include the specified key/value pair. @@ -90,7 +90,7 @@ public interface FeatureI * @param value The value. * @return True if the feature's value for this key matches the specified value. */ - public boolean hasAttribute( String key, String value ); + boolean hasAttribute(String key, String value); /** * A string representation of the feature. @@ -98,15 +98,15 @@ public interface FeatureI * @return The string. */ @Override - public String toString(); + String toString(); /** * Get HashMap of user data. * * @return The user HashMap. */ - public HashMap userData(); + HashMap userData(); - public HashMap getAttributes(); + HashMap getAttributes(); } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureList.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureList.java index 19b7afec93..45aac4219c 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureList.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/FeatureList.java @@ -40,7 +40,7 @@ @SuppressWarnings("serial") public class FeatureList extends ArrayList { - Map>> featindex = new HashMap>>(); + final Map>> featindex = new HashMap<>(); Location mLocation; //genomic location (union of feature locations) /** @@ -81,11 +81,11 @@ public boolean add(FeatureI feature) { if (featindex.containsKey(entry.getKey())){ Map> feat = featindex.get(entry.getKey()); if (feat==null){ - feat= new HashMap>(); + feat= new HashMap<>(); } List features = feat.get(entry.getValue()); if (features==null){ - features = new ArrayList(); + features = new ArrayList<>(); } features.add(feature); feat.put(entry.getValue(), features); @@ -103,9 +103,7 @@ public boolean add(FeatureI feature) { * @param list The collection of FeatureI objects. */ public void add(Collection list) { - for (FeatureI f : list) { - add(f); - } + this.addAll(list); } /** @@ -185,7 +183,7 @@ public String splice(DNASequence sequence) { * the order of features in the list. */ public Collection groupValues() { - Set set = new HashSet(); + Set set = new HashSet<>(); for (FeatureI f : this) { //enter in a set -- removes duplicates set.add(f.group()); @@ -207,10 +205,10 @@ public Collection attributeValues(String key) { if (featindex.containsKey(key)){ Map> map = featindex.get(key); Collection result = map.keySet(); - if (result == null) result = new HashSet(); + if (result == null) result = new HashSet<>(); return Collections.unmodifiableCollection(result); } - LinkedHashMap hash = new LinkedHashMap(); + LinkedHashMap hash = new LinkedHashMap<>(); for (FeatureI f : this) { //enter as a key -- removes duplicates hash.put(f.getAttribute(key), null); @@ -353,8 +351,7 @@ public FeatureList selectByUserData(String key) { * on the same strand as the specified location will be considered for inclusion. * @return The new list of features that overlap the location. */ - public FeatureList selectOverlapping(String seqname, Location location, boolean useBothStrands) - throws Exception { + public FeatureList selectOverlapping(String seqname, Location location, boolean useBothStrands) { FeatureList list = new FeatureList(); for (FeatureI feature : this) { @@ -458,7 +455,7 @@ public boolean hasAttribute(String key, String value) { public String toString() { StringBuilder s = new StringBuilder("FeatureList: >>\n"); for (FeatureI f : this) { - s.append( f.seqname() + ":" + f.toString() + "\n"); + s.append(f.seqname()).append(":").append(f.toString()).append("\n"); } s.append("\n<<\n"); @@ -468,7 +465,7 @@ public String toString() { /** * used by sort routine */ - private class FeatureComparator implements Comparator, Serializable { + private static class FeatureComparator implements Comparator, Serializable { private static final long serialVersionUID = 1; @Override diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GFF3Reader.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GFF3Reader.java index a0f5b573f8..049dc68a55 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GFF3Reader.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GFF3Reader.java @@ -100,7 +100,7 @@ public static FeatureList read(String filename, List indexes) throws IOE public static FeatureList read(String filename) throws IOException { - return read(filename,new ArrayList(0)); + return read(filename, new ArrayList<>(0)); } @@ -122,7 +122,7 @@ private static Feature parseLine(String s) { String locEnd =line[4].trim(); - Double score; + double score; try { score = Double.parseDouble(line[5].trim()); diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GFF3Writer.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GFF3Writer.java index c4bc070f21..9f1df17ea1 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GFF3Writer.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GFF3Writer.java @@ -20,15 +20,15 @@ */ package org.biojava.nbio.genome.parsers.gff; -import org.biojava.nbio.genome.GeneFeatureHelper; import org.biojava.nbio.core.sequence.*; +import org.biojava.nbio.genome.GeneFeatureHelper; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.ArrayList; -import java.util.Collections; import java.util.LinkedHashMap; +import java.util.Map; /** * @@ -45,9 +45,10 @@ public class GFF3Writer { public void write(OutputStream outputStream, LinkedHashMap chromosomeSequenceList) throws Exception { outputStream.write("##gff-version 3\n".getBytes()); - for (String key : chromosomeSequenceList.keySet()) { - ChromosomeSequence chromosomeSequence = chromosomeSequenceList.get(key); - String gff3line = ""; + for (Map.Entry entry : chromosomeSequenceList.entrySet()) { + String key = entry.getKey(); + ChromosomeSequence chromosomeSequence = entry.getValue(); + String gff3line; // if(source.length() == 0){ // Collection genes = chromosomeSequence.getGeneSequences().values(); // for(GeneSequence gene : genes){ @@ -94,8 +95,8 @@ public void write(OutputStream outputStream, LinkedHashMap cdsSequenceList = new ArrayList(transcriptSequence.getCDSSequences().values()); - Collections.sort(cdsSequenceList, new SequenceComparator()); + ArrayList cdsSequenceList = new ArrayList<>(transcriptSequence.getCDSSequences().values()); + cdsSequenceList.sort(new SequenceComparator()); for (CDSSequence cdsSequence : cdsSequenceList) { gff3line = key + "\t" + cdsSequence.getSource() + "\t" + "CDS" + "\t" + cdsSequence.getBioBegin() + "\t" + cdsSequence.getBioEnd() + "\t"; score = cdsSequence.getSequenceScore(); diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GeneIDGFF2Reader.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GeneIDGFF2Reader.java index c7f59de102..2b8851c311 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GeneIDGFF2Reader.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GeneIDGFF2Reader.java @@ -24,7 +24,6 @@ import org.slf4j.LoggerFactory; import java.io.*; -import java.util.ListIterator; /** * http://www.bioperl.org/wiki/GTF @@ -93,7 +92,7 @@ private static Feature parseLine(String s) { //FIXME update to use regex split on tabs //FIXME better errors on parse failures - int start = 0; + int start; int end = 0; start = end; @@ -116,7 +115,7 @@ private static Feature parseLine(String s) { end = s.indexOf('\t', start); String locEnd = s.substring(start, end); - Double score; + double score; start = end + 1; end = s.indexOf('\t', start); try { @@ -145,11 +144,11 @@ private static Feature parseLine(String s) { //grab everything until end of line (or # comment) start = end + 1; end = s.indexOf('#', start); - String attributes = null; + String attributes; if (end < 0) { - attributes = new String(s.substring(start)); + attributes = s.substring(start); } else { - attributes = new String(s.substring(start, end)); + attributes = s.substring(start, end); } //need to add in attribute assignment for geneid where it just provides a gene name and will make it gtf like attributes = "gene_id " + '"' + attributes + '"' + ";"; @@ -170,9 +169,8 @@ public static void write(FeatureList features, String filename) throws IOExcepti BufferedWriter bw = new BufferedWriter(new FileWriter(filename)); - ListIterator iter = features.listIterator(); - while (iter.hasNext()) { - Feature feature = (Feature) iter.next(); + for (FeatureI featureI : features) { + Feature feature = (Feature) featureI; writeLine(feature, bw); } @@ -186,7 +184,7 @@ private static void writeLine(Feature f, BufferedWriter bw) throws IOException { s += f.location().bioStart() + "\t"; s += f.location().bioEnd() + "\t"; - s += Double.toString(f.score()) + "\t"; + s += f.score() + "\t"; s += f.location().bioStrand() + "\t"; if (f.frame() == -1) { diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GeneMarkGTFReader.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GeneMarkGTFReader.java index 8f0f53b026..c0c191d07a 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GeneMarkGTFReader.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/GeneMarkGTFReader.java @@ -93,7 +93,7 @@ public static FeatureList read(String filename) throws IOException { private static Feature parseLine(String s) { //FIXME update to use regex split on tabs //FIXME better errors on parse failures - int start = 0; + int start; int end = 0; start = end; @@ -116,7 +116,7 @@ private static Feature parseLine(String s) { end = s.indexOf('\t', start); String locEnd = s.substring(start, end); - Double score; + double score; start = end + 1; end = s.indexOf('\t', start); try { @@ -145,11 +145,11 @@ private static Feature parseLine(String s) { //grab everything until end of line (or # comment) start = end + 1; end = s.indexOf('#', start); - String attributes = null; + String attributes; if (end < 0) { - attributes = new String(s.substring(start)); + attributes = s.substring(start); } else { - attributes = new String(s.substring(start, end)); + attributes = s.substring(start, end); } return new Feature(seqname, source, type, location, score, frame, attributes); diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/LocIterator.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/LocIterator.java index c8ffd98974..06c94a92d6 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/LocIterator.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/LocIterator.java @@ -44,9 +44,9 @@ public class LocIterator implements Iterator { int mIncrement; @SuppressWarnings("unused") - private LocIterator() {}; + private LocIterator() {} - /** + /** * Construct an iterator that slides a window over a Location. * * @param bounds The location over which to iterate. @@ -138,7 +138,7 @@ public boolean hasNext() */ public Location remainder() { - Location remainder= null; + Location remainder; if( mPosition == 0 ) { diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/Location.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/Location.java index 91e71463f8..6a4b1baeea 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/Location.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/gff/Location.java @@ -69,8 +69,8 @@ public class Location implements Iterable { - private int mStart; - private int mEnd; + private final int mStart; + private final int mEnd; /** @@ -267,8 +267,8 @@ public Location union( Location other ) } else { - int start= (other.mStart < mStart)? other.mStart: mStart; - int end= (other.mEnd > mEnd)? other.mEnd: mEnd; + int start= Math.min(other.mStart, mStart); + int end= Math.max(other.mEnd, mEnd); return new Location( start, end ); } @@ -293,22 +293,22 @@ public Location intersection(Location other) { } } - private Location intersect(int a1, int a2, int b1, int b2) { + private static Location intersect(int a1, int a2, int b1, int b2) { if (a1 > b1) { return intersect(b1, b2, a1, a2); } // Safe to assume a1 <= b1 - if (b1 >= a2) { + else if (b1 >= a2) { // b starts after a ends return null; - } else if (b1 < a2 && b2 <= a2) { + } else if (b2 <= a2) { // b starts after a starts and ends before or at where a ends return new Location(b1, b2); - } else if (b1 >= a1 && a2 <= b2) { + } else if (a2 <= b2) { // b starts after a but extends after the end of a return new Location(b1, a2); - } - return null; + } else + return null; } @@ -368,15 +368,7 @@ public Iterable window( final int windowSize, final int increment ) final Location loc= this; //return iterable anonymous inner class - return new Iterable () - { - @Override - public LocIterator iterator() - { - return new LocIterator( loc, windowSize, increment ); - } - - }; + return () -> new LocIterator( loc, windowSize, increment ); } /** @@ -503,7 +495,7 @@ public Location prefix( Location other ) { if( other.mStart >= mStart ) { - return new Location( mStart, (other.mStart < mEnd)? other.mStart: mEnd ); + return new Location( mStart, Math.min(other.mStart, mEnd)); } else { @@ -531,7 +523,7 @@ public Location suffix( Location other ) { if( other.mEnd <= mEnd ) { - return new Location( (other.mEnd > mStart)? other.mEnd: mStart, mEnd ); + return new Location(Math.max(other.mEnd, mStart), mEnd ); } else { @@ -843,7 +835,7 @@ public boolean isSameStrand( Location other ) @Override public String toString() { - return new String( "[L=" + (mEnd - mStart) + "; S=" + mStart + "; E=" + mEnd +"]" ); + return "[L=" + (mEnd - mStart) + "; S=" + mStart + "; E=" + mEnd + "]"; } /* (non-Javadoc) @@ -865,24 +857,17 @@ public int hashCode() { public boolean equals(Object obj) { if (this == obj) return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) + if (obj == null || getClass() != obj.getClass()) return false; Location other = (Location) obj; - if (mEnd != other.mEnd) - return false; - if (mStart != other.mStart) - return false; - return true; + return mStart == other.mStart && mEnd == other.mEnd; } /** * */ - private boolean isHealthy() - { - return ( mStart <= mEnd ) && (( mStart <= 0 && mEnd <= 0 ) || (mStart >= 0 && mEnd >= 0)); + private boolean isHealthy() { + return ( mStart <= mEnd ) && (( mStart <= 0 && mEnd <= 0 ) || (mStart >= 0 /*&& mEnd >= 0*/)); } } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/twobit/SimpleTwoBitFileProvider.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/twobit/SimpleTwoBitFileProvider.java index b587a5950f..a23e4a6d69 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/twobit/SimpleTwoBitFileProvider.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/twobit/SimpleTwoBitFileProvider.java @@ -20,7 +20,7 @@ */ package org.biojava.nbio.genome.parsers.twobit; -import org.biojava.nbio.core.util.FileDownloadUtils; +import org.biojava.nbio.core.util.Download; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -49,7 +49,7 @@ public static synchronized void downloadIfNoTwoBitFileExists(File twoBitFileLoca logger.info("downloading " + twoBitFileURL + " to " + tmp.getAbsolutePath()); // 2bit files are large and take a while to download - FileDownloadUtils.downloadFile(twoBitFileURL, tmp); + Download.downloadFile(twoBitFileURL, tmp); // check the parent directory exists diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/twobit/TwoBitFacade.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/twobit/TwoBitFacade.java index 71dfc4174f..f90b33d4f2 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/twobit/TwoBitFacade.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/twobit/TwoBitFacade.java @@ -28,7 +28,7 @@ */ public class TwoBitFacade { - private TwoBitParser twoBitParser = null; + private final TwoBitParser twoBitParser; /** @@ -43,7 +43,7 @@ public TwoBitFacade(File file) throws Exception { /** * Closes .2bit file twoBitParser. */ - public void close() throws Exception { + public void close() { if (twoBitParser != null) twoBitParser.close(); diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/twobit/TwoBitParser.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/twobit/TwoBitParser.java index 4f5733037d..9e74f1dda8 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/twobit/TwoBitParser.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/parsers/twobit/TwoBitParser.java @@ -46,13 +46,13 @@ public class TwoBitParser extends InputStream { private static final Logger logger = LoggerFactory.getLogger(TwoBitParser.class); - public int DEFAULT_BUFFER_SIZE = 10000; + public final int DEFAULT_BUFFER_SIZE = 10000; // - private RandomAccessFile raf; - private File f; + private final RandomAccessFile raf; + private final File f; private boolean reverse = false; - private String[] seq_names; - private HashMap seq2pos = new HashMap(); + private final String[] seq_names; + private final HashMap seq2pos = new HashMap<>(); private String cur_seq_name; private long[][] cur_nn_blocks; private long[][] cur_mask_blocks; @@ -98,7 +98,7 @@ else if(sign==0x4327411A) { } } private long readFourBytes() throws Exception { - long ret = 0; + long ret; if(!reverse) { ret = raf.read(); ret += raf.read()*0x100; @@ -170,7 +170,7 @@ public void setCurrentSequence(String seq_name) throws Exception { * Method resets current position to the begining of sequence stream. */ @Override - public synchronized void reset() throws IOException { + public synchronized void reset() { cur_seq_pos = 0; cur_nn_block_num = (cur_nn_blocks.length>0)?0:-1; cur_mask_block_num = (cur_mask_blocks.length>0)?0:-1; @@ -228,7 +228,7 @@ public int read() throws IOException { else if(bit_num==3) { file_pos++; } - char ret = 'N'; + char ret; if((cur_nn_block_num>=0)&& (cur_nn_blocks[cur_nn_block_num][0]<=cur_seq_pos)) { if(cur_bits[bit_num]!=0) { @@ -297,7 +297,7 @@ public synchronized long skip(long n) throws IOException { * new current sequence. */ @Override - public void close() throws IOException { + public void close() { cur_seq_name = null; cur_nn_blocks = null; cur_mask_blocks = null; diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/query/BlastXMLQuery.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/query/BlastXMLQuery.java index ff5e1318d0..241eb19df7 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/query/BlastXMLQuery.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/query/BlastXMLQuery.java @@ -29,6 +29,7 @@ import java.util.ArrayList; import java.util.LinkedHashMap; +import java.util.List; /** * @@ -38,7 +39,7 @@ public class BlastXMLQuery { private static final Logger logger = LoggerFactory.getLogger(BlastXMLQuery.class); - Document blastDoc = null; + Document blastDoc; public BlastXMLQuery(String blastFile) throws Exception { logger.info("Start read of {}", blastFile); @@ -47,31 +48,27 @@ public BlastXMLQuery(String blastFile) throws Exception { } public LinkedHashMap> getHitsQueryDef(double maxEScore) throws Exception { - LinkedHashMap> hitsHashMap = new LinkedHashMap>(); + LinkedHashMap> hitsHashMap = new LinkedHashMap<>(); logger.info("Query for hits"); - ArrayList elementList = XMLHelper.selectElements(blastDoc.getDocumentElement(), "BlastOutput_iterations/Iteration[Iteration_hits]"); + List elementList = XMLHelper.selectElements(blastDoc.getDocumentElement(), "BlastOutput_iterations/Iteration[Iteration_hits]"); logger.info("{} hits", elementList.size()); for (Element element : elementList) { Element iterationquerydefElement = XMLHelper.selectSingleElement(element, "Iteration_query-def"); String querydef = iterationquerydefElement.getTextContent(); Element iterationHitsElement = XMLHelper.selectSingleElement(element, "Iteration_hits"); - ArrayList hitList = XMLHelper.selectElements(iterationHitsElement, "Hit"); + List hitList = XMLHelper.selectElements(iterationHitsElement, "Hit"); for (Element hitElement : hitList) { Element hitaccessionElement = XMLHelper.selectSingleElement(hitElement, "Hit_accession"); String hitaccession = hitaccessionElement.getTextContent(); Element hithspsElement = XMLHelper.selectSingleElement(hitElement, "Hit_hsps"); - ArrayList hspList = XMLHelper.selectElements(hithspsElement, "Hsp"); + List hspList = XMLHelper.selectElements(hithspsElement, "Hsp"); for (Element hspElement : hspList) { Element evalueElement = XMLHelper.selectSingleElement(hspElement, "Hsp_evalue"); String value = evalueElement.getTextContent(); double evalue = Double.parseDouble(value); if (evalue <= maxEScore) { - ArrayList hits = hitsHashMap.get(querydef); - if (hits == null) { - hits = new ArrayList(); - hitsHashMap.put(querydef, hits); - } + ArrayList hits = hitsHashMap.computeIfAbsent(querydef, k -> new ArrayList<>()); hits.add(hitaccession); } } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/uniprot/UniprotToFasta.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/uniprot/UniprotToFasta.java index 66a9d2a086..2806e83d9d 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/uniprot/UniprotToFasta.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/uniprot/UniprotToFasta.java @@ -67,10 +67,10 @@ public void process( String uniprotDatFileName,String fastaFileName ) throws Exc String line = br.readLine(); String id = ""; StringBuffer sequence = new StringBuffer(); - ArrayList seqCodingRegionsList = new ArrayList(); + ArrayList seqCodingRegionsList = new ArrayList<>(); int count = 0; - HashMap uniqueGenes = new HashMap(); - HashMap uniqueSpecies = new HashMap(); + HashMap uniqueGenes = new HashMap<>(); + HashMap uniqueSpecies = new HashMap<>(); while(line != null){ if(line.startsWith("ID")){ String[] data = line.split(" "); diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/util/ChromosomeMappingTools.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/util/ChromosomeMappingTools.java index a63a78a236..0c03ce9c2e 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/util/ChromosomeMappingTools.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/util/ChromosomeMappingTools.java @@ -49,10 +49,10 @@ public class ChromosomeMappingTools { public static final String CHROMOSOME = "CHROMOSOME"; public static final String CDS = "CDS"; - private static int base = 1; - public static void setCoordinateSystem(int baseInt) { - base = baseInt; - } +// private static final int base = 1; +// public static void setCoordinateSystem(int baseInt) { +// base = baseInt; +// } /** * Pretty print the details of a GeneChromosomePosition to a String @@ -100,7 +100,7 @@ private static String formatExonStructureForward(GeneChromosomePosition chromPos s.append(" <- Exon : ").append(format(start + 1)).append(" - ").append(format(cdsEnd)).append(" | ").append(Integer.toString(cdsEnd - start)).append(" | ").append(Integer.toString(codingLength)).append(" | ").append(Integer.toString(codingLength % 3)); s.append(newline); - s.append(" UTR : " + (cdsEnd +1) + " - " + format(end)); + s.append(" UTR : ").append(String.valueOf(cdsEnd + 1)).append(" - ").append(format(end)); s.append(newline); } else if (inCoding) { @@ -112,7 +112,7 @@ private static String formatExonStructureForward(GeneChromosomePosition chromPos } } s.append("Coding Length: "); - s.append((codingLength-3)+""); + s.append(String.valueOf(codingLength - 3)); s.append(newline); return s.toString(); } @@ -159,7 +159,7 @@ private static String formatExonStructureReverse(GeneChromosomePosition chromPos } codingLength += (cdsEnd - tmpstart); - s.append(" UTR :" + format(cdsEnd + 1) + " | " + format(end)); + s.append(" UTR :").append(format(cdsEnd + 1)).append(" | ").append(format(end)); s.append(newline); if (tmpstart == start) s.append(" -> "); @@ -169,16 +169,16 @@ private static String formatExonStructureReverse(GeneChromosomePosition chromPos s.append(newline); // single exon with UTR on both ends if (tmpstart != start) - s.append(" UTR :" + format(cdsStart ) + " - " + format(start + 1)); + s.append(" UTR :").append(format(cdsStart)).append(" - ").append(format(start + 1)); s.append(newline); } else if (start <= cdsStart && end >= cdsStart) { inCoding = false; codingLength += (end - cdsStart); - s.append(" <- Exon : " + format(cdsStart+1) + " - " + format(end) + " | " + (end - cdsStart) + " | " + codingLength + " | " + (codingLength % 3)); + s.append(" <- Exon : ").append(format(cdsStart + 1)).append(" - ").append(format(end)).append(" | ").append(String.valueOf(end - cdsStart)).append(" | ").append(String.valueOf(codingLength)).append(" | ").append(String.valueOf(codingLength % 3)); s.append(newline); - s.append(" UTR : " + format(start+1) + " - " + format(cdsStart )); + s.append(" UTR : ").append(format(start + 1)).append(" - ").append(format(cdsStart)); s.append(newline); @@ -186,7 +186,7 @@ private static String formatExonStructureReverse(GeneChromosomePosition chromPos // full exon is coding codingLength += (end - start); - s.append(" Exon : " + format(start+1) + " - " + format(end) + " | " + (end - start) + " | " + codingLength + " | " + (codingLength % 3)); + s.append(" Exon : ").append(format(start + 1)).append(" - ").append(format(end)).append(" | ").append(String.valueOf(end - start)).append(" | ").append(String.valueOf(codingLength)).append(" | ").append(String.valueOf(codingLength % 3)); s.append(newline); } else { // e.g. see UBQLN3 @@ -207,7 +207,7 @@ private static String formatExonStructureReverse(GeneChromosomePosition chromPos * @param chromPos * @return length of the CDS in nucleotides. */ - public static int getCDSLength(GeneChromosomePosition chromPos) { + public static int getCDSLength(GeneChromosomePosition chromPos, int base) { List exonStarts = chromPos.getExonStarts(); List exonEnds = chromPos.getExonEnds(); @@ -217,9 +217,9 @@ public static int getCDSLength(GeneChromosomePosition chromPos) { int codingLength; if (chromPos.getOrientation().equals('+')) - codingLength = ChromosomeMappingTools.getCDSLengthForward(exonStarts, exonEnds, cdsStart, cdsEnd); + codingLength = ChromosomeMappingTools.getCDSLengthForward(exonStarts, exonEnds, cdsStart, cdsEnd, base); else - codingLength = ChromosomeMappingTools.getCDSLengthReverse(exonStarts, exonEnds, cdsStart, cdsEnd); + codingLength = ChromosomeMappingTools.getCDSLengthReverse(exonStarts, exonEnds, cdsStart, cdsEnd, base); return codingLength; } @@ -242,7 +242,7 @@ public static ChromPos getChromosomePosForCDScoordinate(int cdsNucleotidePositio int cdsEnd = chromPos.getCdsEnd(); - ChromPos chromosomePos = null; + ChromPos chromosomePos; if (chromPos.getOrientation().equals('+')) @@ -333,18 +333,18 @@ public static ChromPos getChromPosReverse(int cdsPos, List exonStarts, if ( debug ) { - StringBuffer b = new StringBuffer(); + StringBuilder b = new StringBuilder(); - b.append(" UTR :" + format(cdsEnd + 1) + " - " + format(end) + newline); + b.append(" UTR :").append(format(cdsEnd + 1)).append(" - ").append(format(end)).append(newline); if (tmpstart == start) b.append(" -> "); else b.append(" <-> "); - b.append("Exon :" + format(tmpstart + 1) + " - " + (cdsEnd) + " | " + format(cdsEnd - tmpstart + 1) + " - " + codingLength + " | " + (codingLength % 3) + newline); + b.append("Exon :").append(format(tmpstart + 1)).append(" - ").append(cdsEnd).append(" | ").append(format(cdsEnd - tmpstart + 1)).append(" - ").append(codingLength).append(" | ").append(codingLength % 3).append(newline); // single exon with UTR on both ends if (tmpstart != start) - b.append(" UTR :" + format(cdsStart) + " - " + format(start + 1) + newline); + b.append(" UTR :").append(format(cdsStart)).append(" - ").append(format(start + 1)).append(newline); logger.debug(b.toString()); } @@ -498,7 +498,7 @@ public static ChromPos getChromPosForward(int cdsPos, List exonStarts, * @param cdsEnd * @return */ - public static int getCDSLengthReverse(List exonStarts, List exonEnds, int cdsStart, int cdsEnd) { + public static int getCDSLengthReverse(List exonStarts, List exonEnds, int cdsStart, int cdsEnd, int base) { int codingLength = 0; @@ -545,7 +545,7 @@ public static int getCDSLengthReverse(List exonStarts, List ex * @param cdsEnd * @return */ - public static int getCDSLengthForward(List exonStarts, List exonEnds, int cdsStart, int cdsEnd) { + public static int getCDSLengthForward(List exonStarts, List exonEnds, int cdsStart, int cdsEnd, int base) { int codingLength = 0; @@ -586,9 +586,9 @@ public static List> getCDSExonRanges(GeneChromosomePosition chrom * @return */ public static List> getChromosomalRangesForCDS(GeneChromosomePosition chromPos){ - if ( chromPos.getOrientation() == '+') - return getCDSExonRangesForward(chromPos,CHROMOSOME); - return getCDSExonRangesReverse(chromPos,CHROMOSOME); + return chromPos.getOrientation() == '+' ? + getCDSExonRangesForward(chromPos, CHROMOSOME) : + getCDSExonRangesReverse(chromPos, CHROMOSOME); } private static List> getCDSExonRangesReverse(GeneChromosomePosition chromPos, String responseType) { @@ -657,56 +657,46 @@ private static List> getCDSExonRangesReverse(GeneChromosomePositi } - Range r ; - if ( responseType.equals(CDS)) - r = Range.closed(0,codingLength); - else - r = Range.closed(tmpstart,cdsEnd); - data.add(r); + data.add(responseType.equals(CDS) ? + Range.closed(0, codingLength) : + Range.closed(tmpstart, cdsEnd)); } else if (start <= cdsStart && end >= cdsStart) { inCoding = false; - Range r; - if ( responseType.equals(CDS)) - r = Range.closed(codingLength,codingLength+(end-cdsStart)); - else - r = Range.closed(cdsStart+1,end); - - data.add(r); + data.add(responseType.equals(CDS) ? + Range.closed(codingLength, codingLength + (end - cdsStart)) : + Range.closed(cdsStart + 1, end)); codingLength += (end - cdsStart); if (debug) { - s.append(" <- Exon : " + format(cdsStart + 1) + " - " + format(end) + " | " + (end - cdsStart) + " | " + codingLength + " | " + (codingLength % 3)); + s.append(" <- Exon : ").append(format(cdsStart + 1)).append(" - ").append(format(end)).append(" | ").append(end - cdsStart).append(" | ").append(codingLength).append(" | ").append(codingLength % 3); s.append(newline); s.append(" UTR : ").append(format(start + 1)).append(" - ").append(format(cdsStart)); s.append(newline); } } else if (inCoding) { // full exon is coding - Range r; - if ( responseType.equals(CDS)) - r = Range.closed(codingLength,codingLength+(end-start)); - else - r = Range.closed(start,end); - data.add(r); + data.add(responseType.equals(CDS) ? + Range.closed(codingLength, codingLength + (end - start)) : + Range.closed(start, end)); codingLength += (end - start); if (debug) { - s.append(" Exon : " + format(start + 1) + " - " + format(end) + " | " + (end - start) + " | " + codingLength + " | " + (codingLength % 3)); + s.append(" Exon : ").append(format(start + 1)).append(" - ").append(format(end)).append(" | ").append(end - start).append(" | ").append(codingLength).append(" | ").append(codingLength % 3); s.append(newline); } } else { // e.g. see UBQLN3 if ( debug ) { - s.append(" no translation! UTR: " + format(start) + " - " + format(end)); + s.append(" no translation! UTR: ").append(format(start)).append(" - ").append(format(end)); s.append(newline); } } } if ( debug ) { - s.append("CDS length: ").append(Integer.toString(codingLength - 3)); + s.append("CDS length: ").append((codingLength - 3)); s.append(newline); logger.debug(s.toString()); } @@ -736,33 +726,24 @@ private static List> getCDSExonRangesForward(GeneChromosomePositi inCoding = true; codingLength += (end - cdsStart); - Range r; - if ( responseType.equals(CDS)) - r = Range.closed(0,codingLength); - else - r = Range.closed(cdsStart,end); - data.add(r); + data.add(responseType.equals(CDS) ? + Range.closed(0, codingLength) : + Range.closed(cdsStart, end)); } else if (start <= cdsEnd && end >= cdsEnd) { //logger.debug(" <-- CDS end at: " + cdsEnd ); inCoding = false; - Range r; - if ( responseType.equals(CDS)) - r = Range.closed(codingLength,codingLength+(cdsEnd-start)); - else - r = Range.closed(start,cdsEnd); - data.add(r); + data.add(responseType.equals(CDS) ? + Range.closed(codingLength, codingLength + (cdsEnd - start)) : + Range.closed(start, cdsEnd)); codingLength += (cdsEnd - start); } else if (inCoding) { // full exon is coding - Range r; - if ( responseType.equals(CDS)) - r = Range.closed(codingLength,codingLength+(end-start)); - else - r = Range.closed(start,end); - data.add(r); + data.add(responseType.equals(CDS) ? + Range.closed(codingLength, codingLength + (end - start)) : + Range.closed(start, end)); codingLength += (end - start); } } @@ -773,23 +754,24 @@ private static List> getCDSExonRangesForward(GeneChromosomePositi * I have a genomic coordinate, where is it on the mRNA * * @param coordinate - * @param chromosomePosition + * @param p * @return */ - public static int getCDSPosForChromosomeCoordinate(int coordinate, GeneChromosomePosition chromosomePosition) { + public static int getCDSPosForChromosomeCoordinate(int coordinate, GeneChromosomePosition p, int base) { - if ( chromosomePosition.getOrientation() == '+') + if ( p.getOrientation() == '+') return getCDSPosForward(coordinate, - chromosomePosition.getExonStarts(), - chromosomePosition.getExonEnds(), - chromosomePosition.getCdsStart(), - chromosomePosition.getCdsEnd()); - - return getCDSPosReverse(coordinate, - chromosomePosition.getExonStarts(), - chromosomePosition.getExonEnds(), - chromosomePosition.getCdsStart(), - chromosomePosition.getCdsEnd()); + p.getExonStarts(), + p.getExonEnds(), + p.getCdsStart(), + p.getCdsEnd(), base); + + else + return getCDSPosReverse(coordinate, + p.getExonStarts(), + p.getExonEnds(), + p.getCdsStart(), + p.getCdsEnd(), base); } /** @@ -807,7 +789,7 @@ public static int getCDSPosForChromosomeCoordinate(int coordinate, GeneChromosom * @author Yana Valasatava */ public static int getCDSPosForward(int chromPos, List exonStarts, List exonEnds, - int cdsStart, int cdsEnd) { + int cdsStart, int cdsEnd, int base) { // the genetic coordinate is not in a coding region if ( (chromPos < (cdsStart+base) ) || ( chromPos > (cdsEnd+base) ) ) { @@ -821,7 +803,7 @@ public static int getCDSPosForward(int chromPos, List exonStarts, List< List> cdsRegions = getCDSRegions(exonStarts, exonEnds, cdsStart, cdsEnd); int codingLength = 0; - int lengthExon = 0; + int lengthExon; for (Range range : cdsRegions) { int start = range.lowerEndpoint(); @@ -854,7 +836,7 @@ public static int getCDSPosForward(int chromPos, List exonStarts, List< * @author Yana Valasatava */ public static int getCDSPosReverse(int chromPos, List exonStarts, List exonEnds, - int cdsStart, int cdsEnd) { + int cdsStart, int cdsEnd, int base) { // the genetic coordinate is not in a coding region if ( (chromPos < (cdsStart+base)) || ( chromPos > (cdsEnd+base) ) ) { @@ -868,7 +850,7 @@ public static int getCDSPosReverse(int chromPos, List exonStarts, List< List> cdsRegions = getCDSRegions(exonStarts, exonEnds, cdsStart, cdsEnd); int codingLength = 0; - int lengthExon = 0; + int lengthExon; for ( int i=cdsRegions.size()-1; i>=0; i-- ) { int start = cdsRegions.get(i).lowerEndpoint(); @@ -899,8 +881,8 @@ public static int getCDSPosReverse(int chromPos, List exonStarts, List< public static List> getCDSRegions(List origExonStarts, List origExonEnds, int cdsStart, int cdsEnd) { // remove exons that are fully landed in UTRs - List exonStarts = new ArrayList(origExonStarts); - List exonEnds = new ArrayList(origExonEnds); + List exonStarts = new ArrayList<>(origExonStarts); + List exonEnds = new ArrayList<>(origExonEnds); int j=0; for (int i = 0; i < origExonStarts.size(); i++) { @@ -920,7 +902,7 @@ public static List> getCDSRegions(List origExonStarts, L exonEnds.remove(nExons-1); exonEnds.add(cdsEnd); - List> cdsRegion = new ArrayList>(); + List> cdsRegion = new ArrayList<>(); for ( int i=0; i r = Range.closed(exonStarts.get(i), exonEnds.get(i)); cdsRegion.add(r); diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/util/ProteinMappingTools.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/util/ProteinMappingTools.java index 8fdb093c54..bff7888d08 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/util/ProteinMappingTools.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/util/ProteinMappingTools.java @@ -44,7 +44,7 @@ public static ProteinSequence convertDNAtoProteinSequence(String dnaSequence) th * * @return the protein sequence */ - public static ProteinSequence convertDNAtoProteinSequence(DNASequence dnaSequence) throws CompoundNotFoundException { + public static ProteinSequence convertDNAtoProteinSequence(DNASequence dnaSequence) { RNASequence mRNA = dnaSequence.getRNASequence(); return mRNA.getProteinSequence(); } diff --git a/biojava-genome/src/main/java/org/biojava/nbio/genome/util/SplitFasta.java b/biojava-genome/src/main/java/org/biojava/nbio/genome/util/SplitFasta.java index 4948a62c76..fa7a4f6dfb 100644 --- a/biojava-genome/src/main/java/org/biojava/nbio/genome/util/SplitFasta.java +++ b/biojava-genome/src/main/java/org/biojava/nbio/genome/util/SplitFasta.java @@ -40,7 +40,7 @@ public class SplitFasta { private static final Logger logger = LoggerFactory.getLogger(SplitFasta.class); - public void processNucleotides(File fastaFileName,String uniqueid, File outputDirectory ) throws Exception{ + public static void processNucleotides(File fastaFileName, String uniqueid, File outputDirectory) throws Exception{ if(!outputDirectory.exists()) outputDirectory.mkdirs(); @@ -52,7 +52,7 @@ public void processNucleotides(File fastaFileName,String uniqueid, File outputDi }else{ fileName = fileName + uniqueid + dnaSequence.getAccession().getID() + ".fna"; } - ArrayList dnaList = new ArrayList(); + ArrayList dnaList = new ArrayList<>(); dnaList.add(dnaSequence); FastaWriterHelper.writeNucleotideSequence(new File(fileName), dnaList); } @@ -61,8 +61,8 @@ public void processNucleotides(File fastaFileName,String uniqueid, File outputDi public static void main( String[] args ){ try{ - SplitFasta splitFasta = new SplitFasta(); - splitFasta.processNucleotides(new File("/Users/Scooter/scripps/dyadic/analysis/454Scaffolds/454Scaffolds.fna"), "", new File("/Users/Scooter/scripps/dyadic/analysis/454Scaffolds/individual")); +// SplitFasta splitFasta = new SplitFasta(); + SplitFasta.processNucleotides(new File("/Users/Scooter/scripps/dyadic/analysis/454Scaffolds/454Scaffolds.fna"), "", new File("/Users/Scooter/scripps/dyadic/analysis/454Scaffolds/individual")); }catch(Exception e){ logger.error("Exception: ", e); } diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/FeatureListTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/FeatureListTest.java index 6e1cae5d8b..ed554272ba 100644 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/FeatureListTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/FeatureListTest.java @@ -35,8 +35,7 @@ */ public class FeatureListTest { @Test - public void testAddIndex() throws Exception - { + public void testAddIndex() { FeatureList fl = new FeatureList(); fl.add(new Feature("seqname", "source", "type", new Location(1, 2), (double)0, 0, "gene_id \"gene_id_1\"; transcript_id \"transcript_id_1\";")); fl.addIndex("transcript_id"); diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/GeneFeatureHelperTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/GeneFeatureHelperTest.java index db4fa31328..bf710a01f0 100644 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/GeneFeatureHelperTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/GeneFeatureHelperTest.java @@ -21,13 +21,13 @@ package org.biojava.nbio.genome; import junitx.framework.FileAssert; -import org.biojava.nbio.genome.parsers.gff.FeatureList; -import org.biojava.nbio.genome.parsers.gff.GFF3Reader; -import org.biojava.nbio.genome.parsers.gff.GFF3Writer; import org.biojava.nbio.core.sequence.ChromosomeSequence; import org.biojava.nbio.core.sequence.GeneSequence; import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.io.FastaWriterHelper; +import org.biojava.nbio.genome.parsers.gff.FeatureList; +import org.biojava.nbio.genome.parsers.gff.GFF3Reader; +import org.biojava.nbio.genome.parsers.gff.GFF3Writer; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -48,11 +48,11 @@ public class GeneFeatureHelperTest { private static final Logger logger = LoggerFactory.getLogger(GeneFeatureHelperTest.class); @Before - public void setUp() throws Exception { + public void setUp() { } @After - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/TestChromosomeMappingTools.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/TestChromosomeMappingTools.java index 9ddd43357a..59facf95e7 100644 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/TestChromosomeMappingTools.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/TestChromosomeMappingTools.java @@ -43,8 +43,8 @@ public void testGetCDSLengthForward() { int cdsEnd = 75; int cdsDesired = 23 - 3; - ChromosomeMappingTools.setCoordinateSystem(0); - int cdsTest = ChromosomeMappingTools.getCDSLengthForward(exonStarts, exonEnds, cdsStart, cdsEnd); + + int cdsTest = ChromosomeMappingTools.getCDSLengthForward(exonStarts, exonEnds, cdsStart, cdsEnd, 0); assertEquals(cdsDesired, cdsTest); } @@ -58,8 +58,8 @@ public void testGetCDSLengthReverseAsc() { int cdsEnd = 75; int cdsDesired = 12 - 3; - ChromosomeMappingTools.setCoordinateSystem(0); - int cdsTest = ChromosomeMappingTools.getCDSLengthReverse(exonStarts, exonEnds, cdsStart, cdsEnd); + + int cdsTest = ChromosomeMappingTools.getCDSLengthReverse(exonStarts, exonEnds, cdsStart, cdsEnd, 0); assertEquals(cdsDesired, cdsTest); } @@ -73,8 +73,8 @@ public void testGetCDSLengthReverseDesc() { int cdsEnd = 50; int cdsDesired = 17 - 3; - ChromosomeMappingTools.setCoordinateSystem(0); - int cdsTest = ChromosomeMappingTools.getCDSLengthReverse(exonStarts, exonEnds, cdsStart, cdsEnd); + + int cdsTest = ChromosomeMappingTools.getCDSLengthReverse(exonStarts, exonEnds, cdsStart, cdsEnd, 0); assertEquals(cdsDesired, cdsTest); } diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/TestGenomeMapping.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/TestGenomeMapping.java index 8a19d041e4..b4859b722d 100644 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/TestGenomeMapping.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/TestGenomeMapping.java @@ -22,19 +22,18 @@ import com.google.common.collect.Lists; import com.google.common.collect.Range; +import org.biojava.nbio.core.util.Download; import org.biojava.nbio.genome.parsers.genename.GeneChromosomePosition; import org.biojava.nbio.genome.parsers.genename.GeneChromosomePositionParser; import org.biojava.nbio.genome.util.ChromosomeMappingTools; import org.junit.Assert; -import org.junit.Before; import org.junit.Test; -import java.io.InputStream; +import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.zip.GZIPInputStream; /** * Created by andreas on 7/19/16. @@ -43,14 +42,24 @@ public class TestGenomeMapping { private static final String geneChromosomeFile = "http://cdn.rcsb.org/gene/hg38/geneChromosome38.tsf.gz"; - private List gcps = null; + private static final List gcps; - @Before - public void setUp() throws Exception { - InputStream input = new GZIPInputStream(new URL(geneChromosomeFile).openStream()); - gcps = GeneChromosomePositionParser.getChromosomeMappings(input); + static { + List g; + try { + g = GeneChromosomePositionParser.getChromosomeMappings( Download.stream(new URL(geneChromosomeFile)) ); + } catch (IOException e) { + e.printStackTrace(); + g = null; + } + gcps = g; } +// @Before +// public void setUp() throws Exception { +// +// } + @Test public void testAK1() { String geneName = "AK1"; @@ -74,9 +83,9 @@ public void testAK1() { if ( ! pos.getGenebankId().equals("NM_000476")) continue; - Assert.assertTrue(pos.getGeneName().equals(geneName)); - Assert.assertTrue(pos.getOrientation().equals('-')); - Assert.assertTrue(pos.getChromosome().equals("chr9")); + Assert.assertEquals(pos.getGeneName(), geneName); + Assert.assertEquals('-', (char) pos.getOrientation()); + Assert.assertEquals("chr9", pos.getChromosome()); List> cdsranges = ChromosomeMappingTools.getCDSExonRanges(pos); @@ -88,16 +97,16 @@ public void testAK1() { validateExon(5,516,585, cdsranges ); - int cdslength = ChromosomeMappingTools.getCDSLength(pos); + int cdslength = ChromosomeMappingTools.getCDSLength(pos, 1); - Assert.assertTrue("CDS length should be 582, but is " + cdslength, cdslength == (uniProtLength * 3)); + Assert.assertEquals("CDS length should be 582, but is " + cdslength, cdslength, (uniProtLength * 3)); List> chromranges = ChromosomeMappingTools.getChromosomalRangesForCDS(pos); // we are reverse strand. reverse the order chromranges = Lists.reverse(chromranges); - Assert.assertTrue(chromranges.size() == 6); + Assert.assertEquals(6, chromranges.size()); // compare with https://www.ncbi.nlm.nih.gov/CCDS/CcdsBrowse.cgi?REQUEST=CCDS&DATA=CCDS6881 validateExon(0,127868008,127868076, chromranges ); @@ -129,16 +138,16 @@ public void testHBA(){ if ( ! pos.getGeneName().equals(geneName)) continue; - Assert.assertTrue(pos.getGeneName().equals("HBA1")); - Assert.assertTrue(pos.getGenebankId().equals("NM_000558")); - Assert.assertTrue(pos.getChromosome().equals("chr16")); - Assert.assertTrue(pos.getTranscriptionStart().equals(176650)); - Assert.assertTrue(pos.getTranscriptionEnd().equals(177522)); - Assert.assertTrue(pos.getOrientation().equals('+')); + Assert.assertEquals("HBA1", pos.getGeneName()); + Assert.assertEquals("NM_000558", pos.getGenebankId()); + Assert.assertEquals("chr16", pos.getChromosome()); + Assert.assertEquals(176650, (int) pos.getTranscriptionStart()); + Assert.assertEquals(177522, (int) pos.getTranscriptionEnd()); + Assert.assertEquals('+', (char) pos.getOrientation()); List> cdsranges = ChromosomeMappingTools.getCDSExonRanges(pos); - Assert.assertTrue(cdsranges.size() == 3); + Assert.assertEquals(3, cdsranges.size()); validateExon(0,0,95,cdsranges); validateExon(1,95,300,cdsranges); @@ -163,8 +172,8 @@ public void testHBA(){ private void validateExon(int exonNr, int start, int stop, List> cdsranges) { Range exon = cdsranges.get(exonNr); - Assert.assertTrue("Exon " + exonNr + " boundary " + exon.lowerEndpoint() + " does not match " + start, exon.lowerEndpoint().equals(start)); - Assert.assertTrue("Exon " + exonNr + " boundary " + exon.upperEndpoint() + " does not match " + stop, exon.upperEndpoint().equals(stop)); + Assert.assertEquals("Exon " + exonNr + " boundary " + exon.lowerEndpoint() + " does not match " + start, (int) exon.lowerEndpoint(), start); + Assert.assertEquals("Exon " + exonNr + " boundary " + exon.upperEndpoint() + " does not match " + stop, (int) exon.upperEndpoint(), stop); } @@ -173,16 +182,19 @@ private void validateExon(int exonNr, int start, int stop, List> * * @author Yana Valasatava */ - private int getPositionInmRNA(String geneName, String genebankId, int posChrom) { + private int getPositionInmRNA(String geneName, String genebankId, int posChrom, int base) { for (GeneChromosomePosition gcp : gcps) { if ( gcp.getGeneName().equals(geneName) ) { if ( gcp.getGenebankId().equals(genebankId) ) { - return ChromosomeMappingTools.getCDSPosForChromosomeCoordinate(posChrom, gcp); + return ChromosomeMappingTools.getCDSPosForChromosomeCoordinate(posChrom, gcp, base); } } } return -1; } + private int getPositionInmRNA(String geneName, String genebankId, int posChrom) { + return getPositionInmRNA(geneName, genebankId, posChrom, 1); + } /** Make sure the mapping tool correctly retrieves the mRNA position for a gene * living on the forward DNA strand for different chromosome positions. @@ -336,39 +348,39 @@ public void testMappingCromosomePosTomRNAMultiUTRs() { @Test public void testGenomeMappingToolGetCDSRanges(){ - List lst1 = new ArrayList<>(Arrays.asList( new Integer[]{86346823, 86352858, 86354529})); - List lst2 = new ArrayList<>(Arrays.asList(new Integer[]{86348878, 86352984, 86354692})); + List lst1 = new ArrayList<>(Arrays.asList(86346823, 86352858, 86354529)); + List lst2 = new ArrayList<>(Arrays.asList(86348878, 86352984, 86354692)); - Integer cdsStart=86348749, cdsEnd=86387027; + int cdsStart=86348749, cdsEnd=86387027; List> result = ChromosomeMappingTools.getCDSRegions(lst1,lst2,cdsStart,cdsEnd); // makes sure the first list does not get changed; - Assert.assertTrue(lst1.get(0) == 86346823); + Assert.assertEquals(86346823, (int) lst1.get(0)); - Assert.assertTrue(result.get(0).lowerEndpoint() == 86348749); - Assert.assertTrue(result.get(1).lowerEndpoint() == 86352858); - Assert.assertTrue(result.get(2).lowerEndpoint() == 86354529); + Assert.assertEquals(86348749, (int) result.get(0).lowerEndpoint()); + Assert.assertEquals(86352858, (int) result.get(1).lowerEndpoint()); + Assert.assertEquals(86354529, (int) result.get(2).lowerEndpoint()); - Assert.assertTrue(result.get(0).upperEndpoint() == 86348878); - Assert.assertTrue(result.get(1).upperEndpoint() == 86352984); - Assert.assertTrue(result.get(2).upperEndpoint() == 86387027); + Assert.assertEquals(86348878, (int) result.get(0).upperEndpoint()); + Assert.assertEquals(86352984, (int) result.get(1).upperEndpoint()); + Assert.assertEquals(86387027, (int) result.get(2).upperEndpoint()); } @Test public void testGenomeMappingToolGetCDSRangesSERINC2(){ - List lst1 = new ArrayList<>(Arrays.asList( new Integer[]{31413812, 31415872, 31423692})); - List lst2 = new ArrayList<>(Arrays.asList(new Integer[]{31414777, 31415907, 31423854})); + List lst1 = new ArrayList<>(Arrays.asList(31413812, 31415872, 31423692)); + List lst2 = new ArrayList<>(Arrays.asList(31414777, 31415907, 31423854)); - Integer cdsStart=31423818, cdsEnd=31434199; + int cdsStart=31423818, cdsEnd=31434199; List> result = ChromosomeMappingTools.getCDSRegions(lst1,lst2,cdsStart,cdsEnd); // makes sure the first list does not get changed; - Assert.assertTrue(result.get(0).lowerEndpoint() == 31423818); + Assert.assertEquals(31423818, (int) result.get(0).lowerEndpoint()); } } diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/TestIssue355.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/TestIssue355.java index 5543682f17..3691555999 100644 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/TestIssue355.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/TestIssue355.java @@ -20,11 +20,12 @@ */ package org.biojava.nbio.genome; -import static org.junit.Assert.*; - import org.biojava.nbio.genome.parsers.gff.Location; import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + public class TestIssue355 { @Test diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/TestLocation.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/TestLocation.java index 1289cb757e..2153db9843 100644 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/TestLocation.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/TestLocation.java @@ -20,11 +20,11 @@ */ package org.biojava.nbio.genome; -import static org.junit.Assert.*; - import org.biojava.nbio.genome.parsers.gff.Location; import org.junit.Test; +import static org.junit.Assert.*; + public class TestLocation { @Test @@ -64,11 +64,11 @@ public void testLocation() { //isBefore assertTrue( r2_5.isBefore( r5_8 )); - assertTrue( !r2_5.isBefore( r4_7 )); + assertFalse(r2_5.isBefore(r4_7)); //isAfter assertTrue(r5_8.isAfter( r2_5 )); - assertTrue(!r5_8.isAfter( r4_7 )); + assertFalse(r5_8.isAfter(r4_7)); //contains assertTrue(p15_19.contains( p16_19 )); @@ -76,8 +76,8 @@ public void testLocation() { //overlaps assertTrue(r2_5.overlaps( r4_7 )); assertTrue(r2_5.overlaps( r0_3 )); - assertTrue(!r5_8.overlaps( r2_5 )); - assertTrue(!r2_5.overlaps( r5_8 )); + assertFalse(r5_8.overlaps(r2_5)); + assertFalse(r2_5.overlaps(r5_8)); //prefix diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/AbstractFastqReaderTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/AbstractFastqReaderTest.java index 6dbfbe968c..c87079a1da 100755 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/AbstractFastqReaderTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/AbstractFastqReaderTest.java @@ -312,35 +312,17 @@ public void testMultipleWrappedQuality() throws Exception } @Test - public void testErrorExamples() throws Exception - { + public void testErrorExamples() { FastqReader reader = createFastqReader(); for (String errorExample : ERROR_EXAMPLES) { - InputStream inputStream = getClass().getResourceAsStream(errorExample); - try - { + try (InputStream inputStream = getClass().getResourceAsStream(errorExample)) { reader.read(inputStream); Assert.fail("error example " + errorExample + " expected IOException"); - } - catch (IOException e) - { + } catch (IOException e) { // expected } - finally - { - if (inputStream != null) - { - try - { - inputStream.close(); - } - catch (IOException e) - { - // ignore - } - } - } + // ignore } } @@ -351,37 +333,37 @@ public void testParse() throws Exception final String input = ""; reader.parse(new StringReader(input), new ParseListener() { @Override - public void description(final String description) throws IOException { + public void description(final String description) { // empty } @Override - public void sequence(final String sequence) throws IOException { + public void sequence(final String sequence) { // empty } @Override - public void appendSequence(final String sequence) throws IOException { + public void appendSequence(final String sequence) { // empty } @Override - public void repeatDescription(final String repeatDescription) throws IOException { + public void repeatDescription(final String repeatDescription) { // empty } @Override - public void quality(final String quality) throws IOException { + public void quality(final String quality) { // empty } @Override - public void appendQuality(final String quality) throws IOException { + public void appendQuality(final String quality) { // empty } @Override - public void complete() throws IOException { + public void complete() { // empty } }); @@ -393,39 +375,39 @@ public void testParseNullReadable() throws Exception FastqReader reader = createFastqReader(); try { - reader.parse((Readable) null, new ParseListener() { + reader.parse(null, new ParseListener() { @Override - public void description(final String description) throws IOException { + public void description(final String description) { // empty } @Override - public void sequence(final String sequence) throws IOException { + public void sequence(final String sequence) { // empty } @Override - public void appendSequence(final String sequence) throws IOException { + public void appendSequence(final String sequence) { // empty } @Override - public void repeatDescription(final String repeatDescription) throws IOException { + public void repeatDescription(final String repeatDescription) { // empty } @Override - public void quality(final String quality) throws IOException { + public void quality(final String quality) { // empty } @Override - public void appendQuality(final String quality) throws IOException { + public void appendQuality(final String quality) { // empty } @Override - public void complete() throws IOException { + public void complete() { // empty } }); diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/AbstractFastqWriterTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/AbstractFastqWriterTest.java index b2596dd51b..b3f39fa927 100755 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/AbstractFastqWriterTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/AbstractFastqWriterTest.java @@ -79,7 +79,7 @@ public void testAppendVararg() throws Exception try { - writer.append((Appendable) null, fastq0); + writer.append(null, fastq0); Assert.fail("append(null,) expected IllegalArgumentException"); } catch (IllegalArgumentException e) @@ -96,7 +96,7 @@ public void testAppendIterable() throws Exception Fastq fastq0 = createFastq(); Fastq fastq1 = createFastq(); Fastq fastq2 = createFastq(); - List list = new ArrayList(); + List list = new ArrayList<>(); Assert.assertSame(appendable, writer.append(appendable, list)); list.add(fastq0); Assert.assertSame(appendable, writer.append(appendable, list)); @@ -109,7 +109,7 @@ public void testAppendIterable() throws Exception try { - writer.append((Appendable) null, list); + writer.append(null, list); Assert.fail("append(null,) expected IllegalArgumentException"); } catch (IllegalArgumentException e) @@ -163,7 +163,7 @@ public void testWriteFileIterable() throws Exception Fastq fastq0 = createFastq(); Fastq fastq1 = createFastq(); Fastq fastq2 = createFastq(); - List list = new ArrayList(); + List list = new ArrayList<>(); File file0 = File.createTempFile("abstractFastqWriterTest", null); writer.write(file0, list); @@ -238,7 +238,7 @@ public void testWriteOutputStreamIterable() throws Exception Fastq fastq1 = createFastq(); Fastq fastq2 = createFastq(); OutputStream outputStream = new ByteArrayOutputStream(); - List list = new ArrayList(); + List list = new ArrayList<>(); writer.write(outputStream, list); list.add(fastq0); writer.write(outputStream, list); diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/ConvertTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/ConvertTest.java index 0c6775a659..aa32f8b7de 100644 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/ConvertTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/ConvertTest.java @@ -20,16 +20,16 @@ */ package org.biojava.nbio.genome.io.fastq; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import org.junit.Test; + import java.io.File; import java.io.FileWriter; import java.util.List; import java.util.Map; -import org.junit.Test; -import static org.junit.Assert.*; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; +import static org.junit.Assert.assertEquals; /** * Round trip conversion functional tests. @@ -99,7 +99,7 @@ public void testConvert() throws Exception } } - private final class FastqVariantPair + private static final class FastqVariantPair { final FastqVariant variant1; final FastqVariant variant2; diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqBuilderTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqBuilderTest.java index b013e996d2..e2af4e776d 100755 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqBuilderTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqBuilderTest.java @@ -316,7 +316,7 @@ public void testBuildNonMatchingSequenceQualityScoreLengthsSequenceNull() .withQuality("0123") .withVariant(FastqVariant.FASTQ_SOLEXA); - Assert.assertEquals(false, fastqBuilder.sequenceAndQualityLengthsMatch()); + Assert.assertFalse(fastqBuilder.sequenceAndQualityLengthsMatch()); } @Test @@ -327,7 +327,7 @@ public void testBuildNonMatchingSequenceQualityScoreLengthsQualityNull() .withSequence("ACTG") .withVariant(FastqVariant.FASTQ_SOLEXA); - Assert.assertEquals(false, fastqBuilder.sequenceAndQualityLengthsMatch()); + Assert.assertFalse(fastqBuilder.sequenceAndQualityLengthsMatch()); } @Test diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqTest.java index b6fc3c98b0..d3454718e2 100755 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqTest.java @@ -77,7 +77,7 @@ public void testConstructor() public void testDescription() { Fastq fastq = new Fastq("description", "sequence", "quality_", FastqVariant.FASTQ_SANGER); - Assert.assertTrue(fastq.getDescription() != null); + Assert.assertNotNull(fastq.getDescription()); Assert.assertEquals("description", fastq.getDescription()); } @@ -85,7 +85,7 @@ public void testDescription() public void testSequence() { Fastq fastq = new Fastq("description", "sequence", "quality_", FastqVariant.FASTQ_SANGER); - Assert.assertTrue(fastq.getSequence() != null); + Assert.assertNotNull(fastq.getSequence()); Assert.assertEquals("sequence", fastq.getSequence()); } @@ -93,7 +93,7 @@ public void testSequence() public void testQuality() { Fastq fastq = new Fastq("description", "sequence", "quality_", FastqVariant.FASTQ_SANGER); - Assert.assertTrue(fastq.getQuality() != null); + Assert.assertNotNull(fastq.getQuality()); Assert.assertEquals("quality_", fastq.getQuality()); } @@ -101,7 +101,7 @@ public void testQuality() public void testVariant() { Fastq fastq = new Fastq("description", "sequence", "quality_", FastqVariant.FASTQ_SANGER); - Assert.assertTrue(fastq.getVariant() != null); + Assert.assertNotNull(fastq.getVariant()); Assert.assertEquals(FastqVariant.FASTQ_SANGER, fastq.getVariant()); } @@ -117,15 +117,15 @@ public void testEquals() Fastq fastq0 = new Fastq("description", "sequence", "quality_", FastqVariant.FASTQ_SANGER); Fastq fastq1 = new Fastq("description", "sequence", "quality_", FastqVariant.FASTQ_SANGER); - Assert.assertFalse(fastq0.equals(null)); - Assert.assertFalse(fastq1.equals(null)); - Assert.assertFalse(fastq0.equals(new Object())); - Assert.assertFalse(fastq1.equals(new Object())); - Assert.assertTrue(fastq0.equals(fastq0)); - Assert.assertTrue(fastq1.equals(fastq1)); - Assert.assertFalse(fastq0 == fastq1); - Assert.assertFalse(fastq0.equals(fastq1)); - Assert.assertFalse(fastq1.equals(fastq0)); + Assert.assertNotEquals(null, fastq0); + Assert.assertNotEquals(null, fastq1); + Assert.assertNotEquals(fastq0, new Object()); + Assert.assertNotEquals(fastq1, new Object()); + Assert.assertEquals(fastq0, fastq0); + Assert.assertEquals(fastq1, fastq1); + Assert.assertNotSame(fastq0, fastq1); + Assert.assertNotEquals(fastq0, fastq1); + Assert.assertNotEquals(fastq1, fastq0); } @Test diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqToolsTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqToolsTest.java index 469601e624..6aca0fda15 100644 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqToolsTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqToolsTest.java @@ -30,7 +30,6 @@ import org.junit.Assert; import org.junit.Test; - import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; @@ -505,14 +504,14 @@ public void testConvertQualitiesIlluminaToSolexa() @Test public void testToList() { - List list = new ArrayList(); + List list = new ArrayList<>(); Assert.assertSame(list, FastqTools.toList(list)); } @Test public void testToListNotAList() { - Collection collection = new HashSet(); + Collection collection = new HashSet<>(); Assert.assertTrue(FastqTools.toList(collection) instanceof List); Assert.assertNotSame(collection, FastqTools.toList(collection)); } diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqVariantTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqVariantTest.java index f8b0855a8e..af7a33f79f 100755 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqVariantTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/FastqVariantTest.java @@ -20,11 +20,11 @@ */ package org.biojava.nbio.genome.io.fastq; -import static org.biojava.nbio.genome.io.fastq.FastqVariant.*; - import org.junit.Assert; import org.junit.Test; +import static org.biojava.nbio.genome.io.fastq.FastqVariant.*; + /** * Unit test for FastqVariant. */ @@ -66,9 +66,9 @@ public void testIsIllumina() @Test public void testParseFastqVariant() { - Assert.assertEquals(null, parseFastqVariant(null)); - Assert.assertEquals(null, parseFastqVariant("")); - Assert.assertEquals(null, parseFastqVariant("not a valid FASTQ variant")); + Assert.assertNull(parseFastqVariant(null)); + Assert.assertNull(parseFastqVariant("")); + Assert.assertNull(parseFastqVariant("not a valid FASTQ variant")); Assert.assertEquals(FASTQ_SANGER, parseFastqVariant("FASTQ_SANGER")); Assert.assertEquals(FASTQ_SANGER, parseFastqVariant("fastq-sanger")); } diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/IlluminaFastqReaderTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/IlluminaFastqReaderTest.java index d7b0a8b9d2..54fd055615 100755 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/IlluminaFastqReaderTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/IlluminaFastqReaderTest.java @@ -21,12 +21,13 @@ package org.biojava.nbio.genome.io.fastq; import org.junit.Test; -import static org.junit.Assert.*; import java.io.IOException; import java.io.InputStream; import java.net.URL; +import static org.junit.Assert.*; + /** * Unit test for IlluminaFastqReader. @@ -59,8 +60,7 @@ public FastqWriter createFastqWriter() } @Test - public void testValidateDescription() throws Exception - { + public void testValidateDescription() { IlluminaFastqReader reader = new IlluminaFastqReader(); URL invalidDescription = getClass().getResource("illumina-invalid-description.fastq"); try @@ -75,8 +75,7 @@ public void testValidateDescription() throws Exception } @Test - public void testValidateRepeatDescription() throws Exception - { + public void testValidateRepeatDescription() { IlluminaFastqReader reader = new IlluminaFastqReader(); URL invalidRepeatDescription = getClass().getResource("illumina-invalid-repeat-description.fastq"); try diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/SangerFastqReaderTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/SangerFastqReaderTest.java index af6f67319f..e5d66dbc80 100755 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/SangerFastqReaderTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/SangerFastqReaderTest.java @@ -58,8 +58,7 @@ public FastqWriter createFastqWriter() return new SangerFastqWriter(); } - public void testValidateDescription() throws Exception - { + public void testValidateDescription() { SangerFastqReader reader = new SangerFastqReader(); URL invalidDescription = getClass().getResource("sanger-invalid-description.fastq"); try @@ -74,8 +73,7 @@ public void testValidateDescription() throws Exception } @Test - public void testValidateRepeatDescription() throws Exception - { + public void testValidateRepeatDescription() { SangerFastqReader reader = new SangerFastqReader(); URL invalidRepeatDescription = getClass().getResource("sanger-invalid-repeat-description.fastq"); try diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/SolexaFastqReaderTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/SolexaFastqReaderTest.java index 5f6f041c84..25909e97dd 100755 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/SolexaFastqReaderTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/SolexaFastqReaderTest.java @@ -60,8 +60,7 @@ public FastqWriter createFastqWriter() } @Test - public void testValidateDescription() throws Exception - { + public void testValidateDescription() { SolexaFastqReader reader = new SolexaFastqReader(); URL invalidDescription = getClass().getResource("solexa-invalid-description.fastq"); try @@ -76,8 +75,7 @@ public void testValidateDescription() throws Exception } @Test - public void testValidateRepeatDescription() throws Exception - { + public void testValidateRepeatDescription() { SolexaFastqReader reader = new SolexaFastqReader(); URL invalidRepeatDescription = getClass().getResource("solexa-invalid-repeat-description.fastq"); try diff --git a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/StreamingFastqParserTest.java b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/StreamingFastqParserTest.java index a80f44a43d..6818977adb 100644 --- a/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/StreamingFastqParserTest.java +++ b/biojava-genome/src/test/java/org/biojava/nbio/genome/io/fastq/StreamingFastqParserTest.java @@ -36,11 +36,8 @@ public void testStreamNullReadable() throws Exception { try { - StreamingFastqParser.stream((Readable) null, FastqVariant.FASTQ_SANGER, new StreamListener() { - @Override - public void fastq(final Fastq fastq) { - // empty - } + StreamingFastqParser.stream(null, FastqVariant.FASTQ_SANGER, fastq -> { + // empty }); Assert.fail("stream(null,,) expected IllegalArgumentException"); } @@ -56,11 +53,8 @@ public void testStreamNullVariant() throws Exception try { final String input = ""; - StreamingFastqParser.stream(new StringReader(input), null, new StreamListener() { - @Override - public void fastq(final Fastq fastq) { - // empty - } + StreamingFastqParser.stream(new StringReader(input), null, fastq -> { + // empty }); Assert.fail("stream(null,,) expected IllegalArgumentException"); } diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/MMcifTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/MMcifTest.java index 4947e0077a..284533d954 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/MMcifTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/MMcifTest.java @@ -28,7 +28,6 @@ import org.biojava.nbio.structure.io.mmcif.SimpleMMcifConsumer; import org.biojava.nbio.structure.io.mmcif.SimpleMMcifParser; import org.junit.Test; -import static org.junit.Assert.*; import java.io.BufferedReader; import java.io.IOException; @@ -36,6 +35,8 @@ import java.io.InputStreamReader; import java.util.List; +import static org.junit.Assert.*; + public class MMcifTest { private static boolean headerOnly; @@ -106,7 +107,7 @@ private void comparePDB2cif(String id, String chainId) throws IOException { // load the PDB file via the PDB parser - Structure pdbStructure = null; + Structure pdbStructure; InputStream pinStream = this.getClass().getResourceAsStream("/"+id+".pdb"); assertNotNull(inStream); diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/PDBFileParserTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/PDBFileParserTest.java index 7bc3c2846d..9256483e15 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/PDBFileParserTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/PDBFileParserTest.java @@ -24,20 +24,7 @@ */ package org.biojava.nbio.structure.test; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.ChainImpl; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.JournalArticle; -import org.biojava.nbio.structure.PDBHeader; -import org.biojava.nbio.structure.Site; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.FileParsingParameters; import org.biojava.nbio.structure.io.PDBFileParser; @@ -45,6 +32,11 @@ import org.junit.Before; import org.junit.Test; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; + import static org.junit.Assert.*; /** @@ -108,7 +100,7 @@ public void testCorrectFloatingPointDisplay() throws IOException { Structure s = parser.parsePDBFile(br); String pdb = s.toPDB(); - assertTrue("the created PDB file does not match the input file", pdb.equals(t)); + assertEquals("the created PDB file does not match the input file", pdb, t); } @@ -304,7 +296,7 @@ public void testSITE() throws IOException { // System.out.println("Got:"); // System.out.println(remark800.toString()); } - assertTrue("the created PDB REMARK800 section does not match the input file", remark800.toString().equals(remark800Test)); + assertEquals("the created PDB REMARK800 section does not match the input file", remark800.toString(), remark800Test); if (!sites.toString().equals(sitesTest)) { System.out.println("Expected:"); @@ -331,7 +323,7 @@ public void testMultiLineJRNL() throws IOException { BufferedReader br = new BufferedReader(new StringReader(jrnlString)); - Structure s = null; + Structure s; s = parser.parsePDBFile(br); @@ -357,7 +349,7 @@ public void testIncorrectDateFormatMultiLineJRNL() throws IOException{ BufferedReader br = new BufferedReader(new StringReader(jrnlString)); - Structure s = null; + Structure s; s = parser.parsePDBFile(br); // String jrnl = s.getJournalArticle().toString(); // System.out.println(jrnl); @@ -380,7 +372,7 @@ public void testInvalidFormatREFsectionJRNL() throws IOException{ BufferedReader br = new BufferedReader(new StringReader(jrnlString)); - Structure s = null; + Structure s; s = parser.parsePDBFile(br); // String jrnl = s.getJournalArticle().toString(); // System.out.println(jrnl); @@ -406,7 +398,7 @@ public void testSecondMultiLineJRNL() throws IOException{ BufferedReader br = new BufferedReader(new StringReader(jrnlString)); - Structure s = null; + Structure s; s = parser.parsePDBFile(br); // String jrnl = s.getJournalArticle().toString(); // System.out.println(jrnl); @@ -433,7 +425,7 @@ public void testSingleLineJRNL() throws IOException{ BufferedReader br = new BufferedReader(new StringReader(jrnlString)); - Structure s = null; + Structure s; s = parser.parsePDBFile(br); // String jrnl = s.getJournalArticle().toString(); // System.out.println(jrnl); @@ -459,7 +451,7 @@ public void testToBePublishedJRNL() throws IOException{ BufferedReader br = new BufferedReader(new StringReader(jrnlString)); - Structure s = null; + Structure s; s = parser.parsePDBFile(br); JournalArticle journalArticle = s.getJournalArticle(); @@ -552,7 +544,7 @@ public void testCorrectAtomNamePadding() throws IOException { String pdb = s.toPDB(); - assertTrue("the created PDB file does not match the input file", pdb.equals(atomLines)); + assertEquals("the created PDB file does not match the input file", pdb, atomLines); } @@ -619,13 +611,13 @@ public void testMissingElements() throws IOException { BufferedReader br = new BufferedReader(new StringReader(missingElement)); Structure s = parser.parsePDBFile(br); String pdb = s.toPDB(); - assertTrue("the Element column has not been filled correctly", pdb.equals(original)); + assertEquals("the Element column has not been filled correctly", pdb, original); br = new BufferedReader(new StringReader(emptyElement)); s = parser.parsePDBFile(br); pdb = s.toPDB(); - assertTrue("the Element column has not been filled correctly", pdb.equals(original)); + assertEquals("the Element column has not been filled correctly", pdb, original); } diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/StructureTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/StructureTest.java index 15198acbfa..d13c3c2bf5 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/StructureTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/StructureTest.java @@ -25,16 +25,15 @@ import org.biojava.nbio.structure.io.FileParsingParameters; import org.biojava.nbio.structure.io.PDBFileParser; import org.biojava.nbio.structure.io.SSBondImpl; +import org.junit.BeforeClass; +import org.junit.Test; + +import javax.vecmath.Matrix4d; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Set; -import javax.vecmath.Matrix4d; - -import org.junit.BeforeClass; -import org.junit.Test; - import static org.junit.Assert.*; /** @@ -98,10 +97,9 @@ public void testSeqResParsing() { /** * Tests if a PDB file can be parsed - * @throws Exception */ @Test - public void testReadPDBFile() throws Exception { + public void testReadPDBFile() { assertEquals("pdb code not set!","5PTI",structure.getPDBCode()); @@ -126,7 +124,7 @@ public void testReadPDBFile() throws Exception { } @Test - public void testSSBondParsing() throws Exception { + public void testSSBondParsing() { assertNotNull(structure); List ssbonds = structure.getSSBonds(); @@ -164,16 +162,15 @@ private void assertDisulfideBond(String expectedChainId1, String expectedChainId /** * Tests that standard amino acids are working properly - * @throws Exception */ @Test - public void testStandardAmino() throws Exception { + public void testStandardAmino() { AminoAcid arg = StandardAminoAcid.getAminoAcid("ARG"); - assertTrue(arg.size() == 11 ); + assertEquals(11, arg.size()); AminoAcid gly = StandardAminoAcid.getAminoAcid("G"); - assertTrue(gly.size() == 4); + assertEquals(4, gly.size()); } @@ -182,7 +179,7 @@ public void testPDBHeader(){ PDBHeader header = structure.getPDBHeader(); String classification = header.getClassification(); - assertTrue(classification.equals("PROTEINASE INHIBITOR (TRYPSIN)")); + assertEquals("PROTEINASE INHIBITOR (TRYPSIN)", classification); String idCode = header.getIdCode(); assertEquals("the idCode in the Header is " + idCode + " and not 5PTI, as expected","5PTI",idCode); @@ -208,7 +205,7 @@ public void testPDBHeader(){ //assertEquals("did not find the right number of compounds! ", 2, compounds.size()); EntityInfo comp = compounds.get(0); - assertEquals("did not get the right compounds info",true,comp.getDescription().startsWith("TRYPSIN INHIBITOR")); + assertTrue("did not get the right compounds info", comp.getDescription().startsWith("TRYPSIN INHIBITOR")); List chainIds = comp.getChainIds(); List chains = comp.getChains(); @@ -224,12 +221,11 @@ public void testCreateVirtualCBAtom(){ if ( g1.getPDBName().equals("GLY")){ if ( g1 instanceof AminoAcid){ - try { - Atom cb = Calc.createVirtualCBAtom((AminoAcid)g1); - g1.addAtom(cb); - } catch (StructureException e){ - fail ("createVirtualCBAtom failed with " + e.getMessage()); - } +// try { + g1.addAtom(Calc.createVirtualCBAtom((AminoAcid)g1)); +// } catch (StructureException e){ +// fail ("createVirtualCBAtom failed with " + e.getMessage()); +// } } } else { fail("the group at position 11 is not a GLY!"); @@ -237,14 +233,14 @@ public void testCreateVirtualCBAtom(){ } @Test - public void testMutation() throws Exception { + public void testMutation() { Group g1 = (Group)structure.getChainByIndex(0).getAtomGroup(21).clone(); - assertTrue(g1 != null); + assertNotNull(g1); Group g2 = (Group)structure.getChainByIndex(0).getAtomGroup(53).clone(); - assertTrue(g2 != null); + assertNotNull(g2); assertEquals("The group at position 22 is not a PHE","PHE", g1.getPDBName()); @@ -292,13 +288,13 @@ public void testMutation() throws Exception { } @Test - public void testElement() throws Exception { + public void testElement() { // there should be no wild card elements // in a structure (!= Element.R) for (Chain c: structure.getChains()) { for (Group g: c.getAtomGroups()) { for (Atom a: g.getAtoms()) { - assertFalse(a.getElement().equals(Element.R)); + assertNotEquals(a.getElement(), Element.R); } } } diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/StructureToolsTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/StructureToolsTest.java index b2ae39611c..337c8900cb 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/StructureToolsTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/StructureToolsTest.java @@ -35,8 +35,9 @@ import java.io.IOException; import java.io.InputStream; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assume.assumeNoException; -import static org.junit.Assert.*; public class StructureToolsTest { diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/Test1a4w.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/Test1a4w.java index 870c74a13a..5a67cbf67f 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/Test1a4w.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/Test1a4w.java @@ -82,7 +82,7 @@ public void test1a4wPDBFile() throws IOException - Structure structure2 = null; + Structure structure2; InputStream inStream = this.getClass().getResourceAsStream("/1a4w.cif"); Assert.assertNotNull(inStream); @@ -132,15 +132,15 @@ private void testStructure(Structure structure){ //System.out.println(structure); Assert.assertTrue("chain " + a.getName() + " length should be 26. was: " + a.getAtomGroups(GroupType.AMINOACID).size(), (a.getAtomGroups(GroupType.AMINOACID).size() == 26)); - Assert.assertTrue("chain " + a.getName() + " seqres length should be 36. was: " + a.getSeqResLength(), a.getSeqResLength() == 36); + Assert.assertEquals("chain " + a.getName() + " seqres length should be 36. was: " + a.getSeqResLength(), 36, a.getSeqResLength()); Assert.assertTrue("chain " + b.getName() + " length should be 248. was: " + b.getAtomGroups(GroupType.AMINOACID).size(), (b.getAtomGroups(GroupType.AMINOACID).size() == 248)); - Assert.assertTrue("chain " + b.getName() + " seqres length should be 259. was: " + b.getSeqResLength(), b.getSeqResLength() == 259); + Assert.assertEquals("chain " + b.getName() + " seqres length should be 259. was: " + b.getSeqResLength(), 259, b.getSeqResLength()); Assert.assertTrue("chain " + c.getName() + " length should be 9. was: " + c.getAtomGroups(GroupType.AMINOACID).size(), (c.getAtomGroups(GroupType.AMINOACID).size() == 9)); - Assert.assertTrue("chain " + c.getName() + " seqres length should be 12. was: " + c.getSeqResLength(), c.getSeqResLength() == 12); + Assert.assertEquals("chain " + c.getName() + " seqres length should be 12. was: " + c.getSeqResLength(), 12, c.getSeqResLength()); Assert.assertEquals("chain " + c.getName() + " seqres sequences is not correct!", "NGDFEEIPEEYL", c.getSeqResSequence()); } @@ -253,14 +253,18 @@ public void testSiteGroups(){ // before biojava 5.0 we were asserting for same chain, but now the DAR residue is in its own nonpoly chain, can't do it anymore //assertEquals(c2, g.getChain()); String pdbName = g.getPDBName(); - if ( pdbName.equals("DAR")) { - darPresent = true; - //System.out.println("darPresent"); + switch (pdbName) { + case "DAR": + darPresent = true; + //System.out.println("darPresent"); + break; + case "GLY": + glyPresent = true; + break; + case "H2O": + noWater = false; + break; } - else if ( pdbName.equals("GLY")) - glyPresent = true; - else if ( pdbName.equals("H2O")) - noWater = false; } } } diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/Test1o2f.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/Test1o2f.java index 7acde4166e..d99b9a4153 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/Test1o2f.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/Test1o2f.java @@ -25,7 +25,6 @@ import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.LocalPDBDirectory.FetchBehavior; - import org.junit.Assert; import org.junit.Before; import org.junit.Test; diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/TestSECalignment.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/TestSECalignment.java index 6a9516251b..9716ce5d63 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/TestSECalignment.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/TestSECalignment.java @@ -23,6 +23,7 @@ package org.biojava.nbio.structure.test; import junit.framework.TestCase; +import org.biojava.nbio.core.util.StringManipulationHelper; import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.align.StructureAlignment; import org.biojava.nbio.structure.align.StructureAlignmentFactory; @@ -33,7 +34,6 @@ import org.biojava.nbio.structure.align.xml.AFPChainXMLParser; import org.biojava.nbio.structure.test.align.fatcat.FlipAFPChainTest; import org.biojava.nbio.structure.test.util.StringManipulationTestsHelper; -import org.biojava.nbio.core.util.StringManipulationHelper; import java.io.InputStream; diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/AlignmentToolsTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/AlignmentToolsTest.java index 339f1e4eee..3c46c1b258 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/AlignmentToolsTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/AlignmentToolsTest.java @@ -97,7 +97,7 @@ public void testGetSymmetryOrderForMaps() { final float minimumMetricChange = .5f;// be liberal, since we have small alignments // noisy C3 alignment - Map alignment1 = new HashMap(); + Map alignment1 = new HashMap<>(); alignment1.put(1, 5); alignment1.put(2, 6); alignment1.put(4, 7); @@ -107,14 +107,14 @@ public void testGetSymmetryOrderForMaps() { alignment1.put(10, 3); alignment1.put(11, 4); - Map identity = new AlignmentTools.IdentityMap(); + Map identity = new AlignmentTools.IdentityMap<>(); order = AlignmentTools.getSymmetryOrder(alignment1, identity, maxSymmetry, minimumMetricChange); Assert.assertEquals("Wrong order for alignment 1", 3, order); // sequential alignment. Should be order 1, but we report this as "no symmetry" //TODO Change default return value in getSymmetry - Map alignment2 = new HashMap(); + Map alignment2 = new HashMap<>(); for(int i=1;i<10;i++) { alignment2.put(i, i+1); } @@ -123,7 +123,7 @@ public void testGetSymmetryOrderForMaps() { Assert.assertEquals("Wrong order for alignment 2", 1, order); // now try to get symmetry order with an imperfect identity - Map alignment3 = new HashMap(); + Map alignment3 = new HashMap<>(); alignment3.put(1, 15); alignment3.put(2, 16); alignment3.put(4, 17); @@ -133,7 +133,7 @@ public void testGetSymmetryOrderForMaps() { alignment3.put(10, 13); alignment3.put(11, 14); - Map identityMinus10 = new HashMap(); + Map identityMinus10 = new HashMap<>(); for(int i=1;i<=11;i++) { identityMinus10.put(i+10, i); } @@ -155,7 +155,7 @@ public void testGetSymmetryOrderForMaps() { @Test public void testGuessSequentialAlignment() { // noisy C3 alignment - Map alignment1 = new HashMap(); + Map alignment1 = new HashMap<>(); alignment1.put(1, 5); alignment1.put(2, 6); alignment1.put(4, 7); @@ -166,7 +166,7 @@ public void testGuessSequentialAlignment() { alignment1.put(11, 4); // Sequential version of the alignment - Map sequentialForward = new HashMap(); + Map sequentialForward = new HashMap<>(); sequentialForward.put(1, 2); sequentialForward.put(2, 3); sequentialForward.put(4, 4); @@ -177,7 +177,7 @@ public void testGuessSequentialAlignment() { sequentialForward.put(11, 11); // inverse of sequentialForward - Map sequentialBackward = new HashMap(); + Map sequentialBackward = new HashMap<>(); sequentialBackward.put(2, 1); sequentialBackward.put(3, 2); sequentialBackward.put(4, 4); @@ -254,7 +254,7 @@ public void testGetSymmetryOrderWithCECP() throws IOException, StructureExceptio @Test public void testApplyAlignment() { // noisy C3 alignment - Map alignment1 = new HashMap(); + Map alignment1 = new HashMap<>(); alignment1.put(1, 5); alignment1.put(2, 6); alignment1.put(4, 7); @@ -264,7 +264,7 @@ public void testApplyAlignment() { alignment1.put(10, 3); alignment1.put(11, 4); - Map image1 = new HashMap(); + Map image1 = new HashMap<>(); image1.put(1, null); image1.put(2, 9); image1.put(4, 11); @@ -284,7 +284,7 @@ public void testApplyAlignment() { @Test public void testApplyAlignmentNonIdentical() { // noisy C3 alignment - Map alignment1 = new HashMap(); + Map alignment1 = new HashMap<>(); alignment1.put(1, 15); alignment1.put(2, 16); alignment1.put(4, 17); @@ -294,7 +294,7 @@ public void testApplyAlignmentNonIdentical() { alignment1.put(10, 13); alignment1.put(11, 14); - Map image1 = new HashMap(); + Map image1 = new HashMap<>(); image1.put(1, null); image1.put(2, 19); image1.put(4, 21); @@ -306,7 +306,7 @@ public void testApplyAlignmentNonIdentical() { //image1.put(5, null); //image1.put(3, null); - Map identity1 = new HashMap(); + Map identity1 = new HashMap<>(); for(int i=1;i<12;i++) { identity1.put(i+10,i); } @@ -320,7 +320,7 @@ public void testToConciseAlignmentString() { String result,expected; int i=0; - test = new HashMap(); + test = new HashMap<>(); test.put(1, 2); test.put(2, 3); test.put(3, 4); @@ -331,7 +331,7 @@ public void testToConciseAlignmentString() { Assert.assertEquals((i++) + ". Linear strings.", expected, result); - test = new HashMap(); + test = new HashMap<>(); test.put(1, 2); test.put(2, 3); test.put(3, 1); @@ -341,7 +341,7 @@ public void testToConciseAlignmentString() { result = AlignmentTools.toConciseAlignmentString(test); Assert.assertEquals((i++) + ". Cycles.", expected, result); - test = new HashMap(); + test = new HashMap<>(); test.put(1, 2); test.put(2, 3); test.put(3, 1); @@ -351,7 +351,7 @@ public void testToConciseAlignmentString() { result = AlignmentTools.toConciseAlignmentString(test); Assert.assertEquals((i++) + ". Complex.", expected, result); - test = new HashMap(); + test = new HashMap<>(); test.put(1, 2); test.put(2, 3); test.put(3, 4); @@ -376,7 +376,7 @@ public void testToConciseAlignmentString() { result = AlignmentTools.toConciseAlignmentString(test); Assert.assertEquals((i++) + ". Sub-optimal arrangement", expected, result); - Map test2 = new HashMap(); + Map test2 = new HashMap<>(); test2.put(1, 12.); test2.put(2, 13.); test2.put(3, 14.); @@ -409,7 +409,7 @@ public void testUpdateSuperposition() throws IOException, StructureException { Atom[] ca2 = StructureTools.getRepresentativeAtomArray(s); StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(new FileReader("src/test/resources/align/31BI_symm_align.xml")); - String line = ""; + String line; while ((line = br.readLine()) != null) { sb.append(line); } @@ -429,7 +429,7 @@ public void testUpdateSuperposition() throws IOException, StructureException { */ public static class OffsetMap extends AbstractMap { - private int offset; + private final int offset; public OffsetMap(int offset) { this.offset = offset; } diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/FlipAFPChainTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/FlipAFPChainTest.java index 6213503c64..b3f0752f86 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/FlipAFPChainTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/FlipAFPChainTest.java @@ -139,8 +139,7 @@ private void flip(String name1, String name2, String algorithmName) throws Struc * @param ca2 * @return */ - private double getRMSD(AFPChain afpChain, Atom[] ca1, Atom[] ca2) - throws StructureException { + private double getRMSD(AFPChain afpChain, Atom[] ca1, Atom[] ca2) { Atom[] ca2clone = StructureTools.cloneAtomArray(ca2); rotateAtoms2(afpChain,ca2clone); @@ -150,9 +149,9 @@ private double getRMSD(AFPChain afpChain, Atom[] ca1, Atom[] ca2) Atom[] catmp1 = AFPAlignmentDisplay.getAlignedAtoms1(afpChain, ca1); Atom[] catmp2 = AFPAlignmentDisplay.getAlignedAtoms2(afpChain, ca2clone); - assertTrue(catmp1.length == catmp2.length); + assertEquals(catmp1.length, catmp2.length); - assertTrue(catmp1.length == afpChain.getNrEQR()); + assertEquals(catmp1.length, afpChain.getNrEQR()); return Calc.rmsd(catmp1,catmp2); } diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/TestSimilarityCalc.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/TestSimilarityCalc.java index 48e905a9e5..00ecaa6c3b 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/TestSimilarityCalc.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/TestSimilarityCalc.java @@ -26,14 +26,12 @@ import org.biojava.nbio.structure.align.StructureAlignment; import org.biojava.nbio.structure.align.StructureAlignmentFactory; import org.biojava.nbio.structure.align.model.AFPChain; -import org.biojava.nbio.structure.align.model.AfpChainWriter; import org.biojava.nbio.structure.align.seq.SmithWaterman3DParameters; import org.biojava.nbio.structure.align.seq.SmithWaterman3Daligner; import org.biojava.nbio.structure.align.util.AtomCache; import org.junit.Test; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; /** @@ -49,8 +47,8 @@ public void testSimilarityDisplay(){ AtomCache cache = new AtomCache(); - Structure structure1 = null; - Structure structure2 = null; + Structure structure1; + Structure structure2; try { @@ -71,9 +69,9 @@ public void testSimilarityDisplay(){ afpChain.setName2(name2); - assertTrue(afpChain.getAlnLength() == 71); + assertEquals(71, afpChain.getAlnLength()); - assertTrue(afpChain.getAlnLength() == 71); + assertEquals(71, afpChain.getAlnLength()); assertTrue(afpChain.getSimilarity() > .57); assertTrue(afpChain.getSimilarity() <= .6); diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/ce/OptimalCECPMainTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/ce/OptimalCECPMainTest.java index bf7ee56be4..4b055b27eb 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/ce/OptimalCECPMainTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/ce/OptimalCECPMainTest.java @@ -25,8 +25,11 @@ import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.StructureAlignmentFactory; -import org.biojava.nbio.structure.align.ce.*; +import org.biojava.nbio.structure.align.ce.CECPParameters; import org.biojava.nbio.structure.align.ce.CECPParameters.DuplicationHint; +import org.biojava.nbio.structure.align.ce.CeCPMain; +import org.biojava.nbio.structure.align.ce.CeMain; +import org.biojava.nbio.structure.align.ce.OptimalCECPMain; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.util.AtomCache; import org.junit.Assert; @@ -44,13 +47,13 @@ */ public class OptimalCECPMainTest { - private AtomCache cache = new AtomCache(); + private final AtomCache cache = new AtomCache(); /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ @Before - public void setUp() throws Exception { + public void setUp() { } /** @@ -183,22 +186,22 @@ public void testPermuteArray() throws Exception { arrP = Arrays.copyOf(arr0, arr0.length); Assert.assertTrue("Shallow equals!", Arrays.deepEquals(arr0, arrP)); permuteArray.invoke(null, arrP, 0); - Assert.assertTrue(String.format("Permuting by 0 gave %s%s%s%s%s%s", (Object[]) arrP), + Assert.assertTrue(String.format("Permuting by 0 gave %s%s%s%s%s%s", arrP), Arrays.deepEquals(arr0, arrP)); arrP = Arrays.copyOf(arr0, arr0.length); permuteArray.invoke(null, arrP, 1); - Assert.assertTrue(String.format("Permuting by 1 gave %s%s%s%s%s%s", (Object[]) arrP), + Assert.assertTrue(String.format("Permuting by 1 gave %s%s%s%s%s%s", arrP), Arrays.deepEquals(arr1, arrP)); arrP = Arrays.copyOf(arr0, arr0.length); permuteArray.invoke(null, arrP, 5); - Assert.assertTrue(String.format("Permuting by 7 gave %s%s%s%s%s%s", (Object[]) arrP), + Assert.assertTrue(String.format("Permuting by 7 gave %s%s%s%s%s%s", arrP), Arrays.deepEquals(arr5, arrP)); arrP = Arrays.copyOf(arr0, arr0.length); permuteArray.invoke(null, arrP, -1); - Assert.assertTrue(String.format("Permuting by -1 gave %s%s%s%s%s%s", (Object[]) arrP), + Assert.assertTrue(String.format("Permuting by -1 gave %s%s%s%s%s%s", arrP), Arrays.deepEquals(arr5, arrP)); try { diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/AFPChainSerialisationTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/AFPChainSerialisationTest.java index 9d0bc303b7..391e98506e 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/AFPChainSerialisationTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/AFPChainSerialisationTest.java @@ -29,7 +29,8 @@ import java.io.IOException; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; public class AFPChainSerialisationTest { @@ -148,13 +149,13 @@ private void testAlignment(String name1, String name2, Atom[] ca1, Atom[] ca2, b int blockNum = afpChain.getBlockNum(); int[] optLen = afpChain.getOptLen(); - assertTrue("The nr of aligned blocks is not the same! " + blockNum + " " + newChain.getBlockNum() , blockNum == newChain.getBlockNum()); + assertEquals("The nr of aligned blocks is not the same! " + blockNum + " " + newChain.getBlockNum(), blockNum, newChain.getBlockNum()); for ( int i =0 ; i < blockNum ; i++){ int newLenI = newChain.getOptLen()[i]; - assertTrue("The values in the optLen field don't match! pos:" + i + " orig:" + optLen[i] + " new:" + newLenI,optLen[i] == newLenI); + assertEquals("The values in the optLen field don't match! pos:" + i + " orig:" + optLen[i] + " new:" + newLenI, optLen[i], newLenI); } // test the internal optAlign data structure: @@ -170,8 +171,8 @@ private void testAlignment(String name1, String name2, Atom[] ca1, Atom[] ca2, b int n1 = optAln2[i][0][j]; int n2 = optAln2[i][1][j]; - assertTrue(p1 == n1); - assertTrue(p2 == n2); + assertEquals(p1, n1); + assertEquals(p2, n2); } } @@ -187,7 +188,7 @@ private void testAlignment(String name1, String name2, Atom[] ca1, Atom[] ca2, b } - private AFPChain doAlign(String name1, String name2, Atom[] ca1, Atom[] ca2 , boolean doRigid) throws StructureException,IOException{ + private AFPChain doAlign(String name1, String name2, Atom[] ca1, Atom[] ca2 , boolean doRigid) throws StructureException { FatCatParameters params = new FatCatParameters(); FatCat fatCat = new FatCat(); @@ -222,14 +223,14 @@ public String[] align (String name1, String name2, Atom[] ca1, Atom[] ca2 , bool @org.junit.Test public void testMulti() throws IOException, StructureException { - Atom[] ca1 = null; - Atom[] ca2 = null; - Atom[] ca3 = null; - Atom[] ca4 = null; - Atom[] ca5 = null; - Atom[] ca6 = null; - String[] result1 = null; - String[] result2 = null; + Atom[] ca1; + Atom[] ca2; + Atom[] ca3; + Atom[] ca4; + Atom[] ca5; + Atom[] ca6; + String[] result1; + String[] result2; String name1 = "5pti.A"; String name2 = "1znf.A"; @@ -264,7 +265,7 @@ public void testMulti() throws IOException, StructureException { //WARNING: THE ORDER CAN CHANGE: order of elements in XML is not necessarily the same! AFPChain[] chains = AFPChainXMLParser.parseMultiXML(xmlNew); - assertTrue(chains.length == 2); + assertEquals(2, chains.length); // recreate the correct chains... AFPChain new1 = getAfpFor(name1,chains); @@ -273,16 +274,16 @@ public void testMulti() throws IOException, StructureException { assertNotNull(new1); assertNotNull(new2); - assertTrue(new1.getName1().equals(name1)); + assertEquals(new1.getName1(), name1); //System.out.println(new2.getName1() + " " + new2.getName2() + " "+ name3); - assertTrue(new2.getName1().equals(name3)); + assertEquals(new2.getName1(), name3); AFPChainXMLParser.rebuildAFPChain(new1, ca1, ca3); String fatcat1 = new1.toFatcat(ca1, ca3); assertEquals(fatcat1, result1[0]); String xmlnew1 = AFPChainXMLConverter.toXML(new1, ca1, ca3); - assertTrue(xmlnew1.equals(result1[1])); + assertEquals(xmlnew1, result1[1]); AFPChainXMLParser.rebuildAFPChain(new2, ca4, ca6); String fatcat2 = new2.toFatcat(ca4, ca6); diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/FlipAFPChainTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/FlipAFPChainTest.java index 41a03bee70..85fa4750ca 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/FlipAFPChainTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/FlipAFPChainTest.java @@ -24,7 +24,10 @@ package org.biojava.nbio.structure.test.align.fatcat; -import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.Atom; +import org.biojava.nbio.structure.Calc; +import org.biojava.nbio.structure.StructureException; +import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.StructureAlignment; import org.biojava.nbio.structure.align.StructureAlignmentFactory; import org.biojava.nbio.structure.align.ce.CeMain; @@ -118,7 +121,7 @@ private void align (StructureAlignment algorithm, String name1, String name2) Assert.assertNotNull("could not get nr. of eqr: ", afpChain.getNrEQR()); Assert.assertNotNull("could not get nr. of eqr: ", origFlip.getNrEQR()); - Assert.assertTrue("The nr. of equivalent positions is not equal!", afpChain.getNrEQR() == origFlip.getNrEQR()); + Assert.assertEquals("The nr. of equivalent positions is not equal!", afpChain.getNrEQR(), origFlip.getNrEQR()); Atom shift1 = afpChain.getBlockShiftVector()[0]; Atom shift2 = origFlip.getBlockShiftVector()[0]; @@ -158,8 +161,7 @@ private void align (StructureAlignment algorithm, String name1, String name2) * @param ca2 * @return */ - private double getRMSD(AFPChain afpChain, Atom[] ca1, Atom[] ca2) - throws StructureException { + private double getRMSD(AFPChain afpChain, Atom[] ca1, Atom[] ca2) { Atom[] ca2clone = StructureTools.cloneAtomArray(ca2); rotateAtoms2(afpChain,ca2clone); @@ -169,9 +171,9 @@ private double getRMSD(AFPChain afpChain, Atom[] ca1, Atom[] ca2) Atom[] catmp1 = AFPAlignmentDisplay.getAlignedAtoms1(afpChain, ca1); Atom[] catmp2 = AFPAlignmentDisplay.getAlignedAtoms2(afpChain, ca2clone); - Assert.assertTrue(catmp1.length == catmp2.length); + Assert.assertEquals(catmp1.length, catmp2.length); - Assert.assertTrue(catmp1.length == afpChain.getNrEQR()); + Assert.assertEquals(catmp1.length, afpChain.getNrEQR()); return Calc.rmsd(catmp1,catmp2); } diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/MyTestHelper.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/MyTestHelper.java index 1905b173af..0fc48c7a5e 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/MyTestHelper.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/MyTestHelper.java @@ -41,7 +41,7 @@ public class MyTestHelper public static String compareAlignment(String pdb1, String chain1, String pdb2, String chain2, String originalOutput, boolean doRigid){ - AFPChain afpChain = null; + AFPChain afpChain; PDBFileReader pdbpars = new PDBFileReader(); pdbpars.setPath(pdbPath); diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/TestFlexibleRotationMatrices.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/TestFlexibleRotationMatrices.java index 5a4709e2e0..e4e7cac756 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/TestFlexibleRotationMatrices.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/TestFlexibleRotationMatrices.java @@ -24,7 +24,10 @@ package org.biojava.nbio.structure.test.align.fatcat; -import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.Atom; +import org.biojava.nbio.structure.Calc; +import org.biojava.nbio.structure.StructureException; +import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.StructureAlignment; import org.biojava.nbio.structure.align.fatcat.FatCatFlexible; import org.biojava.nbio.structure.align.fatcat.FatCatRigid; @@ -38,12 +41,11 @@ import org.biojava.nbio.structure.jama.Matrix; import org.junit.Test; +import javax.vecmath.Matrix4d; import java.io.IOException; import java.util.ArrayList; import java.util.List; -import javax.vecmath.Matrix4d; - import static org.junit.Assert.*; public class TestFlexibleRotationMatrices { @@ -86,7 +88,7 @@ private void compare(String name1, String name2, boolean doRigid){ //Atom[] shifts1 = afpChain.getBlockShiftVector(); double[] blockRmsd = afpChain.getBlockRmsd(); - assertTrue( afpChain.getBlockNum() == newChain.getBlockNum()); + assertEquals(afpChain.getBlockNum(), newChain.getBlockNum()); // make sure the XML conversion worked OK. for ( int i = 0 ; i < newChain.getBlockNum();i++) { @@ -96,7 +98,7 @@ private void compare(String name1, String name2, boolean doRigid){ assertTrue(compareRmsd(blockRmsd[i], newChain.getBlockRmsd()[i]) ); } - assertTrue(afpChain.getOptLength() == newChain.getOptLength()); + assertEquals(afpChain.getOptLength(), newChain.getOptLength()); // get the aligned blocks and check RMSD int[] blockSize =afpChain.getBlockSize(); @@ -122,9 +124,7 @@ private void compare(String name1, String name2, boolean doRigid){ } - } catch (IOException e){ - fail(e.getMessage()); - } catch (StructureException e){ + } catch (IOException | StructureException e){ fail(e.getMessage()); } @@ -142,7 +142,7 @@ private boolean compareRmsd(double rmsdOrig, double rmsdNew) { } private void compareBlock(int blockNr, AFPChain afpChain, AFPChain newChain, - Atom[] ca1, Atom[] ca2) throws StructureException { + Atom[] ca1, Atom[] ca2) { @@ -161,9 +161,9 @@ private void compareBlock(int blockNr, AFPChain afpChain, AFPChain newChain, // get the eqr atoms of block X: int[] optLen =afpChain.getOptLen(); - List eqrPos1 = new ArrayList(); - List eqrPos2 = new ArrayList(); - List eqrPos2copy = new ArrayList(); + List eqrPos1 = new ArrayList<>(); + List eqrPos2 = new ArrayList<>(); + List eqrPos2copy = new ArrayList<>(); for ( int z = 0 ; z < blocks2[blockNr][0].length && z < optLen[blockNr] ; z++){ int pos1 = blocks2[blockNr][0][z]; int pos2 = blocks2[blockNr][1][z]; @@ -177,15 +177,15 @@ private void compareBlock(int blockNr, AFPChain afpChain, AFPChain newChain, eqrPos2copy.add(c3); } - assertTrue("The nr of Atoms in block " + blockNr + " does not match the expected nr. Expected:" + afpChain.getOptLen()[blockNr] + " but found: " + eqrPos2.size() , eqrPos2.size() == afpChain.getOptLen()[blockNr]); + assertEquals("The nr of Atoms in block " + blockNr + " does not match the expected nr. Expected:" + afpChain.getOptLen()[blockNr] + " but found: " + eqrPos2.size(), eqrPos2.size(), afpChain.getOptLen()[blockNr]); // THIS IS ROTATING the coordinates according to what is in the file. - Atom[] blockSet1 = eqrPos1.toArray(new Atom[eqrPos1.size()]); - Atom[] blockSet2 = eqrPos2.toArray(new Atom[eqrPos2.size()]); - Atom[] blockSet2copy = eqrPos2copy.toArray(new Atom[eqrPos2copy.size()]); + Atom[] blockSet1 = eqrPos1.toArray(Atom.EmptyAtomArray); + Atom[] blockSet2 = eqrPos2.toArray(Atom.EmptyAtomArray); + Atom[] blockSet2copy = eqrPos2copy.toArray(Atom.EmptyAtomArray); //System.out.println(shift ); @@ -248,7 +248,7 @@ private void compareBlock(int blockNr, AFPChain afpChain, AFPChain newChain, } - private boolean compareVectors(Atom atom1, Atom atom2) throws StructureException { + private boolean compareVectors(Atom atom1, Atom atom2) { //System.out.println(Math.abs(atom1.getX()- atom2.getX())); assertTrue("The X coordinates are too far apart!", Math.abs(atom1.getX()- atom2.getX()) < 0.01); @@ -270,7 +270,7 @@ private boolean compareMatrices(Matrix matrix1, Matrix matrix2) { } - private AFPChain getAlignment (String name1, String name2, Atom[] ca1, Atom[] ca2 , boolean doRigid) throws StructureException,IOException{ + private AFPChain getAlignment (String name1, String name2, Atom[] ca1, Atom[] ca2 , boolean doRigid) throws StructureException { FatCatParameters params = new FatCatParameters(); StructureAlignment fatCat ; diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/TestOutputStrings.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/TestOutputStrings.java index 4917d67cf3..0b9c1a7c4a 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/TestOutputStrings.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/fatcat/TestOutputStrings.java @@ -207,31 +207,10 @@ public void test1buz1aliFlexible(){ String pdb2 = "1ali"; String chain2 ="A"; - String originalOutput ="Align 1buzA.pdb 116 with 1aliA.pdb 446" +newline + - "Twists 1 ini-len 64 ini-rmsd 3.12 opt-equ 88 opt-rmsd 3.34 chain-rmsd 5.32 Score 103.72 align-len 199 gaps 111 (55.78%)" +newline + - "P-value 3.26e-01 Afp-num 15578 Identity 6.25% Similarity 25.89%" +newline + - "Block 0 afp 1 score 23.14 rmsd 0.76 gap 0 (0.00%)" +newline + - "Block 1 afp 7 score 100.08 rmsd 3.32 gap 17 (0.23%)" +newline + - "" +newline + - " . : . : . : . : . : . : . :" +newline + - "Chain 1: 5 DMNVKESVLCIRLTGELDH---------------------------------HTAETLKQKVTQSLEKDD" +newline + - " 1 11111111111111 222222222222222222" +newline + - "Chain 2: 246 VTEANQQKPLLGLFADGNMPVRWLGPKATYHGNIDKPAVTCTPNPQRNDSVPTLAQMTDKAIELLSKNEK" +newline + - "" +newline + - " . : . : . : . : . : . : . :" +newline + - "Chain 1: 42 IRHIVLNLEDLS------------FMDSSGLGVILGRYKQIK-QIGGEMVVCAISPAVKRLFDMSGLFKI" +newline + - " 222222222222 222222222222222222 2222222222222 " +newline + - "Chain 2: 316 GFFLQVEGASIDKQDHAANPCGQIGETVDLDEAVQRALEFAKKEGNTLVIVTADHAHASQIVAPDTKAPG" +newline + - "" +newline + - " . : . : . : . : . : ." +newline + - "Chain 1: 99 I---------------------------------RFEQSE--------QQALLTLGVAS" +newline + - " 22 222222 2222" +newline + - "Chain 2: 386 LTQALNTKDGAVMVMSYGNSEEDSQENTGSQLRIAAYGPHAANVVGLTDQTDLFYTMKA" +newline + - "" +newline + - "Note: positions are from PDB; the numbers between alignments are block index" +newline ; + String originalOutput = "Align 1buzA.pdb 116 with 1aliA.pdb 446" + newline + "Twists 1 ini-len 64 ini-rmsd 3.12 opt-equ 88 opt-rmsd 3.34 chain-rmsd 5.32 Score 103.72 align-len 199 gaps 111 (55.78%)" + newline + "P-value 3.26e-01 Afp-num 15578 Identity 6.25% Similarity 25.89%" + newline + "Block 0 afp 1 score 23.14 rmsd 0.76 gap 0 (0.00%)" + newline + "Block 1 afp 7 score 100.08 rmsd 3.32 gap 17 (0.23%)" + newline + newline + " . : . : . : . : . : . : . :" + newline + "Chain 1: 5 DMNVKESVLCIRLTGELDH---------------------------------HTAETLKQKVTQSLEKDD" + newline + " 1 11111111111111 222222222222222222" + newline + "Chain 2: 246 VTEANQQKPLLGLFADGNMPVRWLGPKATYHGNIDKPAVTCTPNPQRNDSVPTLAQMTDKAIELLSKNEK" + newline + newline + " . : . : . : . : . : . : . :" + newline + "Chain 1: 42 IRHIVLNLEDLS------------FMDSSGLGVILGRYKQIK-QIGGEMVVCAISPAVKRLFDMSGLFKI" + newline + " 222222222222 222222222222222222 2222222222222 " + newline + "Chain 2: 316 GFFLQVEGASIDKQDHAANPCGQIGETVDLDEAVQRALEFAKKEGNTLVIVTADHAHASQIVAPDTKAPG" + newline + newline + " . : . : . : . : . : ." + newline + "Chain 1: 99 I---------------------------------RFEQSE--------QQALLTLGVAS" + newline + " 22 222222 2222" + newline + "Chain 2: 386 LTQALNTKDGAVMVMSYGNSEEDSQENTGSQLRIAAYGPHAANVVGLTDQTDLFYTMKA" + newline + newline + "Note: positions are from PDB; the numbers between alignments are block index" + newline; String result = MyTestHelper.compareAlignment(pdb1, chain1, pdb2, chain2, originalOutput,false); - if (! result.equals("")){ + if (!result.isEmpty()){ String msg = "the created alignment images are not identical! "; printMismatch(originalOutput,result); printFirstMismatch(result, originalOutput); @@ -327,25 +306,9 @@ public void test1a641hngFlexible(){ String pdb2 = "1hng"; String chain2 ="B"; - String originalOutput="Align 1a64A.pdb 94 with 1hngB.pdb 175" +newline + - "Twists 1 ini-len 88 ini-rmsd 1.84 opt-equ 94 opt-rmsd 0.64 chain-rmsd 20.77 Score 235.94 align-len 96 gaps 2 (2.08%)" +newline + - "P-value 4.23e-13 Afp-num 6497 Identity 98.94% Similarity 100.00%" +newline + - "Block 0 afp 5 score 118.80 rmsd 0.75 gap 0 (0.00%)" +newline + - "Block 1 afp 6 score 143.14 rmsd 0.46 gap 0 (0.00%)" +newline + - "" +newline + - " . : . : . : . : . : . : . :" +newline + - "Chain 1: 4 GTVWGALGHGINLNIPNFQMTDDIDEVRWERGSTLVAEFKR--KPFLKSGAFEILANGDLKIKNLTRDDS" +newline + - " 11111111111111111111111111111111111111111 222222222222222222222222222" +newline + - "Chain 2: 4 GTVWGALGHGINLNIPNFQMTDDIDEVRWERGSTLVAEFKRKMKPFLKSGAFEILANGDLKIKNLTRDDS" +newline + - "" +newline + - " . : . : ." +newline + - "Chain 1: 74 GTYNVTVYSTNGTRILDKALDLRILE" +newline + - " 22222222222222222222222222" +newline + - "Chain 2: 74 GTYNVTVYSTNGTRILNKALDLRILE" +newline + - "" +newline + - "Note: positions are from PDB; the numbers between alignments are block index" +newline ; + String originalOutput= "Align 1a64A.pdb 94 with 1hngB.pdb 175" + newline + "Twists 1 ini-len 88 ini-rmsd 1.84 opt-equ 94 opt-rmsd 0.64 chain-rmsd 20.77 Score 235.94 align-len 96 gaps 2 (2.08%)" + newline + "P-value 4.23e-13 Afp-num 6497 Identity 98.94% Similarity 100.00%" + newline + "Block 0 afp 5 score 118.80 rmsd 0.75 gap 0 (0.00%)" + newline + "Block 1 afp 6 score 143.14 rmsd 0.46 gap 0 (0.00%)" + newline + newline + " . : . : . : . : . : . : . :" + newline + "Chain 1: 4 GTVWGALGHGINLNIPNFQMTDDIDEVRWERGSTLVAEFKR--KPFLKSGAFEILANGDLKIKNLTRDDS" + newline + " 11111111111111111111111111111111111111111 222222222222222222222222222" + newline + "Chain 2: 4 GTVWGALGHGINLNIPNFQMTDDIDEVRWERGSTLVAEFKRKMKPFLKSGAFEILANGDLKIKNLTRDDS" + newline + newline + " . : . : ." + newline + "Chain 1: 74 GTYNVTVYSTNGTRILDKALDLRILE" + newline + " 22222222222222222222222222" + newline + "Chain 2: 74 GTYNVTVYSTNGTRILNKALDLRILE" + newline + newline + "Note: positions are from PDB; the numbers between alignments are block index" + newline; String result = MyTestHelper.compareAlignment(pdb1, chain1, pdb2, chain2, originalOutput,false); - if (! result.equals("")){ + if (!result.isEmpty()){ String msg = "the created alignment images are not identical! "; printMismatch(originalOutput,result); printFirstMismatch(result, originalOutput); @@ -509,31 +472,10 @@ public void test1a211hwgFlexible(){ String pdb2 = "1hwg"; String chain2 ="C"; - String originalOutput="Align 1a21A.pdb 194 with 1hwgC.pdb 191" +newline + - "Twists 1 ini-len 120 ini-rmsd 3.04 opt-equ 150 opt-rmsd 2.96 chain-rmsd 4.21 Score 233.34 align-len 210 gaps 60 (28.57%)" +newline + - "P-value 1.15e-05 Afp-num 12696 Identity 11.98% Similarity 23.95%" +newline + - "Block 0 afp 4 score 66.42 rmsd 2.03 gap 6 (0.16%)" +newline + - "Block 1 afp 11 score 184.29 rmsd 3.24 gap 69 (0.44%)" +newline + - "" +newline + - " . : . : . : . : . : . : . :" +newline + - "Chain 1: 6 RAYNLTWKSTN-FKTILEWEPKSIDHVYTVQISTRLENWKSKCFLTAE---TECDLTDEVVKDVGQTYMA" +newline + - " 11111111111 111111111 111111111111111111 222222222 222222 " +newline + - "Chain 2: 32 EPKFTKCRSPERETFSCHWTD-----PIQLFYTRRNQEWKECPDYVSAGENSCYFNSSFT---SIWIPYC" +newline + - "" +newline + - " . : . : . : . : . : . : . :" +newline + - "Chain 1: 72 RVLSYPARNTTGFPEEPPFRNSPEFTPYLDTNLGQPTIQSFEQVG-------TKLNVTVQDARTLVTFLS" +newline + - " 22222222222222222222222 222222222222 222" +newline + - "Chain 2: 109 IKLTSNGGTVDE----------KCFSVDEIVQPDPPIALNWTLLNVSLTGIHADIQVRWEAPRN---ADI" +newline + - "" +newline + - " . : . : . : . : . : . : . :" +newline + - "Chain 1: 141 LRAVFGKDLNYTLYYWR-----KKTAT-TNTNEFLIDVDKGE-NYCFSVQAVIPSRKRKQRSPESLTECT" +newline + - " 222222 222222222 22222 22222222222222 2222222222222 222222222222" +newline + - "Chain 2: 166 QKGWMV--LEYELQYKEVNETKWKMMDPILTTSVPVYSLKVDKEYEVRVRSKQRNS--GNYGEFSEVLYV" +newline + - "" +newline + - "Note: positions are from PDB; the numbers between alignments are block index" +newline; + String originalOutput= "Align 1a21A.pdb 194 with 1hwgC.pdb 191" + newline + "Twists 1 ini-len 120 ini-rmsd 3.04 opt-equ 150 opt-rmsd 2.96 chain-rmsd 4.21 Score 233.34 align-len 210 gaps 60 (28.57%)" + newline + "P-value 1.15e-05 Afp-num 12696 Identity 11.98% Similarity 23.95%" + newline + "Block 0 afp 4 score 66.42 rmsd 2.03 gap 6 (0.16%)" + newline + "Block 1 afp 11 score 184.29 rmsd 3.24 gap 69 (0.44%)" + newline + newline + " . : . : . : . : . : . : . :" + newline + "Chain 1: 6 RAYNLTWKSTN-FKTILEWEPKSIDHVYTVQISTRLENWKSKCFLTAE---TECDLTDEVVKDVGQTYMA" + newline + " 11111111111 111111111 111111111111111111 222222222 222222 " + newline + "Chain 2: 32 EPKFTKCRSPERETFSCHWTD-----PIQLFYTRRNQEWKECPDYVSAGENSCYFNSSFT---SIWIPYC" + newline + newline + " . : . : . : . : . : . : . :" + newline + "Chain 1: 72 RVLSYPARNTTGFPEEPPFRNSPEFTPYLDTNLGQPTIQSFEQVG-------TKLNVTVQDARTLVTFLS" + newline + " 22222222222222222222222 222222222222 222" + newline + "Chain 2: 109 IKLTSNGGTVDE----------KCFSVDEIVQPDPPIALNWTLLNVSLTGIHADIQVRWEAPRN---ADI" + newline + newline + " . : . : . : . : . : . : . :" + newline + "Chain 1: 141 LRAVFGKDLNYTLYYWR-----KKTAT-TNTNEFLIDVDKGE-NYCFSVQAVIPSRKRKQRSPESLTECT" + newline + " 222222 222222222 22222 22222222222222 2222222222222 222222222222" + newline + "Chain 2: 166 QKGWMV--LEYELQYKEVNETKWKMMDPILTTSVPVYSLKVDKEYEVRVRSKQRNS--GNYGEFSEVLYV" + newline + newline + "Note: positions are from PDB; the numbers between alignments are block index" + newline; String result = MyTestHelper.compareAlignment(pdb1, chain1, pdb2, chain2, originalOutput,false); - if (! result.equals("")){ + if (!result.isEmpty()){ String msg = "the created alignment images are not identical! "; printMismatch(originalOutput,result); printFirstMismatch(result, originalOutput); diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/qsalign/TestQsAlignExamples.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/qsalign/TestQsAlignExamples.java index b9ad316c4b..f30670097b 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/qsalign/TestQsAlignExamples.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/qsalign/TestQsAlignExamples.java @@ -20,10 +20,6 @@ */ package org.biojava.nbio.structure.test.align.qsalign; -import static org.junit.Assert.*; - -import java.io.IOException; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; @@ -34,6 +30,11 @@ import org.biojava.nbio.structure.cluster.SubunitClustererParameters; import org.junit.Test; +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + /** * Test the correctness of the {@link QsAlign} algorithm with some examples of * different levels of quaternary structure similarity. diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/seq/TestSmithWaterman3Daligner.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/seq/TestSmithWaterman3Daligner.java index ce6ade5543..253f4685be 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/seq/TestSmithWaterman3Daligner.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/align/seq/TestSmithWaterman3Daligner.java @@ -20,12 +20,7 @@ */ package org.biojava.nbio.structure.test.align.seq; -import static org.junit.Assert.*; - -import java.io.IOException; - import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.model.AFPChain; @@ -33,6 +28,11 @@ import org.biojava.nbio.structure.align.seq.SmithWaterman3Daligner; import org.junit.Test; +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + /** * Test the superposition based on a sequence alignment on different cases. * @@ -50,11 +50,6 @@ public class TestSmithWaterman3Daligner { @Test public void testMaxRMSD() throws StructureException, IOException { - Structure s1 = StructureTools.getStructure("1A3N.A"); - Structure s2 = StructureTools.getStructure("1A3N.B"); - - Atom[] ca1 = StructureTools.getRepresentativeAtomArray(s1); - Atom[] ca2 = StructureTools.getRepresentativeAtomArray(s2); SmithWaterman3Daligner aligner = new SmithWaterman3Daligner(); SmithWaterman3DParameters params = new SmithWaterman3DParameters(); @@ -62,6 +57,9 @@ public void testMaxRMSD() throws StructureException, IOException { // Use no restriction on the RMSD params.setMaxRmsd(99.0); + Atom[] ca1 = StructureTools.getRepresentativeAtomArray(StructureTools.getStructure("1A3N.A")); + Atom[] ca2 = StructureTools.getRepresentativeAtomArray(StructureTools.getStructure("1A3N.B")); + AFPChain afpChain = aligner.align(ca1, ca2, params); assertEquals("RMSD is wrong", 1.39, afpChain.getTotalRmsdOpt(), 0.005); diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/cluster/TestSubunitClustererExamples.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/cluster/TestSubunitClustererExamples.java index 161a4c8b96..6f5b8ffdba 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/cluster/TestSubunitClustererExamples.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/cluster/TestSubunitClustererExamples.java @@ -20,13 +20,6 @@ */ package org.biojava.nbio.structure.test.cluster; -import static org.junit.Assert.*; - -import java.io.IOException; -import java.util.List; -import java.util.function.Function; -import java.util.stream.Collectors; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; @@ -37,6 +30,14 @@ import org.biojava.nbio.structure.symmetry.core.Stoichiometry; import org.junit.Test; +import java.io.IOException; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + /** * Test the {@link SubunitClusterer} clustering correctness on different real * structures with different types of chain clustering difficulties. diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/contact/TestInterfaceFinder.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/contact/TestInterfaceFinder.java new file mode 100644 index 0000000000..b71f4d63d1 --- /dev/null +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/contact/TestInterfaceFinder.java @@ -0,0 +1,43 @@ +package org.biojava.nbio.structure.test.contact; + +import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.StructureException; +import org.biojava.nbio.structure.StructureIO; +import org.biojava.nbio.structure.contact.*; +import org.junit.Test; + +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; + +import static org.junit.Assert.assertEquals; + +public class TestInterfaceFinder { + + @Test + public void testGetAllInterfaces() throws StructureException, IOException { + Structure s = StructureIO.getStructure("3hbx"); + + long start = System.currentTimeMillis(); + + InterfaceFinder finder = new InterfaceFinder(s); + StructureInterfaceList list = finder.getAllInterfaces(); + + long end = System.currentTimeMillis(); + System.out.println("Took " + (end-start) + " ms to calculate interfaces"); + + assertEquals(12, list.size()); + + Set> unique = new HashSet<>(); + + for (StructureInterface interf : list) { + System.out.println("Interface " + interf.getMoleculeIds()); + AtomContactSet set = interf.getContacts(); + System.out.println("Number of contacts: " + set.size()); + + unique.add(interf.getMoleculeIds()); + + } + assertEquals(12, unique.size()); + } +} diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/ecod/EcodInstallationTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/ecod/EcodInstallationTest.java index 8ab3f29fb3..63dc49048e 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/ecod/EcodInstallationTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/ecod/EcodInstallationTest.java @@ -20,24 +20,6 @@ package org.biojava.nbio.structure.test.ecod; -import static org.junit.Assert.*; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import org.biojava.nbio.core.util.ConcurrencyTools; import org.biojava.nbio.structure.ResidueNumber; import org.biojava.nbio.structure.ResidueRange; @@ -54,6 +36,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; +import java.io.IOException; +import java.util.*; +import java.util.concurrent.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.junit.Assert.*; + /** * @author Spencer Bliven * @@ -148,7 +139,7 @@ public void testByPDB() throws IOException { private void matchNames(String pdbId,String[] expected,List actual) { assertEquals("Wrong number of domains for "+pdbId, expected.length, actual.size()); - Set exp = new HashSet(Arrays.asList(expected)); + Set exp = new HashSet<>(Arrays.asList(expected)); for(EcodDomain d : actual) { assertTrue("Unexpected domain "+d.getDomainId()+" in "+pdbId,exp.contains(d.getDomainId())); } @@ -175,7 +166,7 @@ public void testParsing() throws IOException { } expected = new EcodDomain( // Long uid, String domainId, Boolean manual, - 20669l, "e1lyw.1", false, + 20669L, "e1lyw.1", false, // Integer xGroup, Integer hGroup, Integer tGroup, Integer fGroup, String pdbId, 1,1,1,fGroup,"1lyw", // String chainName, String range, String seqId, String architectureName, @@ -184,7 +175,7 @@ public void testParsing() throws IOException { "cradle loop barrel", "RIFT-related","acid protease", // String fGroupName, Boolean isAssembly, List ligands fGroupName, - 20669l, Collections.singleton("EPE") + 20669L, Collections.singleton("EPE") ); assertEquals(ecodId,expected,domain); @@ -195,13 +186,13 @@ public void testParsing() throws IOException { } @Test - public void testMultithreaded() throws IOException { + public void testMultithreaded() { final EcodInstallation ecod = (EcodInstallation) EcodFactory.getEcodDatabase(VERSION); ecod.clear(); String[] ecodIds = new String[] { "e4s1gA1", "e4umoB1", "e4v0cA1", "e4v1af1", "e3j7yj1", "e4wfcA1","e4b0jP1", }; - List> futureDomains = new ArrayList>(); + List> futureDomains = new ArrayList<>(); for(final String ecodId : ecodIds) { Callable job = new Callable() { @Override @@ -246,8 +237,8 @@ public void testFilterByHierarchy() throws IOException { Set expected,actual; // expected members through at least develop133 - expected = new HashSet(Arrays.asList( - "e4il6R1 e4pj0R1 e4pj0r1 e4ub6R1 e4ub8R1".split(" ") )); + expected = new HashSet<>(Arrays.asList( + "e4il6R1 e4pj0R1 e4pj0r1 e4ub6R1 e4ub8R1".split(" "))); // expanded by develop204 if( ecod.getVersion().compareToIgnoreCase("develop204") >= 0) { expected.addAll(Arrays.asList( @@ -256,21 +247,21 @@ public void testFilterByHierarchy() throws IOException { } filtered = ecod.filterByHierarchy("6106.1.1"); - actual = new HashSet(); + actual = new HashSet<>(); for(EcodDomain d : filtered) { actual.add(d.getDomainId()); } assertEquals(expected,actual); filtered = ecod.filterByHierarchy("6106.1"); - actual = new HashSet(); + actual = new HashSet<>(); for(EcodDomain d : filtered) { actual.add(d.getDomainId()); } assertEquals(expected,actual); filtered = ecod.filterByHierarchy("6106"); - actual = new HashSet(); + actual = new HashSet<>(); for(EcodDomain d : filtered) { actual.add(d.getDomainId()); } diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/ecod/EcodParseTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/ecod/EcodParseTest.java index 96d7e31d62..1d741033a7 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/ecod/EcodParseTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/ecod/EcodParseTest.java @@ -20,17 +20,7 @@ */ package org.biojava.nbio.structure.test.ecod; -import java.io.IOException; -import java.util.List; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.AtomPositionMap; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.ResidueRange; -import org.biojava.nbio.structure.ResidueRangeAndLength; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.ecod.EcodDatabase; import org.biojava.nbio.structure.ecod.EcodDomain; @@ -39,6 +29,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.util.List; + /** * This is not a unit test. * @@ -85,11 +78,7 @@ private static int testVersion(String ecodVersion) throws IOException { try { struct = cache.getStructure(d.getPdbId()); ca1 = StructureTools.getRepresentativeAtomArray(struct); - } catch (IOException e) { - logger.error("Error getting structure for "+d.getDomainId(),e); - errors++; - continue; - } catch (StructureException e) { + } catch (IOException | StructureException e) { logger.error("Error getting structure for "+d.getDomainId(),e); errors++; continue; @@ -111,6 +100,7 @@ private static int testVersion(String ecodVersion) throws IOException { for(ResidueRange r : ranges) { if( r == null ) { clean = false; + break; } } if( ! clean ) { @@ -128,12 +118,11 @@ private static int testVersion(String ecodVersion) throws IOException { Group g = struct.getPolyChainByPDB(range.getStart().getChainName()).getGroupByPDB(range.getStart()); if(g!=null) { logger.warn("No CA atom for starting residue "+d.getDomainId()+"_"+range); - clean = false; - } else { + } else { logger.error("Start doesn't exist for "+d.getDomainId()+"_"+range.toString()); - clean = false; - } - } + } + clean = false; + } } catch(Exception e) { logger.error("Start doesn't exist for "+d.getDomainId()+"_"+range.toString(),e); clean = false; @@ -147,12 +136,11 @@ private static int testVersion(String ecodVersion) throws IOException { } catch(StructureException e ) {} if(g!=null) { logger.warn("No CA atom for ending residue "+d.getDomainId()+"_"+range); - clean = false; - } else { + } else { logger.error("End doesn't exist for "+d.getDomainId()+"_"+range.toString()); - clean = false; - } - } + } + clean = false; + } } catch(Exception e) { logger.error("End doesn't exist for "+d.getDomainId()+"_"+range.toString(),e); clean = false; @@ -172,6 +160,7 @@ private static int testVersion(String ecodVersion) throws IOException { for(ResidueRange r : ranges) { if( r == null ) { clean = false; + break; } } if( ! clean ) { diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/geometry/TestProteinSuperposition.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/geometry/TestProteinSuperposition.java index 8d30a82f4d..4464b7d1dd 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/geometry/TestProteinSuperposition.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/geometry/TestProteinSuperposition.java @@ -20,18 +20,7 @@ */ package org.biojava.nbio.structure.test.geometry; -import static org.junit.Assert.*; - -import java.io.IOException; - -import javax.vecmath.Point3d; - -import org.biojava.nbio.structure.Calc; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.geometry.SuperPosition; import org.biojava.nbio.structure.geometry.SuperPositionQCP; import org.biojava.nbio.structure.geometry.SuperPositionQuat; @@ -39,6 +28,11 @@ import org.junit.BeforeClass; import org.junit.Test; +import javax.vecmath.Point3d; +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + public class TestProteinSuperposition { private static Point3d[] chain1; diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/LoadOldXMLfileTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/LoadOldXMLfileTest.java index 69c52dd2de..97f10a7ca4 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/LoadOldXMLfileTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/LoadOldXMLfileTest.java @@ -94,7 +94,7 @@ public static String convertStreamToString(InputStream stream) throws IOExceptio BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder sb = new StringBuilder(); - String line = null; + String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/StructureIOTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/StructureIOTest.java index c6a3cdab86..7082c455f5 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/StructureIOTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/StructureIOTest.java @@ -20,14 +20,14 @@ */ package org.biojava.nbio.structure.test.io; -import static org.junit.Assert.*; - -import java.io.IOException; - import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; import org.junit.Test; +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + /** * Test StructureIO methods. * diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/Test4v5a.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/Test4v5a.java index 006396e8cb..c9b65aa83e 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/Test4v5a.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/Test4v5a.java @@ -22,9 +22,6 @@ //import static org.junit.Assert.*; -import java.io.IOException; - - import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.align.util.AtomCache; @@ -32,6 +29,8 @@ import org.junit.Ignore; import org.junit.Test; +import java.io.IOException; + /** * Test for a difficult large mmCIF file (a ribosome) with many 2-letter chain ids. * Both tests are set to Ignore because the parsing of the file takes too long. diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestBioassemblies.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestBioassemblies.java index 23a73a7ae8..b311b10917 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestBioassemblies.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestBioassemblies.java @@ -20,11 +20,6 @@ */ package org.biojava.nbio.structure.test.io; -import static org.junit.Assert.*; - -import java.io.IOException; -import java.util.List; - import org.biojava.nbio.structure.Chain; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; @@ -32,6 +27,11 @@ import org.biojava.nbio.structure.align.util.AtomCache; import org.junit.Test; +import java.io.IOException; +import java.util.List; + +import static org.junit.Assert.*; + public class TestBioassemblies { @@ -39,10 +39,9 @@ public class TestBioassemblies { /** * A test for an NMR structure * @throws StructureException - * @throws IOException - */ + */ @Test - public void test1E17() throws IOException, StructureException { + public void test1E17() throws StructureException { AtomCache prevAtomCache = StructureIO.getAtomCache(); @@ -72,10 +71,9 @@ public void test1E17() throws IOException, StructureException { /** * A test for an entry with a biounit that is a subset of the AU * @throws StructureException - * @throws IOException - */ + */ @Test - public void test4TTX() throws IOException, StructureException { + public void test4TTX() throws StructureException { AtomCache prevAtomCache = StructureIO.getAtomCache(); AtomCache cache = new AtomCache(); @@ -145,11 +143,10 @@ public void test1M4X() throws IOException, StructureException { /** * A difficult case: see http://www.mail-archive.com/jmol-users@lists.sourceforge.net/msg25927.html - * @throws IOException * @throws StructureException */ @Test - public void test4OPJ() throws IOException, StructureException { + public void test4OPJ() throws StructureException { AtomCache prevAtomCache = StructureIO.getAtomCache(); AtomCache cache = new AtomCache(); @@ -191,8 +188,8 @@ public void test4OPJ() throws IOException, StructureException { List model = multiModelBioAssemblies.get(0).getModel(modelIdx); for (Chain c:model) { System.out.println(c.getId()+" "+c.getName()); - assertTrue(!c.getId().contains("_")); - assertTrue(!c.getName().contains("_")); + assertFalse(c.getId().contains("_")); + assertFalse(c.getName().contains("_")); } } diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestCrystallographicMetadata.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestCrystallographicMetadata.java index 26f83b7a28..f52a6d2524 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestCrystallographicMetadata.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestCrystallographicMetadata.java @@ -20,12 +20,12 @@ */ package org.biojava.nbio.structure.test.io; -import org.junit.Test; -import static org.junit.Assert.*; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.align.util.AtomCache; +import org.junit.Test; + +import static org.junit.Assert.*; /** * A test for the parsing of some crystallographic metadata: non standard space group and non standard coordinate frame convention. diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestLongPdbVsMmCifParsing.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestLongPdbVsMmCifParsing.java index daadcc7023..efcc5686f8 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestLongPdbVsMmCifParsing.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestLongPdbVsMmCifParsing.java @@ -26,11 +26,7 @@ import org.biojava.nbio.structure.io.LocalPDBDirectory.ObsoleteBehavior; import org.biojava.nbio.structure.quaternary.BioAssemblyInfo; import org.biojava.nbio.structure.xtal.CrystalCell; -import org.junit.After; -import org.junit.BeforeClass; -import org.junit.ComparisonFailure; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -100,9 +96,9 @@ public static void setUpBeforeClass() { (cache.getPath().equals(System.getProperty("java.io.tmpdir")+File.separator)) ) { throw new IllegalArgumentException("PDB_DIR has not been set or it is set to the default temp directory. Please set PDB_DIR to run this test"); - }; + } - params = new FileParsingParameters(); + params = new FileParsingParameters(); cache.setFileParsingParams(params); cache.setObsoleteBehavior(ObsoleteBehavior.THROW_EXCEPTION); } @@ -130,7 +126,7 @@ public void testVeryLongPdbVsMmCif() throws IOException, StructureException { @Ignore @Test public void testSingle() throws IOException, StructureException { - testAll(Arrays.asList("4kro")); + testAll(Collections.singletonList("4kro")); } @After @@ -141,7 +137,7 @@ public void printInfo() { private void testAll(List pdbIds) throws IOException, StructureException { - pdbIdsWithMismatchingMolIds = new HashSet(); + pdbIdsWithMismatchingMolIds = new HashSet<>(); long start = System.currentTimeMillis(); @@ -229,7 +225,10 @@ private void testStructureMethods(Structure sPdb, Structure sCif) { // sugar polymers are not in pdb at all: we avoid them boolean canCompareEntityCounts = true; for (EntityInfo e:sCif.getEntityInfos()) { - if (e.getDescription().contains("SUGAR")) canCompareEntityCounts = false; + if (e.getDescription().contains("SUGAR")) { + canCompareEntityCounts = false; + break; + } } if (canCompareEntityCounts) { int entCountCif = 0; @@ -358,7 +357,7 @@ private void testHeader(Structure sPdb, Structure sCif) { if (ciPdb.getNcsOperators()==null) { - assertTrue(ciCif.getNcsOperators()==null); + assertNull(ciCif.getNcsOperators()); } else { Matrix4d[] ncsOpersPdb = ciPdb.getNcsOperators(); @@ -393,18 +392,19 @@ private void testHeader(Structure sPdb, Structure sCif) { hPdb.getNrBioAssemblies(),batPdb.size()); assertEquals("Size of bioassemblies maps don't coincide",batPdb.size(), batCif.size()); - for (int id:batPdb.keySet()) { + for (Map.Entry entry : batPdb.entrySet()) { + int id = entry.getKey(); assertTrue("Bioassembly id is not contained in mmCIF",batCif.containsKey(id)); // there's an inconsistency in 4amh pdb vs mmCIF in mmSize if (sPdb.getPDBCode().equalsIgnoreCase("4amh")) continue; assertEquals("Macromolecular size of assembly "+id+" doesn't coincide", - batPdb.get(id).getMacromolecularSize(), batCif.get(id).getMacromolecularSize()); + entry.getValue().getMacromolecularSize(), batCif.get(id).getMacromolecularSize()); } } } - private void testChains(Structure sPdb, Structure sCif) throws StructureException { + private void testChains(Structure sPdb, Structure sCif) { assertNotNull(sPdb.getChains()); assertNotNull(sCif.getChains()); @@ -432,7 +432,7 @@ private void testChains(Structure sPdb, Structure sCif) throws StructureExceptio - Set chainIds = new TreeSet(); + Set chainIds = new TreeSet<>(); for (Chain chain:sPdb.getPolyChains()){ chainIds.add(chain.getName()); } @@ -601,7 +601,7 @@ private List readTestSetFile(String testSetFile) throws IOException { InputStream inStream = this.getClass().getResourceAsStream(testSetFile); BufferedReader br = new BufferedReader(new InputStreamReader(inStream)); - List list = new ArrayList(); + List list = new ArrayList<>(); String line; while ((line=br.readLine())!=null) { diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestNcsOpsParsing.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestNcsOpsParsing.java index 390d68eab7..6ccb5e9fb8 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestNcsOpsParsing.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestNcsOpsParsing.java @@ -20,18 +20,17 @@ */ package org.biojava.nbio.structure.test.io; -import static org.junit.Assert.*; - -import java.io.IOException; - -import javax.vecmath.Matrix4d; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.align.util.AtomCache; import org.junit.Test; +import javax.vecmath.Matrix4d; +import java.io.IOException; + +import static org.junit.Assert.*; + public class TestNcsOpsParsing { /** diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestSeqResParsing.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestSeqResParsing.java index de6c072719..3e45656211 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestSeqResParsing.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestSeqResParsing.java @@ -24,16 +24,11 @@ package org.biojava.nbio.structure.test.io; -import java.io.IOException; - -import org.biojava.nbio.structure.AminoAcid; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.junit.Test; -import org.biojava.nbio.structure.StructureIO; + +import java.io.IOException; import static org.junit.Assert.*; diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestStructWithMultiparentChemComp.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestStructWithMultiparentChemComp.java index cbedb5b108..7eefa0e010 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestStructWithMultiparentChemComp.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/TestStructWithMultiparentChemComp.java @@ -20,14 +20,13 @@ */ package org.biojava.nbio.structure.test.io; -import org.junit.Test; -import static org.junit.Assert.*; - - import org.biojava.nbio.structure.Chain; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.align.util.AtomCache; +import org.junit.Test; + +import static org.junit.Assert.*; public class TestStructWithMultiparentChemComp { diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/cif/CifFileConsumerIntegrationTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/cif/CifFileConsumerIntegrationTest.java index 9101ee5524..fc03ec003b 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/cif/CifFileConsumerIntegrationTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/cif/CifFileConsumerIntegrationTest.java @@ -1,17 +1,7 @@ package org.biojava.nbio.structure.test.io.cif; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.DBRef; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.GroupType; -import org.biojava.nbio.structure.PDBHeader; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.io.BcifFileReader; -import org.biojava.nbio.structure.io.CifFileReader; -import org.biojava.nbio.structure.io.FileParsingParameters; -import org.biojava.nbio.structure.io.LocalPDBDirectory; -import org.biojava.nbio.structure.io.PDBFileParser; +import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.io.*; import org.junit.Test; import java.io.IOException; diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/cif/CifFileSupplierIntegrationTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/cif/CifFileSupplierIntegrationTest.java index 03e2f6f060..16076c1fea 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/cif/CifFileSupplierIntegrationTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/io/cif/CifFileSupplierIntegrationTest.java @@ -1,17 +1,6 @@ package org.biojava.nbio.structure.test.io.cif; -import org.biojava.nbio.structure.AminoAcidImpl; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.AtomImpl; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.ChainImpl; -import org.biojava.nbio.structure.Element; -import org.biojava.nbio.structure.EntityInfo; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureImpl; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.io.cif.CifFileConverter; import org.junit.Test; diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/BerkeleyScopInstallationTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/BerkeleyScopInstallationTest.java index 96c01ae03c..5d47b6bbdb 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/BerkeleyScopInstallationTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/BerkeleyScopInstallationTest.java @@ -42,7 +42,7 @@ public BerkeleyScopInstallationTest(String tag,ScopDatabase scop) { } @Parameters(name="{0}") public static Collection availableDatabases() { - ArrayList databases = new ArrayList(); + ArrayList databases = new ArrayList<>(); ScopInstallation scop; for(String version : new String[] { diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/RemoteScopInstallationTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/RemoteScopInstallationTest.java index 2abe7d63ae..74cd9df51c 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/RemoteScopInstallationTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/RemoteScopInstallationTest.java @@ -46,7 +46,7 @@ public RemoteScopInstallationTest(String tag,ScopDatabase scop) { //@Parameters @Parameters(name="{0}") public static Collection availableDatabases() { - ArrayList databases = new ArrayList(); + ArrayList databases = new ArrayList<>(); RemoteScopInstallation scop; for(String version : new String[] { ScopFactory.LATEST_VERSION, diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopDatabaseTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopDatabaseTest.java index 2a34d017f1..3813498846 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopDatabaseTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopDatabaseTest.java @@ -46,8 +46,8 @@ */ @RunWith(Parameterized.class) public abstract class ScopDatabaseTest { - protected ScopDatabase scop; - String tag; + protected final ScopDatabase scop; + final String tag; /** * @@ -94,7 +94,7 @@ public void traverseHierarchy() desc = scop.getScopDescriptionBySunid(node.getSunid()); assertEquals(tag,46487,node.getSunid()); assertEquals(tag,"-",desc.getName()); - assertTrue(tag,Pattern.matches("Human \\(Homo sapiens\\)( \\[TaxId: 9606\\])?",desc.getDescription())); + assertTrue(tag,Pattern.matches("Human \\(Homo sapiens\\)( \\[TaxId: 9606])?",desc.getDescription())); assertEquals(tag,"a.1.1.2",desc.getClassificationId()); node = scop.getScopNode(node.getParentSunid()); diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopInstallationTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopInstallationTest.java index c1c940da84..c1b7e3be5b 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopInstallationTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopInstallationTest.java @@ -47,7 +47,7 @@ public ScopInstallationTest(String tag,ScopDatabase scop) { //@Parameters @Parameters(name="{0}") public static Collection availableDatabases() { - ArrayList databases = new ArrayList(); + ArrayList databases = new ArrayList<>(); ScopInstallation scop; for(String version : new String[] { diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopTest.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopTest.java index f7d5e8fdee..305916aea5 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopTest.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/scop/ScopTest.java @@ -20,11 +20,7 @@ */ package org.biojava.nbio.structure.test.scop; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.GroupIterator; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.scop.ScopDatabase; import org.biojava.nbio.structure.scop.ScopDomain; @@ -35,7 +31,8 @@ import java.io.IOException; import java.util.List; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; //import org.biojava.nbio.structure.scop.RemoteScopInstallation; @@ -43,7 +40,7 @@ public class ScopTest { - boolean debug = false; + final boolean debug = false; @Test public void testLocalScop() throws IOException, StructureException{ @@ -98,11 +95,11 @@ private void runSCOPTests() throws IOException, StructureException { List domains = scop.getDomainsForPDB("4HHB"); - assertTrue(domains.size() == 4); + assertEquals(4, domains.size()); // test case sensitivity; List domains2 = scop.getDomainsForPDB("4hhb"); - assertTrue(domains2.size() == domains.size()); + assertEquals(domains2.size(), domains.size()); //System.out.println(domains); @@ -110,7 +107,7 @@ private void runSCOPTests() throws IOException, StructureException { String scop1m02 = "d1m02a_ 1m02 A: k.36.1.1 74353 cl=58788,cf=75796,sf=75797,fa=75798,dm=75799,sp=75800,px=74353"; List domains1m02 = scop.getDomainsForPDB("1m02"); - assertTrue(domains1m02.size() == 1); + assertEquals(1, domains1m02.size()); ScopDomain d1 = domains1m02.get(0); assertNotNull(d1); @@ -119,7 +116,7 @@ private void runSCOPTests() throws IOException, StructureException { List domains1cdg = scop.getDomainsForPDB("1CDG"); - assertTrue(domains1cdg.size() == 4); + assertEquals(4, domains1cdg.size()); ScopDomain d2 = domains1cdg.get(0); assertEquals("Wrong SCOP Id", "d1cdga1", d2.getScopId()); AtomCache cache = new AtomCache(); @@ -146,7 +143,7 @@ private void runSCOPTests() throws IOException, StructureException { // check a domain with multiple ranges List domains1xzp = scop.getDomainsForPDB("1xzp"); - assertTrue(domains1xzp.size() ==4 ); + assertEquals(4, domains1xzp.size()); @@ -163,7 +160,7 @@ private void runSCOPTests() throws IOException, StructureException { // check insertion codes List domains2bq6 = scop.getDomainsForPDB("2bq6"); - assertTrue(domains2bq6.size() == 2); + assertEquals(2, domains2bq6.size()); ScopDomain target = scop.getDomainByScopID("d2bq6a1"); assertNotNull(target); diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/symmetry/TestQuatSymmetryDetectorExamples.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/symmetry/TestQuatSymmetryDetectorExamples.java index a5cd0a9fb4..9ceec479d9 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/symmetry/TestQuatSymmetryDetectorExamples.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/symmetry/TestQuatSymmetryDetectorExamples.java @@ -20,11 +20,6 @@ */ package org.biojava.nbio.structure.test.symmetry; -import static org.junit.Assert.*; - -import java.io.IOException; -import java.util.*; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; @@ -45,6 +40,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.*; + /** * Test the {@link QuatSymmetryDetector} algorithm for symmetry detection on a * variety of structures with different symmetries. @@ -267,7 +270,7 @@ public void testLocal() throws IOException, StructureException { for (QuatSymmetryResults local:foundLocal) { logger.info("Found stoichiometry "+local.getStoichiometry().toString()+" with symmetry "+local.getSymmetry()); assertTrue("Stoichiometry "+local.getStoichiometry().toString()+" not expected for "+testIds.get(iTest), - refLocal.keySet().contains(local.getStoichiometry().toString())); + refLocal.containsKey(local.getStoichiometry().toString())); assertEquals("Symmetry "+local.getSymmetry()+" with stoichiometry "+local.getStoichiometry().toString()+ " not expected for "+testIds.get(iTest), diff --git a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/xtal/TestCrystalBuilder.java b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/xtal/TestCrystalBuilder.java index 898e108a8e..710cac54f6 100644 --- a/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/xtal/TestCrystalBuilder.java +++ b/biojava-integrationtest/src/test/java/org/biojava/nbio/structure/test/xtal/TestCrystalBuilder.java @@ -33,7 +33,7 @@ import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; public class TestCrystalBuilder { diff --git a/biojava-modfinder/pom.xml b/biojava-modfinder/pom.xml index 5367030867..a7ba91e08a 100644 --- a/biojava-modfinder/pom.xml +++ b/biojava-modfinder/pom.xml @@ -58,15 +58,7 @@ - - org.apache.maven.plugins - maven-jar-plugin - - - demo/** - - - + org.apache.maven.plugins diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/phosphosite/Dataset.java b/biojava-modfinder/src/main/java/org/biojava/nbio/phosphosite/Dataset.java index 71604d9bb3..a993a42ace 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/phosphosite/Dataset.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/phosphosite/Dataset.java @@ -82,11 +82,11 @@ public File[] getLocalFiles(){ File dir = getLocalDir(); - List files = new ArrayList(); + List files = new ArrayList<>(); for ( String f : rfiles) { - int slashIndex = f.lastIndexOf("/"); + int slashIndex = f.lastIndexOf('/'); String fileName = f.substring(slashIndex); @@ -98,7 +98,7 @@ public File[] getLocalFiles(){ } - return files.toArray(new File[files.size()]); + return files.toArray(new File[0]); } @@ -135,7 +135,7 @@ public void download(){ try { - int slashIndex = f.lastIndexOf("/"); + int slashIndex = f.lastIndexOf('/'); String fileName = f.substring(slashIndex); @@ -170,7 +170,7 @@ public void downloadFile(URL u, File localFile) throws IOException { FileOutputStream w = new FileOutputStream(tmp); - int i= 0; + int i; byte[] bytesIn = new byte[300000]; while ((i = in.read(bytesIn)) >= 0) { w.write(bytesIn,0,i); diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/phosphosite/Site.java b/biojava-modfinder/src/main/java/org/biojava/nbio/phosphosite/Site.java index ca5e4a5f2f..bb3c1f52e4 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/phosphosite/Site.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/phosphosite/Site.java @@ -25,6 +25,7 @@ import java.io.*; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.zip.GZIPInputStream; @@ -48,11 +49,11 @@ public static List parseSites(File f) throws IOException { Reader decoder = new InputStreamReader(gzipStream); BufferedReader buf = new BufferedReader(decoder); - String line = null; + String line; - List data = new ArrayList(); + List data = new ArrayList<>(); - List headerFields = null; + List headerFields; int proteinIndex = -1; int uniprotIndex = -1; @@ -131,11 +132,7 @@ public static List parseSites(File f) throws IOException { private static List parseHeaderFields(String line) { String[] spl = line.split("\t"); - List h = new ArrayList(); - for (String s: spl){ - h.add(s); - - } + List h = new ArrayList<>(Arrays.asList(spl)); return h; } @@ -215,26 +212,24 @@ public void setOrganism(String organism) { @Override public String toString() { - StringBuffer s = new StringBuffer(); + StringBuilder s = new StringBuilder(); - s.append("Site{" + - "protein='" + protein + '\''); + s.append("Site{" + "protein='").append(protein).append('\''); if ( uniprot != null) - s.append(", uniprot='" + uniprot + '\'' ); + s.append(", uniprot='").append(uniprot).append('\''); if ( geneSymb != null) - s.append( - ", geneSymb='" + geneSymb + '\'' ); + s.append(", geneSymb='").append(geneSymb).append('\''); if (chrLoc != null) - s.append(", chrLoc='" + chrLoc + '\'' ); + s.append(", chrLoc='").append(chrLoc).append('\''); if (modType != null) - s.append(", modType='" + modType + '\'' ); + s.append(", modType='").append(modType).append('\''); if (residue != null) - s.append( ", residue='" + residue + '\'' ); + s.append(", residue='").append(residue).append('\''); if ( group != null) - s.append(", group='" + group + '\'' ); + s.append(", group='").append(group).append('\''); if (organism != null) - s.append(", organism='" + organism + '\'' ); + s.append(", organism='").append(organism).append('\''); s.append( '}'); diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/Component.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/Component.java index ff4b0abb82..4a35ff5218 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/Component.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/Component.java @@ -50,10 +50,10 @@ public final class Component { */ private static void lazyInit() { if (components==null) { - components = new HashSet(); - nonTerminalComps = new HashMap, Component>(); - nTerminalAminoAcids = new HashMap, Component>(); - cTerminalAminoAcids = new HashMap, Component>(); + components = new HashSet<>(); + nonTerminalComps = new HashMap<>(); + nTerminalAminoAcids = new HashMap<>(); + cTerminalAminoAcids = new HashMap<>(); } } diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationCategory.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationCategory.java index 89d9bd9720..170cf5cdbf 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationCategory.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationCategory.java @@ -93,7 +93,7 @@ public boolean isCrossLink() { /** * The variable is the same as the <Type> in the ptm_list XML file. */ - private String label; + private final String label; private String desc; @@ -106,9 +106,9 @@ public static ModificationCategory getByLabel(String label) { return mapLabelCat.get(label); } - private static Map mapLabelCat; + private static final Map mapLabelCat; static { - mapLabelCat = new HashMap(); + mapLabelCat = new HashMap<>(); for (ModificationCategory cat:ModificationCategory.values()) { mapLabelCat.put(cat.label, cat); } diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationCondition.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationCondition.java index 3afc2f171a..ce4b0a491b 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationCondition.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationCondition.java @@ -37,11 +37,11 @@ public interface ModificationCondition { * * @return the involved components. */ - public List getComponents(); + List getComponents(); /** * * @return a list of all {Link ModificationLinkage}s. */ - public List getLinkages(); + List getLinkages(); } diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationConditionImpl.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationConditionImpl.java index 2af28ed33f..5cb7857bdd 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationConditionImpl.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationConditionImpl.java @@ -49,7 +49,7 @@ public ModificationConditionImpl(final List components, if (components.size() > 1) { - Set indices = new HashSet(); + Set indices = new HashSet<>(); for (ModificationLinkage linkage : linkages) { indices.add(linkage.getIndexOfComponent1()); indices.add(linkage.getIndexOfComponent2()); diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationOccurrenceType.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationOccurrenceType.java index 30a4bad4e0..fde9dcee68 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationOccurrenceType.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ModificationOccurrenceType.java @@ -60,7 +60,7 @@ public String toString() { /** * The variable is the same as the <Occurrence> in the ptm_list XML file. */ - private String label; + private final String label; /** * @@ -71,9 +71,9 @@ public static ModificationOccurrenceType getByLabel(String label) { return mapLabelOcc.get(label); } - private static Map mapLabelOcc; + private static final Map mapLabelOcc; static { - mapLabelOcc = new HashMap(); + mapLabelOcc = new HashMap<>(); for (ModificationOccurrenceType occ:ModificationOccurrenceType.values()) { mapLabelOcc.put(occ.label, occ); } diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModification.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModification.java index b173f63f11..6f5b15633f 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModification.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModification.java @@ -39,84 +39,84 @@ public interface ProteinModification { * * @return modification id. */ - public String getId(); + String getId(); /** * * @return Protein Data Bank Chemical Component ID. */ - public String getPdbccId(); + String getPdbccId(); /** * * @return Protein Data Bank Chemical Component name. */ - public String getPdbccName(); + String getPdbccName(); /** * * @return RESID ID. */ - public String getResidId(); + String getResidId(); /** * * @return RESID name. */ - public String getResidName(); + String getResidName(); /** * * @return PSI-MOD ID. */ - public String getPsimodId(); + String getPsimodId(); /** * * @return PSI-MOD name. */ - public String getPsimodName(); + String getPsimodName(); /** * * @return Systematic name. */ - public String getSystematicName(); + String getSystematicName(); /** * * @return Description. */ - public String getDescription(); + String getDescription(); /** * * @return a set of keywords. */ - public Set getKeywords(); + Set getKeywords(); /** * * @return {@link ModificationCondition} */ - public ModificationCondition getCondition(); + ModificationCondition getCondition(); /** * * @return formula of the modified residue. */ - public String getFormula(); + String getFormula(); /** * * @return the modification category. */ - public ModificationCategory getCategory(); + ModificationCategory getCategory(); /** * * @return the modification occurrence type. */ - public ModificationOccurrenceType getOccurrenceType(); + ModificationOccurrenceType getOccurrenceType(); } diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModificationImpl.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModificationImpl.java index a06ee41936..dd4f11d41f 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModificationImpl.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModificationImpl.java @@ -251,7 +251,7 @@ public static class Builder { private String sysName = null; private String formula = null; - private Set keywords = new LinkedHashSet(); + private Set keywords = new LinkedHashSet<>(); /** * @@ -289,7 +289,7 @@ public Builder(final ProteinModification copyFrom) { this.sysName = copyFrom.getSystematicName(); this.formula = copyFrom.getFormula(); - this.keywords = new LinkedHashSet(copyFrom.getKeywords()); + this.keywords = new LinkedHashSet<>(copyFrom.getKeywords()); } public Builder setCategory(final ModificationCategory cat) { @@ -448,7 +448,7 @@ private ProteinModificationImpl(Builder builder) { this.sysName = builder.sysName; this.formula = builder.formula; - this.keywords = new LinkedHashSet(builder.keywords); + this.keywords = new LinkedHashSet<>(builder.keywords); } @Override diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModificationRegistry.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModificationRegistry.java index 54babab8e1..95e08fe90f 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModificationRegistry.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/ProteinModificationRegistry.java @@ -55,7 +55,7 @@ public class ProteinModificationRegistry { private static Map> byCategory = null; private static Map> byOccurrenceType = null; - private static String DIR_XML_PTM_LIST = "ptm_list.xml"; + private static final String DIR_XML_PTM_LIST = "ptm_list.xml"; @@ -109,22 +109,22 @@ private static synchronized void lazyInit() { private static synchronized void lazyInit(InputStream inStream) { if (registry==null) { - registry = new HashSet(); - byId = new HashMap(); - byResidId = new HashMap>(); - byPsimodId = new HashMap>(); - byPdbccId = new HashMap>(); - byKeyword = new HashMap>(); - byComponent = new HashMap>(); - byCategory = new EnumMap>( + registry = new HashSet<>(); + byId = new HashMap<>(); + byResidId = new HashMap<>(); + byPsimodId = new HashMap<>(); + byPdbccId = new HashMap<>(); + byKeyword = new HashMap<>(); + byComponent = new HashMap<>(); + byCategory = new EnumMap<>( ModificationCategory.class); for (ModificationCategory cat:ModificationCategory.values()) { - byCategory.put(cat, new HashSet()); + byCategory.put(cat, new HashSet<>()); } - byOccurrenceType = new EnumMap>( + byOccurrenceType = new EnumMap<>( ModificationOccurrenceType.class); for (ModificationOccurrenceType occ:ModificationOccurrenceType.values()) { - byOccurrenceType.put(occ, new HashSet()); + byOccurrenceType.put(occ, new HashSet<>()); } registerCommonProteinModifications(inStream); } @@ -156,50 +156,30 @@ public static void register(final ProteinModification modification) { ModificationCondition condition = modification.getCondition(); List comps = condition.getComponents(); for (Component comp:comps) { - Set mods = byComponent.get(comp); - if (mods==null) { - mods = new HashSet(); - byComponent.put(comp, mods); - } + Set mods = byComponent.computeIfAbsent(comp, k -> new HashSet<>()); mods.add(modification); } String pdbccId = modification.getPdbccId(); if (pdbccId!=null) { - Set mods = byPdbccId.get(pdbccId); - if (mods==null) { - mods = new HashSet(); - byPdbccId.put(pdbccId, mods); - } + Set mods = byPdbccId.computeIfAbsent(pdbccId, k -> new HashSet<>()); mods.add(modification); } String residId = modification.getResidId(); if (residId!=null) { - Set mods = byResidId.get(residId); - if (mods==null) { - mods = new HashSet(); - byResidId.put(residId, mods); - } + Set mods = byResidId.computeIfAbsent(residId, k -> new HashSet<>()); mods.add(modification); } String psimodId = modification.getPsimodId(); if (psimodId!=null) { - Set mods = byPsimodId.get(psimodId); - if (mods==null) { - mods = new HashSet(); - byPsimodId.put(psimodId, mods); - } + Set mods = byPsimodId.computeIfAbsent(psimodId, k -> new HashSet<>()); mods.add(modification); } for (String keyword : modification.getKeywords()) { - Set mods = byKeyword.get(keyword); - if (mods==null) { - mods = new HashSet(); - byKeyword.put(keyword, mods); - } + Set mods = byKeyword.computeIfAbsent(keyword, k -> new HashSet<>()); mods.add(modification); } } @@ -308,7 +288,7 @@ public static Set getByComponent(final Component comp1, if (comps.length==0) { return Collections.unmodifiableSet(mods); } else { - Set ret = new HashSet(mods); + Set ret = new HashSet<>(mods); for (Component comp:comps) { mods = byComponent.get(comp); if (mods==null) { diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ComponentXMLConverter.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ComponentXMLConverter.java index 138488b650..45ce14a428 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ComponentXMLConverter.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ComponentXMLConverter.java @@ -20,8 +20,8 @@ */ package org.biojava.nbio.protmod.io; -import org.biojava.nbio.protmod.Component; import org.biojava.nbio.core.util.PrettyXMLWriter; +import org.biojava.nbio.protmod.Component; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; @@ -46,8 +46,8 @@ public static String toXML(Component component) throws IOException{ public static void toXML(Component component, PrettyXMLWriter xml) throws IOException{ xml.openTag("component"); - xml.attribute("nTerminal" , component.isNTerminal()+""); - xml.attribute("cTerminal", component.isCTerminal()+""); + xml.attribute("nTerminal" , String.valueOf(component.isNTerminal())); + xml.attribute("cTerminal", String.valueOf(component.isCTerminal())); for (String pdbccId : component.getPdbccIds()){ xml.openTag("pdbccID"); xml.attribute("id", pdbccId); @@ -74,7 +74,7 @@ public static Component fromXML(Node componentN) { boolean isNTerminal = Boolean.parseBoolean(nTerminalS); boolean isCTerminal = Boolean.parseBoolean(cTerminalS); - SetpdbccIds = new HashSet(); + SetpdbccIds = new HashSet<>(); NodeList valList = componentN.getChildNodes(); int numChildren = valList.getLength(); diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ModifiedCompoundXMLConverter.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ModifiedCompoundXMLConverter.java index fb76e02340..6867d454e1 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ModifiedCompoundXMLConverter.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ModifiedCompoundXMLConverter.java @@ -20,10 +20,10 @@ */ package org.biojava.nbio.protmod.io; +import org.biojava.nbio.core.util.PrettyXMLWriter; import org.biojava.nbio.protmod.ProteinModification; import org.biojava.nbio.protmod.ProteinModificationRegistry; import org.biojava.nbio.protmod.structure.*; -import org.biojava.nbio.core.util.PrettyXMLWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; @@ -31,7 +31,6 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; -import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import javax.xml.parsers.DocumentBuilder; @@ -110,7 +109,7 @@ public static ModifiedCompound fromXML(String xml){ ProteinModification modification = null; //Collection linkages = new ArrayList(); StructureAtomLinkage[] linkages = null; - List structureGroups = new ArrayList(); + List structureGroups = new ArrayList<>(); try { //Convert string to XML document @@ -142,41 +141,41 @@ public static ModifiedCompound fromXML(String xml){ if(!listOfConditions.hasAttributes()) continue; - if ( listOfConditions.getNodeName().equals("proteinModification")) { - //modification = ProteinModificationXMLConverter.fromXML(listOfConditions); - String modId = getAttribute(listOfConditions, "id"); - modification = ProteinModificationRegistry.getById(modId); - if (modification==null) { - logger.warn("Error: no modification information."); - } - } else if ( listOfConditions.getNodeName().equals("linkage")) { - double dist = Double.parseDouble(getAttribute(listOfConditions, "distance")); - int pos = Integer.parseInt(getAttribute(listOfConditions,"pos")); - int total = Integer.parseInt(getAttribute(listOfConditions,"total")); - if ( linkages == null) - linkages = new StructureAtomLinkage[total]; - - StructureAtom atom1 = getAtom("atom1", listOfConditions); - StructureAtom atom2 = getAtom("atom2",listOfConditions); - StructureAtomLinkage linkage = new StructureAtomLinkage(atom1, atom2, dist); - //linkages.add(linkage); - linkages[pos] = linkage; - } else if (listOfConditions.getNodeName().equals("structureGroup")) { - StructureGroup group = StructureGroupXMLConverter.fromXML(listOfConditions); - structureGroups.add(group); + switch (listOfConditions.getNodeName()) { + case "proteinModification": + //modification = ProteinModificationXMLConverter.fromXML(listOfConditions); + String modId = getAttribute(listOfConditions, "id"); + modification = ProteinModificationRegistry.getById(modId); + if (modification == null) { + logger.warn("Error: no modification information."); + } + break; + case "linkage": + double dist = Double.parseDouble(getAttribute(listOfConditions, "distance")); + int pos = Integer.parseInt(getAttribute(listOfConditions, "pos")); + int total = Integer.parseInt(getAttribute(listOfConditions, "total")); + if (linkages == null) + linkages = new StructureAtomLinkage[total]; + + StructureAtom atom1 = getAtom("atom1", listOfConditions); + StructureAtom atom2 = getAtom("atom2", listOfConditions); + StructureAtomLinkage linkage = new StructureAtomLinkage(atom1, atom2, dist); + //linkages.add(linkage); + linkages[pos] = linkage; + break; + case "structureGroup": + StructureGroup group = StructureGroupXMLConverter.fromXML(listOfConditions); + structureGroups.add(group); // logger.info("structureGroups size:" + structureGroups.size()); + break; } } } } catch (SAXParseException err) { logger.error("** Parsing error, line: {}, uri: {}", err.getLineNumber (), err.getSystemId (), err); - } - catch (SAXException e) { + } catch (Throwable e) { logger.error("Exception: ", e); } - catch (Throwable t) { - logger.error("Exception: ", t); - } if ( linkages != null) { diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ProteinModificationXmlReader.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ProteinModificationXmlReader.java index 0a1c5f36e9..6f245e5c5a 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ProteinModificationXmlReader.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/ProteinModificationXmlReader.java @@ -110,7 +110,7 @@ public static void registerProteinModificationFromXml(InputStream isXml) } // condition - ModificationCondition condition = null; + ModificationCondition condition; { nodes = infoNodes.get("Condition"); if (nodes==null || nodes.size()!=1) { @@ -121,14 +121,14 @@ public static void registerProteinModificationFromXml(InputStream isXml) Node compsNode = nodes.get(0); // keep track of the labels of component indices - Map mapLabelComp = new HashMap(); + Map mapLabelComp = new HashMap<>(); Map> compInfoNodes = getChildNodes(compsNode); // components List compNodes = compInfoNodes.get("Component"); int sizeComp = compNodes.size(); - List comps = new ArrayList(sizeComp); + List comps = new ArrayList<>(sizeComp); for (int iComp=0; iComp compIds = new HashSet(); + Set compIds = new HashSet<>(); List compIdNodes = getChildNodes(compNode).get("Id"); if (compIdNodes!=null) { for (Node compIdNode : compIdNodes) { @@ -199,7 +199,7 @@ public static void registerProteinModificationFromXml(InputStream isXml) List linkages = null; if (bondNodes!=null) { int sizeBonds = bondNodes.size(); - linkages = new ArrayList(sizeBonds); + linkages = new ArrayList<>(sizeBonds); for (int iBond=0; iBond> bondChildNodes = getChildNodes(bondNode); @@ -305,12 +305,16 @@ public static void registerProteinModificationFromXml(InputStream isXml) xrefName = xrefNode.get(0).getTextContent(); } - if (xrefDb.equals("PDBCC")) { - modBuilder.setPdbccId(xrefId).setPdbccName(xrefName); - } else if (xrefDb.equals("RESID")) { - modBuilder.setResidId(xrefId).setResidName(xrefName); - } else if (xrefDb.equals("PSI-MOD")) { - modBuilder.setPsimodId(xrefId).setPsimodName(xrefName); + switch (xrefDb) { + case "PDBCC": + modBuilder.setPdbccId(xrefId).setPdbccName(xrefName); + break; + case "RESID": + modBuilder.setResidId(xrefId).setResidName(xrefName); + break; + case "PSI-MOD": + modBuilder.setPsimodId(xrefId).setPsimodName(xrefName); + break; } } } // end of cross references @@ -342,7 +346,7 @@ private static Map> getChildNodes(Node parent) { if (parent==null) return Collections.emptyMap(); - Map> children = new HashMap>(); + Map> children = new HashMap<>(); NodeList nodes = parent.getChildNodes(); int nNodes = nodes.getLength(); @@ -352,11 +356,7 @@ private static Map> getChildNodes(Node parent) { continue; String name = node.getNodeName(); - List namesakes = children.get(name); - if (namesakes==null) { - namesakes = new ArrayList(); - children.put(name, namesakes); - } + List namesakes = children.computeIfAbsent(name, k -> new ArrayList<>()); namesakes.add(node); } diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/StructureAtomXMLConverter.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/StructureAtomXMLConverter.java index 08f69725bf..8419c97dd8 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/StructureAtomXMLConverter.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/StructureAtomXMLConverter.java @@ -20,9 +20,9 @@ */ package org.biojava.nbio.protmod.io; +import org.biojava.nbio.core.util.PrettyXMLWriter; import org.biojava.nbio.protmod.structure.StructureAtom; import org.biojava.nbio.protmod.structure.StructureGroup; -import org.biojava.nbio.core.util.PrettyXMLWriter; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/StructureGroupXMLConverter.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/StructureGroupXMLConverter.java index 61a56e3b6b..71cec2c619 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/StructureGroupXMLConverter.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/io/StructureGroupXMLConverter.java @@ -20,9 +20,9 @@ */ package org.biojava.nbio.protmod.io; +import org.biojava.nbio.core.util.PrettyXMLWriter; import org.biojava.nbio.protmod.structure.StructureGroup; import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.core.util.PrettyXMLWriter; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; @@ -36,8 +36,8 @@ public static void toXML(StructureGroup group, PrettyXMLWriter xml) throws IOExc xml.attribute("chainID", group.getChainId()); xml.attribute("pdbName", group.getPDBName()); if ( group.getInsCode() != null) - xml.attribute("insCode",group.getInsCode()+""); - xml.attribute("residueNr", group.getResidueNumber()+""); + xml.attribute("insCode", String.valueOf(group.getInsCode())); + xml.attribute("residueNr", String.valueOf(group.getResidueNumber())); xml.attribute("isAminoAcid", Boolean.toString(group.isAminoAcid())); xml.closeTag("structureGroup"); } @@ -57,7 +57,7 @@ public static StructureGroup fromXML(Node n) { resNum.setInsCode(insCode.charAt(0)); resNum.setSeqNum(Integer.parseInt(resN)); - StructureGroup g = new StructureGroup(resNum, pdbName, Boolean.valueOf(isAminoAcid)); + StructureGroup g = new StructureGroup(resNum, pdbName, Boolean.parseBoolean(isAminoAcid)); return g; } diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ModifiedCompound.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ModifiedCompound.java index 164c3d86d9..5d9937d9d2 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ModifiedCompound.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ModifiedCompound.java @@ -41,32 +41,32 @@ public interface ModifiedCompound { * * @return a description */ - public String getDescription(); + String getDescription(); - public void setDescription(String desc); + void setDescription(String desc); /** * * @return {@link ProteinModificationBean} occurred on the residue. */ - public ProteinModification getModification(); + ProteinModification getModification(); - public void setModification(ProteinModification modi); + void setModification(ProteinModification modi); /** * * @return a set of involved group. */ - public Set getGroups(); + Set getGroups(); - public void setGroups(Set groups); + void setGroups(Set groups); /** * * @param isAminoAcid true if amino acids. * @return a set of involved group of the type. */ - public Set getGroups(boolean isAminoAcid); + Set getGroups(boolean isAminoAcid); @@ -76,13 +76,13 @@ public interface ModifiedCompound { * @see #getLinkedGroupPairs * @see StructureAtomLinkage */ - public Set getAtomLinkages(); + Set getAtomLinkages(); /** Set atom linkages * * @return */ - public void setAtomLinkages(Set linkages); + void setAtomLinkages(Set linkages); /** * Add a linkage. Add new the involved groups first using {@link addGroup}. @@ -90,20 +90,20 @@ public interface ModifiedCompound { * @return true if this linkage was not already contained. * @see StructureAtomLinkage */ - public boolean addAtomLinkage(StructureAtomLinkage linkage); + boolean addAtomLinkage(StructureAtomLinkage linkage); /** * Add a collections of linkages. * @param linkages an atom linkage. */ - public void addAtomLinkages(Collection linkages); + void addAtomLinkages(Collection linkages); /** * * @return true if groups from multiple chains were involved */ - public boolean crossChains(); + boolean crossChains(); } diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ModifiedCompoundImpl.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ModifiedCompoundImpl.java index e42d987e61..8e369f7c17 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ModifiedCompoundImpl.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ModifiedCompoundImpl.java @@ -75,7 +75,7 @@ public ModifiedCompoundImpl ( throw new IllegalArgumentException("Null argument(s)"); } - groups = new HashSet(1); + groups = new HashSet<>(1); groups.add(modifiedResidue); // is it possible that components be added by addLinkage later? @@ -101,7 +101,7 @@ public ModifiedCompoundImpl( ProteinModification modification, throw new IllegalArgumentException("at least one linkage."); } - this.groups = new HashSet(); + this.groups = new HashSet<>(); addAtomLinkages(linkages); @@ -128,7 +128,7 @@ else if (originalModification.getCategory()!=ModificationCategory.UNDEFINED) modification = originalModification; else { int nRes = 0; - Set ligands = new HashSet(); + Set ligands = new HashSet<>(); for (StructureGroup group : groups) { if (group.isAminoAcid()) { nRes ++; @@ -174,7 +174,7 @@ public Set getGroups() { @Override public Set getGroups(boolean isAminoAcid) { - Set result = new HashSet(); + Set result = new HashSet<>(); for (StructureGroup group : groups) { if (group.isAminoAcid() == isAminoAcid) { result.add(group); @@ -194,7 +194,7 @@ public Set getAtomLinkages() { if (atomLinkages==null) { return Collections.emptySet(); } else { - Set result = new HashSet(); + Set result = new HashSet<>(); for (Set linkages : atomLinkages.values()) { result.addAll(linkages); } @@ -218,20 +218,20 @@ public boolean addAtomLinkage(StructureAtomLinkage linkage) { throw new IllegalArgumentException("Null linkage"); } - Set gs = new HashSet(2); + Set gs = new HashSet<>(2); gs.add(linkage.getAtom1().getGroup()); gs.add(linkage.getAtom2().getGroup()); if (atomLinkages==null) { - atomLinkages = new HashMap, Set>(); + atomLinkages = new HashMap<>(); } Set linkages = atomLinkages.get(gs); if (linkages == null) { - linkages = new HashSet(); + linkages = new HashSet<>(); atomLinkages.put(gs, linkages); groups.addAll(gs); // it's possible of new groups - }; + } return linkages.add(linkage); } diff --git a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ProteinModificationIdentifier.java b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ProteinModificationIdentifier.java index fdfd8cf312..63e19579ea 100644 --- a/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ProteinModificationIdentifier.java +++ b/biojava-modfinder/src/main/java/org/biojava/nbio/protmod/structure/ProteinModificationIdentifier.java @@ -267,9 +267,9 @@ public void identify(final List chains, } - residues = new ArrayList(); - List ligands = new ArrayList(); - Map> mapCompGroups = new HashMap>(); + residues = new ArrayList<>(); + List ligands = new ArrayList<>(); + Map> mapCompGroups = new HashMap<>(); for (Chain chain : chains) { @@ -292,7 +292,7 @@ public void identify(final List chains, } logger.warn("No amino acids found for {}. Either you did not parse the PDB file with alignSEQRES records, or this record does not contain any amino acids.", pdbId); } - List modComps = new ArrayList(); + List modComps = new ArrayList<>(); for (ProteinModification mod : potentialModifications) { ModificationCondition condition = mod.getCondition(); @@ -333,10 +333,10 @@ public void identify(final List chains, } private void reset() { - identifiedModifiedCompounds = new LinkedHashSet(); + identifiedModifiedCompounds = new LinkedHashSet<>(); if (recordUnidentifiableModifiedCompounds) { - unidentifiableAtomLinkages = new LinkedHashSet(); - unidentifiableModifiedResidues = new LinkedHashSet(); + unidentifiableAtomLinkages = new LinkedHashSet<>(); + unidentifiableModifiedResidues = new LinkedHashSet<>(); } } @@ -392,7 +392,7 @@ private void identifyAdditionalAttachments(ModifiedCompound mc, // ligands to amino acid bonds for same modification of unknown category // will be combined in mergeModComps() // TODO: how about chain-chain links? - List identifiedGroups = new ArrayList(); + List identifiedGroups = new ArrayList<>(); for (StructureGroup num : mc.getGroups(false)) { Group group; try { @@ -464,7 +464,7 @@ private Group getGroup(StructureGroup num, List chains) throws StructureE * Merge identified modified compounds if linked. */ private void mergeModComps(List modComps) { - TreeSet remove = new TreeSet(); + TreeSet remove = new TreeSet<>(); int n = modComps.size(); for (int icurr=1; icurr modComps, List ligands) { // first put identified linkages in a map for fast query - Set identifiedLinkages = new HashSet(); + Set identifiedLinkages = new HashSet<>(); for (ModifiedCompound mc : modComps) { identifiedLinkages.addAll(mc.getAtomLinkages()); } @@ -555,7 +555,7 @@ private void recordUnidentifiableAtomLinkages(List modComps, } private void recordUnidentifiableModifiedResidues(List modComps) { - Set identifiedComps = new HashSet(); + Set identifiedComps = new HashSet<>(); for (ModifiedCompound mc : modComps) { identifiedComps.addAll(mc.getGroups(true)); } @@ -592,18 +592,14 @@ private void addModificationGroups( throw new IllegalArgumentException("Null argument(s)."); } - Map> mapSingleMultiComps = new HashMap>(); + Map> mapSingleMultiComps = new HashMap<>(); for (ProteinModification mod : modifications) { ModificationCondition condition = mod.getCondition(); for (Component comp : condition.getComponents()) { for (String pdbccId : comp.getPdbccIds()) { Component single = Component.of(Collections.singleton(pdbccId), comp.isNTerminal(), comp.isCTerminal()); - Set mult = mapSingleMultiComps.get(single); - if (mult == null) { - mult = new HashSet(); - mapSingleMultiComps.put(single, mult); - } + Set mult = mapSingleMultiComps.computeIfAbsent(single, k -> new HashSet<>()); mult.add(comp); } } @@ -619,11 +615,7 @@ private void addModificationGroups( Component.of(pdbccId)); for (Component comp : unionComponentSet(ligandsWildCard, comps)) { - Set gs = saveTo.get(comp); - if (gs==null) { - gs = new LinkedHashSet(); - saveTo.put(comp, gs); - } + Set gs = saveTo.computeIfAbsent(comp, k -> new LinkedHashSet<>()); gs.add(group); } } @@ -645,11 +637,7 @@ private void addModificationGroups( Component.of(pdbccId)); for (Component comp : unionComponentSet(residuesWildCard, comps)) { - Set gs = saveTo.get(comp); - if (gs==null) { - gs = new LinkedHashSet(); - saveTo.put(comp, gs); - } + Set gs = saveTo.computeIfAbsent(comp, k -> new LinkedHashSet<>()); gs.add(group); } } @@ -669,11 +657,7 @@ private void addModificationGroups( Component.of(res.getPDBName(), true, false)); for (Component comp : unionComponentSet(nTermWildCard, comps)) { - Set gs = saveTo.get(comp); - if (gs==null) { - gs = new LinkedHashSet(); - saveTo.put(comp, gs); - } + Set gs = saveTo.computeIfAbsent(comp, k -> new LinkedHashSet<>()); gs.add(res); } } while (iRes gs = saveTo.get(comp); - if (gs==null) { - gs = new LinkedHashSet(); - saveTo.put(comp, gs); - } + Set gs = saveTo.computeIfAbsent(comp, k -> new LinkedHashSet<>()); gs.add(res); } } while (iRes>=0 && ligands.contains(res)); @@ -712,7 +692,7 @@ private Set unionComponentSet(Set set1, Set set if (set2 == null) return set1; - Set set = new HashSet(set1.size()+set2.size()); + Set set = new HashSet<>(set1.size() + set2.size()); set.addAll(set1); set.addAll(set2); @@ -728,7 +708,7 @@ private List> getMatchedAtomsOfLinkages( int nLink = linkages.size(); List> matchedAtomsOfLinkages = - new ArrayList>(nLink); + new ArrayList<>(nLink); for (int iLink=0; iLink> getMatchedAtomsOfLinkages( Set groups1 = mapCompGroups.get(comp1); Set groups2 = mapCompGroups.get(comp2); - List list = new ArrayList(); + List list = new ArrayList<>(); List potentialNamesOfAtomOnGroup1 = linkage.getPDBNameOfPotentialAtomsOnComponent1(); for (String name : potentialNamesOfAtomOnGroup1) { @@ -810,9 +790,9 @@ private void assembleLinkages(List> matchedAtomsOfLinkages, int nLink = matchedAtomsOfLinkages.size(); int[] indices = new int[nLink]; - Set identifiedCompounds = new HashSet(); + Set identifiedCompounds = new HashSet<>(); while (indices[0] atomLinkages = new ArrayList(nLink); + List atomLinkages = new ArrayList<>(nLink); for (int iLink=0; iLink> matchedAtomsOfLinkages, // matched int n = atomLinkages.size(); - List linkages = new ArrayList(n); + List linkages = new ArrayList<>(n); for (int i=0; i findAtomLinkages(final Group group1, throw new IllegalArgumentException("bondLengthTolerance cannot be negative."); } - List ret = new ArrayList(); + List ret = new ArrayList<>(); if (potentialNamesOfAtomOnGroup1 == null) { // if empty name, search for all atoms @@ -282,8 +282,8 @@ private static boolean hasMetalBond(Atom a1, Atom a2, MetalBondDistance definiti double distance = Calc.getDistance(a1,a2); - Float min = definition.getLowerLimit(); - Float max = definition.getUpperLimit(); + float min = definition.getLowerLimit(); + float max = definition.getUpperLimit(); return ( min < distance && max > distance); @@ -327,7 +327,7 @@ public static List getAtomNames(Group group) { } int n = atoms.size(); - List ret = new ArrayList(n); + List ret = new ArrayList<>(n); for (int i=0; i testXMLSerialization(String pdbId){ String xml = null; ModifiedCompound currentMC = null; - List all = new ArrayList(); + List all = new ArrayList<>(); try { Structure struc = TmpAtomCache.cache.getStructure(pdbId); @@ -220,7 +221,7 @@ public String convertStreamToString(InputStream is) char[] buffer = new char[1024]; try { Reader reader = new BufferedReader( - new InputStreamReader(is, "UTF-8")); + new InputStreamReader(is, StandardCharsets.UTF_8)); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); diff --git a/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/ProteinModificationParserTest.java b/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/ProteinModificationParserTest.java index cd7bd76a30..a5ffff2bc3 100644 --- a/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/ProteinModificationParserTest.java +++ b/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/ProteinModificationParserTest.java @@ -22,7 +22,9 @@ import org.biojava.nbio.protmod.ProteinModification; import org.biojava.nbio.protmod.ProteinModificationRegistry; -import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.ResidueNumber; +import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.StructureException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -477,7 +479,7 @@ private Set identifyAllModfications(Structure struc) { * http://www.biojava.org/wiki/BioJava:CookBook3:ProtMod */ private List identifyPhosphosites(Structure struc) { - List phosphosites = new ArrayList(); + List phosphosites = new ArrayList<>(); ProteinModificationIdentifier parser = new ProteinModificationIdentifier(); parser.identify(struc, ProteinModificationRegistry.getByKeyword("phosphoprotein")); Set mcs = parser.getIdentifiedModifiedCompound(); diff --git a/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/ProteinModificationRegistryTest.java b/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/ProteinModificationRegistryTest.java index 7590904de6..a25f76e8dc 100644 --- a/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/ProteinModificationRegistryTest.java +++ b/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/ProteinModificationRegistryTest.java @@ -49,7 +49,7 @@ public class ProteinModificationRegistryTest { @Test public void testRegisterModification() { // define the involved components, in this case two cystines (CYS) - List components = new ArrayList(2); + List components = new ArrayList<>(2); components.add(Component.of("CYS")); components.add(Component.of("CYS")); diff --git a/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/TmpAtomCache.java b/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/TmpAtomCache.java index 8d757a74a8..95ddb12e95 100644 --- a/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/TmpAtomCache.java +++ b/biojava-modfinder/src/test/java/org/biojava/nbio/protmod/structure/TmpAtomCache.java @@ -30,8 +30,8 @@ public class TmpAtomCache { - static String tmpDir = System.getProperty("java.io.tmpdir"); - public static AtomCache cache = new AtomCache(tmpDir, tmpDir); + static final String tmpDir = System.getProperty("java.io.tmpdir"); + public static final AtomCache cache = new AtomCache(tmpDir, tmpDir); static { FileParsingParameters params = new FileParsingParameters(); params.setAlignSeqRes(true); diff --git a/biojava-ontology/pom.xml b/biojava-ontology/pom.xml index b6a4fa0967..9b75177d21 100644 --- a/biojava-ontology/pom.xml +++ b/biojava-ontology/pom.xml @@ -1,51 +1,52 @@ - - 4.0.0 - - org.biojava - biojava - 5.3.1-SNAPSHOT - + + 4.0.0 + + org.biojava + biojava + 5.3.1-SNAPSHOT + - biojava-ontology - biojava-ontology - http://www.biojava.org + biojava-ontology + biojava-ontology + http://www.biojava.org - - - GNU LGPL v2 - http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt - repo - - + + + GNU LGPL v2 + http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt + repo + + - - - junit - junit - test - - - - org.slf4j - slf4j-api - - - - org.apache.logging.log4j - log4j-slf4j-impl - - - org.apache.logging.log4j - log4j-api - - - org.apache.logging.log4j - log4j-core - - + + + junit + junit + test + + + + org.slf4j + slf4j-api + + + + org.apache.logging.log4j + log4j-slf4j-impl + + + org.apache.logging.log4j + log4j-api + + + org.apache.logging.log4j + log4j-core + + - + UTF-8 UTF-8 @@ -56,16 +57,8 @@ - - - org.apache.maven.plugins - maven-jar-plugin - - - demo/** - - - + + org.apache.maven.plugins diff --git a/biojava-ontology/src/main/java/demo/ParseGO.java b/biojava-ontology/src/main/java/demo/ParseGO.java index c16dffed89..827a7e699e 100644 --- a/biojava-ontology/src/main/java/demo/ParseGO.java +++ b/biojava-ontology/src/main/java/demo/ParseGO.java @@ -34,7 +34,6 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; -import java.util.Iterator; import java.util.Set; public class ParseGO { @@ -56,11 +55,9 @@ public static void main(String[] args){ Ontology ontology = parser.parseOBO(oboFile, "BioSapiens", "the BioSapiens ontology"); Set keys = ontology.getTerms(); - Iterator iter = keys.iterator(); - while (iter.hasNext()){ - Term t = iter.next(); - logger.info("{} [{}]", t.getName(), t.getDescription()); - } + for (Term t : keys) { + logger.info("{} [{}]", t.getName(), t.getDescription()); + } } catch (Exception e){ logger.error("Exception: ", e); } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/IntegerOntology.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/IntegerOntology.java index c8ee792a5b..432400f979 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/IntegerOntology.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/IntegerOntology.java @@ -117,14 +117,13 @@ public Set getRemoteTerms() { } @Override - public Term createTerm(String name) throws AlreadyExistsException, IllegalArgumentException { + public Term createTerm(String name) throws IllegalArgumentException { throw new IllegalArgumentException(getName() + " is immutable"); } @Override public Term createTerm(String name, String description) throws - AlreadyExistsException, IllegalArgumentException { @@ -134,7 +133,6 @@ public Term createTerm(String name, String description) @Override public Term createTerm(String name, String description, Object[] synonyms) throws - AlreadyExistsException, IllegalArgumentException { @@ -144,7 +142,6 @@ public Term createTerm(String name, String description, Object[] synonyms) @Override public Variable createVariable(String name, String description) throws - AlreadyExistsException, IllegalArgumentException { @@ -160,10 +157,7 @@ public Term importTerm(Term t, String name) } @Override - public Triple createTriple(Term subject, Term object, Term predicate, String name, String description) - throws - AlreadyExistsException - { + public Triple createTriple(Term subject, Term object, Term predicate, String name, String description) { throw new IllegalArgumentException(getName() + " is immutable"); } @@ -190,7 +184,7 @@ public boolean containsTerm(String name) { } public IntTerm resolveInt(int val) { - Integer i = new Integer(val); + Integer i = val; IntTerm term = (IntTerm) termCache.get(i); if(term == null) { @@ -205,7 +199,7 @@ public final class IntTerm implements Term { private final int val; - private Set synonyms; + private final Set synonyms; public IntTerm(int val) { this(val, null); diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntoTools.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntoTools.java index 1b1d7afd27..c7b548e215 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntoTools.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntoTools.java @@ -73,13 +73,7 @@ public final class OntoTools { public static final Term PARTIAL_ORDER; static { - DEFAULT_FACTORY = new OntologyFactory() { - @Override - public Ontology createOntology(String name, String desc) - throws OntologyException { - return new Ontology.Impl(name, desc); - } - }; + DEFAULT_FACTORY = Ontology.Impl::new; try { BufferedReader reader = new BufferedReader( diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Ontology.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Ontology.java index 365aab4251..d3ebca831e 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Ontology.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Ontology.java @@ -51,14 +51,14 @@ public interface Ontology { * @return the name of the ontology */ - public String getName(); + String getName(); /** Set the name for this ontology * * @param name - the name * */ - public void setName(String name); + void setName(String name); /** * Return a human-readable description of this ontology, or the empty @@ -66,13 +66,13 @@ public interface Ontology { * @return the description of the term */ - public String getDescription(); + String getDescription(); /** set the description of this ontology * * @param description */ - public void setDescription(String description); + void setDescription(String description); @@ -81,7 +81,7 @@ public interface Ontology { * @return a Set of all Terms of the ontology. */ - public Set getTerms(); + Set getTerms(); /** * Fetch the term with the specified name. @@ -91,7 +91,7 @@ public interface Ontology { * @throws NoSuchElementException if no term exists with that name */ - public Term getTerm(String name) throws NoSuchElementException; + Term getTerm(String name) throws NoSuchElementException; /** * Return all triples from this ontology which match the supplied @@ -104,7 +104,7 @@ public interface Ontology { * @return a Set of triples */ - public Set getTriples(Term subject, Term object, Term predicate); + Set getTriples(Term subject, Term object, Term predicate); /** * Return the associated OntologyOps. @@ -118,7 +118,7 @@ public interface Ontology { * @return the OntologyOps instance associated with this instance. */ - public OntologyOps getOps(); + OntologyOps getOps(); /** * Create a new term in this ontology. @@ -132,7 +132,7 @@ public interface Ontology { * @throws ChangeVetoException */ - public Term createTerm(String name) + Term createTerm(String name) throws AlreadyExistsException, @@ -151,7 +151,7 @@ public Term createTerm(String name) * @throws ChangeVetoException */ - public Term createTerm(String name, String description) + Term createTerm(String name, String description) throws AlreadyExistsException, @@ -171,7 +171,7 @@ public Term createTerm(String name, String description) * @throws ChangeVetoException */ - public Term createTerm(String name, String description, Object[] synonyms) + Term createTerm(String name, String description, Object[] synonyms) throws AlreadyExistsException, @@ -190,7 +190,7 @@ public Term createTerm(String name, String description, Object[] synonyms) * @throws ChangeVetoException */ - public Variable createVariable(String name, String description) + Variable createVariable(String name, String description) throws AlreadyExistsException, @@ -212,7 +212,7 @@ public Variable createVariable(String name, String description) * @throws IllegalArgumentException */ - public Term importTerm(Term t, String localName) + Term importTerm(Term t, String localName) throws IllegalArgumentException; @@ -233,7 +233,7 @@ public Term importTerm(Term t, String localName) * @throws IllegalArgumentException if subject, object or predicate are not all * from the same ontology */ - public Triple createTriple(Term subject, Term object, Term predicate, String name, String description) + Triple createTriple(Term subject, Term object, Term predicate, String name, String description) throws AlreadyExistsException ; @@ -246,7 +246,7 @@ public Triple createTriple(Term subject, Term object, Term predicate, String nam * @return true if contained */ - public boolean containsTriple(Term subject, Term object, Term predicate); + boolean containsTriple(Term subject, Term object, Term predicate); /** * Remove a term from an ontology, together with all triples which refer to it. @@ -254,7 +254,7 @@ public Triple createTriple(Term subject, Term object, Term predicate, String nam * @throws ChangeVetoException */ - public void deleteTerm(Term t) ; + void deleteTerm(Term t) ; /** * Determines if this ontology currently contains a term named name @@ -262,7 +262,7 @@ public Triple createTriple(Term subject, Term object, Term predicate, String nam * @return true is contained */ - public boolean containsTerm(String name); + boolean containsTerm(String name); /** * A basic in-memory implementation of an ontology @@ -274,7 +274,7 @@ public Triple createTriple(Term subject, Term object, Term predicate, String nam // AP: I am setting name and description to public changeable fields // e.g during parsing of an .obo file we don't know them when the ontology is instanciated - public final class Impl + final class Impl implements Ontology, java.io.Serializable { /** @@ -294,13 +294,13 @@ public final class Impl private final OntologyOps ops; { - terms = new HashMap(); - triples = new HashSet(); - subjectTriples = new HashMap>(); - objectTriples = new HashMap>(); - relationTriples = new HashMap>(); - remoteTerms = new HashMap(); - localRemoteTerms = new HashSet(); + terms = new HashMap<>(); + triples = new HashSet<>(); + subjectTriples = new HashMap<>(); + objectTriples = new HashMap<>(); + relationTriples = new HashMap<>(); + remoteTerms = new HashMap<>(); + localRemoteTerms = new HashSet<>(); } public Impl(String name, String description) { @@ -337,7 +337,7 @@ public void setDescription(String description){ @Override public Set getTerms() { - return new HashSet(terms.values()); + return new HashSet<>(terms.values()); } @Override @@ -377,16 +377,15 @@ public Set getTriples(Term subject, Term object, Term predicate) { } } - private Set filterTriples(Set base, Term subject, Term object, Term predicate) { + private static Set filterTriples(Set base, Term subject, Term object, Term predicate) { if (base == null) { return Collections.EMPTY_SET; } else if (subject == null && object == null && predicate == null) { - return Collections.unmodifiableSet(new HashSet(base)); + return Collections.unmodifiableSet(new HashSet<>(base)); } - Set retval = new HashSet(); - for (Iterator i = base.iterator(); i.hasNext(); ) { - Triple t = i.next(); + Set retval = new HashSet<>(); + for (Triple t : base) { if (subject != null && t.getSubject() != subject) { continue; } @@ -531,8 +530,7 @@ public Triple createTriple(Term subject, String description) throws AlreadyExistsException, - IllegalArgumentException, - NullPointerException, + NullPointerException, IllegalArgumentException { Triple t = new Triple.Impl(subject, object, predicate, name, description); @@ -564,12 +562,7 @@ private void addTriple(Triple t) { } private void pushTriple(Map> m, Term key, Triple t) { - Set s = m.get(key); - if (s == null) { - s = new HashSet(); - m.put(key, s); - } - s.add(t); + m.computeIfAbsent(key, k -> new HashSet<>(1)).add(t); } private void removeTriple(Triple t) { diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyFactory.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyFactory.java index 1bac93c033..64f7d52221 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyFactory.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyFactory.java @@ -34,8 +34,7 @@ public interface OntologyFactory { * @param description the description for the ontology * @return an Ontology * @throws NullPointerException if either name or description are null - * @throws OntologyException if the ontology could not be created */ - public Ontology createOntology(String name, String description) - throws OntologyException; + Ontology createOntology(String name, String description) + ; } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyOps.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyOps.java index a4e1b243a0..97104b4620 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyOps.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyOps.java @@ -49,5 +49,5 @@ public interface OntologyOps { * * @return a Set containing all remote terms in the ontology */ - public Set getRemoteTerms(); + Set getRemoteTerms(); } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyTerm.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyTerm.java index 849bbc8ff0..e4256f46f8 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyTerm.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/OntologyTerm.java @@ -52,7 +52,7 @@ public interface OntologyTerm extends Term { */ @Override - public Ontology getOntology(); + Ontology getOntology(); /** * Simple in-memory implementation of a remote ontology term. @@ -60,7 +60,7 @@ public interface OntologyTerm extends Term { * This can be used to implement Ontology.importTerm */ - public final static class Impl + final class Impl implements OntologyTerm, java.io.Serializable { @@ -68,7 +68,7 @@ public final static class Impl private final Ontology ontology; private final Ontology target; - private Set synonyms; + private final Set synonyms; public Impl(Ontology ontology, Ontology target) { this(ontology, target, null); diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/RemoteTerm.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/RemoteTerm.java index c003bb8ff3..e6a9721f30 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/RemoteTerm.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/RemoteTerm.java @@ -60,7 +60,7 @@ public interface RemoteTerm extends Term { * @return the term */ - public Term getRemoteTerm(); + Term getRemoteTerm(); /** * Simple in-memory implementation of a remote ontology term. @@ -68,7 +68,7 @@ public interface RemoteTerm extends Term { * This can be used to implement Ontology.importTerm */ - public final static class Impl + final class Impl extends AbstractTerm implements RemoteTerm, java.io.Serializable { /** @@ -78,7 +78,7 @@ public final static class Impl private final Ontology ontology; private final Term remoteTerm; private final String name; - private Set synonyms; + private final Set synonyms; public Impl(Ontology ontology, Term remoteTerm, String name) { this(ontology, remoteTerm, name, null); diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Synonym.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Synonym.java index 968bac29e7..f2f2cd28df 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Synonym.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Synonym.java @@ -45,12 +45,7 @@ public String toString(){ return txt; } - public final static Comparator COMPARATOR = new Comparator() { - @Override - public int compare(Synonym a, Synonym b) { - return String.CASE_INSENSITIVE_ORDER.compare(a.toString(), b.toString()); - } - }; + public final static Comparator COMPARATOR = (a, b) -> String.CASE_INSENSITIVE_ORDER.compare(a.toString(), b.toString()); public Synonym() { } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Term.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Term.java index 387aa7c17a..ad20f570bf 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Term.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Term.java @@ -66,7 +66,7 @@ public interface Term extends Annotatable { * @return the name of the term */ - public String getName(); + String getName(); /** * Return a human-readable description of this term, or the empty string if @@ -74,42 +74,42 @@ public interface Term extends Annotatable { * @return the description of the term */ - public String getDescription(); + String getDescription(); /** set the description of the term; * * @param description * */ - public void setDescription(String description); + void setDescription(String description); /** * Return the ontology in which this term exists. * @return the ontology */ - public Ontology getOntology(); + Ontology getOntology(); /** * Return the synonyms for this term. * @return the synonyms */ - public Object[] getSynonyms(); + Object[] getSynonyms(); /** * Add a synonym for this term. * @param synonym the synonym */ - public void addSynonym(Object synonym); + void addSynonym(Object synonym); /** * Remove a synonym for this term. * @param synonym */ - public void removeSynonym(Object synonym); + void removeSynonym(Object synonym); /** * Simple in-memory implementation of an ontology term. @@ -117,7 +117,7 @@ public interface Term extends Annotatable { * This can be used to implement Ontology.createTerm */ - public static class Impl + class Impl extends AbstractTerm implements Term, java.io.Serializable { /** @@ -155,7 +155,7 @@ public Impl(Ontology ontology, String name, String description, Object[] synonym this.description = description; this.ontology = ontology; - this.synonyms = new TreeSet(); + this.synonyms = new TreeSet<>(); if (synonyms!=null) this.synonyms.addAll(Arrays.asList(synonyms)); } @@ -227,7 +227,7 @@ public boolean equals(Object obj) Term that = (Term) obj; return this.getOntology() == that.getOntology() && - this.getName() == that.getName(); + this.getName().equals(that.getName()); } } } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Triple.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Triple.java index 550c4d5651..5a1d2439c5 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Triple.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Triple.java @@ -51,21 +51,21 @@ public interface Triple * @return the subject term */ - public Term getSubject(); + Term getSubject(); /** * Return the object term of this triple. * @return the object term */ - public Term getObject(); + Term getObject(); /** * Return a Term which defines the type of relationship between the subject and object terms. * @return the predicate */ - public Term getPredicate(); + Term getPredicate(); /** * The hashcode for a Triple. @@ -82,7 +82,7 @@ public interface Triple *

    */ @Override - public int hashCode(); + int hashCode(); /** * Check to see if an object is an equivalent Triple. @@ -105,7 +105,7 @@ public interface Triple *

    */ @Override - public boolean equals(Object obj); + boolean equals(Object obj); /** * Basic in-memory implementation of a Triple in an ontology @@ -114,7 +114,7 @@ public interface Triple * @see org.biojavax.ontology.SimpleComparableTriple */ - public static final class Impl + final class Impl implements Triple, java.io.Serializable { /** @@ -126,7 +126,7 @@ public static final class Impl private final Term predicate; private /*final*/ String name; private /*final*/ String description; - private Set synonyms; + private final Set synonyms; public Impl(Term subject, Term object, Term predicate) { this(subject, object, predicate, null, null, null); @@ -182,7 +182,7 @@ public Impl(Term subject, this.name = name; this.description = description; - this.synonyms = new TreeSet(); + this.synonyms = new TreeSet<>(); if (synonyms!=null) this.synonyms.addAll(Arrays.asList(synonyms)); } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Variable.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Variable.java index 2c453f674b..014850d319 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Variable.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/Variable.java @@ -27,7 +27,7 @@ */ public interface Variable extends Term { - public static class Impl + class Impl extends Term.Impl implements Variable { diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/GOParser.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/GOParser.java index 7754ec130a..e7f3a8ab8c 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/GOParser.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/GOParser.java @@ -25,7 +25,6 @@ import java.io.BufferedReader; import java.io.IOException; -import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; @@ -42,13 +41,13 @@ public Ontology parseGO(BufferedReader goFile, String ontoName, String ontoDescription, OntologyFactory factory) - throws ParseException, IOException + throws IOException { try { Ontology onto = factory.createOntology(ontoName, ontoDescription); Term isa = onto.importTerm(OntoTools.IS_A, null); Term partof = null; // fixme: onto.importTerm(OntoTools.PART_OF, null); - List termStack = new ArrayList(); + List termStack = new ArrayList<>(); String line; while ((line = goFile.readLine()) != null) { int leadSpaces = 0; @@ -101,7 +100,7 @@ private void safeAddTriple(Ontology onto, Term s, Term o, Term p) } private Term parseTerm(Ontology onto, String s) - throws ParseException, AlreadyExistsException + throws AlreadyExistsException { int semi = s.indexOf(';'); int semi2 = s.indexOf(';', semi + 1); @@ -122,7 +121,7 @@ private Term parseTerm(Ontology onto, String s) } else { Term t = onto.createTerm(termName, termDesc); if (toke.hasMoreTokens()) { - List secondaries = new ArrayList(); + List secondaries = new ArrayList<>(); while (toke.hasMoreTokens()) { secondaries.add(toke.nextToken()); } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/OboParser.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/OboParser.java index d772850e05..1f03130185 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/OboParser.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/OboParser.java @@ -23,16 +23,14 @@ package org.biojava.nbio.ontology.io; -import org.biojava.nbio.ontology.*; -import org.biojava.nbio.ontology.obo.OboFileEventListener; +import org.biojava.nbio.ontology.OntoTools; +import org.biojava.nbio.ontology.Ontology; +import org.biojava.nbio.ontology.OntologyFactory; import org.biojava.nbio.ontology.obo.OboFileHandler; import org.biojava.nbio.ontology.obo.OboFileParser; import java.io.BufferedReader; import java.io.IOException; -import java.text.ParseException; - - /** Parses an OBO file. @@ -70,7 +68,6 @@ public class OboParser { * @param ontoDescription * @return the ontology represented as a BioJava ontology file - * @throws ParseException * @throws IOException */ public Ontology parseOBO( @@ -78,27 +75,26 @@ public Ontology parseOBO( String ontoName, String ontoDescription ) - throws ParseException, IOException { + throws IOException { - try { +// try { OntologyFactory factory = OntoTools.getDefaultFactory(); - Ontology ontology = factory.createOntology(ontoName, ontoDescription); OboFileParser parser = new OboFileParser(); - OboFileEventListener handler = new OboFileHandler(ontology); + Ontology ontology = factory.createOntology(ontoName, ontoDescription); - parser.addOboFileEventListener(handler); + parser.addOboFileEventListener(new OboFileHandler(ontology)); parser.parseOBO(oboFile); return ontology; - - } catch (AlreadyExistsException ex) { - throw new RuntimeException( "Duplication in ontology"); - } catch (OntologyException ex) { - throw new RuntimeException(ex); - } +// +// } catch (AlreadyExistsException ex) { +// throw new RuntimeException( "Duplication in ontology"); +// } catch (OntologyException ex) { +// throw new RuntimeException(ex); +// } } } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/TabDelimParser.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/TabDelimParser.java index 2c0ed0a3ae..f035375236 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/TabDelimParser.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/io/TabDelimParser.java @@ -86,11 +86,9 @@ public class TabDelimParser { * @param of an OntologyFactory used to create the Ontology instance * @return a new Ontology * @throws IOException if there is some problem with the buffered reader - * @throws OntologyException if it was not possible to instantiate a new - * ontology - */ + */ public Ontology parse(BufferedReader in, OntologyFactory of) - throws IOException, OntologyException { + throws IOException { String name = ""; String description = ""; Ontology onto = null; @@ -139,8 +137,8 @@ public Ontology parse(BufferedReader in, OntologyFactory of) Term objT = resolveTerm(object, onto); Term relT = resolveTerm(predicate, onto); - Triple trip = resolveTriple(subT, objT, relT, onto); - trip = trip==null?null:trip; // prevent unused field error + /*Triple trip =*/ resolveTriple(subT, objT, relT, onto); + //trip = trip; // prevent unused field error } catch (StringIndexOutOfBoundsException e) { throw new IOException("Could not parse line: " + line); } @@ -159,8 +157,8 @@ private Term resolveTerm(String termName, Ontology onto) { } else { try { if(isTrippleTerm) { - int c1 = termName.indexOf(","); - int c2 = termName.indexOf(",", c1 + 1); + int c1 = termName.indexOf(','); + int c2 = termName.indexOf(',', c1 + 1); String source = termName.substring(1, c1); String target = termName.substring(c2 + 1, termName.length() - 1); diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileEventListener.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileEventListener.java index 7350b6a2cb..0e061bcf74 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileEventListener.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileEventListener.java @@ -37,36 +37,36 @@ public interface OboFileEventListener { * * */ - public void documentStart(); + void documentStart(); /** end of parsing a new OBO file * * */ - public void documentEnd(); + void documentEnd(); /** parsed a new OBO file header * * */ - public void newOboFileHeader(); + void newOboFileHeader(); /** parsed a new stanza in the file * * @param stanza */ - public void newStanza(String stanza); + void newStanza(String stanza); /**found a new key in the file * * @param key * @param value */ - public void newKey(String key, String value ); + void newKey(String key, String value); /** a new synonym has been found * * @param synonym */ - public void newSynonym(Synonym synonym); + void newSynonym(Synonym synonym); } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileHandler.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileHandler.java index 49e3c2b56c..a064859684 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileHandler.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileHandler.java @@ -43,7 +43,7 @@ public class OboFileHandler implements OboFileEventListener { private static final Logger logger = LoggerFactory.getLogger(OboFileEventListener.class); - Ontology ontology; + final Ontology ontology; List termStack ; public static final String TERM = "Term"; @@ -91,7 +91,7 @@ public void documentEnd() { @Override public void documentStart() { - termStack = new ArrayList(); + termStack = new ArrayList<>(); } @Override @@ -136,54 +136,68 @@ public void newKey(String key, String value) { logger.warn("did not find ID for Term! "); return; } - if (key.equals(NAMESPACE)){ - Annotation anno = currentTerm.getAnnotation(); - anno.setProperty(NAMESPACE, value); - } - else if (key.equals(NAME)){ - currentTerm.setDescription(value); - } else if (key.equals(DEF)){ - //TODO - // set definition - Annotation anno = currentTerm.getAnnotation(); - anno.setProperty(DEF, value); - } else if (key.equals(XREF_ANALOG)){ - // set xref analog - Annotation anno = currentTerm.getAnnotation(); - anno.setProperty(XREF_ANALOG, value); - } else if (key.equals(IS_OBSOLETE)) { - // ignore obsolete Terms... - //logger.info("obsolete: {}", currentTerm); - Annotation anno = currentTerm.getAnnotation(); - anno.setProperty(IS_OBSOLETE, new Boolean(true)); - - } else if (key.equals(IS_A) || - key.equals(RELATIONSHIP) || - key.equals(DISJOINT_FROM) || - key.equals(INTERSECTION_OF) || - key.equals(SUBSET)) { - try { - Term object = (ontology.containsTerm(value) ? - ontology.getTerm(value): ontology.createTerm(value)); - Term predicate = (ontology.containsTerm(key) ? ontology.getTerm(key) : ontology.createTerm(key)); - ontology.createTriple(currentTerm, object, predicate, currentTerm + " " + predicate + " " + object, key+"-relationship"); - } catch (AlreadyExistsException ex) { + switch (key) { + case NAMESPACE: { + Annotation anno = currentTerm.getAnnotation(); + anno.setProperty(NAMESPACE, value); + break; + } + case NAME: + currentTerm.setDescription(value); + break; + case DEF: { + //TODO + // set definition + Annotation anno = currentTerm.getAnnotation(); + anno.setProperty(DEF, value); + break; + } + case XREF_ANALOG: { + // set xref analog + Annotation anno = currentTerm.getAnnotation(); + anno.setProperty(XREF_ANALOG, value); + break; } + case IS_OBSOLETE: { + // ignore obsolete Terms... + //logger.info("obsolete: {}", currentTerm); + Annotation anno = currentTerm.getAnnotation(); + anno.setProperty(IS_OBSOLETE, Boolean.TRUE); - } else if (key.equals(COMMENT)){ - Annotation anno = currentTerm.getAnnotation(); - anno.setProperty(COMMENT, value); - } else if (key.equals(ALT_ID)){ - Annotation anno = currentTerm.getAnnotation(); - anno.setProperty(ALT_ID, value); - } - else if (key.equals(REPLACED_BY)) { - Annotation anno = currentTerm.getAnnotation(); - anno.setProperty(REPLACED_BY, value); - } + break; + } + case IS_A: + case RELATIONSHIP: + case DISJOINT_FROM: + case INTERSECTION_OF: + case SUBSET: + try { + Term object = (ontology.containsTerm(value) ? + ontology.getTerm(value) : ontology.createTerm(value)); + Term predicate = (ontology.containsTerm(key) ? ontology.getTerm(key) : ontology.createTerm(key)); + ontology.createTriple(currentTerm, object, predicate, currentTerm + " " + predicate + " " + object, key + "-relationship"); + } catch (AlreadyExistsException ex) { + } - else { - //logger.info("unknown key {}", key); + break; + case COMMENT: { + Annotation anno = currentTerm.getAnnotation(); + anno.setProperty(COMMENT, value); + break; + } + case ALT_ID: { + Annotation anno = currentTerm.getAnnotation(); + anno.setProperty(ALT_ID, value); + break; + } + case REPLACED_BY: { + Annotation anno = currentTerm.getAnnotation(); + anno.setProperty(REPLACED_BY, value); + break; + } + default: + //logger.info("unknown key {}", key); + break; } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileParser.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileParser.java index 76b7d673c2..76dd2d7819 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileParser.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/obo/OboFileParser.java @@ -53,49 +53,47 @@ public class OboFileParser { List listeners; protected String line; - protected int linenum = 0; + protected final int linenum = 0; protected int totalSize = 0; protected int bytesRead = 0; - protected StringBuffer tempBuffer = new StringBuffer(); + protected final StringBuffer tempBuffer = new StringBuffer(); protected SimpleDateFormat dateFormat = new SimpleDateFormat("dd:MM:yyyy HH:mm", Locale.US); protected static final Map escapeChars = - new HashMap(); + new HashMap<>(); protected static final Map unescapeChars = - new HashMap(); + new HashMap<>(); static { - escapeChars.put(new Character('n'), new Character('\n')); - escapeChars.put(new Character('W'), new Character(' ')); - escapeChars.put(new Character('t'), new Character('\t')); - escapeChars.put(new Character(':'), new Character(':')); - escapeChars.put(new Character(','), new Character(',')); - escapeChars.put(new Character('"'), new Character('"')); - escapeChars.put(new Character('\''), new Character('\'')); - escapeChars.put(new Character('\\'), new Character('\\')); - escapeChars.put(new Character('{'), new Character('{')); - escapeChars.put(new Character('}'), new Character('}')); - escapeChars.put(new Character('('), new Character('(')); - escapeChars.put(new Character(')'), new Character(')')); - escapeChars.put(new Character('['), new Character('[')); - escapeChars.put(new Character(']'), new Character(']')); - escapeChars.put(new Character('!'), new Character('!')); - Iterator it = escapeChars.keySet().iterator(); - while (it.hasNext()) { - Character key = it.next(); - Character value = escapeChars.get(key); - unescapeChars.put(value, key); + escapeChars.put('n', '\n'); + escapeChars.put('W', ' '); + escapeChars.put('t', '\t'); + escapeChars.put(':', ':'); + escapeChars.put(',', ','); + escapeChars.put('"', '"'); + escapeChars.put('\'', '\''); + escapeChars.put('\\', '\\'); + escapeChars.put('{', '{'); + escapeChars.put('}', '}'); + escapeChars.put('(', '('); + escapeChars.put(')', ')'); + escapeChars.put('[', '['); + escapeChars.put(']', ']'); + escapeChars.put('!', '!'); + for (Map.Entry entry : escapeChars.entrySet()) { + Character value = entry.getValue(); + unescapeChars.put(value, entry.getKey()); } } public static class SOPair { - public String str = null; + public final String str; - public int index = -1; + public final int index; - public int endIndex = -1; + public final int endIndex; public SOPair(String str, int index) { this(str, index, -1); @@ -114,7 +112,7 @@ public SOPair(String str, int index, int endIndex) { public OboFileParser(){ - listeners = new ArrayList(); + listeners = new ArrayList<>(); } @@ -166,7 +164,7 @@ public void parseOBO(BufferedReader oboFile) throws IOException{ lineEnd = line.length(); // find nested values - NestedValue nv = null; + NestedValue nv; int trailingStartIndex = -1; int trailingEndIndex = -1; @@ -258,12 +256,17 @@ private Synonym parseSynonym(String key, String value) throws IOException{ StringTokenizer tokenizer = new StringTokenizer(leftovers, " \t"); int scope = Synonym.RELATED_SYNONYM; - if ( key.equals(OboFileHandler.EXACT_SYNONYM)) - scope = Synonym.EXACT_SYNONYM; - else if ( key.equals(OboFileHandler.BROAD_SYNONYM)) - scope = Synonym.BROAD_SYNONYM; - else if ( key.equals(OboFileHandler.NARROW_SYNONYM)) - scope = Synonym.NARROW_SYNONYM; + switch (key) { + case OboFileHandler.EXACT_SYNONYM: + scope = Synonym.EXACT_SYNONYM; + break; + case OboFileHandler.BROAD_SYNONYM: + scope = Synonym.BROAD_SYNONYM; + break; + case OboFileHandler.NARROW_SYNONYM: + scope = Synonym.NARROW_SYNONYM; + break; + } String catID = null; @@ -271,19 +274,24 @@ else if ( key.equals(OboFileHandler.NARROW_SYNONYM)) String token = tokenizer.nextToken(); //logger.info("TOKEN:" +token); if (i == 0) { - if (token.equals("RELATED")) - scope = Synonym.RELATED_SYNONYM; - else if (token.equals("UNSPECIFIED")) - scope = Synonym.RELATED_SYNONYM; - else if (token.equals("EXACT")) - scope = Synonym.EXACT_SYNONYM; - else if (token.equals("BROAD")) - scope = Synonym.BROAD_SYNONYM; - else if (token.equals("NARROW")) - scope = Synonym.NARROW_SYNONYM; - else - throw new IOException("Found unexpected scope " - + "identifier " + token + line); + switch (token) { + case "RELATED": + case "UNSPECIFIED": + scope = Synonym.RELATED_SYNONYM; + break; + case "EXACT": + scope = Synonym.EXACT_SYNONYM; + break; + case "BROAD": + scope = Synonym.BROAD_SYNONYM; + break; + case "NARROW": + scope = Synonym.NARROW_SYNONYM; + break; + default: + throw new IOException("Found unexpected scope " + + "identifier " + token + line); + } } else if (i == 1) { catID = token; } else @@ -316,7 +324,7 @@ else if (token.equals("NARROW")) } protected Map[] getDbxrefList(String line, int startoffset, int endoffset) throws IOException { - Vector> temp = new Vector>(); + Vector> temp = new Vector<>(); boolean stop = false; while (!stop) { int braceIndex = findUnescaped(line, '{', startoffset, endoffset); @@ -343,7 +351,7 @@ protected Map[] getDbxrefList(String line, int startoffset, int e startoffset++; continue; } - NestedValue nv = null; + NestedValue nv; if (trailing) { nv = new NestedValue(); endIndex = getNestedValue(nv, line, endIndex + 1); @@ -367,7 +375,7 @@ protected Map[] getDbxrefList(String line, int startoffset, int e protected Map parseXref(String line, int startoffset, int endoffset) throws IOException { - String xref_str = null; + String xref_str; String desc_str = null; SOPair xref = unescape(line, '"', startoffset, endoffset, false); @@ -381,7 +389,7 @@ protected Map parseXref(String line, } - Map m = new HashMap(); + Map m = new HashMap<>(); m.put("xref",xref_str); m.put("desc",desc_str); return m; @@ -390,34 +398,28 @@ protected Map parseXref(String line, private void triggerNewStanza(String stanza){ - Iterator iter = listeners.iterator(); - while (iter.hasNext()){ - OboFileEventListener li = iter.next(); + for (OboFileEventListener li : listeners) { li.newStanza(stanza); } } private void triggerNewKey(String key, String value){ - Iterator iter = listeners.iterator(); - while (iter.hasNext()){ - OboFileEventListener li = iter.next(); + for (OboFileEventListener li : listeners) { li.newKey(key, value); } } private void triggerNewSynonym(Synonym synonym){ - Iterator iter = listeners.iterator(); - while (iter.hasNext()){ - OboFileEventListener li = iter.next(); + for (OboFileEventListener li : listeners) { li.newSynonym(synonym); } } public static String escape(String str, boolean escapespaces) { - StringBuffer out = new StringBuffer(); + StringBuilder out = new StringBuilder(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); - Object o = unescapeChars.get(new Character(c)); + Object o = unescapeChars.get(c); if (o == null) out.append(c); else { @@ -441,7 +443,7 @@ public SOPair unescape(String str, char toChar, int startindex, public SOPair unescape(String str, char toChar, int startindex, int endindex, boolean mustFindChar) throws IOException { - StringBuffer out = new StringBuffer(); + StringBuilder out = new StringBuilder(); int endValue = -1; for (int i = startindex; i < endindex; i++) { char c = str.charAt(i); @@ -449,7 +451,7 @@ public SOPair unescape(String str, char toChar, int startindex, i++; c = str.charAt(i); Character mapchar = escapeChars - .get(new Character(c)); + .get(c); if (mapchar == null) throw new IOException("Unrecognized escape" + " character " + c + " found."); @@ -604,7 +606,7 @@ else if (str.charAt(startIndex) == ',') { class NestedValue { - protected Properties propertyValues = new Properties(); + protected final Properties propertyValues = new Properties(); protected String name; protected String suggestedComment; @@ -615,9 +617,8 @@ public NestedValue() { public String toString(){ String txt = "NestedValue: " ; Set keys = propertyValues.keySet(); - Iterator iter = keys.iterator(); - while (iter.hasNext()){ - String key = iter.next().toString(); + for (Object o : keys) { + String key = o.toString(); String value = propertyValues.get(key).toString(); txt += " [" + key + ":" + value + "]"; } @@ -636,9 +637,8 @@ public Properties getPropertyValues() { public void addPropertyValue(Properties pv) { Set keys = pv.keySet(); - Iterator iter = keys.iterator(); - while (iter.hasNext()){ - String key = iter.next().toString(); + for (Object o : keys) { + String key = o.toString(); String value = pv.get(key).toString(); propertyValues.setProperty(key, value); } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/AbstractAnnotation.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/AbstractAnnotation.java index d6f9374328..69e0630f9e 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/AbstractAnnotation.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/AbstractAnnotation.java @@ -135,7 +135,7 @@ public Set keys() { @Override public String toString() { - StringBuffer sb = new StringBuffer("{"); + StringBuilder sb = new StringBuilder("{"); Map prop = getProperties(); Iterator i = prop.keySet().iterator(); if(i.hasNext()) { diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/Annotation.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/Annotation.java index fccf023371..dabfa9ebf8 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/Annotation.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/Annotation.java @@ -113,7 +113,7 @@ void setProperty(Object key, Object value) * */ - public void removeProperty(Object key) + void removeProperty(Object key) throws NoSuchElementException; /** @@ -157,6 +157,6 @@ public void removeProperty(Object key) * an implementation to have annotation even though it should implement * Annotatable. */ - static final Annotation EMPTY_ANNOTATION = new EmptyAnnotation(); + Annotation EMPTY_ANNOTATION = new EmptyAnnotation(); } diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/KeyedWeakReference.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/KeyedWeakReference.java index 46b345c368..6e10eae149 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/KeyedWeakReference.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/KeyedWeakReference.java @@ -35,7 +35,7 @@ */ public class KeyedWeakReference extends WeakReference { - private Object key; + private final Object key; public KeyedWeakReference(Object key, Object ref) { super(ref); diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/SmallMap.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/SmallMap.java index c1f37caae5..b00e4eadea 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/SmallMap.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/SmallMap.java @@ -222,7 +222,7 @@ public void remove() { } private class MapEntry implements Map.Entry { - private int offset; + private final int offset; private MapEntry(int offset) { this.offset = offset; diff --git a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/WeakValueHashMap.java b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/WeakValueHashMap.java index 7762642c76..f3ece73302 100644 --- a/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/WeakValueHashMap.java +++ b/biojava-ontology/src/main/java/org/biojava/nbio/ontology/utils/WeakValueHashMap.java @@ -110,7 +110,7 @@ public Set entrySet() { } private class WVEntrySet extends AbstractSet { - private Set keyRefEntrySet; + private final Set keyRefEntrySet; public WVEntrySet() { super(); @@ -130,9 +130,9 @@ public Iterator iterator() { } } - private class WVEntryIterator implements Iterator { + private static class WVEntryIterator implements Iterator { private Object cache; - private Iterator keyRefIterator; + private final Iterator keyRefIterator; public WVEntryIterator(Iterator keyRefIterator) { this.keyRefIterator = keyRefIterator; @@ -182,8 +182,8 @@ private void primeCache() { } private static class WVMapEntry implements Map.Entry { - private Object key; - private Object value; + private final Object key; + private final Object value; private WVMapEntry(Object key, Object value) { this.key = key; diff --git a/biojava-ontology/src/test/java/org/biojava/nbio/ontology/TestOboFileParsing.java b/biojava-ontology/src/test/java/org/biojava/nbio/ontology/TestOboFileParsing.java index 8c8bf3e3e2..ed9ab28709 100644 --- a/biojava-ontology/src/test/java/org/biojava/nbio/ontology/TestOboFileParsing.java +++ b/biojava-ontology/src/test/java/org/biojava/nbio/ontology/TestOboFileParsing.java @@ -25,6 +25,7 @@ package org.biojava.nbio.ontology; import org.biojava.nbio.ontology.io.OboParser; +import org.biojava.nbio.ontology.utils.Annotation; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; @@ -34,8 +35,6 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.util.Set; -import java.util.Iterator; -import org.biojava.nbio.ontology.utils.Annotation; public class TestOboFileParsing { @@ -71,24 +70,22 @@ public void testParsingHPOOBO() throws Exception { ontology = parser.parseOBO(oboFile, "Human_phenotype", "the Human Phenotype ontology"); Set keys = ontology.getTerms(); - Iterator iter = keys.iterator(); - - while (iter.hasNext()){ - Term term = (Term) iter.next(); - if(term.getName().equals("HP:0000057")) { - Annotation anno = term.getAnnotation(); - Assert.assertTrue(anno.containsProperty("replaced_by")); - Assert.assertEquals("HP:0008665", anno.getProperty("replaced_by")); - } - if(term.getName().equals("HP:0000006")) { - Assert.assertEquals("Autosomal dominant inheritance", term.getDescription()); - Object[] syns = term.getSynonyms(); - Assert.assertEquals(3, syns.length); - Assert.assertEquals("Autosomal dominant", ((Synonym) syns[0]).getName()); - Assert.assertEquals("Autosomal dominant form", ((Synonym) syns[1]).getName()); - Assert.assertEquals("Autosomal dominant type", ((Synonym) syns[2]).getName()); - } - } + + for (Term term : keys) { + if (term.getName().equals("HP:0000057")) { + Annotation anno = term.getAnnotation(); + Assert.assertTrue(anno.containsProperty("replaced_by")); + Assert.assertEquals("HP:0008665", anno.getProperty("replaced_by")); + } + if (term.getName().equals("HP:0000006")) { + Assert.assertEquals("Autosomal dominant inheritance", term.getDescription()); + Object[] syns = term.getSynonyms(); + Assert.assertEquals(3, syns.length); + Assert.assertEquals("Autosomal dominant", ((Synonym) syns[0]).getName()); + Assert.assertEquals("Autosomal dominant form", ((Synonym) syns[1]).getName()); + Assert.assertEquals("Autosomal dominant type", ((Synonym) syns[2]).getName()); + } + } } } diff --git a/biojava-ontology/src/test/java/org/biojava/nbio/ontology/TestParseOBO.java b/biojava-ontology/src/test/java/org/biojava/nbio/ontology/TestParseOBO.java index b9fe2df034..dcc7871f34 100644 --- a/biojava-ontology/src/test/java/org/biojava/nbio/ontology/TestParseOBO.java +++ b/biojava-ontology/src/test/java/org/biojava/nbio/ontology/TestParseOBO.java @@ -27,7 +27,6 @@ import org.junit.Test; import java.io.*; -import java.text.ParseException; import java.util.Set; import static org.biojava.nbio.ontology.obo.OboFileHandler.NAMESPACE; @@ -35,7 +34,7 @@ public class TestParseOBO { @Test - public void testNamespace() throws IOException, ParseException { + public void testNamespace() throws IOException { String testTermEntry = "\n[Term]\n" + "id: SO:0000691\n" + diff --git a/biojava-protein-disorder/src/main/java/demo/PredictDisorder.java b/biojava-protein-disorder/src/main/java/demo/PredictDisorder.java index f6013dadd2..7fad8197d8 100644 --- a/biojava-protein-disorder/src/main/java/demo/PredictDisorder.java +++ b/biojava-protein-disorder/src/main/java/demo/PredictDisorder.java @@ -36,7 +36,7 @@ public static void main(String[] args) throws Exception{ ProteinSequence seq = getUniprot(uniprotID); System.out.println("Protein Sequence: "+ seq.toString()); - AminoAcidCompoundSet compoundSet = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet compoundSet = AminoAcidCompoundSet.aminoAcidCompoundSet; if (!compoundSet.isValidSequence(seq) ) { System.err.println("Invalid sequence, exiting"); @@ -58,8 +58,8 @@ public static void main(String[] args) throws Exception{ */ private static ProteinSequence getUniprot(String uniProtID) throws Exception { - AminoAcidCompoundSet set = AminoAcidCompoundSet.getAminoAcidCompoundSet(); - UniprotProxySequenceReader uniprotSequence = new UniprotProxySequenceReader(uniProtID,set); + AminoAcidCompoundSet set = AminoAcidCompoundSet.aminoAcidCompoundSet; + UniprotProxySequenceReader uniprotSequence = new UniprotProxySequenceReader<>(uniProtID, set); ProteinSequence seq = new ProteinSequence(uniprotSequence); diff --git a/biojava-protein-disorder/src/main/java/org/biojava/nbio/data/sequence/FastaSequence.java b/biojava-protein-disorder/src/main/java/org/biojava/nbio/data/sequence/FastaSequence.java index 6af6f13712..b915989ebb 100644 --- a/biojava-protein-disorder/src/main/java/org/biojava/nbio/data/sequence/FastaSequence.java +++ b/biojava-protein-disorder/src/main/java/org/biojava/nbio/data/sequence/FastaSequence.java @@ -26,8 +26,7 @@ import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +import java.util.Objects; /** * A FASTA formatted sequence. Please note that this class does not make any @@ -41,173 +40,150 @@ */ @XmlAccessorType(XmlAccessType.FIELD) -public final class FastaSequence implements Comparable{ - - /** - * Sequence id - */ - private String id; - - // TODO what about gapped sequence here! should be indicated - /** - * Returns the string representation of sequence - */ - private String sequence; - - @SuppressWarnings("unused") - private FastaSequence() { - // Default constructor for JaxB - } - - /** - * Upon construction the any whitespace characters are removed from the - * sequence - * - * @param id - * @param sequence - */ - public FastaSequence(final String id, final String sequence) { - this.id = id.trim(); - this.sequence = SequenceUtil.cleanSequence(sequence); - } - - /** - * Gets the value of id - * - * @return the value of id - */ - public String getId() { - return id; - } - - /** - * Gets the value of sequence - * - * @return the value of sequence - */ - public String getSequence() { - return sequence; - } - - public static int countMatchesInSequence(final String theString, - final String theRegExp) { - final Pattern p = Pattern.compile(theRegExp); - final Matcher m = p.matcher(theString); - int cnt = 0; - while (m.find()) { - cnt++; - } - return cnt; - } - - public String getFormattedFasta() { - return getFormatedSequence(80); - } - - /** - * - * @return one line name, next line sequence, no matter what the sequence - * length is - */ - public String getOnelineFasta() { - String fasta = ">" + getId() + "\n"; - fasta += getSequence() + "\n"; - return fasta; - } - - /** - * Format sequence per width letter in one string. Without spaces. - * - * @return multiple line formated sequence, one line width letters length - * - */ - public String getFormatedSequence(final int width) { - if (sequence == null) { - return ""; - } - - assert width >= 0 : "Wrong width parameter "; - - final StringBuilder sb = new StringBuilder(sequence); - int nchunks = sequence.length() / width; - // add up inserted new line chars - nchunks = (nchunks + sequence.length()) / width; - int nlineCharcounter = 0; - for (int i = 1; i <= nchunks; i++) { - final int insPos = width * i + nlineCharcounter; - // to prevent inserting new line in the very end of a sequence then - // it would have failed. - // Also covers the case when the sequences shorter than width - if (sb.length() <= insPos) { - break; - } - sb.insert(insPos, "\n"); - nlineCharcounter++; - } - return sb.toString(); - } - - /** - * - * @return sequence length - */ - public int getLength() { - return sequence.length(); - } - - /** - * Same as oneLineFasta - */ - @Override - public String toString() { - return this.getOnelineFasta(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result - + ((sequence == null) ? 0 : sequence.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final FastaSequence other = (FastaSequence) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (sequence == null) { - if (other.sequence != null) { - return false; - } - } else if (!sequence.equals(other.sequence)) { - return false; - } - return true; - } - - @Override - public int compareTo(FastaSequence o) { - if(o==null || o.id==null) - return 1; - - return this.getId().compareTo(o.id); - } +public final class FastaSequence implements Comparable { + + /** + * Sequence id + */ + private String id; + + // TODO what about gapped sequence here! should be indicated + /** + * Returns the string representation of sequence + */ + private String sequence; + + @SuppressWarnings("unused") + private FastaSequence() { + // Default constructor for JaxB + } + + /** + * Upon construction the any whitespace characters are removed from the + * sequence + * + * @param id + * @param sequence + */ + public FastaSequence(final String id, final String sequence) { + this.id = id.trim(); + this.sequence = SequenceUtil.cleanSequence(sequence); + } + + /** + * Gets the value of id + * + * @return the value of id + */ + public String getId() { + return id; + } + + /** + * Gets the value of sequence + * + * @return the value of sequence + */ + public String getSequence() { + return sequence; + } + +// public static int countMatchesInSequence(final String theString, +// final String theRegExp) { +// final Pattern p = Pattern.compile(theRegExp); +// final Matcher m = p.matcher(theString); +// int cnt = 0; +// while (m.find()) { +// cnt++; +// } +// return cnt; +// } + + public String getFormattedFasta() { + return getFormatedSequence(80); + } + + /** + * @return one line name, next line sequence, no matter what the sequence + * length is + */ + public String getOnelineFasta() { + return ">" + getId() + "\n" + (getSequence() + "\n"); + } + + /** + * Format sequence per width letter in one string. Without spaces. + * + * @return multiple line formated sequence, one line width letters length + */ + public String getFormatedSequence(final int width) { + if (sequence == null) { + return ""; + } + + assert width >= 0 : "Wrong width parameter "; + + final StringBuilder sb = new StringBuilder(sequence); + int nchunks = sequence.length() / width; + // add up inserted new line chars + nchunks = (nchunks + sequence.length()) / width; + int nlineCharcounter = 0; + for (int i = 1; i <= nchunks; i++) { + final int insPos = width * i + nlineCharcounter; + // to prevent inserting new line in the very end of a sequence then + // it would have failed. + // Also covers the case when the sequences shorter than width + if (sb.length() <= insPos) { + break; + } + sb.insert(insPos, "\n"); + nlineCharcounter++; + } + return sb.toString(); + } + + /** + * @return sequence length + */ + public int getLength() { + return sequence.length(); + } + + /** + * Same as oneLineFasta + */ + @Override + public String toString() { + return this.getOnelineFasta(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((sequence == null) ? 0 : sequence.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + + if (obj == null || getClass() != obj.getClass()) + return false; + + final FastaSequence other = (FastaSequence) obj; + return Objects.equals(id, other.id) && Objects.equals(sequence, other.sequence); + } + + @Override + public int compareTo(FastaSequence o) { + if (o == null || o.id == null) + return 1; + + return this.getId().compareTo(o.id); + } } diff --git a/biojava-protein-disorder/src/main/java/org/biojava/nbio/data/sequence/SequenceUtil.java b/biojava-protein-disorder/src/main/java/org/biojava/nbio/data/sequence/SequenceUtil.java index 55b9bc5cc6..096927f51d 100644 --- a/biojava-protein-disorder/src/main/java/org/biojava/nbio/data/sequence/SequenceUtil.java +++ b/biojava-protein-disorder/src/main/java/org/biojava/nbio/data/sequence/SequenceUtil.java @@ -29,6 +29,7 @@ import org.slf4j.LoggerFactory; import java.io.*; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; @@ -43,255 +44,251 @@ */ public final class SequenceUtil { - private static final Logger logger = LoggerFactory.getLogger(SequenceUtil.class); - - /** - * A whitespace character: [\t\n\x0B\f\r] - */ - public static final Pattern WHITE_SPACE = Pattern.compile("\\s"); - - /** - * A digit - */ - public static final Pattern DIGIT = Pattern.compile("\\d"); - - /** - * Non word - */ - public static final Pattern NONWORD = Pattern.compile("\\W"); - - /** - * Valid Amino acids - */ - public static final Pattern AA = Pattern.compile("[ARNDCQEGHILKMFPSTWYVUO]+", - Pattern.CASE_INSENSITIVE); - - /** - * inversion of AA pattern - */ - public static final Pattern NON_AA = Pattern.compile( - "[^ARNDCQEGHILKMFPSTWYVXUO]+", Pattern.CASE_INSENSITIVE); - - /** - * Same as AA pattern but with one additional letters - X - */ - public static final Pattern AMBIGUOUS_AA = Pattern.compile( - "[ARNDCQEGHILKMFPSTWYVXUO]+", Pattern.CASE_INSENSITIVE); - - /** - * Nucleotides a, t, g, c, u - */ - public static final Pattern NUCLEOTIDE = Pattern.compile("[AGTCU]+", - Pattern.CASE_INSENSITIVE); - - /** - * Ambiguous nucleotide - */ - public static final Pattern AMBIGUOUS_NUCLEOTIDE = Pattern.compile( - "[AGTCRYMKSWHBVDNU]+", Pattern.CASE_INSENSITIVE); // see IUPAC - /** - * Non nucleotide - */ - public static final Pattern NON_NUCLEOTIDE = Pattern.compile("[^AGTCU]+", - Pattern.CASE_INSENSITIVE); - - private SequenceUtil() { - } // utility class, no instantiation - - /* - * public static void write_PirSeq(OutputStream os, FastaSequence seq) - * throws IOException { BufferedWriter pir_out = new BufferedWriter(new - * OutputStreamWriter(os)); pir_out.write(">P1;" + seq.getId() + - * SysPrefs.newlinechar); pir_out.write(seq.getSequence() + - * SysPrefs.newlinechar); pir_out.close(); } - * - * public static void write_FastaSeq(OutputStream os, FastaSequence seq) - * throws IOException { BufferedWriter fasta_out = new BufferedWriter( new - * OutputStreamWriter(os)); fasta_out.write(">" + seq.getId() + - * SysPrefs.newlinechar); fasta_out.write(seq.getSequence() + - * SysPrefs.newlinechar); fasta_out.close(); } - */ - - /** - * @return true is the sequence contains only letters a,c, t, g, u - */ - public static boolean isNucleotideSequence(final FastaSequence s) { - return SequenceUtil.isNonAmbNucleotideSequence(s.getSequence()); - } - - /** - * Ambiguous DNA chars : AGTCRYMKSWHBVDN // differs from protein in only one - * (!) - B char - */ - public static boolean isNonAmbNucleotideSequence(String sequence) { - sequence = SequenceUtil.cleanSequence(sequence); - if (SequenceUtil.DIGIT.matcher(sequence).find()) { - return false; - } - if (SequenceUtil.NON_NUCLEOTIDE.matcher(sequence).find()) { - return false; - /* - * System.out.format("I found the text starting at " + - * "index %d and ending at index %d.%n", nonDNAmatcher .start(), - * nonDNAmatcher.end()); - */ - } - final Matcher DNAmatcher = SequenceUtil.NUCLEOTIDE.matcher(sequence); - return DNAmatcher.find(); - } - - /** - * Removes all whitespace chars in the sequence string - * - * @param sequence - * @return cleaned up sequence - */ - public static String cleanSequence(String sequence) { - assert sequence != null; - final Matcher m = SequenceUtil.WHITE_SPACE.matcher(sequence); - sequence = m.replaceAll("").toUpperCase(); - return sequence; - } - - /** - * Removes all special characters and digits as well as whitespace chars - * from the sequence - * - * @param sequence - * @return cleaned up sequence - */ - public static String deepCleanSequence(String sequence) { - sequence = SequenceUtil.cleanSequence(sequence); - sequence = SequenceUtil.DIGIT.matcher(sequence).replaceAll(""); - sequence = SequenceUtil.NONWORD.matcher(sequence).replaceAll(""); - final Pattern othernonSeqChars = Pattern.compile("[_-]+"); - sequence = othernonSeqChars.matcher(sequence).replaceAll(""); - return sequence; - } - - /** - * - * @param sequence - * @return true is the sequence is a protein sequence, false overwise - */ - public static boolean isProteinSequence(String sequence) { - sequence = SequenceUtil.cleanSequence(sequence); - if (SequenceUtil.isNonAmbNucleotideSequence(sequence)) { - return false; - } - if (SequenceUtil.DIGIT.matcher(sequence).find()) { - return false; - } - if (SequenceUtil.NON_AA.matcher(sequence).find()) { - logger.info("Found non aa: {}", sequence); - return false; - } - final Matcher protmatcher = SequenceUtil.AA.matcher(sequence); - return protmatcher.find(); - } - - /** - * Check whether the sequence confirms to amboguous protein sequence - * - * @param sequence - * @return return true only if the sequence if ambiguous protein sequence - * Return false otherwise. e.g. if the sequence is non-ambiguous - * protein or DNA - */ - public static boolean isAmbiguosProtein(String sequence) { - sequence = SequenceUtil.cleanSequence(sequence); - if (SequenceUtil.isNonAmbNucleotideSequence(sequence)) { - return false; - } - if (SequenceUtil.DIGIT.matcher(sequence).find()) { - return false; - } - if (SequenceUtil.NON_AA.matcher(sequence).find()) { - return false; - } - if (SequenceUtil.AA.matcher(sequence).find()) { - return false; - } - final Matcher amb_prot = SequenceUtil.AMBIGUOUS_AA.matcher(sequence); - return amb_prot.find(); - } - - /** - * Writes list of FastaSequeces into the outstream formatting the sequence - * so that it contains width chars on each line - * - * @param outstream - * @param sequences - * @param width - * - the maximum number of characters to write in one line - * @throws IOException - */ - public static void writeFasta(final OutputStream outstream, - final List sequences, final int width) - throws IOException { - final OutputStreamWriter writer = new OutputStreamWriter(outstream); - final BufferedWriter fastawriter = new BufferedWriter(writer); - for (final FastaSequence fs : sequences) { - fastawriter.write(fs.getFormatedSequence(width)); - } - outstream.flush(); - fastawriter.close(); - writer.close(); - } - - /** - * Reads fasta sequences from inStream into the list of FastaSequence - * objects - * - * @param inStream - * from - * @return list of FastaSequence objects - * @throws IOException - */ - public static List readFasta(final InputStream inStream) - throws IOException { - final List seqs = new ArrayList(); - - final BufferedReader infasta = new BufferedReader( - new InputStreamReader(inStream, "UTF8"), 16000); - final Pattern pattern = Pattern.compile("//s+"); - - String line; - String sname = "", seqstr = null; - do { - line = infasta.readLine(); - if ((line == null) || line.startsWith(">")) { - if (seqstr != null) { - seqs.add(new FastaSequence(sname.substring(1), seqstr)); - } - sname = line; // remove > - seqstr = ""; - } else { - final String subseq = pattern.matcher(line).replaceAll(""); - seqstr += subseq; - } - } while (line != null); - - infasta.close(); - return seqs; - } - - /** - * Writes FastaSequence in the file, each sequence will take one line only - * - * @param os - * @param sequences - * @throws IOException - */ - public static void writeFasta(final OutputStream os, - final List sequences) throws IOException { - final OutputStreamWriter outWriter = new OutputStreamWriter(os); - final BufferedWriter fasta_out = new BufferedWriter(outWriter); - for (final FastaSequence fs : sequences) { - fasta_out.write(fs.getOnelineFasta()); - } - fasta_out.close(); - outWriter.close(); - } + private static final Logger logger = LoggerFactory.getLogger(SequenceUtil.class); + + /** + * A whitespace character: [\t\n\x0B\f\r] + */ + public static final Pattern WHITE_SPACE = Pattern.compile("\\s"); + + /** + * A digit + */ + public static final Pattern DIGIT = Pattern.compile("\\d"); + + /** + * Non word + */ + public static final Pattern NONWORD = Pattern.compile("\\W"); + + /** + * Valid Amino acids + */ + public static final Pattern AA = Pattern.compile("[ARNDCQEGHILKMFPSTWYVUO]+", + Pattern.CASE_INSENSITIVE); + + /** + * inversion of AA pattern + */ + public static final Pattern NON_AA = Pattern.compile( + "[^ARNDCQEGHILKMFPSTWYVXUO]+", Pattern.CASE_INSENSITIVE); + + /** + * Same as AA pattern but with one additional letters - X + */ + public static final Pattern AMBIGUOUS_AA = Pattern.compile( + "[ARNDCQEGHILKMFPSTWYVXUO]+", Pattern.CASE_INSENSITIVE); + + /** + * Nucleotides a, t, g, c, u + */ + public static final Pattern NUCLEOTIDE = Pattern.compile("[AGTCU]+", + Pattern.CASE_INSENSITIVE); + + /** + * Ambiguous nucleotide + */ + public static final Pattern AMBIGUOUS_NUCLEOTIDE = Pattern.compile( + "[AGTCRYMKSWHBVDNU]+", Pattern.CASE_INSENSITIVE); // see IUPAC + /** + * Non nucleotide + */ + public static final Pattern NON_NUCLEOTIDE = Pattern.compile("[^AGTCU]+", + Pattern.CASE_INSENSITIVE); + + private SequenceUtil() { + } // utility class, no instantiation + + /* + * public static void write_PirSeq(OutputStream os, FastaSequence seq) + * throws IOException { BufferedWriter pir_out = new BufferedWriter(new + * OutputStreamWriter(os)); pir_out.write(">P1;" + seq.getId() + + * SysPrefs.newlinechar); pir_out.write(seq.getSequence() + + * SysPrefs.newlinechar); pir_out.close(); } + * + * public static void write_FastaSeq(OutputStream os, FastaSequence seq) + * throws IOException { BufferedWriter fasta_out = new BufferedWriter( new + * OutputStreamWriter(os)); fasta_out.write(">" + seq.getId() + + * SysPrefs.newlinechar); fasta_out.write(seq.getSequence() + + * SysPrefs.newlinechar); fasta_out.close(); } + */ + + /** + * @return true is the sequence contains only letters a,c, t, g, u + */ + public static boolean isNucleotideSequence(final FastaSequence s) { + return SequenceUtil.isNonAmbNucleotideSequence(s.getSequence()); + } + + /** + * Ambiguous DNA chars : AGTCRYMKSWHBVDN // differs from protein in only one + * (!) - B char + */ + public static boolean isNonAmbNucleotideSequence(String sequence) { + + sequence = SequenceUtil.cleanSequence(sequence); + + if (SequenceUtil.DIGIT.matcher(sequence).find()) + return false; + + if (SequenceUtil.NON_NUCLEOTIDE.matcher(sequence).find()) + return false; + /* + * System.out.format("I found the text starting at " + + * "index %d and ending at index %d.%n", nonDNAmatcher .start(), + * nonDNAmatcher.end()); + */ + + return SequenceUtil.NUCLEOTIDE.matcher(sequence).find(); + } + + /** + * Removes all whitespace chars in the sequence string + * + * @param sequence + * @return cleaned up sequence + */ + public static String cleanSequence(String sequence) { + assert sequence != null; + return SequenceUtil.WHITE_SPACE.matcher(sequence).replaceAll("").toUpperCase(); + } + + /** + * Removes all special characters and digits as well as whitespace chars + * from the sequence + * + * @param sequence + * @return cleaned up sequence + */ + public static String deepCleanSequence(String sequence) { + sequence = SequenceUtil.cleanSequence(sequence); + sequence = SequenceUtil.DIGIT.matcher(sequence).replaceAll(""); + sequence = SequenceUtil.NONWORD.matcher(sequence).replaceAll(""); + final Pattern othernonSeqChars = Pattern.compile("[_-]+"); + sequence = othernonSeqChars.matcher(sequence).replaceAll(""); + return sequence; + } + + /** + * @param sequence + * @return true is the sequence is a protein sequence, false overwise + */ + public static boolean isProteinSequence(String sequence) { + sequence = SequenceUtil.cleanSequence(sequence); + if (SequenceUtil.isNonAmbNucleotideSequence(sequence)) { + return false; + } + if (SequenceUtil.DIGIT.matcher(sequence).find()) { + return false; + } + if (SequenceUtil.NON_AA.matcher(sequence).find()) { + logger.info("Found non aa: {}", sequence); + return false; + } + final Matcher protmatcher = SequenceUtil.AA.matcher(sequence); + return protmatcher.find(); + } + + /** + * Check whether the sequence confirms to amboguous protein sequence + * + * @param sequence + * @return return true only if the sequence if ambiguous protein sequence + * Return false otherwise. e.g. if the sequence is non-ambiguous + * protein or DNA + */ + public static boolean isAmbiguosProtein(String sequence) { + sequence = SequenceUtil.cleanSequence(sequence); + if (SequenceUtil.isNonAmbNucleotideSequence(sequence)) { + return false; + } + if (SequenceUtil.DIGIT.matcher(sequence).find()) { + return false; + } + if (SequenceUtil.NON_AA.matcher(sequence).find()) { + return false; + } + if (SequenceUtil.AA.matcher(sequence).find()) { + return false; + } + final Matcher amb_prot = SequenceUtil.AMBIGUOUS_AA.matcher(sequence); + return amb_prot.find(); + } + + /** + * Writes list of FastaSequeces into the outstream formatting the sequence + * so that it contains width chars on each line + * + * @param outstream + * @param sequences + * @param width - the maximum number of characters to write in one line + * @throws IOException + */ + public static void writeFasta(final OutputStream outstream, + final List sequences, final int width) + throws IOException { + final OutputStreamWriter writer = new OutputStreamWriter(outstream); + final BufferedWriter fastawriter = new BufferedWriter(writer); + for (final FastaSequence fs : sequences) { + fastawriter.write(fs.getFormatedSequence(width)); + } + outstream.flush(); + fastawriter.close(); + writer.close(); + } + + /** + * Reads fasta sequences from inStream into the list of FastaSequence + * objects + * + * @param inStream from + * @return list of FastaSequence objects + * @throws IOException + */ + public static List readFasta(final InputStream inStream) + throws IOException { + final List seqs = new ArrayList<>(); + + final BufferedReader infasta = new BufferedReader( + new InputStreamReader(inStream, StandardCharsets.UTF_8), 16000); + final Pattern pattern = Pattern.compile("//s+"); + + String line; + String sname = "", seqstr = null; + do { + line = infasta.readLine(); + if ((line == null) || line.startsWith(">")) { + if (seqstr != null) { + seqs.add(new FastaSequence(sname.substring(1), seqstr)); + } + sname = line; // remove > + seqstr = ""; + } else { + final String subseq = pattern.matcher(line).replaceAll(""); + seqstr += subseq; + } + } while (line != null); + + infasta.close(); + return seqs; + } + + /** + * Writes FastaSequence in the file, each sequence will take one line only + * + * @param os + * @param sequences + * @throws IOException + */ + public static void writeFasta(final OutputStream os, + final List sequences) throws IOException { + final OutputStreamWriter outWriter = new OutputStreamWriter(os); + final BufferedWriter fasta_out = new BufferedWriter(outWriter); + for (final FastaSequence fs : sequences) { + fasta_out.write(fs.getOnelineFasta()); + } + fasta_out.close(); + outWriter.close(); + } } diff --git a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/Jronn.java b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/Jronn.java index 60b259aff2..f886cfec54 100644 --- a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/Jronn.java +++ b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/Jronn.java @@ -58,9 +58,7 @@ public class Jronn implements Serializable { static { try { loader.loadModels(); - } catch (NumberFormatException e) { - throw new RuntimeException("Fails to load models!" + e.getMessage(), e); - } catch (IOException e) { + } catch (NumberFormatException | IOException e) { throw new RuntimeException("Fails to load models!" + e.getMessage(), e); } } @@ -157,7 +155,7 @@ public static float[] getDisorderScores(ProteinSequence sequence) { * @return */ public static FastaSequence convertProteinSequencetoFasta(ProteinSequence sequence){ - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); for (AminoAcidCompound compound : sequence) { String c = compound.getShortName(); @@ -175,14 +173,12 @@ public static FastaSequence convertProteinSequencetoFasta(ProteinSequence sequen private static float[] predictSerial(FastaSequence fsequence) { ORonn.validateSequenceForRonn(fsequence); ORonn ronn; - float[] disorder = null; + float[] disorder; try { ronn = new ORonn(fsequence, loader); disorder = ronn.call().getMeanScores(); } catch (NumberFormatException e) { throw new RuntimeException("Jronn fails to load models " + e.getLocalizedMessage(), e); - } catch (IOException e) { - throw new RuntimeException("Jronn fails to load models " + e.getLocalizedMessage(), e); } return disorder; } @@ -215,7 +211,7 @@ public static Range[] scoresToRanges(float[] scores, float probability) { int count=0; int regionLen=0; - List ranges = new ArrayList(); + List ranges = new ArrayList<>(); for(float score: scores) { count++; // Round to 2 decimal points before comparison @@ -233,7 +229,7 @@ public static Range[] scoresToRanges(float[] scores, float probability) { if(regionLen>1) { ranges.add(new Range(count-regionLen+1, count,scores[scores.length-1])); } - return ranges.toArray(new Range[ranges.size()]); + return ranges.toArray(new Range[0]); } @@ -246,7 +242,7 @@ public static Range[] scoresToRanges(float[] scores, float probability) { * @see #getDisorder(FastaSequence) */ public static Map getDisorderScores(List sequences) { - Map results = new TreeMap(); + Map results = new TreeMap<>(); for(FastaSequence fsequence : sequences) { results.put(fsequence, predictSerial(fsequence)); } @@ -261,7 +257,7 @@ public static Map getDisorderScores(List s * @see #getDisorder(FastaSequence) */ public static Map getDisorder(List sequences) { - Map disorderRanges = new TreeMap(); + Map disorderRanges = new TreeMap<>(); for(FastaSequence fs: sequences) { disorderRanges.put(fs, getDisorder(fs)); } diff --git a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ModelLoader.java b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ModelLoader.java index f6eb3aac47..7e6bc4e872 100644 --- a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ModelLoader.java +++ b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ModelLoader.java @@ -33,6 +33,7 @@ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashMap; import java.util.Map; @@ -94,8 +95,8 @@ public static class Model { */ final float[] W;// = new float[RonnConstraint.maxD]; - int numOfDBAAseq; - int modelNum = -1; + final int numOfDBAAseq; + final int modelNum; public Model(final int modelNum, final int numberofSequence) { this.modelNum = modelNum; @@ -155,7 +156,7 @@ public String toString() { } - private static final Map models = new HashMap(); + private static final Map models = new HashMap<>(); public Model getModel(final int modelNum) { return ModelLoader.models.get(modelNum); @@ -167,8 +168,8 @@ void loadModels() throws NumberFormatException, IOException { final BufferedReader bfr = new BufferedReader( new InputStreamReader(ModelLoader.class.getResourceAsStream( "model" + i + ".rec"), - "ISO-8859-1")); - String line = null; + StandardCharsets.ISO_8859_1)); + String line; line = bfr.readLine().trim(); final int numberOfSeqs = Integer.parseInt(line); final Model model = new Model(i, numberOfSeqs); diff --git a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/NullOutputStream.java b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/NullOutputStream.java index 572e4ddee6..cfcae3d36e 100644 --- a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/NullOutputStream.java +++ b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/NullOutputStream.java @@ -27,7 +27,6 @@ package org.biojava.nbio.ronn; -import java.io.IOException; import java.io.OutputStream; /** @@ -40,7 +39,7 @@ public final class NullOutputStream extends OutputStream { @Override - public void write(final int b) throws IOException { + public void write(final int b) { // this methods does nothing. // This is an intention } diff --git a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ORonn.java b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ORonn.java index 16dbcb72a1..0440e56b06 100644 --- a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ORonn.java +++ b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ORonn.java @@ -26,7 +26,6 @@ import org.biojava.nbio.data.sequence.FastaSequence; import org.biojava.nbio.data.sequence.SequenceUtil; -import org.biojava.nbio.ronn.ModelLoader.Model; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -91,8 +90,7 @@ public final class ORonn implements Callable { timer = new Timer(TimeUnit.MILLISECONDS); } //This constructor is for API calls where the caller collects the results directly - ORonn(final FastaSequence sequence, final ModelLoader mloader) throws NumberFormatException, - IOException { + ORonn(final FastaSequence sequence, final ModelLoader mloader) throws NumberFormatException { this.sequence = sequence; this.mloader = mloader; out = new PrintWriter(new NullOutputStream()); @@ -136,23 +134,16 @@ static boolean isValidSequence(final FastaSequence fsequence) { } @Override - public ORonn call() throws NumberFormatException, IOException { + public ORonn call() throws NumberFormatException { final String seq = sequence.getSequence(); // Calculate for each model - for (int m = 0; m < ORonn.NUMBER_OF_MODELS; m++) { - final Model model = mloader.getModel(m); - final ORonnModel rmodel = new ORonnModel(seq, model, disorder); - final float[] scores = rmodel.detect(); - addScore(scores); - } + for (int m = 0; m < ORonn.NUMBER_OF_MODELS; m++) + addScore(new ORonnModel(seq, mloader.getModel(m), disorder).detect()); - final char[] ch = seq.toCharArray(); final float[] meanScores = getMeanScores(); - assert meanScores.length == seq.length() : "Scores are not calculated for " - + "all residues!"; - writeResults(meanScores, ch); - stat.println(timer.getTotalTime() + "ms prediction completed for " - + sequence.getId()); + assert meanScores.length == seq.length() : "Scores are not calculated for all residues!"; + writeResults(meanScores, seq.toCharArray()); + stat.println(timer.getTotalTime() + "ms prediction completed for " + sequence.getId()); return this; } @@ -172,8 +163,9 @@ private void addScore(final float[] scores) { } float[] getMeanScores() { - final float[] meanScores = new float[cummulativeScore.length]; - for (int i = 0; i < cummulativeScore.length; i++) { + int n = cummulativeScore.length; + final float[] meanScores = new float[n]; + for (int i = 0; i < n; i++) { meanScores[i] = cummulativeScore[i] / ORonn.NUMBER_OF_MODELS; } return meanScores; @@ -190,7 +182,7 @@ float[] getMeanScores() { * sequence. Letters and values separated by tabulation in this case. * */ - static enum ResultLayout { + enum ResultLayout { VERTICAL, HORIZONTAL } @@ -201,7 +193,7 @@ static void printUsage() { static boolean isValidSequenceForRonn(final FastaSequence fsequence, final PrintWriter stat) { boolean valid = true; - String message = ""; + String message; if (!ORonn.isValidSequence(fsequence)) { message = "IGNORING sequence " + fsequence.getId() @@ -225,7 +217,7 @@ static boolean isValidSequenceForRonn(final FastaSequence fsequence, static void validateSequenceForRonn(final FastaSequence fsequence) { - String message = ""; + String message; if (!ORonn.isValidSequence(fsequence)) { message = "IGNORING sequence " + fsequence.getId() @@ -353,7 +345,7 @@ static void predictParallel(final List fsequences, // Do parallel execution final ExecutorService executor = new ThreadPoolExecutor(prms .getThreadNum(), prms.getThreadNum(), 0L, TimeUnit.SECONDS, - new SynchronousQueue(), + new SynchronousQueue<>(), new ThreadPoolExecutor.CallerRunsPolicy()); try { for (final FastaSequence sequence : fsequences) { @@ -369,8 +361,7 @@ static void predictParallel(final List fsequences, executor.submit(ronn); } executor.shutdown(); - final int timeOut = (fsequences.size() < 60) ? 60 : fsequences - .size(); + final int timeOut = Math.max(fsequences.size(), 60); stat.println("All task submitted. Waiting for complition for " + "maximum of " + timeOut + " minutes"); executor.awaitTermination(timeOut, TimeUnit.MINUTES); diff --git a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ORonnModel.java b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ORonnModel.java index 41253be8c1..98a027ddf7 100644 --- a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ORonnModel.java +++ b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/ORonnModel.java @@ -34,7 +34,6 @@ import java.io.PrintWriter; - /** * Fully re-factored version of RONN model. Based on the code in C version of * RONN. @@ -45,142 +44,142 @@ */ public final class ORonnModel { - private static final Logger logger = LoggerFactory.getLogger(ORonnModel.class); - - /** - * Order probability, corresponds to disorder as 1-order - */ - private final float disorder_weight; - - private final static int AA_ALPHABET = 19; - private final static int maxR = 110; - //private final static float coef = 1.0f; - /** - * Holds encoded query sequence - */ - private final short[] seqAA; - /** - * Holds query sequence - */ - private final char[] query; - - private final Model model; - - /** - * Disorder scores for all residues - */ - private float[] scores = null; - - final float[] detect() { - - scores = new float[query.length]; - int sResidue; - int dIndex; - int r; - float est, fOrder, pDisor, fDisor; - final float[][] Z = new float[seqAA.length][ORonnModel.maxR]; - final int[] Q = new int[seqAA.length]; - final Threshold thold = new ModelLoader.Threshold(model.modelNum); - - /* - * 19 looks like a size of the sliding window. So for any sequences - * shorted than 19 AA the score will be NaN. Original RONN segfault in - * such condition - */ - for (sResidue = 0; sResidue <= query.length - ORonnModel.AA_ALPHABET; sResidue++) { - est = 0.0f; - - for (dIndex = 0; dIndex < model.numOfDBAAseq; dIndex++) { - final float[] rho = align(sResidue, dIndex);// search for the - // maximum alignment between ith peptide from the - // query and the dIndex-th database sequence - est += model.W[dIndex] * Math.exp((rho[1] - rho[0]) / rho[0]); - } - - fOrder = (float) (Math.exp(-0.5 * Math.pow(est - thold.mu0, 2.0) - / thold.sigma0) / (Math.sqrt(6.28) * thold.sigma0)); - - fDisor = (float) (Math.exp(-0.5 * Math.pow(est - thold.mu1, 2.0) - / thold.sigma1) / (Math.sqrt(6.28) * thold.sigma1)); - - pDisor = (float) (disorder_weight * fDisor / ((1.0 - disorder_weight) - * fOrder + disorder_weight * fDisor)); - for (r = sResidue; r < sResidue + ORonnModel.AA_ALPHABET; r++) { - Z[r][Q[r]] = pDisor; - Q[r]++; - } - } - - for (sResidue = 0; sResidue < query.length; sResidue++) { - est = 0.0f; - float[] zRow = Z[sResidue]; - int numOfIterations = Q[sResidue]; - for (r = 0; r < numOfIterations; r++) { - est += zRow[r]; - } - scores[sResidue] = est / numOfIterations; - } - return scores; - } - - public void getScores(final File outfile) throws FileNotFoundException { - final PrintWriter output = new PrintWriter(outfile); - if (scores == null) { - synchronized (this) { - if (scores == null) { - detect(); - } - } - } - for (int i = 0; i < scores.length; i++) { - output.printf("%c\t%f\n", query[i], scores[i]); - } - output.close(); - } - - // sResidue query sequence index and dIndex database sequence index - private final float[] align(final int sResidue, final int dIndex) { - int dResidue, r; - float maxScore = -1000000; - float rho1 = 0; - int maxIdx = 0; - float rho0 = 0; - short[] dbAARow = model.dbAA[dIndex]; - int numOfIterations = model.Length[dIndex] - ORonnModel.AA_ALPHABET; - for (dResidue = 0; dResidue <= numOfIterations; dResidue++) { - // go though the database sequence for maximised alignment - rho1 = 0.0f; - for (r = 0; r < ORonnModel.AA_ALPHABET; r++) { - // go through the query sequence for one alignment - rho1 += RonnConstraint.Blosum62[seqAA[sResidue + r]][dbAARow[dResidue - + r]]; - } - if (rho1 > maxScore) { - maxScore = rho1; - maxIdx = dResidue; - } - } - for (r = 0; r < ORonnModel.AA_ALPHABET; r++) { - rho0 += RonnConstraint.Blosum62[dbAARow[maxIdx + r]][dbAARow[maxIdx - + r]]; - } - return new float[] { rho0, maxScore }; - } - - public ORonnModel(final String sequence, final Model model, - final float disorder) throws NumberFormatException { - this.disorder_weight = disorder; - this.model = model; - query = sequence.toCharArray(); - seqAA = new short[query.length]; - assert model != null; - assert model.numOfDBAAseq > 0; - for (int sResidue = 0; sResidue < sequence.length(); sResidue++) { - seqAA[sResidue] = RonnConstraint.INDEX[query[sResidue] - 'A']; - if ((seqAA[sResidue] < 0) || (seqAA[sResidue] > 19)) { - logger.error("seqAA[sResidue]={}({})", seqAA[sResidue], query[sResidue]); - System.exit(1); - } - } - } + private static final Logger logger = LoggerFactory.getLogger(ORonnModel.class); + + /** + * Order probability, corresponds to disorder as 1-order + */ + private final float disorder_weight; + + private final static int AA_ALPHABET = 19; + private final static int maxR = 110; + //private final static float coef = 1.0f; + /** + * Holds encoded query sequence + */ + private final short[] seqAA; + /** + * Holds query sequence + */ + private final char[] query; + + private final Model model; + + /** + * Disorder scores for all residues + */ + private float[] scores = null; + + final float[] detect() { + + scores = new float[query.length]; + int sResidue; + int dIndex; + int r; + double est, fOrder, pDisor, fDisor; + final float[][] Z = new float[seqAA.length][ORonnModel.maxR]; + final int[] Q = new int[seqAA.length]; + final Threshold thold = new ModelLoader.Threshold(model.modelNum); + + /* + * 19 looks like a size of the sliding window. So for any sequences + * shorted than 19 AA the score will be NaN. Original RONN segfault in + * such condition + */ + for (sResidue = 0; sResidue <= query.length - ORonnModel.AA_ALPHABET; sResidue++) { + est = 0.0; + + for (dIndex = 0; dIndex < model.numOfDBAAseq; dIndex++) { + final float[] rho = align(sResidue, dIndex);// search for the + // maximum alignment between ith peptide from the + // query and the dIndex-th database sequence + est += model.W[dIndex] * Math.exp((rho[1] - rho[0]) / rho[0]); + } + + fOrder = (float) (Math.exp(-0.5 * Math.pow(est - thold.mu0, 2.0) + / thold.sigma0) / (Math.sqrt(6.28) * thold.sigma0)); + + fDisor = (float) (Math.exp(-0.5 * Math.pow(est - thold.mu1, 2.0) + / thold.sigma1) / (Math.sqrt(6.28) * thold.sigma1)); + + pDisor = (float) (disorder_weight * fDisor / ((1.0 - disorder_weight) + * fOrder + disorder_weight * fDisor)); + for (r = sResidue; r < sResidue + ORonnModel.AA_ALPHABET; r++) { + Z[r][Q[r]] = (float) pDisor; + Q[r]++; + } + } + + for (sResidue = 0; sResidue < query.length; sResidue++) { + est = 0.0f; + float[] zRow = Z[sResidue]; + int numOfIterations = Q[sResidue]; + for (r = 0; r < numOfIterations; r++) + est += zRow[r]; + + scores[sResidue] = (float) (est / numOfIterations); + } + return scores; + } + + public void getScores(final File outfile) throws FileNotFoundException { + final PrintWriter output = new PrintWriter(outfile); + if (scores == null) { + synchronized (this) { + if (scores == null) { + detect(); + } + } + } + for (int i = 0; i < scores.length; i++) { + output.printf("%c\t%f\n", query[i], scores[i]); + } + output.close(); + } + + // sResidue query sequence index and dIndex database sequence index + private float[] align(final int sResidue, final int dIndex) { + int dResidue, r; + double maxScore = Double.NEGATIVE_INFINITY; + int maxIdx = 0; + float rho0 = 0; + short[] dbAARow = model.dbAA[dIndex]; + int numOfIterations = model.Length[dIndex] - ORonnModel.AA_ALPHABET; + for (dResidue = 0; dResidue <= numOfIterations; dResidue++) { + // go though the database sequence for maximised alignment + double rho1 = 0.0f; + for (r = 0; r < ORonnModel.AA_ALPHABET; r++) { + // go through the query sequence for one alignment + rho1 += RonnConstraint.Blosum62[seqAA[sResidue + r]][dbAARow[dResidue + r]]; + } + if (rho1 > maxScore) { + maxScore = rho1; + maxIdx = dResidue; + } + } + for (r = 0; r < ORonnModel.AA_ALPHABET; r++) { + rho0 += RonnConstraint.Blosum62[dbAARow[maxIdx + r]][dbAARow[maxIdx + r]]; + } + return new float[]{rho0, (float)maxScore}; + } + + public ORonnModel(final String sequence, final Model model, + final float disorder) throws NumberFormatException { + + assert model != null; + assert model.numOfDBAAseq > 0; + + this.disorder_weight = disorder; + this.model = model; + this.query = sequence.toCharArray(); + this.seqAA = new short[query.length]; + + int sLen = sequence.length(); + for (int sResidue = 0; sResidue < sLen; sResidue++) { + short r = RonnConstraint.INDEX[query[sResidue] - 'A']; + if ((r < 0) || (r > 19)) + throw new RuntimeException("seqAA[sResidue]=" + r + "(" + query[sResidue] + ")");//System.exit(1); + this.seqAA[sResidue] = r; + } + } } diff --git a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/RonnConstraint.java b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/RonnConstraint.java index dacf3067bd..4329a8e521 100644 --- a/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/RonnConstraint.java +++ b/biojava-protein-disorder/src/main/java/org/biojava/nbio/ronn/RonnConstraint.java @@ -37,197 +37,202 @@ */ public final class RonnConstraint { - public final static float DEFAULT_DISORDER = 0.53f; - public final static float DEFAULT_ORDER = 0.47f; - - public final static float DEFAULT_RANGE_PROBABILITY_THRESHOLD = 0.50f; - - // A b C D E F G H I j K L M N o P Q R S T u V W x Y - // - // 0 0 1 2 3 4 5 6 7 0 8 9 10 11 0 12 13 14 15 16 0 17 18 0 19 - - public static final short[] INDEX = new short[] { 0, 0, 1, 2, 3, 4, 5, 6, - 7, 0, 8, 9, 10, 11, 0, 12, 13, 14, 15, 16, 0, 17, 18, 0, 19 }; - - public static final short[][] Blosum62 = new short[][] { - { 4, 0, -2, -1, -2, 0, -2, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, - -2, -3, -2 }, - { 0, 9, -3, -4, -2, -3, -3, -1, -3, -1, -1, -3, -3, -3, -3, -1, -1, - -1, -2, -2 }, - { -2, -3, 6, 2, -3, -1, -1, -3, -1, -4, -3, 1, -1, 0, -2, 0, 1, -3, - -4, -3 }, - { -1, -4, 2, 5, -3, -2, 0, -3, 1, -3, -2, 0, -1, 2, 0, 0, 0, -3, - -3, -2 }, - { -2, -2, -3, -3, 6, -3, -1, 0, -3, 0, 0, -3, -4, -3, -3, -2, -2, - -1, 1, 3 }, - { 0, -3, -1, -2, -3, 6, -2, -4, -2, -4, -3, -2, -2, -2, -2, 0, 1, - 0, -2, -3 }, - { -2, -3, 1, 0, -1, -2, 8, -3, -1, -3, -2, 1, -2, 0, 0, -1, 0, -2, - -2, 2 }, - { -1, -1, -3, -3, 0, -4, -3, 4, -3, 2, 1, -3, -3, -3, -3, -2, -2, - 1, -3, -1 }, - { -1, -3, -1, 1, -3, -2, -1, -3, 5, -2, -1, 0, -1, 1, 2, 0, 0, -3, - -3, -2 }, - { -1, -1, -4, -3, 0, -4, -3, 2, -2, 4, 2, -3, -3, -2, -2, -2, -2, - 3, -2, -1 }, - { -1, -1, -3, -2, 0, -3, -2, 1, -1, 2, 5, -2, -2, 0, -1, -1, -1, - -2, -1, -1 }, - { -2, -3, 1, 0, -3, 0, -1, -3, 0, -3, -2, 6, -2, 0, 0, 1, 0, -3, - -4, -2 }, - { -1, -3, -1, -1, -4, -2, -2, -3, -1, -3, -2, -1, 7, -1, -2, -1, 1, - -2, -4, -3 }, - { -1, -3, 0, 2, -3, -2, 0, -3, 1, -2, 0, 0, -1, 5, 1, 0, 0, -2, -2, - -1 }, - { -1, -3, -2, 0, -3, -2, 0, -3, 2, -2, -1, 0, -2, 1, 5, -1, -1, -3, - -3, -2 }, - { 1, -1, 0, 0, -2, 0, -1, -2, 0, -2, -1, 1, -1, 0, -1, 4, 1, -2, - -3, -2 }, - { -1, -1, 1, 0, -2, 1, 0, -2, 0, -2, -1, 0, 1, 0, -1, 1, 4, -2, -3, - -2 }, - { 0, -1, -3, -2, -1, -3, -3, 3, -2, 1, 1, -3, -2, -2, -3, -2, -2, - 4, -3, -1 }, - { -3, -2, -4, -3, 1, -2, -2, -3, -3, -2, -1, -4, -4, -2, -3, -3, - -3, -3, 11, 2 }, - { -2, -2, -3, -2, 3, -3, 2, -1, -2, -1, -1, -2, -3, -1, -2, -2, -2, - -1, 2, 7 } }; - - public static enum Threshold { - T0(0, RonnConstraint.THRESHOLD0), T1(1, RonnConstraint.THRESHOLD1), T2( - 2, RonnConstraint.THRESHOLD2), T3(3, RonnConstraint.THRESHOLD3), T4( - 4, RonnConstraint.THRESHOLD4), T5(5, RonnConstraint.THRESHOLD5), T6( - 6, RonnConstraint.THRESHOLD6), T7(7, RonnConstraint.THRESHOLD7), T8( - 8, RonnConstraint.THRESHOLD8), T9(9, RonnConstraint.THRESHOLD9); - - private final int tnum; - private final float[] values; - - private Threshold(final int tnum, final float[] values) { - this.tnum = tnum; - this.values = values; - } - - public float[] getValues() { - return values; - } - - public static float[] getTreshold(final int number) { - assert (number >= 0) && (number < 10) : number; - for (final Threshold t : Threshold.values()) { - if (t.tnum == number) { - return t.values; - } - } - return null; - } - - } - - static final float[] THRESHOLD0 = { 0.09847548204866169f, - 0.5537946867723033f, 0.052493213903229766f, 0.07714031903493762f }; - - static final float[] THRESHOLD1 = { 0.09032956077766974f, - 0.5167594539472075f, 0.04596823441915963f, 0.06455503987769765f }; - - static final float[] THRESHOLD2 = { 0.09266796710382286f, - 0.5127732233896729f, 0.04963484289158484f, 0.061048745226114226f }; - - static final float[] THRESHOLD3 = { 0.10562230953899814f, - 0.4488757690530404f, 0.04922765471815812f, 0.0824807293665649f }; - - static final float[] THRESHOLD4 = { 0.1163716006651586f, - 0.5315238539228951f, 0.0556565226094971f, 0.0714892726762588f }; - - static final float[] THRESHOLD5 = { 0.09358976618303182f, - 0.49296410198137725f, 0.054219917228374236f, 0.06593535778132877f }; - - static final float[] THRESHOLD6 = { 0.10526844980518248f, - 0.4842710501752991f, 0.05215080306266067f, 0.06518758643119664f }; - - static final float[] THRESHOLD7 = { 0.08434396215650031f, - 0.6007148113473553f, 0.05107636795876212f, 0.10341362611675203f }; - - static final float[] THRESHOLD8 = { 0.1309148603226209f, - 0.5122245658772394f, 0.06436561753520677f, 0.06639259175313134f }; - - static final float[] THRESHOLD9 = { 0.18610705811017647f, - 0.5279244438321989f, 0.0721466513318003f, 0.07983168408322228f }; - - static final byte MIN_SEQUENCE_LENGTH = 19; - - static final String HELP_MESSAGE = " \r\n" + - "JRONN version 3.1b usage 1 August 2011:\r\n" + - "java -jar JRONN_JAR_NAME -i=inputfile \r\n" + - "\r\n" + - "Where -i=input file \r\n" + - " Input file can contain one or more FASTA formatted sequences.\r\n" + - "\r\n" + - "All OPTIONS are optional\r\n" + - "Supported OPTIONS are: \r\n" + - " -o=output file\r\n" + - " -d=disorder value\r\n" + - " -f=V or H \r\n" + - " -s=statistics file\r\n" + - " -n=number of threads to use\r\n" + - "OPTION DETAILED DESCRIPTION:\r\n" + - " -o full path to the output file, if not specified \r\n" + - " standard out is used\r\n" + - "\r\n" + - " -d the value of disorder, defaults to 0.5\r\n" + - "\r\n" + - " -f output format, V for vertical, where the letters \r\n" + - " of the sequence and corresponding disorder values are \r\n" + - " output in two column layout. H for horizontal, where the\r\n" + - " disorder values are provided under the letters of the \r\n" + - " sequence. Letters and values separated by tabulation in\r\n" + - " this case. Defaults to V.\r\n" + - "\r\n" + - " -s the file name to write execution statistics to.\r\n" + - "\r\n" + - " -n the number of threads to use. Defaults to the number of \r\n" + - " cores available on the computer. n=1 mean sequential \r\n" + - " processing. Valid values are 1 < n < (2 x num_of_cores)\r\n" + - " Default value will give the best performance.\r\n" + - " \r\n" + - "EXAMPLES: \r\n" + - "\r\n" + - " Predict disorder values for sequences from input file /home/input.fasta\r\n" + - " output the results to the standard out. Use default disorder value\r\n" + - " and utilise all cpus available on the computer.\r\n" + - "\r\n" + - " java -jar JRONN.JAR -i=/home/input.fasta\r\n" + - " \r\n" + - " Predict disorder values for sequences from input file /home/input.fasta\r\n" + - " output the results in horizontal layout to the /home/jronn.out, collect \r\n" + - " execution statistics to /home/jronn.stat.txt file and limit the number \r\n" + - " of threads to two. \r\n" + - " \r\n" + - " java -jar JRONN.JAR -i=/home/input.fasta -o=/home/jronn.out -d=0.6 -n=2 -f=H\r\n" + - " \r\n" + - " The arguments can be provided in any order.\r\n" + - "\r\n" + - "ABOUT THE PROGRAM: \r\n" + - " \r\n" + - " JRONN is a Java implementation of RONN. JRONN is based on RONN and uses the \r\n" + - " same model data, therefore gives the same predictions. Main motivation \r\n" + - " behind JRONN development was providing an implementation of RONN more \r\n" + - " suitable to use by the automated analysis pipelines and web services. \r\n" + - " \r\n" + - " Original version of RONN is described in Yang,Z.R., Thomson,R., \r\n" + - " McMeil,P. and Esnouf,R.M. (2005) RONN: the bio-basis function neural network\r\n" + - " technique applied to the detection of natively disordered regions in proteins \r\n" + - " Bioinformatics 21: 3369-3376\r\n" + - " See also http://www.strubi.ox.ac.uk/RONN\r\n" + - " \r\n" + - " Author: Peter Troshin \r\n" + - " email: to.petr AT gmail DOT com\r\n" + - " \r\n" + - " This is a free software which comes with no guarantees.\r\n" + - " JRONN is distributed under Apache Licence version 2. The full version of \r\n" + - " licence can be obtained from http://www.apache.org/licenses/LICENSE-2.0\r\n" + - " "; - /** - * 700 - maximum number of lines (with sequence values) in the single model - * file. - */ - static final int maxD = 700; + public final static float DEFAULT_DISORDER = 0.53f; + public final static float DEFAULT_ORDER = 0.47f; + + public final static float DEFAULT_RANGE_PROBABILITY_THRESHOLD = 0.50f; + + // A b C D E F G H I j K L M N o P Q R S T u V W x Y + // + // 0 0 1 2 3 4 5 6 7 0 8 9 10 11 0 12 13 14 15 16 0 17 18 0 19 + + /** + * TODO signed byte? + */ + public static final short[] INDEX = new short[]{0, 0, 1, 2, 3, 4, 5, 6, + 7, 0, 8, 9, 10, 11, 0, 12, 13, 14, 15, 16, 0, 17, 18, 0, 19}; + + /** + * TODO signed byte? + */ + public static final short[][] Blosum62 = new short[][]{ + {4, 0, -2, -1, -2, 0, -2, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, + -2, -3, -2}, + {0, 9, -3, -4, -2, -3, -3, -1, -3, -1, -1, -3, -3, -3, -3, -1, -1, + -1, -2, -2}, + {-2, -3, 6, 2, -3, -1, -1, -3, -1, -4, -3, 1, -1, 0, -2, 0, 1, -3, + -4, -3}, + {-1, -4, 2, 5, -3, -2, 0, -3, 1, -3, -2, 0, -1, 2, 0, 0, 0, -3, + -3, -2}, + {-2, -2, -3, -3, 6, -3, -1, 0, -3, 0, 0, -3, -4, -3, -3, -2, -2, + -1, 1, 3}, + {0, -3, -1, -2, -3, 6, -2, -4, -2, -4, -3, -2, -2, -2, -2, 0, 1, + 0, -2, -3}, + {-2, -3, 1, 0, -1, -2, 8, -3, -1, -3, -2, 1, -2, 0, 0, -1, 0, -2, + -2, 2}, + {-1, -1, -3, -3, 0, -4, -3, 4, -3, 2, 1, -3, -3, -3, -3, -2, -2, + 1, -3, -1}, + {-1, -3, -1, 1, -3, -2, -1, -3, 5, -2, -1, 0, -1, 1, 2, 0, 0, -3, + -3, -2}, + {-1, -1, -4, -3, 0, -4, -3, 2, -2, 4, 2, -3, -3, -2, -2, -2, -2, + 3, -2, -1}, + {-1, -1, -3, -2, 0, -3, -2, 1, -1, 2, 5, -2, -2, 0, -1, -1, -1, + -2, -1, -1}, + {-2, -3, 1, 0, -3, 0, -1, -3, 0, -3, -2, 6, -2, 0, 0, 1, 0, -3, + -4, -2}, + {-1, -3, -1, -1, -4, -2, -2, -3, -1, -3, -2, -1, 7, -1, -2, -1, 1, + -2, -4, -3}, + {-1, -3, 0, 2, -3, -2, 0, -3, 1, -2, 0, 0, -1, 5, 1, 0, 0, -2, -2, + -1}, + {-1, -3, -2, 0, -3, -2, 0, -3, 2, -2, -1, 0, -2, 1, 5, -1, -1, -3, + -3, -2}, + {1, -1, 0, 0, -2, 0, -1, -2, 0, -2, -1, 1, -1, 0, -1, 4, 1, -2, + -3, -2}, + {-1, -1, 1, 0, -2, 1, 0, -2, 0, -2, -1, 0, 1, 0, -1, 1, 4, -2, -3, + -2}, + {0, -1, -3, -2, -1, -3, -3, 3, -2, 1, 1, -3, -2, -2, -3, -2, -2, + 4, -3, -1}, + {-3, -2, -4, -3, 1, -2, -2, -3, -3, -2, -1, -4, -4, -2, -3, -3, + -3, -3, 11, 2}, + {-2, -2, -3, -2, 3, -3, 2, -1, -2, -1, -1, -2, -3, -1, -2, -2, -2, + -1, 2, 7}}; + + public enum Threshold { + T0(0, RonnConstraint.THRESHOLD0), T1(1, RonnConstraint.THRESHOLD1), T2( + 2, RonnConstraint.THRESHOLD2), T3(3, RonnConstraint.THRESHOLD3), T4( + 4, RonnConstraint.THRESHOLD4), T5(5, RonnConstraint.THRESHOLD5), T6( + 6, RonnConstraint.THRESHOLD6), T7(7, RonnConstraint.THRESHOLD7), T8( + 8, RonnConstraint.THRESHOLD8), T9(9, RonnConstraint.THRESHOLD9); + + private final int tnum; + private final float[] values; + + Threshold(final int tnum, final float[] values) { + this.tnum = tnum; + this.values = values; + } + +// public float[] getValues() { +// return values; +// } + + public static float[] getTreshold(final int number) { + assert (number >= 0) && (number < 10) : number; + for (final Threshold t : Threshold.values()) { //TODO use a Map + if (t.tnum == number) + return t.values; + } + return null; + } + + } + + static final float[] THRESHOLD0 = {0.09847548204866169f, + 0.5537946867723033f, 0.052493213903229766f, 0.07714031903493762f}; + + static final float[] THRESHOLD1 = {0.09032956077766974f, + 0.5167594539472075f, 0.04596823441915963f, 0.06455503987769765f}; + + static final float[] THRESHOLD2 = {0.09266796710382286f, + 0.5127732233896729f, 0.04963484289158484f, 0.061048745226114226f}; + + static final float[] THRESHOLD3 = {0.10562230953899814f, + 0.4488757690530404f, 0.04922765471815812f, 0.0824807293665649f}; + + static final float[] THRESHOLD4 = {0.1163716006651586f, + 0.5315238539228951f, 0.0556565226094971f, 0.0714892726762588f}; + + static final float[] THRESHOLD5 = {0.09358976618303182f, + 0.49296410198137725f, 0.054219917228374236f, 0.06593535778132877f}; + + static final float[] THRESHOLD6 = {0.10526844980518248f, + 0.4842710501752991f, 0.05215080306266067f, 0.06518758643119664f}; + + static final float[] THRESHOLD7 = {0.08434396215650031f, + 0.6007148113473553f, 0.05107636795876212f, 0.10341362611675203f}; + + static final float[] THRESHOLD8 = {0.1309148603226209f, + 0.5122245658772394f, 0.06436561753520677f, 0.06639259175313134f}; + + static final float[] THRESHOLD9 = {0.18610705811017647f, + 0.5279244438321989f, 0.0721466513318003f, 0.07983168408322228f}; + + static final byte MIN_SEQUENCE_LENGTH = 19; + + static final String HELP_MESSAGE = " \r\n" + + "JRONN version 3.1b usage 1 August 2011:\r\n" + + "java -jar JRONN_JAR_NAME -i=inputfile \r\n" + + "\r\n" + + "Where -i=input file \r\n" + + " Input file can contain one or more FASTA formatted sequences.\r\n" + + "\r\n" + + "All OPTIONS are optional\r\n" + + "Supported OPTIONS are: \r\n" + + " -o=output file\r\n" + + " -d=disorder value\r\n" + + " -f=V or H \r\n" + + " -s=statistics file\r\n" + + " -n=number of threads to use\r\n" + + "OPTION DETAILED DESCRIPTION:\r\n" + + " -o full path to the output file, if not specified \r\n" + + " standard out is used\r\n" + + "\r\n" + + " -d the value of disorder, defaults to 0.5\r\n" + + "\r\n" + + " -f output format, V for vertical, where the letters \r\n" + + " of the sequence and corresponding disorder values are \r\n" + + " output in two column layout. H for horizontal, where the\r\n" + + " disorder values are provided under the letters of the \r\n" + + " sequence. Letters and values separated by tabulation in\r\n" + + " this case. Defaults to V.\r\n" + + "\r\n" + + " -s the file name to write execution statistics to.\r\n" + + "\r\n" + + " -n the number of threads to use. Defaults to the number of \r\n" + + " cores available on the computer. n=1 mean sequential \r\n" + + " processing. Valid values are 1 < n < (2 x num_of_cores)\r\n" + + " Default value will give the best performance.\r\n" + + " \r\n" + + "EXAMPLES: \r\n" + + "\r\n" + + " Predict disorder values for sequences from input file /home/input.fasta\r\n" + + " output the results to the standard out. Use default disorder value\r\n" + + " and utilise all cpus available on the computer.\r\n" + + "\r\n" + + " java -jar JRONN.JAR -i=/home/input.fasta\r\n" + + " \r\n" + + " Predict disorder values for sequences from input file /home/input.fasta\r\n" + + " output the results in horizontal layout to the /home/jronn.out, collect \r\n" + + " execution statistics to /home/jronn.stat.txt file and limit the number \r\n" + + " of threads to two. \r\n" + + " \r\n" + + " java -jar JRONN.JAR -i=/home/input.fasta -o=/home/jronn.out -d=0.6 -n=2 -f=H\r\n" + + " \r\n" + + " The arguments can be provided in any order.\r\n" + + "\r\n" + + "ABOUT THE PROGRAM: \r\n" + + " \r\n" + + " JRONN is a Java implementation of RONN. JRONN is based on RONN and uses the \r\n" + + " same model data, therefore gives the same predictions. Main motivation \r\n" + + " behind JRONN development was providing an implementation of RONN more \r\n" + + " suitable to use by the automated analysis pipelines and web services. \r\n" + + " \r\n" + + " Original version of RONN is described in Yang,Z.R., Thomson,R., \r\n" + + " McMeil,P. and Esnouf,R.M. (2005) RONN: the bio-basis function neural network\r\n" + + " technique applied to the detection of natively disordered regions in proteins \r\n" + + " Bioinformatics 21: 3369-3376\r\n" + + " See also http://www.strubi.ox.ac.uk/RONN\r\n" + + " \r\n" + + " Author: Peter Troshin \r\n" + + " email: to.petr AT gmail DOT com\r\n" + + " \r\n" + + " This is a free software which comes with no guarantees.\r\n" + + " JRONN is distributed under Apache Licence version 2. The full version of \r\n" + + " licence can be obtained from http://www.apache.org/licenses/LICENSE-2.0\r\n" + + " "; + /** + * 700 - maximum number of lines (with sequence values) in the single model + * file. + */ + static final int maxD = 700; } diff --git a/biojava-protein-disorder/src/test/java/org/biojava/nbio/ronn/JronnTest.java b/biojava-protein-disorder/src/test/java/org/biojava/nbio/ronn/JronnTest.java index 65bfc5ed36..2783477538 100644 --- a/biojava-protein-disorder/src/test/java/org/biojava/nbio/ronn/JronnTest.java +++ b/biojava-protein-disorder/src/test/java/org/biojava/nbio/ronn/JronnTest.java @@ -79,7 +79,7 @@ public void checkJronn() { * Credit Thomas Klambauer, but here have removed the implement of * AutoCloseable (Java 7) for BioJava support of Java 6. */ - public class ScopedProperty { + public static class ScopedProperty { private final String key; private final String oldValue; diff --git a/biojava-protein-disorder/src/test/java/org/biojava/nbio/ronn/NonstandardProteinCompoundTest.java b/biojava-protein-disorder/src/test/java/org/biojava/nbio/ronn/NonstandardProteinCompoundTest.java index d3c50fd61b..864e74ee1f 100644 --- a/biojava-protein-disorder/src/test/java/org/biojava/nbio/ronn/NonstandardProteinCompoundTest.java +++ b/biojava-protein-disorder/src/test/java/org/biojava/nbio/ronn/NonstandardProteinCompoundTest.java @@ -55,7 +55,7 @@ public void test() throws IOException, InterruptedException { try { testUniprot(id); // throttle load on uniprot server - Thread.sleep(1000); + Thread.sleep(200); } catch (CompoundNotFoundException e){ @@ -65,11 +65,11 @@ public void test() throws IOException, InterruptedException { } } - private void testUniprot(String uniprotID) throws CompoundNotFoundException, IOException { + private void testUniprot(String uniprotID) throws IOException { ProteinSequence seq = getUniprot(uniprotID); - AminoAcidCompoundSet compoundSet = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet compoundSet = AminoAcidCompoundSet.aminoAcidCompoundSet; /* for (AminoAcidCompound compound : seq) { System.out.println(compound.getShortName() + " " + compound.getLongName() + " " + compound.getDescription() + " | " + compoundSet.getEquivalentCompounds(compound) + " " + compound.getMolecularWeight() + " " + compound.getBase()); @@ -94,9 +94,9 @@ private void testUniprot(String uniprotID) throws CompoundNotFoundException, IOE */ private static ProteinSequence getUniprot(String uniProtID) throws CompoundNotFoundException, IOException { - AminoAcidCompoundSet set = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet set = AminoAcidCompoundSet.aminoAcidCompoundSet; UniprotProxySequenceReader uniprotSequence = - new UniprotProxySequenceReader(uniProtID,set); + new UniprotProxySequenceReader<>(uniProtID, set); ProteinSequence seq = new ProteinSequence(uniprotSequence); diff --git a/biojava-structure-gui/pom.xml b/biojava-structure-gui/pom.xml index e6605344bc..27bd24317e 100644 --- a/biojava-structure-gui/pom.xml +++ b/biojava-structure-gui/pom.xml @@ -42,7 +42,7 @@ net.sourceforge.jmol jmol - 14.29.17 + 14.29.27 @@ -78,15 +78,7 @@ - - org.apache.maven.plugins - maven-jar-plugin - - - demo/** - - - + diff --git a/biojava-structure-gui/src/main/java/demo/AFPFromFasta.java b/biojava-structure-gui/src/main/java/demo/AFPFromFasta.java index 5327b18e2f..8eec576679 100644 --- a/biojava-structure-gui/src/main/java/demo/AFPFromFasta.java +++ b/biojava-structure-gui/src/main/java/demo/AFPFromFasta.java @@ -26,7 +26,6 @@ import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.StructureAlignment; import org.biojava.nbio.structure.align.gui.StructureAlignmentDisplay; @@ -37,8 +36,6 @@ import org.biojava.nbio.structure.io.FastaAFPChainConverter; import org.biojava.nbio.structure.io.FastaStructureParser; -import java.io.IOException; - /** * Demo displaying a structural alignment from a FASTA file using {@link FastaAFPChainConverter}. * @@ -48,7 +45,7 @@ */ public class AFPFromFasta { - public static void main(String[] args) throws IOException, StructureException, Exception { + public static void main(String[] args) throws Exception { Structure structure1 = StructureTools.getStructure("1w0p"); Structure structure2 = StructureTools.getStructure("1w0p"); String first = "alfdynatgdtefdspakqgwmqdntnngsgvltnadgmpawlvqgiggraqwtyslstnqhaqassfgwrmttemkvlsggmitnyyangtqrvlpiisldssgnlvvefegqtgrtvlatgtaateyhkfelvflpgsnpsasfyfdgklirdniqptaskQNMIVWGNGSSntdgvaayrdikfei------------------------------------------------------------------------------------------------------------------QGDVIf------------RGPDRIPSIVASsvTPGVVTAFAEKRVGGgdpgalsntNDIITRTSRDGGITWDTELNLTEQinvsdeFDFSDPRPIYDPs---SNTVLVSYARWPtdaaqngdrikpwmpNGIFYSVYDVASgnWQAPIDVTdqvkersfqiagwggselyrrntslnsqqdwqsnakirivdgaanqiqvadgsrkyvvtlsidesgglvanlngvsapiilqsehakvhsfhdyelqysalnhtttlfvdgqqittwagevsqenniqfgnadaqidgrlhvqkivltqqghnlvefdafylaqqtpevekdleklgwtkiktgntmslygNASVNPGpgHGITLtrqqnisgsqNGRLIYPAIVLdrfFLNVMSIYSDDGgsnwq-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------TGSTLpipfrwksssileTLEPSEADMVELQN--GDLLLTARLDFNQivngvny--SPRQQFLSKDGGITWSLLEANNANvfsnistgTVDASITRFEqsdgSHFLLFTNPQGnpagTNgr------------QNLGLWFSFDEG--VTWKGPIQ--LVNGasaysdiyqldsenaivivetdnsnmrilrmpitllkqklt"; diff --git a/biojava-structure-gui/src/main/java/demo/DemoAlignmentFromFasta.java b/biojava-structure-gui/src/main/java/demo/DemoAlignmentFromFasta.java index fbd3ecc74d..8cf8fafc44 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoAlignmentFromFasta.java +++ b/biojava-structure-gui/src/main/java/demo/DemoAlignmentFromFasta.java @@ -20,11 +20,6 @@ */ package demo; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; - import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; @@ -32,11 +27,7 @@ import org.biojava.nbio.core.sequence.io.GenericFastaHeaderParser; import org.biojava.nbio.core.sequence.io.template.SequenceCreatorInterface; import org.biojava.nbio.core.sequence.io.template.SequenceHeaderParserInterface; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.gui.StructureAlignmentDisplay; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.util.AlignmentTools; @@ -44,6 +35,11 @@ import org.biojava.nbio.structure.io.FastaStructureParser; import org.biojava.nbio.structure.io.StructureSequenceMatcher; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + /** * Demo of how to use the {@link FastaStructureParser} class to read protein * structures from a FASTA file. @@ -53,7 +49,7 @@ */ public class DemoAlignmentFromFasta { - public static void getAlignmentFromFasta() throws StructureException { + public static void getAlignmentFromFasta() { // Load a test sequence // Normally this would come from a file, eg @@ -68,26 +64,21 @@ public static void getAlignmentFromFasta() throws StructureException { InputStream fasta; - try { - fasta = new ByteArrayInputStream(fastaStr.getBytes("UTF-8")); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - return; - } + fasta = new ByteArrayInputStream(fastaStr.getBytes(StandardCharsets.UTF_8)); - // Create a header parser to parse the header lines into valid structure accessions. + // Create a header parser to parse the header lines into valid structure accessions. // The resulting accession can be anything interpretable by AtomCache.getStructure. // Possible Examples: "4HHB" (whole structure), "d4hhba_" (SCOP domain), // "4HHB.A:1-15" (residue range) // For this example, the built-in fasta parser will extract the correct accession. SequenceHeaderParserInterface headerParser; - headerParser = new GenericFastaHeaderParser(); + headerParser = new GenericFastaHeaderParser<>(); // Create AtomCache to fetch structures from the PDB AtomCache cache = new AtomCache(); // Create SequenceCreator. This converts a String to a ProteinSequence - AminoAcidCompoundSet aaSet = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet aaSet = AminoAcidCompoundSet.aminoAcidCompoundSet; SequenceCreatorInterface creator; creator = new CasePreservingProteinSequenceCreator(aaSet); @@ -96,10 +87,7 @@ public static void getAlignmentFromFasta() throws StructureException { fasta, headerParser, creator, cache); try { parser.process(); - } catch (IOException e) { - e.printStackTrace(); - return; - } catch (StructureException e) { + } catch (IOException | StructureException e) { e.printStackTrace(); return; } @@ -133,7 +121,7 @@ public static void getAlignmentFromFasta() throws StructureException { } - public static void main(String[] args) throws StructureException { + public static void main(String[] args) { getAlignmentFromFasta(); } } diff --git a/biojava-structure-gui/src/main/java/demo/DemoCE.java b/biojava-structure-gui/src/main/java/demo/DemoCE.java index 5e2bb0aabb..81630472f0 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoCE.java +++ b/biojava-structure-gui/src/main/java/demo/DemoCE.java @@ -60,8 +60,8 @@ public static void main(String[] args){ ChemCompGroupFactory.setChemCompProvider(prov); - Structure structure1 = null; - Structure structure2 = null; + Structure structure1; + Structure structure2; try { diff --git a/biojava-structure-gui/src/main/java/demo/DemoCeSymm.java b/biojava-structure-gui/src/main/java/demo/DemoCeSymm.java index a7fc6eeacd..a120793c96 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoCeSymm.java +++ b/biojava-structure-gui/src/main/java/demo/DemoCeSymm.java @@ -20,7 +20,6 @@ */ package demo; -import java.io.IOException; import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; @@ -33,6 +32,8 @@ import org.biojava.nbio.structure.symmetry.internal.CeSymm; import org.biojava.nbio.structure.symmetry.internal.CeSymmResult; +import java.io.IOException; + /** * Quick demo of how to call CE-Symm programmatically. * Some examples of different symmetry types are proposed. diff --git a/biojava-structure-gui/src/main/java/demo/DemoFATCAT.java b/biojava-structure-gui/src/main/java/demo/DemoFATCAT.java index ac7a0542f6..173bd90436 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoFATCAT.java +++ b/biojava-structure-gui/src/main/java/demo/DemoFATCAT.java @@ -53,8 +53,8 @@ public static void main(String[] args){ AtomCache cache = new AtomCache(); - Structure structure1 = null; - Structure structure2 = null; + Structure structure1; + Structure structure2; try { diff --git a/biojava-structure-gui/src/main/java/demo/DemoMultipleMC.java b/biojava-structure-gui/src/main/java/demo/DemoMultipleMC.java index 062bc6d8d7..d365e4242c 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoMultipleMC.java +++ b/biojava-structure-gui/src/main/java/demo/DemoMultipleMC.java @@ -20,12 +20,6 @@ */ package demo; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.ArrayList; -import java.util.concurrent.ExecutionException; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIdentifier; @@ -38,6 +32,11 @@ import org.biojava.nbio.structure.align.multiple.mc.MultipleMcParameters; import org.biojava.nbio.structure.align.util.AtomCache; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + /** * Demo for running the CEMC Algorithm on a protein family and * visualizing the results. @@ -48,7 +47,7 @@ */ public class DemoMultipleMC { - public static void main(String[] args) throws IOException, StructureException, InterruptedException, ExecutionException { + public static void main(String[] args) throws IOException, StructureException { //ASP-proteinases (CEMC paper) //List names = Arrays.asList("3app", "4ape", "2apr", "5pep", "1psn", "4cms", "1bbs.A", "1smr.A", "2jxr.A", "1mpp", "2asi", "1am5"); @@ -97,9 +96,9 @@ public static void main(String[] args) throws IOException, StructureException, I //Load the CA atoms of the structures AtomCache cache = new AtomCache(); - List identifiers = new ArrayList(); + List identifiers = new ArrayList<>(); - List atomArrays = new ArrayList(); + List atomArrays = new ArrayList<>(); for (String name:names) { atomArrays.add(cache.getAtoms(name)); identifiers.add(new SubstructureIdentifier(name)); diff --git a/biojava-structure-gui/src/main/java/demo/DemoRotationAxis.java b/biojava-structure-gui/src/main/java/demo/DemoRotationAxis.java index 83b676eb8f..06faf0faf3 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoRotationAxis.java +++ b/biojava-structure-gui/src/main/java/demo/DemoRotationAxis.java @@ -118,10 +118,8 @@ public static void main(String[] args) { jmolPanel.evalString("draw ID z VECTOR {0,0,0} {0,0,5} WIDTH 0.5 COLOR blue \">z\";"); */ - } catch (IOException e) { - e.printStackTrace(); - } catch (StructureException e) { + } catch (IOException | StructureException e) { e.printStackTrace(); } - } + } } diff --git a/biojava-structure-gui/src/main/java/demo/DemoSW3DAligner.java b/biojava-structure-gui/src/main/java/demo/DemoSW3DAligner.java index bcb4ac1e96..cc9ef9b874 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoSW3DAligner.java +++ b/biojava-structure-gui/src/main/java/demo/DemoSW3DAligner.java @@ -44,8 +44,8 @@ public static void main(String[] args){ AtomCache cache = new AtomCache(); - Structure structure1 = null; - Structure structure2 = null; + Structure structure1; + Structure structure2; try { diff --git a/biojava-structure-gui/src/main/java/demo/DemoShowBiolAssembly.java b/biojava-structure-gui/src/main/java/demo/DemoShowBiolAssembly.java index 1293af91a6..273da76812 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoShowBiolAssembly.java +++ b/biojava-structure-gui/src/main/java/demo/DemoShowBiolAssembly.java @@ -21,8 +21,8 @@ package demo; import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol; import org.biojava.nbio.structure.StructureIO; +import org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol; public class DemoShowBiolAssembly { diff --git a/biojava-structure-gui/src/main/java/demo/DemoShowCATHDomain.java b/biojava-structure-gui/src/main/java/demo/DemoShowCATHDomain.java index 7ddf7671f6..00d5a7e7fd 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoShowCATHDomain.java +++ b/biojava-structure-gui/src/main/java/demo/DemoShowCATHDomain.java @@ -23,6 +23,7 @@ package demo; +import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.align.client.StructureName; import org.biojava.nbio.structure.align.util.UserConfiguration; import org.biojava.nbio.structure.cath.CathDatabase; @@ -30,7 +31,6 @@ import org.biojava.nbio.structure.cath.CathInstallation; import org.biojava.nbio.structure.cath.CathSegment; import org.biojava.nbio.structure.gui.BiojavaJmol; -import org.biojava.nbio.structure.StructureIO; import java.util.List; diff --git a/biojava-structure-gui/src/main/java/demo/DemoShowLargeAssembly.java b/biojava-structure-gui/src/main/java/demo/DemoShowLargeAssembly.java index c626e90f8a..7719d32442 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoShowLargeAssembly.java +++ b/biojava-structure-gui/src/main/java/demo/DemoShowLargeAssembly.java @@ -1,10 +1,10 @@ package demo; import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.FileParsingParameters; -import org.biojava.nbio.structure.StructureIO; /* * BioJava development code @@ -90,7 +90,7 @@ public static Structure readStructure(String pdbId, int bioAssemblyId) { // download missing files - Structure structure = null; + Structure structure; try { structure = StructureIO.getBiologicalAssembly(pdbId,bioAssemblyId); } catch (Exception e){ diff --git a/biojava-structure-gui/src/main/java/demo/DemoShowValidationResults.java b/biojava-structure-gui/src/main/java/demo/DemoShowValidationResults.java index 80001fd6bf..b695ca5fe2 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoShowValidationResults.java +++ b/biojava-structure-gui/src/main/java/demo/DemoShowValidationResults.java @@ -24,8 +24,8 @@ package demo; import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol; import org.biojava.nbio.structure.StructureIO; +import org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol; import org.biojava.nbio.structure.validation.*; import javax.xml.bind.JAXBContext; @@ -46,7 +46,7 @@ public static void main(String[] args){ private static void showPdbValidation(String pdbId) { try { - JAXBContext ctx = JAXBContext.newInstance(new Class[] {WwPDBValidationInformation.class}); + JAXBContext ctx = JAXBContext.newInstance(WwPDBValidationInformation.class); Unmarshaller um = ctx.createUnmarshaller(); @@ -87,7 +87,7 @@ private static void showPdbValidation(String pdbId) { pos +="^" + iCode; pos +=":" + chainId; - BigDecimal base = new BigDecimal(0.5); + BigDecimal base = new BigDecimal("0.5"); for (Clash clash : clashes){ String clashatom = clash.getAtom(); diff --git a/biojava-structure-gui/src/main/java/demo/DemoStructureFromFasta.java b/biojava-structure-gui/src/main/java/demo/DemoStructureFromFasta.java index c99678d4b9..11bfb74fa4 100644 --- a/biojava-structure-gui/src/main/java/demo/DemoStructureFromFasta.java +++ b/biojava-structure-gui/src/main/java/demo/DemoStructureFromFasta.java @@ -20,12 +20,6 @@ */ package demo; -import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.align.util.AtomCache; -import org.biojava.nbio.structure.gui.BiojavaJmol; -import org.biojava.nbio.structure.io.FastaStructureParser; import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; @@ -33,11 +27,17 @@ import org.biojava.nbio.core.sequence.io.ProteinSequenceCreator; import org.biojava.nbio.core.sequence.io.template.SequenceCreatorInterface; import org.biojava.nbio.core.sequence.io.template.SequenceHeaderParserInterface; +import org.biojava.nbio.structure.ResidueNumber; +import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.StructureException; +import org.biojava.nbio.structure.align.util.AtomCache; +import org.biojava.nbio.structure.gui.BiojavaJmol; +import org.biojava.nbio.structure.io.FastaStructureParser; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; /** * Demo of how to use the {@link FastaStructureParser} class to read protein @@ -60,26 +60,21 @@ public static void getStructureFromFasta() { "KVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTLAAHLPAEFTPA\n" + "VHASLDKFLASVSTVLTSKYR\n"; InputStream fasta; - try { - fasta = new ByteArrayInputStream(fastaStr.getBytes("UTF-8")); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - return; - } + fasta = new ByteArrayInputStream(fastaStr.getBytes(StandardCharsets.UTF_8)); - // Create a header parser to parse the header lines into valid structure accessions. + // Create a header parser to parse the header lines into valid structure accessions. // The resulting accession can be anything interpretable by AtomCache.getStructure. // Possible Examples: "4HHB" (whole structure), "d4hhba_" (SCOP domain), // "4HHB.A:1-15" (residue range) // For this example, the built-in fasta parser will extract the correct accession. SequenceHeaderParserInterface headerParser; - headerParser = new GenericFastaHeaderParser(); + headerParser = new GenericFastaHeaderParser<>(); // Create AtomCache to fetch structures from the PDB AtomCache cache = new AtomCache(); // Create SequenceCreator. This converts a String to a ProteinSequence - AminoAcidCompoundSet aaSet = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet aaSet = AminoAcidCompoundSet.aminoAcidCompoundSet; SequenceCreatorInterface creator; creator = new ProteinSequenceCreator(aaSet); @@ -88,10 +83,7 @@ public static void getStructureFromFasta() { fasta, headerParser, creator, cache); try { parser.process(); - } catch (IOException e) { - e.printStackTrace(); - return; - } catch (StructureException e) { + } catch (IOException | StructureException e) { e.printStackTrace(); return; } diff --git a/biojava-structure-gui/src/main/java/demo/ShowStructureInJmol.java b/biojava-structure-gui/src/main/java/demo/ShowStructureInJmol.java index adeda7dac1..b451f32a9f 100644 --- a/biojava-structure-gui/src/main/java/demo/ShowStructureInJmol.java +++ b/biojava-structure-gui/src/main/java/demo/ShowStructureInJmol.java @@ -21,8 +21,8 @@ package demo; import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol; import org.biojava.nbio.structure.StructureIO; +import org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol; /** Demo how to load and display a structure in Jmol diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AboutDialog.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AboutDialog.java index 1d978876cf..afa66cb16d 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AboutDialog.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AboutDialog.java @@ -26,10 +26,7 @@ import javax.swing.*; import javax.swing.event.HyperlinkEvent; -import javax.swing.event.HyperlinkListener; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; public class AboutDialog { @@ -66,22 +63,18 @@ public void showDialog(){ vBox= Box.createVerticalBox(); vBox.add(scroll); - txt.addHyperlinkListener(new HyperlinkListener(){ - - @Override - public void hyperlinkUpdate(HyperlinkEvent e) { - - if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { - String href = e.getDescription(); - BrowserOpener.showDocument(href); - } - if ( e.getEventType() == HyperlinkEvent.EventType.ENTERED) { - // change the mouse curor - vBox.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - } - if (e.getEventType() == HyperlinkEvent.EventType.EXITED) { - vBox.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - } + txt.addHyperlinkListener(e -> { + + if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { + String href = e.getDescription(); + BrowserOpener.showDocument(href); + } + if ( e.getEventType() == HyperlinkEvent.EventType.ENTERED) { + // change the mouse curor + vBox.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + } + if (e.getEventType() == HyperlinkEvent.EventType.EXITED) { + vBox.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } }); @@ -90,17 +83,14 @@ public void hyperlinkUpdate(HyperlinkEvent e) { JButton close = new JButton("Close"); - close.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent event) { - Object source = event.getSource(); + close.addActionListener(event -> { + Object source = event.getSource(); - JButton but = (JButton)source; - Container parent = but.getParent().getParent().getParent().getParent().getParent().getParent() ; + JButton but = (JButton)source; + Container parent = but.getParent().getParent().getParent().getParent().getParent().getParent() ; - JDialog dia = (JDialog) parent; - dia.dispose(); - } + JDialog dia = (JDialog) parent; + dia.dispose(); }); Box hBoxb = Box.createHorizontalBox(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalc.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalc.java index 98ed76f7a4..4bda6f155f 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalc.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalc.java @@ -52,8 +52,8 @@ public class AlignmentCalc implements AlignmentCalculationRunnable { String pdb1; String pdb2; - String name1; - String name2; + final String name1; + final String name2; Structure structure1; Structure structure2; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalcDB.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalcDB.java index 74637e4617..b0b8899410 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalcDB.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalcDB.java @@ -40,11 +40,11 @@ public class AlignmentCalcDB implements AlignmentCalculationRunnable { - public static String SCOP_VERSION = "1.75"; + public static final String SCOP_VERSION = "1.75"; //private static final Logger logger = LoggerFactory.getLogger(AlignmentCalcDB.class); - AtomicBoolean interrupted ; + final AtomicBoolean interrupted ; String name1; @@ -56,10 +56,10 @@ public class AlignmentCalcDB implements AlignmentCalculationRunnable { UserConfiguration config; - String outFile; + final String outFile; int nrCPUs; - Boolean domainSplit ; + final Boolean domainSplit ; StructureAlignment customAlgorithm; @@ -97,7 +97,7 @@ public AlignmentCalcDB(AlignmentGui parent, Structure s1, String name1, UserCon @Override public void run() { - StructureAlignment algorithm = null; + StructureAlignment algorithm; if ( parent != null ) algorithm = parent.getStructureAlignment(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalculationRunnable.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalculationRunnable.java index e50de3f637..d9559b2227 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalculationRunnable.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentCalculationRunnable.java @@ -27,8 +27,8 @@ public interface AlignmentCalculationRunnable extends Runnable { - public void interrupt(); - public void cleanup(); - public void setNrCPUs(int useNrCPUs); + void interrupt(); + void cleanup(); + void setNrCPUs(int useNrCPUs); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentGui.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentGui.java index c55e6689e3..c3d9813f67 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentGui.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentGui.java @@ -22,23 +22,6 @@ */ package org.biojava.nbio.structure.align.gui; -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.io.File; -import java.io.IOException; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JMenuBar; -import javax.swing.JOptionPane; -import javax.swing.JProgressBar; -import javax.swing.JTabbedPane; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.StructureAlignment; @@ -52,6 +35,12 @@ import org.biojava.nbio.structure.gui.util.ScopSelectPanel; import org.biojava.nbio.structure.gui.util.StructurePairSelector; +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.io.File; +import java.io.IOException; + /** A JFrame that allows to trigger a pairwise structure alignment, * either from files in a directory, * or after manual upload. @@ -65,24 +54,24 @@ */ public class AlignmentGui extends JFrame{ - private final static long serialVersionUID =0l; + private final static long serialVersionUID = 0L; StructureAlignment algorithm; JButton abortB; - SelectPDBPanel tab1 ; - PDBUploadPanel tab2; - ScopSelectPanel tab3; + final SelectPDBPanel tab1 ; + final PDBUploadPanel tab2; + final ScopSelectPanel tab3; Thread thread; AlignmentCalculationRunnable alicalc; - JTabbedPane masterPane; - JTabbedPane tabPane; + final JTabbedPane masterPane; + final JTabbedPane tabPane; JProgressBar progress; - private DBSearchGUI dbsearch; + private final DBSearchGUI dbsearch; public static void main(String[] args){ @@ -93,7 +82,7 @@ public static void main(String[] args){ static final ResourceManager resourceManager = ResourceManager.getResourceManager("ce"); - private static final String MAIN_TITLE = "Pairwise Structure Alignment - Main - V." + resourceManager.getString("ce.version");; + private static final String MAIN_TITLE = "Pairwise Structure Alignment - Main - V." + resourceManager.getString("ce.version"); private static final AlignmentGui me = new AlignmentGui(); @@ -208,7 +197,7 @@ private Box setupAlgorithm() algorithmList.setSelectedIndex(0); Action actionAlgorithm = new AbstractAction("Algorithm") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -226,7 +215,7 @@ public void actionPerformed(ActionEvent evt) { Action paramAction = new AbstractAction("Parameters") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -269,7 +258,7 @@ private Box initButtons(){ // hBox42.add(Box.createGlue()); // vBox.add(hBox42); Action action1 = new AbstractAction("Align") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -290,7 +279,7 @@ else if ( selectedIndex == 1) JButton submitB = new JButton(action1); Action action3 = new AbstractAction("Abort") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -304,7 +293,7 @@ public void actionPerformed(ActionEvent evt) { abortB.setEnabled(false); Action action2 = new AbstractAction("Exit") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -377,8 +366,8 @@ private void calcAlignment() { return; } - String name1 = "custom1"; - String name2 = "custom2"; + String name1; + String name2; if ( pos == 0){ name1 = tab1.getName1().getIdentifier(); @@ -400,9 +389,7 @@ private void calcAlignment() { progress.setIndeterminate(true); ProgressThreadDrawer drawer = new ProgressThreadDrawer(progress); drawer.start(); - } catch (StructureException e){ - JOptionPane.showMessageDialog(null,"Could not align structures. Exception: " + e.getMessage()); - } catch (IOException e) { + } catch (StructureException | IOException e){ JOptionPane.showMessageDialog(null,"Could not align structures. Exception: " + e.getMessage()); } @@ -449,14 +436,14 @@ private void calcDBSearch() { } String name1 = s.getName(); - if ( name1 == null || name1.equals("")) + if ( name1 == null || name1.isEmpty()) name1 = s.getPDBCode(); System.out.println("name1 in alig gui:" + name1); String file = dbsearch.getOutFileLocation(); - if ( file == null || file.equals("") ){ + if ( file == null || file.isEmpty()){ JOptionPane.showMessageDialog(null,"Please select a directory to contain the DB search results."); return; } @@ -550,7 +537,7 @@ private void updateAlgorithm(String algorithmName) { class ProgressThreadDrawer extends Thread { JProgressBar progress; - static int interval = 300; + static final int interval = 300; public ProgressThreadDrawer(JProgressBar progress) { this.progress = progress; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentTextPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentTextPanel.java index d5aea38c5d..caee4ee93d 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentTextPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/AlignmentTextPanel.java @@ -33,7 +33,7 @@ public class AlignmentTextPanel extends JPrintPanel { * */ private static final long serialVersionUID = 5092386365924879073L; - JEditorPane tp; + final JEditorPane tp; public AlignmentTextPanel(){ super(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ChooseDirAction.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ChooseDirAction.java index c603392c08..cdf02e8154 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ChooseDirAction.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ChooseDirAction.java @@ -39,14 +39,14 @@ */ public class ChooseDirAction extends AbstractAction{ - JTextField textField; + final JTextField textField; UserConfiguration config; public ChooseDirAction (JTextField textField, UserConfiguration config){ super("Choose"); this.config = config; this.textField = textField; } - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ConfigPDBInstallPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ConfigPDBInstallPanel.java index 637183a3af..028e464591 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ConfigPDBInstallPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ConfigPDBInstallPanel.java @@ -44,11 +44,11 @@ public class ConfigPDBInstallPanel extends JPanel private static final long serialVersionUID = -1055193854675583808L; JCheckBox fromFtp; - JComboBox fileType; + final JComboBox fileType; JTextField pdbDir; - private static ConfigPDBInstallPanel instance = new ConfigPDBInstallPanel(); + private static final ConfigPDBInstallPanel instance = new ConfigPDBInstallPanel(); static JDialog dialog; @@ -137,22 +137,14 @@ public static void showDialog(){ vBox.add(Box.createGlue()); JButton apply = new JButton("Apply"); - apply.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent event) { - instance.applyValues(); - dialog.dispose(); - } + apply.addActionListener(event -> { + instance.applyValues(); + dialog.dispose(); }); JButton close = new JButton("Cancel"); - close.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent event) { - dialog.dispose(); - } - }); + close.addActionListener(event -> dialog.dispose()); Box hBoxb = Box.createHorizontalBox(); hBoxb.add(Box.createGlue()); @@ -206,7 +198,7 @@ public void setPDBDirField(JTextField dir){ } class MyAction implements ActionListener{ - JDialog dialog; + final JDialog dialog; public MyAction(JDialog dialog) { this.dialog= dialog; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DBResultTable.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DBResultTable.java index b71b040f8e..700b8707cd 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DBResultTable.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DBResultTable.java @@ -96,7 +96,7 @@ public DBResultTable(){ public void show(BufferedReader in, UserConfiguration config) throws IOException{ String str; - List tmpdat = new ArrayList(); + List tmpdat = new ArrayList<>(); while ((str = in.readLine()) != null) { if ( str.startsWith("#")) { if ( str.startsWith("# algorithm:")) { @@ -142,9 +142,7 @@ else if ( str.startsWith("#param:scoring=")){ ceParams.setScoringStrategy(scoreS); } } - } catch (IndexOutOfBoundsException e){ - System.err.println("Unknown scoring strategy from line: " + str); - } catch (IllegalArgumentException e) { + } catch (IndexOutOfBoundsException | IllegalArgumentException e){ System.err.println("Unknown scoring strategy from line: " + str); } catch (Exception e) { System.err.println("Unknown parameter can't read parameters from line: " + str); @@ -260,7 +258,7 @@ private void initAlgorithm(String algorithmName) { } private void outputSelection() { - StringBuffer output = new StringBuffer(); + StringBuilder output = new StringBuilder(); output.append(String.format("Lead: %d, %d. ", table.getSelectionModel().getLeadSelectionIndex(), table.getColumnModel().getSelectionModel(). @@ -309,7 +307,7 @@ private void showAlignment( String name1, String name2){ } try { - Structure structure1 = null; + Structure structure1; if ( name1.equals("CUSTOM")) { // user uploaded a custom PDB file... structure1 = loadCustomStructure(userPath,userChain); @@ -348,7 +346,7 @@ private void showAlignment( String name1, String name2){ private Structure loadCustomStructure(String userPath2, String userChain2) throws StructureException{ StructureIOFile reader = new PDBFileReader(); - Structure s = null; + Structure s; try { s = reader.getStructure(userPath2); } catch (IOException e){ diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DBSearchGUI.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DBSearchGUI.java index 885a544d28..6b982cb872 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DBSearchGUI.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DBSearchGUI.java @@ -31,8 +31,6 @@ import org.biojava.nbio.structure.gui.util.ScopSelectPanel; import javax.swing.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.io.File; public class DBSearchGUI extends JPanel { @@ -44,13 +42,13 @@ public class DBSearchGUI extends JPanel { StructureAlignment algorithm; - SelectPDBPanel tab1; + final SelectPDBPanel tab1; JTabbedPane tabPane; - PDBUploadPanel tab2; - ScopSelectPanel tab3; + final PDBUploadPanel tab2; + final ScopSelectPanel tab3; - JPanel listPane; + final JPanel listPane; JButton abortB; AlignmentCalcDB alicalc; JProgressBar progress; @@ -155,30 +153,26 @@ private JPanel createListPane() { dir.add(hBox); - chB.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - JFileChooser chooser = new JFileChooser(); - chooser.setMultiSelectionEnabled(false); - chooser.setDialogTitle("Select Output Directory"); - chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - // - // disable the "All files" option. - // - chooser.setAcceptAllFileFilterUsed(false); - // - - - // In response to a button click: - int returnVal = chooser.showSaveDialog(null); - if ( returnVal == JFileChooser.APPROVE_OPTION) { - File file = chooser.getSelectedFile(); - outFileLocation.setText(file.getPath()); - outFileLocation.repaint(); - } - + chB.addActionListener(e -> { + JFileChooser chooser = new JFileChooser(); + chooser.setMultiSelectionEnabled(false); + chooser.setDialogTitle("Select Output Directory"); + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + // + // disable the "All files" option. + // + chooser.setAcceptAllFileFilterUsed(false); + // + + + // In response to a button click: + int returnVal = chooser.showSaveDialog(null); + if ( returnVal == JFileChooser.APPROVE_OPTION) { + File file = chooser.getSelectedFile(); + outFileLocation.setText(file.getPath()); + outFileLocation.repaint(); } + }); //tabP.addTab("Select Output Directory", null, dir, @@ -203,18 +197,14 @@ private Box createDomainSelectPane() { JComboBox domainList = new JComboBox(petStrings); domainList.setSelectedIndex(0); domainList.setToolTipText("Either align whole chains or SCOP domains and domains assigned with PDP, where no SCOP available."); - domainList.addActionListener(new ActionListener() { + domainList.addActionListener(arg0 -> { + JComboBox box = (JComboBox)arg0.getSource(); + int index = box.getSelectedIndex(); + if ( index == 0) + useDomainSplit = true; + else + useDomainSplit = false; - @Override - public void actionPerformed(ActionEvent arg0) { - JComboBox box = (JComboBox)arg0.getSource(); - int index = box.getSelectedIndex(); - if ( index == 0) - useDomainSplit = true; - else - useDomainSplit = false; - - } }); JLabel label= new JLabel("Domains:"); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DisplayAFP.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DisplayAFP.java index 03aa7d5084..5ce33ee02c 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DisplayAFP.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DisplayAFP.java @@ -19,32 +19,23 @@ package org.biojava.nbio.structure.align.gui; -import java.awt.Dimension; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.swing.Box; -import javax.swing.JFrame; -import javax.swing.JMenuBar; -import javax.swing.JScrollPane; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.gui.aligpanel.AligPanel; import org.biojava.nbio.structure.align.gui.aligpanel.StatusDisplay; import org.biojava.nbio.structure.align.gui.jmol.AbstractAlignmentJmol; import org.biojava.nbio.structure.align.gui.jmol.JmolTools; import org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol; import org.biojava.nbio.structure.align.model.AFPChain; -import org.biojava.nbio.structure.align.util.AFPAlignmentDisplay; import org.biojava.nbio.structure.align.util.AlignmentTools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.swing.*; +import java.awt.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + /** A utility class for visualistion of structure alignments * * @author Andreas Prlic @@ -55,8 +46,8 @@ public class DisplayAFP { private static final Logger logger = LoggerFactory.getLogger(DisplayAFP.class); //TODO: same as getEqrPos??? !!! - public static final List getEQRAlignmentPos(AFPChain afpChain){ - List lst = new ArrayList(); + public static List getEQRAlignmentPos(AFPChain afpChain){ + List lst = new ArrayList<>(); char[] s1 = afpChain.getAlnseq1(); char[] s2 = afpChain.getAlnseq2(); @@ -106,8 +97,8 @@ private static boolean isAlignedPosition(int i, char c1, char c2, boolean isFatC * @param afpChain * @param ca */ - public static final List getPDBresnum(int aligPos, AFPChain afpChain, Atom[] ca){ - List lst = new ArrayList(); + public static List getPDBresnum(int aligPos, AFPChain afpChain, Atom[] ca){ + List lst = new ArrayList<>(); if ( aligPos > 1) { System.err.println("multiple alignments not supported yet!"); return lst; @@ -145,7 +136,7 @@ public static final List getPDBresnum(int aligPos, AFPChain afpChain, At * @param getPrevious gives the previous position if false, gives the next posible atom * @return a CA atom that is at a particular position of the alignment */ - public static final Atom getAtomForAligPos(AFPChain afpChain,int chainNr, int aligPos, Atom[] ca , boolean getPrevious ) throws StructureException{ + public static Atom getAtomForAligPos(AFPChain afpChain, int chainNr, int aligPos, Atom[] ca , boolean getPrevious ) throws StructureException{ int[] optLen = afpChain.getOptLen(); // int[][][] optAln = afpChain.getOptAln(); @@ -230,7 +221,7 @@ private static int getNextFatCatPos(AFPChain afpChain, int chainNr, if(len > 0) { - int lmax = (p1 - p1b - 1)>(p2 - p2b - 1)?(p1 - p1b - 1):(p2 - p2b - 1); + int lmax = Math.max((p1 - p1b - 1), (p2 - p2b - 1)); // lmax gives the length of an alignment gap @@ -312,7 +303,7 @@ private static int getNextFatCatPos(AFPChain afpChain, int chainNr, } - private static final int getUngappedFatCatPos(AFPChain afpChain, int chainNr, int aligPos){ + private static int getUngappedFatCatPos(AFPChain afpChain, int chainNr, int aligPos){ char[] aseq; if ( chainNr == 0 ) aseq = afpChain.getAlnseq1(); @@ -343,7 +334,7 @@ private static final int getUngappedFatCatPos(AFPChain afpChain, int chainNr, in if(len > 0) { - int lmax = (p1 - p1b - 1)>(p2 - p2b - 1)?(p1 - p1b - 1):(p2 - p2b - 1); + int lmax = Math.max((p1 - p1b - 1), (p2 - p2b - 1)); // lmax gives the length of an alignment gap @@ -404,10 +395,9 @@ private static final int getUngappedFatCatPos(AFPChain afpChain, int chainNr, in * @param ca * @param hetatms * @return - * @throws StructureException */ - public static final Atom[] getAtomArray(Atom[] ca,List hetatms ) throws StructureException{ - List atoms = new ArrayList(); + public static Atom[] getAtomArray(Atom[] ca, List hetatms ) { + List atoms = new ArrayList<>(); Collections.addAll(atoms, ca); logger.debug("got {} hetatoms", hetatms.size()); @@ -425,7 +415,7 @@ public static final Atom[] getAtomArray(Atom[] ca,List hetatms ) throws S atoms.add(a); } - Atom[] arr = atoms.toArray(new Atom[atoms.size()]); + Atom[] arr = atoms.toArray(Atom.EmptyAtomArray); return arr; } @@ -434,9 +424,9 @@ public static final Atom[] getAtomArray(Atom[] ca,List hetatms ) throws S /** Note: ca2, hetatoms2 and nucleotides2 should not be rotated. This will be done here... * */ - public static final StructureAlignmentJmol display(AFPChain afpChain,Group[] twistedGroups, Atom[] ca1, Atom[] ca2,List hetatms1, List hetatms2 ) throws StructureException { + public static StructureAlignmentJmol display(AFPChain afpChain, Group[] twistedGroups, Atom[] ca1, Atom[] ca2, List hetatms1, List hetatms2 ) { - List twistedAs = new ArrayList(); + List twistedAs = new ArrayList<>(); for ( Group g: twistedGroups){ if ( g == null ) @@ -446,7 +436,7 @@ public static final StructureAlignmentJmol display(AFPChain afpChain,Group[] twi Atom a = g.getAtom(0); twistedAs.add(a); } - Atom[] twistedAtoms = twistedAs.toArray(new Atom[twistedAs.size()]); + Atom[] twistedAtoms = twistedAs.toArray(Atom.EmptyAtomArray); twistedAtoms = StructureTools.cloneAtomArray(twistedAtoms); Atom[] arr1 = getAtomArray(ca1, hetatms1); @@ -476,7 +466,7 @@ public static final StructureAlignmentJmol display(AFPChain afpChain,Group[] twi return jmol; } - public static void showAlignmentPanel(AFPChain afpChain, Atom[] ca1, Atom[] ca2, AbstractAlignmentJmol jmol) throws StructureException { + public static void showAlignmentPanel(AFPChain afpChain, Atom[] ca1, Atom[] ca2, AbstractAlignmentJmol jmol) { AligPanel me = new AligPanel(); me.setAlignmentJmol(jmol); @@ -548,10 +538,9 @@ public static void showAlignmentImage(AFPChain afpChain, String result) { * @param ca1 atoms for protein 1 * @param ca2 atoms for protein 2 * @return a protein structure with 2 models. - * @throws StructureException - */ + */ public static Structure createArtificalStructure(AFPChain afpChain, Atom[] ca1, - Atom[] ca2) throws StructureException{ + Atom[] ca2) { if ( afpChain.getNrEQR() < 1){ @@ -560,7 +549,7 @@ public static Structure createArtificalStructure(AFPChain afpChain, Atom[] ca1, Group[] twistedGroups = AlignmentTools.prepareGroupsForDisplay(afpChain,ca1, ca2); - List twistedAs = new ArrayList(); + List twistedAs = new ArrayList<>(); for ( Group g: twistedGroups){ if ( g == null ) @@ -570,7 +559,7 @@ public static Structure createArtificalStructure(AFPChain afpChain, Atom[] ca1, Atom a = g.getAtom(0); twistedAs.add(a); } - Atom[] twistedAtoms = twistedAs.toArray(new Atom[twistedAs.size()]); + Atom[] twistedAtoms = twistedAs.toArray(Atom.EmptyAtomArray); List hetatms = StructureTools.getUnalignedGroups(ca1); List hetatms2 = StructureTools.getUnalignedGroups(ca2); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DotPlotPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DotPlotPanel.java index 22f4ad1822..cc1b3f15cf 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DotPlotPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/DotPlotPanel.java @@ -76,7 +76,7 @@ public DotPlotPanel(AFPChain alignment ){ int[][][] optAln = alignment.getOptAln(); // [block #][{0,1} chain index][pos] for(;alignNumber < optAln.length;alignNumber++) { - List alignPairs = new ArrayList(); + List alignPairs = new ArrayList<>(); for(int pos = 0; pos createAndShowGUI(progressListener)); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/HelpDialog.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/HelpDialog.java index 0a83191339..81113bc20c 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/HelpDialog.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/HelpDialog.java @@ -29,10 +29,7 @@ import javax.swing.*; import javax.swing.event.HyperlinkEvent; -import javax.swing.event.HyperlinkListener; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; public class HelpDialog { Box vBox; @@ -55,40 +52,33 @@ public void showDialog(){ vBox= Box.createVerticalBox(); vBox.add(scroll); - txt.addHyperlinkListener(new HyperlinkListener(){ + txt.addHyperlinkListener(e -> { - @Override - public void hyperlinkUpdate(HyperlinkEvent e) { - - if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { - String href = e.getDescription(); - BrowserOpener.showDocument(href); - } - if ( e.getEventType() == HyperlinkEvent.EventType.ENTERED) { - // change the mouse curor - vBox.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - } - if (e.getEventType() == HyperlinkEvent.EventType.EXITED) { - vBox.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - } - } - }); + if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { + String href = e.getDescription(); + BrowserOpener.showDocument(href); + } + if ( e.getEventType() == HyperlinkEvent.EventType.ENTERED) { + // change the mouse curor + vBox.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + } + if (e.getEventType() == HyperlinkEvent.EventType.EXITED) { + vBox.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); + } + }); JButton close = new JButton("Close"); - close.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent event) { - Object source = event.getSource(); + close.addActionListener(event -> { + Object source = event.getSource(); - JButton but = (JButton)source; - Container parent = but.getParent().getParent().getParent().getParent().getParent().getParent() ; + JButton but = (JButton)source; + Container parent = but.getParent().getParent().getParent().getParent().getParent().getParent() ; - JDialog dia = (JDialog) parent; - dia.dispose(); - } - }); + JDialog dia = (JDialog) parent; + dia.dispose(); + }); Box hBoxb = Box.createHorizontalBox(); hBoxb.add(Box.createGlue()); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/JPrintPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/JPrintPanel.java index 47ee654f2a..8f9e8322c4 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/JPrintPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/JPrintPanel.java @@ -30,7 +30,6 @@ import java.awt.event.ActionListener; import java.awt.print.PageFormat; import java.awt.print.Printable; -import java.awt.print.PrinterException; import java.awt.print.PrinterJob; public class JPrintPanel extends JPanel implements Printable,ActionListener{ @@ -40,7 +39,7 @@ public class JPrintPanel extends JPanel implements Printable,ActionListener{ private static final long serialVersionUID = -3337337068138131455L; @Override - public int print(Graphics g, PageFormat pf, int pi) throws PrinterException { + public int print(Graphics g, PageFormat pf, int pi) { if (pi >= 1) { return Printable.NO_SUCH_PAGE; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MemoryMonitor.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MemoryMonitor.java index 91ca7571b4..6b6f160441 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MemoryMonitor.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MemoryMonitor.java @@ -55,13 +55,13 @@ */ public class MemoryMonitor extends JPanel { - static JCheckBox dateStampCB = new JCheckBox("Output Date Stamp"); - public Surface surf; - JPanel controls; + static final JCheckBox dateStampCB = new JCheckBox("Output Date Stamp"); + public final Surface surf; + final JPanel controls; boolean doControls; - JTextField tf; + final JTextField tf; - public static final long serialVersionUID = 56289234782130l; + public static final long serialVersionUID = 56289234782130L; public MemoryMonitor() { setLayout(new BorderLayout()); @@ -103,28 +103,28 @@ public void mouseClicked(MouseEvent e) { } - public class Surface extends JPanel implements Runnable { + public static class Surface extends JPanel implements Runnable { - public static final long serialVersionUID = 2387409854370432908l; + public static final long serialVersionUID = 2387409854370432908L; public Thread thread; public long sleepAmount = 1000; private int w, h; private BufferedImage bimg; private Graphics2D big; - private Font font = new Font("Times New Roman", Font.PLAIN, 11); - private Runtime r = Runtime.getRuntime(); + private final Font font = new Font("Times New Roman", Font.PLAIN, 11); + private final Runtime r = Runtime.getRuntime(); private int columnInc; private int[] pts; private int ptNum; private int ascent, descent; //private float freeMemory, totalMemory; - private Rectangle graphOutlineRect = new Rectangle(); - private Rectangle2D mfRect = new Rectangle2D.Float(); - private Rectangle2D muRect = new Rectangle2D.Float(); - private Line2D graphLine = new Line2D.Float(); - private Color graphColor = new Color(46, 139, 87); - private Color mfColor = new Color(0, 100, 0); + private final Rectangle graphOutlineRect = new Rectangle(); + private final Rectangle2D mfRect = new Rectangle2D.Float(); + private final Rectangle2D muRect = new Rectangle2D.Float(); + private final Line2D graphLine = new Line2D.Float(); + private final Color graphColor = new Color(46, 139, 87); + private final Color mfColor = new Color(0, 100, 0); private String usedStr; @@ -169,8 +169,8 @@ public void paint(Graphics g) { // .. Draw allocated and used strings .. big.setColor(Color.green); - big.drawString(String.valueOf((int) totalMemory/1024) + "K allocated", 4.0f, ascent+0.5f); - usedStr = String.valueOf(((int) (totalMemory - freeMemory))/1024) + big.drawString((int) totalMemory / 1024 + "K allocated", 4.0f, ascent+0.5f); + usedStr = ((int) (totalMemory - freeMemory)) / 1024 + "K used"; big.drawString(usedStr, 4, h-descent); @@ -234,7 +234,7 @@ public void paint(Graphics g) { pts = new int[graphW]; ptNum = 0; } else if (pts.length != graphW) { - int[] tmp = null; + int[] tmp; if (ptNum < graphW) { tmp = new int[ptNum]; System.arraycopy(pts, 0, tmp, 0, tmp.length); @@ -259,9 +259,7 @@ public void paint(Graphics g) { } if (ptNum+2 == pts.length) { // throw out oldest point - for (int j = 1;j < ptNum; j++) { - pts[j-1] = pts[j]; - } + if (ptNum - 1 >= 0) System.arraycopy(pts, 1, pts, 0, ptNum - 1); --ptNum; } else { ptNum++; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MenuCreator.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MenuCreator.java index 9484217af9..133bb59b43 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MenuCreator.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MenuCreator.java @@ -29,7 +29,6 @@ import org.biojava.nbio.structure.align.webstart.WebStartMain; import javax.swing.*; - import java.awt.*; import java.awt.event.*; import java.io.File; @@ -209,38 +208,34 @@ public static JMenuBar initJmolMenu(JFrame frame, public static JMenuItem getDBResultMenuItem() { ImageIcon saveicon = createImageIcon("/icons/kpdf.png"); - JMenuItem saveI = null; + JMenuItem saveI; if ( saveicon == null) saveI = new JMenuItem(LOAD_DB_RESULTS); else saveI = new JMenuItem(LOAD_DB_RESULTS, saveicon); - saveI.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - final JFileChooser fc = new JFileChooser(); + saveI.addActionListener(e -> { + final JFileChooser fc = new JFileChooser(); - // In response to a button click: - int returnVal = fc.showOpenDialog(null); - if ( returnVal == JFileChooser.APPROVE_OPTION) { - File file = fc.getSelectedFile(); - - UserConfiguration config = WebStartMain.getWebStartConfig(); - DBResultTable table = new DBResultTable(); - table.show(file,config); - } + // In response to a button click: + int returnVal = fc.showOpenDialog(null); + if ( returnVal == JFileChooser.APPROVE_OPTION) { + File file = fc.getSelectedFile(); + UserConfiguration config = WebStartMain.getWebStartConfig(); + DBResultTable table = new DBResultTable(); + table.show(file,config); } - } ); + + }); return saveI; } public static JMenuItem getShowPDBMenuItem() { ImageIcon loadI = createImageIcon("/icons/background.png"); - JMenuItem openI = null; + JMenuItem openI; if ( loadI == null) openI =new JMenuItem("Show By ID"); @@ -255,7 +250,7 @@ public static JMenuItem getShowPDBMenuItem() { public static JMenuItem getOpenPDBMenuItem() { ImageIcon loadI = createImageIcon("/icons/background.png"); - JMenuItem openI = null; + JMenuItem openI; if ( loadI == null) openI =new JMenuItem("Open PDB file"); @@ -269,7 +264,7 @@ public static JMenuItem getOpenPDBMenuItem() { public static JMenuItem getLoadMenuItem() { - JMenuItem loadF = null; + JMenuItem loadF; ImageIcon loadI = createImageIcon("/icons/revert.png"); if ( loadI == null) loadF = new JMenuItem(LOAD_ALIGNMENT_XML); @@ -305,7 +300,7 @@ public static JMenuBar getAlignmentPanelMenu(JFrame frame, ImageIcon saveicon = createImageIcon("/icons/filesave.png"); - JMenuItem saveF = null; + JMenuItem saveF; if (saveicon != null) saveF = new JMenuItem("Save text display", saveicon); @@ -400,7 +395,7 @@ public static JMenuBar getAlignmentTextMenu(JFrame frame, ImageIcon saveicon = createImageIcon("/icons/filesave.png"); - JMenuItem saveF = null; + JMenuItem saveF; if (saveicon != null ) saveF = new JMenuItem("Save text display", saveicon); @@ -487,7 +482,7 @@ public static JMenuItem getPrintMenuItem() { public static JMenuItem getExportPDBMenuItem(AbstractAlignmentJmol parent) { ImageIcon saveicon = createImageIcon("/icons/compfile.png"); - JMenuItem exportI = null; + JMenuItem exportI; if ( saveicon == null) exportI = new JMenuItem("Export PDB file"); @@ -504,7 +499,7 @@ public static JMenuItem getSaveAlignmentMenuItem(AFPChain afpChain, MultipleAlignment msa){ ImageIcon saveicon = createImageIcon("/icons/filesave.png"); - JMenuItem saveF = null; + JMenuItem saveF; if (saveicon == null) saveF = new JMenuItem(SAVE_ALIGNMENT_XML); @@ -522,7 +517,7 @@ public static JMenuItem getAboutMenuItem() { ImageIcon helpIcon = createImageIcon("/icons/help.png"); - JMenuItem aboutM = null; + JMenuItem aboutM; if ( helpIcon == null) aboutM = new JMenuItem("About this Software"); @@ -530,14 +525,7 @@ public static JMenuItem getAboutMenuItem() { aboutM = new JMenuItem("About this Software", helpIcon); aboutM.setMnemonic(KeyEvent.VK_A); - aboutM.addActionListener(new ActionListener(){ - - @Override - public void actionPerformed(ActionEvent e) { - MenuCreator.showAboutDialog(); - - } - }); + aboutM.addActionListener(e -> MenuCreator.showAboutDialog()); return aboutM; } @@ -547,7 +535,7 @@ private static JMenuItem getSystemInfoItem() ImageIcon helpIcon = createImageIcon("/icons/help.png"); - JMenuItem aboutM = null; + JMenuItem aboutM; if ( helpIcon == null) aboutM = new JMenuItem("System Info"); @@ -555,14 +543,7 @@ private static JMenuItem getSystemInfoItem() aboutM = new JMenuItem("System Info", helpIcon); aboutM.setMnemonic(KeyEvent.VK_S); - aboutM.addActionListener(new ActionListener(){ - - @Override - public void actionPerformed(ActionEvent e) { - MenuCreator.showSystemInfo(); - - } - }); + aboutM.addActionListener(e -> MenuCreator.showSystemInfo()); return aboutM; } @@ -579,15 +560,11 @@ public static JMenuItem getExitMenuItem(){ exitI = new JMenuItem("Quit",exitIcon); exitI.setMnemonic(KeyEvent.VK_Q); exitI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, keyMask)); - exitI.addActionListener(new ActionListener(){ + exitI.addActionListener(e -> { + String cmd = e.getActionCommand(); - @Override - public void actionPerformed(ActionEvent e) { - String cmd = e.getActionCommand(); - - if ( cmd.equals("Quit")){ - System.exit(0); - } + if ( cmd.equals("Quit")){ + System.exit(0); } }); return exitI; @@ -607,14 +584,10 @@ public static JMenuItem getHelpMenuItem(){ helpM = new JMenuItem("Help", helpIcon); helpM.setMnemonic(KeyEvent.VK_H); - helpM.addActionListener(new ActionListener(){ - - @Override - public void actionPerformed(ActionEvent e) { - HelpDialog d = new HelpDialog(); - d.showDialog(); + helpM.addActionListener(e -> { + HelpDialog d = new HelpDialog(); + d.showDialog(); - } }); return helpM; @@ -635,7 +608,7 @@ public static JMenuItem getCloseMenuItem(JFrame frame){ closeI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, keyMask)); class MyCloseListener implements ActionListener{ - JFrame f; + final JFrame f; MyCloseListener(JFrame frame){ f=frame; } @@ -713,14 +686,11 @@ protected static JMenuItem getPairwiseAlignmentMenuItem() { pairI = new JMenuItem(PAIRWISE_ALIGN, alignIcon); pairI.setMnemonic(KeyEvent.VK_N); pairI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, keyMask)); - pairI.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String cmd = e.getActionCommand(); + pairI.addActionListener(e -> { + String cmd = e.getActionCommand(); - if ( cmd.equals(PAIRWISE_ALIGN)){ - MenuCreator.showPairDialog(); - } + if ( cmd.equals(PAIRWISE_ALIGN)){ + MenuCreator.showPairDialog(); } }); return pairI; @@ -736,14 +706,11 @@ protected static JMenuItem getMultipleAlignmentMenuItem() { multipleI = new JMenuItem(MULTIPLE_ALIGN, alignIcon); multipleI.setMnemonic(KeyEvent.VK_N); multipleI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, keyMask)); - multipleI.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String cmd = e.getActionCommand(); + multipleI.addActionListener(e -> { + String cmd = e.getActionCommand(); - if ( cmd.equals(MULTIPLE_ALIGN)){ - MenuCreator.showMultipleDialog(); - } + if ( cmd.equals(MULTIPLE_ALIGN)){ + MenuCreator.showMultipleDialog(); } }); return multipleI; @@ -844,7 +811,7 @@ public static JMenuBar initAlignmentGUIMenu(JFrame frame) { private static JMenuItem getMemoryMonitorItem() { ImageIcon helpIcon = createImageIcon("/icons/help.png"); - JMenuItem aboutM = null; + JMenuItem aboutM; if ( helpIcon == null) aboutM = new JMenuItem("Memory Monitor"); @@ -852,14 +819,7 @@ private static JMenuItem getMemoryMonitorItem() { aboutM = new JMenuItem("Memory Monitor", helpIcon); aboutM.setMnemonic(KeyEvent.VK_M); - aboutM.addActionListener(new ActionListener(){ - - @Override - public void actionPerformed(ActionEvent e) { - MenuCreator.showMemoryMonitor(); - - } - }); + aboutM.addActionListener(e -> MenuCreator.showMemoryMonitor()); return aboutM; } @@ -888,14 +848,7 @@ public void windowClosing(WindowEvent e) {} Box b = Box.createHorizontalBox(); JButton b1 = new JButton("Run Garbage Collector"); - b1.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - System.gc(); - - } - }); + b1.addActionListener(e -> System.gc()); b.add(b1); b.add(Box.createGlue()); @@ -920,15 +873,11 @@ private static JMenuItem getConfigMenuItem() { else configI = new JMenuItem("Settings",configIcon); configI.setMnemonic(KeyEvent.VK_S); - configI.addActionListener(new ActionListener(){ - - @Override - public void actionPerformed(ActionEvent e) { - String cmd = e.getActionCommand(); + configI.addActionListener(e -> { + String cmd = e.getActionCommand(); - if ( cmd.equals("Settings")){ - ConfigPDBInstallPanel.showDialog(); - } + if ( cmd.equals("Settings")){ + ConfigPDBInstallPanel.showDialog(); } }); return configI; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentCalc.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentCalc.java index e764a5e654..37ffe36517 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentCalc.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentCalc.java @@ -22,19 +22,15 @@ */ package org.biojava.nbio.structure.align.gui; -import java.util.ArrayList; -import java.util.List; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIdentifier; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.MultipleStructureAligner; import org.biojava.nbio.structure.align.multiple.MultipleAlignment; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.List; + /** * A class that obtains structures via DAS and aligns them. * This is done in a separate thread. @@ -78,7 +74,7 @@ public void run() { parent.getMultipleStructureAligner(); try { - List atomArrays = new ArrayList(); + List atomArrays = new ArrayList<>(); for (Structure s:structures){ Atom[] ca = StructureTools.getRepresentativeAtomArray(s); atomArrays.add(ca); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentGUI.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentGUI.java index 95a4ac248e..2cf8e7503f 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentGUI.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentGUI.java @@ -22,22 +22,6 @@ */ package org.biojava.nbio.structure.align.gui; -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.util.List; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JMenuBar; -import javax.swing.JOptionPane; -import javax.swing.JProgressBar; -import javax.swing.JTabbedPane; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIdentifier; @@ -50,6 +34,11 @@ import org.biojava.nbio.structure.align.webstart.AligUIManager; import org.biojava.nbio.structure.gui.util.SelectMultiplePanel; +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.util.List; + /** * A JFrame that allows to trigger a multiple structure alignment, * either from files in a directory or after manual upload. @@ -64,14 +53,14 @@ */ public class MultipleAlignmentGUI extends JFrame { - private final static long serialVersionUID =0l; + private final static long serialVersionUID = 0L; private final static String version = "1.0"; private MultipleStructureAligner multiple; private StructureAlignment pairwise; - private SelectMultiplePanel tab; - private JTabbedPane tabPane; + private final SelectMultiplePanel tab; + private final JTabbedPane tabPane; private Thread thread; private AlignmentCalculationRunnable alicalc; @@ -154,7 +143,7 @@ private Box setupPairwiseAlgorithm() { algorithmList.setSelectedIndex(0); Action actionAlgorithm = new AbstractAction("Algorithm") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; @Override public void actionPerformed(ActionEvent evt) { JComboBox cb = (JComboBox)evt.getSource(); @@ -165,7 +154,7 @@ public void actionPerformed(ActionEvent evt) { algorithmList.addActionListener(actionAlgorithm); Action paramAction = new AbstractAction("Parameters") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; @Override public void actionPerformed(ActionEvent evt) { StructureAlignment p = getPairwiseStructureAligner(); @@ -197,7 +186,7 @@ private Box setupMultipleAlgorithm() { multList.setSelectedIndex(0); Action actionMultiple = new AbstractAction("Algorithm") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; @Override public void actionPerformed(ActionEvent evt) { updateMultipleAlgorithm(); @@ -206,7 +195,7 @@ public void actionPerformed(ActionEvent evt) { multList.addActionListener(actionMultiple); Action paramAction = new AbstractAction("Parameters") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; @Override public void actionPerformed(ActionEvent evt) { MultipleStructureAligner m = getMultipleStructureAligner(); @@ -236,7 +225,7 @@ private Box initButtons(){ progress.setVisible(false); Action action1 = new AbstractAction("Align") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -246,7 +235,7 @@ public void actionPerformed(ActionEvent evt) { JButton submitB = new JButton(action1); Action action3 = new AbstractAction("Abort") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -257,7 +246,7 @@ public void actionPerformed(ActionEvent evt) { abortB.setEnabled(false); Action action2 = new AbstractAction("Exit") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -284,7 +273,7 @@ public void cleanUp() { private void calcAlignment() { - try { +// try { List structures = tab.getStructures(); if ( structures.size() < 2) { @@ -309,10 +298,10 @@ private void calcAlignment() { ProgressThreadDrawer drawer = new ProgressThreadDrawer(progress); drawer.start(); - } catch (StructureException e){ - JOptionPane.showMessageDialog(null,"Could not align structures. " - + "Exception: " + e.getMessage()); - } +// } catch (StructureException e){ +// JOptionPane.showMessageDialog(null,"Could not align structures. " +// + "Exception: " + e.getMessage()); +// } } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentJmolDisplay.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentJmolDisplay.java index fac312875f..d746a83aea 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentJmolDisplay.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MultipleAlignmentJmolDisplay.java @@ -20,15 +20,6 @@ */ package org.biojava.nbio.structure.align.gui; -import java.awt.Dimension; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.Box; -import javax.swing.JFrame; -import javax.swing.JMenuBar; -import javax.swing.JScrollPane; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.gui.aligpanel.MultipleAligPanel; @@ -39,6 +30,11 @@ import org.biojava.nbio.structure.align.multiple.Block; import org.biojava.nbio.structure.align.multiple.MultipleAlignment; import org.biojava.nbio.structure.align.multiple.util.MultipleAlignmentDisplay; + +import javax.swing.*; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; @@ -76,7 +72,7 @@ public class MultipleAlignmentJmolDisplay { public static List getPDBresnum(int structNum, MultipleAlignment multAln, Atom[] ca){ - List lst = new ArrayList(); + List lst = new ArrayList<>(); for(Block block : multAln.getBlocks() ) { @@ -99,11 +95,9 @@ else if (pos < ca.length) { * * @param multAln * @param jmol - - * @throws StructureException */ public static void showMultipleAligmentPanel(MultipleAlignment multAln, - AbstractAlignmentJmol jmol) throws StructureException { + AbstractAlignmentJmol jmol) { MultipleAligPanel me = new MultipleAligPanel(multAln, jmol); JFrame frame = new JFrame(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyAlignmentLoadListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyAlignmentLoadListener.java index 2a85930c27..bd11a5af1b 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyAlignmentLoadListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyAlignmentLoadListener.java @@ -20,6 +20,7 @@ */ package org.biojava.nbio.structure.align.gui; +import org.biojava.nbio.core.util.InputStreamProvider; import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol; import org.biojava.nbio.structure.align.model.AFPChain; @@ -30,10 +31,8 @@ import org.biojava.nbio.structure.align.webstart.WebStartMain; import org.biojava.nbio.structure.align.xml.AFPChainXMLParser; import org.biojava.nbio.structure.align.xml.MultipleAlignmentXMLParser; -import org.biojava.nbio.core.util.InputStreamProvider; import javax.swing.*; - import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; @@ -76,7 +75,7 @@ public void actionPerformed(ActionEvent evt) { BufferedReader in = new BufferedReader( new InputStreamReader(stream)); - StringBuffer input = new StringBuffer(); + StringBuilder input = new StringBuilder(); String str; while ((str = in.readLine()) != null) { input.append(str); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyDistMaxListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyDistMaxListener.java index 9faf74cfe7..87152b52c7 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyDistMaxListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyDistMaxListener.java @@ -24,7 +24,6 @@ import org.biojava.nbio.structure.jama.Matrix; import javax.swing.*; - import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; @@ -35,7 +34,7 @@ */ public class MyDistMaxListener implements ActionListener{ - AbstractAlignmentJmol parent; + final AbstractAlignmentJmol parent; public MyDistMaxListener(AbstractAlignmentJmol parent){ this.parent = parent; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyExportListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyExportListener.java index 77a550c57c..88d24421d7 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyExportListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyExportListener.java @@ -21,8 +21,8 @@ import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.align.gui.jmol.AbstractAlignmentJmol; -import javax.swing.*; +import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; @@ -32,7 +32,7 @@ public class MyExportListener implements ActionListener{ - AbstractAlignmentJmol parent; + final AbstractAlignmentJmol parent; MyExportListener(AbstractAlignmentJmol parent){ this.parent = parent; } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MySaveFileListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MySaveFileListener.java index f93fba29df..1704f82061 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MySaveFileListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MySaveFileListener.java @@ -30,7 +30,6 @@ import org.biojava.nbio.structure.align.xml.AFPChainXMLConverter; import javax.swing.*; - import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedWriter; @@ -52,8 +51,8 @@ */ public class MySaveFileListener implements ActionListener { - private AFPChain afpChain; - private MultipleAlignment msa; + private final AFPChain afpChain; + private final MultipleAlignment msa; private boolean printText; public MySaveFileListener (AFPChain afpChain){ diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyTableRowSorter.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyTableRowSorter.java index a8f141e76a..5d0745108e 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyTableRowSorter.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/MyTableRowSorter.java @@ -50,7 +50,7 @@ public Comparator getComparator(int column) class MyComparator implements Comparator, Serializable { private static final long serialVersionUID = 1; - int column; + final int column; public MyComparator(int column){ this.column = column; } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ParameterGUI.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ParameterGUI.java index 836e386ab4..afa9f5500d 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ParameterGUI.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/ParameterGUI.java @@ -24,8 +24,6 @@ import javax.swing.*; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; @@ -82,7 +80,7 @@ public ParameterGUI(ConfigStrucAligParams params, String algorithm) { assert(names.size() == types.size()); assert(names.size() == helps.size()); - textFields = new ArrayList(); + textFields = new ArrayList<>(); Box vBox = Box.createVerticalBox(); for (int i = 0 ; i < keys.size(); i++){ @@ -146,32 +144,21 @@ public ParameterGUI(ConfigStrucAligParams params, String algorithm) { JButton abort = new JButton("Cancel"); - abort.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent event) { - destroy(); - dispose(); } - }); + abort.addActionListener(event -> { + destroy(); + dispose(); }); JButton defaultB = new JButton("Default"); - defaultB.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent event) { - setDefault(); - } - }); + defaultB.addActionListener(event -> setDefault()); JButton close = new JButton("Apply"); - close.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent event) { + close.addActionListener(event -> { - storeParameters(); + storeParameters(); - destroy(); - dispose(); } - }); + destroy(); + dispose(); }); Box hBox = Box.createHorizontalBox(); hBox.add(abort); @@ -247,7 +234,7 @@ protected void storeParameters() { Class type = types.get(i); String key = keys.get(i); // String name = keys.get(i); - String value = null; + String value; System.out.println(key); if( type.isEnum() ) { JComboBox field = (JComboBox) textFields.get(i); @@ -256,10 +243,10 @@ protected void storeParameters() { } else if ( type == Boolean.class){ JComboBox field = (JComboBox) textFields.get(i); int sel = field.getSelectedIndex(); - Boolean flag = true; + boolean flag = true; if ( sel == 1 ) flag = false; - value = flag.toString(); + value = Boolean.toString(flag); } else { JTextField field = (JTextField)textFields.get(i); value = field.getText(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/SelectPDBPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/SelectPDBPanel.java index d8eb946e4d..2099eac80f 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/SelectPDBPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/SelectPDBPanel.java @@ -20,26 +20,16 @@ */ package org.biojava.nbio.structure.align.gui; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.io.IOException; - -import javax.swing.Box; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTabbedPane; -import javax.swing.JTextField; - -import org.biojava.nbio.structure.ResidueRange; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIdentifier; -import org.biojava.nbio.structure.SubstructureIdentifier; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.align.util.UserConfiguration; import org.biojava.nbio.structure.align.webstart.WebStartMain; import org.biojava.nbio.structure.gui.util.StructurePairSelector; +import javax.swing.*; +import java.awt.*; +import java.io.IOException; + /** A Panel that allows user to specify PDB & chain ID, as well as sub-ranges * @@ -52,12 +42,12 @@ public class SelectPDBPanel boolean debug = true; - JTextField f1; - JTextField f2; - JTextField c1; - JTextField c2; - JTextField r1; - JTextField r2; + final JTextField f1; + final JTextField f2; + final JTextField c1; + final JTextField c2; + final JTextField r1; + final JTextField r2; UserConfiguration config; JTabbedPane configPane; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/StructureAlignmentDisplay.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/StructureAlignmentDisplay.java index 266abef138..90ec47afca 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/StructureAlignmentDisplay.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/StructureAlignmentDisplay.java @@ -20,8 +20,6 @@ */ package org.biojava.nbio.structure.align.gui; -import java.util.List; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Group; import org.biojava.nbio.structure.StructureException; @@ -30,6 +28,8 @@ import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.util.AlignmentTools; +import java.util.List; + public class StructureAlignmentDisplay { /** Display an AFPChain alignment diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/StructureLoaderThread.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/StructureLoaderThread.java index fa4bba99f2..bb350bbc81 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/StructureLoaderThread.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/StructureLoaderThread.java @@ -34,10 +34,10 @@ public class StructureLoaderThread extends SwingWorker { - String name; - boolean showBiolAssembly; + final String name; + final boolean showBiolAssembly; - UserConfiguration config; + final UserConfiguration config; StructureLoaderThread(UserConfiguration config, String name, boolean showBiolAssembly){ this.name = name; @@ -52,7 +52,7 @@ protected String doInBackground() { System.out.println("loading " + name ); AtomCache cache = new AtomCache(config.getPdbFilePath(),config.getCacheFilePath()); - Structure s = null; + Structure s; try { if ( showBiolAssembly) { s= StructureIO.getBiologicalAssembly(name); @@ -97,29 +97,25 @@ public static void showProgressBar() { if ( progressFrame == null){ - SwingUtilities.invokeLater(new Runnable() { + SwingUtilities.invokeLater(() -> { + // TODO Auto-generated method stub - @Override - public void run() { - // TODO Auto-generated method stub + final JFrame frame = new JFrame("Loading ..."); + final JProgressBar progressBar = new JProgressBar(); - final JFrame frame = new JFrame("Loading ..."); - final JProgressBar progressBar = new JProgressBar(); + progressBar.setIndeterminate(true); - progressBar.setIndeterminate(true); - - final JPanel contentPane = new JPanel(); - contentPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); - contentPane.setLayout(new BorderLayout()); - contentPane.add(new JLabel("Loading ..."), BorderLayout.NORTH); - contentPane.add(progressBar, BorderLayout.CENTER); - frame.setContentPane(contentPane); - frame.pack(); - frame.setLocationRelativeTo(null); - progressFrame = frame; - frame.setVisible(true); - } + final JPanel contentPane = new JPanel(); + contentPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); + contentPane.setLayout(new BorderLayout()); + contentPane.add(new JLabel("Loading ..."), BorderLayout.NORTH); + contentPane.add(progressBar, BorderLayout.CENTER); + frame.setContentPane(contentPane); + frame.pack(); + frame.setLocationRelativeTo(null); + progressFrame = frame; + frame.setVisible(true); }); } @@ -130,14 +126,10 @@ public void run() { static JFrame progressFrame = null; private void hideProgressBar() { - SwingUtilities.invokeLater(new Runnable() { - - @Override - public void run() { - if ( progressFrame != null){ - progressFrame.dispose(); - progressFrame = null; - } + SwingUtilities.invokeLater(() -> { + if ( progressFrame != null){ + progressFrame.dispose(); + progressFrame = null; } }); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/SystemInfo.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/SystemInfo.java index a899f485c8..dacf98c759 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/SystemInfo.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/SystemInfo.java @@ -29,10 +29,7 @@ import javax.swing.*; import javax.swing.border.EtchedBorder; import javax.swing.event.HyperlinkEvent; -import javax.swing.event.HyperlinkListener; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.util.Enumeration; import java.util.Properties; import java.util.StringTokenizer; @@ -72,7 +69,7 @@ public class SystemInfo + "user.dir " + "user.home " + "user.name "; - EtchedBorder border; + final EtchedBorder border; public SystemInfo() { @@ -212,11 +209,11 @@ public void addOneSystemProperty( } } else if (isURLProperty(name)) { - StringBuffer fixed = new StringBuffer(); + StringBuilder fixed = new StringBuilder(); int start = 0; - int hit = 0; + int hit; while ((hit = propValue.indexOf('%', start)) >= 0) { - fixed.append(propValue.substring(start, hit)); + fixed.append(propValue, start, hit); int value = Integer.parseInt(propValue.substring(hit + 1, hit + 3), 16); fixed.append(((char) value)); @@ -280,22 +277,18 @@ public void showDialog(){ vBox= Box.createVerticalBox(); vBox.add(scroll); - txt.addHyperlinkListener(new HyperlinkListener(){ + txt.addHyperlinkListener(e -> { - @Override - public void hyperlinkUpdate(HyperlinkEvent e) { - - if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { - String href = e.getDescription(); - BrowserOpener.showDocument(href); - } - if ( e.getEventType() == HyperlinkEvent.EventType.ENTERED) { - // change the mouse curor - vBox.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - } - if (e.getEventType() == HyperlinkEvent.EventType.EXITED) { - vBox.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); - } + if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { + String href = e.getDescription(); + BrowserOpener.showDocument(href); + } + if ( e.getEventType() == HyperlinkEvent.EventType.ENTERED) { + // change the mouse curor + vBox.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); + } + if (e.getEventType() == HyperlinkEvent.EventType.EXITED) { + vBox.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } }); @@ -304,17 +297,14 @@ public void hyperlinkUpdate(HyperlinkEvent e) { JButton close = new JButton("Close"); - close.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent event) { - Object source = event.getSource(); + close.addActionListener(event -> { + Object source = event.getSource(); - JButton but = (JButton)source; - Container parent = but.getParent().getParent().getParent().getParent().getParent().getParent() ; + JButton but = (JButton)source; + Container parent = but.getParent().getParent().getParent().getParent().getParent().getParent() ; - JDialog dia = (JDialog) parent; - dia.dispose(); - } + JDialog dia = (JDialog) parent; + dia.dispose(); }); Box hBoxb = Box.createHorizontalBox(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/AligPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/AligPanel.java index 6eadd48dcd..312186cfc2 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/AligPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/AligPanel.java @@ -63,11 +63,11 @@ public class AligPanel extends JPrintPanel implements AlignmentPositionListener private static final long serialVersionUID = -6892229111166263764L; private AFPChain afpChain; - private AFPChainCoordManager coordManager ; - private Font seqFont; - private Font eqFont; + private final AFPChainCoordManager coordManager ; + private final Font seqFont; + private final Font eqFont; private AbstractAlignmentJmol jmol; - private AligPanelMouseMotionListener mouseMoLi; + private final AligPanelMouseMotionListener mouseMoLi; private BitSet selection; @@ -89,7 +89,7 @@ public static void main(String[] args){ try { BufferedReader in = new BufferedReader(new FileReader(file)); - StringBuffer xml = new StringBuffer(); + StringBuilder xml = new StringBuilder(); String str; while ((str = in.readLine()) != null) { xml.append(str); @@ -279,7 +279,7 @@ public void paintComponent(Graphics g){ int colorPos = 0; if (isFATCAT) { - int block = 0; + int block; char s = symb[i]; try { block = Integer.parseInt(String.valueOf(s)) - 1; @@ -430,7 +430,7 @@ private void updateJmolDisplay() { int size = afpChain.getAlnLength(); - StringBuffer cmd = new StringBuffer("select "); + StringBuilder cmd = new StringBuilder("select "); int nrSelected = 0; try { @@ -450,7 +450,7 @@ private void updateJmolDisplay() { select2 = JmolTools.getPdbInfo(a2); // nothing to display - if ( select1.equals("") && select2.equals("")) + if (select1.isEmpty() && select2.isEmpty()) continue; if ( nrSelected > 0) @@ -581,30 +581,42 @@ public void windowOpened(WindowEvent e) { public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); // print is handled by superclass - if ( cmd.equals(MenuCreator.PRINT)) { - super.actionPerformed(e); - } else if (cmd.equals(MenuCreator.TEXT_ONLY)){ - String result = AfpChainWriter.toWebSiteDisplay(afpChain, ca1, ca2); - DisplayAFP.showAlignmentImage(afpChain, result); - } else if ( cmd.equals(MenuCreator.PAIRS_ONLY)) { - String result = AfpChainWriter.toAlignedPairs(afpChain, ca1, ca2) ; - DisplayAFP.showAlignmentImage(afpChain, result); - } else if (cmd.equals(MenuCreator.FATCAT_TEXT)){ - String result = afpChain.toFatcat(ca1, ca2); - result += AFPChain.newline; - result += afpChain.toRotMat(); - DisplayAFP.showAlignmentImage(afpChain, result); - } else if ( cmd.equals(MenuCreator.SELECT_EQR)){ - selectEQR(); - } else if ( cmd.equals(MenuCreator.SIMILARITY_COLOR)){ - colorBySimilarity(true); - } else if ( cmd.equals(MenuCreator.EQR_COLOR)){ - colorBySimilarity(false); - } else if ( cmd.equals(MenuCreator.FATCAT_BLOCK)){ - colorByAlignmentBlock(); - } - else { - System.err.println("Unknown command:" + cmd); + switch (cmd) { + case MenuCreator.PRINT: + super.actionPerformed(e); + break; + case MenuCreator.TEXT_ONLY: { + String result = AfpChainWriter.toWebSiteDisplay(afpChain, ca1, ca2); + DisplayAFP.showAlignmentImage(afpChain, result); + break; + } + case MenuCreator.PAIRS_ONLY: { + String result = AfpChainWriter.toAlignedPairs(afpChain, ca1, ca2); + DisplayAFP.showAlignmentImage(afpChain, result); + break; + } + case MenuCreator.FATCAT_TEXT: { + String result = afpChain.toFatcat(ca1, ca2); + result += AFPChain.newline; + result += afpChain.toRotMat(); + DisplayAFP.showAlignmentImage(afpChain, result); + break; + } + case MenuCreator.SELECT_EQR: + selectEQR(); + break; + case MenuCreator.SIMILARITY_COLOR: + colorBySimilarity(true); + break; + case MenuCreator.EQR_COLOR: + colorBySimilarity(false); + break; + case MenuCreator.FATCAT_BLOCK: + colorByAlignmentBlock(); + break; + default: + System.err.println("Unknown command:" + cmd); + break; } } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/AligPanelMouseMotionListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/AligPanelMouseMotionListener.java index 9914f07d2a..8cbe50f689 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/AligPanelMouseMotionListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/AligPanelMouseMotionListener.java @@ -34,7 +34,7 @@ public class AligPanelMouseMotionListener implements MouseMotionListener, MouseL AligPanel parent; - List aligPosListeners; + final List aligPosListeners; int prevPos; boolean isDragging ; @@ -44,7 +44,7 @@ public class AligPanelMouseMotionListener implements MouseMotionListener, MouseL public AligPanelMouseMotionListener(AligPanel parent){ this.parent = parent; - aligPosListeners = new ArrayList(); + aligPosListeners = new ArrayList<>(); prevPos = -1; isDragging = false; selectionStart = null; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleAligPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleAligPanel.java index 1387bbd417..84ccbe53dd 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleAligPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleAligPanel.java @@ -20,22 +20,7 @@ */ package org.biojava.nbio.structure.align.gui.aligpanel; -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.event.ActionEvent; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; -import java.util.ArrayList; -import java.util.BitSet; -import java.util.List; - import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.gui.JPrintPanel; import org.biojava.nbio.structure.align.gui.MenuCreator; import org.biojava.nbio.structure.align.gui.MultipleAlignmentJmolDisplay; @@ -50,6 +35,14 @@ import org.biojava.nbio.structure.gui.events.AlignmentPositionListener; import org.biojava.nbio.structure.gui.util.AlignedPosition; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; +import java.util.ArrayList; +import java.util.BitSet; +import java.util.List; + /** * A JPanel that can display the sequence alignment of a * {@link MultipleAlignment} in a nice way and interact with Jmol by @@ -77,11 +70,11 @@ public class MultipleAligPanel extends JPrintPanel int size; //number of structures int length; //number of aligned positions in sequence alignment - private Font seqFont; - private Font eqFont; + private final Font seqFont; + private final Font eqFont; private AbstractAlignmentJmol jmol; - private MultipleAligPanelMouseMotionListener mouseMoLi; + private final MultipleAligPanelMouseMotionListener mouseMoLi; private MultipleAlignmentCoordManager coordManager; private BitSet selection; @@ -120,10 +113,9 @@ public MultipleAligPanel(){ * @param afpChain * @param ca1 * @param ca2 - * @throws StructureException */ public MultipleAligPanel(AFPChain afpChain, Atom[] ca1, Atom[] ca2, - AbstractAlignmentJmol jmol) throws StructureException { + AbstractAlignmentJmol jmol) { this(); @@ -139,7 +131,7 @@ public MultipleAligPanel(AFPChain afpChain, Atom[] ca1, Atom[] ca2, this.multAln = ensemble.getMultipleAlignment(0); //Create the sequence alignment and the structure-sequence mapping. - this.mapSeqToStruct = new ArrayList(); + this.mapSeqToStruct = new ArrayList<>(); this.alnSeq = MultipleAlignmentTools.getSequenceAlignment( this.multAln, this.mapSeqToStruct); @@ -162,7 +154,7 @@ public MultipleAligPanel(MultipleAlignment msa, AbstractAlignmentJmol jm) { this.multAln = msa; //Create the sequence alignment and the structure-sequence mapping. - this.mapSeqToStruct = new ArrayList(); + this.mapSeqToStruct = new ArrayList<>(); this.alnSeq = MultipleAlignmentTools.getSequenceAlignment( this.multAln, this.mapSeqToStruct); @@ -225,7 +217,7 @@ public void paintComponent(Graphics g){ else isGapped = true; //Loop through every structure to get all the points - List points = new ArrayList(); + List points = new ArrayList<>(); for (int str=0; str aligPosListeners; + private final List aligPosListeners; private int prevPos; private boolean isDragging ; @@ -52,7 +52,7 @@ public class MultipleAligPanelMouseMotionListener public MultipleAligPanelMouseMotionListener(MultipleAligPanel parent){ this.parent = parent; - aligPosListeners = new ArrayList(); + aligPosListeners = new ArrayList<>(); prevPos = -1; isDragging = false; selectionStart = null; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleAlignmentCoordManager.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleAlignmentCoordManager.java index 35c65c524c..e7f562487e 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleAlignmentCoordManager.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleAlignmentCoordManager.java @@ -31,8 +31,8 @@ */ public class MultipleAlignmentCoordManager { - private int alignmentLength; //number of aligned residues - private int alignmentSize; //number of strucures aligned + private final int alignmentLength; //number of aligned residues + private final int alignmentSize; //number of strucures aligned /** * Constructor. diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleStatusDisplay.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleStatusDisplay.java index e87ad5817c..4ea5893b8f 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleStatusDisplay.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/aligpanel/MultipleStatusDisplay.java @@ -20,19 +20,17 @@ */ package org.biojava.nbio.structure.align.gui.aligpanel; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; - -import javax.swing.JTextField; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.align.gui.jmol.JmolTools; import org.biojava.nbio.structure.align.multiple.util.MultipleAlignmentTools; import org.biojava.nbio.structure.gui.events.AlignmentPositionListener; import org.biojava.nbio.structure.gui.util.AlignedPosition; +import javax.swing.*; +import java.awt.*; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; + /** * This class provides information of the selected positions in the * {@link MultipleAligPanel}. diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/AutoSuggestProvider.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/AutoSuggestProvider.java index 88352df175..64105ca298 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/AutoSuggestProvider.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/AutoSuggestProvider.java @@ -38,31 +38,31 @@ public interface AutoSuggestProvider { * @param userInput * @return list of suggestions */ - public Vector getSuggestion(String userInput); + Vector getSuggestion(String userInput); /** set the maximum number of suggestions to return * * @param maxNrSuggestions */ - public void setMaxNrSuggestions(int maxNrSuggestions); + void setMaxNrSuggestions(int maxNrSuggestions); /** Get the maximun nr of suggestions * * @return maxNrSuggestions */ - public int getMaxNrSuggestions(); + int getMaxNrSuggestions(); /** reset all suggestions * */ - public void clear(); + void clear(); /** Interrupt searching for suggestions * */ - public void stop(); + void stop(); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/DefaultAutoSuggestProvider.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/DefaultAutoSuggestProvider.java index 045ff5ce8d..1a87aa786a 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/DefaultAutoSuggestProvider.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/DefaultAutoSuggestProvider.java @@ -30,7 +30,7 @@ public class DefaultAutoSuggestProvider implements AutoSuggestProvider { @Override public Vector getSuggestion(String userInput) { - Vector data = new Vector(); + Vector data = new Vector<>(); data.add(userInput + " no AutoSuggestProvider registered yet!"); return data; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/JAutoSuggest.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/JAutoSuggest.java index 128ee39149..fae350ef65 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/JAutoSuggest.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/JAutoSuggest.java @@ -135,11 +135,11 @@ public void focusLost(FocusEvent e) { System.out.println("Lost Focus"); dialog.setVisible(false); - if (getText().trim().equals("") && e.getOppositeComponent() != null && e.getOppositeComponent().getName() != null) { + if (getText().trim().isEmpty() && e.getOppositeComponent() != null && e.getOppositeComponent().getName() != null) { if (!e.getOppositeComponent().getName().equals("suggestFieldDropdownButton")) { setText(defaultText); } - } else if (getText().trim().equals("")) { + } else if (getText().trim().isEmpty()) { setText(defaultText); } } @@ -247,7 +247,7 @@ private void init(){ lastWord = ""; regular = getFont(); busy = new Font(getFont().getName(), Font.ITALIC, getFont().getSize()); - suggestions = new Vector(); + suggestions = new Vector<>(); defaultText = DEFAULT_TEXT; @@ -340,7 +340,7 @@ private void updateLocation() { */ private class SuggestionFetcher extends SwingWorker { /** flag used to stop the thread */ - private AtomicBoolean stop = new AtomicBoolean(false); + private final AtomicBoolean stop = new AtomicBoolean(false); String previousWord; /** @@ -352,7 +352,7 @@ public String doInBackground() { try { setFont(busy); String userInput = getText().trim(); - if ( userInput == null || userInput.equals("")) + if ( userInput == null || userInput.isEmpty()) return ""; if ( previousWord != null){ diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/SCOPAutoSuggestProvider.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/SCOPAutoSuggestProvider.java index d90fd0380f..662f9bd3a5 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/SCOPAutoSuggestProvider.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/autosuggest/SCOPAutoSuggestProvider.java @@ -36,18 +36,18 @@ public class SCOPAutoSuggestProvider implements AutoSuggestProvider{ - boolean DEBUG = false; + final boolean DEBUG = false; int maxResults = 20; - AtomicBoolean stop = new AtomicBoolean(false); + final AtomicBoolean stop = new AtomicBoolean(false); @Override public Vector getSuggestion(String userInput) { long timeS = System.currentTimeMillis(); - List domains = new ArrayList(); + List domains; domains = getPossibleScopDomains(userInput); @@ -55,7 +55,7 @@ public Vector getSuggestion(String userInput) { // convert domains to Strings - Vector v=new Vector(); + Vector v= new Vector<>(); int counter = 0; for ( ScopDomain d : domains){ @@ -82,7 +82,7 @@ public Vector getSuggestion(String userInput) { private List getPossibleScopDomains(String userInput) { - List domains = new ArrayList(); + List domains = new ArrayList<>(); ScopDatabase scop = ScopFactory.getSCOP(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AbstractAlignmentJmol.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AbstractAlignmentJmol.java index 4663505797..b6cdf1f0fc 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AbstractAlignmentJmol.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AbstractAlignmentJmol.java @@ -20,23 +20,7 @@ */ package org.biojava.nbio.structure.align.gui.jmol; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionListener; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; -import java.util.List; - -import javax.swing.JFrame; -import javax.swing.JTextField; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.ChainImpl; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureImpl; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.ResourceManager; import org.biojava.nbio.structure.jama.Matrix; import org.jcolorbrewer.ColorBrewer; @@ -45,6 +29,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.swing.*; +import java.awt.event.*; +import java.util.List; + /** * An Abstract Class to generalize the visualization of AFP and * MultipleAlignment structure alignments in Jmol. diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AtomInfo.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AtomInfo.java index e90fafcf43..83b93ac1bc 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AtomInfo.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AtomInfo.java @@ -40,7 +40,7 @@ public class AtomInfo { String residueNumber; int modelNumber; - private static Pattern inscodePatter ; + private static final Pattern inscodePatter ; static { inscodePatter = Pattern.compile("([0-9]+)([a-zA-Z]*)?"); } @@ -106,25 +106,25 @@ public void setAtomName(String name) { @Override public String toString() { - String aa3 = ""; + String aa3; boolean printResName = true; - String chain1 =""; - String res1 = ""; + String chain1; + String res1; aa3 = residueName; res1 = residueNumber; chain1 = chainId; - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); if ( printResName) { - if ( !aa3.equals("")){ + if (!aa3.isEmpty()){ buf.append("["); buf.append(aa3); buf.append("]"); } } - if ( ! res1.equals("")) { + if (!res1.isEmpty()) { // let's check if there is an insertion code... Matcher matcher = inscodePatter.matcher(res1); @@ -137,7 +137,7 @@ public String toString() { String residueNumber = matcher.group(1); String insCode = matcher.group(2); buf.append(residueNumber); - if ( insCode != null && ! ( insCode.equals(""))) { + if ( insCode != null && ! (insCode.isEmpty())) { buf.append("^"); buf.append(insCode); } @@ -145,7 +145,7 @@ public String toString() { } - if ( ! chain1.equals("")){ + if (!chain1.isEmpty()){ buf.append(":"); buf.append(chain1); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AtomInfoParser.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AtomInfoParser.java index ac4dd69120..8cef15b12b 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AtomInfoParser.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/AtomInfoParser.java @@ -33,11 +33,11 @@ public class AtomInfoParser { private static final Logger logger = LoggerFactory.getLogger(AtomInfoParser.class); - static Pattern pattern; + static final Pattern pattern; static { - String numberPattern = "\\[(.*)\\]([0-9^a-zA-Z]+)(:[a-zA-Z]*)?\\.([a-zA-Z]+)(/[0-9]*)?"; + String numberPattern = "\\[(.*)]([0-9^a-zA-Z]+)(:[a-zA-Z]*)?\\.([a-zA-Z]+)(/[0-9]*)?"; pattern = Pattern.compile(numberPattern); } @@ -94,12 +94,12 @@ public static AtomInfo parse(String jmolAtomInfo){ String ci = " "; if (chainId != null) - ci = chainId.substring(1,chainId.length()); + ci = chainId.substring(1); info.setChainId(ci); int mn = 1; if ( modelNumber != null) - mn = Integer.parseInt(modelNumber.substring(1,modelNumber.length())); + mn = Integer.parseInt(modelNumber.substring(1)); info.setModelNumber(mn); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/JmolPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/JmolPanel.java index b8b37c6251..8ee76173b1 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/JmolPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/JmolPanel.java @@ -24,27 +24,7 @@ package org.biojava.nbio.structure.align.gui.jmol; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; -import java.text.DecimalFormat; -import java.util.List; - -import javax.swing.JComboBox; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Calc; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.gui.JPrintPanel; import org.biojava.nbio.structure.domain.LocalProteinDomainParser; import org.biojava.nbio.structure.domain.pdp.Domain; @@ -63,6 +43,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.*; +import java.text.DecimalFormat; +import java.util.List; + +import static org.jmol.util.Logger.LEVEL_FATAL; + public class JmolPanel extends JPrintPanel @@ -74,7 +64,7 @@ public class JmolPanel private JmolViewer viewer; private JmolAdapter adapter; - JmolStatusListener statusListener; + final JmolStatusListener statusListener; final Dimension currentSize = new Dimension(); final Rectangle rectClip = new Rectangle(); @@ -91,6 +81,7 @@ public JmolPanel() { adapter, null,null,null,null, statusListener); + setIgnoreRepaint(true); } @@ -135,9 +126,9 @@ public void setStructure(final Structure s, boolean useMmtf) { try ( PipedOutputStream out = new PipedOutputStream(); // Viewer requires a BufferedInputStream for reflection - InputStream in = new BufferedInputStream(new PipedInputStream(out)); - ) { - new Thread((Runnable)() -> { + InputStream in = new BufferedInputStream(new PipedInputStream(out)) + ) { + new Thread(() -> { try { MmtfActions.writeToOutputStream(s,out); } catch (Exception e) { @@ -171,39 +162,7 @@ public void setStructure(final Structure s) { */ public void jmolColorByChain(){ String script = - "function color_by_chain(objtype, color_list) {"+ String.format("%n") + - ""+ String.format("%n") + - " if (color_list) {"+ String.format("%n") + - " if (color_list.type == \"string\") {"+ String.format("%n") + - " color_list = color_list.split(\",\").trim();"+ String.format("%n") + - " }"+ String.format("%n") + - " } else {"+ String.format("%n") + - " color_list = [\"104BA9\",\"AA00A2\",\"C9F600\",\"FFA200\",\"284A7E\",\"7F207B\",\"9FB82E\",\"BF8B30\",\"052D6E\",\"6E0069\",\"83A000\",\"A66A00\",\"447BD4\",\"D435CD\",\"D8FA3F\",\"FFBA40\",\"6A93D4\",\"D460CF\",\"E1FA71\",\"FFCC73\"];"+ String.format("%n") + - " }"+ String.format("%n") + - - " var cmd2 = \"\";"+ String.format("%n") + - - " if (!objtype) {"+ String.format("%n") + - " var type_list = [ \"backbone\",\"cartoon\",\"dots\",\"halo\",\"label\",\"meshribbon\",\"polyhedra\",\"rocket\",\"star\",\"strand\",\"strut\",\"trace\"];"+ String.format("%n") + - " cmd2 = \"color \" + type_list.join(\" none; color \") + \" none;\";"+ String.format("%n") + - " objtype = \"atoms\";"+ String.format("%n") + - - " }"+ String.format("%n") + - - " var chain_list = script(\"show chain\").trim().lines;"+ String.format("%n") + - " var chain_count = chain_list.length;"+ String.format("%n") + - - " var color_count = color_list.length;"+ String.format("%n") + - " var sel = {selected};"+ String.format("%n") + - " var cmds = \"\";"+ String.format("%n") + - - - " for (var chain_number=1; chain_number<=chain_count; chain_number++) {"+ String.format("%n") + - " // remember, Jmol arrays start with 1, but % can return 0"+ String.format("%n") + - " cmds += \"select sel and :\" + chain_list[chain_number] + \";color \" + objtype + \" [x\" + color_list[(chain_number-1) % color_count + 1] + \"];\" + cmd2;"+ String.format("%n") + - " }"+ String.format("%n") + - " script INLINE @{cmds + \"select sel\"}"+ String.format("%n") + - "}"; + "function color_by_chain(objtype, color_list) {" + String.format("%n") + String.format("%n") + " if (color_list) {" + String.format("%n") + " if (color_list.type == \"string\") {" + String.format("%n") + " color_list = color_list.split(\",\").trim();" + String.format("%n") + " }" + String.format("%n") + " } else {" + String.format("%n") + " color_list = [\"104BA9\",\"AA00A2\",\"C9F600\",\"FFA200\",\"284A7E\",\"7F207B\",\"9FB82E\",\"BF8B30\",\"052D6E\",\"6E0069\",\"83A000\",\"A66A00\",\"447BD4\",\"D435CD\",\"D8FA3F\",\"FFBA40\",\"6A93D4\",\"D460CF\",\"E1FA71\",\"FFCC73\"];" + String.format("%n") + " }" + String.format("%n") + " var cmd2 = \"\";" + String.format("%n") + " if (!objtype) {" + String.format("%n") + " var type_list = [ \"backbone\",\"cartoon\",\"dots\",\"halo\",\"label\",\"meshribbon\",\"polyhedra\",\"rocket\",\"star\",\"strand\",\"strut\",\"trace\"];" + String.format("%n") + " cmd2 = \"color \" + type_list.join(\" none; color \") + \" none;\";" + String.format("%n") + " objtype = \"atoms\";" + String.format("%n") + " }" + String.format("%n") + " var chain_list = script(\"show chain\").trim().lines;" + String.format("%n") + " var chain_count = chain_list.length;" + String.format("%n") + " var color_count = color_list.length;" + String.format("%n") + " var sel = {selected};" + String.format("%n") + " var cmds = \"\";" + String.format("%n") + " for (var chain_number=1; chain_number<=chain_count; chain_number++) {" + String.format("%n") + " // remember, Jmol arrays start with 1, but % can return 0" + String.format("%n") + " cmds += \"select sel and :\" + chain_list[chain_number] + \";color \" + objtype + \" [x\" + color_list[(chain_number-1) % color_count + 1] + \"];\" + cmd2;" + String.format("%n") + " }" + String.format("%n") + " script INLINE @{cmds + \"select sel\"}" + String.format("%n") + "}"; executeCmd(script); } @@ -229,66 +188,86 @@ public void actionPerformed(ActionEvent event) { String selectLigand = "select ligand;wireframe 0.16;spacefill 0.5; color cpk ;"; - if ( value.equals("Cartoon")){ - String script = "hide null; select all; spacefill off; wireframe off; backbone off;" + - " cartoon on; " + - " select ligand; wireframe 0.16;spacefill 0.5; color cpk; " + - " select *.FE; spacefill 0.7; color cpk ; " + - " select *.CU; spacefill 0.7; color cpk ; " + - " select *.ZN; spacefill 0.7; color cpk ; " + - " select all; "; - this.executeCmd(script); - } else if (value.equals("Backbone")){ - String script = "hide null; select all; spacefill off; wireframe off; backbone 0.4;" + - " cartoon off; " + - " select ligand; wireframe 0.16;spacefill 0.5; color cpk; " + - " select *.FE; spacefill 0.7; color cpk ; " + - " select *.CU; spacefill 0.7; color cpk ; " + - " select *.ZN; spacefill 0.7; color cpk ; " + - " select all; "; - this.executeCmd(script); - } else if (value.equals("CPK")){ - String script = "hide null; select all; spacefill off; wireframe off; backbone off;" + - " cartoon off; cpk on;" + - " select ligand; wireframe 0.16;spacefill 0.5; color cpk; " + - " select *.FE; spacefill 0.7; color cpk ; " + - " select *.CU; spacefill 0.7; color cpk ; " + - " select *.ZN; spacefill 0.7; color cpk ; " + - " select all; "; - this.executeCmd(script); - - } else if (value.equals("Ligands")){ - this.executeCmd("restrict ligand; cartoon off; wireframe on; display selected;"); - } else if (value.equals("Ligands and Pocket")){ - this.executeCmd(" select within (6.0,ligand); cartoon off; wireframe on; backbone off; display selected; "); - } else if ( value.equals("Ball and Stick")){ - String script = "hide null; restrict not water; wireframe 0.2; spacefill 25%;" + - " cartoon off; backbone off; " + - " select ligand; wireframe 0.16; spacefill 0.5; color cpk; " + - " select *.FE; spacefill 0.7; color cpk ; " + - " select *.CU; spacefill 0.7; color cpk ; " + - " select *.ZN; spacefill 0.7; color cpk ; " + - " select all; "; - this.executeCmd(script); - } else if ( value.equals("By Chain")){ - jmolColorByChain(); - String script = "hide null; select all;set defaultColors Jmol; color_by_chain(\"cartoon\"); color_by_chain(\"\"); " + selectLigand + "; select all; "; - this.executeCmd(script); - } else if ( value.equals("Rainbow")) { - this.executeCmd("hide null; select all; set defaultColors Jmol; color group; color cartoon group; " + selectLigand + "; select all; " ); - } else if ( value.equals("Secondary Structure")){ - this.executeCmd("hide null; select all; set defaultColors Jmol; color structure; color cartoon structure;" + selectLigand + "; select all; " ); - - } else if ( value.equals("By Element")){ - this.executeCmd("hide null; select all; set defaultColors Jmol; color cpk; color cartoon cpk; " + selectLigand + "; select all; "); - } else if ( value.equals("By Amino Acid")){ - this.executeCmd("hide null; select all; set defaultColors Jmol; color amino; color cartoon amino; " + selectLigand + "; select all; " ); - } else if ( value.equals("Hydrophobicity") ){ - this.executeCmd("hide null; set defaultColors Jmol; select hydrophobic; color red; color cartoon red; select not hydrophobic ; color blue ; color cartoon blue; "+ selectLigand+"; select all; "); - } else if ( value.equals("Suggest Domains")){ - colorByPDP(); - } else if ( value.equals("Show SCOP Domains")){ - colorBySCOP(); + switch (value) { + case "Cartoon": { + String script = "hide null; select all; spacefill off; wireframe off; backbone off;" + + " cartoon on; " + + " select ligand; wireframe 0.16;spacefill 0.5; color cpk; " + + " select *.FE; spacefill 0.7; color cpk ; " + + " select *.CU; spacefill 0.7; color cpk ; " + + " select *.ZN; spacefill 0.7; color cpk ; " + + " select all; "; + this.executeCmd(script); + break; + } + case "Backbone": { + String script = "hide null; select all; spacefill off; wireframe off; backbone 0.4;" + + " cartoon off; " + + " select ligand; wireframe 0.16;spacefill 0.5; color cpk; " + + " select *.FE; spacefill 0.7; color cpk ; " + + " select *.CU; spacefill 0.7; color cpk ; " + + " select *.ZN; spacefill 0.7; color cpk ; " + + " select all; "; + this.executeCmd(script); + break; + } + case "CPK": { + String script = "hide null; select all; spacefill off; wireframe off; backbone off;" + + " cartoon off; cpk on;" + + " select ligand; wireframe 0.16;spacefill 0.5; color cpk; " + + " select *.FE; spacefill 0.7; color cpk ; " + + " select *.CU; spacefill 0.7; color cpk ; " + + " select *.ZN; spacefill 0.7; color cpk ; " + + " select all; "; + this.executeCmd(script); + + break; + } + case "Ligands": + this.executeCmd("restrict ligand; cartoon off; wireframe on; display selected;"); + break; + case "Ligands and Pocket": + this.executeCmd(" select within (6.0,ligand); cartoon off; wireframe on; backbone off; display selected; "); + break; + case "Ball and Stick": { + String script = "hide null; restrict not water; wireframe 0.2; spacefill 25%;" + + " cartoon off; backbone off; " + + " select ligand; wireframe 0.16; spacefill 0.5; color cpk; " + + " select *.FE; spacefill 0.7; color cpk ; " + + " select *.CU; spacefill 0.7; color cpk ; " + + " select *.ZN; spacefill 0.7; color cpk ; " + + " select all; "; + this.executeCmd(script); + break; + } + case "By Chain": { + jmolColorByChain(); + String script = "hide null; select all;set defaultColors Jmol; color_by_chain(\"cartoon\"); color_by_chain(\"\"); " + selectLigand + "; select all; "; + this.executeCmd(script); + break; + } + case "Rainbow": + this.executeCmd("hide null; select all; set defaultColors Jmol; color group; color cartoon group; " + selectLigand + "; select all; "); + break; + case "Secondary Structure": + this.executeCmd("hide null; select all; set defaultColors Jmol; color structure; color cartoon structure;" + selectLigand + "; select all; "); + + break; + case "By Element": + this.executeCmd("hide null; select all; set defaultColors Jmol; color cpk; color cartoon cpk; " + selectLigand + "; select all; "); + break; + case "By Amino Acid": + this.executeCmd("hide null; select all; set defaultColors Jmol; color amino; color cartoon amino; " + selectLigand + "; select all; "); + break; + case "Hydrophobicity": + this.executeCmd("hide null; set defaultColors Jmol; select hydrophobic; color red; color cartoon red; select not hydrophobic ; color blue ; color cartoon blue; " + selectLigand + "; select all; "); + break; + case "Suggest Domains": + colorByPDP(); + break; + case "Show SCOP Domains": + colorBySCOP(); + break; } evalString("restore selection; "); } @@ -361,7 +340,7 @@ private void colorByPDP() { Group startG = ca[start].getGroup(); Group endG = ca[end].getGroup(); logger.debug(" Segment: " +startG.getResidueNumber() +":" + startG.getChainId() + " - " + endG.getResidueNumber()+":"+endG.getChainId() + " " + s); - String j1 = startG.getResidueNumber()+""; + String j1 = String.valueOf(startG.getResidueNumber()); String j2 = endG.getResidueNumber()+":"+endG.getChainId(); String script = " select " +j1 +"-" +j2 +"/1;"; script += " color [" + c1.getRed() + ","+c1.getGreen() + "," +c1.getBlue()+"];"; @@ -407,7 +386,7 @@ public void destroy(){ } public static class JmolLoggerAdapter implements LoggerInterface { - private Logger slf; + private final Logger slf; public JmolLoggerAdapter(Logger slf) { this.slf=slf; } @@ -422,7 +401,9 @@ public int getLogLevel() { return org.jmol.util.Logger.LEVEL_WARN; if( slf.isErrorEnabled() ) return org.jmol.util.Logger.LEVEL_ERROR; - throw new IllegalStateException("Unknown SLF4J error level"); + + return LEVEL_FATAL; + //throw new IllegalStateException("Unknown SLF4J error level"); } @Override public void debug(String txt) { diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/JmolTools.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/JmolTools.java index 5a42f37cad..9d9044015d 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/JmolTools.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/JmolTools.java @@ -34,11 +34,11 @@ public class JmolTools { * * @return a String representation in Jmol style of the PDB information of this atom */ - public static final String getPdbInfo(Atom a){ + public static String getPdbInfo(Atom a){ return getPdbInfo(a,true); } - private static Pattern inscodePatter ; + private static final Pattern inscodePatter ; static { inscodePatter = Pattern.compile("([0-9]+)([a-zA-Z]*)?"); } @@ -63,7 +63,7 @@ public static void main(String[] args){ // TODO: move this to AtomInfo class - public static final String getPdbInfo(Atom a, boolean printResName){ + public static String getPdbInfo(Atom a, boolean printResName){ String aa3 = ""; String chain1 =""; @@ -80,15 +80,15 @@ public static final String getPdbInfo(Atom a, boolean printResName){ } } - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); if ( printResName) { - if ( !aa3.equals("")){ + if (!aa3.isEmpty()){ buf.append("["); buf.append(aa3); buf.append("]"); } } - if ( ! res1.equals("")) { + if (!res1.isEmpty()) { // let's check if there is an insertion code... Matcher matcher = inscodePatter.matcher(res1); @@ -101,7 +101,7 @@ public static final String getPdbInfo(Atom a, boolean printResName){ String residueNumber = matcher.group(1); String insCode = matcher.group(2); buf.append(residueNumber); - if ( insCode != null && ! ( insCode.equals(""))) { + if ( insCode != null && ! (insCode.isEmpty())) { buf.append("^"); buf.append(insCode); } @@ -112,7 +112,7 @@ public static final String getPdbInfo(Atom a, boolean printResName){ - if ( ! chain1.equals("")){ + if (chain1!=null && !chain1.isEmpty()){ buf.append(":"); buf.append(chain1); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/MultipleAlignmentJmol.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/MultipleAlignmentJmol.java index fc7d209312..ac1360b238 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/MultipleAlignmentJmol.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/MultipleAlignmentJmol.java @@ -20,33 +20,8 @@ */ package org.biojava.nbio.structure.align.gui.jmol; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JMenuBar; -import javax.swing.JPanel; -import javax.swing.JTextField; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.gui.MenuCreator; import org.biojava.nbio.structure.align.gui.MultipleAlignmentGUI; import org.biojava.nbio.structure.align.gui.MultipleAlignmentJmolDisplay; @@ -64,6 +39,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ItemEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; + /** * A class that provides a 3D visualization Frame in Jmol for * {@link MultipleAlignment}s. @@ -77,7 +62,7 @@ public class MultipleAlignmentJmol extends AbstractAlignmentJmol { private MultipleAlignment multAln; private List transformedAtoms; private JCheckBox colorByBlocks; - private List selectedStructures; + private final List selectedStructures; private static final String LIGAND_DISPLAY_SCRIPT = "select ligand; wireframe 40; spacefill 120; color CPK;"; @@ -113,7 +98,7 @@ public MultipleAlignmentJmol(MultipleAlignment msa, frame.setJMenuBar(menu); this.multAln = msa; this.transformedAtoms = rotatedAtoms; - this.selectedStructures = new ArrayList(); + this.selectedStructures = new ArrayList<>(); frame.addWindowListener(new WindowAdapter() { @@ -168,23 +153,19 @@ public void windowClosing(WindowEvent e) { vBox.add(modelSelection); JButton show = new JButton("Show Only: "); - show.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - jmolPanel.evalString("save selection;"); - String cmd = getJmolString(multAln, - transformedAtoms, colorPalette, - colorByBlocks.isSelected()); - cmd += "; restrict "; - for (int st = 0; st < multAln.size(); st++) { - if (selectedStructures.get(st).isSelected()) { - cmd += "*/" + (st + 1) + ", "; - } + show.addActionListener(e -> { + jmolPanel.evalString("save selection;"); + String cmd = getJmolString(multAln, + transformedAtoms, colorPalette, + colorByBlocks.isSelected()); + cmd += "; restrict "; + for (int st = 0; st < multAln.size(); st++) { + if (selectedStructures.get(st).isSelected()) { + cmd += "*/" + (st + 1) + ", "; } - cmd += "none;"; - jmolPanel.executeCmd(cmd + " restore selection;"); } + cmd += "none;"; + jmolPanel.executeCmd(cmd + " restore selection;"); }); modelSelection.add(show); @@ -228,29 +209,31 @@ public void actionPerformed(ActionEvent e) { String[] cPalette = { "Spectral", "Set1", "Set2", "Pastel" }; JComboBox palette = new JComboBox<>(cPalette); - palette.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { + palette.addActionListener(e -> { - @SuppressWarnings("unchecked") - JComboBox source = (JComboBox) e.getSource(); - String value = source.getSelectedItem().toString(); - evalString("save selection; select *; color grey; " - + "select ligand; color CPK;"); + @SuppressWarnings("unchecked") + JComboBox source = (JComboBox) e.getSource(); + String value = source.getSelectedItem().toString(); + evalString("save selection; select *; color grey; " + + "select ligand; color CPK;"); - if (value == "Set1") { + switch (value) { + case "Set1": colorPalette = ColorBrewer.Set1; - } else if (value == "Set2") { + break; + case "Set2": colorPalette = ColorBrewer.Set2; - } else if (value == "Spectral") { + break; + case "Spectral": colorPalette = ColorBrewer.Spectral; - } else if (value == "Pastel") { + break; + case "Pastel": colorPalette = ColorBrewer.Pastel1; - } - String script = getJmolString(multAln, transformedAtoms, - colorPalette, colorByBlocks.isSelected()); - evalString(script + "; restore selection; "); + break; } + String script = getJmolString(multAln, transformedAtoms, + colorPalette, colorByBlocks.isSelected()); + evalString(script + "; restore selection; "); }); hBox1.add(Box.createGlue()); @@ -262,45 +245,32 @@ public void actionPerformed(ActionEvent e) { hBox2.setMaximumSize(new Dimension(Short.MAX_VALUE, 30)); JButton resetDisplay = new JButton("Reset Display"); - resetDisplay.addActionListener(new ActionListener() { + resetDisplay.addActionListener(e -> { + logger.info("reset!!"); + jmolPanel.executeCmd("restore STATE state_1"); - @Override - public void actionPerformed(ActionEvent e) { - logger.info("reset!!"); - jmolPanel.executeCmd("restore STATE state_1"); - - } }); hBox2.add(resetDisplay); hBox2.add(Box.createGlue()); JCheckBox toggleSelection = new JCheckBox("Show Selection"); - toggleSelection.addItemListener(new ItemListener() { - - @Override - public void itemStateChanged(ItemEvent e) { - boolean showSelection = (e.getStateChange() == ItemEvent.SELECTED); + toggleSelection.addItemListener(e -> { + boolean showSelection = (e.getStateChange() == ItemEvent.SELECTED); - if (showSelection) { - jmolPanel.executeCmd("set display selected"); - } else - jmolPanel.executeCmd("set display off"); - } + if (showSelection) { + jmolPanel.executeCmd("set display selected"); + } else + jmolPanel.executeCmd("set display off"); }); hBox2.add(toggleSelection); hBox2.add(Box.createGlue()); colorByBlocks = new JCheckBox("Color By Block"); - colorByBlocks.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - evalString("save selection; " - + getJmolString(multAln, transformedAtoms, - colorPalette, colorByBlocks.isSelected()) - + "; restore selection;"); - } - }); + colorByBlocks.addItemListener(e -> evalString("save selection; " + + getJmolString(multAln, transformedAtoms, + colorPalette, colorByBlocks.isSelected()) + + "; restore selection;")); hBox2.add(colorByBlocks); hBox2.add(Box.createGlue()); @@ -343,7 +313,7 @@ public void itemStateChanged(ItemEvent e) { @Override protected void initCoords() { - try { +// try { if (multAln == null) { if (structure != null) setStructure(structure); @@ -354,10 +324,11 @@ protected void initCoords() { } Structure artificial = MultipleAlignmentTools.toMultimodelStructure(multAln, transformedAtoms); setStructure(artificial); - logger.info(artificial.getPDBHeader().getTitle()); - } catch (StructureException e) { - e.printStackTrace(); - } + if (logger.isInfoEnabled()) + logger.info(artificial.getPDBHeader().getTitle()); +// } catch (StructureException e) { +// e.printStackTrace(); +// } } @Override @@ -375,37 +346,45 @@ public void actionPerformed(ActionEvent ae) { return; } try { - if (cmd.equals(MenuCreator.TEXT_ONLY)) { - logger.warn("Option not available for MultipleAlignments"); - - } else if (cmd.equals(MenuCreator.PAIRS_ONLY)) { - String result = MultipleAlignmentWriter - .toAlignedResidues(multAln); - MultipleAlignmentJmolDisplay - .showAlignmentImage(multAln, result); - - } else if (cmd.equals(MenuCreator.ALIGNMENT_PANEL)) { - MultipleAlignmentJmolDisplay.showMultipleAligmentPanel(multAln, - this); - - } else if (cmd.equals(MenuCreator.FATCAT_TEXT)) { - String result = MultipleAlignmentWriter.toFatCat(multAln) - + "\n"; - result += MultipleAlignmentWriter.toTransformMatrices(multAln); - MultipleAlignmentJmolDisplay - .showAlignmentImage(multAln, result); - - } else if (cmd.equals(MenuCreator.PHYLOGENETIC_TREE)) { - - // Kimura, Structural and Fractional Dissimilarity Score - Phylogeny kimura = MultipleAlignmentTools - .getKimuraTree(multAln); - Phylogeny sdm = MultipleAlignmentTools.getHSDMTree(multAln); - // Phylogeny structural = MultipleAlignmentTools - // .getStructuralTree(multAln); - - Archaeopteryx - .createApplication(new Phylogeny[] { kimura, sdm }); + switch (cmd) { + case MenuCreator.TEXT_ONLY: + logger.warn("Option not available for MultipleAlignments"); + + break; + case MenuCreator.PAIRS_ONLY: { + String result = MultipleAlignmentWriter + .toAlignedResidues(multAln); + MultipleAlignmentJmolDisplay + .showAlignmentImage(multAln, result); + + break; + } + case MenuCreator.ALIGNMENT_PANEL: + MultipleAlignmentJmolDisplay.showMultipleAligmentPanel(multAln, + this); + + break; + case MenuCreator.FATCAT_TEXT: { + String result = MultipleAlignmentWriter.toFatCat(multAln) + + "\n"; + result += MultipleAlignmentWriter.toTransformMatrices(multAln); + MultipleAlignmentJmolDisplay + .showAlignmentImage(multAln, result); + + break; + } + case MenuCreator.PHYLOGENETIC_TREE: + + // Kimura, Structural and Fractional Dissimilarity Score + Phylogeny kimura = MultipleAlignmentTools + .getKimuraTree(multAln); + Phylogeny sdm = MultipleAlignmentTools.getHSDMTree(multAln); + // Phylogeny structural = MultipleAlignmentTools + // .getStructuralTree(multAln); + + Archaeopteryx + .createApplication(new Phylogeny[]{kimura, sdm}); + break; } } catch (Exception e) { logger.error("Could not complete display option.", e); @@ -426,13 +405,13 @@ public static String getJmolString(MultipleAlignment multAln, colorPalette, colorByBlocks); Color[] colors = colorPalette.getColorPalette(multAln.size()); - StringBuffer j = new StringBuffer(); + StringBuilder j = new StringBuilder(); j.append(DEFAULT_SCRIPT); // Color the equivalent residues of every structure - StringBuffer sel = new StringBuffer(); + StringBuilder sel = new StringBuilder(); sel.append("select *; color lightgrey; backbone 0.1; "); - List> allPDB = new ArrayList>(); + List> allPDB = new ArrayList<>(); // Get the aligned residues of every structure for (int i = 0; i < multAln.size(); i++) { @@ -449,12 +428,11 @@ public static String getJmolString(MultipleAlignment multAln, pos++; sel.append(res); - sel.append("/" + (i + 1)); + sel.append("/").append(i + 1); } if (pos == 0) sel.append("none"); - sel.append("; backbone 0.3 ; color [" + colors[i].getRed() + "," - + colors[i].getGreen() + "," + colors[i].getBlue() + "]; "); + sel.append("; backbone 0.3 ; color [").append(colors[i].getRed()).append(",").append(colors[i].getGreen()).append(",").append(colors[i].getBlue()).append("]; "); } j.append(sel); @@ -482,8 +460,7 @@ public static String getMultiBlockJmolString(MultipleAlignment multAln, // For every structure color all the blocks with the printBlock method for (int str = 0; str < transformedAtoms.size(); str++) { - jmol.append("select */" + (str + 1) + "; color lightgrey; model " - + (str + 1) + "; "); + jmol.append("select */").append(String.valueOf(str + 1)).append("; color lightgrey; model ").append(String.valueOf(str + 1)).append("; "); int index = 0; for (BlockSet bs : multAln.getBlockSets()) { @@ -508,7 +485,7 @@ private static void printJmolScript4Block(Atom[] atoms, int str, int colorPos, int blockNum) { // Obtain the residues aligned in this block of the structure - List pdb = new ArrayList(); + List pdb = new ArrayList<>(); for (int i = 0; i < alignRes.get(str).size(); i++) { // Handle gaps - only color if it is not null @@ -525,12 +502,11 @@ private static void printJmolScript4Block(Atom[] atoms, if (count > 0) buf.append(","); buf.append(res); - buf.append("/" + (str + 1)); + buf.append("/").append(str + 1); count++; } - buf.append("; backbone 0.3 ; color [" + blockColor.getRed() + "," - + blockColor.getGreen() + "," + blockColor.getBlue() + "]; "); + buf.append("; backbone 0.3 ; color [").append(blockColor.getRed()).append(",").append(blockColor.getGreen()).append(",").append(blockColor.getBlue()).append("]; "); jmol.append(buf); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/MyJmolStatusListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/MyJmolStatusListener.java index f0a5a5864d..00243ec366 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/MyJmolStatusListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/MyJmolStatusListener.java @@ -24,15 +24,14 @@ package org.biojava.nbio.structure.align.gui.jmol; -import java.util.Map; - -import javax.swing.JTextField; - import org.jmol.api.JmolStatusListener; import org.jmol.c.CBK; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.swing.*; +import java.util.Map; + public class MyJmolStatusListener implements JmolStatusListener { private static final Logger logger = LoggerFactory.getLogger(MyJmolStatusListener.class); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/RasmolCommandListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/RasmolCommandListener.java index 6c47f80276..e890e90274 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/RasmolCommandListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/RasmolCommandListener.java @@ -41,16 +41,16 @@ public class RasmolCommandListener implements ActionListener, MouseListener { - JTextField textfield; - JmolPanel jmolPanel; + final JTextField textfield; + final JmolPanel jmolPanel; - List history; + final List history; int historyPosition; public RasmolCommandListener(JmolPanel panel, JTextField field){ textfield = field; jmolPanel = panel; - history = new ArrayList(); + history = new ArrayList<>(); historyPosition = -2; // -2 = history = empty; } @@ -69,7 +69,7 @@ public void actionPerformed(ActionEvent event) { // now comes history part: // no need for history: - if ( cmd.equals("")) return; + if (cmd.isEmpty()) return; // check last command in history // if equivalent, don't add, @@ -95,18 +95,20 @@ public void mouseClicked(MouseEvent e){ textfield.setText(""); textfield.repaint(); } - }; + } @Override - public void mouseExited(MouseEvent e){}; + public void mouseExited(MouseEvent e){} + @Override - public void mouseReleased(MouseEvent e){}; + public void mouseReleased(MouseEvent e){} + @Override - public void mousePressed(MouseEvent e){}; + public void mousePressed(MouseEvent e){} @Override - public void mouseEntered(MouseEvent e){}; + public void mouseEntered(MouseEvent e){} /** takes care of the cursor up/down keys. triggers copying of stored * commands into the current textfield diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/StructureAlignmentJmol.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/StructureAlignmentJmol.java index 1b0ee9a6f8..a24d560901 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/StructureAlignmentJmol.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/gui/jmol/StructureAlignmentJmol.java @@ -23,7 +23,9 @@ */ package org.biojava.nbio.structure.align.gui.jmol; -import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.Atom; +import org.biojava.nbio.structure.PDBHeader; +import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.align.gui.AlignmentGui; import org.biojava.nbio.structure.align.gui.DisplayAFP; import org.biojava.nbio.structure.align.gui.MenuCreator; @@ -40,9 +42,11 @@ import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; - import java.awt.*; -import java.awt.event.*; +import java.awt.event.ActionEvent; +import java.awt.event.ItemEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; @@ -200,14 +204,10 @@ public void windowClosing(WindowEvent e) { JButton resetDisplay = new JButton("Reset Display"); - resetDisplay.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - System.out.println("reset!!"); - jmolPanel.executeCmd("restore STATE state_1"); + resetDisplay.addActionListener(e -> { + System.out.println("reset!!"); + jmolPanel.executeCmd("restore STATE state_1"); - } }); hBox2.add(resetDisplay); @@ -216,21 +216,17 @@ public void actionPerformed(ActionEvent e) { JCheckBox toggleSelection = new JCheckBox("Show Selection"); toggleSelection.addItemListener( - new ItemListener() { - - @Override - public void itemStateChanged(ItemEvent e) { - boolean showSelection = (e.getStateChange() == ItemEvent.SELECTED); - - if (showSelection){ - jmolPanel.executeCmd("set display selected"); - } else { - jmolPanel.executeCmd("set display off"); - } + e -> { + boolean showSelection = (e.getStateChange() == ItemEvent.SELECTED); + if (showSelection){ + jmolPanel.executeCmd("set display selected"); + } else { + jmolPanel.executeCmd("set display off"); } + } - ); + ); @@ -256,13 +252,13 @@ public void itemStateChanged(ItemEvent e) { zoomSlider.setMajorTickSpacing(100); zoomSlider.setPaintTicks(true); - Hashtable labelTable = new Hashtable(); - labelTable.put(new Integer(0),new JLabel("0%")); - labelTable.put(new Integer(100),new JLabel("100%")); - labelTable.put(new Integer(200),new JLabel("200%")); - labelTable.put(new Integer(300),new JLabel("300%")); - labelTable.put(new Integer(400),new JLabel("400%")); - labelTable.put(new Integer(500),new JLabel("500%")); + Hashtable labelTable = new Hashtable<>(); + labelTable.put(0,new JLabel("0%")); + labelTable.put(100,new JLabel("100%")); + labelTable.put(200,new JLabel("200%")); + labelTable.put(300,new JLabel("300%")); + labelTable.put(400,new JLabel("400%")); + labelTable.put(500,new JLabel("500%")); zoomSlider.setLabelTable(labelTable); zoomSlider.setPaintLabels(true); @@ -273,21 +269,17 @@ public void itemStateChanged(ItemEvent e) { // SPIN CHECKBOX JCheckBox toggleSpin = new JCheckBox("Spin"); toggleSpin.addItemListener( - new ItemListener() { - - @Override - public void itemStateChanged(ItemEvent e) { - boolean spinOn = (e.getStateChange() == ItemEvent.SELECTED); - - if (spinOn){ - jmolPanel.executeCmd("spin ON"); - } else { - jmolPanel.executeCmd("spin OFF"); - } + e -> { + boolean spinOn = (e.getStateChange() == ItemEvent.SELECTED); + if (spinOn){ + jmolPanel.executeCmd("spin ON"); + } else { + jmolPanel.executeCmd("spin OFF"); } + } - ); + ); hBox3.add(toggleSpin); @@ -337,7 +329,7 @@ public void itemStateChanged(ItemEvent e) { @Override protected void initCoords() { - try { +// try { if (ca1 == null || ca2 == null) { if (structure != null) setStructure(structure); @@ -354,9 +346,9 @@ protected void initCoords() { header.setTitle(title); artificial.setPDBHeader(header); setStructure(artificial); - } catch (StructureException e) { - e.printStackTrace(); - } +// } catch (StructureException e) { +// e.printStackTrace(); +// } } @Override @@ -370,47 +362,55 @@ public void destroy() { @Override public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); - if (cmd.equals(MenuCreator.TEXT_ONLY)) { - if (afpChain == null) { - System.err.println("Currently not viewing an alignment!"); - return; - } - // Clone the AFPChain to not override the FatCat numbers in alnsymb - AFPChain textAFP = (AFPChain) afpChain.clone(); - String result = AfpChainWriter.toWebSiteDisplay(textAFP, ca1, ca2); + switch (cmd) { + case MenuCreator.TEXT_ONLY: { + if (afpChain == null) { + System.err.println("Currently not viewing an alignment!"); + return; + } + // Clone the AFPChain to not override the FatCat numbers in alnsymb + AFPChain textAFP = (AFPChain) afpChain.clone(); + String result = AfpChainWriter.toWebSiteDisplay(textAFP, ca1, ca2); - DisplayAFP.showAlignmentImage(afpChain, result); + DisplayAFP.showAlignmentImage(afpChain, result); - } else if (cmd.equals(MenuCreator.PAIRS_ONLY)) { - if (afpChain == null) { - System.err.println("Currently not viewing an alignment!"); - return; + break; } - String result = AfpChainWriter.toAlignedPairs(afpChain, ca1, ca2); + case MenuCreator.PAIRS_ONLY: { + if (afpChain == null) { + System.err.println("Currently not viewing an alignment!"); + return; + } + String result = AfpChainWriter.toAlignedPairs(afpChain, ca1, ca2); - DisplayAFP.showAlignmentImage(afpChain, result); + DisplayAFP.showAlignmentImage(afpChain, result); - } else if (cmd.equals(MenuCreator.ALIGNMENT_PANEL)) { - if (afpChain == null) { - System.err.println("Currently not viewing an alignment!"); - return; - } - try { - DisplayAFP.showAlignmentPanel(afpChain, ca1, ca2, this); - } catch (Exception e1) { - e1.printStackTrace(); - return; + break; } + case MenuCreator.ALIGNMENT_PANEL: + if (afpChain == null) { + System.err.println("Currently not viewing an alignment!"); + return; + } + try { + DisplayAFP.showAlignmentPanel(afpChain, ca1, ca2, this); + } catch (Exception e1) { + e1.printStackTrace(); + return; + } - } else if (cmd.equals(MenuCreator.FATCAT_TEXT)) { - if (afpChain == null) { - System.err.println("Currently not viewing an alignment!"); - return; + break; + case MenuCreator.FATCAT_TEXT: { + if (afpChain == null) { + System.err.println("Currently not viewing an alignment!"); + return; + } + String result = afpChain.toFatcat(ca1, ca2); + result += AFPChain.newline; + result += afpChain.toRotMat(); + DisplayAFP.showAlignmentImage(afpChain, result); + break; } - String result = afpChain.toFatcat(ca1, ca2); - result += AFPChain.newline; - result += afpChain.toRotMat(); - DisplayAFP.showAlignmentImage(afpChain, result); } } @@ -420,11 +420,11 @@ public static String getJmolString(AFPChain afpChain, Atom[] ca1, Atom[] ca2) { return getMultiBlockJmolScript(afpChain, ca1, ca2); } - StringBuffer j = new StringBuffer(); + StringBuilder j = new StringBuilder(); j.append(DEFAULT_SCRIPT); // now color the equivalent residues ... - StringBuffer sel = new StringBuffer(); + StringBuilder sel = new StringBuilder(); List pdb1 = DisplayAFP.getPDBresnum(0, afpChain, ca1); sel.append("select "); int pos = 0; @@ -465,7 +465,7 @@ public static String getJmolString(AFPChain afpChain, Atom[] ca1, Atom[] ca2) { // Rasmol // and now select the aligned residues... - StringBuffer buf = new StringBuffer("select "); + StringBuilder buf = new StringBuilder("select "); int count = 0; for (String res : pdb1) { if (count > 0) @@ -559,8 +559,8 @@ private static void printJmolScript4Block(Atom[] ca1, Atom[] ca2, int blockNum, c1 = ColorUtils.getIntermediate(ColorUtils.orange, end1, blockNum, bk); c2 = ColorUtils.getIntermediate(ColorUtils.cyan, end2, blockNum, bk); - List pdb1 = new ArrayList(); - List pdb2 = new ArrayList(); + List pdb1 = new ArrayList<>(); + List pdb2 = new ArrayList<>(); for (int i = 0; i < optLen[bk]; i++) { /// int pos1 = optAln[bk][0][i]; @@ -580,7 +580,7 @@ private static void printJmolScript4Block(Atom[] ca1, Atom[] ca2, int blockNum, count++; } - buf.append("; backbone 0.6 ; color [" + c1.getRed() + "," + c1.getGreen() + "," + c1.getBlue() + "]; select "); + buf.append("; backbone 0.6 ; color [").append(c1.getRed()).append(",").append(c1.getGreen()).append(",").append(c1.getBlue()).append("]; select "); count = 0; for (String res : pdb2) { @@ -593,7 +593,7 @@ private static void printJmolScript4Block(Atom[] ca1, Atom[] ca2, int blockNum, } // buf.append("; set display selected;"); - buf.append("; backbone 0.6 ; color [" + c2.getRed() + "," + c2.getGreen() + "," + c2.getBlue() + "];"); + buf.append("; backbone 0.6 ; color [").append(c2.getRed()).append(",").append(c2.getGreen()).append(",").append(c2.getBlue()).append("];"); // now color this block: jmol.append(buf); @@ -622,7 +622,7 @@ public List getDistanceMatrices() { public void stateChanged(ChangeEvent e) { JSlider source = (JSlider) e.getSource(); if (!source.getValueIsAdjusting()) { - int zoomValue = (int) source.getValue(); + int zoomValue = source.getValue(); jmolPanel.executeCmd("zoom " + zoomValue); } } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/AligUIManager.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/AligUIManager.java index 7767b948fa..a86fd15062 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/AligUIManager.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/AligUIManager.java @@ -25,7 +25,6 @@ package org.biojava.nbio.structure.align.webstart; import javax.swing.*; -import javax.swing.UIManager.LookAndFeelInfo; public class AligUIManager @@ -43,13 +42,13 @@ public static void setLookAndFeel(){ } //System.out.println("Installed Look And Feels:"); - LookAndFeelInfo[] feels = UIManager.getInstalledLookAndFeels(); + //LookAndFeelInfo[] feels = UIManager.getInstalledLookAndFeels(); - if ( feels != null){ + //if ( feels != null){ //for ( LookAndFeelInfo info: feels){ //System.out.println(info.getName() + " " + info.getClassName()); // } - } + //} //System.out.println("Auxiliary Look And Feels:"); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/ConfigXMLHandler.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/ConfigXMLHandler.java index 78d43fe862..b0659c861c 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/ConfigXMLHandler.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/ConfigXMLHandler.java @@ -35,7 +35,7 @@ */ public class ConfigXMLHandler extends DefaultHandler { - UserConfiguration config ; + final UserConfiguration config ; /** * diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/JNLPProxy.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/JNLPProxy.java index 99e8a6eb3e..8b070a17dd 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/JNLPProxy.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/JNLPProxy.java @@ -78,12 +78,12 @@ public static boolean showDocument ( URL url ) try { Method method = basicServiceClass.getMethod ( - "showDocument", new Class [ ] { URL.class } ); + "showDocument", URL.class); Boolean resultBoolean = ( Boolean ) method.invoke ( basicServiceObject, new Object [ ] { url } ); - boolean success = resultBoolean.booleanValue ( ); + boolean success = resultBoolean; if ( ! success ) System.out.println("invocation of method failed!"); return success; @@ -109,10 +109,10 @@ private static Object getBasicServiceObject ( ) = Class.forName ( "javax.jnlp.ServiceManager" ); Method lookupMethod = serviceManagerClass.getMethod ( "lookup", - new Class [ ] { String.class } ); + String.class); return lookupMethod.invoke ( - null, new Object [ ] { "javax.jnlp.BasicService" } ); + null, "javax.jnlp.BasicService"); } catch ( Exception ex ) { diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/WebStartMain.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/WebStartMain.java index 27c0ceb322..eab0bd83c0 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/WebStartMain.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/align/webstart/WebStartMain.java @@ -41,7 +41,6 @@ import org.biojava.nbio.structure.align.util.UserConfiguration; import javax.swing.*; - import java.io.File; public class WebStartMain @@ -73,13 +72,7 @@ public static void main(String[] args){ // we did not get enough arguments, show the general user interface... - javax.swing.SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - - AlignmentGui.getInstance(); - } - }); + javax.swing.SwingUtilities.invokeLater(AlignmentGui::getInstance); return; @@ -88,12 +81,7 @@ public void run() { else if ( args.length < 3){ //String arg0 = args[0]; - javax.swing.SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - AlignmentGui.getInstance(); - } - }); + javax.swing.SwingUtilities.invokeLater(AlignmentGui::getInstance); return; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/BiojavaJmol.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/BiojavaJmol.java index eeffe5b749..d2542e9240 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/BiojavaJmol.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/BiojavaJmol.java @@ -32,7 +32,9 @@ import javax.swing.*; import java.awt.*; -import java.awt.event.*; +import java.awt.event.ItemEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; /** A class that provides a simple GUI for Jmol @@ -51,8 +53,8 @@ public class BiojavaJmol { Structure structure; - JmolPanel jmolPanel; - JFrame frame ; + final JmolPanel jmolPanel; + final JFrame frame ; public static void main(String[] args){ @@ -149,35 +151,27 @@ public void windowClosing(WindowEvent e) { JButton resetDisplay = new JButton("Reset Display"); - resetDisplay.addActionListener(new ActionListener() { + resetDisplay.addActionListener(e -> { + System.out.println("reset!!"); + jmolPanel.executeCmd("restore STATE state_1"); - @Override - public void actionPerformed(ActionEvent e) { - System.out.println("reset!!"); - jmolPanel.executeCmd("restore STATE state_1"); - - } }); hBox2.add(resetDisplay); hBox2.add(Box.createGlue()); JCheckBox toggleSelection = new JCheckBox("Show Selection"); toggleSelection.addItemListener( - new ItemListener() { - - @Override - public void itemStateChanged(ItemEvent e) { - boolean showSelection = (e.getStateChange() == ItemEvent.SELECTED); + e -> { + boolean showSelection = (e.getStateChange() == ItemEvent.SELECTED); - if (showSelection){ - jmolPanel.executeCmd("set display selected"); - } else { - jmolPanel.executeCmd("set display off"); - } + if (showSelection){ + jmolPanel.executeCmd("set display selected"); + } else { + jmolPanel.executeCmd("set display off"); + } - } } - ); + ); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/JMatrixPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/JMatrixPanel.java index 4f2fbd160b..3f6a889ce5 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/JMatrixPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/JMatrixPanel.java @@ -63,7 +63,7 @@ public class JMatrixPanel extends JPanel{ int selectedAlignmentPos; final static BasicStroke stroke = new BasicStroke(2.0f); - StrucAligParameters params; + final StrucAligParameters params; public JMatrixPanel(){ scale = 1; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/JmolViewerImpl.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/JmolViewerImpl.java index e361a156c1..e7763c3269 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/JmolViewerImpl.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/JmolViewerImpl.java @@ -42,7 +42,7 @@ public class JmolViewerImpl implements StructureViewer { public static final String smartAdapter = "org.jmol.adapter.smarter.SmarterJmolAdapter"; Structure structure; JmolPanel jmolPanel; - JFrame frame; + final JFrame frame; public JmolViewerImpl() { @@ -203,10 +203,10 @@ static class JmolPanel extends JPanel { adapterC = Class.forName(adapter); smartAdapterC = Class.forName(smartAdapter); - Method m = viewerC.getMethod("allocateSimpleViewer", new Class[]{Component.class, adapterC}); + Method m = viewerC.getMethod("allocateSimpleViewer", Component.class, adapterC); - Constructor constructor = smartAdapterC.getConstructor(new Class[]{}); - adapterO = constructor.newInstance(new Object[]{}); + Constructor constructor = smartAdapterC.getConstructor(); + adapterO = constructor.newInstance(); //viewerC = JmolSimpleViewer.allocateSimpleViewer(this, adapter); viewerO = m.invoke(viewerC, this, adapterO); @@ -214,20 +214,12 @@ static class JmolPanel extends JPanel { evalString = viewerC.getMethod("evalString", String.class); renderScreenImage = viewerC.getMethod("renderScreenImage", - new Class[]{Graphics.class, Dimension.class, Rectangle.class}); + Graphics.class, Dimension.class, Rectangle.class); - openStringInline = viewerC.getMethod("openStringInline", new Class[]{String.class}); + openStringInline = viewerC.getMethod("openStringInline", String.class); - } catch (InstantiationException ex) { + } catch (InstantiationException | NoSuchMethodException | InvocationTargetException | IllegalArgumentException | IllegalAccessException ex) { logger.error("Exception caught", ex); - } catch (IllegalAccessException ex) { - logger.error("Exception caught", ex); - } catch (IllegalArgumentException ex) { - logger.error("Exception caught", ex); - } catch (InvocationTargetException ex) { - logger.error("Exception caught", ex); - } catch (NoSuchMethodException e) { - logger.error("Exception caught", e); } evalString("set scriptQueue on;"); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/ScaleableMatrixPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/ScaleableMatrixPanel.java index b2c6917559..cc33a5b106 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/ScaleableMatrixPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/ScaleableMatrixPanel.java @@ -63,12 +63,12 @@ public class ScaleableMatrixPanel */ private static final long serialVersionUID = -8082261434322968652L; - protected JMatrixPanel mPanel; - protected JSlider slider; - protected JScrollPane scroll; - protected JComboBox coloring; + protected final JMatrixPanel mPanel; + protected final JSlider slider; + protected final JScrollPane scroll; + protected final JComboBox coloring; - protected Map gradients; + protected final Map gradients; protected static final int SLIDER_STEPS = 8; // Number of minor ticks per unit scaled @@ -198,7 +198,7 @@ public ScaleableMatrixPanel(){ protected static Map createGradients() { - SortedMap gradients = new TreeMap(); + SortedMap gradients = new TreeMap<>(); int i = 0; //prepend number, since sorted alphabetically ColorSpace hsv = HSVColorSpace.getHSVColorSpace(); @@ -379,9 +379,10 @@ protected class GradientRenderer extends JPanel implements ListCellRenderer { private static final long serialVersionUID = -2000575579184232365L; - private int min,max; - JLabel title; - JPanel gradientContainer; + private final int min; + private final int max; + final JLabel title; + final JPanel gradientContainer; public GradientRenderer() { this.setPreferredSize(new Dimension(100,25)); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/Selection.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/Selection.java index 902b172b2f..9247940df6 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/Selection.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/Selection.java @@ -27,8 +27,8 @@ public interface Selection { - public void clear(); - public List getSelection(); - public void setSelection(List selection); + void clear(); + List getSelection(); + void setSelection(List selection); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/SequenceDisplay.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/SequenceDisplay.java index dd4dc97cc4..22f6781502 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/SequenceDisplay.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/SequenceDisplay.java @@ -57,11 +57,11 @@ public class SequenceDisplay extends JPanel implements ChangeListener { Structure structure2; AlternativeAlignment alig; StructurePairAligner structurePairAligner; - SequenceScalePanel panel1; - SequenceScalePanel panel2; + final SequenceScalePanel panel1; + final SequenceScalePanel panel2; - JSlider residueSizeSlider; - JLabel percentageDisplay; + final JSlider residueSizeSlider; + final JLabel percentageDisplay; int[] idx1; int[] idx2; @@ -73,15 +73,15 @@ public class SequenceDisplay extends JPanel implements ChangeListener { //private static final Logger logger = LoggerFactory.getLogger(SequenceDisplay.class); - List apos; + final List apos; float scale; - SequenceMouseListener mouseListener1; - SequenceMouseListener mouseListener2; + final SequenceMouseListener mouseListener1; + final SequenceMouseListener mouseListener2; - JLabel label1; - JLabel label2; + final JLabel label1; + final JLabel label2; public static void main(String[] args){ @@ -232,7 +232,7 @@ public SequenceDisplay(StructurePairAligner structurePairAligner){ this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS)); - apos = new ArrayList(); + apos = new ArrayList<>(); } public void clearListeners(){ @@ -451,9 +451,7 @@ private void updatePercentageDisplay(){ private int getMaxSequenceLength(){ int l1 = panel1.getChain().getAtomGroups(GroupType.AMINOACID).size(); int l2 = panel2.getChain().getAtomGroups(GroupType.AMINOACID).size(); - if ( l1 > l2) - return l1; - else return l2; + return Math.max(l1, l2); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/StructureViewer.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/StructureViewer.java index 43f608ef32..62d9369236 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/StructureViewer.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/StructureViewer.java @@ -26,35 +26,35 @@ public interface StructureViewer { - public void setStructure(Structure structure); - public void repaint(); - public void setSelection(Selection selection); - public Selection getSelection(); + void setStructure(Structure structure); + void repaint(); + void setSelection(Selection selection); + Selection getSelection(); /** Apply this color to the current Selection * * @param red */ - public void setColor(Color red); - public Color getColor(); + void setColor(Color red); + Color getColor(); /** Apply this style to the current selection * * @param wireframe renderstyle */ - public void setStyle(RenderStyle wireframe); + void setStyle(RenderStyle wireframe); /** Clear the current display * * */ - public void clear(); + void clear(); /** Set the Zoom level * * @param i */ - public void setZoom(int i); + void setZoom(int i); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/WrapLayout.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/WrapLayout.java index 7694632a9b..73ee69513a 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/WrapLayout.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/WrapLayout.java @@ -20,9 +20,8 @@ */ package org.biojava.nbio.structure.gui; +import javax.swing.*; import java.awt.*; -import javax.swing.JScrollPane; -import javax.swing.SwingUtilities; /** * FlowLayout subclass that fully supports wrapping of components. diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/events/AlignmentPositionListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/events/AlignmentPositionListener.java index 61ca8c5fd9..d955b67f3c 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/events/AlignmentPositionListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/events/AlignmentPositionListener.java @@ -25,11 +25,11 @@ public interface AlignmentPositionListener { - public void mouseOverPosition(AlignedPosition p); - public void positionSelected(AlignedPosition p); - public void toggleSelection(AlignedPosition p); - public void rangeSelected(AlignedPosition start , AlignedPosition end); - public void selectionLocked(); - public void selectionUnlocked(); + void mouseOverPosition(AlignedPosition p); + void positionSelected(AlignedPosition p); + void toggleSelection(AlignedPosition p); + void rangeSelected(AlignedPosition start, AlignedPosition end); + void selectionLocked(); + void selectionUnlocked(); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/events/JmolAlignedPositionListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/events/JmolAlignedPositionListener.java index 14937adea2..97f2cc3fc1 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/events/JmolAlignedPositionListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/events/JmolAlignedPositionListener.java @@ -33,10 +33,10 @@ public class JmolAlignedPositionListener implements AlignmentPositionListener{ - BiojavaJmol parent; + final BiojavaJmol parent; Atom[] ca1; Atom[] ca2; - StructurePairAligner structurePairAligner; + final StructurePairAligner structurePairAligner; public JmolAlignedPositionListener(BiojavaJmol parent, StructurePairAligner alig){ this.parent = parent; @@ -71,8 +71,8 @@ public void mouseOverPosition(AlignedPosition p) { return; } - String pdbpos1 =""; - String pdbpos2 = ""; + String pdbpos1; + String pdbpos2; if ( p1 >-1) { Atom a = ca1[p1]; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/AlternativeAlignmentFrame.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/AlternativeAlignmentFrame.java index 8dc672ed36..462c715bcf 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/AlternativeAlignmentFrame.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/AlternativeAlignmentFrame.java @@ -53,18 +53,18 @@ public class AlternativeAlignmentFrame extends JFrame{ - private static final long serialVersionUID=0l; + private static final long serialVersionUID= 0L; private static final Logger logger = LoggerFactory.getLogger(AlternativeAlignmentFrame.class); - private static String[] columnNames = new String[]{"#","eqr","score", "rms", "gaps","cluster", "show distance matrix","show alignment"}; + private static final String[] columnNames = new String[]{"#","eqr","score", "rms", "gaps","cluster", "show distance matrix","show alignment"}; AlternativeAlignment[] aligs; - JPanel panel; + final JPanel panel; - Structure structure1; - Structure structure2; + final Structure structure1; + final Structure structure2; StructurePairAligner structurePairAligner; public AlternativeAlignmentFrame(Structure s1, Structure s2) { @@ -126,12 +126,12 @@ private Object[][] getDataFromAligs(AlternativeAlignment[] aligs){ for ( int i=0;i< aligs.length;i++){ AlternativeAlignment alig = aligs[i]; - data[i][0] = new Integer(i+1); - data[i][1] = new Integer(alig.getEqr()); - data[i][2] = new Double(alig.getScore()); - data[i][3] = new Double(alig.getRmsd()); - data[i][4] = new Integer(alig.getGaps()); - data[i][5] = new Integer(alig.getCluster()); + data[i][0] = i + 1; + data[i][1] = alig.getEqr(); + data[i][2] = (double) alig.getScore(); + data[i][3] = alig.getRmsd(); + data[i][4] = alig.getGaps(); + data[i][5] = alig.getCluster(); JButton maxb = new JButton("Distance Matrix"); maxb.addMouseListener(new MatrixMouseListener(this,i)); @@ -322,8 +322,8 @@ private String[] createRasmolScripts(AlternativeAlignment alig){ } class MyButtonMouseListener implements MouseListener{ - AlternativeAlignmentFrame parent; - int pos; + final AlternativeAlignmentFrame parent; + final int pos; public MyButtonMouseListener(AlternativeAlignmentFrame parent, int position){ this.parent = parent; @@ -362,8 +362,8 @@ public void mouseExited(MouseEvent arg0) { } class MatrixMouseListener implements MouseListener{ - AlternativeAlignmentFrame parent; - int pos; + final AlternativeAlignmentFrame parent; + final int pos; public MatrixMouseListener( AlternativeAlignmentFrame parent, int position){ this.parent = parent; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JButtonTableCellRenderer.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JButtonTableCellRenderer.java index 586220728e..7466e76b89 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JButtonTableCellRenderer.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JButtonTableCellRenderer.java @@ -27,7 +27,7 @@ import java.awt.*; class JButtonTableCellRenderer implements TableCellRenderer { - private TableCellRenderer __defaultRenderer; + private final TableCellRenderer __defaultRenderer; public JButtonTableCellRenderer(TableCellRenderer renderer) { __defaultRenderer = renderer; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JTableDataButtonModel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JTableDataButtonModel.java index 561d130bbf..af19bbaf42 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JTableDataButtonModel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JTableDataButtonModel.java @@ -26,10 +26,10 @@ class JTableDataButtonModel extends AbstractTableModel { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; - Object[][] __rows; - String[] __columns; + final Object[][] __rows; + final String[] __columns; public JTableDataButtonModel(Object[][] rows, String[] columns){ __rows = rows; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JTableMouseButtonListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JTableMouseButtonListener.java index 5b8269a109..bb3bde4a7f 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JTableMouseButtonListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/JTableMouseButtonListener.java @@ -30,7 +30,7 @@ class JTableMouseButtonListener implements MouseListener { - private JTable __table; + private final JTable __table; private void __forwardEventToButton(MouseEvent e) { TableColumnModel columnModel = __table.getColumnModel(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/MenuCreator.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/MenuCreator.java index ef945c5263..668dbc7503 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/MenuCreator.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/MenuCreator.java @@ -28,8 +28,6 @@ import javax.swing.*; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.File; @@ -56,32 +54,29 @@ public static JMenuBar initMenu(){ JMenuItem openI = new JMenuItem("Open"); openI.setMnemonic(KeyEvent.VK_O); - openI.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent e) { - String cmd = e.getActionCommand(); - if ( cmd.equals("Open")){ - final JFileChooser fc = new JFileChooser(); + openI.addActionListener(e -> { + String cmd = e.getActionCommand(); + if ( cmd.equals("Open")){ + final JFileChooser fc = new JFileChooser(); // In response to a button click: - int returnVal = fc.showOpenDialog(null); - if ( returnVal == JFileChooser.APPROVE_OPTION) { - File file = fc.getSelectedFile(); - - PDBFileReader reader = new PDBFileReader(); - try { - Structure s = reader.getStructure(file); - BiojavaJmol jmol = new BiojavaJmol(); - jmol.setStructure(s); - jmol.evalString("select * ; color chain;"); - jmol.evalString("select *; spacefill off; wireframe off; backbone 0.4; "); - - } catch (Exception ex){ - ex.printStackTrace(); - } + int returnVal = fc.showOpenDialog(null); + if ( returnVal == JFileChooser.APPROVE_OPTION) { + File file1 = fc.getSelectedFile(); + + PDBFileReader reader = new PDBFileReader(); + try { + Structure s = reader.getStructure(file1); + BiojavaJmol jmol = new BiojavaJmol(); + jmol.setStructure(s); + jmol.evalString("select * ; color chain;"); + jmol.evalString("select *; spacefill off; wireframe off; backbone 0.4; "); + + } catch (Exception ex){ + ex.printStackTrace(); + } - } } } }); @@ -89,15 +84,11 @@ public void actionPerformed(ActionEvent e) { JMenuItem exitI = new JMenuItem("Exit"); exitI.setMnemonic(KeyEvent.VK_X); - exitI.addActionListener(new ActionListener(){ - - @Override - public void actionPerformed(ActionEvent e) { - String cmd = e.getActionCommand(); + exitI.addActionListener(e -> { + String cmd = e.getActionCommand(); - if ( cmd.equals("Exit")){ - System.exit(0); - } + if ( cmd.equals("Exit")){ + System.exit(0); } }); @@ -106,14 +97,11 @@ public void actionPerformed(ActionEvent e) { JMenu align = new JMenu("Align"); JMenuItem pairI = new JMenuItem("2 protein structures"); - pairI.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - String cmd = e.getActionCommand(); + pairI.addActionListener(e -> { + String cmd = e.getActionCommand(); - if ( cmd.equals("2 protein structures")){ - MenuCreator.showPairDialog(); - } + if ( cmd.equals("2 protein structures")){ + MenuCreator.showPairDialog(); } }); @@ -123,15 +111,11 @@ public void actionPerformed(ActionEvent e) { JMenu about = new JMenu("About"); JMenuItem aboutI = new JMenuItem("PDBview"); - aboutI.addActionListener(new ActionListener(){ - - @Override - public void actionPerformed(ActionEvent e) { - String cmd = e.getActionCommand(); + aboutI.addActionListener(e -> { + String cmd = e.getActionCommand(); - if ( cmd.equals("PDBview")){ - MenuCreator.showAboutDialog(); - } + if ( cmd.equals("PDBview")){ + MenuCreator.showAboutDialog(); } }); @@ -177,17 +161,14 @@ private static void showAboutDialog(){ JButton close = new JButton("Close"); - close.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent event) { - Object source = event.getSource(); + close.addActionListener(event -> { + Object source = event.getSource(); - JButton but = (JButton)source; - Container parent = but.getParent().getParent().getParent().getParent().getParent().getParent() ; + JButton but = (JButton)source; + Container parent = but.getParent().getParent().getParent().getParent().getParent().getParent() ; - JDialog dia = (JDialog) parent; - dia.dispose(); - } + JDialog dia = (JDialog) parent; + dia.dispose(); }); Box hBoxb = Box.createHorizontalBox(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBDirPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBDirPanel.java index 7db9f67424..67663657ee 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBDirPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBDirPanel.java @@ -52,12 +52,12 @@ public class PDBDirPanel */ private static final long serialVersionUID = -5682120627824627408L; - boolean debug = true; - JTextField pdbDir; - JTextField f1; - JTextField f2; - JTextField c1; - JTextField c2; + final boolean debug = true; + final JTextField pdbDir; + final JTextField f1; + final JTextField f2; + final JTextField c1; + final JTextField c2; private static final Logger logger = LoggerFactory.getLogger(StructurePairSelector.class); @@ -220,12 +220,12 @@ private JPanel getPDBFilePanel(int pos ,JTextField f, JTextField c){ class ChooseDirAction extends AbstractAction{ - JTextField textField; + final JTextField textField; public ChooseDirAction (JTextField textField){ super("Choose"); this.textField = textField; } - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBServerPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBServerPanel.java index 22d0157021..6860f8e5c2 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBServerPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBServerPanel.java @@ -50,12 +50,12 @@ public class PDBServerPanel */ private static final long serialVersionUID = -5682120627824627408L; - boolean debug = true; + final boolean debug = true; JTextField pdbDir; - JTextField f1; - JTextField f2; - JTextField c1; - JTextField c2; + final JTextField f1; + final JTextField f2; + final JTextField c1; + final JTextField c2; private static final Logger logger = LoggerFactory.getLogger(PDBServerPanel.class); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBUploadPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBUploadPanel.java index 2c542f0797..35f12703d3 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBUploadPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/PDBUploadPanel.java @@ -59,12 +59,12 @@ public class PDBUploadPanel - private JComboBox fileType ; + private final JComboBox fileType ; - JTextField filePath1; - JTextField filePath2; - JTextField chain1; - JTextField chain2; + final JTextField filePath1; + final JTextField filePath2; + final JTextField chain1; + final JTextField chain2; public static JComboBox getFileFormatSelect(){ JComboBox fileType = new JComboBox(); @@ -129,7 +129,7 @@ public Structure getStructure2() throws StructureException{ private Structure getStructure(JTextField filePath,JTextField chainId) throws StructureException{ //PDBFileReader reader = new PDBFileReader(); - StructureIOFile reader = null; + StructureIOFile reader; String fileFormat = (String)fileType.getSelectedItem(); if ( fileFormat.equals(UserConfiguration.PDB_FORMAT)){ reader = new PDBFileReader(); @@ -141,7 +141,7 @@ private Structure getStructure(JTextField filePath,JTextField chainId) throws St String path = filePath.getText(); File f = new File(path); - Structure s = null; + Structure s; try { s = reader.getStructure(f); } catch (IOException e){ @@ -157,7 +157,7 @@ private Structure getStructure(JTextField filePath,JTextField chainId) throws St URL u ; - if ( chainId.getText() == null || chainId.getText().equals("")){ + if ( chainId.getText() == null || chainId.getText().isEmpty()){ u = f.toURI().toURL(); } else { @@ -201,12 +201,12 @@ private JPanel getLocalFilePanel(int pos ,JTextField filePath, JTextField chain class ChooseAction extends AbstractAction{ - JTextField textField; + final JTextField textField; public ChooseAction (JTextField textField){ super("Choose"); this.textField = textField; } - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/ScopInstallationInstance.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/ScopInstallationInstance.java index f76fd5ff67..566c0ac33d 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/ScopInstallationInstance.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/ScopInstallationInstance.java @@ -33,8 +33,8 @@ public class ScopInstallationInstance { - static ScopInstallationInstance me = new ScopInstallationInstance(); - ScopDatabase install; + static final ScopInstallationInstance me = new ScopInstallationInstance(); + final ScopDatabase install; private ScopInstallationInstance(){ UserConfiguration config = WebStartMain.getWebStartConfig(); String cacheLocation = config.getPdbFilePath(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/ScopSelectPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/ScopSelectPanel.java index a6571483a6..2ce7594388 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/ScopSelectPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/ScopSelectPanel.java @@ -25,7 +25,6 @@ package org.biojava.nbio.structure.gui.util; import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.gui.autosuggest.AutoSuggestProvider; import org.biojava.nbio.structure.align.gui.autosuggest.JAutoSuggest; import org.biojava.nbio.structure.align.gui.autosuggest.SCOPAutoSuggestProvider; @@ -47,8 +46,8 @@ public class ScopSelectPanel * */ private static final long serialVersionUID = 757947454156959178L; - JAutoSuggest dom1; - JAutoSuggest dom2; + final JAutoSuggest dom1; + final JAutoSuggest dom2; //private static final Logger logger = LoggerFactory.getLogger(ScopSelectPanel.class); @@ -113,22 +112,20 @@ private Box getDomainPanel(int pos ,JTextField f){ } @Override - public Structure getStructure1() throws StructureException - { + public Structure getStructure1() { String scop1 = dom1.getText(); return getStructure(scop1); } @Override - public Structure getStructure2() throws StructureException - { + public Structure getStructure2() { return getStructure(dom2.getText()); } - private Structure getStructure(String domainID) throws StructureException{ + private Structure getStructure(String domainID) { //PDBFileReader reader = new PDBFileReader(); - if ( domainID == null || domainID.equals("")) + if ( domainID == null || domainID.isEmpty()) return null; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SelectMultiplePanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SelectMultiplePanel.java index ae8d859951..254d26369e 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SelectMultiplePanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SelectMultiplePanel.java @@ -23,24 +23,18 @@ */ package org.biojava.nbio.structure.gui.util; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.Box; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; - import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIdentifier; import org.biojava.nbio.structure.align.client.StructureName; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.align.util.UserConfiguration; import org.biojava.nbio.structure.align.webstart.WebStartMain; +import javax.swing.*; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; + /** * A Text Panel that allows the user to specify multiple structure * identifiers, space separated. @@ -53,7 +47,7 @@ public class SelectMultiplePanel extends JPanel { private static final long serialVersionUID = 757947454156959178L; - JTextField input; + final JTextField input; public SelectMultiplePanel(){ this(true); @@ -88,9 +82,9 @@ private Box getDomainPanel(JTextField f){ return hBox; } - public List getStructures() throws StructureException { + public List getStructures() { - List structures = new ArrayList(); + List structures = new ArrayList<>(); for (StructureIdentifier name:getNames()){ structures.add(getStructure(name)); @@ -100,7 +94,7 @@ public List getStructures() throws StructureException { public List getNames() { - List names = new ArrayList(); + List names = new ArrayList<>(); String raw = input.getText().trim(); String[] split = raw.split(" "); @@ -111,7 +105,7 @@ public List getNames() { return names; } - private Structure getStructure(StructureIdentifier name) throws StructureException{ + private Structure getStructure(StructureIdentifier name) { UserConfiguration config = WebStartMain.getWebStartConfig(); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SequenceMouseListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SequenceMouseListener.java index e10331b9d5..09b3ed03fd 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SequenceMouseListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SequenceMouseListener.java @@ -50,7 +50,7 @@ public class SequenceMouseListener implements { - boolean selectionLocked; + final boolean selectionLocked; boolean dragging; int selectionStart; @@ -61,13 +61,13 @@ public class SequenceMouseListener implements int chainLength; - CoordManager coordManager; + final CoordManager coordManager; //private static final Logger logger = LoggerFactory.getLogger(SequenceMouseListener.class); - SequenceDisplay parent; + final SequenceDisplay parent; - List alignmentPositionListeners; + final List alignmentPositionListeners; public SequenceMouseListener(SequenceDisplay parent) { super(); @@ -86,7 +86,7 @@ public SequenceMouseListener(SequenceDisplay parent) { coordManager = new CoordManager(); - alignmentPositionListeners = new ArrayList(); + alignmentPositionListeners = new ArrayList<>(); //renderer.getLayeredPane().addMouseListener(popupFrame); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SequenceScalePanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SequenceScalePanel.java index bc29425c07..c969683c1c 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SequenceScalePanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/SequenceScalePanel.java @@ -39,7 +39,7 @@ public class SequenceScalePanel extends JPanel{ - static final long serialVersionUID = 7893248902423l; + static final long serialVersionUID = 7893248902423L; //private static final Logger logger = LoggerFactory.getLogger(SequenceScalePanel.class); @@ -105,7 +105,7 @@ public SequenceScalePanel(int position) { setPrefSize(); coordManager = new CoordManager(); - apos = new ArrayList(); + apos = new ArrayList<>(); } @@ -219,7 +219,7 @@ public void paintComponent(Graphics g){ setPaintDefaults(g2D); - int y = 1; + int y; // draw the scale @@ -378,7 +378,7 @@ protected void drawIdx(Graphics2D g2D, int y){ if ( scale <= 3) lineH = 8; - int i = startpos; + int i; // display the actual sequence!; @@ -446,7 +446,7 @@ protected int drawSequence(Graphics2D g2D, int y){ //g2D.setColor(SCALE_COLOR); - int i = startpos; + int i; // display the actual sequence!; for ( int gap = startpos ; gap < apos.size() ;gap++){ diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/StructurePairSelector.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/StructurePairSelector.java index 1ced9fe59f..74a9352861 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/StructurePairSelector.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/StructurePairSelector.java @@ -21,11 +21,11 @@ */ package org.biojava.nbio.structure.gui.util; -import java.io.IOException; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; +import java.io.IOException; + /** To be implemented by JPanels that are part of the GUI to trigger structure aligmnents. * * @@ -35,7 +35,7 @@ */ public interface StructurePairSelector { - public Structure getStructure1() throws StructureException, IOException; - public Structure getStructure2() throws StructureException, IOException; + Structure getStructure1() throws StructureException, IOException; + Structure getStructure2() throws StructureException, IOException; } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ColorInterpolator.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ColorInterpolator.java index 13aedf3b8c..33f04c1240 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ColorInterpolator.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ColorInterpolator.java @@ -36,5 +36,5 @@ public interface ColorInterpolator { * @return The color between a and b * @throws IllegalArgumentException if mixing is not between 0 and 1 */ - public Color interpolate(Color a, Color b, float mixing); + Color interpolate(Color a, Color b, float mixing); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ColorUtils.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ColorUtils.java index 0d253a054d..cfbedfdb17 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ColorUtils.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ColorUtils.java @@ -29,9 +29,9 @@ public class ColorUtils { - public static Color orange = Color.decode("#FFA500"); - public static Color cyan = Color.decode("#00FFFF"); - public static Color gold = Color.decode("#FFD700"); + public static final Color orange = Color.decode("#FFA500"); + public static final Color cyan = Color.decode("#00FFFF"); + public static final Color gold = Color.decode("#FFD700"); static final Color c1 = Color.decode("#228B22"); // green diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ContinuousColorMapper.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ContinuousColorMapper.java index 8ee0c4e2c9..e5442627f0 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ContinuousColorMapper.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ContinuousColorMapper.java @@ -37,5 +37,5 @@ public interface ContinuousColorMapper { * @param value The real to be mapped * @return The color corresponding to value */ - public Color getColor(double value); + Color getColor(double value); } diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ContinuousColorMapperTransform.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ContinuousColorMapperTransform.java index 5cd010b356..d8a884cc24 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ContinuousColorMapperTransform.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/ContinuousColorMapperTransform.java @@ -36,7 +36,7 @@ */ public abstract class ContinuousColorMapperTransform implements ContinuousColorMapper { - protected ContinuousColorMapper mapper; + protected final ContinuousColorMapper mapper; /** * Creates a transform. diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/DefaultMatrixMapper.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/DefaultMatrixMapper.java index 3b9975d0c0..7b246173da 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/DefaultMatrixMapper.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/DefaultMatrixMapper.java @@ -48,7 +48,7 @@ public DefaultMatrixMapper(double scale, float saturation ) { */ @Override public Color getColor(double value) { - float hue = 1.0f; + float hue; hue = (float)(1-(value/scalevalue)); if (hue < 0) hue = 0; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/GradientMapper.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/GradientMapper.java index 4678d68707..f28c74d053 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/GradientMapper.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/GradientMapper.java @@ -51,7 +51,7 @@ public class GradientMapper implements ContinuousColorMapper, Map public static final int RAINBOW_GRADIENT = 4; public static final int RAINBOW_INTENSITY_GRADIENT = 5; - private NavigableMap mapping; + private final NavigableMap mapping; private ColorInterpolator interpolator; public GradientMapper() { @@ -61,7 +61,7 @@ public GradientMapper(Color negInf, Color posInf) { this(negInf,posInf,ColorSpace.getInstance(ColorSpace.CS_sRGB)); } public GradientMapper(Color negInf, Color posInf, ColorSpace cspace) { - mapping = new TreeMap(); + mapping = new TreeMap<>(); mapping.put(Double.NEGATIVE_INFINITY, negInf); mapping.put(Double.POSITIVE_INFINITY, posInf); interpolator = new LinearColorInterpolator(cspace); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/GradientPanel.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/GradientPanel.java index 68690b58cb..7f88f732ca 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/GradientPanel.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/GradientPanel.java @@ -26,8 +26,9 @@ public class GradientPanel extends JPanel { private static final long serialVersionUID = -6387922432121206731L; - private ContinuousColorMapper mapper; - private double min, max; + private final ContinuousColorMapper mapper; + private final double min; + private final double max; public GradientPanel(ContinuousColorMapper mapper, double min, double max) { diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/LinearColorInterpolator.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/LinearColorInterpolator.java index 9522ec7a15..c98b5812e3 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/LinearColorInterpolator.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/gui/util/color/LinearColorInterpolator.java @@ -23,6 +23,7 @@ import java.awt.*; import java.awt.color.ColorSpace; +import java.util.Arrays; /** * @author Spencer Bliven @@ -156,8 +157,7 @@ public void setColorSpace(ColorSpace colorSpace, InterpolationDirection[] dir) { public void setColorSpace(ColorSpace colorSpace) { InterpolationDirection[] dir = new InterpolationDirection[colorSpace.getNumComponents()]; - for(int i=0;i> cyclicForm = axes.getRepeatsCyclicForm(a); - List repAtoms = new ArrayList(); + List repAtoms = new ArrayList<>(); for(List cycle : cyclicForm) { for(Integer repeat : cycle) { repAtoms.addAll(Arrays.asList(repeats.get(repeat))); @@ -247,7 +244,7 @@ public static String printSymmetryAxes(CeSymmResult symm,boolean allAxes) } script += rot.getJmolScript( - repAtoms.toArray(new Atom[repAtoms.size()]), id); + repAtoms.toArray(Atom.EmptyAtomArray), id); id++; } @@ -299,7 +296,7 @@ public static String printSymmetryGroup(CeSymmResult symm) */ public static String getSymmTitle(CeSymmResult result) { - StringBuffer buff = new StringBuffer(); + StringBuilder buff = new StringBuilder(); // Add algorithm name and version buff.append(result.getMultipleAlignment().getEnsemble() diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/gui/SymmetryGui.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/gui/SymmetryGui.java index 7568141b55..df8b5d4323 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/gui/SymmetryGui.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/gui/SymmetryGui.java @@ -20,22 +20,6 @@ */ package org.biojava.nbio.structure.symmetry.gui; -import java.awt.Dimension; -import java.awt.event.ActionEvent; -import java.io.IOException; - -import javax.swing.AbstractAction; -import javax.swing.Action; -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JMenuBar; -import javax.swing.JOptionPane; -import javax.swing.JProgressBar; -import javax.swing.JTabbedPane; - import org.biojava.nbio.structure.PassthroughIdentifier; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; @@ -53,6 +37,11 @@ import org.biojava.nbio.structure.symmetry.internal.CESymmParameters; import org.biojava.nbio.structure.symmetry.internal.CeSymm; +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.io.IOException; + /** * A JFrame that allows to trigger a symmetry analysis, either from files * in a directory or after manual upload @@ -65,19 +54,19 @@ */ public class SymmetryGui extends JFrame { - private final static long serialVersionUID = 0l; + private final static long serialVersionUID = 0L; - private CESymmParameters params = new CESymmParameters(); + private final CESymmParameters params = new CESymmParameters(); private JButton abortB; - private SelectPDBPanel tab1 ; - private PDBUploadPanel tab2; - private ScopSelectPanel tab3; + private final SelectPDBPanel tab1 ; + private final PDBUploadPanel tab2; + private final ScopSelectPanel tab3; private Thread thread; private AlignmentCalculationRunnable alicalc; - private JTabbedPane masterPane; - private JTabbedPane tabPane; + private final JTabbedPane masterPane; + private final JTabbedPane tabPane; private JProgressBar progress; public static void main(String[] args){ @@ -159,7 +148,7 @@ private Box setupAlgorithm() { algorithmList.setSelectedIndex(0); Action paramAction = new AbstractAction("Parameters") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -188,7 +177,7 @@ private Box initButtons(){ progress.setVisible(false); Action action1 = new AbstractAction("Analyze") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -206,7 +195,7 @@ public void actionPerformed(ActionEvent evt) { JButton submitB = new JButton(action1); Action action3 = new AbstractAction("Abort") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -220,7 +209,7 @@ public void actionPerformed(ActionEvent evt) { abortB.setEnabled(false); Action action2 = new AbstractAction("Exit") { - public static final long serialVersionUID = 0l; + public static final long serialVersionUID = 0L; // This method is called when the button is pressed @Override public void actionPerformed(ActionEvent evt) { @@ -302,10 +291,7 @@ private void calcAlignment() { progress.setIndeterminate(true); ProgressThreadDrawer drawer = new ProgressThreadDrawer(progress); drawer.start(); - } catch (StructureException e){ - JOptionPane.showMessageDialog(null, - "Could not align structures. Exception: " + e.getMessage()); - } catch (IOException e) { + } catch (StructureException | IOException e){ JOptionPane.showMessageDialog(null, "Could not align structures. Exception: " + e.getMessage()); } @@ -335,7 +321,7 @@ public CESymmParameters getParameters() { class ProgressThreadDrawer extends Thread { JProgressBar progress; - static int interval = 300; + static final int interval = 300; public ProgressThreadDrawer(JProgressBar progress) { this.progress = progress; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/gui/SymmetryListener.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/gui/SymmetryListener.java index 1fdb882f7c..f14c6c69b1 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/gui/SymmetryListener.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/gui/SymmetryListener.java @@ -20,9 +20,6 @@ */ package org.biojava.nbio.structure.symmetry.gui; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.gui.StructureAlignmentDisplay; @@ -33,6 +30,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + /** * Action Listener for the symmetry menu. Trigger various internal symmetry * specific analysis. @@ -43,8 +43,8 @@ */ public class SymmetryListener implements ActionListener { - private MultipleAlignmentJmol jmol; - private CeSymmResult symm; + private final MultipleAlignmentJmol jmol; + private final CeSymmResult symm; private static final Logger logger = LoggerFactory .getLogger(SymmetryListener.class); @@ -64,34 +64,41 @@ public void actionPerformed(ActionEvent ae) { logger.error("Currently not displaying a symmetry!"); try { - if (cmd.equals("Repeats Superposition")) { - MultipleAlignmentJmol j = SymmetryDisplay.displayRepeats(symm); - String s = SymmetryDisplay.printSymmetryAxes(symm, false); - j.evalString(s); - j.evalString("save STATE state_1"); - + switch (cmd) { + case "Repeats Superposition": { + MultipleAlignmentJmol j = SymmetryDisplay.displayRepeats(symm); + String s = SymmetryDisplay.printSymmetryAxes(symm, false); + j.evalString(s); + j.evalString("save STATE state_1"); - } else if (cmd.equals("Multiple Structure Alignment")) { - MultipleAlignmentJmol j = SymmetryDisplay.displayFull(symm); - String s = SymmetryDisplay.printSymmetryAxes(symm); - j.evalString(s); - j.evalString("save STATE state_1"); - } else if (cmd.equals("Optimal Self Alignment")) { - Atom[] cloned = StructureTools.cloneAtomArray(symm.getAtoms()); - AbstractAlignmentJmol jmol = StructureAlignmentDisplay.display( - symm.getSelfAlignment(), symm.getAtoms(), cloned); - RotationAxis axis = new RotationAxis(symm.getSelfAlignment()); - jmol.evalString(axis.getJmolScript(symm.getAtoms())); - jmol.setTitle(SymmetryDisplay.getSymmTitle(symm)); + break; + } + case "Multiple Structure Alignment": { + MultipleAlignmentJmol j = SymmetryDisplay.displayFull(symm); + String s = SymmetryDisplay.printSymmetryAxes(symm); + j.evalString(s); + j.evalString("save STATE state_1"); - } else if (cmd.equals("Show Symmetry Group")) { - String script = SymmetryDisplay.printSymmetryGroup(symm); - jmol.evalString(script); + break; + } + case "Optimal Self Alignment": { + Atom[] cloned = StructureTools.cloneAtomArray(symm.getAtoms()); + AbstractAlignmentJmol jmol = StructureAlignmentDisplay.display( + symm.getSelfAlignment(), symm.getAtoms(), cloned); + RotationAxis axis = new RotationAxis(symm.getSelfAlignment()); + jmol.evalString(axis.getJmolScript(symm.getAtoms())); + jmol.setTitle(SymmetryDisplay.getSymmTitle(symm)); - } else if (cmd.equals("Show Symmetry Axes")) { - String s = SymmetryDisplay.printSymmetryAxes(symm); - jmol.evalString(s); + break; + } + case "Show Symmetry Group": + jmol.evalString(SymmetryDisplay.printSymmetryGroup(symm)); + break; + case "Show Symmetry Axes": { + jmol.evalString(SymmetryDisplay.printSymmetryAxes(symm)); + break; + } } } catch (Exception e) { diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGenerator.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGenerator.java index dd2401b2c8..1aa07aa747 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGenerator.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGenerator.java @@ -27,7 +27,6 @@ import javax.vecmath.Color4f; import javax.vecmath.Matrix4d; import javax.vecmath.Tuple3d; - import java.util.List; import java.util.Map; import java.util.Map.Entry; diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGeneratorH.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGeneratorH.java index 428635c78b..7b45bfe811 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGeneratorH.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGeneratorH.java @@ -28,10 +28,9 @@ import org.jcolorbrewer.ColorBrewer; import javax.vecmath.*; - import java.awt.*; -import java.util.*; import java.util.List; +import java.util.*; /** @@ -39,10 +38,10 @@ * */ public class JmolSymmetryScriptGeneratorH extends JmolSymmetryScriptGenerator { - private static double AXIS_SCALE_FACTOR = 1.2; - private static double SIDE_CHAIN_EXTENSION = 6.0; - private HelixAxisAligner helixAxisAligner = null; - private String name = ""; + private static final double AXIS_SCALE_FACTOR = 1.2; + private static final double SIDE_CHAIN_EXTENSION = 6.0; + private final HelixAxisAligner helixAxisAligner; + private final String name; private String defaultColoring = ""; private boolean onTheFly = false; @@ -416,16 +415,12 @@ public String colorBySubunit() { colors[half+i] = temp; } } - Map> colorMap = new HashMap>(); + Map> colorMap = new HashMap<>(); for (int i = 0; i < orbits.size(); i++) { for (Integer j: orbits.get(i)) { Color4f c = colors[i]; - List ids = colorMap.get(c); - if (ids == null) { - ids = new ArrayList(); - colorMap.put(c, ids); - } + List ids = colorMap.computeIfAbsent(c, k -> new ArrayList<>()); String id = getChainSpecification(modelNumbers, chainIds, j); ids.add(id); } @@ -448,15 +443,11 @@ public String colorBySequenceCluster() { int clusters = Collections.max(seqClusterIds) + 1; Color[] col = ColorBrewer.BrBG.getColorPalette(clusters); Color4f[] colors = ColorConverter.convertColor4f(col); - Map> colorMap = new HashMap>(); + Map> colorMap = new HashMap<>(); for (int i = 0; i < n; i++) { Color4f c = colors[seqClusterIds.get(i)]; - List ids = colorMap.get(c); - if (ids == null) { - ids = new ArrayList(); - colorMap.put(c, ids); - } + List ids = colorMap.computeIfAbsent(c, k -> new ArrayList<>()); String id = getChainSpecification(modelNumbers, chainIds, i); ids.add(id); @@ -481,7 +472,7 @@ public String colorBySymmetry() { List clusterIds = subunits.getClusterIds(); int clusterCount = Collections.max(clusterIds) + 1; - Map> colorMap = new HashMap>(); + Map> colorMap = new HashMap<>(); int maxLen = 0; for (List unit: units) { @@ -502,11 +493,7 @@ public String colorBySymmetry() { Color4f c = new Color4f(colors[count]); count++; c.scale(scale); - List ids = colorMap.get(c); - if (ids == null) { - ids = new ArrayList(); - colorMap.put(c, ids); - } + List ids = colorMap.computeIfAbsent(c, k -> new ArrayList<>()); String id = getChainSpecification(modelNumbers, chainIds, subunit); ids.add(id); } @@ -579,7 +566,7 @@ private List extendUnitCenters(List points) { // System.out.println("XZRadius: " + radius); - List ePoints = new ArrayList(points.size()); + List ePoints = new ArrayList<>(points.size()); for (Point3d p: points) { Point3d q = new Point3d(p); transformation.transform(q); @@ -597,7 +584,7 @@ private List interiorCenters(List points) { Matrix4d transformation = helixAxisAligner.getTransformation(); Matrix4d reversetransformation = helixAxisAligner.getReverseTransformation(); - List ePoints = new ArrayList(points.size()); + List ePoints = new ArrayList<>(points.size()); for (Point3d p: points) { Point3d q = new Point3d(p); transformation.transform(q); diff --git a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGeneratorPointGroup.java b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGeneratorPointGroup.java index 1a4f8a7301..80123eab84 100644 --- a/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGeneratorPointGroup.java +++ b/biojava-structure-gui/src/main/java/org/biojava/nbio/structure/symmetry/jmolScript/JmolSymmetryScriptGeneratorPointGroup.java @@ -24,32 +24,31 @@ package org.biojava.nbio.structure.symmetry.jmolScript; import org.biojava.nbio.structure.symmetry.axis.RotationAxisAligner; +import org.biojava.nbio.structure.symmetry.core.QuatSymmetrySubunits; import org.biojava.nbio.structure.symmetry.core.Rotation; import org.biojava.nbio.structure.symmetry.core.RotationGroup; -import org.biojava.nbio.structure.symmetry.core.QuatSymmetrySubunits; import org.biojava.nbio.structure.symmetry.geometry.Polyhedron; import org.jcolorbrewer.ColorBrewer; import javax.vecmath.*; - import java.awt.*; -import java.util.*; import java.util.List; +import java.util.*; /** * @author Peter * */ public abstract class JmolSymmetryScriptGeneratorPointGroup extends JmolSymmetryScriptGenerator { - private static String N_FOLD_AXIS_COLOR = "red"; - private static String TWO_FOLD_AXIS_COLOR = "deepskyblue"; - private static String THREE_FOLD_AXIS_COLOR = "lime"; - private static double AXIS_SCALE_FACTOR = 1.2; + private static final String N_FOLD_AXIS_COLOR = "red"; + private static final String TWO_FOLD_AXIS_COLOR = "deepskyblue"; + private static final String THREE_FOLD_AXIS_COLOR = "lime"; + private static final double AXIS_SCALE_FACTOR = 1.2; - private RotationAxisAligner rotationAxisAligner = null; - private RotationGroup rotationGroup = null; + private RotationAxisAligner rotationAxisAligner; + private RotationGroup rotationGroup; private Polyhedron polyhedron = null; - private String name = ""; + private final String name; private String defaultColoring = ""; private boolean onTheFly = true; @@ -298,15 +297,14 @@ public String colorBySubunit() { List> orbits = rotationAxisAligner.getOrbits(); int fold = rotationGroup.getRotation(0).getFold(); - Color[] col = null; - Color4f[] colors = null; + Color[] col; + Color4f[] colors; if (fold > 1) { col = ColorBrewer.Spectral.getColorPalette(2*fold); - colors = ColorConverter.convertColor4f(col); } else { col = ColorBrewer.Spectral.getColorPalette(orbits.size()); - colors = ColorConverter.convertColor4f(col); } + colors = ColorConverter.convertColor4f(col); int half = colors.length/2; for (int i = 0; i < half; i++) { if (i % 2 != 0) { @@ -315,7 +313,7 @@ public String colorBySubunit() { colors[half+i] = temp; } } - Map> colorMap = new HashMap>(); + Map> colorMap = new HashMap<>(); for (int i = 0; i < orbits.size(); i++) { for (int j = 0; j < fold; j++) { @@ -330,11 +328,7 @@ public String colorBySubunit() { } int subunit = orbits.get(i).get(j); Color4f c = colors[colorIndex]; - List ids = colorMap.get(c); - if (ids == null) { - ids = new ArrayList(); - colorMap.put(c, ids); - } + List ids = colorMap.computeIfAbsent(c, k -> new ArrayList<>()); String id = getChainSpecification(modelNumbers, chainIds, subunit); ids.add(id); } @@ -356,15 +350,11 @@ public String colorBySequenceCluster() { int clusters = Collections.max(seqClusterIds) + 1; Color[] col = ColorBrewer.BrBG.getColorPalette(clusters); Color4f[] colors = ColorConverter.convertColor4f(col); - Map> colorMap = new HashMap>(); + Map> colorMap = new HashMap<>(); for (int i = 0; i < n; i++) { Color4f c = colors[seqClusterIds.get(i)]; - List ids = colorMap.get(c); - if (ids == null) { - ids = new ArrayList(); - colorMap.put(c, ids); - } + List ids = colorMap.computeIfAbsent(c, k -> new ArrayList<>()); String id = getChainSpecification(modelNumbers, chainIds, i); ids.add(id); @@ -388,7 +378,7 @@ public String colorBySymmetry() { int n = subunits.getSubunitCount(); int fold = rotationGroup.getRotation(0).getFold(); - Map> colorMap = new HashMap>(); + Map> colorMap = new HashMap<>(); // Simple Cn symmetry if (pointGroup.startsWith("C") && n == fold) { @@ -396,7 +386,7 @@ public String colorBySymmetry() { // complex cases } else if ((pointGroup.startsWith("D") && orbits.size() > 2) || pointGroup.equals("T")|| pointGroup.equals("O") || pointGroup.equals("I")) { - int nColor = 0; + int nColor; if (orbits.size() % 2 == 0) { nColor = orbits.size()/2; } else { @@ -412,11 +402,7 @@ public String colorBySymmetry() { colorIndex = orbits.size() - 1 - i; } Color4f c = colors[colorIndex]; - List ids = colorMap.get(c); - if (ids == null) { - ids = new ArrayList(); - colorMap.put(c, ids); - } + List ids = colorMap.computeIfAbsent(c, k -> new ArrayList<>()); for (int subunit: orbits.get(i)) { String id = getChainSpecification(modelNumbers, chainIds, subunit); ids.add(id); @@ -429,11 +415,7 @@ public String colorBySymmetry() { for (int i = 0; i < orbits.size(); i++) { Color4f c = new Color4f(colors[i]); - List ids = colorMap.get(c); - if (ids == null) { - ids = new ArrayList(); - colorMap.put(c, ids); - } + List ids = colorMap.computeIfAbsent(c, k -> new ArrayList<>()); List orbit = orbits.get(i); for (int j = 0; j < orbit.size(); j++) { String id = getChainSpecification(modelNumbers, chainIds, orbit.get(j)); @@ -531,20 +513,16 @@ private Map> getCnColorMap() { int fold = rotationGroup.getRotation(0).getFold(); - Map> colorMap = new HashMap>(); + Map> colorMap = new HashMap<>(); Color4f[] colors = getSymmetryColors(fold); for (List orbit: orbits) { for (int i = 0; i < fold; i++) { int subunit = orbit.get(i); - String id = null; + String id; id = getChainSpecification(modelNumbers, chainIds, subunit); Color4f c = colors[i]; - List ids = colorMap.get(c); - if (ids == null) { - ids = new ArrayList(); - colorMap.put(c, ids); - } + List ids = colorMap.computeIfAbsent(c, k -> new ArrayList<>()); ids.add(id); } } @@ -580,8 +558,8 @@ private Color4f getPolyhedronColor() { */ private Color4f[] getSymmetryColors(int nColors) { String pointGroup = rotationGroup.getPointGroup(); - Color[] col = null; - Color4f[] colors = null; + Color[] col; + Color4f[] colors; if (pointGroup.equals("C1")) { col = ColorBrewer.Greys.getColorPalette(nColors); colors = ColorConverter.convertColor4f(col); @@ -638,7 +616,7 @@ private String drawInertiaAxes() { s.append(" off;"); } return s.toString(); - }; + } private String drawSymmetryAxes() { StringBuilder s = new StringBuilder(); @@ -649,8 +627,8 @@ private String drawSymmetryAxes() { } float diameter = 0.5f; - double radius = 0; - String color = ""; + double radius; + String color; List axes = getUniqueAxes(); @@ -933,7 +911,7 @@ private static Vector3d[] getC2PolygonVertices(Vector3d axis, Vector3d reference // in reverse order, draw reflected half of arc (1/6 of full circle) // don't draw first and last element, since the are already part of the previous arc for (int i = k; i < 2*k-2; i++) { - axisAngle.angle = (f/2*k + i + 1.5) * 2 * Math.PI/(f*k); + axisAngle.angle = (f/2.0*k + i + 1.5) * 2 * Math.PI/(f*k); vectors[i] = new Vector3d(ref); m.set(axisAngle); // make sure matrix element m33 is 1.0. It's 0 on Linux. @@ -947,7 +925,7 @@ private static Vector3d[] getC2PolygonVertices(Vector3d axis, Vector3d reference private List getUniqueAxes() { - List uniqueRotations = new ArrayList(); + List uniqueRotations = new ArrayList<>(); for (int i = 0, n = rotationGroup.getOrder(); i < n; i++) { Rotation rotationI = rotationGroup.getRotation(i); diff --git a/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/JmolViewerImplTest.java b/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/JmolViewerImplTest.java index 727cbc137d..7bf2cebab9 100644 --- a/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/JmolViewerImplTest.java +++ b/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/JmolViewerImplTest.java @@ -36,11 +36,11 @@ public class JmolViewerImplTest { @Before - public void setUp() throws Exception { + public void setUp() { } @After - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/RenderStyleTest.java b/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/RenderStyleTest.java index b26b3b6431..1c99583faa 100644 --- a/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/RenderStyleTest.java +++ b/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/RenderStyleTest.java @@ -34,11 +34,11 @@ public class RenderStyleTest { @Before - public void setUp() throws Exception { + public void setUp() { } @After - public void tearDown() throws Exception { + public void tearDown() { } @Test diff --git a/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/StructureViewerTest.java b/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/StructureViewerTest.java index f954b27b20..0c29bbd0f7 100644 --- a/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/StructureViewerTest.java +++ b/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/StructureViewerTest.java @@ -37,11 +37,11 @@ public class StructureViewerTest { @Before - public void setUp() throws Exception { + public void setUp() { } @After - public void tearDown() throws Exception { + public void tearDown() { } /** @@ -178,7 +178,7 @@ public void testSetZoom() { // fail("The test case is a prototype."); } - public class StructureViewerImpl implements StructureViewer { + public static class StructureViewerImpl implements StructureViewer { @Override public void setStructure(Structure structure) { diff --git a/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/TestAtomInfo.java b/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/TestAtomInfo.java index 9d271a873c..a36c8e0f14 100644 --- a/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/TestAtomInfo.java +++ b/biojava-structure-gui/src/test/java/org/biojava/nbio/structure/gui/TestAtomInfo.java @@ -34,7 +34,7 @@ public void testAtomInfoConversion(){ String s1 = "[MET]508:A.CA/1 #3918"; AtomInfo aa = AtomInfo.fromString(s1); - Assert.assertTrue(aa.getAtomName().equals("CA")); + Assert.assertEquals("CA", aa.getAtomName()); Assert.assertEquals(aa.getChainId(), "A"); Assert.assertEquals(aa.getModelNumber(), 1); Assert.assertEquals(aa.getResidueName(), "MET"); diff --git a/biojava-structure/pom.xml b/biojava-structure/pom.xml index 688984e845..79e02b9d12 100644 --- a/biojava-structure/pom.xml +++ b/biojava-structure/pom.xml @@ -63,7 +63,7 @@ org.jgrapht jgrapht-core - 1.1.0 + 1.4.0 - - org.apache.maven.plugins - maven-jar-plugin - - - demo/** - - - + org.apache.maven.plugins diff --git a/biojava-structure/src/main/java/demo/DemoAtomCache.java b/biojava-structure/src/main/java/demo/DemoAtomCache.java index 460332c3ae..2e112acb36 100644 --- a/biojava-structure/src/main/java/demo/DemoAtomCache.java +++ b/biojava-structure/src/main/java/demo/DemoAtomCache.java @@ -22,9 +22,9 @@ import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.FileParsingParameters; -import org.biojava.nbio.structure.StructureIO; /** Example of how to load PDB files using the AtomCache class. diff --git a/biojava-structure/src/main/java/demo/DemoBioAssemblies.java b/biojava-structure/src/main/java/demo/DemoBioAssemblies.java index 4427bf3eea..c362a82b97 100644 --- a/biojava-structure/src/main/java/demo/DemoBioAssemblies.java +++ b/biojava-structure/src/main/java/demo/DemoBioAssemblies.java @@ -20,8 +20,6 @@ */ package demo; -import java.util.List; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.cluster.SubunitClustererParameters; @@ -29,6 +27,8 @@ import org.biojava.nbio.structure.symmetry.core.QuatSymmetryParameters; import org.biojava.nbio.structure.symmetry.core.QuatSymmetryResults; +import java.util.List; + public class DemoBioAssemblies { public static void main(String[] args) throws Exception { diff --git a/biojava-structure/src/main/java/demo/DemoCE.java b/biojava-structure/src/main/java/demo/DemoCE.java index 5d7859db4f..47a70913c0 100644 --- a/biojava-structure/src/main/java/demo/DemoCE.java +++ b/biojava-structure/src/main/java/demo/DemoCE.java @@ -55,8 +55,8 @@ public static void main(String[] args){ AtomCache cache = new AtomCache(); - Structure structure1 = null; - Structure structure2 = null; + Structure structure1; + Structure structure2; try { @@ -110,7 +110,7 @@ private static void printScores(AFPChain afpChain) { System.out.println("RMSD :\t" + String.format("%.2f",afpChain.getTotalRmsdOpt() )+ "\t The RMSD of the alignment"); System.out.println("Z-score :\t" + afpChain.getProbability() + "\t The Z-score of the alignment (CE)"); System.out.println("TM-score :\t" + String.format("%.2f",afpChain.getTMScore()) + "\t The TM-score of the alignment."); - System.out.println(""); + System.out.println(); System.out.println("Other scores:"); System.out.println("Identity :\t" + String.format("%.2f",afpChain.getIdentity()) + "\t The percent of residues that are sequence-identical in the alignment."); System.out.println("Similarity:\t" + String.format("%.2f",afpChain.getSimilarity()) + "\t The percent of residues in the alignment that are sequence-similar."); diff --git a/biojava-structure/src/main/java/demo/DemoCeSymm.java b/biojava-structure/src/main/java/demo/DemoCeSymm.java index 996c889a9a..9720409837 100644 --- a/biojava-structure/src/main/java/demo/DemoCeSymm.java +++ b/biojava-structure/src/main/java/demo/DemoCeSymm.java @@ -20,8 +20,6 @@ */ package demo; -import java.io.IOException; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; @@ -36,6 +34,8 @@ import org.biojava.nbio.structure.symmetry.internal.CeSymmResult; import org.biojava.nbio.structure.symmetry.utils.SymmetryTools; +import java.io.IOException; + /** * Quick demo of how to call CE-Symm programmatically. * Some examples of different symmetry types are proposed. diff --git a/biojava-structure/src/main/java/demo/DemoCommandLineStartup.java b/biojava-structure/src/main/java/demo/DemoCommandLineStartup.java index 7d9b24e123..a84ad81444 100644 --- a/biojava-structure/src/main/java/demo/DemoCommandLineStartup.java +++ b/biojava-structure/src/main/java/demo/DemoCommandLineStartup.java @@ -29,7 +29,7 @@ public class DemoCommandLineStartup { - public static void main(String[] arg) throws Exception { + public static void main(String[] arg) { // demo how to use with command line parameters String commandLine = "-file1 /tmp/cd/pdb1cdg.ent.gz -file2 file:///tmp/ti/pdb1tim.ent.gz -printCE"; diff --git a/biojava-structure/src/main/java/demo/DemoCrystalInterfaces.java b/biojava-structure/src/main/java/demo/DemoCrystalInterfaces.java index caeef006ed..e6ac5f8da3 100644 --- a/biojava-structure/src/main/java/demo/DemoCrystalInterfaces.java +++ b/biojava-structure/src/main/java/demo/DemoCrystalInterfaces.java @@ -23,13 +23,13 @@ import org.biojava.nbio.structure.Group; import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.contact.*; import org.biojava.nbio.structure.io.FileParsingParameters; import org.biojava.nbio.structure.xtal.CrystalBuilder; import org.biojava.nbio.structure.xtal.CrystalTransform; import org.biojava.nbio.structure.xtal.SpaceGroup; -import org.biojava.nbio.structure.StructureIO; import javax.vecmath.AxisAngle4d; import javax.vecmath.Vector3d; diff --git a/biojava-structure/src/main/java/demo/DemoFATCAT.java b/biojava-structure/src/main/java/demo/DemoFATCAT.java index d24473d98a..ad7b0a5b43 100644 --- a/biojava-structure/src/main/java/demo/DemoFATCAT.java +++ b/biojava-structure/src/main/java/demo/DemoFATCAT.java @@ -49,8 +49,8 @@ public static void main(String[] args){ AtomCache cache = new AtomCache(); - Structure structure1 = null; - Structure structure2 = null; + Structure structure1; + Structure structure2; try { diff --git a/biojava-structure/src/main/java/demo/DemoLoadSecStruc.java b/biojava-structure/src/main/java/demo/DemoLoadSecStruc.java index 8684ba1257..62d47033a3 100644 --- a/biojava-structure/src/main/java/demo/DemoLoadSecStruc.java +++ b/biojava-structure/src/main/java/demo/DemoLoadSecStruc.java @@ -20,9 +20,6 @@ */ package demo; -import java.io.IOException; -import java.util.List; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.util.AtomCache; @@ -32,6 +29,9 @@ import org.biojava.nbio.structure.secstruc.SecStrucInfo; import org.biojava.nbio.structure.secstruc.SecStrucTools; +import java.io.IOException; +import java.util.List; + /** * Demonstration of how to load a Structure with the SS information, either from * the PDB file annotation (Author's assignment) or from the DSSP file in the diff --git a/biojava-structure/src/main/java/demo/DemoLoadStructure.java b/biojava-structure/src/main/java/demo/DemoLoadStructure.java index 276eccaaf3..900db3e4bd 100644 --- a/biojava-structure/src/main/java/demo/DemoLoadStructure.java +++ b/biojava-structure/src/main/java/demo/DemoLoadStructure.java @@ -24,11 +24,11 @@ package demo; +import org.biojava.nbio.core.util.InputStreamProvider; import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.FileParsingParameters; import org.biojava.nbio.structure.io.PDBFileReader; -import org.biojava.nbio.core.util.InputStreamProvider; diff --git a/biojava-structure/src/main/java/demo/DemoMmcifToPdbConverter.java b/biojava-structure/src/main/java/demo/DemoMmcifToPdbConverter.java index 5a5c1a222f..4d73017afe 100644 --- a/biojava-structure/src/main/java/demo/DemoMmcifToPdbConverter.java +++ b/biojava-structure/src/main/java/demo/DemoMmcifToPdbConverter.java @@ -27,12 +27,7 @@ import org.biojava.nbio.structure.io.mmcif.SimpleMMcifConsumer; import org.biojava.nbio.structure.io.mmcif.SimpleMMcifParser; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; +import java.io.*; /** * An example of how to convert mmCIF file to PDB file diff --git a/biojava-structure/src/main/java/demo/DemoMmtfReader.java b/biojava-structure/src/main/java/demo/DemoMmtfReader.java index 0dc4b76ab1..95611353ad 100644 --- a/biojava-structure/src/main/java/demo/DemoMmtfReader.java +++ b/biojava-structure/src/main/java/demo/DemoMmtfReader.java @@ -20,12 +20,11 @@ */ package demo; -import java.io.IOException; - import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.io.mmtf.MmtfActions; +import java.io.IOException; + /** * Class to show how to read a Biojava structure using MMTF * @author Anthony Bradley @@ -37,9 +36,8 @@ public class DemoMmtfReader { * Main function to run the demo * @param args no args to specify * @throws IOException - * @throws StructureException - */ - public static void main(String[] args) throws IOException, StructureException { + */ + public static void main(String[] args) throws IOException { Structure structure = MmtfActions.readFromWeb("4cup"); System.out.println(structure.getChains().size()); } diff --git a/biojava-structure/src/main/java/demo/DemoMmtfWriter.java b/biojava-structure/src/main/java/demo/DemoMmtfWriter.java index c9fcd8166c..6aefaa0986 100644 --- a/biojava-structure/src/main/java/demo/DemoMmtfWriter.java +++ b/biojava-structure/src/main/java/demo/DemoMmtfWriter.java @@ -20,15 +20,15 @@ */ package demo; -import java.io.IOException; -import java.nio.file.Paths; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.io.mmtf.MmtfActions; import org.biojava.nbio.structure.io.mmtf.MmtfUtils; +import java.io.IOException; +import java.nio.file.Paths; + public class DemoMmtfWriter { public static void main(String[] args) throws IOException, StructureException { diff --git a/biojava-structure/src/main/java/demo/DemoMultipleMC.java b/biojava-structure/src/main/java/demo/DemoMultipleMC.java index 4ca84f0174..aa8c7f6f0b 100644 --- a/biojava-structure/src/main/java/demo/DemoMultipleMC.java +++ b/biojava-structure/src/main/java/demo/DemoMultipleMC.java @@ -20,12 +20,6 @@ */ package demo; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.ArrayList; -import java.util.concurrent.ExecutionException; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIdentifier; @@ -37,6 +31,11 @@ import org.biojava.nbio.structure.align.multiple.util.MultipleAlignmentWriter; import org.biojava.nbio.structure.align.util.AtomCache; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + /** * Demo for running the MultipleMC Algorithm on a protein family. * For visualizing the results in jmol use the same Demo in the GUI module. @@ -48,7 +47,7 @@ */ public class DemoMultipleMC { - public static void main(String[] args) throws IOException, StructureException, InterruptedException, ExecutionException { + public static void main(String[] args) throws IOException, StructureException { //Specify the structures to align //ASP-proteinases (CEMC paper) @@ -92,9 +91,9 @@ public static void main(String[] args) throws IOException, StructureException, I //Load the CA atoms of the structures AtomCache cache = new AtomCache(); - List atomArrays = new ArrayList(); + List atomArrays = new ArrayList<>(); - List ids = new ArrayList(); + List ids = new ArrayList<>(); for (String name:names) { StructureIdentifier id = new StructureName(name); ids.add(id); diff --git a/biojava-structure/src/main/java/demo/DemoQsAlign.java b/biojava-structure/src/main/java/demo/DemoQsAlign.java index 5c52aeb58b..a85d722fe3 100644 --- a/biojava-structure/src/main/java/demo/DemoQsAlign.java +++ b/biojava-structure/src/main/java/demo/DemoQsAlign.java @@ -20,8 +20,6 @@ */ package demo; -import java.io.IOException; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; @@ -30,6 +28,8 @@ import org.biojava.nbio.structure.align.quaternary.QsAlignResult; import org.biojava.nbio.structure.cluster.SubunitClustererParameters; +import java.io.IOException; + /** * Demo on how to use programatically {@link QsAlign} for the alignment of * quaternary structures. diff --git a/biojava-structure/src/main/java/demo/DemoSecStrucCalc.java b/biojava-structure/src/main/java/demo/DemoSecStrucCalc.java index 9cadf0f854..782dfef100 100644 --- a/biojava-structure/src/main/java/demo/DemoSecStrucCalc.java +++ b/biojava-structure/src/main/java/demo/DemoSecStrucCalc.java @@ -20,16 +20,16 @@ */ package demo; -import java.io.IOException; -import java.util.List; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.util.AtomCache; -import org.biojava.nbio.structure.secstruc.SecStrucElement; import org.biojava.nbio.structure.secstruc.SecStrucCalc; +import org.biojava.nbio.structure.secstruc.SecStrucElement; import org.biojava.nbio.structure.secstruc.SecStrucTools; +import java.io.IOException; +import java.util.List; + /** * Demonstration on how to use the Secondary Structure Prediction (DSSP) * implementation in BioJava and obtain different SS representations and diff --git a/biojava-structure/src/main/java/demo/DemoSymmetry.java b/biojava-structure/src/main/java/demo/DemoSymmetry.java index 4edc3cdc20..d86f56c6a8 100644 --- a/biojava-structure/src/main/java/demo/DemoSymmetry.java +++ b/biojava-structure/src/main/java/demo/DemoSymmetry.java @@ -20,8 +20,6 @@ */ package demo; -import java.util.List; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; @@ -33,6 +31,8 @@ import org.biojava.nbio.structure.symmetry.core.QuatSymmetryParameters; import org.biojava.nbio.structure.symmetry.core.QuatSymmetryResults; +import java.util.List; + /** * A demo on how to use the quaternary symmetry detection algorithms. * diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/AminoAcid.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/AminoAcid.java index 1877a84c16..ecc76c1dfa 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/AminoAcid.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/AminoAcid.java @@ -52,44 +52,44 @@ public interface AminoAcid extends Group { * Field to distinguish AminoAcids that have been created from SEQRES records and ATOM records. * */ - public static final String ATOMRECORD = "ATOM"; + String ATOMRECORD = "ATOM"; /** * Field to distinguish AminoAcids that have been created from SEQRES records and ATOM records. * */ - public static final String SEQRESRECORD = "SEQRES"; + String SEQRESRECORD = "SEQRES"; /** * Get N atom. * * @return an Atom object or null if N atom does not exist */ - public Atom getN() ; + Atom getN() ; /** * Get CA atom. * @return an Atom object or null if CA atom does not exist */ - public Atom getCA() ; + Atom getCA() ; /** * Get C atom. * @return an Atom object or null if C atom does not exist */ - public Atom getC() ; + Atom getC() ; /** * Get O atom. * @return an Atom object or null if O atom does not exist */ - public Atom getO() ; + Atom getO() ; /** * Get CB atom. * @return an Atom object or null if CB atom does not exist */ - public Atom getCB() ; + Atom getCB() ; /** * Returns the name of the AA, in single letter code. @@ -97,7 +97,7 @@ public interface AminoAcid extends Group { * @return a Character object representing the amino type value * @see #setAminoType */ - public Character getAminoType() ; + Character getAminoType() ; /** * Set the name of the AA, in single letter code . @@ -105,7 +105,7 @@ public interface AminoAcid extends Group { * @param aa a Character object specifying the amino type value * @see #getAminoType */ - public void setAminoType(Character aa) ; + void setAminoType(Character aa) ; /** * Allows to distinguish between amino acids that are provided @@ -113,7 +113,7 @@ public interface AminoAcid extends Group { * @param recordName either ATOMRECORD or SEQRESRECORD * @see #getRecordType() */ - public void setRecordType(String recordName); + void setRecordType(String recordName); /** * Allows to distinguish between amino acids that are provided @@ -121,6 +121,6 @@ public interface AminoAcid extends Group { * @return the origin of this amino acid (ATOM or SEQRES records) * @see #setRecordType(String) */ - public String getRecordType(); + String getRecordType(); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/Atom.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/Atom.java index 7b1c722bd9..893866a6e6 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/Atom.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/Atom.java @@ -23,9 +23,8 @@ */ package org.biojava.nbio.structure; -import java.util.List; - import javax.vecmath.Point3d; +import java.util.List; /** * A simple interface for an Atom. @@ -43,12 +42,15 @@ */ public interface Atom extends Cloneable, PDBRecord { - /** + Atom[] EmptyAtomArray = new Atom[0]; + + + /** * Set atom name, e.g. "CA". * @param s a trimmed String specifying the name value * @see #getName */ - public void setName(String s); + void setName(String s); /** * Get atom name, e.g. "CA". @@ -57,42 +59,42 @@ public interface Atom extends Cloneable, PDBRecord { * @return a trimmed String representing the name value * @see #setName */ - public String getName(); + String getName(); /** * Set element of the atom name, e.g. {@link Element#Fe} * @param e an Element enumeration * @see #getElement */ - public void setElement(Element e); + void setElement(Element e); /** * Get element of the atom, e.g. {@link Element#Ca} * @return an Element enumeration * @see #setElement */ - public Element getElement(); + Element getElement(); /** * Set PDB atom number. * @param i an int specifying the PDBserial value * @see #getPDBserial */ - public void setPDBserial(int i) ; + void setPDBserial(int i) ; /** * Get PDB atom number. * @return an int representing the PDBserial value * @see #setPDBserial */ - public int getPDBserial() ; + int getPDBserial() ; /** * Set the coordinates. * @param c an array of doubles specifying the coords value * @see #getCoords */ - public void setCoords(double[] c); + void setCoords(double[] c); /** * Get the coordinates. @@ -100,7 +102,7 @@ public interface Atom extends Cloneable, PDBRecord { * @see #setCoords * @see #getCoordsAsPoint3d() */ - public double[] getCoords() ; + double[] getCoords() ; /** * Get the coordinates. @@ -110,56 +112,56 @@ public interface Atom extends Cloneable, PDBRecord { * @return a reference to the Point3d coordinates * @see #getCoords() */ - public Point3d getCoordsAsPoint3d(); + Point3d getCoordsAsPoint3d(); /** * Set the X coordinate. * @param x a double * @see #getX() */ - public void setX(double x); + void setX(double x); /** * Set the Y coordinate. * @param y a double * @see #getY() */ - public void setY(double y); + void setY(double y); /** * Set the Z coordinate. * @param z a double * @see #getZ() */ - public void setZ(double z); + void setZ(double z); /** * Get coordinate X. * @return a double * @see #setX(double) */ - public double getX() ; + double getX() ; /** * Get coordinate Y. * @return a double * @see #setY(double) */ - public double getY() ; + double getY() ; /** * Get coordinate Z. * @return a double * @see #setZ(double) */ - public double getZ() ; + double getZ() ; /** * Set alternate Location. * @param c a Character object specifying the alt loc value * @see #getAltLoc */ - public void setAltLoc(Character c); + void setAltLoc(Character c); /** * Get alternate Location. @@ -167,41 +169,41 @@ public interface Atom extends Cloneable, PDBRecord { * is represented by ' ' (space character, ascii 32). * @see #setAltLoc */ - public Character getAltLoc(); + Character getAltLoc(); /** * Set occupancy. * @param occupancy a float specifying the occupancy value * @see #getOccupancy */ - public void setOccupancy(float occupancy) ; + void setOccupancy(float occupancy) ; /** * Get occupancy. * @return a float representing the occupancy value * @see #setOccupancy */ - public float getOccupancy(); + float getOccupancy(); /** * Set temp factor . * @param temp a float specifying the temp factor value * @see #getTempFactor */ - public void setTempFactor(float temp) ; + void setTempFactor(float temp) ; /** * Get temp factor. * @return a float representing the temp factor value * @see #setTempFactor */ - public float getTempFactor() ; + float getTempFactor() ; /** * Return an identical copy of this object . * @return an identical copy of this object */ - public Object clone(); + Object clone(); /** * Set the back-reference to its parent Group. @@ -209,7 +211,7 @@ public interface Atom extends Cloneable, PDBRecord { * @see #getGroup() */ - public void setGroup(Group parent); + void setGroup(Group parent); /** * Return the parent Group of the Atom. @@ -217,27 +219,27 @@ public interface Atom extends Cloneable, PDBRecord { * @return Group the parent Group of the Atom, or null * @see #setGroup(Group) */ - public Group getGroup(); + Group getGroup(); /** * Add a bond * @param bond to be added * @see #getBonds() */ - public void addBond(Bond bond); + void addBond(Bond bond); /** * Get all {@link Bond}s this atom is part of. * * @return a list of {@link Bond}s or null if no bonds exist for this Atom */ - public List getBonds(); + List getBonds(); /** * Sets the bonds * @param bonds */ - public void setBonds(List bonds); + void setBonds(List bonds); /** Test if another atom has a bond to this atom @@ -245,19 +247,19 @@ public interface Atom extends Cloneable, PDBRecord { * @param other * @return */ - public boolean hasBond(Atom other); + boolean hasBond(Atom other); /** * Get the charge of this atom * * @return a the integer charge. */ - public short getCharge(); + short getCharge(); /** * Set the charge of this atom * * @return void. */ - public void setCharge(short charge); + void setCharge(short charge); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/AtomImpl.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/AtomImpl.java index 36ccf49efb..1cdaf3dbf2 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/AtomImpl.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/AtomImpl.java @@ -25,11 +25,10 @@ import org.biojava.nbio.structure.io.FileConvert; +import javax.vecmath.Point3d; import java.util.ArrayList; import java.util.List; -import javax.vecmath.Point3d; - /** * Implementation of an Atom of a PDB file. diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/AtomIterator.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/AtomIterator.java index 20c0bde011..090c0f92df 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/AtomIterator.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/AtomIterator.java @@ -43,7 +43,7 @@ public class AtomIterator implements Iterator { private Group group ; private int current_atom_pos ; - private GroupIterator groupiter ; + private final GroupIterator groupiter ; /** * Constructs an AtomIterator object over all models diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/AtomPositionMap.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/AtomPositionMap.java index b6c806417e..a79d024a92 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/AtomPositionMap.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/AtomPositionMap.java @@ -23,21 +23,15 @@ package org.biojava.nbio.structure; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.NavigableMap; -import java.util.TreeMap; - import org.biojava.nbio.structure.io.mmcif.chem.PolymerType; import org.biojava.nbio.structure.io.mmcif.chem.ResidueType; import org.biojava.nbio.structure.io.mmcif.model.ChemComp; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.Serializable; +import java.util.*; + /** * A map from {@link ResidueNumber ResidueNumbers} to ATOM record positions in a PDB file. * @@ -61,54 +55,46 @@ public class AtomPositionMap { private static final Logger logger = LoggerFactory.getLogger(AtomPositionMap.class); - private HashMap hashMap; - private TreeMap treeMap; + private final HashMap hashMap; + private final TreeMap treeMap; /** * Used as a Predicate to indicate whether a particular Atom should be mapped */ - public static interface GroupMatcher { + public interface GroupMatcher { boolean matches(Group group); } /** * Matches CA atoms of protein groups */ - public static final GroupMatcher AMINO_ACID_MATCHER = new GroupMatcher() { - @Override - public boolean matches(Group group) { - if( group == null ) - return false; - ChemComp chem = group.getChemComp(); - if(chem == null) - return false; - // Get polymer type - PolymerType polyType = chem.getPolymerType(); - if( polyType == null) { - ResidueType type = chem.getResidueType(); - if(type != null ) { - polyType = type.getPolymerType(); - } - } - if( polyType == null ) { - return false; + public static final GroupMatcher AMINO_ACID_MATCHER = group -> { + if( group == null ) + return false; + ChemComp chem = group.getChemComp(); + if(chem == null) + return false; + // Get polymer type + PolymerType polyType = chem.getPolymerType(); + if( polyType == null) { + ResidueType type = chem.getResidueType(); + if(type != null ) { + polyType = type.getPolymerType(); } - - return PolymerType.PROTEIN_ONLY.contains(polyType) - && group.hasAtom(StructureTools.CA_ATOM_NAME); } + if( polyType == null ) { + return false; + } + + return PolymerType.PROTEIN_ONLY.contains(polyType) + && group.hasAtom(StructureTools.CA_ATOM_NAME); }; /** * Matches all atoms */ - public static final GroupMatcher ANYTHING_MATCHER = new GroupMatcher() { - @Override - public boolean matches(Group group) { - return true; - } - }; + public static final GroupMatcher ANYTHING_MATCHER = group -> true; /** * A map that is sorted by its values. Used for the treemap @@ -123,7 +109,7 @@ public boolean matches(Group group) { private static class ValueComparator> implements Comparator, Serializable { private static final long serialVersionUID = 1; - private Map map; + private final Map map; public ValueComparator(Map map) { this.map = map; @@ -153,18 +139,18 @@ public AtomPositionMap(Atom[] atoms) { * @param atoms */ public AtomPositionMap(Atom[] atoms, GroupMatcher matcher) { - hashMap = new HashMap(); + hashMap = new HashMap<>(); for (int i = 0; i < atoms.length; i++) { Group group = atoms[i].getGroup(); ResidueNumber rn = group.getResidueNumber(); if (matcher.matches(group)) { - if (!hashMap.containsKey(rn)) { - hashMap.put(rn, i); - } + //if (!hashMap.containsKey(rn)) { + hashMap.putIfAbsent(rn, i); + //} } } - Comparator vc = new ValueComparator(hashMap); - treeMap = new TreeMap(vc); + Comparator vc = new ValueComparator<>(hashMap); + treeMap = new TreeMap<>(vc); treeMap.putAll(hashMap); } @@ -219,11 +205,7 @@ public int getLength(int positionA, int positionB, String startingChain) { */ public int getLengthDirectional(int positionStart, int positionEnd, String startingChain) { int count = getLength(positionStart,positionEnd,startingChain); - if(positionStart <= positionEnd) { - return count; - } else { - return -count; - } + return positionStart <= positionEnd ? count : -count; } /** @@ -301,8 +283,9 @@ public Integer getPosition(ResidueNumber residueNumber) { public ResidueNumber getFirst(String chainId) { Map.Entry entry = treeMap.firstEntry(); while (true) { - if (entry.getKey().getChainName().equals(chainId)) return entry.getKey(); - entry = treeMap.higherEntry(entry.getKey()); + ResidueNumber k = entry.getKey(); + if (k.getChainName().equals(chainId)) return k; + entry = treeMap.higherEntry(k); if (entry == null) return null; } } @@ -314,8 +297,9 @@ public ResidueNumber getFirst(String chainId) { public ResidueNumber getLast(String chainId) { Map.Entry entry = treeMap.lastEntry(); while (true) { - if (entry.getKey().getChainName().equals(chainId)) return entry.getKey(); - entry = treeMap.lowerEntry(entry.getKey()); + ResidueNumber k = entry.getKey(); + if (k.getChainName().equals(chainId)) return k; + entry = treeMap.lowerEntry(k); if (entry == null) return null; } } @@ -341,20 +325,24 @@ public List getRanges() { String currentChain = ""; ResidueNumber first = null; ResidueNumber prev = null; - List ranges = new ArrayList(); + List ranges = new ArrayList<>(); for (ResidueNumber rn : treeMap.keySet()) { if (!rn.getChainName().equals(currentChain)) { if (first != null) { - ResidueRangeAndLength newRange = new ResidueRangeAndLength(currentChain, first, prev, this.getLength(first, prev)); - ranges.add(newRange); + ranges.add(new ResidueRangeAndLength( + currentChain, first, prev, + getLength(first, prev))); } first = rn; } prev = rn; currentChain = rn.getChainName(); } - ResidueRangeAndLength newRange = new ResidueRangeAndLength(currentChain, first, prev, this.getLength(first, prev)); - ranges.add(newRange); + + ranges.add(new ResidueRangeAndLength( + currentChain, first, prev, + getLength(first, prev))); + return ranges; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/Author.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/Author.java index b0d7253507..1ab5a9a0b0 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/Author.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/Author.java @@ -22,6 +22,7 @@ package org.biojava.nbio.structure; import java.io.Serializable; +import java.util.Objects; /** * Describes author attributes for author information in a PDB file. @@ -59,10 +60,10 @@ public boolean equals(Object obj) { return false; } final Author other = (Author) obj; - if ((this.surname == null) ? (other.surname != null) : !this.surname.equals(other.surname)) { + if (!Objects.equals(this.surname, other.surname)) { return false; } - return !((this.initials == null) ? (other.initials != null) : !this.initials.equals(other.initials)); + return Objects.equals(this.initials, other.initials); } @Override diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/BioAssemblyIdentifier.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/BioAssemblyIdentifier.java index 365948f059..6ef3f7693f 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/BioAssemblyIdentifier.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/BioAssemblyIdentifier.java @@ -20,19 +20,18 @@ */ package org.biojava.nbio.structure; -import java.io.IOException; +import org.biojava.nbio.structure.align.util.AtomCache; + import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.biojava.nbio.structure.align.util.AtomCache; - public class BioAssemblyIdentifier implements StructureIdentifier { private static final long serialVersionUID = -356206725119993449L; - private String pdbCode; - private int biolNr; + private final String pdbCode; + private final int biolNr; public static final Pattern BIO_NAME_PATTERN = Pattern.compile("^(?:BIO:)([0-9][a-z0-9]{3})(?::([0-9]+))?$", Pattern.CASE_INSENSITIVE); @@ -68,18 +67,17 @@ public String toString() { } @Override - public Structure loadStructure(AtomCache cache) throws StructureException, - IOException { + public Structure loadStructure(AtomCache cache) throws StructureException { return cache.getBiologicalAssembly(pdbCode, biolNr, AtomCache.DEFAULT_BIOASSEMBLY_STYLE); } @Override - public SubstructureIdentifier toCanonical() throws StructureException { - return new SubstructureIdentifier(pdbCode, new ArrayList()); + public SubstructureIdentifier toCanonical() { + return new SubstructureIdentifier(pdbCode, new ArrayList<>()); } @Override - public Structure reduce(Structure input) throws StructureException { + public Structure reduce(Structure input) { // Should be the full structure return input; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/Bond.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/Bond.java index 7af10c23e0..8e27a2438c 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/Bond.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/Bond.java @@ -39,7 +39,7 @@ public interface Bond extends Serializable { * @see #getAtomB() * @return one of the two atoms in this bond */ - public Atom getAtomA(); + Atom getAtomA(); /** * Gets atom 'B' of this bond. There is no meaning to which atom is 'A' and @@ -49,7 +49,7 @@ public interface Bond extends Serializable { * @see #getAtomA() * @return one of the two atoms in this bond */ - public Atom getAtomB(); + Atom getAtomB(); /** * A utility method to get the other atom in a bond, given one of its atoms. @@ -66,7 +66,7 @@ public interface Bond extends Serializable { * if the passed atom is not in this bond * @return the atom in this bond that was not passed as an argument */ - public Atom getOther(Atom exclude); + Atom getOther(Atom exclude); /** * Gets the bond order of this bond. A return value of '1' corresponds to a @@ -74,7 +74,7 @@ public interface Bond extends Serializable { * * @return this bond's bond order */ - public int getBondOrder(); + int getBondOrder(); /** * Gets the distance between the two atoms of this bond. @@ -85,5 +85,5 @@ public interface Bond extends Serializable { * * @return the distance between the two atoms of this bond. */ - public double getLength(); + double getLength(); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/BondImpl.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/BondImpl.java index b467a7272e..ac2aa20125 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/BondImpl.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/BondImpl.java @@ -33,9 +33,9 @@ public class BondImpl implements Bond { private static final long serialVersionUID = 8836120946858134380L; - private Atom atomA; - private Atom atomB; - private int bondOrder; + private final Atom atomA; + private final Atom atomB; + private final int bondOrder; /** * Constructs a new bond from a pair of atoms and the bond order of the bond @@ -90,7 +90,7 @@ public BondImpl(Atom atomA, Atom atomB, int bondOrder, boolean addSelfToAtoms) { private void addSelfToAtoms() { List bonds = atomA.getBonds(); if (bonds==null) { - bonds = new ArrayList(AtomImpl.BONDS_INITIAL_CAPACITY); + bonds = new ArrayList<>(AtomImpl.BONDS_INITIAL_CAPACITY); atomA.setBonds(bonds); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/BondType.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/BondType.java index 9b3f752092..a569fb3fe2 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/BondType.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/BondType.java @@ -26,5 +26,5 @@ * @author Jules Jacobsen */ public enum BondType { - UNDEFINED, COVALENT, IONIC, HBOND, VANDERWAALS, HYDROPHOBIC, METAL, PLANAR, ATOM_PLANE; + UNDEFINED, COVALENT, IONIC, HBOND, VANDERWAALS, HYDROPHOBIC, METAL, PLANAR, ATOM_PLANE } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/Calc.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/Calc.java index b6fde44843..2570348365 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/Calc.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/Calc.java @@ -22,15 +22,6 @@ */ package org.biojava.nbio.structure ; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import javax.vecmath.Matrix3d; -import javax.vecmath.Matrix4d; -import javax.vecmath.Point3d; -import javax.vecmath.Vector3d; - import org.biojava.nbio.structure.geometry.CalcPoint; import org.biojava.nbio.structure.geometry.Matrices; import org.biojava.nbio.structure.geometry.SuperPositionSVD; @@ -38,6 +29,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.vecmath.Matrix3d; +import javax.vecmath.Matrix4d; +import javax.vecmath.Point3d; +import javax.vecmath.Vector3d; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + /** * Utility operations on Atoms, AminoAcids, Matrices, Point3d, etc. *

    @@ -65,7 +64,7 @@ public class Calc { * an Atom object * @return a double */ - public static final double getDistance(Atom a, Atom b) { + public static double getDistance(Atom a, Atom b) { double x = a.getX() - b.getX(); double y = a.getY() - b.getY(); double z = a.getZ() - b.getZ(); @@ -87,7 +86,7 @@ public static final double getDistance(Atom a, Atom b) { * an Atom object * @return a double */ - public static double getDistanceFast(Atom a, Atom b) { + public static double getDistanceSqr(Atom a, Atom b) { double x = a.getX() - b.getX(); double y = a.getY() - b.getY(); double z = a.getZ() - b.getZ(); @@ -95,7 +94,7 @@ public static double getDistanceFast(Atom a, Atom b) { return x * x + y * y + z * z; } - public static final Atom invert(Atom a) { + public static Atom invert(Atom a) { double[] coords = new double[]{0.0,0.0,0.0} ; Atom zero = new AtomImpl(); zero.setCoords(coords); @@ -111,7 +110,7 @@ public static final Atom invert(Atom a) { * an Atom object * @return an Atom object */ - public static final Atom add(Atom a, Atom b){ + public static Atom add(Atom a, Atom b){ Atom c = new AtomImpl(); c.setX( a.getX() + b.getX() ); @@ -130,7 +129,7 @@ public static final Atom add(Atom a, Atom b){ * an Atom object * @return n new Atom object representing the difference */ - public static final Atom subtract(Atom a, Atom b) { + public static Atom subtract(Atom a, Atom b) { Atom c = new AtomImpl(); c.setX( a.getX() - b.getX() ); c.setY( a.getY() - b.getY() ); @@ -148,7 +147,7 @@ public static final Atom subtract(Atom a, Atom b) { * an Atom object * @return an Atom object */ - public static final Atom vectorProduct(Atom a , Atom b){ + public static Atom vectorProduct(Atom a , Atom b){ Atom c = new AtomImpl(); c.setX( a.getY() * b.getZ() - a.getZ() * b.getY() ) ; @@ -167,7 +166,7 @@ public static final Atom vectorProduct(Atom a , Atom b){ * an Atom object * @return a double */ - public static final double scalarProduct(Atom a, Atom b) { + public static double scalarProduct(Atom a, Atom b) { return a.getX() * b.getX() + a.getY() * b.getY() + a.getZ() * b.getZ(); } @@ -178,7 +177,7 @@ public static final double scalarProduct(Atom a, Atom b) { * an Atom object * @return Square root of the sum of the squared elements */ - public static final double amount(Atom a){ + public static double amount(Atom a){ return Math.sqrt(scalarProduct(a,a)); } @@ -192,7 +191,7 @@ public static final double amount(Atom a){ * @return Angle between a and b in degrees, in range [0,180]. If either * vector has length 0 then angle is not defined and NaN is returned */ - public static final double angle(Atom a, Atom b){ + public static double angle(Atom a, Atom b){ Vector3d va = new Vector3d(a.getCoordsAsPoint3d()); Vector3d vb = new Vector3d(b.getCoordsAsPoint3d()); @@ -208,7 +207,7 @@ public static final double angle(Atom a, Atom b){ * an Atom object * @return an Atom object */ - public static final Atom unitVector(Atom a) { + public static Atom unitVector(Atom a) { double amount = amount(a) ; double[] coords = new double[3]; @@ -239,7 +238,7 @@ public static final Atom unitVector(Atom a) { * 3 or last 3 atoms are colinear then torsion angle is not defined * and NaN is returned */ - public static final double torsionAngle(Atom a, Atom b, Atom c, Atom d) { + public static double torsionAngle(Atom a, Atom b, Atom c, Atom d) { Atom ab = subtract(a,b); Atom cb = subtract(c,b); @@ -272,7 +271,7 @@ public static final double torsionAngle(Atom a, Atom b, Atom c, Atom d) { * if aminoacids not connected or if any of the 4 needed atoms * missing */ - public static final double getPhi(AminoAcid a, AminoAcid b) + public static double getPhi(AminoAcid a, AminoAcid b) throws StructureException { if ( ! isConnected(a,b)){ @@ -305,7 +304,7 @@ public static final double getPhi(AminoAcid a, AminoAcid b) * if aminoacids not connected or if any of the 4 needed atoms * missing */ - public static final double getPsi(AminoAcid a, AminoAcid b) + public static double getPsi(AminoAcid a, AminoAcid b) throws StructureException { if ( ! isConnected(a,b)) { throw new StructureException( @@ -338,9 +337,9 @@ public static final double getPsi(AminoAcid a, AminoAcid b) * an AminoAcid object * @return true if ... */ - public static final boolean isConnected(AminoAcid a, AminoAcid b) { - Atom C = null ; - Atom N = null; + public static boolean isConnected(AminoAcid a, AminoAcid b) { + Atom C; + Atom N; C = a.getC(); N = b.getN(); @@ -365,7 +364,7 @@ public static final boolean isConnected(AminoAcid a, AminoAcid b) { * @param m * a rotation matrix represented as a double[3][3] array */ - public static final void rotate(Atom atom, double[][] m){ + public static void rotate(Atom atom, double[][] m){ double x = atom.getX(); double y = atom.getY() ; @@ -391,8 +390,8 @@ public static final void rotate(Atom atom, double[][] m){ * @throws StructureException * ... */ - public static final void rotate(Structure structure, - double[][] rotationmatrix) throws StructureException { + public static void rotate(Structure structure, + double[][] rotationmatrix) throws StructureException { if ( rotationmatrix.length != 3 ) { throw new StructureException ("matrix does not have size 3x3 !"); @@ -414,7 +413,7 @@ public static final void rotate(Structure structure, * @throws StructureException * ... */ - public static final void rotate(Group group, double[][] rotationmatrix) + public static void rotate(Group group, double[][] rotationmatrix) throws StructureException { if ( rotationmatrix.length != 3 ) { @@ -422,7 +421,7 @@ public static final void rotate(Group group, double[][] rotationmatrix) } AtomIterator iter = new AtomIterator(group) ; while (iter.hasNext()) { - Atom atom = null ; + Atom atom; atom = iter.next() ; rotate(atom,rotationmatrix); @@ -439,15 +438,14 @@ public static final void rotate(Group group, double[][] rotationmatrix) * @param m * rotation matrix to be applied to the atom */ - public static final void rotate(Atom atom, Matrix m){ + public static void rotate(Atom atom, Matrix m){ double x = atom.getX(); double y = atom.getY(); double z = atom.getZ(); double[][] ad = new double[][]{{x,y,z}}; - Matrix am = new Matrix(ad); - Matrix na = am.times(m); + Matrix na = new Matrix(ad).times(m); atom.setX(na.get(0,0)); atom.setY(na.get(0,1)); @@ -464,14 +462,12 @@ public static final void rotate(Atom atom, Matrix m){ * @param m * a Matrix object representing the rotation matrix */ - public static final void rotate(Group group, Matrix m){ + public static void rotate(Group group, Matrix m){ AtomIterator iter = new AtomIterator(group) ; while (iter.hasNext()) { - Atom atom = iter.next() ; - rotate(atom,m); - + rotate(iter.next(), m); } } @@ -485,7 +481,7 @@ public static final void rotate(Group group, Matrix m){ * @param m * rotation matrix to be applied */ - public static final void rotate(Structure structure, Matrix m){ + public static void rotate(Structure structure, Matrix m){ AtomIterator iter = new AtomIterator(structure) ; @@ -519,7 +515,7 @@ public static void transform(Atom[] ca, Matrix4d t) { * @param atom * @param m */ - public static final void transform (Atom atom, Matrix4d m) { + public static void transform (Atom atom, Matrix4d m) { Point3d p = new Point3d(atom.getX(),atom.getY(),atom.getZ()); m.transform(p); @@ -537,7 +533,7 @@ public static final void transform (Atom atom, Matrix4d m) { * @param group * @param m */ - public static final void transform(Group group, Matrix4d m) { + public static void transform(Group group, Matrix4d m) { for (Atom atom : group.getAtoms()) { transform(atom, m); } @@ -554,7 +550,7 @@ public static final void transform(Group group, Matrix4d m) { * @param structure * @param m */ - public static final void transform(Structure structure, Matrix4d m) { + public static void transform(Structure structure, Matrix4d m) { for (int n=0; n pdbResnumMap; + private final Map pdbResnumMap; private String asymId; // the 'internal' chain identifier as used in mmCIF files @@ -348,7 +351,7 @@ public Group[] getGroupsByPDB(ResidueNumber start, ResidueNumber end, boolean ig throws StructureException { // Short-circut for include all groups if(start == null && end == null) { - return groups.toArray(new Group[groups.size()]); + return groups.toArray(new Group[0]); } @@ -415,7 +418,7 @@ public Group[] getGroupsByPDB(ResidueNumber start, ResidueNumber end, boolean ig //not checking if the end has been found in this case... - return retlst.toArray(new Group[retlst.size()] ); + return retlst.toArray(new Group[0]); } @@ -426,14 +429,18 @@ public Group[] getGroupsByPDB(ResidueNumber start, ResidueNumber end, boolean ig @Override public Group getGroupByPDB(ResidueNumber resNum) throws StructureException { String pdbresnum = resNum.toString(); - if ( pdbResnumMap.containsKey(pdbresnum)) { - Integer pos = pdbResnumMap.get(pdbresnum); + Integer pos = pdbResnumMap.get(pdbresnum); + if ( pos!=null ) { return groups.get(pos); } else { throw new StructureException("unknown PDB residue number " + pdbresnum + " in chain " + authId); } } + public boolean hasGroupByPDB(ResidueNumber resNum) { + return pdbResnumMap.containsKey(resNum); + } + /** * {@inheritDoc} * diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/DBRef.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/DBRef.java index b4c397c544..8e27c687e1 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/DBRef.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/DBRef.java @@ -156,13 +156,13 @@ public String toString(){ for (Method m : methods) { String name = m.getName(); - if (name.substring(0, 3).equals("get")) { + if (name.startsWith("get")) { if (name.equals("getClass")) { continue; } Object o = m.invoke(this); if (o != null) { - buf.append(name.substring(3, name.length())); + buf.append(name.substring(3)); buf.append(": ").append(o).append(" "); } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/Element.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/Element.java index 6afeb2a9b8..f2e8206824 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/Element.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/Element.java @@ -159,24 +159,24 @@ public enum Element { */ R(104, 0, 105, 0.0f, 0.0f, 0, 0, 4, 1, 0, 0.000f, -1, 3, null, 0.00f, ElementType.UNKNOWN); // this is an R-group // should these be declared final? - private int atomicNumber; - private int period; + private final int atomicNumber; + private final int period; //private int hillOrder; - private float VDWRadius; // in Angstroms - private float covalentRadius; // in Angstroms - private int valenceElectronCount; - private int minimumValence; - private int maximumValence; - private int commonValence; - private int maximumCovalentValence; - private float atomicMass; - private int coreElectronCount; - private int oxidationState; - private int[] allOxidationStates; + private final float VDWRadius; // in Angstroms + private final float covalentRadius; // in Angstroms + private final int valenceElectronCount; + private final int minimumValence; + private final int maximumValence; + private final int commonValence; + private final int maximumCovalentValence; + private final float atomicMass; + private final int coreElectronCount; + private final int oxidationState; + private final int[] allOxidationStates; // Pauling electronegativity: http://en.wikipedia.org/wiki/Electronegativity - private float paulingElectronegativity; + private final float paulingElectronegativity; // Element type: http://www.ptable.com/ - private ElementType elementType; + private final ElementType elementType; //private static final Element[] hillOrderIndex; // @@ -191,12 +191,12 @@ public enum Element { private static final Map allElements ; static { - allElements = new HashMap(); + allElements = new HashMap<>(); for (Element e : Element.values()){ allElements.put(e.toString().toLowerCase(), e); } } - private Element(int atomicNumber, + Element(int atomicNumber, int period, int hillOrder, float VDWRadius, diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/ElementType.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/ElementType.java index 41abfd33c6..ea1f3f5e01 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/ElementType.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/ElementType.java @@ -48,9 +48,9 @@ public enum ElementType { POST_TRANSITION_METAL(true), UNKNOWN(false); - private boolean metal; + private final boolean metal; - private ElementType(boolean metal) { + ElementType(boolean metal) { this.metal = metal; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/EntityInfo.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/EntityInfo.java index cc52262b12..e826ee7eb8 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/EntityInfo.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/EntityInfo.java @@ -28,15 +28,7 @@ import org.slf4j.LoggerFactory; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; +import java.util.*; /** * An object to contain the info from the PDB header for a Molecule. @@ -77,7 +69,7 @@ public class EntityInfo implements Serializable { * Initialised lazily upon call to {@link #getAlignedResIndex(Group, Chain)} * Keys are asym_ids of chains, values maps of residue numbers to indices. */ - private Map> chains2pdbResNums2ResSerials; + private final Map> chains2pdbResNums2ResSerials; private String refChainId; private String description = null; @@ -159,11 +151,11 @@ public EntityInfo (EntityInfo c) { this.title = c.title; if (c.synonyms!=null) { - this.synonyms = new ArrayList(); + this.synonyms = new ArrayList<>(); synonyms.addAll(c.synonyms); } if (c.ecNums!=null) { - this.ecNums = new ArrayList(); + this.ecNums = new ArrayList<>(); ecNums.addAll(c.ecNums); } @@ -244,7 +236,7 @@ public Chain getRepresentative() { chainIds.add(chain.getId()); } - Collections.sort(chainIds, String.CASE_INSENSITIVE_ORDER); + chainIds.sort(String.CASE_INSENSITIVE_ORDER); for (Chain chain:chains) { if (chain.getId().equals(chainIds.get(0))) { @@ -380,7 +372,7 @@ private void initResSerialsMap(Chain c) { return; } - Map resNums2ResSerials = new HashMap(); + Map resNums2ResSerials = new HashMap<>(); chains2pdbResNums2ResSerials.put(c.getId(), resNums2ResSerials); for (int i=0;i expTechStr2Value = initExpTechStr2Value(); - private String name; - private boolean isCrystallographic; - private boolean isNmr; + private final String name; + private final boolean isCrystallographic; + private final boolean isNmr; - private ExperimentalTechnique(String name, boolean isXtallographic, boolean isNmr) { + ExperimentalTechnique(String name, boolean isXtallographic, boolean isNmr) { this.name = name; this.isCrystallographic = isXtallographic; this.isNmr = isNmr; @@ -71,7 +71,7 @@ private ExperimentalTechnique(String name, boolean isXtallographic, boolean isNm private static HashMap initExpTechStr2Value() { - HashMap expTechStr2Value = new HashMap(); + HashMap expTechStr2Value = new HashMap<>(); for(ExperimentalTechnique exp:ExperimentalTechnique.values()) { expTechStr2Value.put(exp.getName(), exp); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/Group.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/Group.java index f2bc5a506a..5240d7295a 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/Group.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/Group.java @@ -55,27 +55,27 @@ public interface Group extends Serializable { /** Group property key for secondary structure annotation */ - public static final String SEC_STRUC = "secstruc"; + String SEC_STRUC = "secstruc"; /** * Get number of atoms. * @return number of atoms of this Group */ - public int size(); + int size(); /** * Return true or false, depending if this group has 3D coordinates or not. * * @return true if Group has 3D coordinates */ - public boolean has3D (); + boolean has3D(); /** * Flag if group has 3D data . * * @param flag true to set flag that this Group has 3D coordinates */ - public void setPDBFlag(boolean flag); + void setPDBFlag(boolean flag); /** * Get Type of group, one of {@link GroupType#AMINOACID}, {@link GroupType#HETATM} @@ -83,14 +83,14 @@ public interface Group extends Serializable { * * @return a String representing the type value */ - public GroupType getType(); + GroupType getType(); /** * Add an atom to this group. * * @param atom an Atom object */ - public void addAtom(Atom atom); + void addAtom(Atom atom); /** * Get list of atoms. @@ -98,7 +98,7 @@ public interface Group extends Serializable { * @return a List object representing the atoms * @see #setAtoms(List) */ - public List getAtoms() ; + List getAtoms() ; /** @@ -106,13 +106,13 @@ public interface Group extends Serializable { * @see Atom * @param atoms a list of atoms */ - public void setAtoms(List atoms); + void setAtoms(List atoms); /** * Remove all atoms from this group. * */ - public void clearAtoms(); + void clearAtoms(); /** * Get an atom given its PDB name. @@ -125,7 +125,7 @@ public interface Group extends Serializable { * @param name a trimmed String representing the atom's PDB name, e.g. "CA" * @return an Atom object or null if no such atom exists within this group */ - public Atom getAtom(String name) ; + Atom getAtom(String name) ; /** * Get at atom by position. @@ -133,7 +133,7 @@ public interface Group extends Serializable { * @param position an int * @return an Atom object or null if no Atom exists for given position */ - public Atom getAtom(int position) ; + Atom getAtom(int position) ; /** * Tell whether a particular atom exists within this group. @@ -143,7 +143,7 @@ public interface Group extends Serializable { * @param name a trimmed String representing the atom's PDB name, e.g. "CA" * @return true if Atom with name exists within this group */ - public boolean hasAtom(String name); + boolean hasAtom(String name); /** * Get the PDB 3-letter name for this group. (e.g. ALA) @@ -151,7 +151,7 @@ public interface Group extends Serializable { * @return a String representing the PDBName value * @see #setPDBName */ - public String getPDBName(); + String getPDBName(); /** * Set the PDB 3-letter name for this group. (e.g. ALA) @@ -159,7 +159,7 @@ public interface Group extends Serializable { * @param s a String specifying the PDBName value * @see #getPDBName */ - public void setPDBName(String s) ; + void setPDBName(String s) ; /** @@ -183,7 +183,7 @@ public interface Group extends Serializable { * @return true if all Atoms required for an AminoAcid are available (N, CA, C, O) * @see #getType */ - public boolean hasAminoAtoms() ; + boolean hasAminoAtoms() ; /** @@ -191,7 +191,7 @@ public interface Group extends Serializable { * * @return true if a polymeric group */ - public boolean isPolymeric(); + boolean isPolymeric(); /** @@ -199,7 +199,7 @@ public interface Group extends Serializable { * * @return true if an amino acid */ - public boolean isAminoAcid(); + boolean isAminoAcid(); /** @@ -207,7 +207,7 @@ public interface Group extends Serializable { * * @return true if a nucleotide */ - public boolean isNucleotide(); + boolean isNucleotide(); @@ -220,7 +220,7 @@ public interface Group extends Serializable { * @param properties a Map object specifying the properties value * @see #getProperties */ - public void setProperties(Map properties) ; + void setProperties(Map properties) ; /** * Return properties. @@ -228,7 +228,7 @@ public interface Group extends Serializable { * * @return a HashMap object representing the properties value */ - public Map getProperties() ; + Map getProperties() ; /** * Set a single property . @@ -237,7 +237,7 @@ public interface Group extends Serializable { * @param value an Object * @see #getProperty */ - public void setProperty(String key, Object value) ; + void setProperty(String key, Object value) ; /** * Get a single property . @@ -246,21 +246,21 @@ public interface Group extends Serializable { * @return an Object * @see #setProperty */ - public Object getProperty(String key) ; + Object getProperty(String key) ; /** * Get an Atom Iterator. * * @return an Iterator object */ - public Iterator iterator() ; + Iterator iterator() ; /** * Returns and identical copy of this Group object . * @return and identical copy of this Group object */ - public Object clone(); + Object clone(); /** * Sets the back-reference to its parent Chain. @@ -268,7 +268,7 @@ public interface Group extends Serializable { * @see #getChain() * @since 3.0 */ - public void setChain(Chain chain); + void setChain(Chain chain); /** * Returns the parent Chain of the Group. @@ -277,7 +277,7 @@ public interface Group extends Serializable { * @see #setChain(Chain) * @since 3.0 */ - public Chain getChain() ; + Chain getChain() ; /** * Returns a dynamically created ResidueNumber for the group - this @@ -286,7 +286,7 @@ public interface Group extends Serializable { * @return ResidueNumber for the group. * @since 3.0 */ - public ResidueNumber getResidueNumber(); + ResidueNumber getResidueNumber(); /** @@ -294,7 +294,7 @@ public interface Group extends Serializable { * * @param residueNumber the PDB residueNumber */ - public void setResidueNumber(ResidueNumber residueNumber); + void setResidueNumber(ResidueNumber residueNumber); /** * Utility method to temporarily set a chainID for a group, if a parent chain object does not exist yet. @@ -304,7 +304,7 @@ public interface Group extends Serializable { * @param residueNumber * @param iCode */ - public void setResidueNumber(String chainId, Integer residueNumber, Character iCode); + void setResidueNumber(String chainId, Integer residueNumber, Character iCode); /** * Utility method for returning the chainId of the Group or null if no @@ -314,21 +314,21 @@ public interface Group extends Serializable { * @since 3.0 * @return the ID of the chain */ - public String getChainId(); + String getChainId(); /** * Set the Chemical Component that closer describes this group. * * @param cc the chemical component */ - public void setChemComp(ChemComp cc); + void setChemComp(ChemComp cc); /** * Get the chemical component that closer describes this group. If the information does not exist yet, fetches the information from PDB web site. * * @return the Chemical Component definition for this Group. */ - public ChemComp getChemComp(); + ChemComp getChemComp(); /** @@ -337,7 +337,7 @@ public interface Group extends Serializable { * @return boolean flag if there are alternate locations. * @see #getAltLocs() */ - public boolean hasAltLoc(); + boolean hasAltLoc(); /** @@ -363,14 +363,14 @@ public interface Group extends Serializable { * * @return List of other groups that are on alternate locations */ - public List getAltLocs(); + List getAltLocs(); /** * Add a group that is an alternate location for this group. * * @param g the altloc group to add */ - public void addAltLoc(Group g); + void addAltLoc(Group g); /** * Determines if this group is water. @@ -378,7 +378,7 @@ public interface Group extends Serializable { * @see GroupType#WATERNAMES * @return true if it's water, false otherwise. */ - public boolean isWater(); + boolean isWater(); /** * Gets the alternate location group to this group that has the alt-loc character code passed. @@ -386,7 +386,7 @@ public interface Group extends Serializable { * @param altLoc the alternate location code of the group desired * @return the alternate location group if found, or null otherwise */ - public Group getAltLocGroup(Character altLoc); + Group getAltLocGroup(Character altLoc); /** @@ -394,13 +394,13 @@ public interface Group extends Serializable { * all internal Collection objects to the required size. * */ - public void trimToSize(); + void trimToSize(); /** * Function to get the Group as an MDL molblock * @return the string of the MDL molblock */ - public String toSDF(); + String toSDF(); /** * Tells whether the group is annotated as HETATM in the file. @@ -408,7 +408,7 @@ public interface Group extends Serializable { * polymeric group is in a ligand chain or not. * @return */ - public boolean isHetAtomInFile(); + boolean isHetAtomInFile(); /** * Sets the field isHetAtomInFile which is intented only for @@ -416,5 +416,5 @@ public interface Group extends Serializable { * or in a polymeric chain. * @param isHetAtomInFile */ - public void setHetAtomInFile(boolean isHetAtomInFile); + void setHetAtomInFile(boolean isHetAtomInFile); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/GroupIterator.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/GroupIterator.java index a0e3c5be8b..4fa6a80a18 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/GroupIterator.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/GroupIterator.java @@ -38,7 +38,7 @@ public class GroupIterator implements Iterator { - private Structure structure ; + private final Structure structure ; private int current_model_pos ; private int current_chain_pos ; private int current_group_pos ; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/GroupType.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/GroupType.java index 234813ef42..304b9ac52b 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/GroupType.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/GroupType.java @@ -58,7 +58,7 @@ public enum GroupType { private final String name; private final Set types; - private GroupType(String name,Set types) { + GroupType(String name, Set types) { this.name = name; this.types = types; } @@ -95,7 +95,7 @@ public Set getResidueTypes() { * @return */ private static Set matchPolymerTypes(Set allowedTypes) { - Set matched = new HashSet(); + Set matched = EnumSet.noneOf(ResidueType.class); for(ResidueType restype : ResidueType.values()) { if(allowedTypes.contains(restype.polymerType)) { matched.add(restype); @@ -109,7 +109,7 @@ private static Set matchPolymerTypes(Set allowedTypes) * @return */ private static Set getHetatmTypes() { - Set unmatched = new HashSet(); + Set unmatched = EnumSet.noneOf(ResidueType.class); for(ResidueType restype : ResidueType.values()) { if(!AMINOACID.getResidueTypes().contains(restype) && !NUCLEOTIDE.getResidueTypes().contains(restype) ) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/HetatomImpl.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/HetatomImpl.java index 037dcb2b0b..ffd95ed824 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/HetatomImpl.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/HetatomImpl.java @@ -87,7 +87,7 @@ public enum PerformanceBehavior { } - private static PerformanceBehavior performanceBehavior=PerformanceBehavior.LESS_MEMORY_SLOWER_PERFORMANCE; + private static final PerformanceBehavior performanceBehavior=PerformanceBehavior.LESS_MEMORY_SLOWER_PERFORMANCE; private Map atomNameLookup; @@ -595,34 +595,28 @@ public boolean isWater() { public void trimToSize(){ if ( atoms instanceof ArrayList) { - ArrayList myatoms = (ArrayList) atoms; - myatoms.trimToSize(); + ((ArrayList) atoms).trimToSize(); } if ( altLocs instanceof ArrayList){ - ArrayList myAltLocs = (ArrayList) altLocs; - myAltLocs.trimToSize(); + ((ArrayList) altLocs).trimToSize(); } if ( hasAltLoc()) { - for (Group alt : getAltLocs()){ + for (Group alt : getAltLocs()) alt.trimToSize(); - } } - // now let's fit the hashmaps to size - properties = new HashMap<>(properties); - - if ( atomNameLookup != null) - atomNameLookup = new HashMap<>(atomNameLookup); - +// // now let's fit the hashmaps to size +// properties = new HashMap<>(properties); +// if ( atomNameLookup != null) +// atomNameLookup = new HashMap<>(atomNameLookup); } @Override public String toSDF() { // Function to return the SDF of a given strucutre - GroupToSDF gts = new GroupToSDF(); - return gts.getText(this); + return new GroupToSDF().getText(this); } @Override diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/JournalArticle.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/JournalArticle.java index ff92f608f6..4b17317d79 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/JournalArticle.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/JournalArticle.java @@ -32,8 +32,8 @@ public class JournalArticle implements Serializable { private static final long serialVersionUID = 5062668226159515468L; - private List authorList = new ArrayList(); - private List editorList = new ArrayList(); + private List authorList = new ArrayList<>(); + private List editorList = new ArrayList<>(); private String title = ""; private String ref = ""; private String journalName = ""; @@ -258,19 +258,19 @@ public String toString() { } refString.append(ref); jrnlString.append(refString).append(eol); - if (!publisher.equals("")) { + if (!publisher.isEmpty()) { publString.append(publisher); jrnlString.append(publString).append(eol); } - if (!refn.equals("")) { + if (!refn.isEmpty()) { refnString.append(refn); jrnlString.append(refnString).append(eol); } - if (!pmid.equals("")) { + if (!pmid.isEmpty()) { pmidString.append(pmid); jrnlString.append(pmidString).append(eol); } - if (!doi.equals("")) { + if (!doi.isEmpty()) { doiString.append(doi); jrnlString.append(doiString).append(eol); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/Model.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/Model.java index 36cce008cb..1951d82e07 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/Model.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/Model.java @@ -20,13 +20,13 @@ */ package org.biojava.nbio.structure; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * An internal utility class for StructureImpl to make it easier to manage poly and nonpoly chains. * Not to exposed to users through API. @@ -41,9 +41,9 @@ public class Model implements Serializable { private static final Logger logger = LoggerFactory.getLogger(Model.class); - private List polyChains; - private List nonPolyChains; - private List waterChains; + private final List polyChains; + private final List nonPolyChains; + private final List waterChains; public Model(){ polyChains = new ArrayList<>(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/Mutator.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/Mutator.java index 42e4662689..c9223e18f2 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/Mutator.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/Mutator.java @@ -20,8 +20,6 @@ package org.biojava.nbio.structure; -import org.biojava.nbio.structure.io.PDBParseException; - import java.util.ArrayList; import java.util.List; @@ -56,10 +54,10 @@ * @version %I% %G% */ public class Mutator{ - List supportedAtoms; + final List supportedAtoms; public Mutator(){ - supportedAtoms = new ArrayList(); + supportedAtoms = new ArrayList<>(); supportedAtoms.add("N"); supportedAtoms.add("CA"); supportedAtoms.add("C"); @@ -78,10 +76,8 @@ public Mutator(){ * @param pdbResnum the PDB residue number of the residue * @param newType the new residue type (3 characters) * @return a structure object where one residue has been modified - * @throws PDBParseException - */ - public Structure mutate(Structure struc, String chainId, String pdbResnum, String newType) - throws PDBParseException{ + */ + public Structure mutate(Structure struc, String chainId, String pdbResnum, String newType) { // create a container for the new structure @@ -138,10 +134,8 @@ public Structure mutate(Structure struc, String chainId, String pdbResnum, Stri * @param oldAmino * @param newType * @return a new, mutated, residue - * @throws PDBParseException */ - public AminoAcid mutateResidue(AminoAcid oldAmino, String newType) - throws PDBParseException { + public AminoAcid mutateResidue(AminoAcid oldAmino, String newType) { AminoAcid newgroup = new AminoAcidImpl(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/PDBHeader.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/PDBHeader.java index dbcc0f794c..0a357f6bf1 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/PDBHeader.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/PDBHeader.java @@ -73,7 +73,7 @@ public class PDBHeader implements PDBRecord { private Long id; public static final String newline = System.getProperty("line.separator"); - private DateFormat dateFormat; + private final DateFormat dateFormat; private Map bioAssemblies ; @@ -90,7 +90,7 @@ public PDBHeader(){ rFree = DEFAULT_RFREE; rWork = DEFAULT_RFREE; - bioAssemblies = new LinkedHashMap(); + bioAssemblies = new LinkedHashMap<>(); crystallographicInfo = new PDBCrystallographicInfo(); } @@ -111,22 +111,20 @@ public String toString(){ for (Method m : methods) { String name = m.getName(); - if (name.substring(0, 3).equals("get")) { + if (name.startsWith("get")) { if (name.equals("getClass")) { continue; } Object o = m.invoke(this); if (o != null) { - buf.append(name.substring(3, name.length())); + buf.append(name.substring(3)); buf.append(": ").append(o).append(" "); } } } } catch (ClassNotFoundException e) { logger.error("Exception caught while creating toString ",e); - } catch (InvocationTargetException e) { - logger.error("Exception caught while creating toString ",e); - } catch (IllegalAccessException e) { + } catch (InvocationTargetException | IllegalAccessException e) { logger.error("Exception caught while creating toString ",e); } @@ -216,7 +214,7 @@ private void printAuthors(StringBuffer buf){ String authors = getAuthors(); if ( authors == null) return; - if ( authors.equals("")){ + if (authors.isEmpty()){ return; } @@ -224,7 +222,7 @@ private void printAuthors(StringBuffer buf){ } - private void printMultiLine(StringBuffer buf, String lineStart, String data, char breakChar){ + private static void printMultiLine(StringBuffer buf, String lineStart, String data, char breakChar){ if ( lineStart.length() != 9) logger.info("lineStart != 9, there will be problems :" + lineStart); @@ -308,7 +306,7 @@ private void printMultiLine(StringBuffer buf, String lineStart, String data, cha } - private void fillLine(StringBuffer buf, int currentPos){ + private static void fillLine(StringBuffer buf, int currentPos){ int l = currentPos; while (l < 67){ l++; @@ -408,7 +406,7 @@ public boolean equals(PDBHeader other){ for (Method m : methods) { String name = m.getName(); - if (name.substring(0, 3).equals("get")) { + if (name.startsWith("get")) { if (name.equals("getClass")) { continue; } @@ -432,13 +430,7 @@ public boolean equals(PDBHeader other){ } } } - } catch (ClassNotFoundException e) { - logger.error("Exception caught while comparing PDBHeader objects ",e); - return false; - } catch (InvocationTargetException e) { - logger.error("Exception caught while comparing PDBHeader objects ",e); - return false; - } catch (IllegalAccessException e) { + } catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException e) { logger.error("Exception caught while comparing PDBHeader objects ",e); return false; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/PDBRecord.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/PDBRecord.java index eb3b2b3e5a..0850c1b62c 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/PDBRecord.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/PDBRecord.java @@ -34,13 +34,13 @@ public interface PDBRecord extends Serializable { * * @return a String providing a PDB file like representation of the record. */ - public String toPDB(); + String toPDB(); /** Appends a PDB file like representation of this record to the provided StringBuffer. * */ - public void toPDB(StringBuffer buf); + void toPDB(StringBuffer buf); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/PDBStatus.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/PDBStatus.java index dfb95eab8e..990fd0bab1 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/PDBStatus.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/PDBStatus.java @@ -77,632 +77,613 @@ */ public class PDBStatus { - private static final Logger logger = LoggerFactory.getLogger(PDBStatus.class); - - public static final String DEFAULT_PDB_SERVER = "www.rcsb.org"; - public static final String PDB_SERVER_PROPERTY = "PDB.SERVER"; - - /** - * saves the returned results for further use. - * - */ - //TODO Use SoftReferences to allow garbage collection - private static Map> recordsCache= new Hashtable>(); - - /** - * Represents the status of PDB IDs. 'OBSOLETE' and 'CURRENT' are the most - * common. - * @author Spencer Bliven - * - */ - public enum Status { - OBSOLETE, - CURRENT, - AUTH, - HOLD, - HPUB, - POLC, - PROC, - REFI, - REPL, - WAIT, - WDRN, - MODEL, - UNKNOWN; - - - /** - * - * @param statusStr - * @return - * @throws IllegalArgumentException If the string is not recognized - */ - public static Status fromString(String statusStr) { - Status status; - String statusStrUpper = statusStr.toUpperCase(); - if(statusStrUpper.equalsIgnoreCase("OBSOLETE")) - status = Status.OBSOLETE; - else if(statusStrUpper.equalsIgnoreCase("CURRENT")) - status = Status.CURRENT; - else if(statusStrUpper.equalsIgnoreCase("AUTH")) - status = Status.AUTH; - else if(statusStrUpper.equalsIgnoreCase("HOLD")) - status = Status.HOLD; - else if(statusStrUpper.equalsIgnoreCase("HPUB")) - status = Status.HPUB; - else if(statusStrUpper.equalsIgnoreCase("POLC")) - status = Status.POLC; - else if(statusStrUpper.equalsIgnoreCase("PROC")) - status = Status.PROC; - else if(statusStrUpper.equalsIgnoreCase("REFI")) - status = Status.REFI; - else if(statusStrUpper.equalsIgnoreCase("REPL")) - status = Status.REPL; - else if(statusStrUpper.equalsIgnoreCase("WAIT")) - status = Status.WAIT; - else if(statusStrUpper.equalsIgnoreCase("WDRN")) - status = Status.WDRN; - else if(statusStrUpper.equalsIgnoreCase("MODEL")) - status = Status.MODEL; - else if(statusStrUpper.equalsIgnoreCase("UNKNOWN")) - status = Status.UNKNOWN; - else { - throw new IllegalArgumentException("Unable to parse status '"+statusStrUpper+"'."); - } - return status; - } - } - - /** - * Get the status of the PDB in question. - * - * @param pdbId - * @return The status, or null if an error occurred. - */ - public static Status getStatus(String pdbId) { - Status[] statuses = getStatus(new String[] {pdbId}); - if(statuses != null) { - assert(statuses.length == 1); - return statuses[0]; - } else { - return null; - } - } - - /** - * Get the status of the a collection of PDBs in question in a single query. - * - * @see #getStatus(String) - * @param pdbIds - * @return The status array, or null if an error occurred. - */ - public static Status[] getStatus(String[] pdbIds) { - Status[] statuses = new Status[pdbIds.length]; - - List> attrList = getStatusIdRecords(pdbIds); - //Expect a single record - if(attrList == null || attrList.size() != pdbIds.length) { - logger.error("Error getting Status for {} from the PDB website.", Arrays.toString(pdbIds)); - return null; - } - - - for(int pdbNum = 0;pdbNum attrs : attrList) { - - //Check that the record matches pdbId - String id = attrs.get("structureId"); - if(id == null || !id.equalsIgnoreCase(pdbIds[pdbNum])) { - continue; - } - - //Check that the status is given - String statusStr = attrs.get("status"); - Status status = null; - if(statusStr == null ) { - logger.error("No status returned for {}", pdbIds[pdbNum]); - statuses[pdbNum] = null; - } else { - status = Status.fromString(statusStr); - } - - if(status == null) { - logger.error("Unknown status '{}'", statusStr); - statuses[pdbNum] = null; - } - - statuses[pdbNum] = status; - foundAttr = true; - } - if(!foundAttr) { - logger.error("No result found for {}", pdbIds[pdbNum]); - statuses[pdbNum] = null; - } - } - - return statuses; - } - - /** - * Gets the current version of a PDB ID. This is equivalent to selecting - * the first element from - * {@link #getReplacement(String,boolean,boolean) - * - * @param oldPdbId - * @return The replacement for oldPdbId, or null if none are found or if an error occurred. - */ - public static String getCurrent(String oldPdbId) { - List replacements = getReplacement(oldPdbId,true, false); - if(replacements != null && !replacements.isEmpty()) - return replacements.get(0); - else - return null; - } - - /** - * Gets the PDB which superseded oldPdbId. For CURRENT IDs, this will - * be itself. For obsolete IDs, the behavior depends on the recursion - * parameter. If false, only IDs which directly supersede oldPdbId are - * returned. If true, the replacements for obsolete records are recursively - * fetched, yielding a list of all current replacements of oldPdbId. - * - * - * - * @param oldPdbId A pdb ID - * @param recurse Indicates whether the replacements for obsolete records - * should be fetched. - * @param includeObsolete Indicates whether obsolete records should be - * included in the results. - * @return The PDB which replaced oldPdbId. This may be oldPdbId itself, for - * current records. A return value of null indicates that the ID has - * been removed from the PDB or that an error has occurred. - */ - public static List getReplacement(String oldPdbId, boolean recurse, boolean includeObsolete) { - List> attrList = getStatusIdRecords(new String[] {oldPdbId}); - //Expect a single record - if(attrList == null || attrList.size() != 1) { - logger.error("Error getting Status for {} from the PDB website.", oldPdbId); - return null; - } - - Map attrs = attrList.get(0); - - //Check that the record matches pdbId - String id = attrs.get("structureId"); - if(id == null || !id.equalsIgnoreCase(oldPdbId)) { - logger.error("Results returned from the query don't match {}", oldPdbId); - return null; - } - - //Check that the status is given - String statusStr = attrs.get("status"); - if(statusStr == null ) { - logger.error("No status returned for {}", oldPdbId); - return null; - } - - Status status = Status.fromString(statusStr); - if(status == null ) { - logger.error("Unknown status '{}'", statusStr); - return null; - } - - // If we're current, just return - LinkedList results = new LinkedList(); - switch(status) { - case CURRENT: - results.add(oldPdbId); - return results; - case OBSOLETE: { - String replacementStr = attrs.get("replacedBy"); - if(replacementStr == null) { - logger.error("{} is OBSOLETE but lacks a replacedBy attribute.", oldPdbId); - return null; - } - replacementStr = replacementStr.toUpperCase(); - //include this result - if(includeObsolete) { - results.add(oldPdbId); - } - // Some PDBs are not replaced. - if(replacementStr.equals("NONE")) { - return results; //empty - } - - String[] replacements = replacementStr.split(" "); - Arrays.sort(replacements, new Comparator() { - @Override - public int compare(String o1, String o2) { - return o2.compareToIgnoreCase(o1); - } - }); - for(String replacement : replacements) { - - // Return the replacement. - if(recurse) { - List others = PDBStatus.getReplacement(replacement, recurse, includeObsolete); - mergeReversed(results,others); + private static final Logger logger = LoggerFactory.getLogger(PDBStatus.class); + + public static final String DEFAULT_PDB_SERVER = "www.rcsb.org"; + public static final String PDB_SERVER_PROPERTY = "PDB.SERVER"; + + /** + * saves the returned results for further use. + * + */ + //TODO Use SoftReferences to allow garbage collection + private static final Map> recordsCache = new Hashtable<>(); + + /** + * Represents the status of PDB IDs. 'OBSOLETE' and 'CURRENT' are the most + * common. + * @author Spencer Bliven + * + */ + public enum Status { + OBSOLETE, + CURRENT, + AUTH, + HOLD, + HPUB, + POLC, + PROC, + REFI, + REPL, + WAIT, + WDRN, + MODEL, + UNKNOWN; + + + /** + * + * @param statusStr + * @return + * @throws IllegalArgumentException If the string is not recognized + */ + public static Status fromString(String statusStr) { + Status status; + String statusStrUpper = statusStr.toUpperCase(); + if (statusStrUpper.equalsIgnoreCase("OBSOLETE")) + status = Status.OBSOLETE; + else if (statusStrUpper.equalsIgnoreCase("CURRENT")) + status = Status.CURRENT; + else if (statusStrUpper.equalsIgnoreCase("AUTH")) + status = Status.AUTH; + else if (statusStrUpper.equalsIgnoreCase("HOLD")) + status = Status.HOLD; + else if (statusStrUpper.equalsIgnoreCase("HPUB")) + status = Status.HPUB; + else if (statusStrUpper.equalsIgnoreCase("POLC")) + status = Status.POLC; + else if (statusStrUpper.equalsIgnoreCase("PROC")) + status = Status.PROC; + else if (statusStrUpper.equalsIgnoreCase("REFI")) + status = Status.REFI; + else if (statusStrUpper.equalsIgnoreCase("REPL")) + status = Status.REPL; + else if (statusStrUpper.equalsIgnoreCase("WAIT")) + status = Status.WAIT; + else if (statusStrUpper.equalsIgnoreCase("WDRN")) + status = Status.WDRN; + else if (statusStrUpper.equalsIgnoreCase("MODEL")) + status = Status.MODEL; + else if (statusStrUpper.equalsIgnoreCase("UNKNOWN")) + status = Status.UNKNOWN; + else { + throw new IllegalArgumentException("Unable to parse status '" + statusStrUpper + "'."); + } + return status; + } + } + + /** + * Get the status of the PDB in question. + * + * @param pdbId + * @return The status, or null if an error occurred. + */ + public static Status getStatus(String pdbId) { + Status[] statuses = getStatus(new String[]{pdbId}); + if (statuses != null) { + assert (statuses.length == 1); + return statuses[0]; + } else { + return null; + } + } + + /** + * Get the status of the a collection of PDBs in question in a single query. + * + * @see #getStatus(String) + * @param pdbIds + * @return The status array, or null if an error occurred. + */ + public static Status[] getStatus(String[] pdbIds) { + Status[] statuses = new Status[pdbIds.length]; + + List> attrList = getStatusIdRecords(pdbIds); + //Expect a single record + if (attrList == null || attrList.size() != pdbIds.length) { + logger.error("Error getting Status for {} from the PDB website.", Arrays.toString(pdbIds)); + return null; + } + + + for (int pdbNum = 0; pdbNum < pdbIds.length; pdbNum++) { + //Locate first element of attrList with matching structureId. + //attrList is usually short, so don't worry about performance + boolean foundAttr = false; + for (Map attrs : attrList) { + + //Check that the record matches pdbId + String id = attrs.get("structureId"); + if (id == null || !id.equalsIgnoreCase(pdbIds[pdbNum])) { + continue; + } + + //Check that the status is given + String statusStr = attrs.get("status"); + Status status = null; + if (statusStr == null) { + logger.error("No status returned for {}", pdbIds[pdbNum]); + statuses[pdbNum] = null; + } else { + status = Status.fromString(statusStr); + } + + if (status == null) { + logger.error("Unknown status '{}'", statusStr); + statuses[pdbNum] = null; + } + + statuses[pdbNum] = status; + foundAttr = true; + } + if (!foundAttr) { + logger.error("No result found for {}", pdbIds[pdbNum]); + statuses[pdbNum] = null; + } + } + + return statuses; + } + + /** + * Gets the current version of a PDB ID. This is equivalent to selecting + * the first element from + * {@link #getReplacement(String, boolean, boolean) + * + * @param oldPdbId + * @return The replacement for oldPdbId, or null if none are found or if an error occurred. + */ + public static String getCurrent(String oldPdbId) { + List replacements = getReplacement(oldPdbId, true, false); + if (replacements != null && !replacements.isEmpty()) + return replacements.get(0); + else + return null; + } + + /** + * Gets the PDB which superseded oldPdbId. For CURRENT IDs, this will + * be itself. For obsolete IDs, the behavior depends on the recursion + * parameter. If false, only IDs which directly supersede oldPdbId are + * returned. If true, the replacements for obsolete records are recursively + * fetched, yielding a list of all current replacements of oldPdbId. + * + * + * + * @param oldPdbId A pdb ID + * @param recurse Indicates whether the replacements for obsolete records + * should be fetched. + * @param includeObsolete Indicates whether obsolete records should be + * included in the results. + * @return The PDB which replaced oldPdbId. This may be oldPdbId itself, for + * current records. A return value of null indicates that the ID has + * been removed from the PDB or that an error has occurred. + */ + public static List getReplacement(String oldPdbId, boolean recurse, boolean includeObsolete) { + List> attrList = getStatusIdRecords(oldPdbId); + //Expect a single record + if (attrList == null || attrList.size() != 1) { + logger.error("Error getting Status for {} from the PDB website.", oldPdbId); + return null; + } + + Map attrs = attrList.get(0); + + //Check that the record matches pdbId + String id = attrs.get("structureId"); + if (id == null || !id.equalsIgnoreCase(oldPdbId)) { + logger.error("Results returned from the query don't match {}", oldPdbId); + return null; + } + + //Check that the status is given + String statusStr = attrs.get("status"); + if (statusStr == null) { + logger.error("No status returned for {}", oldPdbId); + return null; + } + + Status status = Status.fromString(statusStr); + if (status == null) { + logger.error("Unknown status '{}'", statusStr); + return null; + } + + // If we're current, just return + LinkedList results = new LinkedList<>(); + switch (status) { + case CURRENT: + results.add(oldPdbId); + return results; + case OBSOLETE: { + String replacementStr = attrs.get("replacedBy"); + if (replacementStr == null) { + logger.error("{} is OBSOLETE but lacks a replacedBy attribute.", oldPdbId); + return null; + } + replacementStr = replacementStr.toUpperCase(); + //include this result + if (includeObsolete) { + results.add(oldPdbId); + } + // Some PDBs are not replaced. + if (replacementStr.equals("NONE")) { + return results; //empty + } + + String[] replacements = replacementStr.split(" "); + Arrays.sort(replacements, (o1, o2) -> o2.compareToIgnoreCase(o1)); + for (String replacement : replacements) { + + // Return the replacement. + if (recurse) { + List others = PDBStatus.getReplacement(replacement, recurse, includeObsolete); + mergeReversed(results, others); + } else { + if (includeObsolete) { + mergeReversed(results, Collections.singletonList(replacement)); + } else { + // check status of replacement + Status replacementStatus = getStatus(replacement); + switch (replacementStatus) { + case OBSOLETE: + //ignore obsolete + break; + case CURRENT: + default: + // include it + mergeReversed(results, Collections.singletonList(replacement)); + } + } + } + } + + + return results; + } + case UNKNOWN: + return null; + default: { //TODO handle other cases explicitly. They might have other syntax than "replacedBy" + String replacementStr = attrs.get("replacedBy"); + + if (replacementStr == null) { + // If no "replacedBy" attribute, treat like we're current + // TODO is this correct? + results.add(oldPdbId); + return results; + } + + replacementStr = replacementStr.toUpperCase(); + // Some PDBs are not replaced. + if (replacementStr.equals("NONE")) + return null; + + + //include this result, since it's not obsolete + results.add(oldPdbId); + + String[] replacements = replacementStr.split(" "); + Arrays.sort(replacements, (o1, o2) -> o2.compareToIgnoreCase(o1)); + for (String replacement : replacements) { + + // Return the replacement. + if (recurse) { + mergeReversed(results, PDBStatus.getReplacement(replacement, recurse, includeObsolete)); + } else { + mergeReversed(results, Collections.singletonList(replacement)); + } + } + + + return results; + } + } + } + + /** + * Takes two reverse sorted lists of strings and merges the second into the + * first. Duplicates are removed. + * + * @param merged A reverse sorted list. Modified by this method to contain + * the contents of other. + * @param other A reverse sorted list. Not modified. + */ + private static void mergeReversed(List merged, final List other) { + + if (other.isEmpty()) + return; + + if (merged.isEmpty()) { + merged.addAll(other); + return; + } + + ListIterator o = other.listIterator(); + + if (o.hasNext()) { + String nextM, prevO; + ListIterator m = merged.listIterator(); + prevO = o.next(); + while (m.hasNext()) { + // peek at m + nextM = m.next(); + m.previous(); + + //insert from O until exhausted or occurs after nextM + while (prevO.compareTo(nextM) > 0) { + m.add(prevO); + if (!o.hasNext()) { + return; } - else { - if(includeObsolete) { - mergeReversed(results,Arrays.asList(replacement)); - } else { - // check status of replacement - Status replacementStatus = getStatus(replacement); - switch(replacementStatus) { - case OBSOLETE: - //ignore obsolete - break; - case CURRENT: - default: - // include it - mergeReversed(results,Arrays.asList(replacement)); - } - } - } - } - - - return results; - } - case UNKNOWN: - return null; - default: { //TODO handle other cases explicitly. They might have other syntax than "replacedBy" - String replacementStr = attrs.get("replacedBy"); - - if(replacementStr == null) { - // If no "replacedBy" attribute, treat like we're current - // TODO is this correct? - results.add(oldPdbId); - return results; - } - - replacementStr = replacementStr.toUpperCase(); - // Some PDBs are not replaced. - if(replacementStr.equals("NONE")) { - return null; + prevO = o.next(); } - - - //include this result, since it's not obsolete - results.add(oldPdbId); - - String[] replacements = replacementStr.split(" "); - Arrays.sort(replacements, new Comparator() { - @Override - public int compare(String o1, String o2) { - return o2.compareToIgnoreCase(o1); - } - }); - for(String replacement : replacements) { - - // Return the replacement. - if(recurse) { - List others = PDBStatus.getReplacement(replacement, recurse, includeObsolete); - mergeReversed(results,others); - } - else { - mergeReversed(results,Arrays.asList(replacement)); + //remove duplicates + if (prevO.equals(nextM)) { + if (!o.hasNext()) { + return; } + prevO = o.next(); } - - return results; + m.next(); } - } - } - - /** - * Takes two reverse sorted lists of strings and merges the second into the - * first. Duplicates are removed. - * - * @param merged A reverse sorted list. Modified by this method to contain - * the contents of other. - * @param other A reverse sorted list. Not modified. - */ - private static void mergeReversed(List merged, - final List other) { - - if(other.isEmpty()) - return; - - if(merged.isEmpty()) { - merged.addAll(other); - return; - } - - ListIterator m = merged.listIterator(); - ListIterator o = other.listIterator(); - - String nextM, prevO; - prevO = o.next(); - while(m.hasNext()) { - // peek at m - nextM = m.next(); - m.previous(); - - //insert from O until exhausted or occurs after nextM - while(prevO.compareTo(nextM) > 0) { - m.add(prevO); - if(!o.hasNext()) { - return; - } - prevO = o.next(); - } - //remove duplicates - if(prevO.equals(nextM)) { - if(!o.hasNext()) { - return; - } - prevO = o.next(); - } - - m.next(); - } - m.add(prevO); - while(o.hasNext()) { - m.add(o.next()); - } - - } - - - /** - * Get the ID of the protein which was made obsolete by newPdbId. - * - * @param newPdbId PDB ID of the newer structure - * @param recurse If true, return all ancestors of newPdbId. - * Otherwise, just go one step newer than oldPdbId. - * @return A (possibly empty) list of ID(s) of the ancestor(s) of - * newPdbId, or null if an error occurred. - */ - public static List getReplaces(String newPdbId, boolean recurse) { - List> attrList = getStatusIdRecords(new String[] {newPdbId}); - //Expect a single record - if(attrList == null || attrList.size() != 1) { - //TODO Is it possible to have multiple record per ID? - // They seem to be combined into one record with space-delimited 'replaces' - logger.error("Error getting Status for {} from the PDB website.", newPdbId); - return null; - } - - Map attrs = attrList.get(0); - - //Check that the record matches pdbId - String id = attrs.get("structureId"); - if(id == null || !id.equals(newPdbId)) { - logger.error("Results returned from the query don't match {}", newPdbId); - return null; - } - - - String replacedList = attrs.get("replaces"); //space-delimited list - if(replacedList == null) { - // no replaces value; assume root - return new ArrayList(); - } - String[] directDescendents = replacedList.split("\\s"); - - // Not the root! Return the replaced PDB. - if(recurse) { - // Note: Assumes a proper directed acyclic graph of revisions - // Cycles will cause infinite loops. - List allDescendents = new LinkedList(); - for(String replaced : directDescendents) { - List roots = PDBStatus.getReplaces(replaced, recurse); - mergeReversed(allDescendents,roots); - } - mergeReversed(allDescendents,Arrays.asList(directDescendents)); - - return allDescendents; - } else { - return Arrays.asList(directDescendents); - } - } - - - /** - * The status of PDB IDs are cached to reduce server overload. - * - * This method clears the cached records. - */ - public static void clearCache() { - recordsCache.clear(); - } - - /** - * Fetches the status of one or more pdbIDs from the server. - * - *

    Returns the results as a list of Attributes. - * Each attribute should contain "structureId" and "status" attributes, and - * possibly more. - * - *

    Example:
    - * http://www.rcsb.org/pdb/rest/idStatus?structureID=1HHB,4HHB
    - *

    <idStatus>
    -	 *  <record structureId="1HHB" status="OBSOLETE" replacedBy="4HHB"/>
    -	 *  <record structureId="4HHB" status="CURRENT" replaces="1HHB"/>
    -	 *</idStatus>
    -	 * 
    - * - *

    Results are not guaranteed to be returned in the same order as pdbIDs. - * Refer to the structureId property to match them. - * - * @param pdbIDs - * @return A map between attributes and values - */ - private static List> getStatusIdRecords(String[] pdbIDs) { - - List> result = new ArrayList>(pdbIDs.length); - - String serverName = System.getProperty(PDB_SERVER_PROPERTY); - - if ( serverName == null) - serverName = DEFAULT_PDB_SERVER; - else - logger.info(String.format("Got System property %s=%s",PDB_SERVER_PROPERTY,serverName)); - - // Build REST query URL - if(pdbIDs.length < 1) { - throw new IllegalArgumentException("No pdbIDs specified"); - } - String urlStr = String.format("http://%s/pdb/rest/idStatus?structureId=",serverName); - for(String pdbId : pdbIDs) { - pdbId = pdbId.toUpperCase(); - //check the cache - if (recordsCache.containsKey(pdbId)) { - //logger.debug("Fetching "+pdbId+" from Cache"); - result.add( recordsCache.get(pdbId) ); - } else { - urlStr += pdbId + ","; - } - } - - // check if any ids still need fetching - if(urlStr.charAt(urlStr.length()-1) == '=') { - return result; - } - - try { - logger.info("Fetching {}", urlStr); - - URL url = new URL(urlStr); - - InputStream uStream = url.openStream(); - - InputSource source = new InputSource(uStream); - SAXParserFactory parserFactory = SAXParserFactory.newInstance(); - SAXParser parser = parserFactory.newSAXParser(); - XMLReader reader = parser.getXMLReader(); - - PDBStatusXMLHandler handler = new PDBStatusXMLHandler(); - - reader.setContentHandler(handler); - reader.parse(source); - - // Fetch results of SAX parsing - List> records = handler.getRecords(); - - //add to cache - for(Map record : records) { - String pdbId = record.get("structureId").toUpperCase(); - if(pdbId != null) { - recordsCache.put(pdbId, record); - } - } - - // return results - result.addAll(handler.getRecords()); - - // TODO should throw these forward and let the caller log - } catch (IOException e){ - logger.error("Problem getting status for {} from PDB server. Error: {}", Arrays.toString(pdbIDs), e.getMessage()); - return null; - } catch (SAXException e) { - logger.error("Problem getting status for {} from PDB server. Error: {}", Arrays.toString(pdbIDs), e.getMessage()); - return null; - } catch (ParserConfigurationException e) { - logger.error("Problem getting status for {} from PDB server. Error: {}", Arrays.toString(pdbIDs), e.getMessage()); - return null; - } - - return result; - } - - /** - * Handles idStatus xml by storing attributes for all record elements. - * - * @author Spencer Bliven - * - */ - private static class PDBStatusXMLHandler extends DefaultHandler { - private List> records; - - public PDBStatusXMLHandler() { - records = new ArrayList>(); - } - - /** - * @param uri - * @param localName - * @param qName - * @param attributes - * @throws SAXException - * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) - */ - @Override - public void startElement(String uri, String localName, String qName, - Attributes attributes) throws SAXException { - //System.out.format("Starting element: uri='%s' localName='%s' qName='%s'\n", uri, localName, qName); - if(qName.equals("record")) { - //Convert attributes into a Map, as it should have been. - //Important since SAX reuses Attributes objects for different calls - Map attrMap = new HashMap(attributes.getLength()*2); - for(int i=0;i> getRecords() { - return records; - } - } - - /** Returns a list of current PDB IDs - * - * @return a list of PDB IDs, or null if a problem occurred - */ - - public static SortedSet getCurrentPDBIds() throws IOException { - - SortedSet allPDBs = new TreeSet(); - String serverName = System.getProperty(PDB_SERVER_PROPERTY); - - if ( serverName == null) - serverName = DEFAULT_PDB_SERVER; - else - logger.info(String.format("Got System property %s=%s",PDB_SERVER_PROPERTY,serverName)); - - // Build REST query URL - - String urlStr = String.format("http://%s/pdb/rest/getCurrent",serverName); - URL u = new URL(urlStr); - - InputStream stream = URLConnectionTools.getInputStream(u, 60000); - - if (stream != null) { - BufferedReader reader = new BufferedReader( - new InputStreamReader(stream)); - - String line = null; - - while ((line = reader.readLine()) != null) { - int index = line.lastIndexOf("structureId="); - if (index > 0) { - allPDBs.add(line.substring(index + 13, index + 17)); - } + m.add(prevO); + while (o.hasNext()) { + m.add(o.next()); } } - return allPDBs; - } + } + + + /** + * Get the ID of the protein which was made obsolete by newPdbId. + * + * @param newPdbId PDB ID of the newer structure + * @param recurse If true, return all ancestors of newPdbId. + * Otherwise, just go one step newer than oldPdbId. + * @return A (possibly empty) list of ID(s) of the ancestor(s) of + * newPdbId, or null if an error occurred. + */ + public static List getReplaces(String newPdbId, boolean recurse) { + List> attrList = getStatusIdRecords(newPdbId); + //Expect a single record + if (attrList == null || attrList.size() != 1) { + //TODO Is it possible to have multiple record per ID? + // They seem to be combined into one record with space-delimited 'replaces' + logger.error("Error getting Status for {} from the PDB website.", newPdbId); + return null; + } + + Map attrs = attrList.get(0); + + //Check that the record matches pdbId + String id = attrs.get("structureId"); + if (id == null || !id.equals(newPdbId)) { + logger.error("Results returned from the query don't match {}", newPdbId); + return null; + } + + + String replacedList = attrs.get("replaces"); //space-delimited list + if (replacedList == null) { + // no replaces value; assume root + return new ArrayList<>(); + } + String[] directDescendents = replacedList.split("\\s"); + + // Not the root! Return the replaced PDB. + if (recurse) { + // Note: Assumes a proper directed acyclic graph of revisions + // Cycles will cause infinite loops. + List allDescendents = new LinkedList<>(); + for (String replaced : directDescendents) { + List roots = PDBStatus.getReplaces(replaced, recurse); + mergeReversed(allDescendents, roots); + } + mergeReversed(allDescendents, Arrays.asList(directDescendents)); + + return allDescendents; + } else { + return Arrays.asList(directDescendents); + } + } + + + /** + * The status of PDB IDs are cached to reduce server overload. + * + * This method clears the cached records. + */ + public static void clearCache() { + recordsCache.clear(); + } + + /** + * Fetches the status of one or more pdbIDs from the server. + * + *

    Returns the results as a list of Attributes. + * Each attribute should contain "structureId" and "status" attributes, and + * possibly more. + * + *

    Example:
    + * http://www.rcsb.org/pdb/rest/idStatus?structureID=1HHB,4HHB
    + *

    <idStatus>
    +     *  <record structureId="1HHB" status="OBSOLETE" replacedBy="4HHB"/>
    +     *  <record structureId="4HHB" status="CURRENT" replaces="1HHB"/>
    +     *</idStatus>
    +     * 
    + * + *

    Results are not guaranteed to be returned in the same order as pdbIDs. + * Refer to the structureId property to match them. + * + * @param pdbIDs + * @return A map between attributes and values + */ + private static List> getStatusIdRecords(String... pdbIDs) { + + List> result = new ArrayList<>(pdbIDs.length); + + String serverName = System.getProperty(PDB_SERVER_PROPERTY); + + if (serverName == null) + serverName = DEFAULT_PDB_SERVER; + else + logger.info(String.format("Got System property %s=%s", PDB_SERVER_PROPERTY, serverName)); + + // Build REST query URL + if (pdbIDs.length < 1) { + throw new IllegalArgumentException("No pdbIDs specified"); + } + String urlStr = String.format("http://%s/pdb/rest/idStatus?structureId=", serverName); + for (String pdbId : pdbIDs) { + pdbId = pdbId.toUpperCase(); + //check the cache + Map theResult = recordsCache.get(pdbId); + if (theResult != null) { + //logger.debug("Fetching "+pdbId+" from Cache"); + result.add(theResult); + } else { + urlStr += pdbId + ","; + } + } + + // check if any ids still need fetching + if (urlStr.charAt(urlStr.length() - 1) == '=') + return result; + + + try { + logger.info("Fetching {}", urlStr); + + URL url = new URL(urlStr); + + InputStream uStream = url.openStream(); + + InputSource source = new InputSource(uStream); + SAXParserFactory parserFactory = SAXParserFactory.newInstance(); + SAXParser parser = parserFactory.newSAXParser(); + XMLReader reader = parser.getXMLReader(); + + PDBStatusXMLHandler handler = new PDBStatusXMLHandler(); + + reader.setContentHandler(handler); + reader.parse(source); + + // Fetch results of SAX parsing + List> records = handler.getRecords(); + + //add to cache + for (Map record : records) { + String pdbId = record.get("structureId").toUpperCase(); + if (pdbId != null) { + recordsCache.put(pdbId, record); + } + } + + // return results + result.addAll(handler.getRecords()); + + // TODO should throw these forward and let the caller log + } catch (IOException | ParserConfigurationException | SAXException e) { + logger.error("Problem getting status for {} from PDB server. Error: {}", Arrays.toString(pdbIDs), e.getMessage()); + return null; + } + + return result; + } + + /** + * Handles idStatus xml by storing attributes for all record elements. + * + * @author Spencer Bliven + * + */ + private static class PDBStatusXMLHandler extends DefaultHandler { + private final List> records; + + public PDBStatusXMLHandler() { + records = new ArrayList<>(); + } + + /** + * @param uri + * @param localName + * @param qName + * @param attributes + * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) + */ + @Override + public void startElement(String uri, String localName, String qName, + Attributes attributes) { + //System.out.format("Starting element: uri='%s' localName='%s' qName='%s'\n", uri, localName, qName); + if (qName.equals("record")) { + //Convert attributes into a Map, as it should have been. + //Important since SAX reuses Attributes objects for different calls + Map attrMap = new HashMap<>(attributes.getLength() * 2); + for (int i = 0; i < attributes.getLength(); i++) { + attrMap.put(attributes.getQName(i), attributes.getValue(i)); + } + records.add(attrMap); + } + } + + + /** + * @param e + * @throws SAXException + * @see org.xml.sax.helpers.DefaultHandler#error(org.xml.sax.SAXParseException) + */ + @Override + public void error(SAXParseException e) throws SAXException { + logger.error(e.getMessage()); + super.error(e); + } + + + public List> getRecords() { + return records; + } + } + + /** Returns a list of current PDB IDs + * + * @return a list of PDB IDs, or null if a problem occurred + */ + + public static SortedSet getCurrentPDBIds() throws IOException { + + SortedSet allPDBs = new TreeSet<>(); + String serverName = System.getProperty(PDB_SERVER_PROPERTY); + + if (serverName == null) + serverName = DEFAULT_PDB_SERVER; + else + logger.info(String.format("Got System property %s=%s", PDB_SERVER_PROPERTY, serverName)); + + // Build REST query URL + + String urlStr = String.format("http://%s/pdb/rest/getCurrent", serverName); + URL u = new URL(urlStr); + + InputStream stream = URLConnectionTools.getInputStream(u, 60000); + + if (stream != null) { + BufferedReader reader = new BufferedReader( + new InputStreamReader(stream)); + + String line; + + while ((line = reader.readLine()) != null) { + int index = line.lastIndexOf("structureId="); + if (index > 0) { + allPDBs.add(line.substring(index + 13, index + 17)); + } + } + } + return allPDBs; + + } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/PassthroughIdentifier.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/PassthroughIdentifier.java index a1793e2816..78abd1a6d5 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/PassthroughIdentifier.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/PassthroughIdentifier.java @@ -20,11 +20,10 @@ */ package org.biojava.nbio.structure; -import java.io.IOException; -import java.util.ArrayList; - import org.biojava.nbio.structure.align.util.AtomCache; +import java.util.ArrayList; + /** * A stub StructureIdentifier, representing the full structure in all cases. * @author Spencer Bliven @@ -34,7 +33,7 @@ public class PassthroughIdentifier implements StructureIdentifier { private static final long serialVersionUID = -2773111624414448950L; - private String identifier; + private final String identifier; public PassthroughIdentifier(String identifier) { this.identifier = identifier; } @@ -48,11 +47,11 @@ public String getIdentifier() { */ @Override public SubstructureIdentifier toCanonical() { - return new SubstructureIdentifier(null, new ArrayList()); + return new SubstructureIdentifier(null, new ArrayList<>()); } @Override - public Structure reduce(Structure input) throws StructureException { + public Structure reduce(Structure input) { return input; } /** @@ -60,8 +59,7 @@ public Structure reduce(Structure input) throws StructureException { * @return null */ @Override - public Structure loadStructure(AtomCache cache) throws StructureException, - IOException { + public Structure loadStructure(AtomCache cache) { return null; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/ResidueNumber.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/ResidueNumber.java index 46dfb9c4d3..544d1bc350 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/ResidueNumber.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/ResidueNumber.java @@ -177,7 +177,7 @@ public String toString() { public String toPDB() { String insCodeS ; if ( insCode != null) - insCodeS = insCode+""; + insCodeS = String.valueOf(insCode); else insCodeS = " "; return String.format("%s%4d%-2s", chainName, seqNum, insCodeS); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/ResidueRange.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/ResidueRange.java index 79dbedbdfc..713289de7d 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/ResidueRange.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/ResidueRange.java @@ -90,7 +90,7 @@ public static ResidueRange parse(String s) { Matcher matcher = RANGE_REGEX.matcher(s); if (matcher.matches()) { ResidueNumber start = null, end = null; - String chain = null; + String chain; try { chain = matcher.group(1); if (matcher.group(2) != null) { @@ -137,7 +137,7 @@ public static List parseMultiple(String s) { } String[] parts = s.split(","); - List list = new ArrayList(parts.length); + List list = new ArrayList<>(parts.length); for (String part : parts) { list.add(parse(part)); } @@ -152,6 +152,10 @@ public ResidueRange(String chainName, String start, String end) { this.end.setChainName(chainName); } + public ResidueRange(String chainName) { + this(chainName, (ResidueNumber)null, null); + } + public ResidueRange(String chainName, ResidueNumber start, ResidueNumber end) { this.chainName = chainName; this.start = start; @@ -257,7 +261,7 @@ public Iterator iterator(final AtomPositionMap map) { final Iterator> entryIt = map.getNavMap().entrySet().iterator(); if(! entryIt.hasNext()) { // empty iterator - return Arrays.asList(new ResidueNumber[0]).iterator(); + return Collections.emptyIterator(); //Arrays.asList(new ResidueNumber[0]).iterator(); } // Peek at upcoming entry @@ -352,7 +356,7 @@ public static Iterator multiIterator(AtomPositionMap map, List parseMultiple(List ranges) { - List rrs = new ArrayList(ranges.size()); + List rrs = new ArrayList<>(ranges.size()); for (String range : ranges) { ResidueRange rr = ResidueRange.parse(range); if (rr != null) rrs.add(rr); @@ -361,7 +365,7 @@ public static List parseMultiple(List ranges) { } public static List toStrings(List ranges) { - List list = new ArrayList(ranges.size()); + List list = new ArrayList<>(ranges.size()); for (ResidueRange range : ranges) { list.add(range.toString()); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/ResidueRangeAndLength.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/ResidueRangeAndLength.java index a8988aada4..1e0e9a95d7 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/ResidueRangeAndLength.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/ResidueRangeAndLength.java @@ -20,13 +20,13 @@ */ package org.biojava.nbio.structure; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * A chain, a start residue, and an end residue. * @@ -129,7 +129,7 @@ public static ResidueRangeAndLength parse(String s, AtomPositionMap map) { public static List parseMultiple(List ranges, AtomPositionMap map) { - List rrs = new ArrayList(ranges.size()); + List rrs = new ArrayList<>(ranges.size()); for (String range : ranges) { ResidueRangeAndLength rr = ResidueRangeAndLength.parse(range, map); if (rr != null) rrs.add(rr); @@ -145,7 +145,7 @@ public static List parseMultiple(List ranges, Ato */ public static List parseMultiple(String s, AtomPositionMap map) { String[] parts = s.split(","); - List list = new ArrayList(parts.length); + List list = new ArrayList<>(parts.length); for (String part : parts) { list.add(parse(part, map)); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/SeqMisMatch.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/SeqMisMatch.java index 9e90a22b7c..0e7fc278b1 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/SeqMisMatch.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/SeqMisMatch.java @@ -25,33 +25,33 @@ */ public interface SeqMisMatch { - public Integer getSeqNum() ; + Integer getSeqNum() ; - public void setSeqNum(Integer seqNum) ; + void setSeqNum(Integer seqNum) ; - public String getOrigGroup() ; + String getOrigGroup() ; - public void setOrigGroup(String origGroup); + void setOrigGroup(String origGroup); - public String getPdbGroup() ; + String getPdbGroup() ; - public void setPdbGroup(String pdbGroup) ; + void setPdbGroup(String pdbGroup) ; - public String getDetails() ; + String getDetails() ; - public void setDetails(String details); - public String getUniProtId() ; + void setDetails(String details); + String getUniProtId() ; - public void setUniProtId(String uniProtId) ; + void setUniProtId(String uniProtId) ; - public String getInsCode() ; + String getInsCode() ; - public void setInsCode(String insCode) ; + void setInsCode(String insCode) ; - public String getPdbResNum() ; + String getPdbResNum() ; - public void setPdbResNum(String pdbResNum) ; + void setPdbResNum(String pdbResNum) ; @Override - public String toString(); + String toString(); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/SeqMisMatchImpl.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/SeqMisMatchImpl.java index 755f951421..73e48950aa 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/SeqMisMatchImpl.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/SeqMisMatchImpl.java @@ -109,26 +109,26 @@ public void setPdbResNum(String pdbResNum) { @Override public String toString() { - StringBuffer s = new StringBuffer(); + StringBuilder s = new StringBuilder(); s.append("SeqMisMatchImpl{"); s.append("seqNum=" ); s.append(seqNum ); s.append(", origGroup='" ); - s.append(origGroup + '\'' ); + s.append(origGroup).append('\''); s.append(", pdbGroup='" ); - s.append(pdbGroup + '\'' ); + s.append(pdbGroup).append('\''); s.append(", details='" ); - s.append(details + '\'' ); + s.append(details).append('\''); s.append(", uniProtId='" ); - s.append(uniProtId + '\'' ); + s.append(uniProtId).append('\''); s.append(", pdbResNum='" ); - s.append(pdbResNum + '\'' ); + s.append(pdbResNum).append('\''); if ( insCode == null) s.append(", insCode=null ") ; else - s.append(", insCode='" + insCode + '\'') ; + s.append(", insCode='").append(insCode).append('\''); s.append('}'); return s.toString(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/Site.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/Site.java index 3e1464cc2a..488107e8b0 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/Site.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/Site.java @@ -23,6 +23,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; +import java.util.Objects; /** * Holds the data of sites presented in PDB files.
    @@ -42,7 +43,7 @@ public class Site implements PDBRecord, Comparable { private static final String lineEnd = System.getProperty("line.separator"); private String siteID = ""; - private List groups = new ArrayList(); + private List groups = new ArrayList<>(); //variables for REMARK 800 private String evCode = ""; private String description = ""; @@ -226,6 +227,7 @@ public void setEvCode(String evCode) { @Override public boolean equals(Object obj) { + if (this == obj) return true; if (obj == null) { return false; } @@ -233,19 +235,7 @@ public boolean equals(Object obj) { return false; } final Site other = (Site) obj; - if ((this.siteID == null) ? (other.siteID != null) : !this.siteID.equals(other.siteID)) { - return false; - } - if (this.groups != other.groups && (this.groups == null || !this.groups.equals(other.groups))) { - return false; - } - if ((this.evCode == null) ? (other.evCode != null) : !this.evCode.equals(other.evCode)) { - return false; - } - if ((this.description == null) ? (other.description != null) : !this.description.equals(other.description)) { - return false; - } - return true; + return Objects.equals(this.siteID, other.siteID) && Objects.equals(this.groups, other.groups) && Objects.equals(this.evCode, other.evCode) && Objects.equals(this.description, other.description); } @Override diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/StandardAminoAcid.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/StandardAminoAcid.java index d52d358385..a4b17c6c94 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/StandardAminoAcid.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/StandardAminoAcid.java @@ -43,7 +43,7 @@ public final class StandardAminoAcid { private static final String STANDARD_AMINOS_FILE = "org/biojava/nbio/structure/standardaminos.pdb.gz"; - static private Map aminoAcids; + static private final Map aminoAcids; /** * Cannot be instantiated. @@ -64,7 +64,7 @@ private StandardAminoAcid() { * @author Tamas Horvath provided the standard amino acids */ static { - aminoAcids = new HashMap(); + aminoAcids = new HashMap<>(); InputStream fileStream = StandardAminoAcid.class.getClassLoader().getResourceAsStream(STANDARD_AMINOS_FILE); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureException.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureException.java index 46c16fd503..c69bc77197 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureException.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureException.java @@ -33,7 +33,7 @@ public class StructureException extends Exception { - public static final long serialVersionUID = 62946250941673093l; + public static final long serialVersionUID = 62946250941673093L; /** * Constructs a StructureException object. * diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureFiletype.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureFiletype.java new file mode 100644 index 0000000000..b94fcb546c --- /dev/null +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureFiletype.java @@ -0,0 +1,27 @@ +package org.biojava.nbio.structure; + +import org.biojava.nbio.structure.io.MMCIFFileReader; +import org.biojava.nbio.structure.io.PDBFileReader; + +import java.util.Collections; +import java.util.List; + +public enum StructureFiletype { + PDB( (new PDBFileReader()).getExtensions()), + CIF( new MMCIFFileReader().getExtensions()), + UNKNOWN(Collections.emptyList()); + + private final List extensions; + /** + * @param extensions List of supported extensions, including leading period + */ + StructureFiletype(List extensions) { + this.extensions = extensions; + } + /** + * @return a list of file extensions associated with this type + */ + public List getExtensions() { + return extensions; + } +} diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureIO.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureIO.java index a90bc6db8c..95fb0dc929 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureIO.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureIO.java @@ -20,14 +20,11 @@ */ package org.biojava.nbio.structure; +import org.biojava.nbio.structure.align.util.AtomCache; + import java.io.IOException; -import java.util.Collections; import java.util.List; -import org.biojava.nbio.structure.align.util.AtomCache; -import org.biojava.nbio.structure.io.MMCIFFileReader; -import org.biojava.nbio.structure.io.PDBFileReader; - /** * A class that provides static access methods for easy lookup of protein structure related components * @@ -39,7 +36,7 @@ public class StructureIO { //private static final Logger logger = LoggerFactory.getLogger(StructureIO.class); - private static AtomCache cache ; + @Deprecated private static final ThreadLocal caches = ThreadLocal.withInitial(()->null) ; /** @@ -95,30 +92,27 @@ public class StructureIO { */ public static Structure getStructure(String name) throws IOException, StructureException{ - checkInitAtomCache(); // delegate this functionality to AtomCache... - return cache.getStructure(name); + return getAtomCache().getStructure(name); } - private static void checkInitAtomCache() { - if ( cache == null){ - cache = new AtomCache(); - } - + @Deprecated public static void setAtomCache(AtomCache c){ + caches.set(c); } - public static void setAtomCache(AtomCache c){ - cache = c; + @Deprecated public static AtomCache getAtomCache() { + //synchronized (StructureIO.class) { + AtomCache cache = caches.get(); + if ( cache == null) + setAtomCache(cache = new AtomCache()); + return cache; + //} } - public static AtomCache getAtomCache() { - checkInitAtomCache(); - return cache; - } /** @@ -143,17 +137,10 @@ public static AtomCache getAtomCache() { * if false the outputStructure will be as the original with added chains with renamed asymIds (in the form originalAsymId_transformId and originalAuthId_transformId). * @return a Structure object or null if that assembly is not available * @throws StructureException - * @throws IOException - */ - public static Structure getBiologicalAssembly(String pdbId, boolean multiModel) throws IOException, StructureException{ + */ + public static Structure getBiologicalAssembly(String pdbId, boolean multiModel) throws StructureException{ - checkInitAtomCache(); - - pdbId = pdbId.toLowerCase(); - - Structure s = cache.getBiologicalAssembly(pdbId, multiModel); - - return s; + return getAtomCache().getBiologicalAssembly(pdbId.toLowerCase(), multiModel); } /** @@ -167,9 +154,8 @@ public static Structure getBiologicalAssembly(String pdbId, boolean multiModel) * @param pdbId * @return a Structure object or null if that assembly is not available * @throws StructureException - * @throws IOException */ - public static Structure getBiologicalAssembly(String pdbId) throws IOException, StructureException{ + public static Structure getBiologicalAssembly(String pdbId) throws StructureException{ return getBiologicalAssembly(pdbId, AtomCache.DEFAULT_BIOASSEMBLY_STYLE); } @@ -191,17 +177,9 @@ public static Structure getBiologicalAssembly(String pdbId) throws IOException, * if false the outputStructure will be as the original with added chains with renamed asymIds (in the form originalAsymId_transformId and originalAuthId_transformId). * @return a Structure object or null if that assembly is not available * @throws StructureException if there is no bioassembly available for given biolAssemblyNr or some other problems encountered while loading it - * @throws IOException - */ - public static Structure getBiologicalAssembly(String pdbId, int biolAssemblyNr, boolean multiModel) throws IOException, StructureException { - - checkInitAtomCache(); - - pdbId = pdbId.toLowerCase(); - - Structure s = cache.getBiologicalAssembly(pdbId, biolAssemblyNr, multiModel); - - return s; + */ + public static Structure getBiologicalAssembly(String pdbId, int biolAssemblyNr, boolean multiModel) throws StructureException { + return getAtomCache().getBiologicalAssembly(pdbId.toLowerCase(), biolAssemblyNr, multiModel); } /** @@ -211,9 +189,8 @@ public static Structure getBiologicalAssembly(String pdbId, int biolAssemblyNr, * @param biolAssemblyNr - the ith biological assembly that is available for a PDB ID (we start counting at 1, 0 represents the asym unit). * @return a Structure object or null if that assembly is not available * @throws StructureException if there is no bioassembly available for given biolAssemblyNr or some other problems encountered while loading it - * @throws IOException - */ - public static Structure getBiologicalAssembly(String pdbId, int biolAssemblyNr) throws IOException, StructureException { + */ + public static Structure getBiologicalAssembly(String pdbId, int biolAssemblyNr) throws StructureException { return getBiologicalAssembly(pdbId, biolAssemblyNr, AtomCache.DEFAULT_BIOASSEMBLY_STYLE); } @@ -235,19 +212,13 @@ public static Structure getBiologicalAssembly(String pdbId, int biolAssemblyNr) * @param multiModel if true the output Structure will be a multi-model one with one transformId per model, * if false the outputStructure will be as the original with added chains with renamed asymIds (in the form originalAsymId_transformId and originalAuthId_transformId). * @return - * @throws IOException * @throws StructureException * @since 5.0 */ - public static List getBiologicalAssemblies(String pdbId, boolean multiModel) throws IOException, StructureException { - - checkInitAtomCache(); - - pdbId = pdbId.toLowerCase(); + public static List getBiologicalAssemblies(String pdbId, boolean multiModel) throws StructureException { - List s = cache.getBiologicalAssemblies(pdbId, multiModel); - return s; + return getAtomCache().getBiologicalAssemblies(pdbId.toLowerCase(), multiModel); } @@ -258,48 +229,27 @@ public static List getBiologicalAssemblies(String pdbId, boolean mult * If only one biological assembly is required use {@link #getBiologicalAssembly(String)} or {@link #getBiologicalAssembly(String, int)} instead. * @param pdbId * @return - * @throws IOException * @throws StructureException * @since 5.0 */ - public static List getBiologicalAssemblies(String pdbId) throws IOException, StructureException { + public static List getBiologicalAssemblies(String pdbId) throws StructureException { return getBiologicalAssemblies(pdbId, AtomCache.DEFAULT_BIOASSEMBLY_STYLE); } - private static final String FILE_SEPARATOR = System.getProperty("file.separator"); - - /** - * Utility method to set the location where PDB files can be found - * - * @param pathToPDBFiles - */ - public static void setPdbPath(String pathToPDBFiles){ - - if ( ! pathToPDBFiles.endsWith(FILE_SEPARATOR)) - pathToPDBFiles += FILE_SEPARATOR; - } - +// private static final String FILE_SEPARATOR = System.getProperty("file.separator"); - public static enum StructureFiletype { - PDB( (new PDBFileReader()).getExtensions()), - CIF( new MMCIFFileReader().getExtensions()), - UNKNOWN(Collections.emptyList()); +// /** +// * Utility method to set the location where PDB files can be found +// * +// * @param pathToPDBFiles +// */ +// public static void setPdbPath(String pathToPDBFiles){ +// +// if ( ! pathToPDBFiles.endsWith(FILE_SEPARATOR)) +// pathToPDBFiles += FILE_SEPARATOR; +// } - private List extensions; - /** - * @param extensions List of supported extensions, including leading period - */ - private StructureFiletype(List extensions) { - this.extensions = extensions; - } - /** - * @return a list of file extensions associated with this type - */ - public List getExtensions() { - return extensions; - } - } /** * Attempts to guess the type of a structure file based on the extension @@ -310,9 +260,8 @@ public static StructureFiletype guessFiletype(String filename) { String lower = filename.toLowerCase(); for(StructureFiletype type : StructureFiletype.values()) { for(String ext : type.getExtensions()) { - if(lower.endsWith(ext.toLowerCase())) { + if(lower.endsWith(ext.toLowerCase())) return type; - } } } return StructureFiletype.UNKNOWN; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureIdentifier.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureIdentifier.java index cc7d8109b2..f79c8f0733 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureIdentifier.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureIdentifier.java @@ -23,11 +23,11 @@ package org.biojava.nbio.structure; +import org.biojava.nbio.structure.align.util.AtomCache; + import java.io.IOException; import java.io.Serializable; -import org.biojava.nbio.structure.align.util.AtomCache; - /** * An identifier that uniquely identifies a whole {@link Structure} or diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureImpl.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureImpl.java index 39664983be..24cf1ea093 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureImpl.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureImpl.java @@ -23,14 +23,14 @@ */ package org.biojava.nbio.structure; -import java.util.ArrayList; -import java.util.List; -import java.util.ListIterator; - import org.biojava.nbio.structure.io.FileConvert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.List; +import java.util.ListIterator; + /** * Implementation of a PDB Structure. This class * provides the data contained in a PDB file. @@ -145,7 +145,7 @@ public Structure clone() { // go through each chain and clone chain for (int i=0;i cloned_model = new ArrayList(); + List cloned_model = new ArrayList<>(); for (int j=0;j groups = new ArrayList<>(); - groups.addAll(polyChain.getAtomGroups()); + List groups = new ArrayList<>(polyChain.getAtomGroups()); // there can be more than one non-poly chain for a given author id diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureTools.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureTools.java index 9ba8170ab5..224519064c 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureTools.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/StructureTools.java @@ -22,32 +22,21 @@ */ package org.biojava.nbio.structure; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.vecmath.Point3d; - +import org.biojava.nbio.core.util.Download; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.contact.AtomContactSet; import org.biojava.nbio.structure.contact.Grid; import org.biojava.nbio.structure.io.FileParsingParameters; import org.biojava.nbio.structure.io.PDBFileParser; -import org.biojava.nbio.core.util.FileDownloadUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.vecmath.Point3d; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.*; + /** * A class that provides some tool methods. * @@ -57,451 +46,437 @@ */ public class StructureTools { - private static final Logger logger = LoggerFactory - .getLogger(StructureTools.class); - - // Amino Acid backbone - /** - * The atom name of the backbone C-alpha atom. Note that this can be - * ambiguous depending on the context since Calcium atoms use the same name - * in PDB. - */ - public static final String CA_ATOM_NAME = "CA"; - - /** - * The atom name for the backbone amide nitrogen - */ - public static final String N_ATOM_NAME = "N"; - - /** - * The atom name for the backbone carbonyl - */ - public static final String C_ATOM_NAME = "C"; - - /** - * The atom name for the backbone carbonyl oxygen - */ - public static final String O_ATOM_NAME = "O"; - - /** - * The atom name of the side-chain C-beta atom - */ - public static final String CB_ATOM_NAME = "CB"; - - // Nucleotide backbone - /** - * The atom name of the backbone C1' in RNA - */ - public static final String C1_ATOM_NAME = "C1'"; - /** - * The atom name of the backbone C2' in RNA - */ - public static final String C2_ATOM_NAME = "C2'"; - /** - * The atom name of the backbone C3' in RNA - */ - public static final String C3_ATOM_NAME = "C3'"; - /** - * The atom name of the backbone C4' in RNA - */ - public static final String C4_ATOM_NAME = "C4'"; - /** - * The atom name of the backbone O2' in RNA - */ - public static final String O2_ATOM_NAME = "O2'"; - /** - * The atom name of the backbone O3' in RNA - */ - public static final String O3_ATOM_NAME = "O3'"; - /** - * The atom name of the backbone O4' in RNA - */ - public static final String O4_ATOM_NAME = "O4'"; - /** - * The atom name of the backbone O4' in RNA - */ - public static final String O5_ATOM_NAME = "O5'"; - /** - * The atom name of the backbone O4' in RNA - */ - public static final String OP1_ATOM_NAME = "OP1"; - /** - * The atom name of the backbone O4' in RNA - */ - public static final String OP2_ATOM_NAME = "OP2"; - /** - * The atom name of the backbone phosphate in RNA - */ - public static final String P_ATOM_NAME = "P"; - - /** - * The atom used as representative for nucleotides, equivalent to - * {@link #CA_ATOM_NAME} for proteins - */ - public static final String NUCLEOTIDE_REPRESENTATIVE = P_ATOM_NAME; - - /** - * The character to use for unknown compounds in sequence strings - */ - public static final char UNKNOWN_GROUP_LABEL = 'X'; - - /** - * Below this ratio of aminoacid/nucleotide residues to the sequence total, - * we use simple majority of aminoacid/nucleotide residues to decide the - * character of the chain (protein/nucleotide) - */ - public static final double RATIO_RESIDUES_TO_TOTAL = 0.95; - - /** - * Threshold for plausible binding of a ligand to the selected substructure - */ - public static final double DEFAULT_LIGAND_PROXIMITY_CUTOFF = 5; - - // there is a file format change in PDB 3.0 and nucleotides are being - // renamed - private static final Map nucleotides30; - private static final Map nucleotides23; - - // amino acid 3 and 1 letter code definitions - private static final Map aminoAcids; - - private static final Set hBondDonorAcceptors; - - static { - nucleotides30 = new HashMap(); - nucleotides30.put("DA", 'A'); - nucleotides30.put("DC", 'C'); - nucleotides30.put("DG", 'G'); - nucleotides30.put("DT", 'T'); - nucleotides30.put("DI", 'I'); - nucleotides30.put("A", 'A'); - nucleotides30.put("G", 'G'); - nucleotides30.put("C", 'C'); - nucleotides30.put("U", 'U'); - nucleotides30.put("I", 'I'); - - // the DNA linkers - the +C , +G, +A +T +U and +I have been replaced - // with these: - nucleotides30.put("TAF", UNKNOWN_GROUP_LABEL); // Fluorinated Thymine - nucleotides30.put("TC1", UNKNOWN_GROUP_LABEL); // Furanosyl - nucleotides30.put("TFE", UNKNOWN_GROUP_LABEL); // Fluorinated Thymine - nucleotides30.put("TFO", UNKNOWN_GROUP_LABEL); // Tenofovir (3' - // terminator) - nucleotides30.put("TGP", UNKNOWN_GROUP_LABEL); // Guanine variant - nucleotides30.put("THX", UNKNOWN_GROUP_LABEL); // 5' terminator - nucleotides30.put("TLC", UNKNOWN_GROUP_LABEL); // Thymine with dicyclic - // sugar - nucleotides30.put("TLN", UNKNOWN_GROUP_LABEL); // locked Thymine - nucleotides30.put("LCG", UNKNOWN_GROUP_LABEL); // locked Guanine - nucleotides30.put("TP1", UNKNOWN_GROUP_LABEL); // Thymine peptide - // nucleic acid, with - // added methyl - nucleotides30.put("CP1", UNKNOWN_GROUP_LABEL); // Cytidine peptide - // nucleic acid, with - // added methyl - nucleotides30.put("TPN", UNKNOWN_GROUP_LABEL); // Thymine peptide - // nucleic acid - nucleotides30.put("CPN", UNKNOWN_GROUP_LABEL); // Cytidine peptide - // nucleic acid - nucleotides30.put("GPN", UNKNOWN_GROUP_LABEL); // Guanine peptide - // nucleic acid - nucleotides30.put("APN", UNKNOWN_GROUP_LABEL); // Adenosine peptide - // nucleic acid - nucleotides30.put("TPC", UNKNOWN_GROUP_LABEL); // Thymine variant - - // store nucleic acids (C, G, A, T, U, and I), and - // the modified versions of nucleic acids (+C, +G, +A, +T, +U, and +I), - // and - nucleotides23 = new HashMap(); - String[] names = { "C", "G", "A", "T", "U", "I", "+C", "+G", "+A", - "+T", "+U", "+I" }; - for (String n : names) { - nucleotides23.put(n, n.charAt(n.length() - 1)); - } - - aminoAcids = new HashMap(); - aminoAcids.put("GLY", 'G'); - aminoAcids.put("ALA", 'A'); - aminoAcids.put("VAL", 'V'); - aminoAcids.put("LEU", 'L'); - aminoAcids.put("ILE", 'I'); - aminoAcids.put("PHE", 'F'); - aminoAcids.put("TYR", 'Y'); - aminoAcids.put("TRP", 'W'); - aminoAcids.put("PRO", 'P'); - aminoAcids.put("HIS", 'H'); - aminoAcids.put("LYS", 'K'); - aminoAcids.put("ARG", 'R'); - aminoAcids.put("SER", 'S'); - aminoAcids.put("THR", 'T'); - aminoAcids.put("GLU", 'E'); - aminoAcids.put("GLN", 'Q'); - aminoAcids.put("ASP", 'D'); - aminoAcids.put("ASN", 'N'); - aminoAcids.put("CYS", 'C'); - aminoAcids.put("MET", 'M'); - // MSE is only found as a molecular replacement for MET - aminoAcids.put("MSE", 'M'); - // 'non-standard', genetically encoded - // http://www.chem.qmul.ac.uk/iubmb/newsletter/1999/item3.html - // IUBMB recommended name is 'SEC' but the wwPDB currently use 'CSE' - // likewise 'PYL' (IUBMB) and 'PYH' (PDB) - aminoAcids.put("CSE", 'U'); - aminoAcids.put("SEC", 'U'); - aminoAcids.put("PYH", 'O'); - aminoAcids.put("PYL", 'O'); - - hBondDonorAcceptors = new HashSet(); - hBondDonorAcceptors.add(Element.N); - hBondDonorAcceptors.add(Element.O); - hBondDonorAcceptors.add(Element.S); - - } - - /** - * Count how many Atoms are contained within a Structure object. - * - * @param s - * the structure object - * @return the number of Atoms in this Structure - */ - public static final int getNrAtoms(Structure s) { - - int nrAtoms = 0; - - Iterator iter = new GroupIterator(s); - - while (iter.hasNext()) { - Group g = iter.next(); - nrAtoms += g.size(); - } - - return nrAtoms; - } - - /** - * Count how many groups are contained within a structure object. - * - * @param s - * the structure object - * @return the number of groups in the structure - */ - public static final int getNrGroups(Structure s) { - int nrGroups = 0; - - List chains = s.getChains(0); - for (Chain c : chains) { - nrGroups += c.getAtomLength(); - } - return nrGroups; - } - - /** - * Returns an array of the requested Atoms from the Structure object. - * Iterates over all groups and checks if the requested atoms are in this - * group, no matter if this is a {@link AminoAcid} or {@link HetatomImpl} - * group. If the group does not contain all requested atoms then no atoms - * are added for that group. For structures with more than one model, only - * model 0 will be used. - * - * @param s - * the structure to get the atoms from - * - * @param atomNames - * contains the atom names to be used. - * @return an Atom[] array - */ - public static final Atom[] getAtomArray(Structure s, String[] atomNames) { - List chains = s.getModel(0); - - List atoms = new ArrayList(); - - extractAtoms(atomNames, chains, atoms); - return atoms.toArray(new Atom[atoms.size()]); - - } - - /** - * Returns an array of the requested Atoms from the Structure object. In - * contrast to {@link #getAtomArray(Structure, String[])} this method - * iterates over all chains. Iterates over all chains and groups and checks - * if the requested atoms are in this group, no matter if this is a - * {@link AminoAcid} or {@link HetatomImpl} group. If the group does not - * contain all requested atoms then no atoms are added for that group. For - * structures with more than one model, only model 0 will be used. - * - * @param s - * the structure to get the atoms from - * - * @param atomNames - * contains the atom names to be used. - * @return an Atom[] array - */ - public static final Atom[] getAtomArrayAllModels(Structure s, - String[] atomNames) { - - List atoms = new ArrayList(); - - for (int i = 0; i < s.nrModels(); i++) { - List chains = s.getModel(i); - extractAtoms(atomNames, chains, atoms); - } - return atoms.toArray(new Atom[atoms.size()]); - - } - - /** - * Convert all atoms of the structure (all models) into an Atom array - * - * @param s - * input structure - * @return all atom array - */ - public static final Atom[] getAllAtomArray(Structure s) { - List atoms = new ArrayList(); - - AtomIterator iter = new AtomIterator(s); - while (iter.hasNext()) { - Atom a = iter.next(); - atoms.add(a); - } - return atoms.toArray(new Atom[atoms.size()]); - } - /** - * Convert all atoms of the structure (specified model) into an Atom array - * - * @param s - * input structure - * @return all atom array - */ - public static final Atom[] getAllAtomArray(Structure s, int model) { - List atoms = new ArrayList(); - - AtomIterator iter = new AtomIterator(s,model); - while (iter.hasNext()) { - Atom a = iter.next(); - atoms.add(a); - } - return atoms.toArray(new Atom[atoms.size()]); - - } - - /** - * Returns and array of all atoms of the chain, including - * Hydrogens (if present) and all HETATOMs. Waters are not included. - * - * @param c - * input chain - * @return all atom array - */ - public static final Atom[] getAllAtomArray(Chain c) { - List atoms = new ArrayList(); - - for (Group g : c.getAtomGroups()) { - if (g.isWater()) - continue; - for (Atom a : g.getAtoms()) { - atoms.add(a); - } - } - return atoms.toArray(new Atom[atoms.size()]); - } - - /** - * List of groups from the structure not included in ca (e.g. ligands). - * - * Unaligned groups are searched from all chains referenced in ca, as well - * as any chains in the first model of the structure from ca[0], if any. - * - * @param ca an array of atoms - * @return - */ - public static List getUnalignedGroups(Atom[] ca) { - Set chains = new HashSet(); - Set caGroups = new HashSet(); - - // Create list of all chains in this structure - Structure s = null; - if (ca.length > 0) { - Group g = ca[0].getGroup(); - if (g != null) { - Chain c = g.getChain(); - if (c != null) { - s = c.getStructure(); - } - } - } - if (s != null) { - // Add all chains from the structure - for (Chain c : s.getChains(0)) { - chains.add(c); - } - } - - // Add groups and chains from ca - for (Atom a : ca) { - Group g = a.getGroup(); - if (g != null) { - caGroups.add(g); - - Chain c = g.getChain(); - if (c != null) { - chains.add(c); - } - } - } - - // Iterate through all chains, finding groups not in ca - List unadded = new ArrayList(); - for (Chain c : chains) { - for (Group g : c.getAtomGroups()) { - if (!caGroups.contains(g)) { - unadded.add(g); - } - } - } - return unadded; - } - - /** - * Finds all ligand groups from the target which fall within the cutoff distance - * of some atom from the query set. - * - * @param target Set of groups including the ligands - * @param query Atom selection - * @param cutoff Distance from query atoms to consider, in angstroms - * @return All groups from the target with at least one atom within cutoff of a query atom - * @see StructureTools#DEFAULT_LIGAND_PROXIMITY_CUTOFF - */ - public static List getLigandsByProximity(Collection target, Atom[] query, double cutoff) { - // Geometric hashing of the reduced structure - Grid grid = new Grid(cutoff); - grid.addAtoms(query); - - List ligands = new ArrayList<>(); - for(Group g :target ) { - // don't worry about waters - if(g.isWater()) { - continue; - } - - if(g.isPolymeric() ) { - // Polymers aren't ligands - continue; - } - - // It is a ligand! - - // Check that it's within cutoff of something in reduced - List groupAtoms = g.getAtoms(); - if( ! grid.hasAnyContact(Calc.atomsToPoints(groupAtoms))) { - continue; - } - - ligands.add(g); - } - return ligands; - } + private static final Logger logger = LoggerFactory + .getLogger(StructureTools.class); + + // Amino Acid backbone + /** + * The atom name of the backbone C-alpha atom. Note that this can be + * ambiguous depending on the context since Calcium atoms use the same name + * in PDB. + */ + public static final String CA_ATOM_NAME = "CA"; + + /** + * The atom name for the backbone amide nitrogen + */ + public static final String N_ATOM_NAME = "N"; + + /** + * The atom name for the backbone carbonyl + */ + public static final String C_ATOM_NAME = "C"; + + /** + * The atom name for the backbone carbonyl oxygen + */ + public static final String O_ATOM_NAME = "O"; + + /** + * The atom name of the side-chain C-beta atom + */ + public static final String CB_ATOM_NAME = "CB"; + + // Nucleotide backbone + /** + * The atom name of the backbone C1' in RNA + */ + public static final String C1_ATOM_NAME = "C1'"; + /** + * The atom name of the backbone C2' in RNA + */ + public static final String C2_ATOM_NAME = "C2'"; + /** + * The atom name of the backbone C3' in RNA + */ + public static final String C3_ATOM_NAME = "C3'"; + /** + * The atom name of the backbone C4' in RNA + */ + public static final String C4_ATOM_NAME = "C4'"; + /** + * The atom name of the backbone O2' in RNA + */ + public static final String O2_ATOM_NAME = "O2'"; + /** + * The atom name of the backbone O3' in RNA + */ + public static final String O3_ATOM_NAME = "O3'"; + /** + * The atom name of the backbone O4' in RNA + */ + public static final String O4_ATOM_NAME = "O4'"; + /** + * The atom name of the backbone O4' in RNA + */ + public static final String O5_ATOM_NAME = "O5'"; + /** + * The atom name of the backbone O4' in RNA + */ + public static final String OP1_ATOM_NAME = "OP1"; + /** + * The atom name of the backbone O4' in RNA + */ + public static final String OP2_ATOM_NAME = "OP2"; + /** + * The atom name of the backbone phosphate in RNA + */ + public static final String P_ATOM_NAME = "P"; + + /** + * The atom used as representative for nucleotides, equivalent to + * {@link #CA_ATOM_NAME} for proteins + */ + public static final String NUCLEOTIDE_REPRESENTATIVE = P_ATOM_NAME; + + /** + * The character to use for unknown compounds in sequence strings + */ + public static final char UNKNOWN_GROUP_LABEL = 'X'; + + /** + * Below this ratio of aminoacid/nucleotide residues to the sequence total, + * we use simple majority of aminoacid/nucleotide residues to decide the + * character of the chain (protein/nucleotide) + */ + public static final double RATIO_RESIDUES_TO_TOTAL = 0.95; + + /** + * Threshold for plausible binding of a ligand to the selected substructure + */ + public static final double DEFAULT_LIGAND_PROXIMITY_CUTOFF = 5; + + // there is a file format change in PDB 3.0 and nucleotides are being + // renamed + private static final Map nucleotides30; + private static final Map nucleotides23; + + // amino acid 3 and 1 letter code definitions + private static final Map aminoAcids; + + private static final Set hBondDonorAcceptors; + + static { + nucleotides30 = new HashMap<>(); + nucleotides30.put("DA", 'A'); + nucleotides30.put("DC", 'C'); + nucleotides30.put("DG", 'G'); + nucleotides30.put("DT", 'T'); + nucleotides30.put("DI", 'I'); + nucleotides30.put("A", 'A'); + nucleotides30.put("G", 'G'); + nucleotides30.put("C", 'C'); + nucleotides30.put("U", 'U'); + nucleotides30.put("I", 'I'); + + // the DNA linkers - the +C , +G, +A +T +U and +I have been replaced + // with these: + nucleotides30.put("TAF", UNKNOWN_GROUP_LABEL); // Fluorinated Thymine + nucleotides30.put("TC1", UNKNOWN_GROUP_LABEL); // Furanosyl + nucleotides30.put("TFE", UNKNOWN_GROUP_LABEL); // Fluorinated Thymine + nucleotides30.put("TFO", UNKNOWN_GROUP_LABEL); // Tenofovir (3' + // terminator) + nucleotides30.put("TGP", UNKNOWN_GROUP_LABEL); // Guanine variant + nucleotides30.put("THX", UNKNOWN_GROUP_LABEL); // 5' terminator + nucleotides30.put("TLC", UNKNOWN_GROUP_LABEL); // Thymine with dicyclic + // sugar + nucleotides30.put("TLN", UNKNOWN_GROUP_LABEL); // locked Thymine + nucleotides30.put("LCG", UNKNOWN_GROUP_LABEL); // locked Guanine + nucleotides30.put("TP1", UNKNOWN_GROUP_LABEL); // Thymine peptide + // nucleic acid, with + // added methyl + nucleotides30.put("CP1", UNKNOWN_GROUP_LABEL); // Cytidine peptide + // nucleic acid, with + // added methyl + nucleotides30.put("TPN", UNKNOWN_GROUP_LABEL); // Thymine peptide + // nucleic acid + nucleotides30.put("CPN", UNKNOWN_GROUP_LABEL); // Cytidine peptide + // nucleic acid + nucleotides30.put("GPN", UNKNOWN_GROUP_LABEL); // Guanine peptide + // nucleic acid + nucleotides30.put("APN", UNKNOWN_GROUP_LABEL); // Adenosine peptide + // nucleic acid + nucleotides30.put("TPC", UNKNOWN_GROUP_LABEL); // Thymine variant + + // store nucleic acids (C, G, A, T, U, and I), and + // the modified versions of nucleic acids (+C, +G, +A, +T, +U, and +I), + // and + nucleotides23 = new HashMap<>(); + String[] names = {"C", "G", "A", "T", "U", "I", "+C", "+G", "+A", + "+T", "+U", "+I"}; + for (String n : names) { + nucleotides23.put(n, n.charAt(n.length() - 1)); + } + + aminoAcids = new HashMap<>(); + aminoAcids.put("GLY", 'G'); + aminoAcids.put("ALA", 'A'); + aminoAcids.put("VAL", 'V'); + aminoAcids.put("LEU", 'L'); + aminoAcids.put("ILE", 'I'); + aminoAcids.put("PHE", 'F'); + aminoAcids.put("TYR", 'Y'); + aminoAcids.put("TRP", 'W'); + aminoAcids.put("PRO", 'P'); + aminoAcids.put("HIS", 'H'); + aminoAcids.put("LYS", 'K'); + aminoAcids.put("ARG", 'R'); + aminoAcids.put("SER", 'S'); + aminoAcids.put("THR", 'T'); + aminoAcids.put("GLU", 'E'); + aminoAcids.put("GLN", 'Q'); + aminoAcids.put("ASP", 'D'); + aminoAcids.put("ASN", 'N'); + aminoAcids.put("CYS", 'C'); + aminoAcids.put("MET", 'M'); + // MSE is only found as a molecular replacement for MET + aminoAcids.put("MSE", 'M'); + // 'non-standard', genetically encoded + // http://www.chem.qmul.ac.uk/iubmb/newsletter/1999/item3.html + // IUBMB recommended name is 'SEC' but the wwPDB currently use 'CSE' + // likewise 'PYL' (IUBMB) and 'PYH' (PDB) + aminoAcids.put("CSE", 'U'); + aminoAcids.put("SEC", 'U'); + aminoAcids.put("PYH", 'O'); + aminoAcids.put("PYL", 'O'); + + hBondDonorAcceptors = new HashSet<>(); + hBondDonorAcceptors.add(Element.N); + hBondDonorAcceptors.add(Element.O); + hBondDonorAcceptors.add(Element.S); + + } + + /** + * Count how many Atoms are contained within a Structure object. + * + * @param s the structure object + * @return the number of Atoms in this Structure + */ + public static int getNrAtoms(Structure s) { + + int nrAtoms = 0; + + Iterator iter = new GroupIterator(s); + + while (iter.hasNext()) { + Group g = iter.next(); + nrAtoms += g.size(); + } + + return nrAtoms; + } + + /** + * Count how many groups are contained within a structure object. + * + * @param s the structure object + * @return the number of groups in the structure + */ + public static int getNrGroups(Structure s) { + int nrGroups = 0; + + List chains = s.getChains(0); + for (Chain c : chains) { + nrGroups += c.getAtomLength(); + } + return nrGroups; + } + + /** + * Returns an array of the requested Atoms from the Structure object. + * Iterates over all groups and checks if the requested atoms are in this + * group, no matter if this is a {@link AminoAcid} or {@link HetatomImpl} + * group. If the group does not contain all requested atoms then no atoms + * are added for that group. For structures with more than one model, only + * model 0 will be used. + * + * @param s the structure to get the atoms from + * @param atomNames contains the atom names to be used. + * @return an Atom[] array + */ + public static Atom[] getAtomArray(Structure s, String[] atomNames) { + List chains = s.getModel(0); + + List atoms = new ArrayList<>(); + + extractAtoms(atomNames, chains, atoms); + return atoms.toArray(Atom.EmptyAtomArray); + + } + + /** + * Returns an array of the requested Atoms from the Structure object. In + * contrast to {@link #getAtomArray(Structure, String[])} this method + * iterates over all chains. Iterates over all chains and groups and checks + * if the requested atoms are in this group, no matter if this is a + * {@link AminoAcid} or {@link HetatomImpl} group. If the group does not + * contain all requested atoms then no atoms are added for that group. For + * structures with more than one model, only model 0 will be used. + * + * @param s the structure to get the atoms from + * @param atomNames contains the atom names to be used. + * @return an Atom[] array + */ + public static Atom[] getAtomArrayAllModels(Structure s, + String[] atomNames) { + + List atoms = new ArrayList<>(); + + for (int i = 0; i < s.nrModels(); i++) { + List chains = s.getModel(i); + extractAtoms(atomNames, chains, atoms); + } + return atoms.toArray(Atom.EmptyAtomArray); + + } + + /** + * Convert all atoms of the structure (all models) into an Atom array + * + * @param s input structure + * @return all atom array + */ + public static Atom[] getAllAtomArray(Structure s) { + List atoms = new ArrayList<>(); + + AtomIterator iter = new AtomIterator(s); + while (iter.hasNext()) { + Atom a = iter.next(); + atoms.add(a); + } + return atoms.toArray(Atom.EmptyAtomArray); + } + + /** + * Convert all atoms of the structure (specified model) into an Atom array + * + * @param s input structure + * @return all atom array + */ + public static Atom[] getAllAtomArray(Structure s, int model) { + List atoms = new ArrayList<>(); + + AtomIterator iter = new AtomIterator(s, model); + while (iter.hasNext()) { + Atom a = iter.next(); + atoms.add(a); + } + return atoms.toArray(Atom.EmptyAtomArray); + + } + + /** + * Returns and array of all atoms of the chain, including + * Hydrogens (if present) and all HETATOMs. Waters are not included. + * + * @param c input chain + * @return all atom array + */ + public static Atom[] getAllAtomArray(Chain c) { + List atoms = new ArrayList<>(); + + for (Group g : c.getAtomGroups()) { + if (g.isWater()) + continue; + atoms.addAll(g.getAtoms()); + } + return atoms.toArray(Atom.EmptyAtomArray); + } + + /** + * List of groups from the structure not included in ca (e.g. ligands). + *

    + * Unaligned groups are searched from all chains referenced in ca, as well + * as any chains in the first model of the structure from ca[0], if any. + * + * @param ca an array of atoms + * @return + */ + public static List getUnalignedGroups(Atom[] ca) { + Set chains = new HashSet<>(); + Set caGroups = new HashSet<>(); + + // Create list of all chains in this structure + Structure s = null; + if (ca.length > 0) { + Group g = ca[0].getGroup(); + if (g != null) { + Chain c = g.getChain(); + if (c != null) { + s = c.getStructure(); + } + } + } + if (s != null) { + // Add all chains from the structure + chains.addAll(s.getChains(0)); + } + + // Add groups and chains from ca + for (Atom a : ca) { + Group g = a.getGroup(); + if (g != null) { + caGroups.add(g); + + Chain c = g.getChain(); + if (c != null) { + chains.add(c); + } + } + } + + // Iterate through all chains, finding groups not in ca + List unadded = new ArrayList<>(); + for (Chain c : chains) { + for (Group g : c.getAtomGroups()) { + if (!caGroups.contains(g)) { + unadded.add(g); + } + } + } + return unadded; + } + + /** + * Finds all ligand groups from the target which fall within the cutoff distance + * of some atom from the query set. + * + * @param target Set of groups including the ligands + * @param query Atom selection + * @param cutoff Distance from query atoms to consider, in angstroms + * @return All groups from the target with at least one atom within cutoff of a query atom + * @see StructureTools#DEFAULT_LIGAND_PROXIMITY_CUTOFF + */ + public static List getLigandsByProximity(Collection target, Atom[] query, double cutoff) { + // Spatial hashing of the reduced structure + Grid grid = new Grid(cutoff); + grid.addAtoms(query); + + List ligands = new ArrayList<>(); + for (Group g : target) { + // don't worry about waters + if (g.isWater()) { + continue; + } + + if (g.isPolymeric()) { + // Polymers aren't ligands + continue; + } + + // It is a ligand! + + // Check that it's within cutoff of something in reduced + List groupAtoms = g.getAtoms(); + if (!grid.hasAnyContact(Calc.atomsToPoints(groupAtoms))) { + continue; + } + + ligands.add(g); + } + return ligands; + } /** * Adds a particular group to a structure. A new chain will be created if necessary. @@ -528,7 +503,7 @@ public static Chain addGroupToStructure(Structure s, Group g, int model, Chain c String chainId = g.getChainId(); assert !chainId.isEmpty(); Chain chain; - if(chainGuess != null && chainGuess.getId() == chainId) { + if(chainGuess != null && chainGuess.getId().equals(chainId)) { // previously guessed chain chain = chainGuess; } else { @@ -580,7 +555,7 @@ public static Chain addGroupToStructure(Structure s, Group g, int model, Chain c * Add a list of groups to a new structure. Chains will be automatically * created in the new structure as needed. * @param s structure to receive the group - * @param g group to add + * @param groups group to add * @param clone Indicates whether the input groups should be cloned before * being added to the new chain */ @@ -591,1354 +566,1303 @@ public static void addGroupsToStructure(Structure s, Collection groups, i } } - /** - * Expand a set of atoms into all groups from the same structure. - * - * If the structure is set, only the first atom is used (assuming all - * atoms come from the same original structure). - * If the atoms aren't linked to a structure (for instance, for cloned atoms), - * searches all chains of all atoms for groups. - * @param atoms Sample of atoms - * @return All groups from all chains accessible from the input atoms - */ - public static Set getAllGroupsFromSubset(Atom[] atoms) { - return getAllGroupsFromSubset(atoms,null); - } - /** - * Expand a set of atoms into all groups from the same structure. - * - * If the structure is set, only the first atom is used (assuming all - * atoms come from the same original structure). - * If the atoms aren't linked to a structure (for instance, for cloned atoms), - * searches all chains of all atoms for groups. - * @param atoms Sample of atoms - * @param types Type of groups to return (useful for getting only ligands, for instance). - * Null gets all groups. - * @return All groups from all chains accessible from the input atoms - */ - public static Set getAllGroupsFromSubset(Atom[] atoms,GroupType types) { - // Get the full structure - Structure s = null; - if (atoms.length > 0) { - Group g = atoms[0].getGroup(); - if (g != null) { - Chain c = g.getChain(); - if (c != null) { - s = c.getStructure(); - } - } - } - // Collect all groups from the structure - Set allChains = new HashSet<>(); - if( s != null ) { - allChains.addAll(s.getChains()); - } - // In case the structure wasn't set, need to use ca chains too - for(Atom a : atoms) { - Group g = a.getGroup(); - if(g != null) { - Chain c = g.getChain(); - if( c != null ) { - allChains.add(c); - } - } - } - - if(allChains.isEmpty() ) { - return Collections.emptySet(); - } - - // Extract all ligand groups - Set full = new HashSet<>(); - for(Chain c : allChains) { - if(types == null) { - full.addAll(c.getAtomGroups()); - } else { - full.addAll(c.getAtomGroups(types)); - } - } - - return full; - } - - - /** - * Returns and array of all non-Hydrogen atoms in the given Structure, - * optionally including HET atoms or not. Waters are not included. - * - * @param s - * @param hetAtoms - * if true HET atoms are included in array, if false they are not - * @return - */ - public static final Atom[] getAllNonHAtomArray(Structure s, boolean hetAtoms) { - AtomIterator iter = new AtomIterator(s); - return getAllNonHAtomArray(s, hetAtoms, iter); - } - /** - * Returns and array of all non-Hydrogen atoms in the given Structure, - * optionally including HET atoms or not. Waters are not included. - * - * @param s - * @param hetAtoms - * if true HET atoms are included in array, if false they are not - * @param modelNr Model number to draw atoms from - * @return - */ - public static final Atom[] getAllNonHAtomArray(Structure s, boolean hetAtoms, int modelNr) { - AtomIterator iter = new AtomIterator(s,modelNr); - return getAllNonHAtomArray(s, hetAtoms, iter); - } - private static final Atom[] getAllNonHAtomArray(Structure s, boolean hetAtoms, AtomIterator iter) { - List atoms = new ArrayList(); - - while (iter.hasNext()) { - Atom a = iter.next(); - if (a.getElement() == Element.H) - continue; - - Group g = a.getGroup(); - - if (g.isWater()) - continue; - - if (!hetAtoms && g.getType().equals(GroupType.HETATM)) - continue; - - atoms.add(a); - } - return atoms.toArray(new Atom[atoms.size()]); - } - - /** - * Returns and array of all non-Hydrogen atoms in the given Chain, - * optionally including HET atoms or not Waters are not included. - * - * @param c - * @param hetAtoms - * if true HET atoms are included in array, if false they are not - * @return - */ - public static final Atom[] getAllNonHAtomArray(Chain c, boolean hetAtoms) { - List atoms = new ArrayList(); - - for (Group g : c.getAtomGroups()) { - if (g.isWater()) - continue; - for (Atom a : g.getAtoms()) { - - if (a.getElement() == Element.H) - continue; - - if (!hetAtoms && g.getType().equals(GroupType.HETATM)) - continue; - - atoms.add(a); - } - } - return atoms.toArray(new Atom[atoms.size()]); - } - - /** - * Returns and array of all non-Hydrogen atoms coordinates in the given Chain, - * optionally including HET atoms or not Waters are not included. - * - * @param c - * @param hetAtoms - * if true HET atoms are included in array, if false they are not - * @return - */ - public static final Point3d[] getAllNonHCoordsArray(Chain c, boolean hetAtoms) { - List atoms = new ArrayList(); - - for (Group g : c.getAtomGroups()) { - if (g.isWater()) - continue; - for (Atom a : g.getAtoms()) { - - if (a.getElement() == Element.H) - continue; - - if (!hetAtoms && g.getType().equals(GroupType.HETATM)) - continue; - - atoms.add(a.getCoordsAsPoint3d()); - } - } - return atoms.toArray(new Point3d[atoms.size()]); - } - - /** - * Adds to the given atoms list, all atoms of groups that contained all - * requested atomNames, i.e. if a group does not contain all of the - * requested atom names, its atoms won't be added. - * - * @param atomNames - * @param chains - * @param atoms - */ - private static void extractAtoms(String[] atomNames, List chains, - List atoms) { - - for (Chain c : chains) { - - for (Group g : c.getAtomGroups()) { - - // a temp container for the atoms of this group - List thisGroupAtoms = new ArrayList(); - // flag to check if this group contains all the requested atoms. - boolean thisGroupAllAtoms = true; - for (String atomName : atomNames) { - Atom a = g.getAtom(atomName); - - if (a == null) { - // this group does not have a required atom, skip it... - thisGroupAllAtoms = false; - break; - } - thisGroupAtoms.add(a); - } - if (thisGroupAllAtoms) { - // add the atoms of this group to the array. - for (Atom a : thisGroupAtoms) { - atoms.add(a); - } - } - - } - } - } - - /** - * Returns an array of the requested Atoms from the Chain object. Iterates - * over all groups and checks if the requested atoms are in this group, no - * matter if this is a AminoAcid or Hetatom group. If the group does not - * contain all requested atoms then no atoms are added for that group. - * - * @param c - * the Chain to get the atoms from - * - * @param atomNames - * contains the atom names to be used. - * @return an Atom[] array - */ - public static final Atom[] getAtomArray(Chain c, String[] atomNames) { - - List atoms = new ArrayList(); - - for (Group g : c.getAtomGroups()) { - - // a temp container for the atoms of this group - List thisGroupAtoms = new ArrayList(); - // flag to check if this group contains all the requested atoms. - boolean thisGroupAllAtoms = true; - for (String atomName : atomNames) { - Atom a = g.getAtom(atomName); - if (a == null) { - logger.debug("Group " + g.getResidueNumber() + " (" - + g.getPDBName() - + ") does not have the required atom '" + atomName - + "'"); - // this group does not have a required atom, skip it... - thisGroupAllAtoms = false; - break; - } - thisGroupAtoms.add(a); - } - - if (thisGroupAllAtoms) { - // add the atoms of this group to the array. - for (Atom a : thisGroupAtoms) { - atoms.add(a); - } - } - - } - return atoms.toArray(new Atom[atoms.size()]); - - } - - /** - * Returns an Atom array of the C-alpha atoms. Any atom that is a carbon and - * has CA name will be returned. - * - * @param c - * the structure object - * @return an Atom[] array - * @see #getRepresentativeAtomArray(Chain) - */ - public static final Atom[] getAtomCAArray(Chain c) { - List atoms = new ArrayList(); - - for (Group g : c.getAtomGroups()) { - if (g.hasAtom(CA_ATOM_NAME) - && g.getAtom(CA_ATOM_NAME).getElement() == Element.C) { - atoms.add(g.getAtom(CA_ATOM_NAME)); - } - } - - return atoms.toArray(new Atom[atoms.size()]); - } - - /** - * Gets a representative atom for each group that is part of the chain - * backbone. Note that modified aminoacids won't be returned as part of the - * backbone if the {@link org.biojava.nbio.structure.io.mmcif.ReducedChemCompProvider} was used to load the - * structure. - * - * For amino acids, the representative is a CA carbon. For nucleotides, the - * representative is the {@value #NUCLEOTIDE_REPRESENTATIVE}. Other group - * types will be ignored. - * - * @param c - * @return representative Atoms of the chain backbone - * @since Biojava 4.1.0 - */ - public static final Atom[] getRepresentativeAtomArray(Chain c) { - List atoms = new ArrayList(); - - for (Group g : c.getAtomGroups()) { - - switch (g.getType()) { - case AMINOACID: - if (g.hasAtom(CA_ATOM_NAME) - && g.getAtom(CA_ATOM_NAME).getElement() == Element.C) { - atoms.add(g.getAtom(CA_ATOM_NAME)); - } - break; - case NUCLEOTIDE: - if (g.hasAtom(NUCLEOTIDE_REPRESENTATIVE)) { - atoms.add(g.getAtom(NUCLEOTIDE_REPRESENTATIVE)); - } - break; - default: - // don't add - } - } - - return atoms.toArray(new Atom[atoms.size()]); - - } - - /** - * Provides an equivalent copy of Atoms in a new array. Clones everything, - * starting with parent groups and chains. The chain will only contain - * groups that are part of the input array. - * - * @param ca - * array of representative atoms, e.g. CA atoms - * @return Atom array - * @since Biojava 4.1.0 - */ - public static final Atom[] cloneAtomArray(Atom[] ca) { - Atom[] newCA = new Atom[ca.length]; - - List model = new ArrayList(); - int apos = -1; - for (Atom a : ca) { - apos++; - Group parentG = a.getGroup(); - Chain parentC = parentG.getChain(); - - Chain newChain = null; - for (Chain c : model) { - if (c.getName().equals(parentC.getName())) { - newChain = c; - break; - } - } - if (newChain == null) { - newChain = new ChainImpl(); - newChain.setId(parentC.getId()); - newChain.setName(parentC.getName()); - model.add(newChain); - } - - Group parentN = (Group) parentG.clone(); - - newCA[apos] = parentN.getAtom(a.getName()); - try { - // if the group doesn't exist yet, this produces a StructureException - newChain.getGroupByPDB(parentN.getResidueNumber()); - } catch (StructureException e) { - // the group doesn't exist yet in the newChain, let's add it - newChain.addGroup(parentN); - } - - } - return newCA; - } - - /** - * Clone a set of representative Atoms, but returns the parent groups - * - * @param ca - * Atom array - * @return Group array - */ - public static Group[] cloneGroups(Atom[] ca) { - Group[] newGroup = new Group[ca.length]; - - List model = new ArrayList(); - int apos = -1; - for (Atom a : ca) { - apos++; - Group parentG = a.getGroup(); - Chain parentC = parentG.getChain(); - - Chain newChain = null; - for (Chain c : model) { - if (c.getName().equals(parentC.getName())) { - newChain = c; - break; - } - } - if (newChain == null) { - newChain = new ChainImpl(); - newChain.setName(parentC.getName()); - model.add(newChain); - } - - Group ng = (Group) parentG.clone(); - newGroup[apos] = ng; - newChain.addGroup(ng); - } - return newGroup; - } - - /** - * Utility method for working with circular permutations. Creates a - * duplicated and cloned set of Calpha atoms from the input array. - * - * @param ca2 - * atom array - * @return cloned and duplicated set of input array - */ - public static Atom[] duplicateCA2(Atom[] ca2) { - // we don't want to rotate input atoms, do we? - Atom[] ca2clone = new Atom[ca2.length * 2]; - - int pos = 0; - - Chain c = null; - String prevChainId = ""; - for (Atom a : ca2) { - Group g = (Group) a.getGroup().clone(); // works because each group - // has only a single atom - - if (c == null) { - c = new ChainImpl(); - Chain orig = a.getGroup().getChain(); - c.setId(orig.getId()); - c.setName(orig.getName()); - } else { - Chain orig = a.getGroup().getChain(); - if (!orig.getId().equals(prevChainId)) { - c = new ChainImpl(); - c.setId(orig.getId()); - c.setName(orig.getName()); - } - } - - c.addGroup(g); - ca2clone[pos] = g.getAtom(a.getName()); - - pos++; - } - - // Duplicate ca2! - c = null; - prevChainId = ""; - for (Atom a : ca2) { - Group g = (Group) a.getGroup().clone(); - - if (c == null) { - c = new ChainImpl(); - Chain orig = a.getGroup().getChain(); - c.setId(orig.getId()); - c.setName(orig.getName()); - } else { - Chain orig = a.getGroup().getChain(); - if (!orig.getId().equals(prevChainId)) { - c = new ChainImpl(); - c.setId(orig.getId()); - c.setName(orig.getName()); - } - } - - c.addGroup(g); - ca2clone[pos] = g.getAtom(a.getName()); - - pos++; - } - - return ca2clone; - - } - - /** - * Return an Atom array of the C-alpha atoms. Any atom that is a carbon and - * has CA name will be returned. - * - * @param s - * the structure object - * @return an Atom[] array - * @see #getRepresentativeAtomArray(Structure) - */ - public static Atom[] getAtomCAArray(Structure s) { - - List atoms = new ArrayList(); - - for (Chain c : s.getChains()) { - for (Group g : c.getAtomGroups()) { - if (g.hasAtom(CA_ATOM_NAME) - && g.getAtom(CA_ATOM_NAME).getElement() == Element.C) { - atoms.add(g.getAtom(CA_ATOM_NAME)); - } - } - } - - return atoms.toArray(new Atom[atoms.size()]); - } - - /** - * Gets a representative atom for each group that is part of the chain - * backbone. Note that modified aminoacids won't be returned as part of the - * backbone if the {@link org.biojava.nbio.structure.io.mmcif.ReducedChemCompProvider} was used to load the - * structure. - * - * For amino acids, the representative is a CA carbon. For nucleotides, the - * representative is the {@value #NUCLEOTIDE_REPRESENTATIVE}. Other group - * types will be ignored. - * - * @param s - * Input structure - * @return representative Atoms of the structure backbone - * @since Biojava 4.1.0 - */ - public static Atom[] getRepresentativeAtomArray(Structure s) { - - List atoms = new ArrayList(); - - for (Chain c : s.getChains()) { - Atom[] chainAtoms = getRepresentativeAtomArray(c); - for (Atom a : chainAtoms) { - atoms.add(a); - } - } - - return atoms.toArray(new Atom[atoms.size()]); - } - - /** - * Return an Atom array of the main chain atoms: CA, C, N, O Any group that - * contains those atoms will be included, be it a standard aminoacid or not - * - * @param s - * the structure object - * @return an Atom[] array - */ - public static Atom[] getBackboneAtomArray(Structure s) { - - List atoms = new ArrayList(); - - for (Chain c : s.getChains()) { - for (Group g : c.getAtomGroups()) { - if (g.hasAminoAtoms()) { - // this means we will only take atoms grom groups that have - // complete backbones - for (Atom a : g.getAtoms()) { - switch (g.getType()) { - case NUCLEOTIDE: - // Nucleotide backbone - if (a.getName().equals(C1_ATOM_NAME)) - atoms.add(a); - if (a.getName().equals(C2_ATOM_NAME)) - atoms.add(a); - if (a.getName().equals(C3_ATOM_NAME)) - atoms.add(a); - if (a.getName().equals(C4_ATOM_NAME)) - atoms.add(a); - if (a.getName().equals(O2_ATOM_NAME)) - atoms.add(a); - if (a.getName().equals(O3_ATOM_NAME)) - atoms.add(a); - if (a.getName().equals(O4_ATOM_NAME)) - atoms.add(a); - if (a.getName().equals(O5_ATOM_NAME)) - atoms.add(a); - if (a.getName().equals(OP1_ATOM_NAME)) - atoms.add(a); - if (a.getName().equals(OP2_ATOM_NAME)) - atoms.add(a); - if (a.getName().equals(P_ATOM_NAME)) - atoms.add(a); - // TODO Allow C4* names as well as C4'? -SB 3/2015 - break; - case AMINOACID: - default: - // we do it this way instead of with g.getAtom() to - // be sure we always use the same order as original - if (a.getName().equals(CA_ATOM_NAME)) - atoms.add(a); - if (a.getName().equals(C_ATOM_NAME)) - atoms.add(a); - if (a.getName().equals(N_ATOM_NAME)) - atoms.add(a); - if (a.getName().equals(O_ATOM_NAME)) - atoms.add(a); - break; - } - } - } - } - - } - - return atoms.toArray(new Atom[atoms.size()]); - } - - /** - * Convert three character amino acid codes into single character e.g. - * convert CYS to C. Valid 3-letter codes will be those of the standard 20 - * amino acids plus MSE, CSE, SEC, PYH, PYL (see the {@link #aminoAcids} - * map) - * - * @return the 1 letter code, or null if the given 3 letter code does not - * correspond to an amino acid code - * @param groupCode3 - * a three character amino acid representation String - * @see {@link #get1LetterCode(String)} - */ - public static final Character get1LetterCodeAmino(String groupCode3) { - return aminoAcids.get(groupCode3); - } - - /** - * Convert a three letter amino acid or nucleotide code into a single - * character code. If the code does not correspond to an amino acid or - * nucleotide, returns {@link #UNKNOWN_GROUP_LABEL}. - * - * Returned null for nucleotides prior to version 4.0.1. - * - * @param groupCode3 - * three letter representation - * @return The 1-letter abbreviation - */ - public static final Character get1LetterCode(String groupCode3) { - - Character code1; - - // is it a standard amino acid ? - code1 = get1LetterCodeAmino(groupCode3); - - if (code1 == null) { - // hm groupCode3 is not standard - // perhaps it is a nucleotide? - groupCode3 = groupCode3.trim(); - if (isNucleotide(groupCode3)) { - code1 = nucleotides30.get(groupCode3); - if (code1 == null) { - code1 = nucleotides23.get(groupCode3); - } - if (code1 == null) { - code1 = UNKNOWN_GROUP_LABEL; - } - } else { - // does not seem to be so let's assume it is - // nonstandard aminoacid and label it "X" - // logger.warning("unknown group name "+groupCode3 ); - code1 = UNKNOWN_GROUP_LABEL; - } - } - - return code1; - - } - - /** - * Test if the three-letter code of an ATOM entry corresponds to a - * nucleotide or to an aminoacid. - * - * @param groupCode3 - * 3-character code for a group. - * - */ - public static boolean isNucleotide(String groupCode3) { - String code = groupCode3.trim(); - return nucleotides30.containsKey(code) - || nucleotides23.containsKey(code); - } - - /** - * Reduce a structure to provide a smaller representation . Only takes the - * first model of the structure. If chainName is provided only return a - * structure containing that Chain ID. Converts lower case chain IDs to - * upper case if structure does not contain a chain with that ID. - * - * @param s - * @param chainId - * @return Structure - * @since 3.0 - * @deprecated Use {@link StructureIdentifier#reduce(Structure)} instead (v. 4.2.0) - */ - @Deprecated - public static Structure getReducedStructure(Structure s, - String chainId) throws StructureException { - // since we deal here with structure alignments, - // only use Model 1... - - Structure newS = new StructureImpl(); - newS.setPDBCode(s.getPDBCode()); - newS.setPDBHeader(s.getPDBHeader()); - newS.setName(s.getName()); - newS.setSSBonds(s.getSSBonds()); - newS.setDBRefs(s.getDBRefs()); - newS.setSites(s.getSites()); - newS.setBiologicalAssembly(s.isBiologicalAssembly()); - newS.setEntityInfos(s.getEntityInfos()); - newS.setSSBonds(s.getSSBonds()); - newS.setSites(s.getSites()); - - if (chainId != null) - chainId = chainId.trim(); - - if (chainId == null || chainId.equals("")) { - // only get model 0 - List model0 = s.getModel(0); - for (Chain c : model0) { - newS.addChain(c); - } - return newS; - - } - - Chain c = null; - try { - c = s.getChainByPDB(chainId); - } catch (StructureException e) { - logger.warn(e.getMessage() + ". Chain id " + chainId - + " did not match, trying upper case Chain id."); - c = s.getChainByPDB(chainId.toUpperCase()); - - } - if (c != null) { - newS.addChain(c); - for (EntityInfo comp : s.getEntityInfos()) { - if (comp.getChainIds() != null - && comp.getChainIds().contains(c.getChainID())) { - // found matching entity info. set description... - newS.getPDBHeader().setDescription( - "Chain " + c.getChainID() + " of " + s.getPDBCode() - + " " + comp.getDescription()); - } - } - } - - return newS; - } - - public static String convertAtomsToSeq(Atom[] atoms) { - - StringBuilder buf = new StringBuilder(); - Group prevGroup = null; - for (Atom a : atoms) { - Group g = a.getGroup(); - if (prevGroup != null) { - if (prevGroup.equals(g)) { - // we add each group only once. - continue; - } - } - String code3 = g.getPDBName(); - Character code1 = get1LetterCodeAmino(code3); - if (code1 == null) - code1 = UNKNOWN_GROUP_LABEL; - - buf.append(code1); - - prevGroup = g; - - } - return buf.toString(); - } - - /** - * Get a group represented by a ResidueNumber. - * - * @param struc - * a {@link Structure} - * @param pdbResNum - * a {@link ResidueNumber} - * @return a group in the structure that is represented by the pdbResNum. - * @throws StructureException - * if the group cannot be found. - */ - public static Group getGroupByPDBResidueNumber(Structure struc, - ResidueNumber pdbResNum) throws StructureException { - if (struc == null || pdbResNum == null) { - throw new IllegalArgumentException("Null argument(s)."); - } - - Chain chain = struc.getPolyChainByPDB(pdbResNum.getChainName()); - - return chain.getGroupByPDB(pdbResNum); - } - - /** - * Returns the set of intra-chain contacts for the given chain for given - * atom names, i.e. the contact map. Uses a geometric hashing algorithm that - * speeds up the calculation without need of full distance matrix. The - * parsing mode {@link FileParsingParameters#setAlignSeqRes(boolean)} needs - * to be set to true for this to work. - * - * @param chain - * @param atomNames - * the array with atom names to be used. Beware: CA will do both - * C-alphas an Calciums if null all non-H atoms of non-hetatoms - * will be used - * @param cutoff - * @return - */ - public static AtomContactSet getAtomsInContact(Chain chain, - String[] atomNames, double cutoff) { - Grid grid = new Grid(cutoff); - - Atom[] atoms = null; - if (atomNames == null) { - atoms = getAllNonHAtomArray(chain, false); - } else { - atoms = getAtomArray(chain, atomNames); - } - // If tha - if(atoms.length==0){ - logger.warn("No atoms found for buidling grid!"); - return new AtomContactSet(cutoff); - } - grid.addAtoms(atoms); - - return grid.getAtomContacts(); - } - - /** - * Returns the set of intra-chain contacts for the given chain for all non-H - * atoms of non-hetatoms, i.e. the contact map. Uses a geometric hashing - * algorithm that speeds up the calculation without need of full distance - * matrix. The parsing mode - * {@link FileParsingParameters#setAlignSeqRes(boolean)} needs to be set to - * true for this to work. - * - * @param chain - * @param cutoff - * @return - */ - public static AtomContactSet getAtomsInContact(Chain chain, double cutoff) { - return getAtomsInContact(chain, (String[]) null, cutoff); - } - - /** - * Returns the set of intra-chain contacts for the given chain for C-alpha - * atoms (including non-standard aminoacids appearing as HETATM groups), - * i.e. the contact map. Uses a geometric hashing algorithm that speeds up - * the calculation without need of full distance matrix. The parsing mode - * {@link FileParsingParameters#setAlignSeqRes(boolean)} needs to be set to - * true for this to work. - * - * @param chain - * @param cutoff - * @return - * @see #getRepresentativeAtomsInContact(Chain, double) - */ - public static AtomContactSet getAtomsCAInContact(Chain chain, double cutoff) { - Grid grid = new Grid(cutoff); - - Atom[] atoms = getAtomCAArray(chain); - - grid.addAtoms(atoms); - - return grid.getAtomContacts(); - } - - /** - * Returns the set of intra-chain contacts for the given chain for C-alpha - * or C3' atoms (including non-standard aminoacids appearing as HETATM - * groups), i.e. the contact map. Uses a geometric hashing algorithm that - * speeds up the calculation without need of full distance matrix. - * - * @param chain - * @param cutoff - * @return - * @since Biojava 4.1.0 - */ - public static AtomContactSet getRepresentativeAtomsInContact(Chain chain, - double cutoff) { - Grid grid = new Grid(cutoff); - - Atom[] atoms = getRepresentativeAtomArray(chain); - - grid.addAtoms(atoms); - - return grid.getAtomContacts(); - } - - /** - * Returns the set of inter-chain contacts between the two given chains for - * the given atom names. Uses a geometric hashing algorithm that speeds up - * the calculation without need of full distance matrix. The parsing mode - * {@link FileParsingParameters#setAlignSeqRes(boolean)} needs to be set to - * true for this to work. - * - * @param chain1 - * @param chain2 - * @param atomNames - * the array with atom names to be used. For Calphas use {"CA"}, - * if null all non-H atoms will be used. Note HET atoms are - * ignored unless this parameter is null. - * @param cutoff - * @param hetAtoms - * if true HET atoms are included, if false they are not - * @return - */ - public static AtomContactSet getAtomsInContact(Chain chain1, Chain chain2, - String[] atomNames, double cutoff, boolean hetAtoms) { - Grid grid = new Grid(cutoff); - Atom[] atoms1 = null; - Atom[] atoms2 = null; - if (atomNames == null) { - atoms1 = getAllNonHAtomArray(chain1, hetAtoms); - atoms2 = getAllNonHAtomArray(chain2, hetAtoms); - } else { - atoms1 = getAtomArray(chain1, atomNames); - atoms2 = getAtomArray(chain2, atomNames); - } - grid.addAtoms(atoms1, atoms2); - - return grid.getAtomContacts(); - } - - /** - * Returns the set of inter-chain contacts between the two given chains for - * all non-H atoms. Uses a geometric hashing algorithm that speeds up the - * calculation without need of full distance matrix. The parsing mode - * {@link FileParsingParameters#setAlignSeqRes(boolean)} needs to be set to - * true for this to work. - * - * @param chain1 - * @param chain2 - * @param cutoff - * @param hetAtoms - * if true HET atoms are included, if false they are not - * @return - */ - public static AtomContactSet getAtomsInContact(Chain chain1, Chain chain2, - double cutoff, boolean hetAtoms) { - return getAtomsInContact(chain1, chain2, null, cutoff, hetAtoms); - } - - /** - * Finds Groups in {@code structure} that contain at least one Atom that is - * within {@code radius} Angstroms of {@code centroid}. - * - * @param structure - * The structure from which to find Groups - * @param centroid - * The centroid of the shell - * @param excludeResidues - * A list of ResidueNumbers to exclude - * @param radius - * The radius from {@code centroid}, in Angstroms - * @param includeWater - * Whether to include Groups whose only atoms are water - * @param useAverageDistance - * When set to true, distances are the arithmetic mean (1-norm) - * of the distances of atoms that belong to the group and that - * are within the shell; otherwise, distances are the minimum of - * these values - * @return A map of Groups within (or partially within) the shell, to their - * distances in Angstroms - */ - public static Map getGroupDistancesWithinShell( - Structure structure, Atom centroid, - Set excludeResidues, double radius, - boolean includeWater, boolean useAverageDistance) { - - // for speed, we avoid calculating square roots - radius = radius * radius; - - Map distances = new HashMap(); - - // we only need this if we're averaging distances - // note that we can't use group.getAtoms().size() because some the - // group's atoms be outside the shell - Map atomCounts = new HashMap(); - - for (Chain chain : structure.getChains()) { - groupLoop: for (Group chainGroup : chain.getAtomGroups()) { - - // exclude water - if (!includeWater && chainGroup.isWater()) - continue; - - // check blacklist of residue numbers - for (ResidueNumber rn : excludeResidues) { - if (rn.equals(chainGroup.getResidueNumber())) - continue groupLoop; - } - - for (Atom testAtom : chainGroup.getAtoms()) { - - // use getDistanceFast as we are doing a lot of comparisons - double dist = Calc.getDistanceFast(centroid, testAtom); - - // if we're the shell - if (dist <= radius) { - if (!distances.containsKey(chainGroup)) - distances.put(chainGroup, Double.POSITIVE_INFINITY); - if (useAverageDistance) { - // sum the distance; we'll divide by the total - // number later - // here, we CANNOT use fastDistance (distance - // squared) because we want the arithmetic mean - distances.put(chainGroup, distances.get(chainGroup) - + Math.sqrt(dist)); - if (!atomCounts.containsKey(chainGroup)) - atomCounts.put(chainGroup, 0); - atomCounts.put(chainGroup, - atomCounts.get(chainGroup) + 1); - } else { - // take the minimum distance among all atoms of - // chainGroup - // note that we can't break here because we might - // find a smaller distance - if (dist < distances.get(chainGroup)) { - distances.put(chainGroup, dist); - } - } - } - - } - } - } - - if (useAverageDistance) { - for (Map.Entry entry : distances.entrySet()) { - int count = atomCounts.get(entry.getKey()); - distances.put(entry.getKey(), entry.getValue() / count); - } - } else { - // in this case we used getDistanceFast - for (Map.Entry entry : distances.entrySet()) { - distances.put(entry.getKey(), Math.sqrt(entry.getValue())); - } - } - - return distances; - - } - - public static Set getGroupsWithinShell(Structure structure, - Atom atom, Set excludeResidues, double distance, - boolean includeWater) { - - // square the distance to use as a comparison against getDistanceFast - // which returns the square of a distance. - distance = distance * distance; - - Set returnSet = new LinkedHashSet(); - for (Chain chain : structure.getChains()) { - groupLoop: for (Group chainGroup : chain.getAtomGroups()) { - if (!includeWater && chainGroup.isWater()) - continue; - for (ResidueNumber rn : excludeResidues) { - if (rn.equals(chainGroup.getResidueNumber())) - continue groupLoop; - } - for (Atom atomB : chainGroup.getAtoms()) { - - // use getDistanceFast as we are doing a lot of comparisons - double dist = Calc.getDistanceFast(atom, atomB); - if (dist <= distance) { - returnSet.add(chainGroup); - break; - } - - } - } - } - return returnSet; - } - - /** - *

    - * Returns a Set of Groups in a structure within the distance specified of a - * given group. - *

    - *

    - * Updated 18-Sep-2015 sroughley to return a Set so only a unique set of - * Groups returned - * - * @param structure - * The structure to work with - * @param group - * The 'query' group - * @param distance - * The cutoff distance - * @param includeWater - * Should water residues be included in the output? - * @return {@link LinkedHashSet} of {@link Group}s within at least one atom - * with {@code distance} of at least one atom in {@code group} - */ - public static Set getGroupsWithinShell(Structure structure, - Group group, double distance, boolean includeWater) { - - Set returnList = new LinkedHashSet(); - - Set excludeGroups = new HashSet(); - excludeGroups.add(group.getResidueNumber()); - for (Atom atom : group.getAtoms()) { - Set set = getGroupsWithinShell(structure, atom, - excludeGroups, distance, includeWater); - returnList.addAll(set); - } - - return returnList; - } - - /** - * Remove all models from a Structure and keep only the first - * - * @param s - * original Structure - * @return a structure that contains only the first model - * @since 3.0.5 - */ - public static Structure removeModels(Structure s) { - if (s.nrModels() == 1) - return s; - - Structure n = new StructureImpl(); - // go through whole substructure and clone ... - - // copy structure data - - n.setPDBCode(s.getPDBCode()); - n.setName(s.getName()); - - // TODO: do deep copying of data! - n.setPDBHeader(s.getPDBHeader()); - n.setDBRefs(s.getDBRefs()); - - n.setSites(s.getSites()); - - n.setChains(s.getModel(0)); - - return n; - - } - - /** - * Removes all polymeric and solvent groups from a list of groups - * - */ - public static List filterLigands(List allGroups) { - - List groups = new ArrayList(); - for (Group g : allGroups) { - - if ( g.isPolymeric()) - continue; - - if (!g.isWater()) { - groups.add(g); - } - } - - return groups; - } - - /** - * Short version of {@link #getStructure(String, PDBFileParser, AtomCache)} - * which creates new parsers when needed - * - * @param name - * @return - * @throws IOException - * @throws StructureException - */ - public static Structure getStructure(String name) throws IOException, - StructureException { - return StructureTools.getStructure(name, null, null); - } - - /** - * Flexibly get a structure from an input String. The intent of this method - * is to allow any reasonable string which could refer to a structure to be - * correctly parsed. The following are currently supported: - *

      - *
    1. Filename (if name refers to an existing file) - *
    2. PDB ID - *
    3. SCOP domains - *
    4. PDP domains - *
    5. Residue ranges - *
    6. Other formats supported by AtomCache - *
    - * - * @param name - * Some reference to the protein structure - * @param parser - * A clean PDBFileParser to use if it is a file. If null, a - * PDBFileParser will be instantiated if needed. - * @param cache - * An AtomCache to use if the structure can be fetched from the - * PDB. If null, a AtomCache will be instantiated if needed. - * @return A Structure object - * @throws IOException - * if name is an existing file, but doesn't parse correctly - * @throws StructureException - * if the format is unknown, or if AtomCache throws an - * exception. - */ - public static Structure getStructure(String name, PDBFileParser parser, - AtomCache cache) throws IOException, StructureException { - File f = new File(FileDownloadUtils.expandUserHome(name)); - if (f.exists()) { - if (parser == null) { - parser = new PDBFileParser(); - } - InputStream inStream = new FileInputStream(f); - return parser.parsePDBFile(inStream); - } else { - if (cache == null) { - cache = new AtomCache(); - } - return cache.getStructure(name); - } - } - - /** - * @deprecated use {@link Chain#isProtein()} instead. - */ - @Deprecated - public static boolean isProtein(Chain c) { - - return c.isProtein(); - } - - /** - * @deprecated use {@link Chain#isNucleicAcid()} instead. - */ - @Deprecated - public static boolean isNucleicAcid(Chain c) { - return c.isNucleicAcid(); - } - - /** - * @deprecated use {@link Chain#getPredominantGroupType()} instead. - */ - @Deprecated - public static GroupType getPredominantGroupType(Chain c) { - return c.getPredominantGroupType(); - } - - /** - * @deprecated use {@link Chain#isWaterOnly()} instead. - */ - @Deprecated - public static boolean isChainWaterOnly(Chain c) { - return c.isWaterOnly(); - } - - /** - * @deprecated use {@link Chain#isPureNonPolymer()} instead. - */ - @Deprecated - public static boolean isChainPureNonPolymer(Chain c) { - - return c.isPureNonPolymer(); - } - - /** - * Cleans up the structure's alternate location (altloc) groups. All alternate location groups should have all atoms (except - * in the case of microheterogenity) or when a deuterium exists. - * Ensure that all the alt loc groups have all the atoms in the main group. - * @param structure The Structure to be cleaned up - */ - public static void cleanUpAltLocs(Structure structure) { - for (int i =0; i< structure.nrModels() ; i++){ - for (Chain chain : structure.getModel(i)) { - for (Group group : chain.getAtomGroups()) { - for (Group altLocGroup : group.getAltLocs()) { - for ( Atom groupAtom : group.getAtoms()) { - // If this alt loc doesn't have this atom - if (! altLocGroup.hasAtom(groupAtom.getName())) { - // Fix for microheterogenity - if (altLocGroup.getPDBName().equals(group.getPDBName())) { - // If it's a Hydrogen then we check for it's Deuterated brother - if(!hasDeuteratedEquiv(groupAtom, altLocGroup)){ - altLocGroup.addAtom(groupAtom); - } - } - } - } - } - } - } - } - } - - /** - * Check to see if an Deuterated atom has a non deuterated brother in the group. - * @param atom the input atom that is putatively deuterium - * @param currentGroup the group the atom is in - * @return true if the atom is deuterated and it's hydrogen equive exists. - */ - public static boolean hasNonDeuteratedEquiv(Atom atom, Group currentGroup) { - if(atom.getElement()==Element.D && currentGroup.hasAtom(replaceFirstChar(atom.getName(),'D', 'H'))) { - // If it's deuterated and has a non-deuterated brother - return true; - } - return false; - } - - /** - * Check to see if a Hydrogen has a Deuterated brother in the group. - * @param atom the input atom that is putatively hydorgen - * @param currentGroup the group the atom is in - * @return true if the atom is hydrogen and it's Deuterium equiv exists. - */ - public static boolean hasDeuteratedEquiv(Atom atom, Group currentGroup) { - if(atom.getElement()==Element.H && currentGroup.hasAtom(replaceFirstChar(atom.getName(),'H', 'D'))) { - // If it's hydrogen and has a deuterated brother - return true; - } - return false; - } - - private static String replaceFirstChar(String name, char c, char d) { - if(name.charAt(0)==c){ - return name.replaceFirst(String.valueOf(c), String.valueOf(d)); - } - return name; - } - - /** - * Remove all atoms but the representative atoms (C alphas or phosphates) from the given structure. - * @param structure the structure - * @since 5.4.0 - */ - public static void reduceToRepresentativeAtoms(Structure structure) { - for (int modelIdx = 0; modelIdx atoms = g.getAtoms(); - if (g.isAminoAcid()) { - atoms.removeIf(a->!a.getName().equals(CA_ATOM_NAME)); - } else if (g.isNucleotide()) { - atoms.removeIf(a->!a.getName().equals(NUCLEOTIDE_REPRESENTATIVE)); - } - // else we keep all other atoms. We are concerned only about aminoacids and nucleotides that make up the bulk of the structures - } - } - } - } + /** + * Expand a set of atoms into all groups from the same structure. + *

    + * If the structure is set, only the first atom is used (assuming all + * atoms come from the same original structure). + * If the atoms aren't linked to a structure (for instance, for cloned atoms), + * searches all chains of all atoms for groups. + * + * @param atoms Sample of atoms + * @return All groups from all chains accessible from the input atoms + */ + public static Set getAllGroupsFromSubset(Atom[] atoms) { + return getAllGroupsFromSubset(atoms, null); + } + + /** + * Expand a set of atoms into all groups from the same structure. + *

    + * If the structure is set, only the first atom is used (assuming all + * atoms come from the same original structure). + * If the atoms aren't linked to a structure (for instance, for cloned atoms), + * searches all chains of all atoms for groups. + * + * @param atoms Sample of atoms + * @param types Type of groups to return (useful for getting only ligands, for instance). + * Null gets all groups. + * @return All groups from all chains accessible from the input atoms + */ + public static Set getAllGroupsFromSubset(Atom[] atoms, GroupType types) { + // Get the full structure + Structure s = null; + if (atoms.length > 0) { + Group g = atoms[0].getGroup(); + if (g != null) { + Chain c = g.getChain(); + if (c != null) { + s = c.getStructure(); + } + } + } + // Collect all groups from the structure + Set allChains = new HashSet<>(); + if (s != null) { + allChains.addAll(s.getChains()); + } + // In case the structure wasn't set, need to use ca chains too + for (Atom a : atoms) { + Group g = a.getGroup(); + if (g != null) { + Chain c = g.getChain(); + if (c != null) { + allChains.add(c); + } + } + } + + if (allChains.isEmpty()) { + return Collections.emptySet(); + } + + // Extract all ligand groups + Set full = new HashSet<>(); + for (Chain c : allChains) { + if (types == null) { + full.addAll(c.getAtomGroups()); + } else { + full.addAll(c.getAtomGroups(types)); + } + } + + return full; + } + + + /** + * Returns and array of all non-Hydrogen atoms in the given Structure, + * optionally including HET atoms or not. Waters are not included. + * + * @param s + * @param hetAtoms if true HET atoms are included in array, if false they are not + * @return + */ + public static Atom[] getAllNonHAtomArray(Structure s, boolean hetAtoms) { + AtomIterator iter = new AtomIterator(s); + return getAllNonHAtomArray(s, hetAtoms, iter); + } + + /** + * Returns and array of all non-Hydrogen atoms in the given Structure, + * optionally including HET atoms or not. Waters are not included. + * + * @param s + * @param hetAtoms if true HET atoms are included in array, if false they are not + * @param modelNr Model number to draw atoms from + * @return + */ + public static Atom[] getAllNonHAtomArray(Structure s, boolean hetAtoms, int modelNr) { + AtomIterator iter = new AtomIterator(s, modelNr); + return getAllNonHAtomArray(s, hetAtoms, iter); + } + + private static Atom[] getAllNonHAtomArray(Structure s, boolean hetAtoms, AtomIterator iter) { + List atoms = new ArrayList<>(); + + while (iter.hasNext()) { + Atom a = iter.next(); + if (a.getElement() == Element.H) + continue; + + Group g = a.getGroup(); + + if (g.isWater()) + continue; + + if (!hetAtoms && g.getType().equals(GroupType.HETATM)) + continue; + + atoms.add(a); + } + return atoms.toArray(Atom.EmptyAtomArray); + } + + /** + * Returns and array of all non-Hydrogen atoms in the given Chain, + * optionally including HET atoms or not Waters are not included. + * + * @param c + * @param hetAtoms if true HET atoms are included in array, if false they are not + * @return + */ + public static Atom[] getAllNonHAtomArray(Chain c, boolean hetAtoms) { + List atoms = new ArrayList<>(); + + for (Group g : c.getAtomGroups()) { + if (g.isWater()) + continue; + for (Atom a : g.getAtoms()) { + + if (a.getElement() == Element.H) + continue; + + if (!hetAtoms && g.getType().equals(GroupType.HETATM)) + continue; + + atoms.add(a); + } + } + return atoms.toArray(Atom.EmptyAtomArray); + } + + /** + * Returns and array of all non-Hydrogen atoms coordinates in the given Chain, + * optionally including HET atoms or not Waters are not included. + * + * @param c + * @param hetAtoms if true HET atoms are included in array, if false they are not + * @return + */ + public static Point3d[] getAllNonHCoordsArray(Chain c, boolean hetAtoms) { + List atoms = new ArrayList<>(); + + for (Group g : c.getAtomGroups()) { + if (g.isWater()) + continue; + for (Atom a : g.getAtoms()) { + + if (a.getElement() == Element.H) + continue; + + if (!hetAtoms && g.getType().equals(GroupType.HETATM)) + continue; + + atoms.add(a.getCoordsAsPoint3d()); + } + } + return atoms.toArray(new Point3d[0]); + } + + /** + * Adds to the given atoms list, all atoms of groups that contained all + * requested atomNames, i.e. if a group does not contain all of the + * requested atom names, its atoms won't be added. + * + * @param atomNames + * @param chains + * @param atoms + */ + private static void extractAtoms(String[] atomNames, List chains, + List atoms) { + + for (Chain c : chains) { + + for (Group g : c.getAtomGroups()) { + + // a temp container for the atoms of this group + List thisGroupAtoms = new ArrayList<>(); + // flag to check if this group contains all the requested atoms. + boolean thisGroupAllAtoms = true; + for (String atomName : atomNames) { + Atom a = g.getAtom(atomName); + + if (a == null) { + // this group does not have a required atom, skip it... + thisGroupAllAtoms = false; + break; + } + thisGroupAtoms.add(a); + } + if (thisGroupAllAtoms) { + // add the atoms of this group to the array. + atoms.addAll(thisGroupAtoms); + } + + } + } + } + + /** + * Returns an array of the requested Atoms from the Chain object. Iterates + * over all groups and checks if the requested atoms are in this group, no + * matter if this is a AminoAcid or Hetatom group. If the group does not + * contain all requested atoms then no atoms are added for that group. + * + * @param c the Chain to get the atoms from + * @param atomNames contains the atom names to be used. + * @return an Atom[] array + */ + public static Atom[] getAtomArray(Chain c, String[] atomNames) { + + List atoms = new ArrayList<>(); + + for (Group g : c.getAtomGroups()) { + + // a temp container for the atoms of this group + List thisGroupAtoms = new ArrayList<>(); + // flag to check if this group contains all the requested atoms. + boolean thisGroupAllAtoms = true; + for (String atomName : atomNames) { + Atom a = g.getAtom(atomName); + if (a == null) { + logger.debug("Group " + g.getResidueNumber() + " (" + + g.getPDBName() + + ") does not have the required atom '" + atomName + + "'"); + // this group does not have a required atom, skip it... + thisGroupAllAtoms = false; + break; + } + thisGroupAtoms.add(a); + } + + if (thisGroupAllAtoms) { + // add the atoms of this group to the array. + atoms.addAll(thisGroupAtoms); + } + + } + return atoms.toArray(Atom.EmptyAtomArray); + + } + + /** + * Returns an Atom array of the C-alpha atoms. Any atom that is a carbon and + * has CA name will be returned. + * + * @param c the structure object + * @return an Atom[] array + * @see #getRepresentativeAtomArray(Chain) + */ + public static Atom[] getAtomCAArray(Chain c) { + List atoms = new ArrayList<>(); + + for (Group g : c.getAtomGroups()) { + if (g.hasAtom(CA_ATOM_NAME) + && g.getAtom(CA_ATOM_NAME).getElement() == Element.C) { + atoms.add(g.getAtom(CA_ATOM_NAME)); + } + } + + return atoms.toArray(Atom.EmptyAtomArray); + } + + /** + * Gets a representative atom for each group that is part of the chain + * backbone. Note that modified aminoacids won't be returned as part of the + * backbone if the {@link org.biojava.nbio.structure.io.mmcif.ReducedChemCompProvider} was used to load the + * structure. + *

    + * For amino acids, the representative is a CA carbon. For nucleotides, the + * representative is the {@value #NUCLEOTIDE_REPRESENTATIVE}. Other group + * types will be ignored. + * + * @param c + * @return representative Atoms of the chain backbone + * @since Biojava 4.1.0 + */ + public static Atom[] getRepresentativeAtomArray(Chain c) { + List atoms = new ArrayList<>(); + + for (Group g : c.getAtomGroups()) { + + switch (g.getType()) { + case AMINOACID: + if (g.hasAtom(CA_ATOM_NAME) + && g.getAtom(CA_ATOM_NAME).getElement() == Element.C) { + atoms.add(g.getAtom(CA_ATOM_NAME)); + } + break; + case NUCLEOTIDE: + if (g.hasAtom(NUCLEOTIDE_REPRESENTATIVE)) { + atoms.add(g.getAtom(NUCLEOTIDE_REPRESENTATIVE)); + } + break; + default: + // don't add + } + } + + return atoms.toArray(Atom.EmptyAtomArray); + + } + + /** + * Provides an equivalent copy of Atoms in a new array. Clones everything, + * starting with parent groups and chains. The chain will only contain + * groups that are part of the input array. + * + * @param ca array of representative atoms, e.g. CA atoms + * @return Atom array + * @since Biojava 4.1.0 + */ + public static Atom[] cloneAtomArray(Atom[] ca) { + Atom[] newCA = new Atom[ca.length]; + + List model = new ArrayList<>(); + int apos = -1; + for (Atom a : ca) { + apos++; + Group parentG = a.getGroup(); + Chain parentC = parentG.getChain(); + + Chain newChain = null; + for (Chain c : model) { + if (c.getName().equals(parentC.getName())) { + newChain = c; + break; + } + } + if (newChain == null) { + newChain = new ChainImpl(); + newChain.setId(parentC.getId()); + newChain.setName(parentC.getName()); + model.add(newChain); + } + + Group parentN = (Group) parentG.clone(); + + newCA[apos] = parentN.getAtom(a.getName()); + + // if the group doesn't exist yet, this produces a StructureException + if (!newChain.hasGroupByPDB(parentN.getResidueNumber())) + newChain.addGroup(parentN); // the group doesn't exist yet in the newChain, let's add it + + } + return newCA; + } + + /** + * Clone a set of representative Atoms, but returns the parent groups + * + * @param ca Atom array + * @return Group array + */ + public static Group[] cloneGroups(Atom[] ca) { + Group[] newGroup = new Group[ca.length]; + + List model = new ArrayList<>(); + int apos = -1; + for (Atom a : ca) { + apos++; + Group parentG = a.getGroup(); + Chain parentC = parentG.getChain(); + + Chain newChain = null; + for (Chain c : model) { + if (c.getName().equals(parentC.getName())) { + newChain = c; + break; + } + } + if (newChain == null) { + newChain = new ChainImpl(); + newChain.setName(parentC.getName()); + model.add(newChain); + } + + Group ng = (Group) parentG.clone(); + newGroup[apos] = ng; + newChain.addGroup(ng); + } + return newGroup; + } + + /** + * Utility method for working with circular permutations. Creates a + * duplicated and cloned set of Calpha atoms from the input array. + * + * @param ca2 atom array + * @return cloned and duplicated set of input array + */ + public static Atom[] duplicateCA2(Atom[] ca2) { + // we don't want to rotate input atoms, do we? + Atom[] ca2clone = new Atom[ca2.length * 2]; + + int pos = 0; + + Chain c = null; + String prevChainId = ""; + for (Atom a : ca2) { + Group g = (Group) a.getGroup().clone(); // works because each group + // has only a single atom + + if (c == null) { + c = new ChainImpl(); + Chain orig = a.getGroup().getChain(); + c.setId(orig.getId()); + c.setName(orig.getName()); + } else { + Chain orig = a.getGroup().getChain(); + if (!orig.getId().equals(prevChainId)) { + c = new ChainImpl(); + c.setId(orig.getId()); + c.setName(orig.getName()); + } + } + + c.addGroup(g); + ca2clone[pos] = g.getAtom(a.getName()); + + pos++; + } + + // Duplicate ca2! + c = null; + prevChainId = ""; + for (Atom a : ca2) { + Group g = (Group) a.getGroup().clone(); + + if (c == null) { + c = new ChainImpl(); + Chain orig = a.getGroup().getChain(); + c.setId(orig.getId()); + c.setName(orig.getName()); + } else { + Chain orig = a.getGroup().getChain(); + if (!orig.getId().equals(prevChainId)) { + c = new ChainImpl(); + c.setId(orig.getId()); + c.setName(orig.getName()); + } + } + + c.addGroup(g); + ca2clone[pos] = g.getAtom(a.getName()); + + pos++; + } + + return ca2clone; + + } + + /** + * Return an Atom array of the C-alpha atoms. Any atom that is a carbon and + * has CA name will be returned. + * + * @param s the structure object + * @return an Atom[] array + * @see #getRepresentativeAtomArray(Structure) + */ + public static Atom[] getAtomCAArray(Structure s) { + + List atoms = new ArrayList<>(); + + for (Chain c : s.getChains()) { + for (Group g : c.getAtomGroups()) { + if (g.hasAtom(CA_ATOM_NAME) + && g.getAtom(CA_ATOM_NAME).getElement() == Element.C) { + atoms.add(g.getAtom(CA_ATOM_NAME)); + } + } + } + + return atoms.toArray(Atom.EmptyAtomArray); + } + + /** + * Gets a representative atom for each group that is part of the chain + * backbone. Note that modified aminoacids won't be returned as part of the + * backbone if the {@link org.biojava.nbio.structure.io.mmcif.ReducedChemCompProvider} was used to load the + * structure. + *

    + * For amino acids, the representative is a CA carbon. For nucleotides, the + * representative is the {@value #NUCLEOTIDE_REPRESENTATIVE}. Other group + * types will be ignored. + * + * @param s Input structure + * @return representative Atoms of the structure backbone + * @since Biojava 4.1.0 + */ + public static Atom[] getRepresentativeAtomArray(Structure s) { + + List atoms = new ArrayList<>(); + + for (Chain c : s.getChains()) { + Atom[] chainAtoms = getRepresentativeAtomArray(c); + atoms.addAll(Arrays.asList(chainAtoms)); + } + + return atoms.toArray(Atom.EmptyAtomArray); + } + + /** + * Return an Atom array of the main chain atoms: CA, C, N, O Any group that + * contains those atoms will be included, be it a standard aminoacid or not + * + * @param s the structure object + * @return an Atom[] array + */ + public static Atom[] getBackboneAtomArray(Structure s) { + + List atoms = new ArrayList<>(); + + for (Chain c : s.getChains()) { + for (Group g : c.getAtomGroups()) { + if (g.hasAminoAtoms()) { + // this means we will only take atoms grom groups that have + // complete backbones + for (Atom a : g.getAtoms()) { + switch (g.getType()) { + case NUCLEOTIDE: + // Nucleotide backbone + if (a.getName().equals(C1_ATOM_NAME)) + atoms.add(a); + if (a.getName().equals(C2_ATOM_NAME)) + atoms.add(a); + if (a.getName().equals(C3_ATOM_NAME)) + atoms.add(a); + if (a.getName().equals(C4_ATOM_NAME)) + atoms.add(a); + if (a.getName().equals(O2_ATOM_NAME)) + atoms.add(a); + if (a.getName().equals(O3_ATOM_NAME)) + atoms.add(a); + if (a.getName().equals(O4_ATOM_NAME)) + atoms.add(a); + if (a.getName().equals(O5_ATOM_NAME)) + atoms.add(a); + if (a.getName().equals(OP1_ATOM_NAME)) + atoms.add(a); + if (a.getName().equals(OP2_ATOM_NAME)) + atoms.add(a); + if (a.getName().equals(P_ATOM_NAME)) + atoms.add(a); + // TODO Allow C4* names as well as C4'? -SB 3/2015 + break; + case AMINOACID: + default: + // we do it this way instead of with g.getAtom() to + // be sure we always use the same order as original + if (a.getName().equals(CA_ATOM_NAME)) + atoms.add(a); + if (a.getName().equals(C_ATOM_NAME)) + atoms.add(a); + if (a.getName().equals(N_ATOM_NAME)) + atoms.add(a); + if (a.getName().equals(O_ATOM_NAME)) + atoms.add(a); + break; + } + } + } + } + + } + + return atoms.toArray(Atom.EmptyAtomArray); + } + + /** + * Convert three character amino acid codes into single character e.g. + * convert CYS to C. Valid 3-letter codes will be those of the standard 20 + * amino acids plus MSE, CSE, SEC, PYH, PYL (see the {@link #aminoAcids} + * map) + * + * @param groupCode3 a three character amino acid representation String + * @return the 1 letter code, or null if the given 3 letter code does not + * correspond to an amino acid code + * @see {@link #get1LetterCode(String)} + */ + public static Character get1LetterCodeAmino(String groupCode3) { + return aminoAcids.get(groupCode3); + } + + /** + * Convert a three letter amino acid or nucleotide code into a single + * character code. If the code does not correspond to an amino acid or + * nucleotide, returns {@link #UNKNOWN_GROUP_LABEL}. + *

    + * Returned null for nucleotides prior to version 4.0.1. + * + * @param groupCode3 three letter representation + * @return The 1-letter abbreviation + */ + public static Character get1LetterCode(String groupCode3) { + + Character code1; + + // is it a standard amino acid ? + code1 = get1LetterCodeAmino(groupCode3); + + if (code1 == null) { + // hm groupCode3 is not standard + // perhaps it is a nucleotide? + groupCode3 = groupCode3.trim(); + if (isNucleotide(groupCode3)) { + code1 = nucleotides30.get(groupCode3); + if (code1 == null) { + code1 = nucleotides23.get(groupCode3); + } + if (code1 == null) { + code1 = UNKNOWN_GROUP_LABEL; + } + } else { + // does not seem to be so let's assume it is + // nonstandard aminoacid and label it "X" + // logger.warning("unknown group name "+groupCode3 ); + code1 = UNKNOWN_GROUP_LABEL; + } + } + + return code1; + + } + + /** + * Test if the three-letter code of an ATOM entry corresponds to a + * nucleotide or to an aminoacid. + * + * @param groupCode3 3-character code for a group. + */ + public static boolean isNucleotide(String groupCode3) { + String code = groupCode3.trim(); + return nucleotides30.containsKey(code) + || nucleotides23.containsKey(code); + } + + /** + * Reduce a structure to provide a smaller representation . Only takes the + * first model of the structure. If chainName is provided only return a + * structure containing that Chain ID. Converts lower case chain IDs to + * upper case if structure does not contain a chain with that ID. + * + * @param s + * @param chainId + * @return Structure + * @since 3.0 + * @deprecated Use {@link StructureIdentifier#reduce(Structure)} instead (v. 4.2.0) + */ + @Deprecated + public static Structure getReducedStructure(Structure s, + String chainId) throws StructureException { + // since we deal here with structure alignments, + // only use Model 1... + + Structure newS = new StructureImpl(); + newS.setPDBCode(s.getPDBCode()); + newS.setPDBHeader(s.getPDBHeader()); + newS.setName(s.getName()); + newS.setSSBonds(s.getSSBonds()); + newS.setDBRefs(s.getDBRefs()); + newS.setSites(s.getSites()); + newS.setBiologicalAssembly(s.isBiologicalAssembly()); + newS.setEntityInfos(s.getEntityInfos()); + newS.setSSBonds(s.getSSBonds()); + newS.setSites(s.getSites()); + + if (chainId != null) + chainId = chainId.trim(); + + if (chainId == null || chainId.isEmpty()) { + // only get model 0 + List model0 = s.getModel(0); + for (Chain c : model0) { + newS.addChain(c); + } + return newS; + + } + + Chain c; + try { + c = s.getChainByPDB(chainId); + } catch (StructureException e) { + logger.warn(e.getMessage() + ". Chain id " + chainId + + " did not match, trying upper case Chain id."); + c = s.getChainByPDB(chainId.toUpperCase()); + + } + if (c != null) { + newS.addChain(c); + for (EntityInfo comp : s.getEntityInfos()) { + if (comp.getChainIds() != null + && comp.getChainIds().contains(c.getChainID())) { + // found matching entity info. set description... + newS.getPDBHeader().setDescription( + "Chain " + c.getChainID() + " of " + s.getPDBCode() + + " " + comp.getDescription()); + } + } + } + + return newS; + } + + public static String convertAtomsToSeq(Atom[] atoms) { + + StringBuilder buf = new StringBuilder(); + Group prevGroup = null; + for (Atom a : atoms) { + Group g = a.getGroup(); + if (prevGroup != null) { + if (prevGroup.equals(g)) { + // we add each group only once. + continue; + } + } + String code3 = g.getPDBName(); + Character code1 = get1LetterCodeAmino(code3); + if (code1 == null) + code1 = UNKNOWN_GROUP_LABEL; + + buf.append(code1); + + prevGroup = g; + + } + return buf.toString(); + } + + /** + * Get a group represented by a ResidueNumber. + * + * @param struc a {@link Structure} + * @param pdbResNum a {@link ResidueNumber} + * @return a group in the structure that is represented by the pdbResNum. + * @throws StructureException if the group cannot be found. + */ + public static Group getGroupByPDBResidueNumber(Structure struc, + ResidueNumber pdbResNum) throws StructureException { + if (struc == null || pdbResNum == null) { + throw new IllegalArgumentException("Null argument(s)."); + } + + Chain chain = struc.getPolyChainByPDB(pdbResNum.getChainName()); + + return chain.getGroupByPDB(pdbResNum); + } + + /** + * Returns the set of intra-chain contacts for the given chain for given + * atom names, i.e. the contact map. Uses a spatial hashing algorithm that + * speeds up the calculation without need of full distance matrix. The + * parsing mode {@link FileParsingParameters#setAlignSeqRes(boolean)} needs + * to be set to true for this to work. + * + * @param chain + * @param atomNames the array with atom names to be used. Beware: CA will do both + * C-alphas an Calciums if null all non-H atoms of non-hetatoms + * will be used + * @param cutoff + * @return + */ + public static AtomContactSet getAtomsInContact(Chain chain, + String[] atomNames, double cutoff) { + Grid grid = new Grid(cutoff); + + Atom[] atoms; + if (atomNames == null) { + atoms = getAllNonHAtomArray(chain, false); + } else { + atoms = getAtomArray(chain, atomNames); + } + // If tha + if (atoms.length == 0) { + logger.warn("No atoms found for buidling grid!"); + return new AtomContactSet(cutoff); + } + grid.addAtoms(atoms); + + return grid.getAtomContacts(); + } + + /** + * Returns the set of intra-chain contacts for the given chain for all non-H + * atoms of non-hetatoms, i.e. the contact map. Uses a spatial hashing + * algorithm that speeds up the calculation without need of full distance + * matrix. The parsing mode + * {@link FileParsingParameters#setAlignSeqRes(boolean)} needs to be set to + * true for this to work. + * + * @param chain + * @param cutoff + * @return + */ + public static AtomContactSet getAtomsInContact(Chain chain, double cutoff) { + return getAtomsInContact(chain, null, cutoff); + } + + /** + * Returns the set of intra-chain contacts for the given chain for C-alpha + * atoms (including non-standard aminoacids appearing as HETATM groups), + * i.e. the contact map. Uses a spatial hashing algorithm that speeds up + * the calculation without need of full distance matrix. The parsing mode + * {@link FileParsingParameters#setAlignSeqRes(boolean)} needs to be set to + * true for this to work. + * + * @param chain + * @param cutoff + * @return + * @see #getRepresentativeAtomsInContact(Chain, double) + */ + public static AtomContactSet getAtomsCAInContact(Chain chain, double cutoff) { + Grid grid = new Grid(cutoff); + + Atom[] atoms = getAtomCAArray(chain); + + grid.addAtoms(atoms); + + return grid.getAtomContacts(); + } + + /** + * Returns the set of intra-chain contacts for the given chain for C-alpha + * or C3' atoms (including non-standard aminoacids appearing as HETATM + * groups), i.e. the contact map. Uses a spatial hashing algorithm that + * speeds up the calculation without need of full distance matrix. + * + * @param chain + * @param cutoff + * @return + * @since Biojava 4.1.0 + */ + public static AtomContactSet getRepresentativeAtomsInContact(Chain chain, + double cutoff) { + Grid grid = new Grid(cutoff); + + Atom[] atoms = getRepresentativeAtomArray(chain); + + grid.addAtoms(atoms); + + return grid.getAtomContacts(); + } + + /** + * Returns the set of inter-chain contacts between the two given chains for + * the given atom names. Uses a spatial hashing algorithm that speeds up + * the calculation without need of full distance matrix. The parsing mode + * {@link FileParsingParameters#setAlignSeqRes(boolean)} needs to be set to + * true for this to work. + * + * @param chain1 + * @param chain2 + * @param atomNames the array with atom names to be used. For Calphas use {"CA"}, + * if null all non-H atoms will be used. Note HET atoms are + * ignored unless this parameter is null. + * @param cutoff + * @param hetAtoms if true HET atoms are included, if false they are not + * @return + */ + public static AtomContactSet getAtomsInContact(Chain chain1, Chain chain2, + String[] atomNames, double cutoff, boolean hetAtoms) { + Grid grid = new Grid(cutoff); + Atom[] atoms1; + Atom[] atoms2; + if (atomNames == null) { + atoms1 = getAllNonHAtomArray(chain1, hetAtoms); + atoms2 = getAllNonHAtomArray(chain2, hetAtoms); + } else { + atoms1 = getAtomArray(chain1, atomNames); + atoms2 = getAtomArray(chain2, atomNames); + } + grid.addAtoms(atoms1, atoms2); + + return grid.getAtomContacts(); + } + + /** + * Returns the set of inter-chain contacts between the two given chains for + * all non-H atoms. Uses a spatial hashing algorithm that speeds up the + * calculation without need of full distance matrix. The parsing mode + * {@link FileParsingParameters#setAlignSeqRes(boolean)} needs to be set to + * true for this to work. + * + * @param chain1 + * @param chain2 + * @param cutoff + * @param hetAtoms if true HET atoms are included, if false they are not + * @return + */ + public static AtomContactSet getAtomsInContact(Chain chain1, Chain chain2, + double cutoff, boolean hetAtoms) { + return getAtomsInContact(chain1, chain2, null, cutoff, hetAtoms); + } + + /** + * Finds Groups in {@code structure} that contain at least one Atom that is + * within {@code radius} Angstroms of {@code centroid}. + * + * @param structure The structure from which to find Groups + * @param centroid The centroid of the shell + * @param excludeResidues A list of ResidueNumbers to exclude + * @param radius The radius from {@code centroid}, in Angstroms + * @param includeWater Whether to include Groups whose only atoms are water + * @param useAverageDistance When set to true, distances are the arithmetic mean (1-norm) + * of the distances of atoms that belong to the group and that + * are within the shell; otherwise, distances are the minimum of + * these values + * @return A map of Groups within (or partially within) the shell, to their + * distances in Angstroms + */ + public static Map getGroupDistancesWithinShell( + Structure structure, Atom centroid, + Set excludeResidues, double radius, + boolean includeWater, boolean useAverageDistance) { + + // for speed, we avoid calculating square roots + radius = radius * radius; + + Map distances = new HashMap<>(); + + // we only need this if we're averaging distances + // note that we can't use group.getAtoms().size() because some the + // group's atoms be outside the shell + Map atomCounts = useAverageDistance ? new HashMap<>() : null; + + for (Chain chain : structure.getChains()) { + groupLoop: + for (Group chainGroup : chain.getAtomGroups()) { + + // exclude water + if (!includeWater && chainGroup.isWater()) + continue; + + ResidueNumber residue = chainGroup.getResidueNumber(); + + // check blacklist of residue numbers + for (ResidueNumber rn : excludeResidues) { + if (rn.equals(residue)) + continue groupLoop; + } + + for (Atom testAtom : chainGroup.getAtoms()) { + + // use getDistanceFast as we are doing a lot of comparisons + double dist = Calc.getDistanceSqr(centroid, testAtom); + + // if we're the shell + if (dist <= radius) { + + + if (useAverageDistance) { + // sum the distance; we'll divide by the total + // number later + // here, we CANNOT use fastDistance (distance + // squared) because we want the arithmetic mean + distances.put(chainGroup, distances.get(chainGroup) + Math.sqrt(dist)); + atomCounts.compute(chainGroup, (Group g, Integer y) -> y + 1); + } else { + // take the minimum distance among all atoms of + // chainGroup + // note that we can't break here because we might + // find a smaller distance + distances.merge(chainGroup, dist, Math::min); + } + } + + } + } + } + + if (useAverageDistance) { + distances.replaceAll((k, v) -> v / (int) atomCounts.get(k)); + } else { + // in this case we used getDistanceFast + distances.replaceAll((k, v) -> Math.sqrt(v)); + } + + return distances; + + } + + public static Set getGroupsWithinShell(Structure structure, + Atom atom, Set excludeResidues, double distance, + boolean includeWater) { + + // square the distance to use as a comparison against getDistanceFast + // which returns the square of a distance. + distance = distance * distance; + + Set returnSet = null; + for (Chain chain : structure.getChains()) { + groupLoop: + for (Group chainGroup : chain.getAtomGroups()) { + if (!includeWater && chainGroup.isWater()) + continue; + + ResidueNumber residue = chainGroup.getResidueNumber(); + for (ResidueNumber rn : excludeResidues) { + if (rn.equals(residue)) + continue groupLoop; + } + + for (Atom atomB : chainGroup.getAtoms()) { + + // use getDistanceFast as we are doing a lot of comparisons + double dist = Calc.getDistanceSqr(atom, atomB); + if (dist <= distance) { + if (returnSet==null) returnSet = new LinkedHashSet<>(); + returnSet.add(chainGroup); + break; + } + + } + } + } + return returnSet == null ? Collections.EMPTY_SET : returnSet; + } + + /** + *

    + * Returns a Set of Groups in a structure within the distance specified of a + * given group. + *

    + *

    + * Updated 18-Sep-2015 sroughley to return a Set so only a unique set of + * Groups returned + * + * @param structure The structure to work with + * @param group The 'query' group + * @param distance The cutoff distance + * @param includeWater Should water residues be included in the output? + * @return {@link LinkedHashSet} of {@link Group}s within at least one atom + * with {@code distance} of at least one atom in {@code group} + */ + public static Set getGroupsWithinShell(Structure structure, + Group group, double distance, boolean includeWater) { + + Set returnList = new LinkedHashSet<>(); + + Set excludeGroups = new HashSet<>(); + excludeGroups.add(group.getResidueNumber()); + for (Atom atom : group.getAtoms()) { + returnList.addAll(getGroupsWithinShell(structure, atom, excludeGroups, distance, includeWater)); + } + + return returnList; + } + + /** + * Remove all models from a Structure and keep only the first + * + * @param s original Structure + * @return a structure that contains only the first model + * @since 3.0.5 + */ + public static Structure removeModels(Structure s) { + if (s.nrModels() == 1) + return s; + + Structure n = new StructureImpl(); + // go through whole substructure and clone ... + + // copy structure data + + n.setPDBCode(s.getPDBCode()); + n.setName(s.getName()); + + // TODO: do deep copying of data! + n.setPDBHeader(s.getPDBHeader()); + n.setDBRefs(s.getDBRefs()); + + n.setSites(s.getSites()); + + n.setChains(s.getModel(0)); + + return n; + + } + + /** + * Removes all polymeric and solvent groups from a list of groups + */ + public static List filterLigands(List allGroups) { + + List groups = null; + for (Group g : allGroups) { + if (!g.isPolymeric() && !g.isWater()) { + if (groups == null) groups = new ArrayList(1); + groups.add(g); + } + } + + return groups!=null ? groups : Collections.EMPTY_LIST; + } + + /** + * Short version of {@link #getStructure(String, PDBFileParser, AtomCache)} + * which creates new parsers when needed + * + * @param name + * @return + * @throws IOException + * @throws StructureException + */ + public static Structure getStructure(String name) throws IOException, + StructureException { + return StructureTools.getStructure(name, null, null); + } + + /** + * Flexibly get a structure from an input String. The intent of this method + * is to allow any reasonable string which could refer to a structure to be + * correctly parsed. The following are currently supported: + *

      + *
    1. Filename (if name refers to an existing file) + *
    2. PDB ID + *
    3. SCOP domains + *
    4. PDP domains + *
    5. Residue ranges + *
    6. Other formats supported by AtomCache + *
    + * + * @param name Some reference to the protein structure + * @param parser A clean PDBFileParser to use if it is a file. If null, a + * PDBFileParser will be instantiated if needed. + * @param cache An AtomCache to use if the structure can be fetched from the + * PDB. If null, a AtomCache will be instantiated if needed. + * @return A Structure object + * @throws IOException if name is an existing file, but doesn't parse correctly + * @throws StructureException if the format is unknown, or if AtomCache throws an + * exception. + */ + public static Structure getStructure(String name, PDBFileParser parser, + AtomCache cache) throws IOException, StructureException { + File f = new File(Download.expandUserHome(name)); + if (f.exists()) { + if (parser == null) { + parser = new PDBFileParser(); + } + return parser.parsePDBFile(new FileInputStream(f)); + } else { + if (cache == null) { + cache = new AtomCache(); + } + return cache.getStructure(name); + } + } + + /** + * @deprecated use {@link Chain#isProtein()} instead. + */ + @Deprecated + public static boolean isProtein(Chain c) { + + return c.isProtein(); + } + + /** + * @deprecated use {@link Chain#isNucleicAcid()} instead. + */ + @Deprecated + public static boolean isNucleicAcid(Chain c) { + return c.isNucleicAcid(); + } + + /** + * @deprecated use {@link Chain#getPredominantGroupType()} instead. + */ + @Deprecated + public static GroupType getPredominantGroupType(Chain c) { + return c.getPredominantGroupType(); + } + + /** + * @deprecated use {@link Chain#isWaterOnly()} instead. + */ + @Deprecated + public static boolean isChainWaterOnly(Chain c) { + return c.isWaterOnly(); + } + + /** + * @deprecated use {@link Chain#isPureNonPolymer()} instead. + */ + @Deprecated + public static boolean isChainPureNonPolymer(Chain c) { + + return c.isPureNonPolymer(); + } + + /** + * Cleans up the structure's alternate location (altloc) groups. All alternate location groups should have all atoms (except + * in the case of microheterogenity) or when a deuterium exists. + * Ensure that all the alt loc groups have all the atoms in the main group. + * + * @param structure The Structure to be cleaned up + */ + public static void cleanUpAltLocs(Structure structure) { + for (int i = 0; i < structure.nrModels(); i++) { + for (Chain chain : structure.getModel(i)) { + for (Group group : chain.getAtomGroups()) { + for (Group altLocGroup : group.getAltLocs()) { + for (Atom groupAtom : group.getAtoms()) { + // If this alt loc doesn't have this atom + if (!altLocGroup.hasAtom(groupAtom.getName())) { + // Fix for microheterogenity + if (altLocGroup.getPDBName().equals(group.getPDBName())) { + // If it's a Hydrogen then we check for it's Deuterated brother + if (!hasDeuteratedEquiv(groupAtom, altLocGroup)) { + altLocGroup.addAtom(groupAtom); + } + } + } + } + } + } + } + } + } + + /** + * Check to see if an Deuterated atom has a non deuterated brother in the group. + * + * @param atom the input atom that is putatively deuterium + * @param currentGroup the group the atom is in + * @return true if the atom is deuterated and it's hydrogen equive exists. + */ + public static boolean hasNonDeuteratedEquiv(Atom atom, Group currentGroup) { + if (atom.getElement() == Element.D && currentGroup.hasAtom(replaceFirstChar(atom.getName(), 'D', 'H'))) { + // If it's deuterated and has a non-deuterated brother + return true; + } + return false; + } + + /** + * Check to see if a Hydrogen has a Deuterated brother in the group. + * + * @param atom the input atom that is putatively hydorgen + * @param currentGroup the group the atom is in + * @return true if the atom is hydrogen and it's Deuterium equiv exists. + */ + public static boolean hasDeuteratedEquiv(Atom atom, Group currentGroup) { + if (atom.getElement() == Element.H && currentGroup.hasAtom(replaceFirstChar(atom.getName(), 'H', 'D'))) { + // If it's hydrogen and has a deuterated brother + return true; + } + return false; + } + + private static String replaceFirstChar(String name, char c, char d) { + if (name.charAt(0) == c) { + return name.replaceFirst(String.valueOf(c), String.valueOf(d)); + } + return name; + } + + /** + * Remove all atoms but the representative atoms (C alphas or phosphates) from the given structure. + * + * @param structure the structure + * @since 5.4.0 + */ + public static void reduceToRepresentativeAtoms(Structure structure) { + for (int modelIdx = 0; modelIdx < structure.nrModels(); modelIdx++) { + for (Chain c : structure.getPolyChains(modelIdx)) { + for (Group g : c.getAtomGroups()) { + List atoms = g.getAtoms(); + if (g.isAminoAcid()) { + atoms.removeIf(a -> !a.getName().equals(CA_ATOM_NAME)); + } else if (g.isNucleotide()) { + atoms.removeIf(a -> !a.getName().equals(NUCLEOTIDE_REPRESENTATIVE)); + } + // else we keep all other atoms. We are concerned only about aminoacids and nucleotides that make up the bulk of the structures + } + } + } + } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/SubstructureIdentifier.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/SubstructureIdentifier.java index da9c1e1dee..39a294869c 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/SubstructureIdentifier.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/SubstructureIdentifier.java @@ -23,17 +23,16 @@ package org.biojava.nbio.structure; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; - import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.contact.Grid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + /** * This is the canonical way to identify a part of a structure. * @@ -75,7 +74,7 @@ public class SubstructureIdentifier implements StructureIdentifier { private static final Logger logger = LoggerFactory.getLogger(SubstructureIdentifier.class); - private final String pdbId; + public final String pdbId; private final List ranges; /** @@ -100,7 +99,7 @@ public SubstructureIdentifier(String id) { this.ranges = ResidueRange.parseMultiple(rangeStr); } else { - this.ranges = new LinkedList(); + this.ranges = new LinkedList<>(); } } @@ -199,7 +198,7 @@ public Structure reduce(Structure s) throws StructureException { for( int modelNr=0;modelNr()); + newS.addModel(new ArrayList<>()); if(getResidueRanges().isEmpty()) { // Include all residues @@ -286,14 +285,11 @@ public Structure reduce(Structure s) throws StructureException { * @return A Structure containing at least the atoms identified by this, * or null if no PDB ID is set * @throws StructureException For errors loading and parsing the structure - * @throws IOException Errors reading the structure from disk - */ + */ @Override - public Structure loadStructure(AtomCache cache) throws IOException, StructureException { - String pdb = getPdbId(); - if(pdb == null) - return null; - return cache.getStructureForPdbId(pdb); + public Structure loadStructure(AtomCache cache) throws StructureException { + String pdb = pdbId; + return pdb == null ? null : cache.getStructureForPdbId(pdb); } /** diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/URLIdentifier.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/URLIdentifier.java index 653683ee0f..0282de7e31 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/URLIdentifier.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/URLIdentifier.java @@ -20,15 +20,19 @@ */ package org.biojava.nbio.structure; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; +import org.biojava.nbio.core.util.InputStreamProvider; +import org.biojava.nbio.structure.align.util.AtomCache; +import org.biojava.nbio.structure.io.PDBFileReader; +import org.biojava.nbio.structure.io.mmcif.MMcifParser; +import org.biojava.nbio.structure.io.mmcif.SimpleMMcifConsumer; +import org.biojava.nbio.structure.io.mmcif.SimpleMMcifParser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; -import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; @@ -36,16 +40,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.biojava.nbio.core.util.InputStreamProvider; -import org.biojava.nbio.structure.StructureIO.StructureFiletype; -import org.biojava.nbio.structure.align.util.AtomCache; -import org.biojava.nbio.structure.io.PDBFileReader; -import org.biojava.nbio.structure.io.mmcif.MMcifParser; -import org.biojava.nbio.structure.io.mmcif.SimpleMMcifConsumer; -import org.biojava.nbio.structure.io.mmcif.SimpleMMcifParser; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Represents a structure loaded from a URL (including a file URL) * @@ -116,14 +110,14 @@ public SubstructureIdentifier toCanonical() { if(params.containsKey(RESIDUES_PARAM)) { ranges = ResidueRange.parseMultiple(params.get(RESIDUES_PARAM)); } else if(params.containsKey(CHAINID_PARAM)) { - ranges = Arrays.asList(new ResidueRange(params.get(CHAINID_PARAM),(ResidueNumber)null,(ResidueNumber)null)); + ranges = Collections.singletonList(new ResidueRange(params.get(CHAINID_PARAM))); } } catch (UnsupportedEncodingException e) { logger.error("Unable to decode URL "+url,e); } if(pdbId == null) { String path = url.getPath(); - pdbId = guessPDBID(path.substring(path.lastIndexOf("/")+1)); + pdbId = guessPDBID(path.substring(path.lastIndexOf('/')+1)); } return new SubstructureIdentifier(pdbId, ranges); } @@ -137,7 +131,7 @@ public Structure reduce(Structure input) throws StructureException { * @return null */ @Override - public Structure loadStructure(AtomCache cache) throws StructureException, + public Structure loadStructure(AtomCache cache) throws IOException { StructureFiletype format = StructureFiletype.UNKNOWN; @@ -217,7 +211,7 @@ public static String guessPDBID(String name) { * @throws UnsupportedEncodingException */ private static Map parseQuery(URL url) throws UnsupportedEncodingException { - Map params = new LinkedHashMap(); + Map params = new LinkedHashMap<>(); String query = url.getQuery(); if( query == null || query.isEmpty()) { // empty query @@ -225,7 +219,7 @@ private static Map parseQuery(URL url) throws UnsupportedEncoding } String[] pairs = url.getQuery().split("&"); for(String pair: pairs) { - int i = pair.indexOf("="); + int i = pair.indexOf('='); String key = pair; if(i > 0) { key = URLDecoder.decode(pair.substring(0, i), "UTF-8"); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/AFPTwister.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/AFPTwister.java index 57ff697730..ff2b1ae4bd 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/AFPTwister.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/AFPTwister.java @@ -35,11 +35,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.vecmath.Matrix4d; import java.util.ArrayList; import java.util.List; -import javax.vecmath.Matrix4d; - //import org.biojava.nbio.structure.align.gui.jmol.StructureAlignmentJmol; public class AFPTwister { @@ -55,8 +54,7 @@ public class AFPTwister { * * @return twisted Groups */ - public static Group[] twistPDB(AFPChain afpChain, Atom[] ca1, Atom[] ca2) - throws StructureException { + public static Group[] twistPDB(AFPChain afpChain, Atom[] ca1, Atom[] ca2) { // -------------------------------------------------------- if (afpChain.isShortAlign()) @@ -165,10 +163,9 @@ public static Group[] twistPDB(AFPChain afpChain, Atom[] ca1, Atom[] ca2) * @param ca1 * @param ca2 * @return Group array twisted. - * @throws StructureException - */ + */ public static Group[] twistOptimized(AFPChain afpChain, Atom[] ca1, - Atom[] ca2) throws StructureException { + Atom[] ca2) { Atom[] optTwistPdb = new Atom[ca2.length]; @@ -250,8 +247,7 @@ public static Group[] twistOptimized(AFPChain afpChain, Atom[] ca1, */ // orig name: transPdb private static void transformOrigPDB(int n, int[] res1, int[] res2, - Atom[] ca1, Atom[] ca2, AFPChain afpChain, int blockNr) - throws StructureException { + Atom[] ca1, Atom[] ca2, AFPChain afpChain, int blockNr) { logger.debug( "transforming original coordinates {} len1: {} res1: {} len2: {} res2: {}", n, ca1.length, res1.length, ca2.length, res2.length); @@ -297,7 +293,7 @@ private static void transformOrigPDB(int n, int[] res1, int[] res2, private static Atom[] getAtoms(Atom[] ca, int[] positions, int length, boolean clone) { - List atoms = new ArrayList(); + List atoms = new ArrayList<>(); for (int i = 0; i < length; i++) { int p = positions[i]; Atom a; @@ -309,7 +305,7 @@ private static Atom[] getAtoms(Atom[] ca, int[] positions, int length, } atoms.add(a); } - return atoms.toArray(new Atom[atoms.size()]); + return atoms.toArray(Atom.EmptyAtomArray); } /** @@ -321,15 +317,14 @@ private static Atom[] getAtoms(Atom[] ca, int[] positions, int length, * @param r2 */ // orig name: modifyCod - private static void cloneAtomRange(Atom[] p1, Atom[] p2, int r1, int r2) - throws StructureException { + private static void cloneAtomRange(Atom[] p1, Atom[] p2, int r1, int r2) { logger.debug("modifyCod from: {} to: {}", r1, r2); // special clone method, can;t use StructureTools.cloneCAArray, since we // access the data // slightly differently here. - List model = new ArrayList(); + List model = new ArrayList<>(); for (int i = r1; i < r2; i++) { Group g = p2[i].getGroup(); @@ -369,7 +364,7 @@ private static void cloneAtomRange(Atom[] p1, Atom[] p2, int r1, int r2) * @return rmsd of CAs */ private static double calCaRmsd(Atom[] ca1, Atom[] pro, int resn, - int[] res1, int[] res2) throws StructureException { + int[] res1, int[] res2) { Atom[] cod1 = getAtoms(ca1, res1, resn, false); Atom[] cod2 = getAtoms(pro, res2, resn, false); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/BioJavaStructureAlignment.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/BioJavaStructureAlignment.java index 6b5b279f20..c94e85e307 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/BioJavaStructureAlignment.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/BioJavaStructureAlignment.java @@ -161,13 +161,13 @@ private void copyResults(AFPChain afpChain, AlternativeAlignment altAlig, Atom[] IndexPair align_se = path[ia]; // no gap - if(align_se.getRow() !=-1 && align_se.getCol()!=-1) { + if(align_se.row() !=-1 && align_se.col()!=-1) { - optAln[0][0][pos] = align_se.getRow(); - optAln[0][1][pos] = align_se.getCol(); + optAln[0][0][pos] = align_se.row(); + optAln[0][1][pos] = align_se.col(); - char l1 = getOneLetter(ca1[align_se.getRow()].getGroup()); - char l2 = getOneLetter(ca2[align_se.getCol()].getGroup()); + char l1 = getOneLetter(ca1[align_se.row()].getGroup()); + char l2 = getOneLetter(ca2[align_se.col()].getGroup()); alnseq1[ia] = Character.toUpperCase(l1); alnseq2[ia] = Character.toUpperCase(l2); @@ -177,16 +177,16 @@ private void copyResults(AFPChain afpChain, AlternativeAlignment altAlig, Atom[] } else { // there is a gap on this position alnsymb[ia] = ' '; - if (align_se.getRow() == -1 ) { + if (align_se.row() == -1 ) { alnseq1[ia] = '-'; } else { - char l1 = getOneLetter(ca1[align_se.getRow()].getGroup()); + char l1 = getOneLetter(ca1[align_se.row()].getGroup()); alnseq1[ia] = Character.toLowerCase(l1); } - if ( align_se.getCol() == -1 ) { + if ( align_se.col() == -1 ) { alnseq2[ia] = '-'; } else { - char l2 = getOneLetter(ca2[align_se.getCol()].getGroup()); + char l2 = getOneLetter(ca2[align_se.col()].getGroup()); alnseq2[ia] = Character.toLowerCase(l2); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/CallableStructureAlignment.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/CallableStructureAlignment.java index 80087f8e3c..1d74107a06 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/CallableStructureAlignment.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/CallableStructureAlignment.java @@ -103,13 +103,15 @@ public AFPChain call() throws Exception { if (ca1 == null) { Structure structure1 = cache.getStructure(pair.getName1()); ca1 = StructureTools.getRepresentativeAtomArray(structure1); - } else ca1 = StructureTools.cloneAtomArray(ca1); + } else + ca1 = StructureTools.cloneAtomArray(ca1); Structure structure2 = null; if (ca2 == null) { structure2 = cache.getStructure(pair.getName2()); ca2 = StructureTools.getRepresentativeAtomArray(structure2); - } else ca2 = StructureTools.cloneAtomArray(ca2); + } else + ca2 = StructureTools.cloneAtomArray(ca2); afpChain = algorithm.align(ca1, ca2); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ClusterAltAligs.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ClusterAltAligs.java index 3a6150da3b..d4c4ef3947 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ClusterAltAligs.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ClusterAltAligs.java @@ -65,7 +65,7 @@ public static void cluster(AlternativeAlignment[] aligs, int cutoff){ List remainList = new ArrayList(); List currentCluster = new ArrayList(); - currentCluster.add( new Integer(i)); + currentCluster.add(i); excludeList.add(a); int j=-1; @@ -94,7 +94,7 @@ public static void cluster(AlternativeAlignment[] aligs, int cutoff){ // " l1:"+ idxA.length + " l2:" + idxB.length + " perpos:" + perpos); if ( perpos > cutoff){ - currentCluster.add(new Integer(j)); + currentCluster.add(j); excludeList.add(b); } else { remainList.add(b); @@ -115,11 +115,10 @@ public static void cluster(AlternativeAlignment[] aligs, int cutoff){ cpos++; //System.out.println("cluster "+cpos+":"); List cluster = (List) iter.next(); - Iterator iter2 = cluster.iterator(); - while (iter2.hasNext()){ - Integer i = (Integer) iter2.next(); + for (Object o : cluster) { + Integer i = (Integer) o; - AlternativeAlignment alig = aligs[i.intValue()]; + AlternativeAlignment alig = aligs[i]; alig.setCluster(cpos); //System.out.println( " ("+ aligs[i.intValue()]+")"); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/FarmJob.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/FarmJob.java index fa749f2127..bad1657cb1 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/FarmJob.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/FarmJob.java @@ -20,6 +20,7 @@ */ package org.biojava.nbio.structure.align; +import org.biojava.nbio.core.util.InputStreamProvider; import org.biojava.nbio.structure.align.client.FarmJobParameters; import org.biojava.nbio.structure.align.client.FarmJobRunnable; import org.biojava.nbio.structure.align.events.AlignmentProgressListener; @@ -29,7 +30,6 @@ import org.biojava.nbio.structure.scop.CachedRemoteScopInstallation; import org.biojava.nbio.structure.scop.ScopDatabase; import org.biojava.nbio.structure.scop.ScopFactory; -import org.biojava.nbio.core.util.InputStreamProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -80,7 +80,7 @@ public void setParams(FarmJobParameters params) { public void addAlignmentProgressListener(AlignmentProgressListener listener){ if (progressListeners == null) - progressListeners = new ArrayList(); + progressListeners = new ArrayList<>(); progressListeners.add(listener); } @@ -165,14 +165,14 @@ public void run(){ System.setProperty(UserConfiguration.PDB_DIR,path); String cachePath = params.getCacheFilePath(); - if ( cachePath != null && ! cachePath.equals("")) + if ( cachePath != null && !cachePath.isEmpty()) System.setProperty(UserConfiguration.PDB_CACHE_DIR,cachePath); else { // if not provided, we use pdbFilePath as the default CACHE path System.setProperty(UserConfiguration.PDB_CACHE_DIR,path); } // declare SCOP to be locally cached, but fetching new stuff from remote - ScopDatabase scop = null; + ScopDatabase scop; try { scop = new CachedRemoteScopInstallation(true); } catch (IOException e) { @@ -181,7 +181,7 @@ public void run(){ ScopFactory.setScopDatabase(scop); String username = params.getUsername(); - jobs = new ArrayList(); + jobs = new ArrayList<>(); for ( int i = 0 ; i < params.getThreads();i++){ logger.info("starting thread #{}", (i+1)); FarmJobRunnable runner = new FarmJobRunnable(params); @@ -232,14 +232,14 @@ public void printHelp(){ System.out.println("-------------------"); System.out.println("FarmJob accepts the following parameters:"); - System.out.println(""); + System.out.println(); System.out.println(" Mandatory:"); System.out.println(" -pdbFilePath (mandatory) Path to the directory in your file system that contains the PDB files."); System.out.println(" provide either -time or -nrAlignments. If both are provided the job stops as soon as any of the criteria has been reached."); System.out.println(" -time maximum number of time to run (in seconds). -1 means no time limit, but run -nrAlignment arguments. Default: " + FarmJobParameters.DEFAULT_JOB_TIME ); System.out.println(" -nrAlignments number of alignments to calculate. Default: " + FarmJobParameters.DEFAULT_NR_ALIGNMENTS) ; - System.out.println(""); + System.out.println(); System.out.println(" Optional: "); System.out.println(" -threads number of parallel threads to calculate alignments. Should be nr. of available CPUs. Default: " + FarmJobParameters.DEFAULT_NR_THREADS); System.out.println(" -server the location of the server URL to talk to. Default : " + FarmJobParameters.DEFAULT_SERVER_URL); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/MultiThreadedDBSearch.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/MultiThreadedDBSearch.java index 636c2ce7a3..6ddc78e86d 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/MultiThreadedDBSearch.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/MultiThreadedDBSearch.java @@ -24,6 +24,7 @@ * */ +import org.biojava.nbio.core.util.ConcurrencyTools; import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; @@ -32,16 +33,12 @@ import org.biojava.nbio.structure.align.client.FarmJobParameters; import org.biojava.nbio.structure.align.client.JFatCatClient; import org.biojava.nbio.structure.align.client.PdbPair; -import org.biojava.nbio.structure.align.client.StructureName; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.align.util.SynchronizedOutFile; import org.biojava.nbio.structure.domain.DomainProvider; import org.biojava.nbio.structure.domain.DomainProviderFactory; import org.biojava.nbio.structure.domain.RemoteDomainProvider; -import org.biojava.nbio.structure.io.LocalPDBDirectory.FetchBehavior; -import org.biojava.nbio.structure.io.PDBFileReader; -import org.biojava.nbio.core.util.ConcurrencyTools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -63,7 +60,7 @@ public class MultiThreadedDBSearch { private final static Logger logger = LoggerFactory.getLogger(MultiThreadedDBSearch.class); - AtomicBoolean interrupted ; + final AtomicBoolean interrupted ; StructureAlignment algorithm; @@ -71,13 +68,13 @@ public class MultiThreadedDBSearch { String name1; - int nrCPUs; + final int nrCPUs; AtomCache cache; File resultList; SortedSet representatives; - boolean domainSplit; + final boolean domainSplit; Structure structure1; @@ -192,7 +189,7 @@ public void setResultFile(File resultList) { public void run(){ - File outFileF = null; + File outFileF; SynchronizedOutFile out ; try { @@ -257,12 +254,7 @@ public void run(){ } out.flush(); - } catch (IOException e){ - logger.error("Error while loading representative structure {}", name1, e); - interrupt(); - cleanup(); - return; - } catch (StructureException e) { + } catch (IOException | StructureException e){ logger.error("Error while loading representative structure {}", name1, e); interrupt(); cleanup(); @@ -270,7 +262,7 @@ public void run(){ } - int nrJobs = 0; + int nrJobs = 0; DomainProvider domainProvider; try { domainProvider = DomainProviderFactory.getDomainProvider(); @@ -301,12 +293,7 @@ public void run(){ } } - } catch(IOException e) { - logger.error("Error while fetching representative domains", e); - interrupt(); - cleanup(); - return; - } catch (StructureException e) { + } catch(IOException | StructureException e) { logger.error("Error while fetching representative domains", e); interrupt(); cleanup(); @@ -314,7 +301,7 @@ public void run(){ } - ThreadPoolExecutor pool = ConcurrencyTools.getThreadPool(); + ThreadPoolExecutor pool = ConcurrencyTools.getThreadPool(); logger.info("{}", pool.getPoolSize()); long startTime = System.currentTimeMillis(); @@ -398,8 +385,7 @@ private void checkLocalFiles() throws IOException, StructureException { } if ( domainProvider instanceof RemoteDomainProvider ) { - RemoteDomainProvider remoteP = (RemoteDomainProvider) domainProvider; - remoteP.flushCache(); + ((RemoteDomainProvider) domainProvider).flushCache(); } logger.info("done checking local files..."); @@ -407,15 +393,15 @@ private void checkLocalFiles() throws IOException, StructureException { } - private void checkFile(String repre) throws IOException, StructureException { - - StructureName name = new StructureName(repre); + @Deprecated private void checkFile(String repre) { - PDBFileReader reader = new PDBFileReader(); - reader.setFetchBehavior(FetchBehavior.FETCH_REMEDIATED); - reader.setPath(cache.getPath()); - reader.setFileParsingParameters(cache.getFileParsingParams()); - reader.prefetchStructure(name.getPdbId()); +// StructureName name = new StructureName(repre); +// +// PDBFileReader reader = new PDBFileReader(); +// reader.setFetchBehavior(FetchBehavior.FETCH_REMEDIATED); +// reader.setPath(cache.getPath()); +// reader.setFileParsingParameters(cache.getFileParsingParams()); +// reader.prefetchStructure(name.getPdbId()); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/MultipleStructureAligner.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/MultipleStructureAligner.java index 964e280935..950123c4ac 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/MultipleStructureAligner.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/MultipleStructureAligner.java @@ -20,13 +20,13 @@ */ package org.biojava.nbio.structure.align; -import java.util.List; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.ce.ConfigStrucAligParams; import org.biojava.nbio.structure.align.multiple.MultipleAlignment; +import java.util.List; + /** * Interface for the Multiple Structure Alignment Algorithms. The Pairwise Alignment Algorithms can also * implement this class to be able to return {@link MultipleAlignment} Objects. @@ -45,7 +45,7 @@ public interface MultipleStructureAligner{ * @throws StructureException * @see #align(List,Object) */ - public MultipleAlignment align(List atomArrays) throws StructureException; + MultipleAlignment align(List atomArrays) throws StructureException; /** * Run an alignment and also send a bean containing the parameters. @@ -55,33 +55,33 @@ public interface MultipleStructureAligner{ * @throws StructureException * @see #align(List) */ - public MultipleAlignment align(List atomArrays, Object params) throws StructureException; + MultipleAlignment align(List atomArrays, Object params) throws StructureException; /** * Return the parameters of this algorithm instance. * * @return The returned Object will be a Java bean. */ - public ConfigStrucAligParams getParameters(); + ConfigStrucAligParams getParameters(); /** * Set the parameters for this algorithm to use. * * @param parameters */ - public void setParameters(ConfigStrucAligParams parameters); + void setParameters(ConfigStrucAligParams parameters); /** * Get the name of this Algorithm. * * @return String name of the algorithm */ - public String getAlgorithmName(); + String getAlgorithmName(); /** * Get the Version information for this Algorithm. * * @return String version of the algorithm */ - public String getVersion(); + String getVersion(); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/StrucAligParameters.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/StrucAligParameters.java index 8851d863e1..36fb609a58 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/StrucAligParameters.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/StrucAligParameters.java @@ -121,19 +121,19 @@ private void setDefault() { } @Override public String toString() { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); String t = " "; - Object[] params = new Object[]{new Integer(initialK) ,new Integer(seedFragmentLength), - new Float(seedRmsdCutoff), - new Integer(fragmentLength), - new Integer(diagonalDistance), new Integer(diagonalDistance2), new Float(fragmentMiniDistance), - new Integer(angleDiff), - new Float(fragCompat), new Integer(maxrefine), - new Boolean(reduceInitialFragments), new Double(joinRMSCutoff), new Boolean(joinPlo), - new Boolean(doAngleCheck), new Boolean(doDistanceCheck), new Boolean(doRMSCheck), - new Boolean(doDensityCheck), new Float(densityCutoff), new Float(create_co), new Integer(maxIter), - new Float(gapOpen), new Float(gapExtension), new Integer(permutationSize), new Float(evalCutoff)}; + Object[] params = new Object[]{initialK, seedFragmentLength, + seedRmsdCutoff, + fragmentLength, + diagonalDistance, diagonalDistance2, fragmentMiniDistance, + angleDiff, + fragCompat, maxrefine, + reduceInitialFragments, joinRMSCutoff, joinPlo, + doAngleCheck, doDistanceCheck, doRMSCheck, + doDensityCheck, densityCutoff, create_co, maxIter, + gapOpen, gapExtension, permutationSize, evalCutoff}; for (int i=0 ; i< params.length ; i++){ buf.append(params[i]); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/StructureAlignment.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/StructureAlignment.java index 8dd138218e..70ff290286 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/StructureAlignment.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/StructureAlignment.java @@ -35,7 +35,7 @@ public interface StructureAlignment { * @return the afpChain object that contains the alignment. * @throws StructureException */ - public AFPChain align(Atom[] ca1, Atom[] ca2) throws StructureException; + AFPChain align(Atom[] ca1, Atom[] ca2) throws StructureException; /** run an alignment and also send a bean containing the parameters. * @@ -45,29 +45,29 @@ public interface StructureAlignment { * @return the afpChain object that contains the alignment. * @throws StructureException */ - public AFPChain align(Atom[] ca1, Atom[] ca2, Object params) throws StructureException; + AFPChain align(Atom[] ca1, Atom[] ca2, Object params) throws StructureException; /** Return the paramers for this algorithm. * * @return The returned object will be a Java bean. */ - public ConfigStrucAligParams getParameters(); + ConfigStrucAligParams getParameters(); /** Set the default parameters for this algorithm to use * * @param parameters */ - public void setParameters(ConfigStrucAligParams parameters); + void setParameters(ConfigStrucAligParams parameters); /** Get the name of the Algorithm * * @return the name of the algorithm */ - public String getAlgorithmName(); + String getAlgorithmName(); /** Get the Version information for this Algorithm. * * @return the version of the algorithm */ - public String getVersion(); + String getVersion(); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/StructureAlignmentFactory.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/StructureAlignmentFactory.java index a31012cf25..17d6f2c001 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/StructureAlignmentFactory.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/StructureAlignmentFactory.java @@ -38,7 +38,7 @@ public class StructureAlignmentFactory { private final static Logger logger = LoggerFactory.getLogger(StructureAlignmentFactory.class); - private static List algorithms = new ArrayList(); + private static final List algorithms = new ArrayList<>(); static { algorithms.add( new CeMain() ); @@ -111,13 +111,7 @@ public static StructureAlignment getAlgorithm(String name) throws StructureExcep @SuppressWarnings("unchecked") Class c = (Class) Class.forName(algo.getClass().getName()); return c.newInstance(); - } catch (ClassNotFoundException e){ - logger.error("Exception: ", e); - return null; - } catch (IllegalAccessException e){ - logger.error("Exception: ", e); - return null; - } catch (InstantiationException e){ + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e){ logger.error("Exception: ", e); return null; } @@ -130,18 +124,18 @@ public static StructureAlignment getAlgorithm(String name) throws StructureExcep } public static StructureAlignment[] getAllAlgorithms(){ - return algorithms.toArray(new StructureAlignment[algorithms.size()]); + return algorithms.toArray(new StructureAlignment[0]); } public static String[] getAllAlgorithmNames(){ StructureAlignment[] algos = getAllAlgorithms(); - List names = new ArrayList(); + List names = new ArrayList<>(); for (StructureAlignment alg : algos){ names.add(alg.getAlgorithmName()); } - return names.toArray(new String[names.size()]); + return names.toArray(new String[0]); } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/StructurePairAligner.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/StructurePairAligner.java index fabe4c9bc6..e9319546e0 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/StructurePairAligner.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/StructurePairAligner.java @@ -35,16 +35,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.vecmath.Matrix4d; import java.io.FileOutputStream; import java.io.InputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; -import java.util.Comparator; import java.util.List; -import javax.vecmath.Matrix4d; - /** * Perform a pairwise protein structure superimposition. * @@ -135,15 +133,14 @@ */ public class StructurePairAligner { - private final static Logger logger = LoggerFactory - .getLogger(StructurePairAligner.class); + private final static Logger logger = LoggerFactory.getLogger(StructurePairAligner.class); AlternativeAlignment[] alts; Matrix distanceMatrix; StrucAligParameters params; FragmentPair[] fragPairs; - List listeners = new ArrayList(); + final List listeners = new ArrayList<>(); public StructurePairAligner() { super(); @@ -444,7 +441,7 @@ public void align(Atom[] ca1, Atom[] ca2, StrucAligParameters params) Atom unitvector = new AtomImpl(); unitvector.setCoords(utmp[0]); - List fragments = new ArrayList(); + List fragments = new ArrayList<>(); for (int i = 0; i < rows; i++) { @@ -500,7 +497,7 @@ public void align(Atom[] ca1, Atom[] ca2, StrucAligParameters params) notifyFragmentListeners(fragments); FragmentPair[] fp = fragments - .toArray(new FragmentPair[fragments.size()]); + .toArray(new FragmentPair[0]); setFragmentPairs(fp); logger.debug(" got # fragment pairs: {}", fp.length); @@ -521,7 +518,7 @@ public void align(Atom[] ca1, Atom[] ca2, StrucAligParameters params) } else if (params.isJoinPlo()) { // this approach by StrComPy (peter lackner): - frags = joiner.frag_pairwise_compat(fp, params.getAngleDiff(), + frags = FragmentJoiner.frag_pairwise_compat(fp, params.getAngleDiff(), params.getFragCompat(), params.getMaxrefine()); } else { @@ -536,7 +533,7 @@ public void align(Atom[] ca1, Atom[] ca2, StrucAligParameters params) logger.debug("step 3 - refine alignments"); - List aas = new ArrayList(); + List aas = new ArrayList<>(); for (int i = 0; i < frags.length; i++) { JointFragments f = frags[i]; AlternativeAlignment a = new AlternativeAlignment(); @@ -544,34 +541,27 @@ public void align(Atom[] ca1, Atom[] ca2, StrucAligParameters params) a.setAltAligNumber(i + 1); a.setDistanceMatrix(distanceMatrix); - try { - if (params.getMaxIter() > 0) { - +// try { + if (params.getMaxIter() > 0) a.refine(params, ca1, ca2); - } else { - + else a.finish(params, ca1, ca2); - - } - } catch (StructureException e) { - logger.error("Refinement of fragment {} failed", i, e); - } +// } catch (StructureException e) { +// logger.error("Refinement of fragment {} failed", i, e); +// } a.calcScores(ca1, ca2); aas.add(a); } // sort the alternative alignments - Comparator comp = new AltAligComparator(); - Collections.sort(aas, comp); + aas.sort(AltAligComparator.the); Collections.reverse(aas); - alts = aas.toArray(new AlternativeAlignment[aas.size()]); + alts = aas.toArray(new AlternativeAlignment[0]); // do final numbering of alternative solutions int aanbr = 0; - for (AlternativeAlignment a : alts) { - aanbr++; - a.setAltAligNumber(aanbr); - } + for (AlternativeAlignment a : alts) + a.setAltAligNumber(++aanbr); logger.debug("total calculation time: {} ms.", (System.currentTimeMillis() - timeStart)); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/AbstractUserArgumentProcessor.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/AbstractUserArgumentProcessor.java index 2ffdbae748..c40ee3f76f 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/AbstractUserArgumentProcessor.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/AbstractUserArgumentProcessor.java @@ -78,11 +78,11 @@ */ public abstract class AbstractUserArgumentProcessor implements UserArgumentProcessor { - public static String newline = System.getProperty("line.separator"); + public static final String newline = System.getProperty("line.separator"); - protected StartupParameters params ; + protected final StartupParameters params ; - public static final List mandatoryArgs= new ArrayList(); + public static final List mandatoryArgs= new ArrayList<>(); protected AbstractUserArgumentProcessor(){ params = getStartupParametersInstance(); @@ -242,7 +242,7 @@ private void runDBSearch() throws ConfigurationException{ String pdbFilePath = params.getPdbFilePath(); - if ( pdbFilePath == null || pdbFilePath.equals("")){ + if ( pdbFilePath == null || pdbFilePath.isEmpty()){ UserConfiguration c = new UserConfiguration(); pdbFilePath = c.getPdbFilePath(); @@ -251,7 +251,7 @@ private void runDBSearch() throws ConfigurationException{ String cacheFilePath = params.getCacheFilePath(); - if ( cacheFilePath == null || cacheFilePath.equals("")){ + if ( cacheFilePath == null || cacheFilePath.isEmpty()){ cacheFilePath = pdbFilePath; } @@ -263,21 +263,21 @@ private void runDBSearch() throws ConfigurationException{ String searchFile = params.getSearchFile(); - if ( alignPairs == null || alignPairs.equals("")) { - if ( searchFile == null || searchFile.equals("")){ + if ( alignPairs == null || alignPairs.isEmpty()) { + if ( searchFile == null || searchFile.isEmpty()){ throw new ConfigurationException("Please specify -alignPairs or -searchFile !"); } } String outputFile = params.getOutFile(); - if ( outputFile == null || outputFile.equals("")){ + if ( outputFile == null || outputFile.isEmpty()){ throw new ConfigurationException("Please specify the mandatory argument -outFile!"); } System.out.println("running DB search with parameters: " + params); - if ( alignPairs != null && ! alignPairs.equals("")) { + if ( alignPairs != null && !alignPairs.isEmpty()) { runAlignPairs(cache, alignPairs, outputFile); } else { // must be a searchFile request... @@ -303,7 +303,7 @@ private void runDbSearch(AtomCache cache, String searchFile, System.out.println("will use " + useNrCPUs + " CPUs."); PDBFileReader reader = new PDBFileReader(); - Structure structure1 = null ; + Structure structure1; try { structure1 = reader.getStructure(searchFile); } catch (IOException e) { @@ -351,7 +351,7 @@ private void runAlignPairs(AtomCache cache, String alignPairs, String legend = getDbSearchLegend(); out.write(legend + newline ); System.out.println(legend); - String line = null; + String line; while ( (line = is.readLine()) != null){ if ( line.startsWith("#")) continue; @@ -431,8 +431,8 @@ private void runPairwise() throws ConfigurationException{ // first load two example structures - Structure structure1 = null; - Structure structure2 = null; + Structure structure1; + Structure structure2; String path = params.getPdbFilePath(); @@ -546,22 +546,7 @@ private void runPairwise() throws ConfigurationException{ System.out.println(afpChain.toCE(ca1, ca2)); } - } catch (IOException e) { - e.printStackTrace(); - System.exit(1); return; - } catch (ClassNotFoundException e) { - e.printStackTrace(); - System.exit(1); return; - } catch (NoSuchMethodException e) { - e.printStackTrace(); - System.exit(1); return; - } catch (InvocationTargetException e) { - e.printStackTrace(); - System.exit(1); return; - } catch (IllegalAccessException e) { - e.printStackTrace(); - System.exit(1); return; - } catch (StructureException e) { + } catch (IOException | StructureException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | ClassNotFoundException e) { e.printStackTrace(); System.exit(1); return; } @@ -578,10 +563,8 @@ private void runPairwise() throws ConfigurationException{ * @throws NoSuchMethodException If an error occurs when invoking jmol * @throws InvocationTargetException If an error occurs when invoking jmol * @throws IllegalAccessException If an error occurs when invoking jmol - * @throws StructureException - */ - private void checkWriteFile( AFPChain afpChain, Atom[] ca1, Atom[] ca2, boolean dbsearch) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, StructureException - { + */ + private void checkWriteFile( AFPChain afpChain, Atom[] ca1, Atom[] ca2, boolean dbsearch) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { String output = null; if ( params.isOutputPDB()){ if (! GuiWrapper.isGuiModuleInstalled()) { @@ -716,12 +699,12 @@ private Structure getStructure(AtomCache cache, String name1, String file) */ private Structure fixStructureName(Structure s, String file) { - if ( s.getName() != null && (! s.getName().equals(""))) + if ( s.getName() != null && (!s.getName().isEmpty())) return s; s.setName(s.getPDBCode()); - if ( s.getName() == null || s.getName().equals("")){ + if ( s.getName() == null || s.getName().isEmpty()){ File f = new File(file); s.setName(f.getName()); } @@ -734,11 +717,11 @@ public String getDbSearchResult(AFPChain afpChain){ @Override public String printHelp() { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); StructureAlignment alg = getAlgorithm(); buf.append("-------------------").append(newline); - buf.append(alg.getAlgorithmName() + " v." + alg.getVersion() + " help: " + newline); + buf.append(alg.getAlgorithmName()).append(" v.").append(alg.getVersion()).append(" help: ").append(newline); buf.append("-------------------").append(newline); buf.append(newline); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CECPParameters.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CECPParameters.java index 146be22a3b..f2aaa8e939 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CECPParameters.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CECPParameters.java @@ -32,14 +32,14 @@ public class CECPParameters extends CeParameters { public static final int DEFAULT_MIN_CP_LENGTH = 5; //The minimum block length for CPs. Blocks shorter than this will be ignored. - public static enum DuplicationHint { + public enum DuplicationHint { SHORTER("Shorter of the two"), LEFT("Left"), RIGHT("Right"); - private String name; - private DuplicationHint(String name) { + private final String name; + DuplicationHint(String name) { this.name = name; } @Override diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CECalculator.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CECalculator.java index e70efd5183..fabe6df622 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CECalculator.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CECalculator.java @@ -26,11 +26,9 @@ import org.biojava.nbio.core.alignment.matrices.ScaledSubstitutionMatrix; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Calc; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; +import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.model.AFP; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.util.AFPAlignmentDisplay; @@ -38,14 +36,11 @@ import org.biojava.nbio.structure.geometry.Matrices; import org.biojava.nbio.structure.geometry.SuperPositions; import org.biojava.nbio.structure.jama.Matrix; -import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; -import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; +import javax.vecmath.Matrix4d; import java.util.ArrayList; import java.util.List; -import javax.vecmath.Matrix4d; - /** This is based on the original Combinatorial Extension (CE) source code from 2003 or 2004 (CE version 2.3), @@ -64,6 +59,8 @@ public class CECalculator { protected static final boolean isPrint = false; private static final boolean debug = false; + public static final double strLenThreshold = 0.95; + int[] f1; int[] f2; double[][]dist1; @@ -85,7 +82,7 @@ public class CECalculator { protected static final double zThr=-0.1; - long timeStart ; + final long timeStart ; long timeEnd; private int nAtom; @@ -100,25 +97,26 @@ public class CECalculator { private Atom t; protected int nTraces; - private double z; +// private double z; private int[] traceIndexContainer; - protected CeParameters params; + protected final CeParameters params; // SHOULD these fields be PARAMETERS? protected static final int nIter = 1; private static final boolean distAll = false; - List matrixListeners; + final List matrixListeners; + static final double[][] EMPTY_DOUBLE_SQUARE = new double[0][0]; public CECalculator(CeParameters params){ timeStart = System.currentTimeMillis(); - dist1= new double[0][0]; - dist2= new double[0][0]; + + dist1 = dist2 = EMPTY_DOUBLE_SQUARE; this.params = params; - matrixListeners = new ArrayList(); + matrixListeners = new ArrayList<>(); } @@ -128,10 +126,8 @@ public CECalculator(CeParameters params){ * @param ca1 * @param ca2 * @return afpChain - * @throws StructureException */ - public AFPChain extractFragments(AFPChain afpChain, - Atom[] ca1, Atom[] ca2) throws StructureException{ + public AFPChain extractFragments(AFPChain afpChain, Atom[] ca1, Atom[] ca2) { int nse1 = ca1.length; int nse2 = ca2.length; @@ -139,7 +135,7 @@ public AFPChain extractFragments(AFPChain afpChain, afpChain.setCa1Length(nse1); afpChain.setCa2Length(nse2); - int traceMaxSize=nse10) { @@ -806,17 +796,17 @@ protected double getScore2(int jse1, int jse2, double[][] traceScore, int traceI ((nTrace>1?traceScore[nTrace-2][traceIndex[nTrace-1]]:score0) *a[nTrace-1]+score1*(a[nTrace]-a[nTrace-1]))/a[nTrace]; */ - double val = 0; + double val; if ( nTrace>1) val =traceScore[nTrace-2][traceIndex[nTrace-1]]; else val = score0; - double score2 = (val * traceIndexContainer[nTrace-1]+score1*(traceIndexContainer[nTrace]-traceIndexContainer[nTrace-1]))/traceIndexContainer[nTrace]; + return (val * traceIndexContainer[nTrace-1]+score1*(traceIndexContainer[nTrace]-traceIndexContainer[nTrace-1]))/traceIndexContainer[nTrace]; //System.out.println("check: score0 " + score0 + " score 1 " + score1 + " sc2: " + score2 + " val: " + val + " nTrace:" + nTrace+ " " + traceIndexContainer[nTrace-1] + " " + traceIndexContainer[nTrace-1] + " " + traceIndexContainer[nTrace] ); - return score2; + } @@ -922,8 +912,7 @@ public void nextStep( AFPChain afpChain, convertAfpChain(afpChain, ca1, ca2); AFPAlignmentDisplay.getAlign(afpChain, ca1, ca2); - double tmScore = AFPChainScorer.getTMScore(afpChain, ca1, ca2,false); - afpChain.setTMScore(tmScore); + afpChain.setTMScore(AFPChainScorer.getTMScore(afpChain, ca1, ca2,false)); } @@ -931,16 +920,16 @@ public void nextStep( AFPChain afpChain, // this part is modified from the original CeCalculator @SuppressWarnings("unused") private void checkBestTraces( AFPChain afpChain, - Atom[] ca1, Atom[] ca2) throws StructureException{ + Atom[] ca1, Atom[] ca2) { - z=0.0; + double z = 0.0; int nGaps; int winSize = params.getWinSize(); int nse1 = ca1.length; int nse2 = ca2.length; - int traceMaxSize=nse1 afpSet = new ArrayList(); + List afpSet = new ArrayList<>(nBestTrace); for (int afp=0;afp= strLen * strLenThreshold) { rmsdLen=rmsd; isRmsdLenAssigned=true; } @@ -1536,7 +1524,7 @@ public static double[][] updateMatrixWithSequenceConservation(double[][] max, At } - AminoAcidCompoundSet set = AminoAcidCompoundSet.getAminoAcidCompoundSet(); + AminoAcidCompoundSet set = AminoAcidCompoundSet.aminoAcidCompoundSet; for (int i = 0 ; i < origM.getRowDimension() ; i++){ for ( int j =0; j < origM.getColumnDimension() ; j ++ ) { @@ -1555,7 +1543,7 @@ public static double[][] updateMatrixWithSequenceConservation(double[][] max, At short aaScore = substMatrix.getValue(ac1,ac2); - double weightedScore = (aaScore / internalScale) * params.getSeqWeight(); + double weightedScore = (((double)aaScore) / internalScale) * params.getSeqWeight(); val += weightedScore; @@ -1609,8 +1597,8 @@ private double dpAlign(int nSeq1, int nSeq2, double gapI, double gapE, // isGlobal1,isGlobal2 are always false... int i, j, is, js, iMax, jMax, k; - boolean ge=(gapE!=0.0?true:false); - double sum, sum_ret, sum_brk; + boolean ge=(gapE != 0.0); + double sum_ret, sum_brk; boolean[][] brk_flg=new boolean [nSeq1][nSeq2]; for(i=0; i=0; j--) { brk_flg[i][j]=false; + double sum; if(j=0; i--) for(j=nSeq2-1; j>=0; j--) { + double sum; brk_flg[i][j]=false; if(jsum_ret) @@ -1773,7 +1763,7 @@ private double dpAlign(int nSeq1, int nSeq2, double gapI, double gapE, for(i=is, j=js; i atoms = new ArrayList(); + List atoms = new ArrayList<>(length); //TODO avoid ArrayList, just craete Atom[] for ( int i = 0 ; i < length ; i++){ - - Atom a; - if ( clone ){ - Group g = (Group)ca[i].getGroup().clone(); - a = g.getAtom(ca[i].getName()); - } - else { - a = ca[i]; - } - atoms.add(a); + atoms.add(clone ? + ((Group) ca[i].getGroup().clone()).getAtom(ca[i].getName()) : + ca[i] + ); } - return atoms.toArray(new Atom[atoms.size()]); + + return atoms.toArray(Atom.EmptyAtomArray); } @@ -1954,33 +1937,33 @@ private void noBestTrace(){ - private double zToP(double z) { + private static double zToP(double z) { int ind=(int)(z/0.1); if(ind<0) ind=0; if(ind>149) ind=149; return(tableZtoP[ind]); } /////////////////////////////////////////////////////////////////////////// - private double pToZ(double p) { + private static double pToZ(double p) { int ind=(int)(-Math.log10(p)*3.0); if(ind<0) ind=0; if(ind>149) ind=149; return(tablePtoZ[ind]); } /////////////////////////////////////////////////////////////////////////// - private double zByZ(double z1, double z2) { + private static double zByZ(double z1, double z2) { double p1=zToP(z1); double p2=zToP(z2); - return(pToZ(p1*p2)); + return pToZ(p1*p2); } - protected double zStrAlign(int winSize, int nTrace, double score, int nGaps) { + protected static double zStrAlign(int winSize, int nTrace, double score, int nGaps) { double z1=zScore(winSize, nTrace, score); double z2=zGaps(winSize, nTrace, nGaps); - return(zByZ(z1, z2)); + return zByZ(z1, z2); } - double zScore(int winSize, int nTrace, double score) { + static double zScore(int winSize, int nTrace, double score) { if(winSize==8) { @@ -2020,7 +2003,7 @@ protected double zStrAlign(int winSize, int nTrace, double score, int nGaps) { } /////////////////////////////////////////////////////////////////////////// - double zGaps(int winSize, int nTrace, int nGaps) { + static double zGaps(int winSize, int nTrace, int nGaps) { if(nTrace<2) return(0.0); double scoreAv_, scoreSd_; @@ -2119,21 +2102,14 @@ public void convertAfpChain(AFPChain afpChain, Atom[] ca1, Atom[] ca2) { afpChain.setBlockNum(1); //afpChain.setAlignScore(z); - Matrix[] m ; - - if ( r != null ) { - m = new Matrix[1]; - m[0] = r; - } else { - m = new Matrix[0]; - } + Matrix[] m = r != null ? new Matrix[]{r} : Matrix.EmptyMatrixArray; Atom[] as ; if ( t != null) { as = new Atom[1]; as[0] = t; } else { - as = new Atom[0]; + as = Atom.EmptyAtomArray; } afpChain.setBlockRotationMatrix(m); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeCPMain.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeCPMain.java index 2d7e76cf77..2c2ac90e82 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeCPMain.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeCPMain.java @@ -28,18 +28,16 @@ import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.util.AFPAlignmentDisplay; -import org.biojava.nbio.structure.align.util.ConfigurationException; import org.biojava.nbio.structure.geometry.Matrices; import org.biojava.nbio.structure.geometry.SuperPositions; import org.biojava.nbio.structure.jama.Matrix; +import javax.vecmath.Matrix4d; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import javax.vecmath.Matrix4d; - /** * A wrapper for {@link CeMain} which sets default parameters to be appropriate for finding * circular permutations. @@ -54,7 +52,7 @@ * */ public class CeCPMain extends CeMain { - private static boolean debug = false; + private static final boolean debug = false; public static final String algorithmName = "jCE Circular Permutation"; @@ -84,7 +82,7 @@ public String getVersion() { return CeCPMain.version; } - public static void main(String[] args) throws ConfigurationException { + public static void main(String[] args) { CeCPUserArgumentProcessor processor = new CeCPUserArgumentProcessor(); //Responsible for creating a CeCPMain instance processor.process(args); } @@ -114,13 +112,11 @@ public AFPChain align(Atom[] ca1, Atom[] ca2, Object param) throws StructureExce case LEFT: duplicateRight = false; break; - case RIGHT: - duplicateRight = true; - break; - case SHORTER: + case SHORTER: duplicateRight = ca1.length >= ca2.length; break; - default: + case RIGHT: + default: duplicateRight = true; } @@ -354,7 +350,7 @@ public static AFPChain filterDuplicateAFPs(AFPChain afpChain, CECalculator ceCal int firstRes = nStart; // start res number after trimming - int lastRes = nStart+ca2len; // last res number after trimming + int lastRes; // last res number after trimming if(nStart >= ca2len || cEnd < ca2len) { // no circular permutation firstRes=nStart; lastRes=cEnd; @@ -415,8 +411,8 @@ public static AFPChain filterDuplicateAFPs(AFPChain afpChain, CECalculator ceCal // Fix numbering: // First, split up the atoms into left and right blocks - List< ResiduePair > left = new ArrayList(); // residues from left of duplication - List< ResiduePair > right = new ArrayList(); // residues from right of duplication + List< ResiduePair > left = new ArrayList<>(); // residues from left of duplication + List< ResiduePair > right = new ArrayList<>(); // residues from right of duplication for(int i=0;i= firstRes && optAln[0][1][i] <= lastRes ) { // not trimmed @@ -432,7 +428,7 @@ public static AFPChain filterDuplicateAFPs(AFPChain afpChain, CECalculator ceCal alignLen = 0; // Now we don't care about left/right, so just call them "blocks" - List> blocks = new ArrayList>(2); + List> blocks = new ArrayList<>(2); if( !left.isEmpty() ) { blocks.add(left); alignLen += left.size(); @@ -581,8 +577,8 @@ private static int[] countNtermResidues(int[] block, int nStart, * @see #filterDuplicateAFPs() */ private static class ResiduePair { - public int a; - public int b; + public final int a; + public final int b; public ResiduePair(int a, int b) { this.a=a; this.b=b; @@ -756,7 +752,7 @@ private static CutPoint calculateCutPoint(int[] block,int nStart, int cEnd, // requires additional dependencies biojava-structure-gui and JmolApplet // TODO dmyersturnbull: This should probably be in structure-gui @SuppressWarnings("unused") - private static void displayAlignment(AFPChain afpChain, Atom[] ca1, Atom[] ca2) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, StructureException { + private static void displayAlignment(AFPChain afpChain, Atom[] ca1, Atom[] ca2) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { Atom[] ca1clone = StructureTools.cloneAtomArray(ca1); Atom[] ca2clone = StructureTools.cloneAtomArray(ca2); if (! GuiWrapper.isGuiModuleInstalled()) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeCPUserArgumentProcessor.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeCPUserArgumentProcessor.java index 1897c96fe2..a437033d5a 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeCPUserArgumentProcessor.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeCPUserArgumentProcessor.java @@ -29,7 +29,7 @@ public class CeCPUserArgumentProcessor extends CeUserArgumentProcessor { - protected class CeCPStartupParams extends CeStartupParams { + protected static class CeCPStartupParams extends CeStartupParams { protected DuplicationHint duplicationHint; protected Integer minCPLength; @@ -67,7 +67,7 @@ public String toString() { @Override protected StartupParameters getStartupParametersInstance() { - return new CeCPStartupParams(); + return new CeCPStartupParams(); } @Override public StructureAlignment getAlgorithm() { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeCalculatorEnhanced.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeCalculatorEnhanced.java index 8610b10d0b..77c57f2a29 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeCalculatorEnhanced.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeCalculatorEnhanced.java @@ -26,21 +26,23 @@ import org.biojava.nbio.core.alignment.matrices.ScaledSubstitutionMatrix; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; -import org.biojava.nbio.structure.*; +import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; +import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; +import org.biojava.nbio.structure.Atom; +import org.biojava.nbio.structure.Calc; +import org.biojava.nbio.structure.Group; +import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.model.AFP; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.util.AFPAlignmentDisplay; import org.biojava.nbio.structure.geometry.Matrices; import org.biojava.nbio.structure.geometry.SuperPositions; import org.biojava.nbio.structure.jama.Matrix; -import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; -import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; +import javax.vecmath.Matrix4d; import java.util.ArrayList; import java.util.List; -import javax.vecmath.Matrix4d; - /** This is based on the original Combinatorial Extension (CE) source code from 2003 or 2004 (CE version 2.3), @@ -83,7 +85,7 @@ public class CeCalculatorEnhanced { protected static final double zThr=-0.1; - long timeStart ; + final long timeStart ; long timeEnd; private int nAtom; @@ -101,13 +103,13 @@ public class CeCalculatorEnhanced { private double z; private int[] traceIndexContainer; - protected CeParameters params; + protected final CeParameters params; // SHOULD these fields be PARAMETERS? protected static final int nIter = 1; private static final boolean distAll = false; - List matrixListeners; + final List matrixListeners; public static final boolean GLOBAL_ALIGN1 = false; public static final boolean GLOBAL_ALIGN2 = false; @@ -117,7 +119,7 @@ public CeCalculatorEnhanced(CeParameters params){ dist1= new double[0][0]; dist2= new double[0][0]; this.params = params; - matrixListeners = new ArrayList(); + matrixListeners = new ArrayList<>(); } @@ -127,10 +129,9 @@ public CeCalculatorEnhanced(CeParameters params){ * @param ca1 * @param ca2 * @return afpChain - * @throws StructureException */ public AFPChain extractFragments(AFPChain afpChain, - Atom[] ca1, Atom[] ca2) throws StructureException{ + Atom[] ca1, Atom[] ca2) { int nse1 = ca1.length; int nse2 = ca2.length; @@ -138,7 +139,7 @@ public AFPChain extractFragments(AFPChain afpChain, afpChain.setCa1Length(nse1); afpChain.setCa2Length(nse2); - int traceMaxSize=nse10) { @@ -805,7 +803,7 @@ protected double getScore2(int jse1, int jse2, double[][] traceScore, int traceI ((nTrace>1?traceScore[nTrace-2][traceIndex[nTrace-1]]:score0) *a[nTrace-1]+score1*(a[nTrace]-a[nTrace-1]))/a[nTrace]; */ - double val = 0; + double val; if ( nTrace>1) val =traceScore[nTrace-2][traceIndex[nTrace-1]]; else @@ -910,7 +908,7 @@ protected double getScoreFromDistanceMatrices(int mse1, int mse2,int winSize) { } public void nextStep( AFPChain afpChain, - Atom[] ca1, Atom[] ca2) throws StructureException{ + Atom[] ca1, Atom[] ca2) { if(nBestTrace>0) { @@ -928,7 +926,7 @@ public void nextStep( AFPChain afpChain, // this part is modified from the original CeCalculator @SuppressWarnings("unused") private void checkBestTraces( AFPChain afpChain, - Atom[] ca1, Atom[] ca2) throws StructureException{ + Atom[] ca1, Atom[] ca2) { z=0.0; @@ -937,7 +935,7 @@ private void checkBestTraces( AFPChain afpChain, int winSize = params.getWinSize(); int nse1 = ca1.length; int nse2 = ca2.length; - int traceMaxSize=nse1 afpSet = new ArrayList(); + List afpSet = new ArrayList<>(); for (int afp=0;afp atoms = new ArrayList(); + List atoms = new ArrayList<>(); for ( int i = 0 ; i < length ; i++){ Atom a; @@ -2027,7 +2022,7 @@ private Atom[] getAtoms(Atom[] ca, int length, boolean clone) throws StructureE } atoms.add(a); } - return atoms.toArray(new Atom[atoms.size()]); + return atoms.toArray(Atom.EmptyAtomArray); } @@ -2210,21 +2205,14 @@ public void convertAfpChain(AFPChain afpChain, Atom[] ca1, Atom[] ca2) { afpChain.setBlockNum(1); //afpChain.setAlignScore(z); - Matrix[] m ; - - if ( r != null ) { - m = new Matrix[1]; - m[0] = r; - } else { - m = new Matrix[0]; - } + Matrix[] m = r != null ? new Matrix[]{r} : Matrix.EmptyMatrixArray; Atom[] as ; if ( t != null) { as = new Atom[1]; as[0] = t; } else { - as = new Atom[0]; + as = Atom.EmptyAtomArray; } afpChain.setBlockRotationMatrix(m); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeMain.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeMain.java index 70f4acb64f..4bc30741a4 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeMain.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeMain.java @@ -75,7 +75,7 @@ public CeMain(){ * -pdbFilePath /tmp -autoFetch -printCE -pdb1 1cnv -pdb2 3cna * */ - public static void main(String[] args) throws Exception { + public static void main(String[] args) { CeUserArgumentProcessor processor = new CeUserArgumentProcessor(); //Responsible for creating a CeMain instance processor.process(args); } @@ -94,12 +94,8 @@ public AFPChain align(Atom[] ca1, Atom[] ca2, Object param) throws StructureExce ca2clone = new Atom[ca2.length]; int pos = 0; - for (Atom a : ca2){ - Group g = (Group)a.getGroup().clone(); // works because each group has only a CA atom - - ca2clone[pos] = g.getAtom(a.getName()); - - pos++; + for (Atom a : ca2) { + ca2clone[pos++] = ((Group) a.getGroup().clone()).getAtom(a.getName()); // works because each group has only a CA atom } calculator = new CECalculator(params); @@ -121,15 +117,17 @@ public AFPChain align(Atom[] ca1, Atom[] ca2, Object param) throws StructureExce if (ca2.length!=0 && ca2[0].getGroup().getChain()!=null && ca2[0].getGroup().getChain().getStructure()!=null) afpChain.setName2(ca2[0].getGroup().getChain().getStructure().getName()); - if ( afpChain.getNrEQR() == 0) + if (afpChain.getNrEQR() == 0) return afpChain; // Set the distance matrix int winSize = params.getWinSize(); int winSizeComb1 = (winSize-1)*(winSize-2)/2; - double[][] m = calculator.initSumOfDistances(ca1.length, ca2.length, winSize, winSizeComb1, ca1, ca2clone); - afpChain.setDistanceMatrix(new Matrix(m)); + + afpChain.setDistanceMatrix(new Matrix( + calculator.initSumOfDistances(ca1.length, ca2.length, winSize, winSizeComb1, ca1, ca2clone) + )); afpChain.setSequentialAlignment(true); return afpChain; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeParameters.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeParameters.java index 8383acf585..ee7dc561d5 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeParameters.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeParameters.java @@ -26,8 +26,8 @@ import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; -import org.biojava.nbio.structure.align.util.CliTools; import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; +import org.biojava.nbio.structure.align.util.CliTools; import java.util.ArrayList; import java.util.List; @@ -46,16 +46,16 @@ public class CeParameters implements ConfigStrucAligParams { protected double rmsdThrJoin; protected double maxOptRMSD; - public static enum ScoringStrategy { + public enum ScoringStrategy { CA_SCORING("CA only"), SIDE_CHAIN_SCORING("Sidechain orientation"), SIDE_CHAIN_ANGLE_SCORING("Angle between sidechains"), CA_AND_SIDE_CHAIN_ANGLE_SCORING("CA distance+Angle between sidechains"), SEQUENCE_CONSERVATION("Sequence Conservation"); - public static ScoringStrategy DEFAULT_SCORING_STRATEGY = CA_SCORING; + public static final ScoringStrategy DEFAULT_SCORING_STRATEGY = CA_SCORING; - private String name; - private ScoringStrategy(String name) { + private final String name; + ScoringStrategy(String name) { this.name = name; } @Override @@ -161,9 +161,9 @@ public void setRmsdThr(Double rmsdThr) { public Double getRmsdThrJoin() { return rmsdThrJoin; } - public void setRmsdThrJoin(Double rmsdThrJoin) { - this.rmsdThrJoin = rmsdThrJoin; - } +// public void setRmsdThrJoin(Double rmsdThrJoin) { +// this.rmsdThrJoin = rmsdThrJoin; +// } public ScoringStrategy getScoringStrategy() { @@ -205,7 +205,7 @@ public Integer getMaxGapSize() { @Override public List getUserConfigHelp() { - List params =new ArrayList(); + List params = new ArrayList<>(); String helpMaxGap = "This parameter configures the maximum gap size G, that is applied during the AFP extension. The larger the value, the longer the calculation time can become, Default value is 30. Set to 0 for no limit. " ; //String helpRmsdThr = "This configures the RMSD threshold applied during the trace of the fragment matrix."; String helpWinSize = "This configures the fragment size m of Aligned Fragment Pairs (AFPs)."; @@ -222,7 +222,7 @@ public List getUserConfigHelp() { @Override public List getUserConfigParameters() { - List params = new ArrayList(); + List params = new ArrayList<>(); params.add("MaxGapSize"); //params.add("RmsdThr"); params.add("WinSize"); @@ -236,7 +236,7 @@ public List getUserConfigParameters() { @Override public List getUserConfigParameterNames(){ - List params = new ArrayList(); + List params = new ArrayList<>(); params.add("max. gap size G (during AFP extension)."); //params.add("RMSD threshold during trace of the fragment matrix."); params.add("fragment size m"); @@ -250,7 +250,7 @@ public List getUserConfigParameterNames(){ @Override @SuppressWarnings("rawtypes") public List getUserConfigTypes() { - List params = new ArrayList(); + List params = new ArrayList<>(); params.add(Integer.class); //params.add(Double.class); params.add(Integer.class); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeSideChainMain.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeSideChainMain.java index f74793e7f4..034ea5b581 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeSideChainMain.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/CeSideChainMain.java @@ -21,7 +21,6 @@ package org.biojava.nbio.structure.align.ce; import org.biojava.nbio.structure.align.StructureAlignment; -import org.biojava.nbio.structure.align.util.ConfigurationException; public class CeSideChainMain extends CeMain implements StructureAlignment { @@ -44,7 +43,7 @@ public CeSideChainMain(){ } } - public static void main(String[] args) throws ConfigurationException { + public static void main(String[] args) { CeSideChainUserArgumentProcessor processor = new CeSideChainUserArgumentProcessor(); processor.process(args); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/ConfigStrucAligParams.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/ConfigStrucAligParams.java index a22323fe25..3af1ca3321 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/ConfigStrucAligParams.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/ConfigStrucAligParams.java @@ -31,31 +31,31 @@ public interface ConfigStrucAligParams { * * @return list of parameters */ - public List getUserConfigParameters(); + List getUserConfigParameters(); /** The labels to be displayed to the user for each parameter * * @return list of parameter names */ - public List getUserConfigParameterNames(); + List getUserConfigParameterNames(); /** Get the data types of the parameters * * @return list of parameter classes */ @SuppressWarnings("rawtypes") - public List getUserConfigTypes(); + List getUserConfigTypes(); /** The help text for each of these parameters. * * @return help strings */ - public List getUserConfigHelp(); + List getUserConfigHelp(); /** Set the parameters to the default. * */ - public void reset(); + void reset(); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/GuiWrapper.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/GuiWrapper.java index 687d2e625f..df7d98ad66 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/GuiWrapper.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/GuiWrapper.java @@ -69,8 +69,8 @@ public static Object display(AFPChain afpChain, Atom[] ca1, Atom[] ca2) Class c = Class.forName(strucAlignmentDisplay); - Method display = c.getMethod("display", new Class[]{AFPChain.class, Atom[].class, - Atom[].class}); + Method display = c.getMethod("display", AFPChain.class, Atom[].class, + Atom[].class); Object structureAlignmentJmol = display.invoke(null, afpChain,ca1,ca2); @@ -87,7 +87,7 @@ public static void showAlignmentImage(AFPChain afpChain, Atom[] ca1, Class abstractAligJmolC = Class.forName(abstractAligJmol); Class c = Class.forName(displayAFP); - Method show = c.getMethod("showAlignmentPanel", new Class[] {AFPChain.class, Atom[].class, Atom[].class, abstractAligJmolC}); + Method show = c.getMethod("showAlignmentPanel", AFPChain.class, Atom[].class, Atom[].class, abstractAligJmolC); show.invoke(null,afpChain, ca1, ca2, jmol); } @@ -104,7 +104,7 @@ public static void showStructure(Structure structure) Object strucAligJ = structureAlignmentJmol.newInstance(); - Method setS = structureAlignmentJmol.getMethod("setStructure", new Class[] {Structure.class}); + Method setS = structureAlignmentJmol.getMethod("setStructure", Structure.class); setS.invoke(strucAligJ,structure); } @@ -129,7 +129,7 @@ public static Structure getAlignedStructure(Atom[] ca1, Atom[] ca2) Class structureAlignmentJmol = Class.forName(strucAligJmol); Class c = Class.forName(displayAFP); - Method show = c.getMethod("getAlignedStructure", new Class[] { Atom[].class, Atom[].class}); + Method show = c.getMethod("getAlignedStructure", Atom[].class, Atom[].class); Structure s = (Structure) show.invoke(null, ca1, ca2); @@ -143,7 +143,7 @@ public static JPanel getScaleableMatrixPanel(Matrix m) Class scaleMatrixPanelC = Class.forName(scaleMatrixPanel); - Method setMatrix = scaleMatrixPanelC.getMethod("setMatrix", new Class[] { Matrix.class}); + Method setMatrix = scaleMatrixPanelC.getMethod("setMatrix", Matrix.class); JPanel panel = (JPanel) scaleMatrixPanelC.newInstance(); @@ -161,7 +161,7 @@ public static Atom[] getAtomArray(Atom[] ca, List hetatoms, List n Class structureAlignmentJmol = Class.forName(strucAligJmol); Class c = Class.forName(displayAFP); - Method show = c.getMethod("getAtomArray", new Class[] { Atom[].class, List.class, List.class}); + Method show = c.getMethod("getAtomArray", Atom[].class, List.class, List.class); Atom[] atoms = (Atom[]) show.invoke(null, ca, hetatoms, nucs); @@ -185,7 +185,7 @@ public static void showDBResults(StartupParameters params) { Class c = Class.forName(tableClass); Object table = c.newInstance(); - Method show = c.getMethod("show", new Class[]{File.class, UserConfiguration.class }); + Method show = c.getMethod("show", File.class, UserConfiguration.class); show.invoke(table, new File(params.getShowDBresult()),config); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/MatrixListener.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/MatrixListener.java index 618f688265..1010a95bcc 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/MatrixListener.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/MatrixListener.java @@ -24,7 +24,7 @@ public interface MatrixListener { - public double[][] matrixInOptimizer(double[][] max); + double[][] matrixInOptimizer(double[][] max); - public boolean[][] initializeBreakFlag(boolean[][] brkFlag); + boolean[][] initializeBreakFlag(boolean[][] brkFlag); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/OptimalCECPMain.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/OptimalCECPMain.java index b10e09fbfd..ac00b171ad 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/OptimalCECPMain.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/OptimalCECPMain.java @@ -34,10 +34,7 @@ import org.biojava.nbio.structure.jama.Matrix; import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Scanner; +import java.util.*; /** * A wrapper for {@link CeMain} which sets default parameters to be appropriate for finding @@ -126,15 +123,11 @@ private static void permuteArray(T[] arr, int cp) { "Permutation point ("+cp+") must be between -ca2.length and ca2.length-1" ); } - List temp = new ArrayList(cp); + List temp = new ArrayList<>(cp); // shift residues left - for(int i=0;i>> blocks = new ArrayList>>(afpChain.getBlockNum()*2); + List>> blocks = new ArrayList<>(afpChain.getBlockNum() * 2); //Update residue indices // newi = (oldi-cp) % N @@ -342,9 +335,9 @@ private static void permuteOptAln(AFPChain afpChain, int cp) continue; // set up storage for the current block - List> currBlock = new ArrayList>(2); - currBlock.add( new ArrayList()); - currBlock.add( new ArrayList()); + List> currBlock = new ArrayList<>(2); + currBlock.add(new ArrayList<>()); + currBlock.add(new ArrayList<>()); blocks.add(currBlock); // pos = 0 case @@ -356,9 +349,9 @@ private static void permuteOptAln(AFPChain afpChain, int cp) //this happens when the new alignment crosses the protein terminus if( optAln[block][1][pos-1]+cp= ca2len) { - currBlock = new ArrayList>(2); - currBlock.add( new ArrayList()); - currBlock.add( new ArrayList()); + currBlock = new ArrayList<>(2); + currBlock.add(new ArrayList<>()); + currBlock.add(new ArrayList<>()); blocks.add(currBlock); } currBlock.get(0).add( optAln[block][0][pos] ); @@ -651,9 +644,8 @@ public static void main(String[] args){ * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException - * @throws StructureException */ - private static void displayAlignment(AFPChain afpChain, Atom[] ca1, Atom[] ca2) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, StructureException { + private static void displayAlignment(AFPChain afpChain, Atom[] ca1, Atom[] ca2) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { Atom[] ca1clone = StructureTools.cloneAtomArray(ca1); Atom[] ca2clone = StructureTools.cloneAtomArray(ca2); if (! GuiWrapper.isGuiModuleInstalled()) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/UserArgumentProcessor.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/UserArgumentProcessor.java index db5e720e5b..e286356b8c 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/UserArgumentProcessor.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/ce/UserArgumentProcessor.java @@ -20,8 +20,6 @@ */ package org.biojava.nbio.structure.align.ce; -import org.biojava.nbio.structure.align.util.ConfigurationException; - public interface UserArgumentProcessor { @@ -29,11 +27,11 @@ public interface UserArgumentProcessor { * * @param argv */ - public void process(String[] argv) throws ConfigurationException; + void process(String[] argv); /** * Print help about the arguments * @return */ - public String printHelp(); + String printHelp(); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/client/FarmJobParameters.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/client/FarmJobParameters.java index 0415ce0439..3ab4dcae93 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/client/FarmJobParameters.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/client/FarmJobParameters.java @@ -29,7 +29,7 @@ public class FarmJobParameters { public static final int DEFAULT_NR_ALIGNMENTS = -1; public static final int DEFAULT_NR_THREADS = 1; public static final String DEFAULT_SERVER_URL; - private static ResourceManager resourceManager; + private static final ResourceManager resourceManager; static { resourceManager = ResourceManager.getResourceManager("jfatcat"); DEFAULT_SERVER_URL = resourceManager.getString("server.url"); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/client/FarmJobRunnable.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/client/FarmJobRunnable.java index d592cc014d..8f2d394319 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/client/FarmJobRunnable.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/client/FarmJobRunnable.java @@ -20,6 +20,8 @@ */ package org.biojava.nbio.structure.align.client; +import org.biojava.nbio.core.util.FlatFileCache; +import org.biojava.nbio.core.util.PrettyXMLWriter; import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.StructureAlignment; @@ -40,8 +42,6 @@ import org.biojava.nbio.structure.io.LocalPDBDirectory.FetchBehavior; import org.biojava.nbio.structure.scop.RemoteScopInstallation; import org.biojava.nbio.structure.scop.ScopFactory; -import org.biojava.nbio.core.util.FlatFileCache; -import org.biojava.nbio.core.util.PrettyXMLWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -70,12 +70,12 @@ public class FarmJobRunnable implements Runnable { private static final String JFATCAT_NAME = "jfatcat.name"; private static final String JFATCAT_VERSION = "jfatcat.version"; - private static ResourceManager resourceManager = ResourceManager.getResourceManager("jfatcat"); + private static final ResourceManager resourceManager = ResourceManager.getResourceManager("jfatcat"); //private static DateFormat dateFormat = new SimpleDateFormat("MMMM dd, yyyy h:mm a",Locale.US); - FarmJobParameters params; + final FarmJobParameters params; String prevName1; Atom[] ca1 ; @@ -93,12 +93,12 @@ public class FarmJobRunnable implements Runnable { boolean terminated ; List progressListeners; - CountProgressListener counter ; + final CountProgressListener counter ; - String userName = null; - protected AtomCache cache; + final String userName; + protected final AtomCache cache; - boolean verbose = false; // TODO dmyersturnbull: we should probably remove this in favor of SLF4J + boolean verbose; // TODO dmyersturnbull: we should probably remove this in favor of SLF4J String version = null; private static final String alignURL = "/align/"; @@ -111,7 +111,7 @@ public FarmJobRunnable(FarmJobParameters params){ cache = new AtomCache( params.getPdbFilePath(), params.getCacheFilePath()); - if ( params.getServer()!= null && (!params.getServer().equals("") ) ) { + if ( params.getServer()!= null && (!params.getServer().isEmpty()) ) { RemotePDPProvider pdpprovider = new RemotePDPProvider(); @@ -155,7 +155,7 @@ public FarmJobRunnable(FarmJobParameters params){ public void addAlignmentProgressListener(AlignmentProgressListener listener){ if (progressListeners == null) - progressListeners = new ArrayList(); + progressListeners = new ArrayList<>(); progressListeners.add(listener); } @@ -228,7 +228,7 @@ public void run() { } SortedSet alignmentPairs = msg.getPairs(); logger.debug("{}: Server responded with {} pairs.", userName, alignmentPairs.size()); - List results = new ArrayList(); + List results = new ArrayList<>(); String algorithmName = msg.getMethod(); if ( version == null) { @@ -470,7 +470,7 @@ private void printMemory() { private StructureAlignment getAlgorithm(String algorithmName) throws StructureException { - StructureAlignment algorithm = null; + StructureAlignment algorithm; if ( algorithmName == null){ @@ -531,7 +531,7 @@ protected PdbPairsMessage getAlignmentPairsFromServer() { if ( maxNrAlignments < nrPairs ) nrPairs = maxNrAlignments; - SortedSet allPairs = new TreeSet(); + SortedSet allPairs = new TreeSet<>(); PdbPairsMessage msg = null; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/client/JFatCatClient.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/client/JFatCatClient.java index 92c4577115..6773045baa 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/client/JFatCatClient.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/client/JFatCatClient.java @@ -20,13 +20,13 @@ */ package org.biojava.nbio.structure.align.client; +import org.biojava.nbio.core.util.Download; import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.fatcat.FatCatRigid; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.util.AtomCache; -import org.biojava.nbio.structure.align.util.URLConnectionTools; import org.biojava.nbio.structure.align.util.ResourceManager; +import org.biojava.nbio.structure.align.util.URLConnectionTools; import org.biojava.nbio.structure.align.xml.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,370 +40,360 @@ import java.util.Random; import java.util.SortedSet; import java.util.TreeSet; +import java.util.stream.Collectors; public class JFatCatClient { - private final static Logger logger = LoggerFactory.getLogger(JFatCatClient.class); + private final static Logger logger = LoggerFactory.getLogger(JFatCatClient.class); + + private static final ResourceManager resourceManager = ResourceManager.getResourceManager("jfatcat"); - private static ResourceManager resourceManager = ResourceManager.getResourceManager("jfatcat"); + private static final String serverAPPEND = "show?name1=%s&name2=%s"; - private static final String serverAPPEND = "show?name1=%s&name2=%s"; + private static final String sendAPPEND = "submit?name1=%s&name2=%s&version=%s"; - private static final String sendAPPEND = "submit?name1=%s&name2=%s&version=%s"; + private static final String multiSendAPPEND = "jobSubmit?username=%s&version=%s"; - private static final String multiSendAPPEND = "jobSubmit?username=%s&version=%s"; + private static final String representAPPEND = "representatives?cluster=%s"; - private static final String representAPPEND = "representatives?cluster=%s"; + private static final String serverHasResult = "hasResult?method=%s&name1=%s&name2=%s"; - private static final String serverHasResult = "hasResult?method=%s&name1=%s&name2=%s"; + private static final int DEFAULT_TIMEOUT = 5000; - private static final int DEFAULT_TIMEOUT = 5000; + private static final String serverPositionInQueue = "queuePosition?method=%s&name1=%s&name2=%s"; - private static final String serverPositionInQueue = "queuePosition?method=%s&name1=%s&name2=%s"; + private static final Random generator; - private static Random generator; + private static final String newline = System.getProperty("line.separator"); - private static String newline = System.getProperty("line.separator"); + private static final String KILL_JOB = "KILL_JOB"; - private static String KILL_JOB = "KILL_JOB"; + private static final String COME_BACK_LATER = "COME_BACK_LATER"; - private static String COME_BACK_LATER = "COME_BACK_LATER"; + static { - static { + generator = new Random(); - generator = new Random(); + } - } + public static void main(String[] args) throws Exception { + //System.out.println(hasPrecalculatedResult("http://source.rcsb.org/jfatcatserver/align/", "jCE Circular Permutation", "1CDG.A", "1TIM.A")); + AtomCache cache = new AtomCache(); + String name1 = "2W72.A"; + String name2 = "1D2Z.D"; - public static void main(String[] args) throws Exception { - //System.out.println(hasPrecalculatedResult("http://source.rcsb.org/jfatcatserver/align/", "jCE Circular Permutation", "1CDG.A", "1TIM.A")); - AtomCache cache = new AtomCache(); - String name1= "2W72.A"; - String name2= "1D2Z.D"; + Atom[] ca1 = cache.getAtoms(name1); + Atom[] ca2 = cache.getAtoms(name2); - Atom[] ca1 = cache.getAtoms(name1); - Atom[] ca2 = cache.getAtoms(name2); + int timeout = 10000; - int timeout = 10000; + String testServer = "http://source.rcsb.org/jfatcatserver/align/"; - String testServer = "http://source.rcsb.org/jfatcatserver/align/"; + System.out.println(getAFPChainFromServer(testServer, FatCatRigid.algorithmName, name1, name2, ca1, ca2, timeout)); - System.out.println(getAFPChainFromServer(testServer, FatCatRigid.algorithmName, name1, name2, ca1, ca2, timeout)); + PdbPairsMessage msg = getPdbPairs(testServer, 1, "test"); - PdbPairsMessage msg = getPdbPairs(testServer, 1, "test"); + System.out.println(msg); - System.out.println(msg); + System.out.println(getRepresentatives(FarmJobParameters.DEFAULT_SERVER_URL, 40)); + } - System.out.println(getRepresentatives(FarmJobParameters.DEFAULT_SERVER_URL, 40)); - } + public static boolean hasPrecalculatedResult(String serverLocation, String method, String name1, String name2) { + return hasPrecalculatedResult(serverLocation, method, name1, name2, DEFAULT_TIMEOUT); + } - public static boolean hasPrecalculatedResult(String serverLocation, String method, String name1, String name2 ){ - return hasPrecalculatedResult(serverLocation, method, name1, name2, DEFAULT_TIMEOUT ); - } + public static boolean hasPrecalculatedResult(String serverLocation, String method, String name1, String name2, int timeout) { - public static boolean hasPrecalculatedResult(String serverLocation, String method, String name1, String name2, int timeout){ + String serverURL = serverLocation + serverHasResult; - String serverURL = serverLocation + serverHasResult; + boolean hasResults = false; + try { + String u = String.format(serverURL, URLEncoder.encode(method, "UTF-8"), name1, name2); + URL url = new URL(u); + //System.out.println("has result ? ..." + url); - boolean hasResults = false; - try { - String u = String.format(serverURL,URLEncoder.encode(method,"UTF-8"),name1,name2) ; - URL url = new URL(u); - //System.out.println("has result ? ..." + url); + InputStream stream = URLConnectionTools.getInputStream(url, timeout); - InputStream stream = URLConnectionTools.getInputStream(url,timeout); + String xml; - String xml = null; + if (stream != null) { - if ( stream != null) { + xml = convertStreamToString(stream); + logger.info(" has PrecalcResults got XML from server: " + xml); + HasResultXMLConverter conv = new HasResultXMLConverter(); + hasResults = conv.fromXML(xml); + } - xml = convertStreamToString(stream); - logger.info(" has PrecalcResults got XML from server: " + xml); - HasResultXMLConverter conv = new HasResultXMLConverter(); - hasResults = conv.fromXML(xml); - } + } catch (IOException e) { + // log error and return false + logger.error("error in JFatCatClient: getAFPChainFromServer", e); + } + return hasResults; + } - } catch (IOException e){ - // log error and return false - logger.error("error in JFatCatClient: getAFPChainFromServer",e); - } - return hasResults; - } + public int getPositionInQueue(String serverLocation, String method, String name1, String name2) { + return getPositionInQueue(serverLocation, method, name1, name2, DEFAULT_TIMEOUT); + } - public int getPositionInQueue(String serverLocation, String method, String name1, String name2){ - return getPositionInQueue(serverLocation, method, name1, name2, DEFAULT_TIMEOUT); - } + public int getPositionInQueue(String serverLocation, String method, String name1, String name2, int timeout) { + String serverURL = serverLocation + serverPositionInQueue; - public int getPositionInQueue(String serverLocation, String method, String name1, String name2, int timeout){ - String serverURL = serverLocation + serverPositionInQueue; + int position = Integer.MIN_VALUE; + try { + String u = String.format(serverURL, URLEncoder.encode(method, "UTF-8"), name1, name2); + URL url = new URL(u); - int position = Integer.MIN_VALUE; - try { - String u = String.format(serverURL,URLEncoder.encode(method,"UTF-8"),name1,name2) ; - URL url = new URL(u); + InputStream stream = URLConnectionTools.getInputStream(url, timeout); - InputStream stream = URLConnectionTools.getInputStream(url,timeout); + String xml; - String xml = null; + if (stream != null) { - if ( stream != null) { + xml = convertStreamToString(stream); + //System.out.println("got XML from server: " + xml); + PositionInQueueXMLConverter conv = new PositionInQueueXMLConverter(); + position = conv.fromXML(xml); + } - xml = convertStreamToString(stream); - //System.out.println("got XML from server: " + xml); - PositionInQueueXMLConverter conv = new PositionInQueueXMLConverter(); - position = conv.fromXML(xml); - } + } catch (IOException e) { + logger.error("error in JFatCatClient: getAFPChainFromServer", e); // TODO dmyersturnbull: method should throw; we shouldn't catch here + } + return position; - } catch (IOException e){ - logger.error("error in JFatCatClient: getAFPChainFromServer",e); // TODO dmyersturnbull: method should throw; we shouldn't catch here - } - return position; + } - } - public static AFPChain getAFPChainFromServer(String serverLocation , String name1, String name2, Atom[] ca1, Atom[] ca2) { - String method = FatCatRigid.algorithmName; - return getAFPChainFromServer(serverLocation, method, name1, name2, ca1, ca2,DEFAULT_TIMEOUT); - } + public static AFPChain getAFPChainFromServer(String serverLocation, String name1, String name2, Atom[] ca1, Atom[] ca2) { + String method = FatCatRigid.algorithmName; + return getAFPChainFromServer(serverLocation, method, name1, name2, ca1, ca2, DEFAULT_TIMEOUT); + } - public static AFPChain getAFPChainFromServer(String serverLocation , String method, String name1, String name2, Atom[] ca1, Atom[] ca2, int timeout) - { + public static AFPChain getAFPChainFromServer(String serverLocation, String method, String name1, String name2, Atom[] ca1, Atom[] ca2, int timeout) { - String serverURL = serverLocation + serverAPPEND; + String serverURL = serverLocation + serverAPPEND; - try { - String u = String.format(serverURL,name1,name2) ; + try { + String u = String.format(serverURL, name1, name2); - if ( method != null) - u+= "&method=" + URLEncoder.encode(method,"UTF-8"); + if (method != null) + u += "&method=" + URLEncoder.encode(method, "UTF-8"); - URL url = new URL(u); - logger.info("requesting alignment from server..." + url); - // have a short timeout for this... - // 5 sec - InputStream stream = URLConnectionTools.getInputStream(url,timeout); + URL url = new URL(u); + logger.info("requesting alignment from server..." + url); + // have a short timeout for this... + // 5 sec + InputStream stream = URLConnectionTools.getInputStream(url, timeout); - String xml = null; - if ( stream != null) { + if (stream != null) { + String xml = convertStreamToString(stream); + return AFPChainXMLParser.fromXML(xml, name1, name2, ca1, ca2); + } - xml = convertStreamToString(stream); - } - if (xml != null) { - return AFPChainXMLParser.fromXML (xml, name1, name2, ca1, ca2); + return null; - } else { - return null; - } - // TODO dmyersturnbull: method should throw; we shouldn't catch here - } catch (IOException e){ - logger.error("error in JFatCatClient: getAFPChainFromServer",e); - } catch (StructureException e) { - logger.error("error in JFatCatClient: getAFPChainFromServer",e); - } - return null; - } + // TODO dmyersturnbull: method should throw; we shouldn't catch here + } catch (IOException e) { + logger.error("error in JFatCatClient: getAFPChainFromServer", e); + } + return null; + } - public static String convertStreamToString(InputStream stream){ - BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); - StringBuilder sb = new StringBuilder(); + public static String convertStreamToString(InputStream stream) { - String line = null; - try { - while ((line = reader.readLine()) != null) { - sb.append(line).append(newline); - } - } catch (IOException e) { - logger.error("Couldn't convert stream to string", e); // TODO dmyersturnbull: method should throw; we shouldn't catch here - } finally { - try { - stream.close(); - } catch (IOException e) { - logger.warn("Can't close stream", e); - } - } + try { - return sb.toString(); - } +// int aa = stream.available(); - public static String sendMultiAFPChainToServer(String serverLocation, String multiXML, String username) throws JobKillException{ - String version = resourceManager.getString("jfatcat.version"); - return sendMultiAFPChainToServer(serverLocation, multiXML, username, version); - } + return new BufferedReader(new InputStreamReader(stream)) + .lines() + .collect(Collectors.joining("\n")); +// String line; +// StringBuilder sb = new StringBuilder(aa); +// while ((line = reader.readLine()) != null) { +// sb.append(line).append(newline); +// } +// return sb.toString(); +// } catch (IOException e) { +// logger.error("Couldn't convert stream to string", e); // TODO dmyersturnbull: method should throw; we shouldn't catch here +// return null; + } finally { + try { + stream.close(); + } catch (IOException e) { + logger.warn("Can't close stream", e); + } + } - public static String sendMultiAFPChainToServer(String serverLocation, String multiXML, String username, String version) throws JobKillException{ - String multiSendURL = serverLocation + multiSendAPPEND; + } - String responseS = ""; + public static String sendMultiAFPChainToServer(String serverLocation, String multiXML, String username) throws JobKillException { + String version = resourceManager.getString("jfatcat.version"); + return sendMultiAFPChainToServer(serverLocation, multiXML, username, version); + } - String u = String.format(multiSendURL,username,version); + public static String sendMultiAFPChainToServer(String serverLocation, String multiXML, String username, String version) throws JobKillException { + String multiSendURL = serverLocation + multiSendAPPEND; - int timeout = getTimeout(); + String responseS = ""; - boolean submitted = false; + String u = String.format(multiSendURL, username, version); - while (! submitted ){ - try { - URL url = new URL(u); - InputStream response = URLConnectionTools.doPOST(url, multiXML,timeout); - responseS = convertStreamToString(response); - submitted = true; - if (! responseS.contains("OK")) - logger.error("server returned " + responseS); + int timeout = getTimeout(); - // server is busy... wait a bit and try again - if ( responseS.startsWith(COME_BACK_LATER)){ - submitted = false; - } + boolean submitted = false; - } catch (Exception e){ - logger.error("Error in JFatCatClient: while sending results back to server",e); + while (!submitted) { + try { + URL url = new URL(u); + InputStream response = URLConnectionTools.doPOST(url, multiXML, timeout); + responseS = convertStreamToString(response); + submitted = true; + if (!responseS.contains("OK")) + logger.error("server returned " + responseS); - try { - int randomSleep = getRandomSleepTime(); - logger.warn("sleeping " + (randomSleep/1000) + " sec."); - Thread.sleep(randomSleep); - } catch (InterruptedException ex){ - logger.warn("Interrupted while sleeping", ex); - } - } - } + // server is busy... wait a bit and try again + if (responseS.startsWith(COME_BACK_LATER)) { + submitted = false; + } - if ( responseS.startsWith(KILL_JOB)){ - throw new JobKillException("Server responded with KILL message."); + } catch (Exception e) { + logger.error("Error in JFatCatClient: while sending results back to server", e); - } + try { + int randomSleep = getRandomSleepTime(); + logger.warn("sleeping " + (randomSleep / 1000) + " sec."); + Thread.sleep(randomSleep); + } catch (InterruptedException ex) { + logger.warn("Interrupted while sleeping", ex); + } + } + } + if (responseS.startsWith(KILL_JOB)) { + throw new JobKillException("Server responded with KILL message."); - return responseS; - } + } - public static int getRandomSleepTime() { - // now wait between 7 and 13 min. + return responseS; + } - int minTime = 560000; + public static int getRandomSleepTime() { - int maxTime = 7800000 - minTime; + // now wait between 7 and 13 min. - int nextId = generator.nextInt(maxTime); - return minTime + nextId; + int minTime = 560000; - } + int maxTime = 7800000 - minTime; + int nextId = generator.nextInt(maxTime); + return minTime + nextId; - public static final void sendAFPChainToServer(String serverLocation, AFPChain afpChain,Atom[] ca1, Atom[] ca2) throws JobKillException - { + } - String sendURL = serverLocation + sendAPPEND; - String version = resourceManager.getString("jfatcat.version"); + public static void sendAFPChainToServer(String serverLocation, AFPChain afpChain, Atom[] ca1, Atom[] ca2) throws JobKillException { - int timeout = getTimeout(); + String sendURL = serverLocation + sendAPPEND; - try { + String version = resourceManager.getString("jfatcat.version"); - // just to make sure that similarity has been calculated! - afpChain.getSimilarity(); + int timeout = getTimeout(); - String xml = AFPChainXMLConverter.toXML(afpChain, ca1, ca2); + try { - String u = String.format(sendURL,afpChain.getName1() , afpChain.getName2(),version); + // just to make sure that similarity has been calculated! + afpChain.getSimilarity(); - URL url = new URL(u); + String xml = AFPChainXMLConverter.toXML(afpChain, ca1, ca2); - InputStream response = URLConnectionTools.doPOST(url, xml,timeout); + String u = String.format(sendURL, afpChain.getName1(), afpChain.getName2(), version); - logger.debug("got response: {}", convertStreamToString(response)); + URL url = new URL(u); - if ( xml.startsWith("KILL_JOB")){ - throw new JobKillException("Server responded with KILL message."); - } + InputStream response = URLConnectionTools.doPOST(url, xml, timeout); - } catch (IOException e){ - logger.error("error in JFatCatClient: sendAFPChainToServer",e); - } + logger.debug("got response: {}", convertStreamToString(response)); - } + if (xml.startsWith("KILL_JOB")) { + throw new JobKillException("Server responded with KILL message."); + } - public static final int getTimeout(){ - String timeoutS = resourceManager.getString("connection.timeout"); - int timeout = 60000; + } catch (IOException e) { + logger.error("error in JFatCatClient: sendAFPChainToServer", e); + } - try { - timeout = Integer.parseInt(timeoutS); - } catch (NumberFormatException ex ){ - logger.error("Bad connection.timeout parameter",ex); - } - return timeout; - } + } + public static int getTimeout() { + String timeoutS = resourceManager.getString("connection.timeout"); + int timeout = 60000; - public static final PdbPairsMessage getPdbPairs(String url,int nrPair, String username) throws IOException, JobKillException { + try { + timeout = Integer.parseInt(timeoutS); + } catch (NumberFormatException ex) { + logger.error("Bad connection.timeout parameter", ex); + } + return timeout; + } - String urlS= url + "getPairs?" + "nrPairs=" + nrPair + "&username=" + URLEncoder.encode(username, "UTF-8"); - int timeout = getTimeout(); + public static PdbPairsMessage getPdbPairs(String url, int nrPair, String username) throws IOException, JobKillException { - PdbPairsMessage msg = null; - logger.info("requesting {}", urlS); - URL serverUrl = new URL(urlS); - // we are very tolerant with requesting a set of pairs, since we probably depend on getting it to get work started... - // 1 min... - InputStream stream = URLConnectionTools.getInputStream(serverUrl,timeout); - String xml = null; - if ( stream != null) { + String urlS = url + "getPairs?" + "nrPairs=" + nrPair + "&username=" + URLEncoder.encode(username, "UTF-8"); + int timeout = getTimeout(); - xml = convertStreamToString(stream); - if (xml != null) { - if ( xml.startsWith("KILL_JOB")){ - // we got the KILL signal from the server... - throw new JobKillException("Server responded with KILL message."); - } - msg = PdbPairXMLConverter.convertXMLtoPairs(xml); + logger.info("requesting {}", urlS); + URL serverUrl = new URL(urlS); + // we are very tolerant with requesting a set of pairs, since we probably depend on getting it to get work started... + // 1 min... + InputStream stream = Download.stream(serverUrl, timeout); //URLConnectionTools.getInputStream(serverUrl,timeout); + String xml; - } - } + xml = convertStreamToString(stream); - return msg; - } + if (xml.startsWith("KILL_JOB")) + throw new JobKillException("Server responded with KILL message."); // we got the KILL signal from the server... + return PdbPairXMLConverter.convertXMLtoPairs(xml); + } - public static final SortedSet getRepresentatives(String serverLocation, int cutoff){ - SortedSet representatives = new TreeSet(); - String representURL = serverLocation + representAPPEND; + public static SortedSet getRepresentatives(String serverLocation, int cutoff) { + SortedSet representatives = new TreeSet<>(); - if ( cutoff < 20) - cutoff = 40; - int timeout = getTimeout(); - String u = String.format(representURL,cutoff); + String representURL = serverLocation + representAPPEND; - logger.info("Fetching representatives from "+u); - try { - URL url = new URL(u); + if (cutoff < 20) + cutoff = 40; + int timeout = getTimeout(); + String u = String.format(representURL, cutoff); - InputStream stream = URLConnectionTools.getInputStream(url,timeout); + logger.info("Fetching representatives from " + u); + try { + URL url = new URL(u); - String xml = null; + InputStream stream = URLConnectionTools.getInputStream(url, timeout); - if ( stream != null) { + String xml = null; - xml = convertStreamToString(stream); - } - if (xml != null) { - representatives = RepresentativeXMLConverter.fromXML(xml); - } - } catch (IOException e){ // TODO dmyersturnbull: method should throw; we shouldn't catch here - logger.error("Error fetching representatives",e); - } - return representatives; - } + if (stream != null) { + xml = convertStreamToString(stream); + } + if (xml != null) { + representatives = RepresentativeXMLConverter.fromXML(xml); + } + } catch (IOException e) { // TODO dmyersturnbull: method should throw; we shouldn't catch here + logger.error("Error fetching representatives", e); + } + return representatives; + } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/client/StructureName.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/client/StructureName.java index 4c682e624f..9962048059 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/client/StructureName.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/client/StructureName.java @@ -21,26 +21,8 @@ package org.biojava.nbio.structure.align.client; -import java.io.File; -import java.io.IOException; -import java.io.Serializable; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.biojava.nbio.structure.BioAssemblyIdentifier; -import org.biojava.nbio.structure.ResidueRange; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIdentifier; -import org.biojava.nbio.structure.SubstructureIdentifier; -import org.biojava.nbio.structure.URLIdentifier; +import org.biojava.nbio.core.util.Download; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.cath.CathDomain; import org.biojava.nbio.structure.cath.CathFactory; @@ -48,13 +30,21 @@ import org.biojava.nbio.structure.domain.PDPProvider; import org.biojava.nbio.structure.domain.RemotePDPProvider; import org.biojava.nbio.structure.ecod.EcodFactory; -import org.biojava.nbio.core.util.FileDownloadUtils; import org.biojava.nbio.structure.scop.ScopDatabase; import org.biojava.nbio.structure.scop.ScopDomain; import org.biojava.nbio.structure.scop.ScopFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; +import java.io.IOException; +import java.io.Serializable; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + /** * A utility class that makes working with names of structures, domains and ranges easier. @@ -74,7 +64,7 @@ public class StructureName implements Comparable, Serializable, S private static final long serialVersionUID = 4021229518711762957L; private static final Logger logger = LoggerFactory.getLogger(StructureName.class); - protected String name; + protected final String name; protected String pdbId; protected String chainName; @@ -94,7 +84,7 @@ public enum Source { FILE, ECOD, BIO, - }; + } private Source mySource = null; @@ -228,7 +218,7 @@ private void init(){ return; // Guess FILE based on file existence - File file = new File(FileDownloadUtils.expandUserHome(name)); + File file = new File(Download.expandUserHome(name)); if( file.canRead() && !file.isDirectory() ) { // an attempt to mitigate issue #398. It doesn't fix it but it catches the most common case of passing a pdb id and finding a file in working dir matching it if (name.matches("\\d\\w\\w\\w")) { @@ -308,7 +298,7 @@ private boolean initFromPDB(String suffix) { SubstructureIdentifier si = new SubstructureIdentifier(suffix); base = si; // Safe to realize immediately - pdbId = si.getPdbId(); + pdbId = si.pdbId; // Set chainName if unique Set chains = getChainNames(si); if(chains.size() == 1) { @@ -340,7 +330,7 @@ private boolean initFromFile() { } private static Set getChainNames(SubstructureIdentifier si) { - Set chains = new TreeSet(); + Set chains = new TreeSet<>(); List ranges = si.getResidueRanges(); for(ResidueRange range : ranges) { String chainName = range.getChainName(); @@ -361,7 +351,7 @@ private static Set getChainNames(SubstructureIdentifier si) { */ public String getPdbId() throws StructureException { if( pdbId == null) { - pdbId = toCanonical().getPdbId(); + pdbId = toCanonical().pdbId; } return pdbId; } @@ -488,7 +478,7 @@ public StructureIdentifier getBaseIdentifier() throws StructureException { } else { filename = name; } - filename = FileDownloadUtils.expandUserHome(filename); + filename = Download.expandUserHome(filename); base = new URLIdentifier(new File(filename).toURI().toURL()); } catch (MalformedURLException e) { // Should never happen @@ -626,13 +616,13 @@ public int compareTo(StructureName o) { * @return The best match for name among the domains of scopDB, or null if none match. */ public static ScopDomain guessScopDomain(String name, ScopDatabase scopDB) { - List matches = new LinkedList(); + List matches = new LinkedList<>(); // Try exact match first ScopDomain domain = scopDB.getDomainByScopID(name); - if (domain != null) { + if (domain != null) return domain; - } + // Didn't work. Guess it! logger.warn("Warning, could not find SCOP domain: " + name); @@ -662,7 +652,7 @@ public static ScopDomain guessScopDomain(String name, ScopDatabase scopDB) { ScopDomain bestMatch = match.next(); if(logger.isWarnEnabled()) { StringBuilder warnMsg = new StringBuilder(); - warnMsg.append("Trying domain " + bestMatch.getScopId() + "."); + warnMsg.append("Trying domain ").append(bestMatch.getScopId()).append("."); if (match.hasNext()) { warnMsg.append(" Other possibilities: "); while (match.hasNext()) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/events/AlignmentProgressListener.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/events/AlignmentProgressListener.java index b8c898d251..0abbf6728c 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/events/AlignmentProgressListener.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/events/AlignmentProgressListener.java @@ -22,17 +22,17 @@ public interface AlignmentProgressListener { - public void alignmentStarted(String name1, String name2); + void alignmentStarted(String name1, String name2); - public void alignmentEnded(); + void alignmentEnded(); - public void logStatus(String message); + void logStatus(String message); - public void downloadingStructures(String name); + void downloadingStructures(String name); - public void requestingAlignmentsFromServer(int nrAlignments); + void requestingAlignmentsFromServer(int nrAlignments); - public void sentResultsToServer(int nrAlignments,String serverMessage); + void sentResultsToServer(int nrAlignments, String serverMessage); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/FatCat.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/FatCat.java index 6a5aa6dc93..00572209e8 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/FatCat.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/FatCat.java @@ -32,7 +32,6 @@ import org.biojava.nbio.structure.align.fatcat.calc.FatCatAligner; import org.biojava.nbio.structure.align.fatcat.calc.FatCatParameters; import org.biojava.nbio.structure.align.model.AFPChain; -import org.biojava.nbio.structure.align.util.ConfigurationException; public class FatCat @@ -60,7 +59,7 @@ public class FatCat * * @param argv */ - public static void main(String[] argv) throws ConfigurationException { + public static void main(String[] argv) { FatCatUserArgumentProcessor processor = new FatCatUserArgumentProcessor(); processor.process(argv); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/FatCatUserArgumentProcessor.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/FatCatUserArgumentProcessor.java index 69a25b9283..43272df12a 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/FatCatUserArgumentProcessor.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/FatCatUserArgumentProcessor.java @@ -34,9 +34,9 @@ public class FatCatUserArgumentProcessor extends AbstractUserArgumentProcessor { - Logger logger = LoggerFactory.getLogger(FatCatUserArgumentProcessor.class); + final Logger logger = LoggerFactory.getLogger(FatCatUserArgumentProcessor.class); - protected class FatCatStartupParams extends StartupParameters { + protected static class FatCatStartupParams extends StartupParameters { int fragLen; Double rmsdCut; double disCut; @@ -91,7 +91,7 @@ protected StartupParameters getStartupParametersInstance() { @Override public StructureAlignment getAlgorithm() { - StructureAlignment algorithm = null; + StructureAlignment algorithm; if ( params != null && ((FatCatStartupParams)params).isFlexible()) { logger.info("running flexible alignment"); algorithm = new FatCatFlexible(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/AFPCalculator.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/AFPCalculator.java index 3fd3400800..ed93796c66 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/AFPCalculator.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/AFPCalculator.java @@ -26,7 +26,9 @@ package org.biojava.nbio.structure.align.fatcat.calc; -import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.Atom; +import org.biojava.nbio.structure.AtomImpl; +import org.biojava.nbio.structure.Calc; import org.biojava.nbio.structure.align.model.AFP; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.geometry.SuperPositions; @@ -45,11 +47,11 @@ public class AFPCalculator public static final boolean debug = FatCatAligner.debug; - public static final void extractAFPChains(FatCatParameters params, AFPChain afpChain,Atom[] ca1,Atom[] ca2) throws StructureException { + public static void extractAFPChains(FatCatParameters params, AFPChain afpChain, Atom[] ca1, Atom[] ca2) { - List afpSet = new ArrayList(); + List afpSet = new ArrayList<>(); afpChain.setAfpSet(afpSet); if ( debug ) @@ -61,7 +63,7 @@ public static final void extractAFPChains(FatCatParameters params, AFPChain afp @SuppressWarnings("unused") int n0, n, n1, n2; double filter1; - double rmsd = 0; + double rmsd; Matrix r = new Matrix(3,3); Atom t = new AtomImpl(); @@ -78,15 +80,12 @@ public static final void extractAFPChains(FatCatParameters params, AFPChain afp int add = sparse + 1; //if add > 1, use sparse sampling n0 = n = n1 = n2 = 0; - int minLen = 0; + int minLen; int prot1Length = ca1.length; int prot2Length = ca2.length; - if(prot1Length < prot2Length) - minLen = prot1Length; - else - minLen = prot2Length; + minLen = Math.min(prot1Length, prot2Length); afpChain.setMinLen(minLen); afpChain.setBlockResList(new int[maxTra+1][2][minLen]); @@ -147,10 +146,10 @@ public static final void extractAFPChains(FatCatParameters params, AFPChain afp * @param p2e * @return */ - private static final double getEnd2EndDistance(Atom[] ca1, Atom[] ca2, int p1b, int p1e, int p2b, int p2e) + private static double getEnd2EndDistance(Atom[] ca1, Atom[] ca2, int p1b, int p1e, int p2b, int p2e) { - double min = 99; + double min; double dist1 = Calc.getDistance(ca1[p1b], ca1[p1e]); double dist2 = Calc.getDistance(ca2[p2b], ca2[p2e]); min = dist1 - dist2; @@ -167,10 +166,10 @@ private static final double getEnd2EndDistance(Atom[] ca1, Atom[] ca2, int p1b, * @return */ - private static final boolean filterTerminal(Atom[] ca1, Atom[] ca2, int p1b, int p1e, int p2b, int p2e, int fragLen, int minLen) + private static boolean filterTerminal(Atom[] ca1, Atom[] ca2, int p1b, int p1e, int p2b, int p2e, int fragLen, int minLen) { - int d1 = (p1b < p2b)?p1b:p2b; - int d2 = (ca1.length - p1e) < (ca2.length - p2e)?(ca1.length - p1e):(ca2.length - p2e); + int d1 = Math.min(p1b, p2b); + int d2 = Math.min((ca1.length - p1e), (ca2.length - p2e)); int d3 = d1 + d2 + fragLen; //maximum alignment length from current AFP @@ -181,8 +180,8 @@ private static final boolean filterTerminal(Atom[] ca1, Atom[] ca2, int p1b, in } - private static final double getRmsd(Atom[] ca1, Atom[] ca2, int fragLen, - int p1, int p2, Matrix m, Atom t) throws StructureException { + private static double getRmsd(Atom[] ca1, Atom[] ca2, int fragLen, + int p1, int p2, Matrix m, Atom t) { double rmsd = 99.9; @@ -211,8 +210,8 @@ private static final double getRmsd(Atom[] ca1, Atom[] ca2, int fragLen, * @param clone: returns a copy of the atom (in case the coordinate get manipulated...) * @return an Atom[] array */ - private static final Atom[] getFragment(Atom[] caall, int pos, int fragmentLength , - boolean clone){ + private static Atom[] getFragment(Atom[] caall, int pos, int fragmentLength , + boolean clone){ if ( pos+fragmentLength > caall.length) return null; @@ -235,7 +234,7 @@ private static final Atom[] getFragment(Atom[] caall, int pos, int fragmentLengt * Assign score to each AFP */ - private static final double scoreAfp(AFP afp, double badRmsd, double fragScore) + private static double scoreAfp(AFP afp, double badRmsd, double fragScore) { //longer AFP with low rmsd is better double s, w; @@ -249,7 +248,7 @@ private static final double scoreAfp(AFP afp, double badRmsd, double fragScore) //------------------------------------------------------------------ //Sort the AFPs in increase of their diagonals(i,j) //------------------------------------------------------------------ - public static final void sortAfps(AFPChain afpChain, Atom[] ca1, Atom[] ca2) + public static void sortAfps(AFPChain afpChain, Atom[] ca1, Atom[] ca2) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/AFPChainer.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/AFPChainer.java index 0f9c2254d9..764d260f23 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/AFPChainer.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/AFPChainer.java @@ -28,16 +28,14 @@ import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Calc; -import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.AFPTwister; import org.biojava.nbio.structure.align.model.AFP; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.geometry.SuperPositions; import org.biojava.nbio.structure.jama.Matrix; -import java.util.List; - import javax.vecmath.Matrix4d; +import java.util.List; /** a class to chain AFPs to an alignment * @@ -94,7 +92,7 @@ public static void doChainAfp(FatCatParameters params, AFPChain afpChain,Atom[] //transformation, calculated at DoChainAfp, be used in List extraction //forward: calculate the score matrix - boolean isConnected = false; + boolean isConnected; int i, j, j0, n; double stmp; @@ -247,14 +245,14 @@ private static int getCompatibleAfps(int afp, int[] list, FatCatParameters para a3 = i1 - f; a2 = a3 - c; a1 = i1 - G; - a2 = a2>0?a2:0; - a1 = a1>0?a1:0; + a2 = Math.max(a2, 0); + a1 = Math.max(a1, 0); b3 = j1 - f; b2 = b3 - c; b1 = j1 - G; - b2 = (b2 > 0)?b2:0; - b1 = (b1 > 0)?b1:0; + b2 = Math.max(b2, 0); + b1 = Math.max(b1, 0); int[][] afpAftIndex = afpChain.getAfpAftIndex(); int[][] afpBefIndex = afpChain.getAfpBefIndex(); @@ -309,8 +307,8 @@ public static boolean afpPairConn(int afp1, int afp2, FatCatParameters params, { - Double conn = afpChain.getConn(); - Double dvar = afpChain.getDVar(); + double conn; + double dvar; double misScore = params.getMisScore(); double maxPenalty = params.getMaxPenalty(); @@ -383,7 +381,7 @@ private static int calcMismatch(AFP afp1, AFP afp2) { int l1 = afp1.getP1() - afp2.getP1() - afp2.getFragLen(); int l2 = afp1.getP2() - afp2.getP2() - afp2.getFragLen(); - return (l1 > l2?l2:l1); + return (Math.min(l1, l2)); } /** @@ -446,7 +444,7 @@ private static void traceBack(int[] pre, int currafp0, int twist, FatCatParamete int minLen = afpChain.getMinLen(); List afpSet = afpChain.getAfpSet(); - int afpChainLen = 0; + int afpChainLen; //trace-back from currafp (maxsco) int[] afpchain = new int[minLen]; @@ -611,7 +609,7 @@ private static void traceBack(int[] pre, int currafp0, int twist, FatCatParamete afpChain.setBlockSize(blockSize); afpChain.setBlockRmsd(blockRmsd); - int blockNum = afpChain.getBlockNum(); + int blockNum; blockNum = ++bk; if ( debug) System.err.println("AFPChainser setBlockNUm:" + blockNum); @@ -698,7 +696,7 @@ private static double getRmsd(int focusResn, int[] focusRes1, int[] focusRes2, A * @param catmp1 * @return */ - private static double getRmsd(Atom[] catmp1, Atom[] catmp2) throws StructureException{ + private static double getRmsd(Atom[] catmp1, Atom[] catmp2) { Matrix4d trans = SuperPositions.superpose(Calc.atomsToPoints(catmp1), Calc.atomsToPoints(catmp2)); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/AFPOptimizer.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/AFPOptimizer.java index 9752c4cc7f..a77e8ad6cf 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/AFPOptimizer.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/AFPOptimizer.java @@ -27,7 +27,6 @@ package org.biojava.nbio.structure.align.fatcat.calc; import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.model.AFP; import org.biojava.nbio.structure.align.model.AFPChain; @@ -41,8 +40,7 @@ public class AFPOptimizer /** * optimize the alignment by dynamic programming */ - public static void optimizeAln(FatCatParameters params, AFPChain afpChain,Atom[] ca1, Atom[] ca2) throws StructureException - { + public static void optimizeAln(FatCatParameters params, AFPChain afpChain,Atom[] ca1, Atom[] ca2) { int minLen = afpChain.getMinLen(); int fragLen = params.getFragLen(); @@ -72,7 +70,7 @@ public static void optimizeAln(FatCatParameters params, AFPChain afpChain,Atom[] List afpSet = afpChain.getAfpSet(); - int optLength = afpChain.getOptLength(); + int optLength; int[] afpChainList = afpChain.getAfpChainList(); int[] block2Afp = afpChain.getBlock2Afp(); int[] blockSize = afpChain.getBlockSize(); @@ -241,7 +239,7 @@ public static void updateScore(FatCatParameters params, AFPChain afpChain) blockScore[i] += afpSet.get(bknow).getScore() + conn; g1 = afpSet.get(bknow).getP1() - afpSet.get(bkold).getP1() - afpSet.get(bkold).getFragLen(); g2 = afpSet.get(bknow).getP2() - afpSet.get(bkold).getP2() - afpSet.get(bkold).getFragLen(); - blockGap[i] += (g1 > g2)?g1:g2; + blockGap[i] += Math.max(g1, g2); } bkold = bknow; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/AFPPostProcessor.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/AFPPostProcessor.java index 5f940ec6a1..a4242e5c85 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/AFPPostProcessor.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/AFPPostProcessor.java @@ -203,7 +203,7 @@ private static void deleteBlock(FatCatParameters params, AFPChain afpChain,Atom[ e2 = ca2.length; } if(blockSize[i] > 1) continue; - len = (e1 - b1) < (e2 - b2)?(e1 - b1):(e2 - b2); + len = Math.min((e1 - b1), (e2 - b2)); //if(i == blockNum - 1) blockNum --; if(len < 2 * fragLen) { for(j = i; j < blockNum - 1; j ++) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/FatCatParameters.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/FatCatParameters.java index 760b196bd5..bee2eb4df5 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/FatCatParameters.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/FatCatParameters.java @@ -366,7 +366,7 @@ public void setSparse(int sparse) @Override public List getUserConfigHelp() { - List params = new ArrayList(); + List params = new ArrayList<>(); String fragLen = "The length of the fragments."; String rmsdCutHelp = "The RMSD cutoff to be used during AFP detection."; String disCutHelp = "The distance cutoff used when calculate the connectivity of AFP pairs"; @@ -382,7 +382,7 @@ public List getUserConfigHelp() { @Override public List getUserConfigParameterNames() { - List params = new ArrayList(); + List params = new ArrayList<>(); params.add("Fragment Length"); params.add("RMSD Cutoff"); params.add("AFP Distance Cutoff"); @@ -393,7 +393,7 @@ public List getUserConfigParameterNames() { @Override public List getUserConfigParameters() { - List params = new ArrayList(); + List params = new ArrayList<>(); params.add("FragLen"); params.add("RmsdCut"); params.add("DisCut"); @@ -406,7 +406,7 @@ public List getUserConfigParameters() { @SuppressWarnings({ "rawtypes" }) public List getUserConfigTypes() { - List params = new ArrayList(); + List params = new ArrayList<>(); params.add(Integer.class); params.add(Double.class); params.add(Double.class); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/SigEva.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/SigEva.java index d111e55fd6..b16477c96b 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/SigEva.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/SigEva.java @@ -169,9 +169,9 @@ private double calSigAll(int twist, int sparse, int len1, int len2, double score else getPara(5, len); //flexible-FATCAT } else if(sparse == 3) { //sparse sampling = 3 - if(twist == 0) getPara(8, len); //rigid-FATCAT - else getPara(8, len); //flexible-FATCAT - } + //flexible-FATCAT + getPara(8, len); //rigid-FATCAT + } else if(sparse == 1) { //sparse sampling = 1 if(twist == 0) getPara(6, len); //rigid-FATCAT else getPara(7, len); //flexible-FATCAT diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/StructureAlignmentOptimizer.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/StructureAlignmentOptimizer.java index 89685fcbbd..5874fe8acb 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/StructureAlignmentOptimizer.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/fatcat/calc/StructureAlignmentOptimizer.java @@ -27,11 +27,13 @@ package org.biojava.nbio.structure.align.fatcat.calc; -import javax.vecmath.Matrix4d; - -import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.Atom; +import org.biojava.nbio.structure.Calc; +import org.biojava.nbio.structure.Group; import org.biojava.nbio.structure.geometry.SuperPositions; +import javax.vecmath.Matrix4d; + public class StructureAlignmentOptimizer @@ -39,13 +41,13 @@ public class StructureAlignmentOptimizer //private static final boolean showAlig = false; - int pro1Len; - int pro2Len; - int maxLen; - Atom[] cod1; - Atom[] cod2; + final int pro1Len; + final int pro2Len; + final int maxLen; + final Atom[] cod1; + final Atom[] cod2; - int[][] equSet; + final int[][] equSet; int equLen; int equLen0; double[][]sij; @@ -76,7 +78,7 @@ public class StructureAlignmentOptimizer */ public StructureAlignmentOptimizer(int b1, int end1, Atom[] c1, int b2, int end2, Atom[] c2, - int iniLen, int[][] iniSet) throws StructureException{ + int iniLen, int[][] iniSet) { //System.err.println("optimizing range:" + b1 + "-" + end1 + "("+ (end1-b1) + ") b2: " + b2 + "-" + end2+ "("+ (end2-b2) + ") iniLen " + iniLen); //System.out.println("ca1: " + c1.length + " ca2: " + c2.length); @@ -111,7 +113,7 @@ public StructureAlignmentOptimizer(int b1, int end1, Atom[] c1, int b2, int end2 //initial equivalent sets - maxLen = (len1 < len2)?len1:len2; + maxLen = Math.min(len1, len2); equSet = new int[2][maxLen]; for(int i = 0; i < iniLen; i ++) { @@ -119,7 +121,7 @@ public StructureAlignmentOptimizer(int b1, int end1, Atom[] c1, int b2, int end2 equSet[0][i] = iniSet[0][i]; equSet[1][i] = iniSet[1][i]; if(iniSet[0][i] > len1 || iniSet[1][i] > len2) { - throw new RuntimeException(String.format("StructureAlignmentOptimizer: focus exceeds the protein 1 or 2 length!")); + throw new RuntimeException("StructureAlignmentOptimizer: focus exceeds the protein 1 or 2 length!"); } } @@ -194,9 +196,8 @@ public StructureAlignmentOptimizer(int b1, int end1, Atom[] c1, int b2, int end2 /** run the optimization * * @param maxi maximum nr. of iterations - * @throws StructureException - */ - public void runOptimization(int maxi) throws StructureException{ + */ + public void runOptimization(int maxi) { superimposeBySet(); if ( debug) System.err.println(" initial rmsd " + rmsd); @@ -232,9 +233,7 @@ private void setParameters() /** * superimpose two structures according to the equivalent residues */ - private void superimposeBySet () - throws StructureException - { + private void superimposeBySet () { //extract the coordinations of equivalent residues Atom[] tmp1 = new Atom[equLen]; @@ -284,13 +283,12 @@ private void superimposeBySet () } - private void optimize(int maxi) throws StructureException - { + private void optimize(int maxi) { long optStart = System.currentTimeMillis(); if ( debug) System.out.println("Optimizing up to " + maxi + " iterations.. "); - boolean ifstop = true;; - int i, alnLen; + boolean ifstop; + int i, alnLen; alnLen = 0; int[][] alnList = new int[2][maxLen]; @@ -334,8 +332,7 @@ private void optimize(int maxi) throws StructureException // Sij = Dc^2 - Dij^2 if Dij <= Dc // 0 else //-------------------------------------------------------------------------------------------------------- - private void calMatrix() throws StructureException - { + private void calMatrix() { int i, j; double dis; for(i = 0; i < pro1Len; i ++) { @@ -356,9 +353,7 @@ private void calMatrix() throws StructureException * the equivalent residues: residues where Dij <= Dc and i,j is an aligned pair * use the previous superimposing */ - private boolean defineEquPos(int alnLen, int[][] alnList) - throws StructureException - { + private boolean defineEquPos(int alnLen, int[][] alnList) { int i, r1, r2; int equLenOld = equLen; int[][] equSetOld = new int[2][equLenOld]; @@ -388,7 +383,7 @@ private boolean defineEquPos(int alnLen, int[][] alnList) //if (debug) // System.out.println(String.format(" OPT: new equLen %d rmsd %f", equLen, rmsd)); - boolean ifstop = false; + boolean ifstop; // if (debug) { // System.out.print(" OPT: rmsd diff: " + Math.abs(rmsd - rmsdOld) + " equLens: " + equLenOld + ":"+ equLen); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/helper/AligMatEl.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/helper/AligMatEl.java index 2f8215292c..db903447f4 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/helper/AligMatEl.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/helper/AligMatEl.java @@ -22,6 +22,8 @@ */ package org.biojava.nbio.structure.align.helper; +import java.util.Objects; + public class AligMatEl extends IndexPair{ @@ -36,7 +38,7 @@ public class AligMatEl public AligMatEl(){ - super(); + super((short)-1, (short)-1); value = -1; contig = -1; } @@ -55,10 +57,25 @@ public void setValue(int value) { this.value = value; } - @Override + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof AligMatEl)) return false; + if (!super.equals(o)) return false; + AligMatEl aligMatEl = (AligMatEl) o; + return value == aligMatEl.value && + contig == aligMatEl.contig; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), value, contig); + } + + @Override public String toString(){ String ret = "AligMatEl val:" + value + " contig:" + contig + - " trackrow:" + getRow() + " trackcol:" + getCol(); + " trackrow:" + row() + " trackcol:" + col(); return ret; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/helper/AlignUtils.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/helper/AlignUtils.java index eb90288595..48a05d122a 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/helper/AlignUtils.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/helper/AlignUtils.java @@ -95,9 +95,7 @@ public static Atom[] getFragmentNoClone(Atom[] caall, int pos, int fragmentLengt Atom[] tmp = new Atom[fragmentLength]; - for (int i=0;i< fragmentLength;i++){ - tmp[i] = caall[i+pos]; - } + if (fragmentLength >= 0) System.arraycopy(caall, 0 + pos, tmp, 0, fragmentLength); return tmp; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/helper/IndexPair.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/helper/IndexPair.java index ce8fd47e5a..e85b0c5803 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/helper/IndexPair.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/helper/IndexPair.java @@ -23,42 +23,61 @@ package org.biojava.nbio.structure.align.helper; import java.io.Serializable; +import java.util.Objects; public class IndexPair implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1832393751152650420L; - short row; - short col; + /** + * + */ + private static final long serialVersionUID = 1832393751152650420L; + private short row; + private short col; - public IndexPair(){ - row = -1; - col = -1; + public IndexPair(int row, int col) { + this.row = (short)row; + this.col = (short)col; + if (this.row!=row || this.col!=col) + throw new ArithmeticException(); } - public IndexPair(short row, short col){ - this.row = row; - this.col=col; + public IndexPair(short row, short col) { + this.row = row; + this.col = col; + } - } - public short getCol() { - return col; - } - public void setCol(short col) { - this.col = col; - } - public short getRow() { - return row; - } - public void setRow(short row) { - this.row = row; - } + public short col() { + return col; + } - @Override -public String toString(){ - return "["+row + " " + col+"]"; - } + public void setCol(short col) { + this.col = col; + } + + public short row() { + return row; + } + + public void setRow(short row) { + this.row = row; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof IndexPair)) return false; + IndexPair indexPair = (IndexPair) o; + return row == indexPair.row && col == indexPair.col; + } + + @Override + public int hashCode() { + return Objects.hash(row, col); + } + + @Override + public String toString() { + return "[" + row + " " + col + "]"; + } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/helper/JointFragments.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/helper/JointFragments.java index 862e7d8d50..dcf65c11c9 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/helper/JointFragments.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/helper/JointFragments.java @@ -23,8 +23,6 @@ package org.biojava.nbio.structure.align.helper; import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; import java.util.List; @@ -38,9 +36,9 @@ public class JointFragments { double rms; - List idxlist; + final List idxlist; public JointFragments(){ - idxlist = new ArrayList(); + idxlist = new ArrayList<>(); rms = 999; } @@ -49,11 +47,7 @@ public JointFragments(){ * Each int[] stores the residue numbers of several equivalent residues. */ public void setIdxlist(List idxs) { - Iterator iter = idxs.iterator(); - while (iter.hasNext()){ - int[] e = iter.next(); - idxlist.add(e); - } + idxlist.addAll(idxs); } @@ -77,16 +71,14 @@ public void add(int p1, int p2,int start,int end){ int[] e = new int[] {p1+k,p2+k}; // check if already known ... - Iterator iter = idxlist.iterator(); - while (iter.hasNext()){ - int[] kno = iter.next(); - if ((kno[0] == e[0]) && ( kno[1] == e[1])){ + for (int[] kno : idxlist) { + if ((kno[0] == e[0]) && (kno[1] == e[1])) { System.err.println("already known index pair, not adding a 2nd time." + e[0] + " " + e[1]); return; } } idxlist.add(e); - Collections.sort(idxlist, new IdxComparator()); + idxlist.sort(new IdxComparator()); } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/model/AFP.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/model/AFP.java index 7156d25c76..5cf9ca4b11 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/model/AFP.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/model/AFP.java @@ -56,7 +56,7 @@ public String toString(){ // Bioinformatics, 24, pp. 872-873 (2008) - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); buf.append("AFP: p1:"); buf.append(p1); buf.append(" p2: "); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/model/AFPChain.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/model/AFPChain.java index 38844a0963..5448091f84 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/model/AFPChain.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/model/AFPChain.java @@ -179,7 +179,7 @@ public AFPChain(AFPChain o) { this.alignScoreUpdate = o.alignScoreUpdate; this.afpChainTwiNum = o.afpChainTwiNum; this.minLen = o.minLen; - this.afpSet = new ArrayList(o.afpSet); + this.afpSet = new ArrayList<>(o.afpSet); this.afpIndex = o.afpIndex == null? null: o.afpIndex.clone(); this.afpAftIndex = o.afpAftIndex == null? null: o.afpAftIndex.clone(); this.afpBefIndex = o.afpBefIndex == null? null: o.afpBefIndex.clone(); @@ -231,8 +231,8 @@ public AFPChain(AFPChain o) { this.ca1Length = o.ca1Length; this.ca2Length = o.ca2Length; this.maxTra = o.maxTra; - this.conn = new Double(o.conn); - this.dvar = new Double(o.dvar); + this.conn = o.conn; + this.dvar = o.dvar; this.probability = o.probability; this.identity = o.identity; this.similarity = o.similarity; @@ -358,7 +358,7 @@ public String toString(){ //int lB = ca2Length; //int distance = lA + lB - 2 * getNrEQR(); - StringBuffer str = new StringBuffer(""); + StringBuilder str = new StringBuilder(); str.append("EQR:"); str.append(getNrEQR()); @@ -400,13 +400,10 @@ public String toString(){ public boolean isSignificantResult(){ if ( algorithmName.equalsIgnoreCase(CeMain.algorithmName) || algorithmName.equalsIgnoreCase(CeSideChainMain.algorithmName)){ - if (probability >= 3.5) - return true; + return probability >= 3.5; } else { - if (probability < 0.01) - return true; + return probability < 0.01; } - return false; } @@ -439,15 +436,15 @@ private void init(){ blockResSize = new int[maxTra+1]; - afpSet = new ArrayList(); + afpSet = new ArrayList<>(); totalLenIni = totalLenOpt = 0; totalRmsdIni = totalRmsdOpt = 0.0; afpChainTwiNum = 0; alignScore = 0; alignScoreUpdate = 0; - conn = new Double(0); - dvar = new Double(0); + conn = (double) 0; + dvar = (double) 0; calculationTime = 0; similarity = -1; @@ -1392,8 +1389,7 @@ public int hashCode() { */ @Override public boolean equals(Object obj) { - if (this == obj) - return true; + if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) @@ -1409,9 +1405,7 @@ public boolean equals(Object obj) { return false; if (!Arrays.equals(optLen, other.optLen)) return false; - if (optLength != other.optLength) - return false; - return true; + return optLength == other.optLength; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/model/AfpChainWriter.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/model/AfpChainWriter.java index ce527bc586..ace0f58b00 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/model/AfpChainWriter.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/model/AfpChainWriter.java @@ -45,7 +45,7 @@ public class AfpChainWriter public static final String newline = System.getProperty("line.separator"); - private static int LINELENGTH = 70; + private static final int LINELENGTH = 70; public static String toFatCat(AFPChain afpChain, Atom[] ca1, Atom[] ca2) { @@ -248,8 +248,7 @@ public static String toFatCatCore( //System.out.println(alnseq1.length + " " + alnseq1.toString()); while((alnLength - t) > 0) { - if(alnLength - t > linelen) len = linelen; - else len = alnLength - t; + len = Math.min(alnLength - t, linelen); if ( ap >= ca1.length) break; @@ -295,12 +294,11 @@ public static String toFatCatCore( if ( showAlignmentBlock && block > -1 ) { a += "" + c1 + ""; b += "" + c2 + ""; - c += "" + cl + ""; } else { a += getPrefix(c1, c2, 0, block, false).toString() + c1 + ""; b += getPrefix(c1, c2, 1, block, false).toString() + c2 + ""; - c += "" + cl + ""; } + c += "" + cl + ""; } else if ( c1 != '-' && c2 != '-') { @@ -330,10 +328,7 @@ public static String toFatCatCore( } txt.append(newline); - if ( longHeader ) - txt.append(String.format("%14s", " ")); - else - txt.append(String.format("%14s", " ")); + txt.append(String.format("%14s", " ")); if ( longHeader ) { for(k = 10; k <= len; k += 10) @@ -589,7 +584,7 @@ public static String toPrettyAlignment(AFPChain afpChain, Atom[] ca1, Atom[] ca2 formatStartingText(p1,p2,header1,header2,footer1,footer2,ca1,ca2); } else { // check for gapped region - int lmax = (p1 - p1b - 1)>(p2 - p2b - 1)?(p1 - p1b - 1):(p2 - p2b - 1); + int lmax = Math.max((p1 - p1b - 1), (p2 - p2b - 1)); for(k = 0; k < lmax; k ++) { @@ -715,15 +710,13 @@ private static void formatGappedRegion(Atom[] ca1, Atom[] ca2, StringBuffer txt, //alnseq1[len] = '-'; if ( formatHTML){ alnseq1.append("-"); - header1.append(" "); - header2.append(" "); } else { alnseq1.append('-'); - header1.append(" "); - header2.append(" "); } + header1.append(" "); + header2.append(" "); } else { @@ -742,13 +735,11 @@ private static void formatGappedRegion(Atom[] ca1, Atom[] ca2, StringBuffer txt, //alnseq2[len] = '-'; if ( formatHTML){ alnseq2.append("-"); - footer1.append(" "); - footer2.append(" "); } else { alnseq2.append('-'); - footer1.append(" "); - footer2.append(" "); } + footer1.append(" "); + footer2.append(" "); } else { @@ -833,10 +824,8 @@ private static void formatPosition(int pos1, Atom[] ca, int len, StringWriter he //System.out.println(len + " p1:" + tmp + " = " + pos1 + " " + " " + display + " " + ignoreH1); if ( ! ignoreH1) { header1.append(String.format("%-13s",display )); - header2.append("|"); - } else { - header2.append("|"); } + header2.append("|"); } else if ( hasInsertionCode){ Character insCode = g.getResidueNumber().getInsCode(); @@ -991,22 +980,16 @@ private static boolean doLenCheck(int len, StringBuffer txt, StringWriter header alnsymb.getBuffer().replace(0, lens, ""); - - header1.getBuffer().replace(0, LINELENGTH, ""); - header2.getBuffer().replace(0, LINELENGTH , ""); - footer1.getBuffer().replace(0, LINELENGTH, ""); - footer2.getBuffer().replace(0, LINELENGTH, ""); - block.getBuffer().replace(0, LINELENGTH, ""); } else { alnseq1.getBuffer().replace(0, LINELENGTH, ""); alnseq2.getBuffer().replace(0, LINELENGTH, ""); alnsymb.getBuffer().replace(0, LINELENGTH, ""); - header1.getBuffer().replace(0, LINELENGTH, ""); - header2.getBuffer().replace(0, LINELENGTH , ""); - footer1.getBuffer().replace(0, LINELENGTH, ""); - footer2.getBuffer().replace(0, LINELENGTH, ""); - block.getBuffer().replace(0, LINELENGTH, ""); } + header1.getBuffer().replace(0, LINELENGTH, ""); + header2.getBuffer().replace(0, LINELENGTH , ""); + footer1.getBuffer().replace(0, LINELENGTH, ""); + footer2.getBuffer().replace(0, LINELENGTH, ""); + block.getBuffer().replace(0, LINELENGTH, ""); StringBuffer buf = header1.getBuffer(); for ( int i=0;i 0) { - if(alnLength - t > linelen) len = linelen; - else len = alnLength - t; + len = Math.min(alnLength - t, linelen); //System.err.println("t,len:"+t+":"+len); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/AbstractScoresCache.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/AbstractScoresCache.java index b1ae2bf543..72b69ba7d1 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/AbstractScoresCache.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/AbstractScoresCache.java @@ -35,7 +35,7 @@ */ public abstract class AbstractScoresCache implements ScoresCache { - private Map scores = null; + private Map scores; protected AbstractScoresCache() { scores = null; @@ -48,7 +48,7 @@ protected AbstractScoresCache(AbstractScoresCache cache) { @Override public void putScore(String property, Double score) { if(scores == null) { - scores = new TreeMap(); + scores = new TreeMap<>(); } scores.put(property, score); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/Block.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/Block.java index 8e79653de6..e7be69a09f 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/Block.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/Block.java @@ -45,7 +45,7 @@ public interface Block extends ScoresCache { * * @return Block identical copy of this object. */ - public Block clone(); + Block clone(); /** * Set the back-reference to its parent BlockSet. @@ -54,7 +54,7 @@ public interface Block extends ScoresCache { * the parent BlockSet. * @see #getBlockSet() */ - public void setBlockSet(BlockSet parent); + void setBlockSet(BlockSet parent); /** * Returns the parent BlockSet of the Block. Returns null if there is no @@ -63,7 +63,7 @@ public interface Block extends ScoresCache { * @return BlockSet the parent BlockSet of the Block, or null. * @see #setBlockSet(BlockSet) */ - public BlockSet getBlockSet(); + BlockSet getBlockSet(); /** * Returns the double List containing the aligned residues for each @@ -74,7 +74,7 @@ public interface Block extends ScoresCache { * @return List a double List of aligned residues for each structure. * @see #setAlignRes() */ - public List> getAlignRes(); + List> getAlignRes(); /** * Set the double List containing the aligned residues for each structure. @@ -83,7 +83,7 @@ public interface Block extends ScoresCache { * a double List of Integers with the aligned residues. * @see #getAlignRes() */ - public void setAlignRes(List> alignRes); + void setAlignRes(List> alignRes); /** * Returns the total number of aligned positions (columns) in the Block. @@ -92,7 +92,7 @@ public interface Block extends ScoresCache { * @see #getCoreLength(); * @see #size() */ - public int length(); + int length(); /** * Returns the number of aligned structures (rows) in the Block. @@ -101,7 +101,7 @@ public interface Block extends ScoresCache { * @see #length() * @see #getCoreLength() */ - public int size(); + int size(); /** * Returns the number of aligned positions (columns) without gaps in the @@ -112,7 +112,7 @@ public interface Block extends ScoresCache { * @see #length() * @see #size() */ - public int getCoreLength(); + int getCoreLength(); /** * Returns the number of non null positions (residues) of each structure in @@ -120,7 +120,7 @@ public interface Block extends ScoresCache { * * @return List of residue counts for each structure */ - public List getAlignResCounts(); + List getAlignResCounts(); /** * Calculates and returns the first position of the specified structure in @@ -132,7 +132,7 @@ public interface Block extends ScoresCache { * * @return the first non null aligned position of the structure */ - public int getStartIndex(int str); + int getStartIndex(int str); /** * Calculates and returns the first residue of the specified structure in @@ -144,7 +144,7 @@ public interface Block extends ScoresCache { * * @return the first non null aligned residue of the structure */ - public int getStartResidue(int str); + int getStartResidue(int str); /** * Calculates and returns the last position of the specified structure in @@ -156,7 +156,7 @@ public interface Block extends ScoresCache { * * @return the last non null aligned position of the structure */ - public int getFinalIndex(int str); + int getFinalIndex(int str); /** * Calculates and returns the last residue of the specified structure in the @@ -168,12 +168,12 @@ public interface Block extends ScoresCache { * * @return the last non null aligned residue of the structure */ - public int getFinalResidue(int str); + int getFinalResidue(int str); /** * Clear scores and other properties which depend on the specific alignment. * This frees memory and ensures consistency of the cached variables. */ - public void clear(); + void clear(); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/BlockImpl.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/BlockImpl.java index 402aa5984e..4e0675f236 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/BlockImpl.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/BlockImpl.java @@ -20,12 +20,12 @@ */ package org.biojava.nbio.structure.align.multiple; +import org.biojava.nbio.structure.align.multiple.util.MultipleAlignmentTools; + import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import org.biojava.nbio.structure.align.multiple.util.MultipleAlignmentTools; - /** * General implementation of a {@link Block} that supports any type of * sequential alignment with gaps. @@ -80,9 +80,9 @@ public BlockImpl(BlockImpl b) { this.alignRes = null; if (b.alignRes != null) { // Make a deep copy of everything - alignRes = new ArrayList>(); + alignRes = new ArrayList<>(); for (int k = 0; k < b.size(); k++) { - alignRes.add(new ArrayList(b.alignRes.get(k))); + alignRes.add(new ArrayList<>(b.alignRes.get(k))); } } } @@ -188,7 +188,7 @@ public List getAlignResCounts() { if (alignResCounts != null) return alignResCounts; - alignResCounts = new ArrayList(size()); + alignResCounts = new ArrayList<>(size()); for (int s = 0; s < size(); s++) { int count = 0; for (int r = 0; r < length(); r++) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/BlockSet.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/BlockSet.java index 4fdf318c61..a6bf88dfcc 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/BlockSet.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/BlockSet.java @@ -20,9 +20,8 @@ */ package org.biojava.nbio.structure.align.multiple; -import java.util.List; - import javax.vecmath.Matrix4d; +import java.util.List; /** * A BlockSet is a Data Structure to store a flexible alignment part of a @@ -55,7 +54,7 @@ public interface BlockSet extends ScoresCache { * * @return BlockSet identical copy of this object. */ - public BlockSet clone(); + BlockSet clone(); /** * Returns the parent MultipleAlignment of the BlockSet. @@ -65,7 +64,7 @@ public interface BlockSet extends ScoresCache { * or null. * @see #setMultipleAlignment(MultipleAlignment) */ - public MultipleAlignment getMultipleAlignment(); + MultipleAlignment getMultipleAlignment(); /** * Set the back-reference to its parent MultipleAlignment. @@ -77,7 +76,7 @@ public interface BlockSet extends ScoresCache { * @param parent the parent MultipleAlignment. * @see #getMultipleAlignment() */ - public void setMultipleAlignment(MultipleAlignment parent); + void setMultipleAlignment(MultipleAlignment parent); /** * Returns the List of alignment Blocks of the BlockSet. @@ -86,7 +85,7 @@ public interface BlockSet extends ScoresCache { * * @see #setBlocks(List) */ - public List getBlocks(); + List getBlocks(); /** * Set the List of alignment Blocks of the BlockSet. @@ -96,7 +95,7 @@ public interface BlockSet extends ScoresCache { * @param blocks List of alignment Blocks. * @see #getBlocks() */ - public void setBlocks(List blocks); + void setBlocks(List blocks); /** * Returns a transformation matrix for each structure giving the @@ -104,7 +103,7 @@ public interface BlockSet extends ScoresCache { * * @return the 3D superimposition information of the alignment */ - public List getTransformations(); + List getTransformations(); /** * Set a new superposition for the structures. @@ -113,7 +112,7 @@ public interface BlockSet extends ScoresCache { * * @param matrices */ - public void setTransformations(List transformations); + void setTransformations(List transformations); /** * Returns the total number of aligned residues (columns) in the alignment: @@ -123,7 +122,7 @@ public interface BlockSet extends ScoresCache { * @see #getCoreLength() * @see #size() */ - public int length(); + int length(); /** * Returns the number of aligned residues (columns) without gaps in the @@ -133,7 +132,7 @@ public interface BlockSet extends ScoresCache { * @see #length() * @see #size() */ - public int getCoreLength(); + int getCoreLength(); /** * Returns the number of non null positions (residues) of each structure in @@ -141,7 +140,7 @@ public interface BlockSet extends ScoresCache { * * @return List of residue counts for each structure */ - public List getAlignResCounts(); + List getAlignResCounts(); /** * Returns the number of aligned structures in the BlockSet. @@ -150,7 +149,7 @@ public interface BlockSet extends ScoresCache { * @see #length() * @see #getCoreLength() */ - public int size(); + int size(); /** * Clear scores and other properties which depend on the specific @@ -158,5 +157,5 @@ public interface BlockSet extends ScoresCache { * variables.

    * Recursively clears the memeber Blocks. */ - public void clear(); + void clear(); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/BlockSetImpl.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/BlockSetImpl.java index c817853634..5246e8a3ad 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/BlockSetImpl.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/BlockSetImpl.java @@ -20,12 +20,11 @@ */ package org.biojava.nbio.structure.align.multiple; +import javax.vecmath.Matrix4d; import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import javax.vecmath.Matrix4d; - /** * A general implementation of a BlockSet to store a flexible part of a multiple * alignment. @@ -88,7 +87,7 @@ public BlockSetImpl(BlockSetImpl bs) { this.pose = null; if (bs.pose != null) { // Make a deep copy of everything - this.pose = new ArrayList(); + this.pose = new ArrayList<>(); for (Matrix4d trans : bs.pose) { Matrix4d newTrans = (Matrix4d) trans.clone(); pose.add(newTrans); @@ -98,7 +97,7 @@ public BlockSetImpl(BlockSetImpl bs) { blocks = null; if (bs.blocks != null) { // Make a deep copy of everything - this.blocks = new ArrayList(); + this.blocks = new ArrayList<>(); for (Block b : bs.blocks) { Block newB = b.clone(); newB.setBlockSet(this); @@ -143,7 +142,7 @@ public void setMultipleAlignment(MultipleAlignment parent) { @Override public List getBlocks() { if (blocks == null) - blocks = new ArrayList(); + blocks = new ArrayList<>(); return blocks; } @@ -232,7 +231,7 @@ public List getAlignResCounts() { if (alignResCounts != null) return alignResCounts; - alignResCounts = new ArrayList(size()); + alignResCounts = new ArrayList<>(size()); for (int s = 0; s < size(); s++) alignResCounts.add(0); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/MultipleAlignment.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/MultipleAlignment.java index 1b167caace..5a5157c51a 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/MultipleAlignment.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/MultipleAlignment.java @@ -20,11 +20,11 @@ */ package org.biojava.nbio.structure.align.multiple; -import java.util.List; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureIdentifier; +import java.util.List; + /** * A MultipleAlignment is a Data Structure to store the core information of a * multiple structure alignment, as a return type. @@ -53,7 +53,7 @@ public interface MultipleAlignment extends ScoresCache { * * @return MultipleAlignment identical copy of this object. */ - public MultipleAlignment clone(); + MultipleAlignment clone(); /** * Returns the parent Ensemble of the MultipleAlignment. Returns null if @@ -63,7 +63,7 @@ public interface MultipleAlignment extends ScoresCache { * BlockSet, or null. * @see #setEnsemble(MultipleAlignmentEnsemble) */ - public MultipleAlignmentEnsemble getEnsemble(); + MultipleAlignmentEnsemble getEnsemble(); /** * Set the back-reference to its parent Ensemble. @@ -76,7 +76,7 @@ public interface MultipleAlignment extends ScoresCache { * the parent MultipleAlignmentEnsemble. * @see #getEnsemble() */ - public void setEnsemble(MultipleAlignmentEnsemble parent); + void setEnsemble(MultipleAlignmentEnsemble parent); /** * Returns the BlockSet List of the multiple structure alignment. @@ -87,7 +87,7 @@ public interface MultipleAlignment extends ScoresCache { * @see #getBlocks() * @see #setBlockSets(List) */ - public List getBlockSets(); + List getBlockSets(); /** * Returns the BlockSet with the specified index of the MultipleAlignment. @@ -100,7 +100,7 @@ public interface MultipleAlignment extends ScoresCache { * @see #getBlocks() * @see #getBlockSets() */ - public BlockSet getBlockSet(int index); + BlockSet getBlockSet(int index); /** * Sets the List of BlockSet List of the specified alignment. @@ -109,7 +109,7 @@ public interface MultipleAlignment extends ScoresCache { * the List of BlockSets that describe the aligned residues. * @see #getBlockSets() */ - public void setBlockSets(List blockSets); + void setBlockSets(List blockSets); /** * Convenience method to get a List of all Blocks from all BlockSets. @@ -119,7 +119,7 @@ public interface MultipleAlignment extends ScoresCache { * @return List of Blocks * @see #getBlockSets() */ - public List getBlocks(); + List getBlocks(); /** * Returns the Block with the specified index of the MultipleAlignment. @@ -132,7 +132,7 @@ public interface MultipleAlignment extends ScoresCache { * @see #getBlocks() * @see #getBlockSets() */ - public Block getBlock(int index); + Block getBlock(int index); /** * Returns the array of Atoms for each structure from its parent Ensemble. @@ -142,7 +142,7 @@ public interface MultipleAlignment extends ScoresCache { * @return List of Atom arrays * @see #getEnsemble() */ - public List getAtomArrays(); + List getAtomArrays(); /** * Returns the StructureIdentifier associated with the structure index from @@ -152,7 +152,7 @@ public interface MultipleAlignment extends ScoresCache { * @return StructureIdentifier * @see #getEnsemble() */ - public StructureIdentifier getStructureIdentifier(int index); + StructureIdentifier getStructureIdentifier(int index); /** * Returns the number of aligned structures in the MultipleAlignment. @@ -161,7 +161,7 @@ public interface MultipleAlignment extends ScoresCache { * @see #length() * @see #getCoreLength() */ - public int size(); + int size(); /** * Returns the total number of aligned residues (columns) in the multiple @@ -171,7 +171,7 @@ public interface MultipleAlignment extends ScoresCache { * @see #getCoreLength() * @see #size() */ - public int length(); + int length(); /** * Returns the number of aligned residues (columns) without gaps in the @@ -181,7 +181,7 @@ public interface MultipleAlignment extends ScoresCache { * @see #length() * @see #size() */ - public int getCoreLength(); + int getCoreLength(); /** * Returns the number of non null positions (residues) of each structure in @@ -189,7 +189,7 @@ public interface MultipleAlignment extends ScoresCache { * * @return List of residue counts for each structure */ - public List getAlignResCounts(); + List getAlignResCounts(); /** * Returns the coverage of the alignment for each structure in the @@ -197,7 +197,7 @@ public interface MultipleAlignment extends ScoresCache { * * @return List coverage for each structure */ - public List getCoverages(); + List getCoverages(); /** * Clear scores and other properties which depend on the specific alignment. @@ -205,7 +205,7 @@ public interface MultipleAlignment extends ScoresCache { *

    * Recursively clears member BlockSets. */ - public void clear(); + void clear(); /** * Return a summary of the MultipleAlignment, containing the structures, the @@ -215,6 +215,6 @@ public interface MultipleAlignment extends ScoresCache { * @return String header summary of the MultipleAlignment */ @Override - public String toString(); + String toString(); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/MultipleAlignmentEnsemble.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/MultipleAlignmentEnsemble.java index d6358a825d..4e754b20d0 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/MultipleAlignmentEnsemble.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/MultipleAlignmentEnsemble.java @@ -20,12 +20,12 @@ */ package org.biojava.nbio.structure.align.multiple; -import java.util.List; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureIdentifier; import org.biojava.nbio.structure.jama.Matrix; +import java.util.List; + /** * A MultipleAlignmentEnsemble is a collection of {@link MultipleAlignment}s * that share the same structures (Atoms) and creation properties (algorithm, @@ -49,7 +49,7 @@ public interface MultipleAlignmentEnsemble extends ScoresCache { * * @return MultipleAlignmentEnsemble identical copy of this object. */ - public MultipleAlignmentEnsemble clone(); + MultipleAlignmentEnsemble clone(); /** * Returns the name of the multiple structure alignment algorithm that @@ -58,7 +58,7 @@ public interface MultipleAlignmentEnsemble extends ScoresCache { * @return String name of the algorithm. * @see #setAlgorithmName(String) */ - public String getAlgorithmName(); + String getAlgorithmName(); /** * Set the name of the multiple structure alignment algorithm that created @@ -67,7 +67,7 @@ public interface MultipleAlignmentEnsemble extends ScoresCache { * @param algorithmName name of the algorithm. * @see #getAlgorithmName() */ - public void setAlgorithmName(String algorithmName); + void setAlgorithmName(String algorithmName); /** * Returns the version of the algorithm used to generate the @@ -76,7 +76,7 @@ public interface MultipleAlignmentEnsemble extends ScoresCache { * @return String version of the algorithm. * @see #setVersion(String) */ - public String getVersion(); + String getVersion(); /** * Sets the version of the algorithm used to generate the MultipleAlignment @@ -85,7 +85,7 @@ public interface MultipleAlignmentEnsemble extends ScoresCache { * @param version the version of the algorithm. * @see #getVersion() */ - public void setVersion(String version); + void setVersion(String version); /** * Returns a List containing the names of the structures aligned @@ -98,7 +98,7 @@ public interface MultipleAlignmentEnsemble extends ScoresCache { * @see #setStructureIdentifiers(List) * @see #getAtomArrays() */ - public List getStructureIdentifiers(); + List getStructureIdentifiers(); /** * Set the List containing the names of the structures aligned @@ -109,7 +109,7 @@ public interface MultipleAlignmentEnsemble extends ScoresCache { * @see #getStructureIdentifiers() * @see #setAtomArrays(List) */ - public void setStructureIdentifiers(List structureIdentifiers); + void setStructureIdentifiers(List structureIdentifiers); /** * Get an array of representative atoms for each structure (CA atoms for @@ -126,7 +126,7 @@ public interface MultipleAlignmentEnsemble extends ScoresCache { * @return List of Atom[]. * @see #setAtomArrays(List) */ - public List getAtomArrays(); + List getAtomArrays(); /** * Sets the List of Atom arrays. Every structure has an Atom array @@ -140,7 +140,7 @@ public interface MultipleAlignmentEnsemble extends ScoresCache { * @see #getAtomArrays() * @see #setStructureIdentifiers(List) */ - public void setAtomArrays(List atomArrays); + void setAtomArrays(List atomArrays); /** * Returns the List containing the interatomic distance Matrix of each @@ -149,7 +149,7 @@ public interface MultipleAlignmentEnsemble extends ScoresCache { * @return List of Matrix interatomic distance matrices. * @see #updateDistanceMatrix() */ - public List getDistanceMatrix(); + List getDistanceMatrix(); /** * Returns the List of MultipleAlignments in the ensemble. @@ -157,7 +157,7 @@ public interface MultipleAlignmentEnsemble extends ScoresCache { * @return List of MultipleAlignment in the ensemble. * @see #setMultipleAlignments() */ - public List getMultipleAlignments(); + List getMultipleAlignments(); /** * Returns the MultipleAlignments at the specified index @@ -167,7 +167,7 @@ public interface MultipleAlignmentEnsemble extends ScoresCache { * @return MultipleAlignment at the index in the ensemble. * @see #setMultipleAlignments() */ - public MultipleAlignment getMultipleAlignment(int index); + MultipleAlignment getMultipleAlignment(int index); /** * Set the List of MultipleAlignments in the ensemble. @@ -176,7 +176,7 @@ public interface MultipleAlignmentEnsemble extends ScoresCache { * ensemble. * @see #addMultipleAlignment(MultipleAlignment) */ - public void setMultipleAlignments(List alignments); + void setMultipleAlignments(List alignments); /** * Add a new MultipleAlignment to the end of the ensemble and set its @@ -184,7 +184,7 @@ public interface MultipleAlignmentEnsemble extends ScoresCache { * * @param alignment */ - public void addMultipleAlignment(MultipleAlignment alignment); + void addMultipleAlignment(MultipleAlignment alignment); /** * Returns the number of aligned structures in the MultipleAlignments. @@ -193,19 +193,19 @@ public interface MultipleAlignmentEnsemble extends ScoresCache { * @see #getStructureIdentifiers() * @see #getAtomArrays() */ - public int size(); + int size(); /** * Returns the io time for this object, in milliseconds. * @return long creation time, or null if unset */ - public Long getIoTime(); + Long getIoTime(); /** * Set the IO time to load this object * @param millis */ - public void setIoTime(Long millis); + void setIoTime(Long millis); /** * Returns the running time of the structure alignment calculation, in @@ -214,14 +214,14 @@ public interface MultipleAlignmentEnsemble extends ScoresCache { * @return long running time of the calculation, or null if unset * @see #getIoTime() */ - public Long getCalculationTime(); + Long getCalculationTime(); /** * Set the running time spent to calculate this alignment. * * @param millis */ - public void setCalculationTime(Long millis); + void setCalculationTime(Long millis); /** * Clear scores and other properties which depend on the specific @@ -229,5 +229,5 @@ public interface MultipleAlignmentEnsemble extends ScoresCache { * variables.

    * Recursively clears the member MultipleAlignments. */ - public void clear(); + void clear(); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/MultipleAlignmentEnsembleImpl.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/MultipleAlignmentEnsembleImpl.java index 04b31447b0..aba7567b38 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/MultipleAlignmentEnsembleImpl.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/MultipleAlignmentEnsembleImpl.java @@ -20,14 +20,6 @@ */ package org.biojava.nbio.structure.align.multiple; -import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.vecmath.Matrix4d; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Calc; import org.biojava.nbio.structure.StructureException; @@ -39,6 +31,13 @@ import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.jama.Matrix; +import javax.vecmath.Matrix4d; +import java.io.IOException; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + /** * A general implementation of a {@link MultipleAlignmentEnsemble}. * @@ -115,7 +114,7 @@ public MultipleAlignmentEnsembleImpl(MultipleAlignmentEnsembleImpl e) { distanceMatrix = null; if (e.distanceMatrix != null) { // Make a deep copy of everything - distanceMatrix = new ArrayList(); + distanceMatrix = new ArrayList<>(); for (Matrix mat : e.distanceMatrix) { distanceMatrix.add((Matrix) mat.clone()); } @@ -124,7 +123,7 @@ public MultipleAlignmentEnsembleImpl(MultipleAlignmentEnsembleImpl e) { multipleAlignments = null; if (e.multipleAlignments != null) { // Make a deep copy of everything - multipleAlignments = new ArrayList(); + multipleAlignments = new ArrayList<>(); for (MultipleAlignment msa : e.multipleAlignments) { MultipleAlignment newMSA = msa.clone(); newMSA.setEnsemble(this); @@ -133,10 +132,10 @@ public MultipleAlignmentEnsembleImpl(MultipleAlignmentEnsembleImpl e) { } if (e.atomArrays != null) { - atomArrays = new ArrayList(e.atomArrays); + atomArrays = new ArrayList<>(e.atomArrays); } if (e.structureIdentifiers != null) { - structureIdentifiers = new ArrayList( + structureIdentifiers = new ArrayList<>( e.structureIdentifiers); } } @@ -163,7 +162,7 @@ public MultipleAlignmentEnsembleImpl(AFPChain afp, Atom[] ca1, Atom[] ca2, atomArrays = Arrays.asList(ca1, ca2); if (afp.getName1() != null && !afp.getName1().isEmpty() && afp.getName2() != null && !afp.getName2().isEmpty()) { - structureIdentifiers = Arrays. asList( + structureIdentifiers = Arrays.asList( new StructureName(afp.getName1()), new StructureName(afp.getName2())); } @@ -172,7 +171,8 @@ public MultipleAlignmentEnsembleImpl(AFPChain afp, Atom[] ca1, Atom[] ca2, calculationTime = afp.getCalculationTime(); MultipleAlignment msa = new MultipleAlignmentImpl(this); - setMultipleAlignments(Arrays.asList(msa)); + ArrayList ms1 = new ArrayList<>(1); ms1.add(msa); + setMultipleAlignments(ms1); // Convert the rotation and translation to a Matrix4D and set it Matrix4d ident = new Matrix4d(); @@ -184,19 +184,17 @@ public MultipleAlignmentEnsembleImpl(AFPChain afp, Atom[] ca1, Atom[] ca2, if (flexible) { for (int bs = 0; bs < afp.getBlockNum(); bs++) { BlockSet blockSet = new BlockSetImpl(msa); - Matrix4d blockTr = null; + Matrix4d blockTr; try { blockTr = Calc.getTransformation(rot[bs], shift[bs]); - } catch (IndexOutOfBoundsException e) { - blockTr = ident; - } catch (NullPointerException e) { + } catch (IndexOutOfBoundsException | NullPointerException e) { blockTr = ident; } blockSet.setTransformations(Arrays.asList(ident, blockTr)); Block block = new BlockImpl(blockSet); - block.setAlignRes(new ArrayList>()); - block.getAlignRes().add(new ArrayList()); - block.getAlignRes().add(new ArrayList()); + block.setAlignRes(new ArrayList<>()); + block.getAlignRes().add(new ArrayList<>()); + block.getAlignRes().add(new ArrayList<>()); // Set the transformation of the BlockSet Matrix rotB = afp.getBlockRotationMatrix()[bs]; @@ -213,20 +211,18 @@ public MultipleAlignmentEnsembleImpl(AFPChain afp, Atom[] ca1, Atom[] ca2, } // Create a Block for every block in AFPChain if not flexible else { BlockSet blockSet = new BlockSetImpl(msa); - Matrix4d blockTr = null; + Matrix4d blockTr; try { blockTr = Calc.getTransformation(rot[0], shift[0]); - } catch (IndexOutOfBoundsException e) { - blockTr = ident; - } catch (NullPointerException e) { + } catch (IndexOutOfBoundsException | NullPointerException e) { blockTr = ident; } blockSet.setTransformations(Arrays.asList(ident, blockTr)); for (int bs = 0; bs < afp.getBlockNum(); bs++) { Block block = new BlockImpl(blockSet); - block.setAlignRes(new ArrayList>()); - block.getAlignRes().add(new ArrayList()); - block.getAlignRes().add(new ArrayList()); + block.setAlignRes(new ArrayList<>()); + block.getAlignRes().add(new ArrayList<>()); + block.getAlignRes().add(new ArrayList<>()); // Convert the optimal alignment to a Block for (int i = 0; i < afp.getOptAln()[bs][0].length; i++) { @@ -303,9 +299,7 @@ public List getAtomArrays() { if (atomArrays == null) { try { updateAtomArrays(); - } catch (IOException e) { - throw new NullPointerException(e.getMessage()); - } catch (StructureException e) { + } catch (IOException | StructureException e) { throw new NullPointerException(e.getMessage()); } } @@ -326,7 +320,7 @@ public void setAtomArrays(List atomArrays) { */ public void updateAtomArrays() throws IOException, StructureException { AtomCache cache = new AtomCache(); - atomArrays = new ArrayList(); + atomArrays = new ArrayList<>(); for (StructureIdentifier name : getStructureIdentifiers()) { Atom[] array = cache.getRepresentativeAtoms(name); atomArrays.add(array); @@ -346,7 +340,7 @@ public List getDistanceMatrix() { public void updateDistanceMatrix() { // Reset the distance Matrix variable - distanceMatrix = new ArrayList(); + distanceMatrix = new ArrayList<>(); for (int s = 0; s < size(); s++) { Atom[] ca = atomArrays.get(s); @@ -359,7 +353,7 @@ public void updateDistanceMatrix() { public List getMultipleAlignments() { if (multipleAlignments == null) { - multipleAlignments = new ArrayList(); + multipleAlignments = new ArrayList<>(); } return multipleAlignments; } @@ -377,7 +371,7 @@ public void setMultipleAlignments(List alignments) { @Override public void addMultipleAlignment(MultipleAlignment alignment) { if (multipleAlignments == null) { - multipleAlignments = new ArrayList(); + multipleAlignments = new ArrayList<>(); } multipleAlignments.add(alignment); alignment.setEnsemble(this); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/MultipleAlignmentImpl.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/MultipleAlignmentImpl.java index e2131449fd..a38d40b232 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/MultipleAlignmentImpl.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/MultipleAlignmentImpl.java @@ -20,14 +20,14 @@ */ package org.biojava.nbio.structure.align.multiple; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIdentifier; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + /** * A general implementation of a {@link MultipleAlignment}. * @@ -99,7 +99,7 @@ public MultipleAlignmentImpl(MultipleAlignmentImpl ma) { blockSets = null; if (ma.blockSets != null) { // Make a deep copy of everything - this.blockSets = new ArrayList(); + this.blockSets = new ArrayList<>(); for (BlockSet bs : ma.blockSets) { BlockSet newBS = bs.clone(); newBS.setMultipleAlignment(this); @@ -126,7 +126,7 @@ public MultipleAlignmentImpl clone() { @Override public String toString() { - List ids = new ArrayList(parent + List ids = new ArrayList<>(parent .getStructureIdentifiers().size()); for (StructureIdentifier i : parent.getStructureIdentifiers()) { ids.add(i.getIdentifier()); @@ -146,13 +146,13 @@ public String toString() { @Override public List getBlockSets() { if (blockSets == null) - blockSets = new ArrayList(); + blockSets = new ArrayList<>(); return blockSets; } @Override public List getBlocks() { - List blocks = new ArrayList(); + List blocks = new ArrayList<>(); for (BlockSet bs : getBlockSets()) { blocks.addAll(bs.getBlocks()); } @@ -262,7 +262,7 @@ public List getAlignResCounts() { if (alignResCounts != null) return alignResCounts; - alignResCounts = new ArrayList(size()); + alignResCounts = new ArrayList<>(size()); for (int s = 0; s < size(); s++) alignResCounts.add(0); @@ -281,7 +281,7 @@ public List getCoverages() { return coverages; List counts = getAlignResCounts(); - coverages = new ArrayList(size()); + coverages = new ArrayList<>(size()); for (int s = 0; s < size(); s++) coverages.add(counts.get(s) / (double) getAtomArrays().get(s).length); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/ScoresCache.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/ScoresCache.java index bca1af269f..480255ab53 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/ScoresCache.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/ScoresCache.java @@ -20,10 +20,10 @@ */ package org.biojava.nbio.structure.align.multiple; -import java.util.Set; - import org.biojava.nbio.structure.align.multiple.util.MultipleAlignmentScorer; +import java.util.Set; + /** * Interface for classes which implement a temporary cache for various numeric * scores, e.g. RMSD, TM-Score, etc. @@ -51,7 +51,7 @@ public interface ScoresCache { * in headers. Example names found in: {@link MultipleAlignmentScorer}. * @param score Value of the score */ - public void putScore(String property, Double score); + void putScore(String property, Double score); /** * Get the value for a particular score. Scores which return null @@ -61,12 +61,12 @@ public interface ScoresCache { * @param property Name of the score to fetch * @return Value of the score, or null if it is not set. */ - public Double getScore(String property); + Double getScore(String property); /** * Get a collection of all scores that have been set. * * @return Set of all score names */ - public Set getScores(); + Set getScores(); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/mc/MultipleMcMain.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/mc/MultipleMcMain.java index dcc843d791..c5cb07847d 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/mc/MultipleMcMain.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/mc/MultipleMcMain.java @@ -20,17 +20,6 @@ */ package org.biojava.nbio.structure.align.multiple.mc; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.SortedSet; -import java.util.TreeSet; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.CallableStructureAlignment; @@ -39,17 +28,13 @@ import org.biojava.nbio.structure.align.ce.CeCPMain; import org.biojava.nbio.structure.align.ce.ConfigStrucAligParams; import org.biojava.nbio.structure.align.model.AFPChain; -import org.biojava.nbio.structure.align.multiple.Block; -import org.biojava.nbio.structure.align.multiple.BlockImpl; -import org.biojava.nbio.structure.align.multiple.BlockSet; -import org.biojava.nbio.structure.align.multiple.BlockSetImpl; -import org.biojava.nbio.structure.align.multiple.MultipleAlignment; -import org.biojava.nbio.structure.align.multiple.MultipleAlignmentEnsemble; -import org.biojava.nbio.structure.align.multiple.MultipleAlignmentEnsembleImpl; -import org.biojava.nbio.structure.align.multiple.MultipleAlignmentImpl; +import org.biojava.nbio.structure.align.multiple.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.*; +import java.util.concurrent.*; + /** * Main class of the Java implementation of the Combinatorial Extension - * Monte Carlo (CEMC) Algorithm, @@ -115,25 +100,24 @@ public MultipleMcMain(StructureAlignment pairwiseAlgo){ * @return MultipleAlignment seed alignment * @throws ExecutionException * @throws InterruptedException - * @throws StructureException - */ + */ private MultipleAlignment generateSeed(List atomArrays) throws InterruptedException, - ExecutionException, StructureException { + ExecutionException { int size = atomArrays.size(); //List to store the all-to-all alignments - List> afpAlignments = new ArrayList>(); + List> afpAlignments = new ArrayList<>(); for (int i=0; i()); + afpAlignments.add(new ArrayList<>()); for (int j=0; j> afpFuture = new ArrayList>(); + List> afpFuture = new ArrayList<>(); //Create all the possible protein pairwise combinations //(N*(N-1)/2) and call the pairwise alignment algorithm @@ -184,7 +168,7 @@ private static int chooseReferenceRMSD(List> afpAlignments){ int size = afpAlignments.size(); - List RMSDs = new ArrayList(); + List RMSDs = new ArrayList<>(); for (int i=0; i> afpAlignments){ * @param ref index of the reference structure * @param flexible uses BlockSets if true, uses Blocks otherwise * @return MultipleAlignment seed alignment - * @throws StructureException */ private static MultipleAlignment combineReferenceAlignments( List afpList, List atomArrays, - int ref, boolean flexible) throws StructureException { + int ref, boolean flexible) { int size = atomArrays.size(); - int length = 0; //the number of residues of the reference structure + int length; //the number of residues of the reference structure if (ref==0) length = afpList.get(1).getCa1Length(); else length = afpList.get(0).getCa2Length(); - SortedSet flexibleBoundaries = new TreeSet(); + SortedSet flexibleBoundaries = new TreeSet<>(); //Stores the equivalencies of all the structures as a double List - List> equivalencies = new ArrayList>(); + List> equivalencies = new ArrayList<>(); for (int str=0; str()); + equivalencies.add(new ArrayList<>()); for (int res=0; res> alnRes = - new ArrayList>(size); + new ArrayList<>(size); for (int k=0; k()); + alnRes.add(new ArrayList<>()); } lastB.setAlignRes(alnRes); } @@ -335,9 +318,7 @@ public MultipleAlignment align(List atomArrays, Object parameters) //Generate the seed alignment and optimize it try { result = generateSeed(atomArrays); - } catch (InterruptedException e) { - logger.warn("Seed generation failed.",e); - } catch (ExecutionException e) { + } catch (InterruptedException | ExecutionException e) { logger.warn("Seed generation failed.",e); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/mc/MultipleMcOptimizer.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/mc/MultipleMcOptimizer.java index 0845c61300..d1caf74991 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/mc/MultipleMcOptimizer.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/mc/MultipleMcOptimizer.java @@ -20,16 +20,6 @@ */ package org.biojava.nbio.structure.align.multiple.mc; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Random; -import java.util.SortedSet; -import java.util.TreeSet; -import java.util.concurrent.Callable; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.multiple.Block; @@ -44,6 +34,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.FileWriter; +import java.io.IOException; +import java.util.*; +import java.util.concurrent.Callable; + /** * This class takes a MultipleAlignment seed previously generated and runs a * Monte Carlo optimization in order to improve the overall score and highlight @@ -67,28 +62,28 @@ public class MultipleMcOptimizer implements Callable { private static final Logger logger = LoggerFactory .getLogger(MultipleMcOptimizer.class); - private Random rnd; - private MultipleSuperimposer imposer; + private final Random rnd; + private final MultipleSuperimposer imposer; // Optimization parameters - private int Rmin; // number of aligned structures without a gap - private int Lmin; // Minimum alignment length of a Block - private int convergenceSteps; // Steps without score change before stopping - private double C; // Probability function constant + private final int Rmin; // number of aligned structures without a gap + private final int Lmin; // Minimum alignment length of a Block + private final int convergenceSteps; // Steps without score change before stopping + private final double C; // Probability function constant // Score function parameters - they are defined by the user - private double Gopen; // Penalty for opening gap - private double Gextend; // Penalty for extending gaps - private double dCutoff; // max allowed residue distance + private final double Gopen; // Penalty for opening gap + private final double Gextend; // Penalty for extending gaps + private final double dCutoff; // max allowed residue distance // Alignment Information private MultipleAlignment msa; // Alignment to optimize private List> freePool; // unaligned residues - private List atomArrays; + private final List atomArrays; // Alignment Properties - private int size; // number of structures in the alignment - private int blockNr; // the number of Blocks in the alignment + private final int size; // number of structures in the alignment + private final int blockNr; // the number of Blocks in the alignment private double mcScore; // Optimization score, objective function // Variables that store the history of the optimization - slower if on @@ -125,7 +120,7 @@ public MultipleMcOptimizer(MultipleAlignment seedAln, imposer = new CoreSuperimposer(reference); if (params.getConvergenceSteps() == 0) { - List lens = new ArrayList(); + List lens = new ArrayList<>(); for (int i = 0; i < size; i++) lens.add(atomArrays.get(i).length); convergenceSteps = Collections.min(lens) * size; @@ -142,8 +137,8 @@ public MultipleMcOptimizer(MultipleAlignment seedAln, Lmin = params.getMinBlockLen(); // Delete all shorter than Lmin blocks, and empty blocksets - List toDelete = new ArrayList(); - List emptyBs = new ArrayList(); + List toDelete = new ArrayList<>(); + List emptyBs = new ArrayList<>(); for (Block b : msa.getBlocks()) { if (b.getCoreLength() < Lmin) { @@ -178,17 +173,16 @@ public MultipleAlignment call() throws Exception { * Initialize the freePool and all the variables needed for the * optimization. * - * @throws StructureException */ - private void initialize() throws StructureException { + private void initialize() { // Initialize alignment variables - freePool = new ArrayList>(); - List> aligned = new ArrayList>(); + freePool = new ArrayList<>(); + List> aligned = new ArrayList<>(); // Generate freePool residues from the ones not aligned for (int i = 0; i < size; i++) { - List residues = new ArrayList(); + List residues = new ArrayList<>(); for (BlockSet bs : msa.getBlockSets()) { for (Block b : bs.getBlocks()) { for (int l = 0; l < b.length(); l++) { @@ -199,7 +193,7 @@ private void initialize() throws StructureException { } } aligned.add(residues); - freePool.add(new TreeSet()); + freePool.add(new TreeSet<>()); } // Add any residue not aligned to the free pool for every structure @@ -219,9 +213,9 @@ private void initialize() throws StructureException { // Initialize the history variables if (history) { - lengthHistory = new ArrayList(); - rmsdHistory = new ArrayList(); - scoreHistory = new ArrayList(); + lengthHistory = new ArrayList<>(); + rmsdHistory = new ArrayList<>(); + scoreHistory = new ArrayList<>(); } } @@ -249,11 +243,9 @@ public MultipleAlignment optimize() throws StructureException { // Save the state of the system MultipleAlignment lastMSA = msa.clone(); - List> lastFreePool = new ArrayList>(); + List> lastFreePool = new ArrayList<>(); for (int k = 0; k < size; k++) { - SortedSet p = new TreeSet(); - for (Integer l : freePool.get(k)) - p.add(l); + SortedSet p = new TreeSet<>(freePool.get(k)); lastFreePool.add(p); } double lastScore = mcScore; @@ -349,10 +341,10 @@ private boolean checkGaps() { boolean shrinkedAny = false; - List> shrinkColumns = new ArrayList>(); + List> shrinkColumns = new ArrayList<>(); // Loop for each Block for (Block b : msa.getBlocks()) { - List shrinkCol = new ArrayList(); + List shrinkCol = new ArrayList<>(); // Loop for each column in the Block for (int res = 0; res < b.length(); res++) { int gapCount = 0; @@ -844,9 +836,9 @@ private void saveHistory(String filePath) throws IOException { for (int i = 0; i < lengthHistory.size(); i++) { writer.append(String.valueOf(i * 100)); - writer.append("," + lengthHistory.get(i)); - writer.append("," + rmsdHistory.get(i)); - writer.append("," + scoreHistory.get(i) + "\n"); + writer.append(",").append(String.valueOf(lengthHistory.get(i))); + writer.append(",").append(String.valueOf(rmsdHistory.get(i))); + writer.append(",").append(String.valueOf(scoreHistory.get(i))).append("\n"); } writer.flush(); writer.close(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/mc/MultipleMcParameters.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/mc/MultipleMcParameters.java index a49d9febc3..d56f16ed3c 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/mc/MultipleMcParameters.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/mc/MultipleMcParameters.java @@ -20,12 +20,12 @@ */ package org.biojava.nbio.structure.align.multiple.mc; +import org.biojava.nbio.structure.align.ce.ConfigStrucAligParams; + import java.util.ArrayList; import java.util.List; import java.util.Random; -import org.biojava.nbio.structure.align.ce.ConfigStrucAligParams; - /** * Contains the parameters to be sent to the MC optimization. * @@ -54,7 +54,7 @@ public MultipleMcParameters(){ @Override public List getUserConfigParameters() { - List params = new ArrayList(); + List params = new ArrayList<>(); params.add("RandomSeed"); params.add("MinBlockLen"); params.add("MinAlignedStructures"); @@ -69,7 +69,7 @@ public List getUserConfigParameters() { @Override public List getUserConfigParameterNames() { - List params = new ArrayList(); + List params = new ArrayList<>(); params.add("Random Seed"); params.add("Minimum Block Length"); params.add("Minimum Structures per Column"); @@ -85,7 +85,7 @@ public List getUserConfigParameterNames() { @SuppressWarnings("rawtypes") public List getUserConfigTypes() { - List params = new ArrayList(); + List params = new ArrayList<>(); params.add(Integer.class); params.add(Integer.class); params.add(Integer.class); @@ -100,7 +100,7 @@ public List getUserConfigTypes() { @Override public List getUserConfigHelp() { - List params =new ArrayList(); + List params = new ArrayList<>(); String randomSeed = "Random seed for the optimizer random number generator."; String minBlockLen = diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/CoreSuperimposer.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/CoreSuperimposer.java index 097615a554..0853b78382 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/CoreSuperimposer.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/CoreSuperimposer.java @@ -20,14 +20,8 @@ */ package org.biojava.nbio.structure.align.multiple.util; -import java.util.ArrayList; -import java.util.List; - -import javax.vecmath.Matrix4d; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Calc; -import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.multiple.Block; import org.biojava.nbio.structure.align.multiple.BlockSet; @@ -35,6 +29,10 @@ import org.biojava.nbio.structure.geometry.SuperPositionSVD; import org.biojava.nbio.structure.geometry.SuperPositions; +import javax.vecmath.Matrix4d; +import java.util.ArrayList; +import java.util.List; + /** * Superimposes the core aligned residues of every structure in a * {@link MultipleAlignment} onto a reference structure. This method @@ -54,7 +52,7 @@ */ public class CoreSuperimposer implements MultipleSuperimposer { - private int reference; + private final int reference; /** * Default Constructor. @@ -79,8 +77,7 @@ public CoreSuperimposer(int reference) { } @Override - public void superimpose(MultipleAlignment alignment) - throws StructureException { + public void superimpose(MultipleAlignment alignment) { //Check for inconsistencies in the alignment if(alignment.getEnsemble() == null) { @@ -111,7 +108,7 @@ public void superimpose(MultipleAlignment alignment) //Block transformations List transforms = - new ArrayList(atomArrays.size()); + new ArrayList<>(atomArrays.size()); //Loop through structures for (int i=0; i atomSet1 = new ArrayList(); - List atomSet2 = new ArrayList(); + List atomSet1 = new ArrayList<>(); + List atomSet2 = new ArrayList<>(); for( Block blk : bs.getBlocks() ) { @@ -156,8 +153,8 @@ public void superimpose(MultipleAlignment alignment) atomSet2.add(curr[pos2]); } } - Atom[] array1 = atomSet1.toArray(new Atom[atomSet1.size()]); - Atom[] array2 = atomSet2.toArray(new Atom[atomSet2.size()]); + Atom[] array1 = atomSet1.toArray(Atom.EmptyAtomArray); + Atom[] array2 = atomSet2.toArray(Atom.EmptyAtomArray); array2 = StructureTools.cloneAtomArray(array2); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleAlignmentDisplay.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleAlignmentDisplay.java index ad5b1dd83f..e7cc54f711 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleAlignmentDisplay.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleAlignmentDisplay.java @@ -26,7 +26,6 @@ import org.slf4j.LoggerFactory; import javax.vecmath.Matrix4d; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -69,7 +68,7 @@ public static List getRotatedAtoms(MultipleAlignment multAln) + atomArrays.get(i).length); } - List rotatedAtoms = new ArrayList(); + List rotatedAtoms = new ArrayList<>(); // TODO implement independent BlockSet superposition of the structure List transf = multAln.getBlockSet(0).getTransformations(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleAlignmentScorer.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleAlignmentScorer.java index 1422348e6d..45851e90a6 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleAlignmentScorer.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleAlignmentScorer.java @@ -20,16 +20,16 @@ */ package org.biojava.nbio.structure.align.multiple.util; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Calc; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.multiple.MultipleAlignment; import org.biojava.nbio.structure.jama.Matrix; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + /** * Utility class for calculating common scores of {@link MultipleAlignment}s. * @@ -66,7 +66,7 @@ public static void calculateScores(MultipleAlignment alignment) alignment.putScore(RMSD, getRMSD(trans)); // Put AvgTM-Score - List lengths = new ArrayList(alignment.size()); + List lengths = new ArrayList<>(alignment.size()); for (Atom[] atoms : alignment.getAtomArrays()) { lengths.add(atoms.length); } @@ -121,7 +121,7 @@ public static double getRMSD(List transformed) { for (int r2 = r1 + 1; r2 < transformed.size(); r2++) { Atom atom = transformed.get(r2)[c]; if (atom != null) { - nonNullSqDist += Calc.getDistanceFast(refAtom, atom); + nonNullSqDist += Calc.getDistanceSqr(refAtom, atom); nonNullLength++; } } @@ -208,7 +208,7 @@ public static double getRefRMSD(List transformed, int reference) { continue; Atom atom = transformed.get(r)[c]; if (atom != null) { - nonNullSqDist += Calc.getDistanceFast(refAtom, atom); + nonNullSqDist += Calc.getDistanceSqr(refAtom, atom); nonNullLength++; } } @@ -237,7 +237,7 @@ public static double getAvgTMScore(MultipleAlignment alignment) List trans = MultipleAlignmentTools.transformAtoms(alignment); - List lengths = new ArrayList(alignment.size()); + List lengths = new ArrayList<>(alignment.size()); for (Atom[] atoms : alignment.getAtomArrays()) { lengths.add(atoms.length); } @@ -314,7 +314,7 @@ public static double getRefTMScore(MultipleAlignment alignment, int ref) List trans = MultipleAlignmentTools.transformAtoms(alignment); - List lengths = new ArrayList(alignment.size()); + List lengths = new ArrayList<>(alignment.size()); for (Atom[] atoms : alignment.getAtomArrays()) { lengths.add(atoms.length); } @@ -395,11 +395,9 @@ public static double getRefTMScore(List transformed, * @param dCutoff * the distance cutoff * @return the value of the score - * @throws StructureException - */ + */ public static double getMCScore(MultipleAlignment alignment, - double gapOpen, double gapExtension, double dCutoff) - throws StructureException { + double gapOpen, double gapExtension, double dCutoff) { List trans = MultipleAlignmentTools.transformAtoms(alignment); @@ -440,11 +438,9 @@ public static double getMCScore(MultipleAlignment alignment, * @param A * the distance cutoff penalization * @return the value of the score - * @throws StructureException */ private static double getMCScore(List trans, double d0, - double gapOpen, double gapExtension, double A) - throws StructureException { + double gapOpen, double gapExtension, double A) { int size = trans.size(); int length = trans.get(0).length; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleAlignmentTools.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleAlignmentTools.java index d790eec19c..2a01044f85 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleAlignmentTools.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleAlignmentTools.java @@ -20,19 +20,6 @@ */ package org.biojava.nbio.structure.align.multiple.util; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.SortedSet; -import java.util.TreeSet; - -import javax.vecmath.Matrix4d; - import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.AccessionID; @@ -42,17 +29,7 @@ import org.biojava.nbio.phylo.DistanceMatrixCalculator; import org.biojava.nbio.phylo.TreeConstructor; import org.biojava.nbio.phylo.TreeConstructorType; -import org.biojava.nbio.structure.AminoAcid; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Calc; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.PDBHeader; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIdentifier; -import org.biojava.nbio.structure.StructureImpl; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.multiple.Block; import org.biojava.nbio.structure.align.multiple.BlockSet; import org.biojava.nbio.structure.align.multiple.MultipleAlignment; @@ -61,6 +38,10 @@ import org.forester.evoinference.matrix.distance.BasicSymmetricalDistanceMatrix; import org.forester.phylogeny.Phylogeny; +import javax.vecmath.Matrix4d; +import java.io.IOException; +import java.util.*; + /** * Utility functions for working with {@link MultipleAlignment}. *

    @@ -108,7 +89,7 @@ public static List getSequenceAlignment( MultipleAlignment alignment, final List mapSeqToStruct) { // Initialize sequence variables - List alnSequences = new ArrayList(); + List alnSequences = new ArrayList<>(); for (int str = 0; str < alignment.size(); str++) alnSequences.add(""); mapSeqToStruct.clear(); @@ -116,15 +97,15 @@ public static List getSequenceAlignment( int globalPos = -1; // Initialize helper variables in constucting the sequence alignment - List> freePool = new ArrayList>(); - List> blockStarts = new ArrayList>(); - List> aligned = new ArrayList>(); + List> freePool = new ArrayList<>(); + List> blockStarts = new ArrayList<>(); + List> aligned = new ArrayList<>(); // Generate freePool residues from the ones not aligned for (int i = 0; i < alignment.size(); i++) { - List residues = new ArrayList(); - freePool.add(new TreeSet()); - blockStarts.add(new TreeSet()); + List residues = new ArrayList<>(); + freePool.add(new TreeSet<>()); + blockStarts.add(new TreeSet<>()); for (BlockSet bs : alignment.getBlockSets()) { for (Block b : bs.getBlocks()) { boolean first = true; @@ -314,7 +295,7 @@ public static List getSequenceAlignment( * for each aligned residue. */ public static List getSequenceAlignment(MultipleAlignment msa) { - return getSequenceAlignment(msa, new ArrayList()); + return getSequenceAlignment(msa, new ArrayList<>()); } /** @@ -346,7 +327,7 @@ public static List getBlockSequenceAlignment( MultipleAlignment alignment, List mapSeqToStruct) { // Initialize sequence variables - List alnSequences = new ArrayList(); + List alnSequences = new ArrayList<>(); for (int str = 0; str < alignment.size(); str++) alnSequences.add(""); mapSeqToStruct.clear(); @@ -471,7 +452,7 @@ else if (previousPos[str] + 1 == residue) { * for each aligned residue. */ public static List getBlockSequenceAlignment(MultipleAlignment ma) { - return getBlockSequenceAlignment(ma, new ArrayList()); + return getBlockSequenceAlignment(ma, new ArrayList<>()); } /** @@ -661,7 +642,7 @@ public static List transformAtoms(MultipleAlignment alignment) { } List atomArrays = alignment.getAtomArrays(); - List transformed = new ArrayList(atomArrays.size()); + List transformed = new ArrayList<>(atomArrays.size()); // Loop through structures for (int i = 0; i < atomArrays.size(); i++) { @@ -729,7 +710,7 @@ public static List transformAtoms(MultipleAlignment alignment) { */ public static List getCorePositions(Block block) { - List corePositions = new ArrayList(); + List corePositions = new ArrayList<>(); for (int col = 0; col < block.length(); col++) { boolean core = true; @@ -755,28 +736,25 @@ public static List getCorePositions(Block block) { * Index of the row to be sorted */ public static void sortBlocks(List blocks, final int sortedIndex) { - Collections.sort(blocks, new Comparator() { - @Override - public int compare(Block o1, Block o2) { - // Compare the first non-null residue of each block - List alignres1 = o1.getAlignRes().get(sortedIndex); - List alignres2 = o2.getAlignRes().get(sortedIndex); - Integer res1 = null; - Integer res2 = null; - for (Integer r : alignres1) { - if (r != null) { - res1 = r; - break; - } + blocks.sort((o1, o2) -> { + // Compare the first non-null residue of each block + List alignres1 = o1.getAlignRes().get(sortedIndex); + List alignres2 = o2.getAlignRes().get(sortedIndex); + Integer res1 = null; + Integer res2 = null; + for (Integer r : alignres1) { + if (r != null) { + res1 = r; + break; } - for (Integer r : alignres2) { - if (r != null) { - res2 = r; - break; - } + } + for (Integer r : alignres2) { + if (r != null) { + res2 = r; + break; } - return res1.compareTo(res2); } + return res1.compareTo(res2); }); } @@ -800,9 +778,9 @@ public static MultipleSequenceAlignment toPr + "the structures aligned are not proteins"); } - MultipleSequenceAlignment msa = new MultipleSequenceAlignment(); + MultipleSequenceAlignment msa = new MultipleSequenceAlignment<>(); - Map uniqueID = new HashMap(); + Map uniqueID = new HashMap<>(); List seqs = getSequenceAlignment(msta); for (int i = 0; i < msta.size(); i++) { // Make sure the identifiers are unique (required by AccessionID) @@ -821,7 +799,7 @@ public static MultipleSequenceAlignment toPr return msa; } - public static Structure toMultimodelStructure(MultipleAlignment multAln, List transformedAtoms) throws StructureException { + public static Structure toMultimodelStructure(MultipleAlignment multAln, List transformedAtoms) { PDBHeader header = new PDBHeader(); String title = multAln.getEnsemble().getAlgorithmName() + " V." + multAln.getEnsemble().getVersion() + " : "; @@ -845,10 +823,8 @@ public static Structure toMultimodelStructure(MultipleAlignment multAln, List atomArrays) - throws StructureException { + public static Structure getAlignedStructure(List atomArrays) { Structure s = new StructureImpl(); for (int i=0; i compared = new ArrayList(); + List compared = new ArrayList<>(); compared.add(superposed.get(i)); compared.add(superposed.get(j)); double rmsd = MultipleAlignmentScorer.getRMSD(compared); @@ -918,10 +894,9 @@ public static Phylogeny getKimuraTree(MultipleAlignment msta) * MultipleAlignment of protein structures * @return Phylogeny phylogenetic tree * @throws CompoundNotFoundException - * @throws IOException */ public static Phylogeny getHSDMTree(MultipleAlignment msta) - throws CompoundNotFoundException, IOException { + throws CompoundNotFoundException { MultipleSequenceAlignment msa = MultipleAlignmentTools .toProteinMSA(msta); BasicSymmetricalDistanceMatrix distmat = (BasicSymmetricalDistanceMatrix) DistanceMatrixCalculator @@ -947,7 +922,7 @@ public static Phylogeny getStructuralTree(MultipleAlignment msta) { BasicSymmetricalDistanceMatrix rmsdDist = (BasicSymmetricalDistanceMatrix) DistanceMatrixCalculator .structuralDistance(rmsdMat, 1, 5, 0.4); // Set the identifiers of the matrix - Map alreadySeen = new HashMap(); + Map alreadySeen = new HashMap<>(); for (int i = 0; i < msta.size(); i++) { // Make sure the identifiers are unique String id = msta.getStructureIdentifier(i).toString(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleAlignmentWriter.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleAlignmentWriter.java index d20a884a62..8f7e4cd6c5 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleAlignmentWriter.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleAlignmentWriter.java @@ -20,25 +20,20 @@ */ package org.biojava.nbio.structure.align.multiple.util; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.List; - -import javax.vecmath.Matrix4d; - import org.biojava.nbio.core.util.PrettyXMLWriter; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.ResidueRange; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIdentifier; -import org.biojava.nbio.structure.SubstructureIdentifier; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.multiple.Block; import org.biojava.nbio.structure.align.multiple.MultipleAlignment; import org.biojava.nbio.structure.align.multiple.MultipleAlignmentEnsemble; import org.biojava.nbio.structure.align.xml.MultipleAlignmentXMLConverter; +import javax.vecmath.Matrix4d; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; + /** * This class contains functions for the conversion of {@link MultipleAlignment} * to various String outputs. @@ -90,10 +85,10 @@ public static String toFatCat(MultipleAlignment alignment) { // Initialize the String and put the summary information StringWriter fatcat = new StringWriter(); - fatcat.append(alignment.toString() + "\n\n"); + fatcat.append(alignment.toString()).append("\n\n"); // Get the alignment sequences and the mapping - List mapSeqToStruct = new ArrayList(); + List mapSeqToStruct = new ArrayList<>(); List alnSequences = MultipleAlignmentTools .getSequenceAlignment(alignment, mapSeqToStruct); @@ -111,14 +106,12 @@ public static String toFatCat(MultipleAlignment alignment) { // Write the Sequence Alignment for (int str = 0; str < alignment.size(); str++) { if (str < 9) { - fatcat.append("Chain 0" + (str + 1) + ": " - + alnSequences.get(str) + "\n"); + fatcat.append("Chain 0").append(String.valueOf(str + 1)).append(": ").append(alnSequences.get(str)).append("\n"); } else { - fatcat.append("Chain " + (str + 1) + ": " - + alnSequences.get(str) + "\n"); + fatcat.append("Chain ").append(String.valueOf(str + 1)).append(": ").append(alnSequences.get(str)).append("\n"); } if (str != alignment.size() - 1) { - fatcat.append(" " + blockNumbers + "\n"); + fatcat.append(" ").append(blockNumbers).append("\n"); } } return fatcat.toString(); @@ -145,15 +138,14 @@ public static String toAlignedResidues(MultipleAlignment multAln) { // Write structure names & PDB codes for (int str = 0; str < multAln.size(); str++) { - residueGroup.append("#Struct" + (str + 1) + ":\t"); + residueGroup.append("#Struct").append(String.valueOf(str + 1)).append(":\t"); residueGroup.append(multAln.getEnsemble().getStructureIdentifiers() .get(str).getIdentifier()); residueGroup.append("\n"); } // Whrite header for columns for (int str = 0; str < multAln.size(); str++) - residueGroup.append("#Num" + (str + 1) + "\tChain" + (str + 1) - + "\tAA" + (str + 1) + "\t"); + residueGroup.append("#Num").append(String.valueOf(str + 1)).append("\tChain").append(String.valueOf(str + 1)).append("\tAA").append(String.valueOf(str + 1)).append("\t"); residueGroup.append("\n"); // Write optimally aligned pairs @@ -197,7 +189,7 @@ public static String toAlignedResidues(MultipleAlignment multAln) { */ public static String toTransformMatrices(MultipleAlignment alignment) { - StringBuffer txt = new StringBuffer(); + StringBuilder txt = new StringBuilder(); for (int bs = 0; bs < alignment.getBlockSets().size(); bs++) { @@ -326,7 +318,7 @@ public static String to3DFormat(MultipleAlignment alignment, StructureIdentifier tName = alignment.getEnsemble().getStructureIdentifiers() .get(templateIndex); SubstructureIdentifier canon = tName.toCanonical(); - String tPdbId = canon.getPdbId(); + String tPdbId = canon.pdbId; String tChain = null; for(ResidueRange range : canon.getResidueRanges()) { tChain = range.getChainName(); @@ -360,11 +352,11 @@ public static String to3DFormat(MultipleAlignment alignment, String tPDB = templateAtoms[tRes].toPDB(); // merge the two records into 3D format - str.append(qPDB.substring(0, 30)); // up through coordinates - str.append(tPDB.substring(30, 54)); // coordinates - str.append(tPDB.substring(22, 27)); // residue number + str.append(qPDB, 0, 30); // up through coordinates + str.append(tPDB, 30, 54); // coordinates + str.append(tPDB, 22, 27); // residue number str.append(' '); - str.append(tPDB.substring(17, 20)); + str.append(tPDB, 17, 20); str.append('\n'); } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleSuperimposer.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleSuperimposer.java index 81f95243f1..815e50c055 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleSuperimposer.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/MultipleSuperimposer.java @@ -20,12 +20,11 @@ */ package org.biojava.nbio.structure.align.multiple.util; -import java.util.List; - -import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.multiple.BlockSet; import org.biojava.nbio.structure.align.multiple.MultipleAlignment; +import java.util.List; + /** * Interface for Multiple Alignment superposition algorithms. *

    @@ -58,8 +57,7 @@ public interface MultipleSuperimposer { * atoms to align (via the {@link MultipleAlignment#getEnsemble() * ensemble}). * - * @throws StructureException */ - public void superimpose(MultipleAlignment alignment) - throws StructureException; + void superimpose(MultipleAlignment alignment) + ; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/ReferenceSuperimposer.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/ReferenceSuperimposer.java index 0285f8a90d..b569b72973 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/ReferenceSuperimposer.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/multiple/util/ReferenceSuperimposer.java @@ -20,14 +20,8 @@ */ package org.biojava.nbio.structure.align.multiple.util; -import java.util.ArrayList; -import java.util.List; - -import javax.vecmath.Matrix4d; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Calc; -import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.multiple.Block; import org.biojava.nbio.structure.align.multiple.BlockSet; @@ -35,6 +29,10 @@ import org.biojava.nbio.structure.geometry.SuperPositionSVD; import org.biojava.nbio.structure.geometry.SuperPositions; +import javax.vecmath.Matrix4d; +import java.util.ArrayList; +import java.util.List; + /** * Superimposes each structure in a {@link MultipleAlignment} onto a reference * structure. @@ -52,7 +50,7 @@ */ public class ReferenceSuperimposer implements MultipleSuperimposer { - private int reference; + private final int reference; /** * Default Constructor. @@ -77,8 +75,7 @@ public ReferenceSuperimposer(int reference) { } @Override - public void superimpose(MultipleAlignment alignment) - throws StructureException { + public void superimpose(MultipleAlignment alignment) { //Check for inconsistencies in the alignment if(alignment.getEnsemble() == null) { @@ -109,7 +106,7 @@ public void superimpose(MultipleAlignment alignment) //Block transformations List transforms = - new ArrayList(atomArrays.size()); + new ArrayList<>(atomArrays.size()); //Loop through structures for (int i=0; i atomSet1 = new ArrayList(); - List atomSet2 = new ArrayList(); + List atomSet1 = new ArrayList<>(); + List atomSet2 = new ArrayList<>(); for( Block blk : bs.getBlocks() ) { if( blk.size() != atomArrays.size()) { @@ -145,8 +142,8 @@ public void superimpose(MultipleAlignment alignment) atomSet2.add(curr[pos2]); } } - Atom[] array1 = atomSet1.toArray(new Atom[atomSet1.size()]); - Atom[] array2 = atomSet2.toArray(new Atom[atomSet2.size()]); + Atom[] array1 = atomSet1.toArray(Atom.EmptyAtomArray); + Atom[] array2 = atomSet2.toArray(Atom.EmptyAtomArray); array2 = StructureTools.cloneAtomArray(array2); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/AligNPE.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/AligNPE.java index b1ef23788c..da23009c0d 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/AligNPE.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/AligNPE.java @@ -61,7 +61,7 @@ public static Alignable align_NPE(Matrix sim,StrucAligParameters params){ for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { - int e=0; + int e; //if ( ( i < rows) && // ( j < cols)) { //TODO: the ALIGFACTOR calc should be hidden in Gotoh!! diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/Alignable.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/Alignable.java index a243cc4f54..ff6893c1c8 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/Alignable.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/Alignable.java @@ -26,22 +26,22 @@ import org.biojava.nbio.structure.align.helper.IndexPair; public interface Alignable { - public int getRows(); - public int getCols(); - public AligMatEl[][] getAligMat(); - public void setAligMat(AligMatEl[][] alignmentMatrix); - public float getGapExtCol(); - public void setGapExtCol(float penalty); - public float getGapExtRow(); - public void setGapExtRow(float penalty); - public float getGapOpenCol(); - public void setGapOpenCol(float penalty); - public float getGapOpenRow(); - public void setGapOpenRow(float penalty); - public void setScore(float score); - public float getScore(); - public int getPathSize(); - public void setPathSize(int pathSize); - public void setPath(IndexPair[] path); - public IndexPair[] getPath(); + int getRows(); + int getCols(); + AligMatEl[][] getAligMat(); + void setAligMat(AligMatEl[][] alignmentMatrix); + float getGapExtCol(); + void setGapExtCol(float penalty); + float getGapExtRow(); + void setGapExtRow(float penalty); + float getGapOpenCol(); + void setGapOpenCol(float penalty); + float getGapOpenRow(); + void setGapOpenRow(float penalty); + void setScore(float score); + float getScore(); + int getPathSize(); + void setPathSize(int pathSize); + void setPath(IndexPair[] path); + IndexPair[] getPath(); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/AlignmentResult.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/AlignmentResult.java index bfa720e183..ebd0e2ec09 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/AlignmentResult.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/AlignmentResult.java @@ -48,7 +48,7 @@ public class AlignmentResult implements Serializable @Override public String toString(){ - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); buf.append(pdb1); buf.append("_"); buf.append(chain1); @@ -166,7 +166,7 @@ public void setIoTime(long ioTime) this.ioTime = ioTime; } public void serialize (File output) - throws FileNotFoundException, IOException{ + throws IOException{ // save alignment result: FileOutputStream outStream = new FileOutputStream(output); @@ -177,7 +177,7 @@ public void serialize (File output) } public static AlignmentResult deserialize(File output) - throws FileNotFoundException, IOException, ClassNotFoundException{ + throws IOException, ClassNotFoundException{ FileInputStream fin = new FileInputStream(output); ObjectInputStream objIn = new ObjectInputStream(fin); AlignmentResult result = (AlignmentResult) objIn.readObject(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/AltAligComparator.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/AltAligComparator.java index 1ac6c90e78..f3ea6adcf4 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/AltAligComparator.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/AltAligComparator.java @@ -33,35 +33,39 @@ * */ public class AltAligComparator implements Comparator, Serializable { + + public static final AltAligComparator the = new AltAligComparator(); + private static final long serialVersionUID = 1; - public AltAligComparator() { + private AltAligComparator() { super(); - } @Override public int compare(AlternativeAlignment a, AlternativeAlignment b) { + if (a==b) return 0; int s1 = a.getIdx1().length; int s2 = b.getIdx1().length; if ( s1 > s2) return 1; - if ( s1 < s2) + else if ( s1 < s2) return -1; + else { - // seem to have the same length - - double rms1 = a.getRmsd(); - double rms2 = b.getRmsd(); - - if ( rms1 < rms2) - return 1; - if ( rms1 < rms2) - return -1; + double rms1 = a.getRmsd(); + double rms2 = b.getRmsd(); + return Double.compare(rms1, rms2); - return 0; +// if (rms1 < rms2) +// return 1; +// if (rms1 < rms2) +// return -1; +// +// return 0; + } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/AlternativeAlignment.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/AlternativeAlignment.java index f6f3073ab7..c5bd2e8e0b 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/AlternativeAlignment.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/AlternativeAlignment.java @@ -34,13 +34,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.vecmath.Matrix4d; import java.io.Serializable; import java.text.DecimalFormat; import java.util.List; - -import javax.vecmath.Matrix4d; - /** * Implements a class which handles one possible (alternative) solution. * @@ -67,17 +65,17 @@ public class AlternativeAlignment implements Serializable{ //short[] alig1; //short[] alig2; - private int nfrags; - private Atom center; - private Matrix rot; - private Atom tr; + private final int nfrags; + private final Atom center; + private final Matrix rot; + private final Atom tr; // the scores... private int gaps0; private int eqr0; - private int rms0; - private int joined; + private final int rms0; + private final int joined; private int percId; private int cluster; private float score; @@ -133,14 +131,8 @@ public String toString(){ d2.setMaximumIntegerDigits(3); d2.setMinimumFractionDigits(2); d2.setMaximumFractionDigits(2); - StringBuffer s = new StringBuffer(); - s.append("#" + getAltAligNumber() + - " cluster:" + cluster + - " eqr:" + getEqr() + - " rmsd:" + d2.format(getRmsd()) + - " %id:" + getPercId() + - " gaps:" + getGaps() + - " score:" + d2.format(score) ); + StringBuilder s = new StringBuilder(); + s.append("#").append(getAltAligNumber()).append(" cluster:").append(cluster).append(" eqr:").append(getEqr()).append(" rmsd:").append(d2.format(getRmsd())).append(" %id:").append(getPercId()).append(" gaps:").append(getGaps()).append(" score:").append(d2.format(score)); return s.toString(); } @@ -246,7 +238,7 @@ public void apairs_from_seed(int l,int i, int j){ for (int x = 0 ; x < l ; x++) { idx1[x]=i+x; idx2[x]=j+x; - aligpath[x] = new IndexPair((short)(i+x),(short)(j+x)); + aligpath[x] = new IndexPair((i+x),(j+x)); } } @@ -258,16 +250,14 @@ public void apairs_from_idxlst(JointFragments jf) { List il = jf.getIdxlist(); //System.out.println("Alt Alig apairs_from_idxlst"); - aligpath = new IndexPair[il.size()]; - idx1 = new int[il.size()]; - idx2 = new int[il.size()]; - for (int i =0 ; i < il.size();i++) { + int ils = il.size(); + aligpath = new IndexPair[ils]; + idx1 = new int[ils]; + idx2 = new int[ils]; + for (int i = 0; i < ils; i++) { int[] p = il.get(i); //System.out.print(" idx1 " + p[0] + " idx2 " + p[1]); - idx1[i] = p[0]; - idx2[i] = p[1]; - aligpath[i] = new IndexPair((short)p[0],(short)p[1]); - + aligpath[i] = new IndexPair(idx1[i] = p[0], idx2[i] = p[1]); } eqr0 = idx1.length; //System.out.println("eqr " + eqr0); @@ -293,24 +283,17 @@ public void setAltAligNumber(int fromia) { * @param ca */ private void rotateShiftAtoms(Atom[] ca){ - - for (int i = 0 ; i < ca.length; i++){ - Atom c = ca[i]; - - Calc.rotate(c,currentRotMatrix); - Calc.shift(c,currentTranMatrix); - //System.out.println("after " + c); - ca[i] = c; + for (Atom c : ca) { + Calc.rotate(c, currentRotMatrix); + Calc.shift(c, currentTranMatrix); } - //System.out.println("after " + ca[0]); } - public void finish(StrucAligParameters params,Atom[]ca1,Atom[]ca2) throws StructureException{ + public void finish(StrucAligParameters params,Atom[]ca1,Atom[]ca2) { Atom[] ca3 = new Atom[ca2.length]; for ( int i = 0 ; i < ca2.length;i++){ ca3[i] = (Atom) ca2[i].clone(); - } // do the inital superpos... @@ -318,7 +301,7 @@ public void finish(StrucAligParameters params,Atom[]ca1,Atom[]ca2) throws Struct rotateShiftAtoms(ca3); calcScores(ca1,ca2); - logger.debug("eqr " + eqr0 + " " + gaps0 + " " +idx1[0] + " " +idx1[1]); + //logger.debug("eqr " + eqr0 + " " + gaps0 + " " +idx1[0] + " " +idx1[1]); getPdbRegions(ca1,ca2); @@ -345,11 +328,11 @@ public static Matrix getDistanceMatrix(Atom[] ca1, Atom[]ca2){ return out; } - private Alignable getInitalStrCompAlignment( + private static Alignable getInitalStrCompAlignment( Atom[] ca1, - Atom[]ca2, + Atom[] ca2, StrucAligParameters params - ){ + ){ int rows = ca1.length; int cols = ca2.length; @@ -383,11 +366,8 @@ private Alignable getInitalStrCompAlignment( aligmat[0][j] = new AligMatEl(); Atom b1 = ca2[j]; - double d = 999; - - d = Calc.getDistance(a1,b1); - + double d = Calc.getDistance(a1,b1); AligMatEl e = new AligMatEl(); if (d > co) { e.setValue(0); @@ -453,10 +433,9 @@ private Alignable getInitalStrCompAlignment( * @param params the parameters * @param ca1 atoms of structure 1 * @param ca2 atoms of structure 2 - * @throws StructureException - */ + */ - public void refine(StrucAligParameters params,Atom[]ca1,Atom[]ca2) throws StructureException{ + public void refine(StrucAligParameters params,Atom[]ca1,Atom[]ca2) { // System.out.println("refine Alternative Alignment #"+ getAltAligNumber()+" l1:" + ca1.length + " l2:" + ca2.length); // for ( int i= 0 ; i < idx1.length;i++){ // System.out.println(idx1[i] + " " + idx2[i]); @@ -497,7 +476,7 @@ public void refine(StrucAligParameters params,Atom[]ca1,Atom[]ca2) throws Struct int maxiter = params.getMaxIter(); for (int iter = 0 ; iter< maxiter; iter++){ - float subscore = 0.0f; + float subscore; rotateShiftAtoms(ca3); @@ -515,10 +494,10 @@ public void refine(StrucAligParameters params,Atom[]ca1,Atom[]ca2) throws Struct // now for a superimposable permutation. First we need to check the size and // position of the quadrant left out by the optimal path - int firsta = path[0].getRow(); - int firstb = path[0].getCol(); - int lasta = path[pathsize-1].getRow(); - int lastb = path[pathsize-1].getCol(); + int firsta = path[0].row(); + int firstb = path[0].col(); + int lasta = path[pathsize-1].row(); + int lastb = path[pathsize-1].col(); int quada_beg, quada_end, quadb_beg,quadb_end; @@ -558,8 +537,7 @@ public void refine(StrucAligParameters params,Atom[]ca1,Atom[]ca2) throws Struct //System.out.println(s+" " +t); //double val = sim.get(s,t); - double val = aligmat[s][t].getValue(); - submat.set(s-quada_beg,t-quadb_beg,val); + submat.set(s-quada_beg,t-quadb_beg, aligmat[s][t].getValue()); } } // and perform a dp alignment again. (Note, that we fix the superposition). @@ -574,19 +552,15 @@ public void refine(StrucAligParameters params,Atom[]ca1,Atom[]ca2) throws Struct int subpathsize = subali.getPathSize(); for ( int p=0;p permsize){ IndexPair[] wholepath = new IndexPair[pathsize+subpathsize]; - for ( int t=0; t < pathsize; t++){ - wholepath[t] = path[t]; - } - for ( int t=0 ; t < subpathsize; t++){ - wholepath[t+pathsize] = subpath[t]; - } + System.arraycopy(path, 0, wholepath, 0, pathsize); + System.arraycopy(subpath, 0, wholepath, 0 + pathsize, subpathsize); pathsize += subpathsize; path = wholepath; ali.setPath(path); @@ -599,16 +573,12 @@ public void refine(StrucAligParameters params,Atom[]ca1,Atom[]ca2) throws Struct int j =0 ; //System.out.println("pathsize,path " + pathsize + " " + path.length); + double cutoffSqr = params.getEvalCutoff(); cutoffSqr*=cutoffSqr; + for (int i=0; i < pathsize; i++){ - int x = path[i].getRow(); - int y = path[i].getCol(); - //System.out.println(x+ " " + y); - double d = Calc.getDistance(ca1[x], ca3[y]); - //double d = dismat.get(x,y); + int x = path[i].row(), y = path[i].col(); // now we apply the evaluation distance cutoff - if ( d < params.getEvalCutoff()){ - //System.out.println("j:"+j+ " " + x+" " + y + " " + d ); - + if (Calc.getDistanceSqr(ca1[x], ca3[y]) < cutoffSqr){ idx1[j] = x; idx2[j] = y; j+=1; @@ -644,8 +614,6 @@ public void refine(StrucAligParameters params,Atom[]ca1,Atom[]ca2) throws Struct } - - idx1 = (int[]) FragmentJoiner.resizeArray(idx1,lenneu); idx2 = (int[]) FragmentJoiner.resizeArray(idx2,lenneu); // new ... get rms... @@ -663,30 +631,17 @@ private void getPdbRegions(Atom[] ca1, Atom[] ca2){ pdbresnum2 = new String[idx2.length]; for (int i =0 ; i < idx1.length;i++){ - Atom a1 = ca1[idx1[i]]; - Atom a2 = ca2[idx2[i]]; - Group p1 = a1.getGroup(); - Group p2 = a2.getGroup(); - Chain c1 = p1.getChain(); - Chain c2 = p2.getChain(); + Group p1 = ca1[idx1[i]].getGroup(); + Group p2 = ca2[idx2[i]].getGroup(); - String cid1 = c1.getId(); - String cid2 = c2.getId(); + String cid1 = p1.getChain().getId(); + String cid2 = p2.getChain().getId(); String pdb1 = p1.getResidueNumber().toString(); String pdb2 = p2.getResidueNumber().toString(); - - if ( ! cid1.equals(" ")) - pdb1 += ":" + cid1; - - - if ( ! cid2.equals(" ")) - pdb2 += ":" + cid2; - - - pdbresnum1[i] = pdb1; - pdbresnum2[i] = pdb2; + pdbresnum1[i] = !cid1.equals(" ") ? (pdb1 + ":" + cid1) : pdb1; + pdbresnum2[i] = !cid2.equals(" ") ? (pdb2 + ":" + cid2) : pdb2; } } @@ -726,16 +681,15 @@ public void setPDBresnum2(String[] pdbresnum2) { * @param i2 * @return the number of gaps in this alignment */ - private int count_gaps(int[] i1, int[] i2){ + private static int count_gaps(int[] i1, int[] i2){ int i0 = i1[0]; int j0 = i2[0]; int gaps = 0; for (int i =1 ; i fragments, FragmentPair public JointFragments[] approach_ap3(Atom[] ca1, Atom[] ca2, FragmentPair[] fraglst, - StrucAligParameters params) throws StructureException { + StrucAligParameters params) { //the final list of joined fragments stores as apairs - List fll = new ArrayList(); + List fll = new ArrayList<>(); FragmentPair[] tmpfidx = new FragmentPair[fraglst.length]; for ( int i=0 ; i < fraglst.length; i++){ @@ -200,22 +199,22 @@ public JointFragments[] approach_ap3(Atom[] ca1, Atom[] ca2, FragmentPair[] frag Comparator comp = new JointFragmentsComparator(); - Collections.sort(fll,comp); + fll.sort(comp); Collections.reverse(fll); int m = Math.min(params.getMaxrefine(),fll.size()); - List retlst = new ArrayList(); + List retlst = new ArrayList<>(); for ( int i = 0 ; i < m ; i++){ JointFragments jf = fll.get(i); retlst.add(jf); } - return retlst.toArray(new JointFragments[retlst.size()]); + return retlst.toArray(new JointFragments[0]); } - private boolean densityCheckOk(Atom[] aa1, Atom[] aa2, List idxlist, - int p2i, int p2j, int l2, - double densityCutoff) throws StructureException { + private static boolean densityCheckOk(Atom[] aa1, Atom[] aa2, List idxlist, + int p2i, int p2j, int l2, + double densityCutoff) { JointFragments ftmp = new JointFragments(); ftmp.setIdxlist(idxlist); ftmp.add(p2i,p2j,0,l2); @@ -244,9 +243,8 @@ private boolean densityCheckOk(Atom[] aa1, Atom[] aa2, List idxlist, * @param ca1subset * @param ca2subset * @return a double - * @throws StructureException */ - private double getDensity(Atom[] ca1subset, Atom[] ca2subset ) throws StructureException{ + private static double getDensity(Atom[] ca1subset, Atom[] ca2subset) { Atom centroid1 = Calc.getCentroid(ca1subset); Atom centroid2 = Calc.getCentroid(ca2subset); @@ -271,7 +269,7 @@ private double getDensity(Atom[] ca1subset, Atom[] ca2subset ) throws StructureE return Math.min(avd1,avd2); } - private double rmsCheck(Atom[] a1, Atom[] a2,List idxlist, int p2i, int p2j, int l2) throws StructureException { + private static double rmsCheck(Atom[] a1, Atom[] a2, List idxlist, int p2i, int p2j, int l2) { //System.out.println(dd); // check if a joint fragment has low rms ... @@ -293,11 +291,11 @@ private double rmsCheck(Atom[] a1, Atom[] a2,List idxlist, int p2i, int p * @param frag the JointFragments object that contains the list of identical positions * @return the rms */ - public static double getRMS(Atom[] ca1, Atom[]ca2,JointFragments frag) throws StructureException { + public static double getRMS(Atom[] ca1, Atom[]ca2,JointFragments frag) { // now svd ftmp and check if the rms is < X ... AlternativeAlignment ali = new AlternativeAlignment(); ali.apairs_from_idxlst(frag); - double rms = 999; + double rms; int[] idx1 = ali.getIdx1(); int[] idx2 = ali.getIdx2(); @@ -321,9 +319,9 @@ public static double getRMS(Atom[] ca1, Atom[]ca2,JointFragments frag) throws St return rms; } - public boolean angleCheckOk(FragmentPair a, FragmentPair b, float distcutoff){ + public static boolean angleCheckOk(FragmentPair a, FragmentPair b, float distcutoff){ - double dist = -999; + double dist; Atom v1 = a.getUnitv(); Atom v2 = b.getUnitv(); @@ -332,7 +330,7 @@ public boolean angleCheckOk(FragmentPair a, FragmentPair b, float distcutoff){ return dist <= distcutoff; } - private boolean distanceCheckOk(FragmentPair a, FragmentPair b, float fragCompatDist){ + private static boolean distanceCheckOk(FragmentPair a, FragmentPair b, float fragCompatDist){ double dd ; @@ -358,7 +356,7 @@ private boolean distanceCheckOk(FragmentPair a, FragmentPair b, float fragCompat * @param maxRefine max number of solutions to keep * @return JointFragments[] */ - public JointFragments[] frag_pairwise_compat(FragmentPair[] fraglst, int angleDiff, float fragCompatDist, int maxRefine ){ + public static JointFragments[] frag_pairwise_compat(FragmentPair[] fraglst, int angleDiff, float fragCompatDist, int maxRefine){ FragmentPair[] tmpfidx = new FragmentPair[fraglst.length]; @@ -372,7 +370,7 @@ public JointFragments[] frag_pairwise_compat(FragmentPair[] fraglst, int angleDi int[] used = new int[n]; //the final list of joined fragments stores as apairs - List fll = new ArrayList(); + List fll = new ArrayList<>(); double adiff = angleDiff * Math.PI / 180d; logger.debug("addiff" + adiff); @@ -440,21 +438,21 @@ public JointFragments[] frag_pairwise_compat(FragmentPair[] fraglst, int angleDi Comparator comp = new JointFragmentsComparator(); - Collections.sort(fll,comp); + fll.sort(comp); Collections.reverse(fll); int m = Math.min(maxRefine,fll.size()); - List retlst = new ArrayList(); + List retlst = new ArrayList<>(); for ( int i = 0 ; i < m ; i++){ JointFragments jf = fll.get(i); retlst.add(jf); } - return retlst.toArray(new JointFragments[retlst.size()]); + return retlst.toArray(new JointFragments[0]); } - public void extendFragments(Atom[] ca1, Atom[] ca2 ,JointFragments[] fragments, StrucAligParameters params) throws StructureException { + public void extendFragments(Atom[] ca1, Atom[] ca2 ,JointFragments[] fragments, StrucAligParameters params) { for(JointFragments p : fragments){ extendFragments(ca1, ca2, p, params); @@ -462,7 +460,7 @@ public void extendFragments(Atom[] ca1, Atom[] ca2 ,JointFragments[] fragments, } - public void extendFragments(Atom[] ca1, Atom[] ca2 , JointFragments fragments, StrucAligParameters params) throws StructureException { + public static void extendFragments(Atom[] ca1, Atom[] ca2, JointFragments fragments, StrucAligParameters params) { List pos = fragments.getIdxlist(); @@ -519,7 +517,7 @@ public void extendFragments(Atom[] ca1, Atom[] ca2 , JointFragments fragments, S } - private double testAdd(Atom[] ca1, Atom[] ca2, JointFragments fragments, int pstart1, int pstart2) throws StructureException { + private static double testAdd(Atom[] ca1, Atom[] ca2, JointFragments fragments, int pstart1, int pstart2) { JointFragments frag = new JointFragments(); frag.setIdxlist(fragments.getIdxlist()); @@ -555,11 +553,7 @@ else if ( s1 < s2){ return -1; } else{ - if ( rms1 < rms2) - return 1; - if ( rms1 > rms2) - return -1; - return 0; + return Double.compare(rms2, rms1); } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/Gotoh.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/Gotoh.java index d0b9752519..8292b6e28c 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/Gotoh.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/pairwise/Gotoh.java @@ -37,9 +37,9 @@ * @version %I% %G% */ public class Gotoh { - public static int ALIGFACTOR = 1000; // constant to shift floats to ints + public static final int ALIGFACTOR = 1000; // constant to shift floats to ints - Alignable a; + final Alignable a; int k,openPen,elgPen,rowDim,colDim,openVal,elgVal; @@ -209,9 +209,9 @@ private void setPath(){ int n; IndexPair[] backId = new IndexPair[a.getRows()+1+a.getCols()+1]; - List path = new ArrayList(); + List path = new ArrayList<>(); - backId[0] = new IndexPair((short)(a.getRows()),(short)(a.getCols())); + backId[0] = new IndexPair((a.getRows()),(a.getCols())); // backtrace, get backId indices, the indices in diagonal store in path @@ -222,13 +222,13 @@ private void setPath(){ n=1; - while ( (backId[n-1].getRow()>=1) && - (backId[n-1].getCol()>=1) + while ( (backId[n-1].row()>=1) && + (backId[n-1].col()>=1) ) { // get backtrace index - int x = backId[n-1].getRow(); - int y = backId[n-1].getCol(); + int x = backId[n-1].row(); + int y = backId[n-1].col(); try { @@ -256,8 +256,8 @@ private void setPath(){ System.exit(0); } // get diagonal indeces into path - if (((backId[n-1].getRow() - backId[n].getRow()) == 1) - && (( backId[n-1].getCol() - backId[n].getCol()) == 1)) { + if (((backId[n-1].row() - backId[n].row()) == 1) + && (( backId[n-1].col() - backId[n].col()) == 1)) { path.add(backId[n-1]); pathsize++; @@ -270,8 +270,7 @@ private void setPath(){ IndexPair[] newpath = new IndexPair[pathsize]; for (int i = 0 ; i < pathsize; i++){ IndexPair o = path.get(pathsize-1-i); - IndexPair np = new IndexPair((short)(o.getRow()-1),(short)(o.getCol()-1)); - newpath[i] = np; + newpath[i] = new IndexPair((o.row()-1), (o.col()-1)); } a.setPath(newpath); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/quaternary/QsAlign.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/quaternary/QsAlign.java index 355c76ea15..3b7e31951e 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/quaternary/QsAlign.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/quaternary/QsAlign.java @@ -20,40 +20,21 @@ */ package org.biojava.nbio.structure.align.quaternary; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import javax.vecmath.Matrix4d; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Calc; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureTools; -import org.biojava.nbio.structure.align.multiple.Block; -import org.biojava.nbio.structure.align.multiple.BlockImpl; -import org.biojava.nbio.structure.align.multiple.BlockSet; -import org.biojava.nbio.structure.align.multiple.BlockSetImpl; -import org.biojava.nbio.structure.align.multiple.MultipleAlignment; -import org.biojava.nbio.structure.align.multiple.MultipleAlignmentEnsembleImpl; -import org.biojava.nbio.structure.align.multiple.MultipleAlignmentImpl; +import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.align.multiple.*; import org.biojava.nbio.structure.align.multiple.util.MultipleAlignmentScorer; import org.biojava.nbio.structure.align.multiple.util.ReferenceSuperimposer; -import org.biojava.nbio.structure.cluster.Subunit; -import org.biojava.nbio.structure.cluster.SubunitCluster; -import org.biojava.nbio.structure.cluster.SubunitClusterer; -import org.biojava.nbio.structure.cluster.SubunitClustererParameters; -import org.biojava.nbio.structure.cluster.SubunitExtractor; +import org.biojava.nbio.structure.cluster.*; import org.biojava.nbio.structure.contact.Pair; import org.biojava.nbio.structure.geometry.SuperPositions; import org.biojava.nbio.structure.geometry.UnitQuaternions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.vecmath.Matrix4d; +import java.util.*; +import java.util.Map.Entry; + /** * Quaternary Structure Alignment (QS-Align). The algorithm takes as input two * protein structures at the quaternary structure level (multiple chains or @@ -83,7 +64,7 @@ public static QsAlignResult align(Structure s1, Structure s2, } public static QsAlignResult align(List s1, List s2, - SubunitClustererParameters cParams, QsAlignParameters aParams) + SubunitClustererParameters cParams, final QsAlignParameters aParams) throws StructureException { QsAlignResult result = new QsAlignResult(s1, s2); @@ -93,75 +74,81 @@ public static QsAlignResult align(List s1, List s2, List c1 = SubunitClusterer.cluster(s1, cParams).getClusters(); List c2 = SubunitClusterer.cluster(s2, cParams).getClusters(); + int c1s = c1.size(); + int c2s = c2.size(); + // STEP 2: match each subunit cluster between groups O(N^2*L^2) - inter - Map clusterMap = new HashMap(); - for (int i = 0; i < c1.size(); i++) { - for (int j = 0; j < c2.size(); j++) { + Map clusterMap = new HashMap<>(); + + for (int i = 0; i < c1s; i++) { + if (clusterMap.containsKey(i)) + continue; - if (clusterMap.keySet().contains(i)) - break; - if (clusterMap.values().contains(j)) + SubunitCluster ci = c1.get(i); + + for (int j = 0; j < c2s; j++) { + if (clusterMap.containsValue(j)) continue; // Use structural alignment to match the subunit clusters - if (c1.get(i).mergeStructure(c2.get(j),cParams)) { + if (ci.mergeStructure(c2.get(j),cParams)) clusterMap.put(i, j); - } } } - logger.info("Cluster Map: " + clusterMap.toString()); + logger.info("Cluster Map: {}", clusterMap); result.setClusters(c1); + final double aParamsCutOff = aParams.getdCutoff(); + final double maxOrientationAngle = aParams.getMaxOrientationAngle(); + // STEP 3: Align the assemblies for each cluster match O(N^2*L) - for (int globalKey : clusterMap.keySet()) { + for (Entry e : clusterMap.entrySet()) { + int globalKey = e.getKey(); // Obtain the clusters SubunitCluster clust1 = c1.get(globalKey); - SubunitCluster clust2 = c2.get(clusterMap.get(globalKey)); + SubunitCluster clust2 = c2.get(e.getValue()); // Take a cluster match as reference int index1 = 0; int index2 = clust1.size() - clust2.size(); - Map subunitMap = new HashMap(); + Map subunitMap = new HashMap<>(1); subunitMap.put(index1, index2); // Map cluster id to their subunit matching - Map> clustSubunitMap = new HashMap>(); + Map> clustSubunitMap = new HashMap<>(1); clustSubunitMap.put(globalKey, subunitMap); // Change order of key set so that globalKey is first - List keySet = new ArrayList(clusterMap.keySet()); + List keySet = new ArrayList<>(clusterMap.keySet()); keySet.remove((Integer) globalKey); keySet.add(0, globalKey); - for (int key : clusterMap.keySet()) { + for (Entry entry : clusterMap.entrySet()) { + int key = entry.getKey(); // Recover subunitMap if it is the reference, new one otherwise - if (key == globalKey) - subunitMap = clustSubunitMap.get(key); - else - subunitMap = new HashMap(); + subunitMap = key == globalKey ? clustSubunitMap.get(key) : new HashMap(); // Obtain the clusters of each subunit group clust1 = c1.get(key); - clust2 = c2.get(clusterMap.get(key)); + clust2 = c2.get(entry.getValue()); // Get the initial subunit indices of each group index1 = 0; index2 = clust1.size() - clust2.size(); for (int i = 0; i < index2; i++) { - for (int j = index2; j < clust1.size(); j++) { + if (subunitMap.containsKey(i)) + continue; - if (subunitMap.keySet().contains(i)) - break; - if (subunitMap.values().contains(j)) + for (int j = index2; j < clust1.size(); j++) { + if (subunitMap.containsValue(j)) continue; // Obtain cumulative transformation matrix - Matrix4d transform = getTransformForClusterSubunitMap( - c1, clustSubunitMap); + Matrix4d transform = getTransformForClusterSubunitMap(c1, clustSubunitMap); // Obtain Atom arrays of the subunit pair to match Atom[] atoms1 = clust1.getAlignedAtomsSubunit(i); @@ -174,11 +161,13 @@ public static QsAlignResult align(List s1, List s2, // 1- Check that the distance fulfills maximum double dCentroid = Calc.getDistance(centr1, centr2); - if (dCentroid > aParams.getdCutoff()) { - logger.debug(String.format("Subunit matching %d " - + "vs %d of cluster %d could not be " - + "matched, because centroid distance is " - + "%.2f", index1, index2, key, dCentroid)); + if (dCentroid > aParamsCutOff) { + if (logger.isDebugEnabled()) { + logger.debug(String.format("Subunit matching %d " + + "vs %d of cluster %d could not be " + + "matched, because centroid distance is " + + "%.2f", index1, index2, key, dCentroid)); + } continue; } @@ -191,28 +180,34 @@ public static QsAlignResult align(List s1, List s2, Calc.atomsToPoints(atoms1), Calc.atomsToPoints(atoms2c), false); qOrient = Math.min(Math.abs(2*Math.PI - qOrient), qOrient); - if (qOrient > aParams.getMaxOrientationAngle()) { - logger.debug(String.format("Subunit matching %d " - + "vs %d of cluster %d could not be " - + "matched, because orientation metric is " - + "%.2f", i, j, key, qOrient)); + if (qOrient > maxOrientationAngle) { + if (logger.isDebugEnabled()) { + logger.debug(String.format("Subunit matching %d " + + "vs %d of cluster %d could not be " + + "matched, because orientation metric is " + + "%.2f", i, j, key, qOrient)); + } continue; } // 3- Check the RMSD condition double rmsd = Calc.rmsd(atoms1, atoms2c); if (rmsd > aParams.getMaxRmsd()) { - logger.debug(String.format("Subunit matching %d " - + "vs %d of cluster %d could not be " - + "matched, because RMSD is %.2f", i, - j, key, rmsd)); + if (logger.isDebugEnabled()) { + logger.debug(String.format("Subunit matching %d " + + "vs %d of cluster %d could not be " + + "matched, because RMSD is %.2f", i, + j, key, rmsd)); + } continue; } - logger.info(String.format("Subunit matching %d vs %d" - + " of cluster %d with centroid distance %.2f" - + ", orientation metric %.2f and RMSD %.2f", - i, j, key, dCentroid, qOrient, rmsd)); + if (logger.isDebugEnabled()) { + logger.debug(String.format("Subunit matching %d vs %d" + + " of cluster %d with centroid distance %.2f" + + ", orientation metric %.2f and RMSD %.2f", + i, j, key, dCentroid, qOrient, rmsd)); + } subunitMap.put(i, j); } @@ -221,23 +216,23 @@ public static QsAlignResult align(List s1, List s2, clustSubunitMap.put(key, subunitMap); } - logger.info("Cluster Subunit Map: " + clustSubunitMap.toString()); + logger.info("Cluster Subunit Map: {}", clustSubunitMap); // Unfold the nested map into subunit map and alignment - subunitMap = new HashMap(); - List alignRes1 = new ArrayList(); - List alignRes2 = new ArrayList(); - List atomArray1 = new ArrayList(); - List atomArray2 = new ArrayList(); + subunitMap = new HashMap<>(); + List alignRes1 = new ArrayList<>(); + List alignRes2 = new ArrayList<>(); + List atomArray1 = new ArrayList<>(); + List atomArray2 = new ArrayList<>(); - for (int key : clustSubunitMap.keySet()) { + for (Entry> entry : clustSubunitMap.entrySet()) { // Obtain the cluster and the alignment in it - SubunitCluster cluster = c1.get(key); + SubunitCluster cluster = c1.get(entry.getKey()); List> clusterEqrs = cluster .getMultipleAlignment().getBlock(0).getAlignRes(); - for (Entry pair : clustSubunitMap.get(key) + for (Entry pair : entry.getValue() .entrySet()) { int i = pair.getKey(); @@ -264,17 +259,20 @@ public static QsAlignResult align(List s1, List s2, } // Evaluate the goodness of the match with an alignment object + + MultipleAlignmentEnsembleImpl msai = new MultipleAlignmentEnsembleImpl(); + msai.setAtomArrays(Arrays.asList( + atomArray1.toArray(Atom.EmptyAtomArray), + atomArray2.toArray(Atom.EmptyAtomArray)) + ); + MultipleAlignment msa = new MultipleAlignmentImpl(); - msa.setEnsemble(new MultipleAlignmentEnsembleImpl()); - msa.getEnsemble().setAtomArrays( - Arrays.asList(new Atom[][] { - atomArray1.toArray(new Atom[atomArray1.size()]), - atomArray2.toArray(new Atom[atomArray2.size()]) })); + msa.setEnsemble(msai); // Fill in the alignment information BlockSet bs = new BlockSetImpl(msa); Block b = new BlockImpl(bs); - List> alignRes = new ArrayList>(2); + List> alignRes = new ArrayList<>(2); alignRes.add(alignRes1); alignRes.add(alignRes2); b.setAlignRes(alignRes); @@ -286,11 +284,13 @@ public static QsAlignResult align(List s1, List s2, MultipleAlignmentScorer.calculateScores(msa); // If it is the best match found so far store it - if (subunitMap.size() > result.getSubunitMap().size()) { + int resultSubUnitMapSize = result.getSubunitMap().size(); + int subUnitMapSize = subunitMap.size(); + if (subUnitMapSize > resultSubUnitMapSize) { result.setSubunitMap(subunitMap); result.setAlignment(msa); - logger.info("Better result found: " + result.toString()); - } else if (subunitMap.size() == result.getSubunitMap().size()) { + logger.info("Better result found: {}", result); + } else if (subUnitMapSize == resultSubUnitMapSize) { if (result.getAlignment() == null) { result.setSubunitMap(subunitMap); result.setAlignment(msa); @@ -298,7 +298,7 @@ public static QsAlignResult align(List s1, List s2, .getRmsd()) { result.setSubunitMap(subunitMap); result.setAlignment(msa); - logger.info("Better result found: " + result.toString()); + logger.info("Better result found: {}", result); } } @@ -324,17 +324,17 @@ private static Pair getAlignedAtomsForClusterSubunitMap( List clusters, Map> clusterSubunitMap) { - List atomArray1 = new ArrayList(); - List atomArray2 = new ArrayList(); + List atomArray1 = new ArrayList<>(); + List atomArray2 = new ArrayList<>(); // For each cluster of subunits - for (int key : clusterSubunitMap.keySet()) { + for (Entry> entry : clusterSubunitMap.entrySet()) { // Obtain the cluster and the alignment in it - SubunitCluster cluster = clusters.get(key); + SubunitCluster cluster = clusters.get(entry.getKey()); // For each subunit matching in the cluster - for (Entry pair : clusterSubunitMap.get(key) + for (Entry pair : entry.getValue() .entrySet()) { int i = pair.getKey(); @@ -348,9 +348,9 @@ private static Pair getAlignedAtomsForClusterSubunitMap( } } - return new Pair( - atomArray1.toArray(new Atom[atomArray1.size()]), - atomArray2.toArray(new Atom[atomArray2.size()])); + return new Pair<>( + atomArray1.toArray(Atom.EmptyAtomArray), + atomArray2.toArray(Atom.EmptyAtomArray)); } /** @@ -364,12 +364,10 @@ private static Pair getAlignedAtomsForClusterSubunitMap( * @param clusterSubunitMap * map from cluster id to subunit matching * @return transformation matrix - * @throws StructureException */ private static Matrix4d getTransformForClusterSubunitMap( List clusters, - Map> clusterSubunitMap) - throws StructureException { + Map> clusterSubunitMap) { Pair pair = getAlignedAtomsForClusterSubunitMap(clusters, clusterSubunitMap); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/quaternary/QsAlignResult.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/quaternary/QsAlignResult.java index 68b0b4a4da..a4d4663b86 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/quaternary/QsAlignResult.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/quaternary/QsAlignResult.java @@ -20,20 +20,19 @@ */ package org.biojava.nbio.structure.align.quaternary; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import javax.vecmath.Matrix4d; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.align.multiple.MultipleAlignment; import org.biojava.nbio.structure.align.multiple.util.MultipleAlignmentScorer; import org.biojava.nbio.structure.cluster.Subunit; import org.biojava.nbio.structure.cluster.SubunitCluster; +import javax.vecmath.Matrix4d; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + /** * Result of a Quaternary Structure Alignment {@link QsAlign}. The QsAlignResult * holds the original inputs of the algorithm and the results and scores of the @@ -47,8 +46,8 @@ public class QsAlignResult { private List clusters; - private List subunits1; - private List subunits2; + private final List subunits1; + private final List subunits2; private Map subunitMap; private MultipleAlignment alignment; @@ -234,7 +233,7 @@ public void setAlignment(MultipleAlignment alignment) { */ public List getAlignedSubunits1() { - List aligned = new ArrayList(subunitMap.size()); + List aligned = new ArrayList<>(subunitMap.size()); for (Integer key : subunitMap.keySet()) aligned.add(subunits1.get(key)); @@ -250,10 +249,10 @@ public List getAlignedSubunits1() { */ public List getAlignedSubunits2() { - List aligned = new ArrayList(subunitMap.size()); + List aligned = new ArrayList<>(subunitMap.size()); - for (Integer key : subunitMap.keySet()) - aligned.add(subunits2.get(subunitMap.get(key))); + for (Integer integer : subunitMap.values()) + aligned.add(subunits2.get(integer)); return aligned; } @@ -295,10 +294,10 @@ public String toString() { + ", length=" + length() + ", Aligned 1: " - + getAlignedSubunits1().stream().map(s -> s.getName()) + + getAlignedSubunits1().stream().map(Subunit::getName) .collect(Collectors.toList()) + ", Aligned 2: " - + getAlignedSubunits2().stream().map(s -> s.getName()) + + getAlignedSubunits2().stream().map(Subunit::getName) .collect(Collectors.toList()) + "]"; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/quaternary/QsRelation.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/quaternary/QsRelation.java index e07ca0fff3..d289cee72a 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/quaternary/QsRelation.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/quaternary/QsRelation.java @@ -71,5 +71,5 @@ public enum QsRelation { * {@link #EQUIVALENT}, {@link #PARTIAL_COMPLETE} or * {@link #PARTIAL_INCOMPLETE}. */ - DIFFERENT; + DIFFERENT } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/seq/SmithWaterman3DParameters.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/seq/SmithWaterman3DParameters.java index 986bf3a8d3..74b8b891d5 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/seq/SmithWaterman3DParameters.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/seq/SmithWaterman3DParameters.java @@ -42,7 +42,7 @@ public SmithWaterman3DParameters() { @Override public List getUserConfigHelp() { - List params = new ArrayList(); + List params = new ArrayList<>(); params.add("The Gap open penalty"); params.add("The Gap extension penalty"); params.add("The maximum RMSD of superposition allowed"); @@ -54,7 +54,7 @@ public List getUserConfigHelp() { @Override public List getUserConfigParameterNames() { - List params = new ArrayList(); + List params = new ArrayList<>(); params.add("Gap Open"); params.add("Gap Extension"); params.add("Maximum RMSD"); @@ -65,7 +65,7 @@ public List getUserConfigParameterNames() { @Override public List getUserConfigParameters() { - List params = new ArrayList(); + List params = new ArrayList<>(); params.add("GapOpen"); params.add("GapExtend"); params.add("MaxRmsd"); @@ -77,7 +77,7 @@ public List getUserConfigParameters() { @Override @SuppressWarnings("rawtypes") public List getUserConfigTypes() { - List params = new ArrayList(); + List params = new ArrayList<>(); params.add(Short.class); params.add(Short.class); params.add(Double.class); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/seq/SmithWaterman3Daligner.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/seq/SmithWaterman3Daligner.java index 1a0597fd07..69a8a0769d 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/seq/SmithWaterman3Daligner.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/seq/SmithWaterman3Daligner.java @@ -23,11 +23,16 @@ import org.biojava.nbio.alignment.Alignments; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; import org.biojava.nbio.alignment.SimpleGapPenalty; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.alignment.template.PairwiseSequenceAligner; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SequencePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; +import org.biojava.nbio.core.exceptions.CompoundNotFoundException; +import org.biojava.nbio.core.sequence.ProteinSequence; +import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; +import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; +import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Group; import org.biojava.nbio.structure.StructureException; @@ -41,12 +46,6 @@ import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.util.AFPAlignmentDisplay; import org.biojava.nbio.structure.align.util.AlignmentTools; -import org.biojava.nbio.structure.align.util.ConfigurationException; -import org.biojava.nbio.core.exceptions.CompoundNotFoundException; -import org.biojava.nbio.core.sequence.ProteinSequence; -import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; -import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; -import org.biojava.nbio.core.sequence.template.Compound; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -77,7 +76,7 @@ public class SmithWaterman3Daligner extends AbstractStructureAlignment implement private static final String version = "1.1"; private SmithWaterman3DParameters params; - public static void main(String[] args) throws ConfigurationException { + public static void main(String[] args) { //args = new String[]{"-pdb1","1cdg.A","-pdb2","1tim.A","-pdbFilePath","/tmp/","-show3d","-printFatCat"}; UserArgumentProcessor processor = new SmithWatermanUserArgumentProcessor(); processor.process(args); @@ -112,8 +111,8 @@ public AFPChain align(Atom[] ca1, Atom[] ca2, Object parameters) String seq1 = StructureTools.convertAtomsToSeq(ca1); String seq2 = StructureTools.convertAtomsToSeq(ca2); - ProteinSequence s1 = null; - ProteinSequence s2 = null; + ProteinSequence s1; + ProteinSequence s2; try { s1 = new ProteinSequence(seq1); @@ -162,10 +161,9 @@ public AFPChain align(Atom[] ca1, Atom[] ca2, Object parameters) * @param smithWaterman pairwise Sequence aligner * @param pair The sequence alignment calculated by aligner * @return an AFPChain encapsulating the alignment in aligPair - * @throws StructureException */ private AFPChain convert(Atom[] ca1, Atom[] ca2, SequencePair pair, PairwiseSequenceAligner smithWaterman) throws StructureException { + AminoAcidCompound> pair, PairwiseSequenceAligner smithWaterman) { AFPChain afpChain = new AFPChain(algorithmName); int ca1Length = ca1.length; int ca2Length = ca2.length; @@ -184,7 +182,7 @@ private AFPChain convert(Atom[] ca1, Atom[] ca2, SequencePair aa1List = Arrays.asList(aa1); - public static Matrix getRotMax(AFPChain afpChain,Atom[] ca1,Atom[] ca2) throws StructureException{ + public static Matrix getRotMax(AFPChain afpChain,Atom[] ca1,Atom[] ca2) { Atom[] a1 = getAlignedAtoms1(afpChain,ca1); Atom[] a2 = getAlignedAtoms2(afpChain,ca2); @@ -76,7 +75,7 @@ public static Matrix getRotMax(AFPChain afpChain,Atom[] ca1,Atom[] ca2) throws S } - public static Atom getTranslation(AFPChain afpChain,Atom[] ca1,Atom[] ca2) throws StructureException{ + public static Atom getTranslation(AFPChain afpChain,Atom[] ca1,Atom[] ca2) { Atom[] a1 = getAlignedAtoms1(afpChain,ca1); @@ -90,7 +89,7 @@ public static Atom getTranslation(AFPChain afpChain,Atom[] ca1,Atom[] ca2) throw } public static Atom[] getAlignedAtoms1(AFPChain afpChain,Atom[] ca1){ - List atoms = new ArrayList(); + List atoms = new ArrayList<>(); int blockNum = afpChain.getBlockNum(); @@ -107,11 +106,11 @@ public static Atom[] getAlignedAtoms1(AFPChain afpChain,Atom[] ca1){ } } - return atoms.toArray(new Atom[atoms.size()]); + return atoms.toArray(Atom.EmptyAtomArray); } public static Atom[] getAlignedAtoms2(AFPChain afpChain,Atom[] ca2){ - List atoms = new ArrayList(); + List atoms = new ArrayList<>(); int blockNum = afpChain.getBlockNum(); @@ -128,7 +127,7 @@ public static Atom[] getAlignedAtoms2(AFPChain afpChain,Atom[] ca2){ } } - return atoms.toArray(new Atom[atoms.size()]); + return atoms.toArray(Atom.EmptyAtomArray); } @@ -233,7 +232,7 @@ public static void getAlign(AFPChain afpChain,Atom[] ca1,Atom[] ca2, boolean sho continue; } if(len > 0) { - lmax = (p1 - p1b - 1)>(p2 - p2b - 1)?(p1 - p1b - 1):(p2 - p2b - 1); + lmax = Math.max((p1 - p1b - 1), (p2 - p2b - 1)); for(k = 0; k < lmax; k ++) { if(k >= (p1 - p1b - 1)) alnseq1[len] = '-'; else { @@ -329,7 +328,7 @@ public static Map calcIdSimilarity(char[] seq1, char[] seq2, int if ( seq1 == null || seq2 == null){ logger.warn("Can't calc %ID for an empty alignment! "); - Map m = new HashMap(); + Map m = new HashMap<>(); m.put("similarity", similarity); m.put("identity", identity); return m; @@ -369,7 +368,7 @@ public static Map calcIdSimilarity(char[] seq1, char[] seq2, int similarity = (similarity) / eqr; identity = identity/eqr; } - Map m = new HashMap(); + Map m = new HashMap<>(); m.put("similarity", similarity); m.put("identity", identity); @@ -387,12 +386,10 @@ public static Map calcIdSimilarity(char[] seq1, char[] seq2, int * @throws NoSuchMethodException If an error occurs when invoking jmol * @throws InvocationTargetException If an error occurs when invoking jmol * @throws IllegalAccessException If an error occurs when invoking jmol - * @throws StructureException - */ + */ public static Structure createArtificalStructure(AFPChain afpChain, Atom[] ca1, Atom[] ca2) throws ClassNotFoundException, NoSuchMethodException, - InvocationTargetException, IllegalAccessException, StructureException - { + InvocationTargetException, IllegalAccessException { if ( afpChain.getNrEQR() < 1){ return GuiWrapper.getAlignedStructure(ca1, ca2); @@ -400,7 +397,7 @@ public static Structure createArtificalStructure(AFPChain afpChain, Atom[] ca1, Group[] twistedGroups = AlignmentTools.prepareGroupsForDisplay(afpChain,ca1, ca2); - List twistedAs = new ArrayList(); + List twistedAs = new ArrayList<>(); for ( Group g: twistedGroups){ if ( g == null ) @@ -410,23 +407,23 @@ public static Structure createArtificalStructure(AFPChain afpChain, Atom[] ca1, Atom a = g.getAtom(0); twistedAs.add(a); } - Atom[] twistedAtoms = twistedAs.toArray(new Atom[twistedAs.size()]); + Atom[] twistedAtoms = twistedAs.toArray(Atom.EmptyAtomArray); - List hetatms = new ArrayList(); - List nucs1 = new ArrayList(); + List hetatms = new ArrayList<>(); + List nucs1 = new ArrayList<>(); Group g1 = ca1[0].getGroup(); - Chain c1 = null; + Chain c1; if ( g1 != null) { c1 = g1.getChain(); if ( c1 != null){ - hetatms = c1.getAtomGroups(GroupType.HETATM);; + hetatms = c1.getAtomGroups(GroupType.HETATM); nucs1 = c1.getAtomGroups(GroupType.NUCLEOTIDE); } } - List hetatms2 = new ArrayList(); - List nucs2 = new ArrayList(); + List hetatms2 = new ArrayList<>(); + List nucs2 = new ArrayList<>(); Group g2 = ca2[0].getGroup(); - Chain c2 = null; + Chain c2; if ( g2 != null){ c2 = g2.getChain(); if ( c2 != null){ @@ -467,7 +464,7 @@ public static int getBlockNrForAlignPos(AFPChain afpChain, int aligPos){ if (len != 0) { // check for gapped region - int lmax = (p1 - p1b - 1)>(p2 - p2b - 1)?(p1 - p1b - 1):(p2 - p2b - 1); + int lmax = Math.max((p1 - p1b - 1), (p2 - p2b - 1)); for(int k = 0; k < lmax; k ++) { len++; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/AFPChainScorer.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/AFPChainScorer.java index 7453a38813..e711f3f4a9 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/AFPChainScorer.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/AFPChainScorer.java @@ -25,8 +25,6 @@ package org.biojava.nbio.structure.align.util; -import javax.vecmath.Matrix4d; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Calc; import org.biojava.nbio.structure.StructureException; @@ -35,6 +33,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.vecmath.Matrix4d; + public class AFPChainScorer { private static final Logger logger = LoggerFactory.getLogger(AFPChainScorer.class); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/AlignmentTools.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/AlignmentTools.java index f7660e2097..8763b19f8e 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/AlignmentTools.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/AlignmentTools.java @@ -33,6 +33,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.vecmath.Matrix4d; import java.io.IOException; import java.io.Writer; import java.util.*; @@ -40,8 +41,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import javax.vecmath.Matrix4d; - /** * Methods for analyzing and manipulating AFPChains and for * other pairwise alignment utilities.

    @@ -57,7 +56,7 @@ public class AlignmentTools { private static final Logger logger = LoggerFactory.getLogger(AlignmentTools.class); - public static boolean debug = false; + public static final boolean debug = false; /** * Checks that the alignment given by afpChain is sequential. This means @@ -157,7 +156,7 @@ public static boolean isSequentialAlignment(AFPChain afpChain, boolean checkWith * @throws StructureException If afpChain is not one-to-one */ public static Map alignmentAsMap(AFPChain afpChain) throws StructureException { - Map map = new HashMap(); + Map map = new HashMap<>(); if( afpChain.getAlnLength() < 1 ) { return map; @@ -189,7 +188,7 @@ public static Map alignmentAsMap(AFPChain afpChain) throws Str * function is undefined for that input. */ public static Map applyAlignment(Map alignmentMap, int k) { - return applyAlignment(alignmentMap, new IdentityMap(), k); + return applyAlignment(alignmentMap, new IdentityMap<>(), k); } /** @@ -223,11 +222,11 @@ public static Map applyAlignment(Map alignmentMap, Map ide if(k<0) throw new IllegalArgumentException("k must be positive"); if(k==1) { - return new HashMap(alignmentMap); + return new HashMap<>(alignmentMap); } // Convert to lists to establish a fixed order - List preimage = new ArrayList(alignmentMap.keySet()); // currently unmodified - List image = new ArrayList(preimage); + List preimage = new ArrayList<>(alignmentMap.keySet()); // currently unmodified + List image = new ArrayList<>(preimage); for(int n=1;n Map applyAlignment(Map alignmentMap, Map ide - Map imageMap = new HashMap(alignmentMap.size()); + Map imageMap = new HashMap<>(alignmentMap.size()); //TODO handle nulls consistently. // assure that all the residues in the domain are valid keys @@ -282,7 +281,7 @@ public static Map applyAlignment(Map alignmentMap, Map ide */ public static int getSymmetryOrder(Map alignment, final int maxSymmetry, final float minimumMetricChange) { - return getSymmetryOrder(alignment, new IdentityMap(), maxSymmetry, minimumMetricChange); + return getSymmetryOrder(alignment, new IdentityMap<>(), maxSymmetry, minimumMetricChange); } /** * Tries to detect symmetry in an alignment. @@ -321,8 +320,8 @@ public static int getSymmetryOrder(Map alignment, */ public static int getSymmetryOrder(Map alignment, Map identity, final int maxSymmetry, final float minimumMetricChange) { - List preimage = new ArrayList(alignment.keySet()); // currently unmodified - List image = new ArrayList(preimage); + List preimage = new ArrayList<>(alignment.keySet()); // currently unmodified + List image = new ArrayList<>(preimage); int bestSymmetry = 1; double bestMetric = Double.POSITIVE_INFINITY; //lower is better @@ -443,10 +442,10 @@ public static int getSymmetryOrder(AFPChain afpChain, int maxSymmetry, float min */ public static Map guessSequentialAlignment( Map alignment, boolean inverseAlignment) { - Map identity = new HashMap(); + Map identity = new HashMap<>(); - SortedSet aligned1 = new TreeSet(); - SortedSet aligned2 = new TreeSet(); + SortedSet aligned1 = new TreeSet<>(); + SortedSet aligned2 = new TreeSet<>(); for(Entry pair : alignment.entrySet()) { aligned1.add(pair.getKey()); @@ -480,18 +479,18 @@ public static Map guessSequentialAlignment( public static List>> getOptAlnAsList(AFPChain afpChain) { int[][][] optAln = afpChain.getOptAln(); int[] optLen = afpChain.getOptLen(); - List>> blocks = new ArrayList>>(afpChain.getBlockNum()); + List>> blocks = new ArrayList<>(afpChain.getBlockNum()); for(int blockNum=0;blockNum align1 = new ArrayList(optLen[blockNum]); - List align2 = new ArrayList(optLen[blockNum]); + List align1 = new ArrayList<>(optLen[blockNum]); + List align2 = new ArrayList<>(optLen[blockNum]); for(int pos=0;pos> block = new ArrayList>(2); + List> block = new ArrayList<>(2); block.add(align1); block.add(align2); blocks.add(block); @@ -559,13 +558,12 @@ public boolean containsKey(Object key) { * Must be the same length as aligned1. * @return An AFPChain representing the alignment. Many properties may be * null or another default. - * @throws StructureException if an error occured during superposition * @throws IllegalArgumentException if aligned1 and aligned2 have different * lengths * @see AlignmentTools#replaceOptAln(AFPChain, Atom[], Atom[], Map) */ public static AFPChain createAFPChain(Atom[] ca1, Atom[] ca2, - ResidueNumber[] aligned1, ResidueNumber[] aligned2 ) throws StructureException { + ResidueNumber[] aligned1, ResidueNumber[] aligned2 ) { //input validation int alnLen = aligned1.length; if(alnLen != aligned2.length) { @@ -627,7 +625,7 @@ public static AFPChain splitBlocksByTopology(AFPChain a, Atom[] ca1, Atom[] ca2) // Determine block lengths // Split blocks if residue indices don't increase monotonically - List newBlkLen = new ArrayList(); + List newBlkLen = new ArrayList<>(); boolean blockChanged = false; for(int blk=0;blk blocks = new ArrayList( newBlkLen.size() ); + List blocks = new ArrayList<>(newBlkLen.size()); int oldBlk = 0; int pos = 0; @@ -758,7 +756,7 @@ public static AFPChain replaceOptAln(AFPChain afpChain, Atom[] ca1, Atom[] ca2, // increasing monotonically. Integer[] res1 = alignment.keySet().toArray(new Integer[0]); Arrays.sort(res1); - List blockLens = new ArrayList(2); + List blockLens = new ArrayList<>(2); int optLength = 0; Integer lastRes = alignment.get(res1[0]); int blkLen = lastRes==null?0:1; @@ -989,17 +987,17 @@ public static Object resizeArray (Object oldArray, int newSize) { */ public static String toConciseAlignmentString(Map alignment, Map identity) { // Clone input to prevent changes - Map alig = new HashMap(alignment); + Map alig = new HashMap<>(alignment); // Generate inverse alignment - Map> inverse = new HashMap>(); + Map> inverse = new HashMap<>(); for(Entry e: alig.entrySet()) { S val = identity.get(e.getValue()); if( inverse.containsKey(val) ) { List l = inverse.get(val); l.add(e.getKey()); } else { - List l = new ArrayList(); + List l = new ArrayList<>(); l.add(e.getKey()); inverse.put(val,l); } @@ -1051,14 +1049,14 @@ public static String toConciseAlignmentString(Map alignment, Map * @see #toConciseAlignmentString(Map, Map) */ public static String toConciseAlignmentString(Map alignment) { - return toConciseAlignmentString(alignment, new IdentityMap()); + return toConciseAlignmentString(alignment, new IdentityMap<>()); } /** * @see #toConciseAlignmentString(Map, Map) */ public static Map fromConciseAlignmentString(String string) { - Map map = new HashMap(); + Map map = new HashMap<>(); boolean matches = true; while (matches) { Pattern pattern = Pattern.compile("(\\d+)>(\\d+)"); @@ -1093,23 +1091,15 @@ public static int[] calculateBlockGap(int[][][] optAln){ //Loop for every position in the block for (int j=0; j last1+1 || optAln[i][1][j] > last2+1){ + if (optAln[i][0][j] > last1 + 1 || optAln[i][1][j] > last2 + 1) { gaps++; - last1 = optAln[i][0][j]; - last2 = optAln[i][1][j]; } //Otherwise just set the last position to the current one - else{ - last1 = optAln[i][0][j]; - last2 = optAln[i][1][j]; - } } + last1 = optAln[i][0][j]; + last2 = optAln[i][1][j]; } blockGap[i] = gaps; } @@ -1199,9 +1189,9 @@ public static void alignmentToSIF(Writer out,AFPChain afpChain, * @return a list of Chains that is built up from the Atoms in the ca array * @throws StructureException */ - public static final List getAlignedModel(Atom[] ca){ + public static List getAlignedModel(Atom[] ca){ - List model = new ArrayList(); + List model = new ArrayList<>(); for ( Atom a: ca){ Group g = a.getGroup(); @@ -1209,7 +1199,8 @@ public static final List getAlignedModel(Atom[] ca){ Chain newChain = null; for ( Chain c : model) { - if ( c.getId().equals(parentC.getId())){ + String cid = c.getId(); + if ( cid!=null && cid.equals(parentC.getId())){ newChain = c; break; } @@ -1236,9 +1227,8 @@ public static final List getAlignedModel(Atom[] ca){ * @param ca1 * @param ca2 * @return a structure object containing two models, one for each set of Atoms. - * @throws StructureException */ - public static final Structure getAlignedStructure(Atom[] ca1, Atom[] ca2) throws StructureException{ + public static Structure getAlignedStructure(Atom[] ca1, Atom[] ca2) { /* Previous implementation commented @@ -1268,9 +1258,8 @@ public static final Structure getAlignedStructure(Atom[] ca1, Atom[] ca2) throws * @param ca1 * @param ca2 * @return an array of Groups that are transformed for 3D display - * @throws StructureException */ - public static Group[] prepareGroupsForDisplay(AFPChain afpChain, Atom[] ca1, Atom[] ca2) throws StructureException{ + public static Group[] prepareGroupsForDisplay(AFPChain afpChain, Atom[] ca1, Atom[] ca2) { if ( afpChain.getBlockRotationMatrix().length == 0 ) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/AtomCache.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/AtomCache.java index 4b7ba3f0fc..d5591981bf 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/AtomCache.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/AtomCache.java @@ -20,13 +20,7 @@ */ package org.biojava.nbio.structure.align.util; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.TreeSet; - +import org.biojava.nbio.core.util.Download; import org.biojava.nbio.core.util.InputStreamProvider; import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.client.StructureName; @@ -41,17 +35,19 @@ import org.biojava.nbio.structure.io.MMCIFFileReader; import org.biojava.nbio.structure.io.MMTFFileReader; import org.biojava.nbio.structure.io.PDBFileReader; -import org.biojava.nbio.core.util.FileDownloadUtils; +import org.biojava.nbio.structure.quaternary.BioAssemblyInfo; import org.biojava.nbio.structure.quaternary.BiologicalAssemblyBuilder; import org.biojava.nbio.structure.quaternary.BiologicalAssemblyTransformation; -import org.biojava.nbio.structure.scop.CachedRemoteScopInstallation; -import org.biojava.nbio.structure.scop.ScopDatabase; -import org.biojava.nbio.structure.scop.ScopDescription; -import org.biojava.nbio.structure.scop.ScopDomain; -import org.biojava.nbio.structure.scop.ScopFactory; +import org.biojava.nbio.structure.scop.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + /** * A utility class that provides easy access to Structure objects. If you are running a script that is frequently * re-using the same PDB structures, the AtomCache keeps an in-memory cache of the files for quicker access. The cache @@ -92,7 +88,8 @@ public class AtomCache { private String cachePath; // make sure IDs are loaded uniquely - private Collection currentlyLoading = Collections.synchronizedCollection(new TreeSet()); + //private final Collection currentlyLoading = Collections.newSetFromMap(new ConcurrentHashMap()); + private final Map map = new ConcurrentHashMap(); private String path; @@ -147,7 +144,7 @@ public AtomCache(String pdbFilePath, String cachePath) { fetchBehavior = FetchBehavior.DEFAULT; obsoleteBehavior = ObsoleteBehavior.DEFAULT; - currentlyLoading.clear(); +// currentlyLoading.clear(); params = new FileParsingParameters(); setUseMmCif(false); @@ -187,19 +184,8 @@ public Atom[] getAtoms(String name) throws IOException, StructureException { return getAtoms(new StructureName(name)); } public Atom[] getAtoms(StructureIdentifier name) throws IOException, StructureException { - - Atom[] atoms = null; - // System.out.println("loading " + name); - Structure s = getStructure(name); - - atoms = StructureTools.getAtomCAArray(s); - - /* - * synchronized (cache){ cache.put(name, atoms); } - */ - - return atoms; + return StructureTools.getAtomCAArray(getStructure(name)); } /** * Returns the representative atoms for the provided name. @@ -216,18 +202,7 @@ public Atom[] getRepresentativeAtoms(String name) throws IOException, StructureE } public Atom[] getRepresentativeAtoms(StructureIdentifier name) throws IOException, StructureException { - - Atom[] atoms = null; - - Structure s = getStructure(name); - - atoms = StructureTools.getRepresentativeAtomArray(s); - - /* - * synchronized (cache){ cache.put(name, atoms); } - */ - - return atoms; + return StructureTools.getRepresentativeAtomArray(getStructure(name)); } /** @@ -245,13 +220,12 @@ public Atom[] getRepresentativeAtoms(StructureIdentifier name) throws IOExceptio * @param multiModel if true the output Structure will be a multi-model one with one transformId per model, * if false the outputStructure will be as the original with added chains with renamed asymIds (in the form originalAsymId_transformId and originalAuthId_transformId). * @return a structure object - * @throws IOException * @throws StructureException if biassemblyId < 0 or other problems while loading structure * @author Peter Rose * @since 3.2 */ public Structure getBiologicalAssembly(String pdbId, int bioAssemblyId, boolean multiModel) - throws StructureException, IOException { + throws StructureException { if (bioAssemblyId < 0) { throw new StructureException("bioAssemblyID must be nonnegative: " + pdbId + " bioAssemblyId " @@ -275,7 +249,7 @@ public Structure getBiologicalAssembly(String pdbId, int bioAssemblyId, boolean // 0 ... asym unit if ( bioAssemblyId == 0) { - logger.info("Requested biological assembly 0 for PDB id "+pdbId+", returning asymmetric unit"); + logger.info("Requested biological assembly 0 for PDB id {} returning asymmetric unit", pdbId); return asymUnit; } // does it exist? @@ -313,21 +287,21 @@ public Structure getBiologicalAssembly(String pdbId, int bioAssemblyId, boolean * @param multiModel if true the output Structure will be a multi-model one with one transformId per model, * if false the outputStructure will be as the original with added chains with renamed asymIds (in the form originalAsymId_transformId and originalAuthId_transformId). * @return a structure object - * @throws IOException * @throws StructureException * @since 4.2 */ - public Structure getBiologicalAssembly(String pdbId, boolean multiModel) throws StructureException, IOException { + public Structure getBiologicalAssembly(String pdbId, boolean multiModel) throws StructureException { - boolean prevIsParseBioAssembly = getFileParsingParams().isParseBioAssembly(); + FileParsingParameters params = getFileParsingParams(); + boolean prevIsParseBioAssembly = params.isParseBioAssembly(); - if (!getFileParsingParams().isParseBioAssembly()) { - getFileParsingParams().setParseBioAssembly(true); + if (!params.isParseBioAssembly()) { + params.setParseBioAssembly(true); } Structure asymUnit = getStructureForPdbId(pdbId); - getFileParsingParams().setParseBioAssembly(prevIsParseBioAssembly); + params.setParseBioAssembly(prevIsParseBioAssembly); if (asymUnit.getPDBHeader() == null || asymUnit.getPDBHeader().getBioAssemblies()==null) { @@ -369,10 +343,9 @@ public Structure getBiologicalAssembly(String pdbId, boolean multiModel) throws * if false the outputStructure will be as the original with added chains with renamed asymIds (in the form originalAsymId_transformId and originalAuthId_transformId). * @return * @throws StructureException - * @throws IOException * @since 5.0 */ - public List getBiologicalAssemblies(String pdbId, boolean multiModel) throws StructureException, IOException { + public List getBiologicalAssemblies(String pdbId, boolean multiModel) throws StructureException { List assemblies = new ArrayList<>(); @@ -387,32 +360,30 @@ public List getBiologicalAssemblies(String pdbId, boolean multiModel) getFileParsingParams().setParseBioAssembly(prevIsParseBioAssembly); - if (asymUnit.getPDBHeader() == null || asymUnit.getPDBHeader().getBioAssemblies()==null) { + Map basms = asymUnit.getPDBHeader().getBioAssemblies(); + if (asymUnit.getPDBHeader() == null || basms ==null) { logger.info("No bioassembly information found for {}, returning asymmetric unit as the only biological assembly", pdbId); assemblies.add(asymUnit); return assemblies; } - for (int bioAssemblyId : asymUnit.getPDBHeader().getBioAssemblies().keySet()) { + for (Map.Entry e : basms.entrySet()) { List transformations = - asymUnit.getPDBHeader().getBioAssemblies().get(bioAssemblyId).getTransforms(); + e.getValue().getTransforms(); //assemblies.get(bioAssemblyId).getTransforms(); if ( transformations == null || transformations.size() == 0){ - - logger.info("Could not load transformations to recreate biological assembly id " + bioAssemblyId + " of " + pdbId+". Assembly id will be missing in biological assemblies."); + if (logger.isInfoEnabled()) + logger.info("Could not load transformations to recreate biological assembly id " + assemblies + " of " + pdbId+". Assembly id will be missing in biological assemblies."); continue; } - BiologicalAssemblyBuilder builder = new BiologicalAssemblyBuilder(); - // if we use mmcif or mmtf, then we need to pass useAsymIds=true - boolean useAsymIds = false; - if (useMmCif) useAsymIds = true; - if (useMmtf) useAsymIds = true; - Structure s = builder.rebuildQuaternaryStructure(asymUnit, transformations, useAsymIds, multiModel); - assemblies.add(s); + assemblies.add(new BiologicalAssemblyBuilder() + .rebuildQuaternaryStructure( + asymUnit, transformations, + useMmCif || useMmtf, multiModel)); } return assemblies; } @@ -492,9 +463,7 @@ public PDPProvider getPdpprovider() { * errors, eg for poorly formatted subranges. */ public Structure getStructure(String name) throws IOException, StructureException { - StructureName structureName = new StructureName(name); - - return getStructure(structureName); + return getStructure(new StructureName(name)); } /** @@ -510,8 +479,7 @@ public Structure getStructure(String name) throws IOException, StructureExceptio * @throws StructureException */ public Structure getStructure(StructureIdentifier strucId) throws IOException, StructureException { - Structure s = strucId.loadStructure(this); - Structure r = strucId.reduce(s); + Structure r = strucId.reduce(strucId.loadStructure(this)); r.setStructureIdentifier(strucId); return r; } @@ -522,10 +490,9 @@ public Structure getStructure(StructureIdentifier strucId) throws IOException, S * @param domain * a SCOP domain * @return a Structure object - * @throws IOException * @throws StructureException */ - public Structure getStructureForDomain(ScopDomain domain) throws IOException, StructureException { + public Structure getStructureForDomain(ScopDomain domain) throws StructureException { return getStructureForDomain(domain, ScopFactory.getSCOP()); } @@ -537,11 +504,10 @@ public Structure getStructureForDomain(ScopDomain domain) throws IOException, St * @param scopDatabase * A {@link ScopDatabase} to use * @return a Structure object - * @throws IOException * @throws StructureException */ - public Structure getStructureForDomain(ScopDomain domain, ScopDatabase scopDatabase) throws IOException, - StructureException { + public Structure getStructureForDomain(ScopDomain domain, ScopDatabase scopDatabase) throws + StructureException { return getStructureForDomain(domain, scopDatabase, false); } @@ -557,11 +523,10 @@ public Structure getStructureForDomain(ScopDomain domain, ScopDatabase scopDatab * domain belongs; if set to true, hetero-atoms are included if and only if they are strictly within the * definition (residue numbers) of the SCOP domain * @return a Structure object - * @throws IOException * @throws StructureException */ public Structure getStructureForDomain(ScopDomain domain, ScopDatabase scopDatabase, boolean strictLigandHandling) - throws IOException, StructureException { + throws StructureException { String pdbId = domain.getPdbId(); Structure fullStructure = getStructureForPdbId(pdbId); @@ -653,13 +618,11 @@ public Structure getStructureForDomain(String scopId) throws IOException, Struct * @param scopDatabase * A {@link ScopDatabase} to use * @return a Structure object - * @throws IOException * @throws StructureException */ - public Structure getStructureForDomain(String scopId, ScopDatabase scopDatabase) throws IOException, + public Structure getStructureForDomain(String scopId, ScopDatabase scopDatabase) throws StructureException { - ScopDomain domain = scopDatabase.getDomainByScopID(scopId); - return getStructureForDomain(domain, scopDatabase); + return getStructureForDomain(scopDatabase.getDomainByScopID(scopId), scopDatabase); } /** @@ -677,11 +640,9 @@ public void notifyShutdown() { // todo: use a SCOP implementation that is backed by SerializableCache ScopDatabase scopInstallation = ScopFactory.getSCOP(); - if (scopInstallation != null) { - if (scopInstallation instanceof CachedRemoteScopInstallation) { - CachedRemoteScopInstallation cacheScop = (CachedRemoteScopInstallation) scopInstallation; - cacheScop.flushCache(); - } + if (scopInstallation instanceof CachedRemoteScopInstallation) { + CachedRemoteScopInstallation cacheScop = (CachedRemoteScopInstallation) scopInstallation; + cacheScop.flushCache(); } } @@ -761,7 +722,7 @@ public void setFetchBehavior(FetchBehavior fetchBehavior) { * to a directory */ public void setPath(String path) { - this.path = FileDownloadUtils.expandUserHome(path); + this.path = Download.expandUserHome(path); } public void setPdpprovider(PDPProvider pdpprovider) { @@ -779,22 +740,23 @@ public boolean isUseMmCif() { * @param useMmCif * the useMmCif to set */ - public void setUseMmCif(boolean useMmCif) { + @Deprecated public void setUseMmCif(boolean useMmCif) { this.useMmCif = useMmCif; // Either way the user wants to use PDB or MMCIF this.useMmtf = false; + map.clear(); } /** * Set whether to use mmtf. * @param useMmtf the input boolean to set */ - public void setUseMmtf(boolean useMmtf) { + @Deprecated public void setUseMmtf(boolean useMmtf) { this.useMmtf = useMmtf; if(useMmtf){ useMmCif=false; } - + map.clear(); } /** Returns useMmtf flag @@ -805,23 +767,22 @@ public boolean isUseMmtf(){ return this.useMmtf; } - private boolean checkLoading(String name) { - return currentlyLoading.contains(name); - - } +// private boolean checkLoading(String name) { +// return currentlyLoading.contains(name); +// } /** * Returns a {@link Structure} corresponding to the CATH identifier supplied in {@code structureName}, using the the {@link CathDatabase} * at {@link CathFactory#getCathDatabase()}. */ - public Structure getStructureForCathDomain(StructureName structureName) throws IOException, StructureException { + public Structure getStructureForCathDomain(StructureName structureName) throws StructureException { return getStructureForCathDomain(structureName, CathFactory.getCathDatabase()); } /** * Returns a {@link Structure} corresponding to the CATH identifier supplied in {@code structureName}, using the specified {@link CathDatabase}. */ - public Structure getStructureForCathDomain(StructureName structureName, CathDatabase cathInstall) throws IOException, StructureException { + public Structure getStructureForCathDomain(StructureName structureName, CathDatabase cathInstall) throws StructureException { CathDomain cathDomain = cathInstall.getDomainByCathId(structureName.getIdentifier()); @@ -845,55 +806,55 @@ public Structure getStructureForCathDomain(StructureName structureName, CathData return n; } - protected void flagLoading(String name) { - if (!currentlyLoading.contains(name)) { - - currentlyLoading.add(name); - } - } - - protected void flagLoadingFinished(String name) { - - currentlyLoading.remove(name); - } +// protected void flagLoading(String name) { +// currentlyLoading.add(name); +// } +// +// protected void flagLoadingFinished(String name) { +// currentlyLoading.remove(name); +// } /** * Loads a structure directly by PDB ID * @param pdbId * @return - * @throws IOException * @throws StructureException */ - public Structure getStructureForPdbId(String pdbId) throws IOException, StructureException { + public Structure getStructureForPdbId(String pdbId) throws StructureException { + if(pdbId == null) return null; - if(pdbId.length() != 4) { + + if(pdbId.length() != 4) throw new StructureException("Unrecognized PDB ID: "+pdbId); - } - while (checkLoading(pdbId)) { - // waiting for loading to be finished... - try { - Thread.sleep(100); - } catch (InterruptedException e) { - logger.error(e.getMessage()); - } +// while (checkLoading(pdbId)) { +// // waiting for loading to be finished... +// +// try { +// Thread.sleep(100); +// } catch (InterruptedException e) { +// logger.error(e.getMessage()); +// } +// +// } - } - Structure s; - if (useMmtf) { - logger.debug("loading from mmtf"); - s = loadStructureFromMmtfByPdbId(pdbId); - } - else if (useMmCif) { - logger.debug("loading from mmcif"); - s = loadStructureFromCifByPdbId(pdbId); - } else { - logger.debug("loading from pdb"); - s = loadStructureFromPdbByPdbId(pdbId); - } - return s; + return map.computeIfAbsent(pdbId, p->{ + try { + if (useMmtf) + return loadStructureFromMmtfByPdbId(pdbId); + else if (useMmCif) + return loadStructureFromCifByPdbId(pdbId); + else + return loadStructureFromPdbByPdbId(pdbId); + } catch (Exception e) { + //TODO wrap exception e as a structure for storage in the cache + + e.printStackTrace(); + return null; + } + }); } /** @@ -907,35 +868,34 @@ private Structure loadStructureFromMmtfByPdbId(String pdbId) throws IOException MMTFFileReader reader = new MMTFFileReader(); reader.setFetchBehavior(fetchBehavior); reader.setObsoleteBehavior(obsoleteBehavior); - Structure structure = reader.getStructureById(pdbId.toLowerCase()); - return structure; + return reader.getStructureById(pdbId.toLowerCase()); } - protected Structure loadStructureFromCifByPdbId(String pdbId) throws IOException, StructureException { + protected Structure loadStructureFromCifByPdbId(String pdbId) throws IOException { logger.debug("Loading structure {} from mmCIF file {}.", pdbId, path); Structure s; - flagLoading(pdbId); - try { +// flagLoading(pdbId); +// try { MMCIFFileReader reader = new MMCIFFileReader(path); reader.setFetchBehavior(fetchBehavior); reader.setObsoleteBehavior(obsoleteBehavior); reader.setFileParsingParameters(params); s = reader.getStructureById(pdbId.toLowerCase()); - } finally { - flagLoadingFinished(pdbId); - } +// } finally { +// flagLoadingFinished(pdbId); +// } return s; } - protected Structure loadStructureFromPdbByPdbId(String pdbId) throws IOException, StructureException { + protected Structure loadStructureFromPdbByPdbId(String pdbId) throws IOException { logger.debug("Loading structure {} from PDB file {}.", pdbId, path); Structure s; - flagLoading(pdbId); - try { +// flagLoading(pdbId); +// try { PDBFileReader reader = new PDBFileReader(path); reader.setFetchBehavior(fetchBehavior); reader.setObsoleteBehavior(obsoleteBehavior); @@ -944,9 +904,9 @@ protected Structure loadStructureFromPdbByPdbId(String pdbId) throws IOException s = reader.getStructureById(pdbId.toLowerCase()); - } finally { - flagLoadingFinished(pdbId); - } +// } finally { +// flagLoadingFinished(pdbId); +// } return s; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/CliTools.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/CliTools.java index 97566c86b3..cb828bb7d4 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/CliTools.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/CliTools.java @@ -39,7 +39,6 @@ import java.beans.PropertyDescriptor; import java.io.*; import java.lang.reflect.Array; -import java.lang.reflect.InvocationTargetException; import java.util.*; /** @@ -100,14 +99,14 @@ public static String[] configureBean(Object bean, String[] args) throw new ConfigurationException("Couldn't get information for target bean " + ex.getMessage()); } - Map propertiesByName = new HashMap(); + Map propertiesByName = new HashMap<>(); for (PropertyDescriptor pd : bi.getPropertyDescriptors() ) { propertiesByName.put(pd.getName(), pd); } - List anonArgs = new ArrayList(); - Map> arrayProps = new HashMap>(); - Set usedProps = new HashSet(); + List anonArgs = new ArrayList<>(); + Map> arrayProps = new HashMap<>(); + Set usedProps = new HashSet<>(); boolean stdInUsed = false; boolean stdOutUsed = false; @@ -125,7 +124,7 @@ public static String[] configureBean(Object bean, String[] args) boolean arrayMode = false; Object propVal = null; - Class propType = null; + Class propType; if (pd == null) { if (arg.startsWith("-no")) { @@ -153,7 +152,7 @@ public static String[] configureBean(Object bean, String[] args) if (propType == Integer.TYPE) { try { - propVal = new Integer(args[++i]); + propVal = Integer.valueOf(args[++i]); } catch (Exception ex) { throw new ConfigurationException("Option " + arg + " requires an integer parameter"); } @@ -274,20 +273,14 @@ else if( val.equalsIgnoreCase("false") || val.equalsIgnoreCase("f")) //System.out.println("setting to: " + propVal + " " + propVal.getClass().getName()); if (arrayMode) { - List valList = arrayProps.get(pd); - if (valList == null) { - valList = new ArrayList(); - arrayProps.put(pd, valList); - } + List valList = arrayProps.computeIfAbsent(pd, k -> new ArrayList()); valList.add(propVal); } else { if (usedProps.contains(pd)) { throw new ConfigurationException("Multiple values supplied for " + pd.getName()); } try { - pd.getWriteMethod().invoke(bean, new Object[] {propVal}); - } catch (InvocationTargetException ex) { - throw new ConfigurationException("Error configuring '" + pd.getName() + "'"); + pd.getWriteMethod().invoke(bean, propVal); } catch (Exception ex) { throw new ConfigurationException("Error configuring '" + pd.getName() + "'"); } @@ -317,15 +310,13 @@ else if( val.equalsIgnoreCase("false") || val.equalsIgnoreCase("f")) valArray = vals.toArray((Object[]) Array.newInstance(compType, vals.size())); } try { - pd.getWriteMethod().invoke(bean, new Object[] {valArray}); - } catch (InvocationTargetException ex) { - throw new ConfigurationException("Error configuring '" + pd.getName() + "'"); + pd.getWriteMethod().invoke(bean, valArray); } catch (Exception ex) { throw new ConfigurationException("Error configuring '" + pd.getName() + "'"); } } - return anonArgs.toArray(new String[anonArgs.size()]); + return anonArgs.toArray(new String[0]); } /** diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/CollectionTools.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/CollectionTools.java index 45b7f38e56..5490f2d76d 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/CollectionTools.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/CollectionTools.java @@ -48,7 +48,7 @@ public static double[] toDoubleArray(Collection l) { } public static Object randomPick(Collection col) { - Object[] objs = col.toArray(new Object[col.size()]); + Object[] objs = col.toArray(new Object[0]); return objs[(int) Math.floor(Math.random() * objs.length)]; } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/RotationAxis.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/RotationAxis.java index 74b361ba87..1f53ff9fcf 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/RotationAxis.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/RotationAxis.java @@ -20,13 +20,6 @@ */ package org.biojava.nbio.structure.align.util; -import java.io.StringWriter; - -import javax.vecmath.AxisAngle4d; -import javax.vecmath.Matrix3d; -import javax.vecmath.Matrix4d; -import javax.vecmath.Vector3d; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.AtomImpl; import org.biojava.nbio.structure.Calc; @@ -36,6 +29,12 @@ import org.biojava.nbio.structure.geometry.Matrices; import org.biojava.nbio.structure.jama.Matrix; +import javax.vecmath.AxisAngle4d; +import javax.vecmath.Matrix3d; +import javax.vecmath.Matrix4d; +import javax.vecmath.Vector3d; +import java.io.StringWriter; + /** * Calculates the rotation axis for an alignment * diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/SynchronizedOutFile.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/SynchronizedOutFile.java index 9d05773c25..3c3f79b973 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/SynchronizedOutFile.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/SynchronizedOutFile.java @@ -30,10 +30,10 @@ public class SynchronizedOutFile { String[] tmp; - int ARR_SIZE=100; + final int ARR_SIZE=100; Integer counter; - boolean useGzipCompression = false; + boolean useGzipCompression; /** Create a thread safe wrapper for writing to this file, the file will be gzip compressed. @@ -62,7 +62,7 @@ public SynchronizedOutFile(File f, boolean gzipCompress) throws FileNotFoundExce * * @param f */ - public SynchronizedOutFile(File f) throws FileNotFoundException, IOException{ + public SynchronizedOutFile(File f) throws IOException{ this(f,false); @@ -98,7 +98,7 @@ private void writeArr() throws IOException{ OutputStream out = null; - FileOutputStream fileOutputStream=null; + FileOutputStream fileOutputStream; try { //This is less code-redundant fileOutputStream = new FileOutputStream(file, true); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/URLConnectionTools.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/URLConnectionTools.java index 9794bf3f1f..75f7b681ca 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/URLConnectionTools.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/URLConnectionTools.java @@ -27,13 +27,13 @@ package org.biojava.nbio.structure.align.util; +import org.biojava.nbio.core.util.Download; + import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; -import java.util.zip.GZIPInputStream; - /** @@ -90,72 +90,24 @@ public static URLConnection openURLConnection(URL url) throws IOException { */ public static InputStream getInputStream(URL url, int timeout) throws IOException { - return getInputStream(url,true, timeout); - } - - - /** - * Connect to a URL and return result as an InputStream. - * always asks for response to be in GZIP encoded - *

    - * The caller is responsible to close the returned InputStream not to cause - * resource leaks. - * @param url the input URL to be read - * @return an {@link InputStream} of response - * @throws IOException due to an error opening the URL - */ - public static InputStream getInputStream(URL url) throws IOException - { - return getInputStream(url,true, DEFAULT_CONNECTION_TIMEOUT); + return Download.stream(url, timeout); } - /** - * Open a URL and return an InputStream to it - * if acceptGzipEncoding == true, use GZIPEncoding to - * compress communication. - *

    - * The caller is responsible to close the returned InputStream not to cause - * resource leaks. - * @param url the input URL to be read - * @param acceptGzipEncoding whether to accept Gzip encoding - * @param timeout - * @return an {@link InputStream} of response - * @throws IOException due to an error opening the URL - */ - public static InputStream getInputStream(URL url, boolean acceptGzipEncoding, int timeout) throws IOException { - InputStream inStream = null ; - URLConnection huc = URLConnectionTools.openURLConnection(url,timeout); - - if ( acceptGzipEncoding) huc.setRequestProperty("Accept-Encoding", "gzip"); - - String contentEncoding = huc.getContentEncoding(); - - inStream = huc.getInputStream(); - - if (contentEncoding != null) { - if (contentEncoding.contains("gzip")) { - inStream = new GZIPInputStream(inStream); - } - } - - return inStream; - - } - - /** - * Do a POST to a URL and return the response stream for further processing elsewhere. - *

    - * The caller is responsible to close the returned InputStream not to cause - * resource leaks. - * @param url the input URL to be read - * @param data the post data - * @return an {@link InputStream} of response - * @throws IOException due to an error opening the URL - */ - public static InputStream doPOST(URL url, String data) throws IOException - { - return doPOST(url,data,DEFAULT_CONNECTION_TIMEOUT); - } +// +// /** +// * Do a POST to a URL and return the response stream for further processing elsewhere. +// *

    +// * The caller is responsible to close the returned InputStream not to cause +// * resource leaks. +// * @param url the input URL to be read +// * @param data the post data +// * @return an {@link InputStream} of response +// * @throws IOException due to an error opening the URL +// */ +// public static InputStream doPOST(URL url, String data) throws IOException +// { +// return doPOST(url,data,DEFAULT_CONNECTION_TIMEOUT); +// } /** * Do a POST to a URL and return the response stream for further processing elsewhere. diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/UserConfiguration.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/UserConfiguration.java index e23f8e6db1..da03a26a6a 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/UserConfiguration.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/util/UserConfiguration.java @@ -19,11 +19,11 @@ package org.biojava.nbio.structure.align.util; +import org.biojava.nbio.core.util.PrettyXMLWriter; +import org.biojava.nbio.core.util.XMLWriter; import org.biojava.nbio.structure.align.ce.StartupParameters; import org.biojava.nbio.structure.io.LocalPDBDirectory.FetchBehavior; import org.biojava.nbio.structure.io.LocalPDBDirectory.ObsoleteBehavior; -import org.biojava.nbio.core.util.PrettyXMLWriter; -import org.biojava.nbio.core.util.XMLWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -55,15 +55,15 @@ public class UserConfiguration public static final String lineSplit = System.getProperty("file.separator"); - private String pdbFilePath; - private String cacheFilePath; + @Deprecated private String pdbFilePath; + @Deprecated private String cacheFilePath; private FetchBehavior fetchBehavior; private ObsoleteBehavior obsoleteBehavior; private String fileFormat; - private static AtomicBoolean warningShown = new AtomicBoolean(false); + private static final AtomicBoolean warningShown = new AtomicBoolean(false); /** @@ -103,7 +103,7 @@ public UserConfiguration(){ private String initPdbFilePath() { - String path = null; + String path; String propertyName = PDB_DIR; @@ -174,7 +174,7 @@ private String initPdbFilePath() { private String initCacheFilePath() { - String path = null; + String path; String propertyName = PDB_CACHE_DIR; @@ -320,8 +320,8 @@ public XMLWriter toXML(XMLWriter xw) if (! pdbFilePath.equals(tempdir)) xw.attribute("path", pdbFilePath); - xw.attribute("fetchBehavior", fetchBehavior+""); - xw.attribute("obsoleteBehavior", obsoleteBehavior+""); + xw.attribute("fetchBehavior", String.valueOf(fetchBehavior)); + xw.attribute("obsoleteBehavior", String.valueOf(obsoleteBehavior)); xw.attribute("fileFormat", fileFormat); xw.closeTag("PDBFILEPATH"); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/AFPChainFlipper.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/AFPChainFlipper.java index 5ace60fc8f..231c82581f 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/AFPChainFlipper.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/AFPChainFlipper.java @@ -26,7 +26,6 @@ import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Calc; -import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.jama.Matrix; @@ -40,7 +39,7 @@ public class AFPChainFlipper { * @param o ... the original AFPCHain that should be flipped * @return a cloned AFPCHain which the positions of name1 and name2 flipped. */ - public static AFPChain flipChain(AFPChain o) throws StructureException{ + public static AFPChain flipChain(AFPChain o) { AFPChain n = new AFPChain(o.getAlgorithmName()); n.setVersion(o.getVersion()); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/AFPChainXMLConverter.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/AFPChainXMLConverter.java index f8be1609c8..9de9e327c8 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/AFPChainXMLConverter.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/AFPChainXMLConverter.java @@ -20,12 +20,12 @@ */ package org.biojava.nbio.structure.align.xml; +import org.biojava.nbio.core.util.PrettyXMLWriter; import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.util.AlignmentTools; import org.biojava.nbio.structure.jama.Matrix; -import org.biojava.nbio.core.util.PrettyXMLWriter; import java.io.IOException; import java.io.PrintWriter; @@ -237,11 +237,11 @@ public static void printXMLHeader(PrettyXMLWriter xml, AFPChain afpChain) throws xml.attribute("name2", afpChain.getName2()); xml.attribute("method", afpChain.getAlgorithmName()); xml.attribute("version" , afpChain.getVersion()); - xml.attribute("alnLength", afpChain.getAlnLength() + ""); - xml.attribute("blockNum", afpChain.getBlockNum() + ""); - xml.attribute("gapLen", afpChain.getGapLen() + ""); - xml.attribute("optLength", afpChain.getOptLength() + ""); - xml.attribute("totalLenIni", afpChain.getTotalLenIni() + ""); + xml.attribute("alnLength", String.valueOf(afpChain.getAlnLength())); + xml.attribute("blockNum", String.valueOf(afpChain.getBlockNum())); + xml.attribute("gapLen", String.valueOf(afpChain.getGapLen())); + xml.attribute("optLength", String.valueOf(afpChain.getOptLength())); + xml.attribute("totalLenIni", String.valueOf(afpChain.getTotalLenIni())); xml.attribute("alignScore", String.format("%5.2f", afpChain.getAlignScore() ).trim()); xml.attribute("chainRmsd", String.format("%5.2f", afpChain.getChainRmsd() ).trim()); @@ -250,13 +250,13 @@ public static void printXMLHeader(PrettyXMLWriter xml, AFPChain afpChain) throws xml.attribute("probability", String.format("%.2e", afpChain.getProbability() ).trim()); xml.attribute("similarity", String.format("%5.4f", afpChain.getSimilarity() ).trim()); - xml.attribute("similarity1", afpChain.getCoverage1() + ""); - xml.attribute("similarity2", afpChain.getCoverage2() + ""); + xml.attribute("similarity1", String.valueOf(afpChain.getCoverage1())); + xml.attribute("similarity2", String.valueOf(afpChain.getCoverage2())); xml.attribute("totalRmsdIni", String.format("%5.2f",afpChain.getTotalRmsdIni() ).trim()); xml.attribute("totalRmsdOpt", String.format("%5.2f",afpChain.getTotalRmsdOpt() ).trim()); - xml.attribute("ca1Length", afpChain.getCa1Length()+""); - xml.attribute("ca2Length", afpChain.getCa2Length()+""); - xml.attribute("afpNum",afpChain.getAfpSet().size()+""); + xml.attribute("ca1Length", String.valueOf(afpChain.getCa1Length())); + xml.attribute("ca2Length", String.valueOf(afpChain.getCa2Length())); + xml.attribute("afpNum", String.valueOf(afpChain.getAfpSet().size())); xml.attribute("alignScoreUpdate",String.format("%5.2f",afpChain.getAlignScoreUpdate()).trim()); xml.attribute("time", String.format("%d",afpChain.getCalculationTime())); if ( afpChain.getTMScore() != -1){ diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/AFPChainXMLParser.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/AFPChainXMLParser.java index 0827134bbe..eb77f56bd1 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/AFPChainXMLParser.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/AFPChainXMLParser.java @@ -61,7 +61,7 @@ public class AFPChainXMLParser * @param ca2 * @return */ - public static AFPChain fromXML(String xml, String name1, String name2, Atom[] ca1, Atom[] ca2) throws IOException, StructureException{ + public static AFPChain fromXML(String xml, String name1, String name2, Atom[] ca1, Atom[] ca2) throws IOException { AFPChain[] afps = parseMultiXML( xml); if ( afps.length > 0 ) { @@ -223,7 +223,7 @@ public static void rebuildAFPChain(AFPChain afpChain, Atom[] ca1, Atom[] ca2){ } public static AFPChain[] parseMultiXML(String xml) throws IOException { - List afpChains = new ArrayList(); + List afpChains = new ArrayList<>(); try { @@ -273,7 +273,7 @@ public static AFPChain[] parseMultiXML(String xml) throws IOException { a.setAlignScore(Double.parseDouble(getAttribute(rootElement,"alignScore"))); a.setChainRmsd(Double.parseDouble(getAttribute(rootElement,"chainRmsd"))); - Double identity = Double.parseDouble(getAttribute(rootElement,"identity")); + double identity = Double.parseDouble(getAttribute(rootElement,"identity")); a.setIdentity(identity); a.setNormAlignScore(Double.parseDouble(getAttribute(rootElement,"normAlignScore"))); @@ -298,7 +298,7 @@ public static AFPChain[] parseMultiXML(String xml) throws IOException { } String calcTimeS = getAttribute(rootElement,"time"); - Long calcTime = -1L; + long calcTime = -1L; if ( calcTimeS != null){ try { @@ -316,7 +316,7 @@ public static AFPChain[] parseMultiXML(String xml) throws IOException { a.setBlockShiftVector(blockShiftVector); int afpNum = Integer.parseInt(getAttribute(rootElement,"afpNum")); - List afpSet = new ArrayList(); + List afpSet = new ArrayList<>(); for (int afp=0;afp parseXMLfile(String xml) throws ParserConfigurationException, SAXException, IOException { List ensembles = - new ArrayList(); + new ArrayList<>(); //Convert string to XML document DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); @@ -113,14 +104,16 @@ public static MultipleAlignmentEnsemble parseEnsemble(Node root){ for (int i=0; i transforms = new ArrayList(); + List transforms = new ArrayList<>(); NodeList children = root.getChildNodes(); for (int i=0; i> alignRes = new ArrayList>(); + List> alignRes = new ArrayList<>(); b.setAlignRes(alignRes); NodeList children = root.getChildNodes(); @@ -195,14 +190,14 @@ public static Block parseBlock(Node root, BlockSet blockSet) { while (node!=null){ if (alignRes.size() < str) { - alignRes.add(new ArrayList()); + alignRes.add(new ArrayList<>()); } String residue = node.getTextContent(); if (residue.equals("null")){ alignRes.get(str-1).add(null); } else { - alignRes.get(str-1).add(new Integer(residue)); + alignRes.get(str-1).add(Integer.valueOf(residue)); } str++; @@ -264,19 +259,19 @@ public static void parseHeader(Node node, String ioTime = atts.getNamedItem("IOTime").getTextContent(); if (!ioTime.equals("null")){ - ensemble.setIoTime(new Long(ioTime)); + ensemble.setIoTime(Long.valueOf(ioTime)); } String time = atts.getNamedItem("CalculationTime").getTextContent(); if (!time.equals("null")){ - ensemble.setCalculationTime(new Long(time)); + ensemble.setCalculationTime(Long.valueOf(time)); } } public static void parseStructures(Node root, MultipleAlignmentEnsemble ensemble) { - List names = new ArrayList(); + List names = new ArrayList<>(); ensemble.setStructureIdentifiers(names); NamedNodeMap atts = root.getAttributes(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/PdbPairXMLConverter.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/PdbPairXMLConverter.java index 433e053a3c..ca7292356f 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/PdbPairXMLConverter.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/PdbPairXMLConverter.java @@ -20,9 +20,9 @@ */ package org.biojava.nbio.structure.align.xml; +import org.biojava.nbio.core.util.PrettyXMLWriter; import org.biojava.nbio.structure.align.client.PdbPair; import org.biojava.nbio.structure.align.fatcat.FatCatRigid; -import org.biojava.nbio.core.util.PrettyXMLWriter; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; @@ -44,7 +44,7 @@ public class PdbPairXMLConverter { public static final String DEFAULT_METHOD_NAME = FatCatRigid.algorithmName; public static PdbPairsMessage convertXMLtoPairs(String xml) { - SortedSet pairs = new TreeSet(); + SortedSet pairs = new TreeSet<>(); PdbPairsMessage message = new PdbPairsMessage(); try { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/PdbPairsMessage.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/PdbPairsMessage.java index 170ee5ff47..6aa415a8d9 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/PdbPairsMessage.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/PdbPairsMessage.java @@ -40,7 +40,7 @@ public PdbPairsMessage(){ method = PdbPairXMLConverter.DEFAULT_METHOD_NAME; - pairs = new TreeSet(); + pairs = new TreeSet<>(); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/RepresentativeXMLConverter.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/RepresentativeXMLConverter.java index dccec37fb3..ff713b592a 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/RepresentativeXMLConverter.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/align/xml/RepresentativeXMLConverter.java @@ -39,7 +39,7 @@ public class RepresentativeXMLConverter { - public static final String toXML(SortedSet representatives){ + public static String toXML(SortedSet representatives){ StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); @@ -59,8 +59,8 @@ public static final String toXML(SortedSet representatives){ return sw.toString(); } - public static final SortedSet fromXML(String xml){ - SortedSet representatives = new TreeSet(); + public static SortedSet fromXML(String xml){ + SortedSet representatives = new TreeSet<>(); try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder db = factory.newDocumentBuilder(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/asa/AsaCalculator.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/asa/AsaCalculator.java index 19ece0ab72..02a2581fcc 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/asa/AsaCalculator.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/asa/AsaCalculator.java @@ -59,9 +59,9 @@ public class AsaCalculator { * The default value for number of sphere points to sample. * See this paper for a nice study on the effect of this parameter: https://f1000research.com/articles/5-189/v1 */ - public static final int DEFAULT_N_SPHERE_POINTS = 1000; +// public static final int DEFAULT_N_SPHERE_POINTS = 1000; public static final double DEFAULT_PROBE_SIZE = 1.4; - public static final int DEFAULT_NTHREADS = 1; +// public static final int DEFAULT_NTHREADS = 1; private static final boolean DEFAULT_USE_SPATIAL_HASHING = true; @@ -86,8 +86,8 @@ public class AsaCalculator { private class AsaCalcWorker implements Runnable { - private int i; - private double[] asas; + private final int i; + private final double[] asas; public AsaCalcWorker(int i, double[] asas) { this.i = i; @@ -101,11 +101,11 @@ public void run() { } - private Point3d[] atomCoords; - private Atom[] atoms; - private double[] radii; - private double probe; - private int nThreads; + private final Point3d[] atomCoords; + private final Atom[] atoms; + private final double[] radii; + private final double probe; + private final int nThreads; private Point3d[] spherePoints; private double cons; private int[][] neighborIndices; @@ -243,7 +243,7 @@ public GroupAsa[] getGroupAsas() { } } - return asas.values().toArray(new GroupAsa[asas.size()]); + return asas.values().toArray(new GroupAsa[0]); } /** @@ -347,7 +347,7 @@ void setUseSpatialHashingForNeighbors(boolean useSpatialHashingForNeighbors) { * @param nSpherePoints the number of points to be used in generating the spherical dot-density * @return */ - private Point3d[] generateSpherePoints(int nSpherePoints) { + private static Point3d[] generateSpherePoints(int nSpherePoints) { Point3d[] points = new Point3d[nSpherePoints]; double inc = Math.PI * (3.0 - Math.sqrt(5.0)); double offset = 2.0 / nSpherePoints; @@ -458,7 +458,7 @@ Point3d[] getAtomCoords() { private List calcContacts() { if (atomCoords.length == 0) - return new ArrayList<>(); + return Collections.EMPTY_LIST;//new ArrayList<>(); double maxRadius = 0; OptionalDouble optionalDouble = Arrays.stream(radii).max(); if (optionalDouble.isPresent()) @@ -480,11 +480,14 @@ private double calcSingleAsa(int i) { int n_accessible_point = 0; + Point3d test_point = new Point3d(); + for (Point3d point: spherePoints){ boolean is_accessible = true; - Point3d test_point = new Point3d(point.x*radius + atom_i.x, - point.y*radius + atom_i.y, - point.z*radius + atom_i.z); + test_point.set( + point.x*radius + atom_i.x, + point.y*radius + atom_i.y, + point.z*radius + atom_i.z); int[] cycled_indices = new int[n_neighbor]; int arind = 0; @@ -498,9 +501,9 @@ private double calcSingleAsa(int i) { } for (int j: cycled_indices) { - Point3d atom_j = atomCoords[neighbor_indices[j]]; - double r = radii[neighbor_indices[j]] + probe; - double diff_sq = test_point.distanceSquared(atom_j); + int jj = neighbor_indices[j]; + double r = radii[jj] + probe; + double diff_sq = test_point.distanceSquared(atomCoords[jj]); if (diff_sq < r*r) { j_closest_neighbor = j; is_accessible = false; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/asa/GroupAsa.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/asa/GroupAsa.java index 05d34b8d21..431405d62c 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/asa/GroupAsa.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/asa/GroupAsa.java @@ -44,7 +44,7 @@ public class GroupAsa implements Serializable { private static HashMap initTriPeptAsas() { // ASA in extended tripeptide conformation (GLY-X-GLY) from Miller et al JMB 1987 (for calculation of relative ASAs) - HashMap map = new HashMap(); + HashMap map = new HashMap<>(); map.put('A', 113.0); map.put('R', 241.0); map.put('N', 158.0); @@ -71,7 +71,7 @@ private static HashMap initTriPeptAsas() { - private Group g; + private final Group g; /** * ASA of uncomplexed residue @@ -223,14 +223,10 @@ public Object clone() { GroupAsa n = new GroupAsa(this.g); n.setAsaC(this.getAsaC()); n.setAsaU(this.getAsaU()); - n.atomAsaUs = new ArrayList(this.atomAsaUs.size()); - n.atomAsaCs = new ArrayList(this.atomAsaCs.size()); - for (int i=0;i(this.atomAsaUs.size()); + n.atomAsaCs = new ArrayList<>(this.atomAsaCs.size()); + n.atomAsaUs.addAll(this.atomAsaUs); + n.atomAsaCs.addAll(this.atomAsaCs); return n; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/basepairs/BasePairParameters.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/basepairs/BasePairParameters.java index 6427447d75..826fcf648a 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/basepairs/BasePairParameters.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/basepairs/BasePairParameters.java @@ -21,34 +21,25 @@ */ package org.biojava.nbio.structure.basepairs; -import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Chain; import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.Atom; +import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.contact.Pair; import org.biojava.nbio.structure.geometry.SuperPosition; import org.biojava.nbio.structure.geometry.SuperPositionQCP; import org.biojava.nbio.structure.io.PDBFileReader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.vecmath.Matrix4d; import javax.vecmath.Point3d; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.Serializable; -import java.util.List; -import java.util.Arrays; -import java.util.ArrayList; -import java.util.Map; -import java.util.HashMap; +import java.util.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static java.lang.Math.sin; -import static java.lang.Math.cos; -import static java.lang.Math.atan2; -import static java.lang.Math.acos; -import static java.lang.Math.PI; +import static java.lang.Math.*; /** * This module calculates the el Hassan-Calladine Base Pairing and Base-pair Step Parameters for any nucleic @@ -70,7 +61,7 @@ public class BasePairParameters implements Serializable { private static final long serialVersionUID = 6214502385L; - private static Logger log = LoggerFactory.getLogger(BasePairParameters.class); + private static final Logger log = LoggerFactory.getLogger(BasePairParameters.class); // See URL http://ndbserver.rutgers.edu/ndbmodule/archives/reports/tsukuba/Table1.html // and the paper cited at the top of this class (also as Table 1). @@ -145,17 +136,17 @@ public class BasePairParameters implements Serializable { } protected Structure structure; - protected boolean canonical = true; - protected boolean useRNA = false; - protected boolean nonredundant = false; + protected boolean canonical; + protected boolean useRNA; + protected boolean nonredundant; protected double[] pairParameters; // this is the main data that the user wants to get back out from the procedure. protected String pairSequence = ""; protected double[][] pairingParameters; protected double[][] stepParameters; - protected List pairingNames = new ArrayList<>(); - protected List referenceFrames = new ArrayList<>(); + protected final List pairingNames = new ArrayList<>(); + protected final List referenceFrames = new ArrayList<>(); /** @@ -227,12 +218,12 @@ public BasePairParameters analyze() { lastStep = currentStep; currentStep = this.basePairReferenceFrame(pairs.get(i)); referenceFrames.add((Matrix4d)currentStep.clone()); - for (int j = 0; j < 6; j++) pairingParameters[i][j] = pairParameters[j]; + System.arraycopy(pairParameters, 0, pairingParameters[i], 0, 6); if (i != 0) { lastStep.invert(); lastStep.mul(currentStep); double[] sparms = calculateTp(lastStep); - for (int j = 0; j < 6; j++) stepParameters[i][j] = sparms[j]; + System.arraycopy(sparms, 0, stepParameters[i], 0, 6); } } return this; @@ -439,11 +430,25 @@ public List getNucleicChains(boolean removeDups) { result.add(c); } } - if (removeDups) for (int i = 0; i < result.size(); i++) { - for (int j = i+2; j < result.size(); j++) { - // remove duplicate sequences (structures with two or more identical units) - if (result.get(i).getAtomSequence().equals(result.get(j).getAtomSequence())) { - result.remove(j); + if (removeDups) { + int s = result.size(); + BitSet toRemove = new BitSet(); + for (int i = 0; i < s; i++) { + for (int j = i + 2; j < s; j++) { + // remove duplicate sequences (structures with two or more identical units) + if (result.get(i).getAtomSequence().equals(result.get(j).getAtomSequence())) { + toRemove.set(j); + } + } + } + if (!toRemove.isEmpty()) { + Iterator r = result.iterator(); + int i = 0; + while (r.hasNext()) { + Chain rr = r.next(); + if (toRemove.get(i++)) { + r.remove(); + } } } } @@ -509,7 +514,7 @@ public List> findPairs(List chains) { if (a == null) valid = false; } if (valid) { - result.add(new Pair(g1, g2)); + result.add(new Pair<>(g1, g2)); pairingNames.add((useRNA ? BASE_LIST_RNA[type1]+ BASE_LIST_RNA[type2] : BASE_LIST_DNA[type1]+ BASE_LIST_DNA[type2])); pairSequence += c.getAtomSequence().charAt(index1 + k); } else if (pairSequence.length() != 0 && pairSequence.charAt(pairSequence.length()-1) != ' ') pairSequence += ' '; @@ -630,14 +635,14 @@ public Matrix4d basePairReferenceFrame(Pair pair) { public String toString() { if (getPairingParameters() == null) return "No data"; StringBuilder result = new StringBuilder(10000); - result.append(pairingParameters.length + " base pairs\n"); + result.append(pairingParameters.length).append(" base pairs\n"); result.append("bp: buckle propeller opening shear stretch stagger tilt roll twist shift slide rise\n"); for (int i = 0; i < pairingParameters.length; i++) { - result.append(pairingNames.get(i)+": "); + result.append(pairingNames.get(i)).append(": "); for (int j = 0; j < 6; j++) - result.append(String.format("%5.4f", pairingParameters[i][j]) + " "); + result.append(String.format("%5.4f", pairingParameters[i][j])).append(" "); for (int j = 0; j < 6; j++) - result.append(String.format("%5.4f", stepParameters[i][j]) + " "); + result.append(String.format("%5.4f", stepParameters[i][j])).append(" "); result.append("\n"); } return result.toString(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/cath/CathCategory.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/cath/CathCategory.java index 4aabdc04b7..14f30e7cda 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/cath/CathCategory.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/cath/CathCategory.java @@ -47,26 +47,27 @@ public enum CathCategory { static final String lut = "CATHSOLID"; public static CathCategory fromString(String type) { - if ( type.equals("C") ) { - return Class; - } else if ( type.equals("A") ) { - return Architecture; - } else if ( type.equals("T") ) { - return Topolgy; - } else if ( type.equals("H") ) { - return Homology; - } else if ( type.equals("S") ) { - return SequenceFamily; - } else if ( type.equals("O") ) { - return OrthologousSequenceFamily; - } else if ( type.equals("L") ) { - return LikeSequenceFamily; - } else if ( type.equals("I") ) { - return IdenticalSequenceFamily; + switch (type) { + case "C": + return Class; + case "A": + return Architecture; + case "T": + return Topolgy; + case "H": + return Homology; + case "S": + return SequenceFamily; + case "O": + return OrthologousSequenceFamily; + case "L": + return LikeSequenceFamily; + case "I": + return IdenticalSequenceFamily; // } else if ( type.equals("D") ) { - } else { - return DomainCounter; - } + default: + return DomainCounter; + } } @Override @@ -97,7 +98,7 @@ public String toString() { public static CathCategory fromCathCode(String code) { int count = 0; int idx = 0; - while ((idx = code.indexOf(".",idx)) != -1) { + while ((idx = code.indexOf('.',idx)) != -1) { count++; idx++; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/cath/CathDatabase.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/cath/CathDatabase.java index 351af83e52..65aa6f41bb 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/cath/CathDatabase.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/cath/CathDatabase.java @@ -35,21 +35,21 @@ public interface CathDatabase { * * @return CATH version */ - public String getCathVersion(); + String getCathVersion(); /** Return the CathNode for a node ID. * * @param nodeId * @return CATH node */ - public CathNode getCathNode(String nodeId); + CathNode getCathNode(String nodeId); /** Return list of CATH descriptions for node representatives at a CATH category (e.g. "T"). * * @param category * @return CATH descriptions */ - public List getByCategory(CathCategory category); + List getByCategory(CathCategory category); /** Return list of CATH descriptions whose CATH codes (e.g. 1.4.6.10) start with the query. * This is currently redundant with getDescriptionsByNodeId. @@ -57,63 +57,63 @@ public interface CathDatabase { * @param query * @return CATH descriptions */ - public List filterByCathCode(String query); + List filterByCathCode(String query); /** Return the CATH sub-tree for a particular domain. * * @param domain * @return CATH sub-tree */ - public List getTree(CathDomain domain); + List getTree(CathDomain domain); /** Return list of CATH domains whose node name (e.g. Orthogonal Bundle) starts with the query. * * @param query * @return CATH domains */ - public List filterByNodeName(String query); + List filterByNodeName(String query); /** Return list of CATH descriptions whose descriptions (name field) starts with the query. * * @param query * @return CATH descriptions */ - public List filterByDescription(String query); + List filterByDescription(String query); /** Return CATH description for node representative by node ID. * * @param nodeId * @return CATH description */ - public CathDomain getDescriptionByNodeId(String nodeId); + CathDomain getDescriptionByNodeId(String nodeId); /** Return all CATH domains for a PDB ID. * * @param pdbId * @return CATH domains */ - public List getDomainsForPdb(String pdbId); + List getDomainsForPdb(String pdbId); /** Return CATH domain for CATH domain ID. * * @param cathId * @return CATH domain */ - public CathDomain getDomainByCathId(String cathId); + CathDomain getDomainByCathId(String cathId); /** Return CATH description for CATH domain ID. * * @param cathId * @return */ - public CathDomain getDescriptionByCathId(String cathId); + CathDomain getDescriptionByCathId(String cathId); /** Return all CATH domains for a particular CATH node. * * @param nodeId * @return */ - public List getDomainsByNodeId(String nodeId); + List getDomainsByNodeId(String nodeId); - public List getFragmentsByPdbId(String pdbId); + List getFragmentsByPdbId(String pdbId); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/cath/CathDomain.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/cath/CathDomain.java index b4d0efaa89..57657de8d5 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/cath/CathDomain.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/cath/CathDomain.java @@ -27,20 +27,12 @@ * @author Daniel Asarnow */ +import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.align.util.AtomCache; + import java.io.IOException; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.biojava.nbio.structure.ResidueRange; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIdentifier; -import org.biojava.nbio.structure.SubstructureIdentifier; -import org.biojava.nbio.structure.align.util.AtomCache; +import java.util.*; /** * A class which represents a single CATH domain. @@ -176,7 +168,7 @@ public String getThePdbId() { */ public String getPdbIdAndChain() { return domainName.substring(0, 4) + - (!domainName.substring(4, 5).equals("0") ? "." + domainName.substring(4, 5) : ""); + (!domainName.startsWith("0", 4) ? "." + domainName.substring(4, 5) : ""); } public Integer getDomainId() { @@ -280,10 +272,10 @@ public void setCATH(String cathCode) { } public String getCATH() { - return Integer.toString(getClassId()) + "." + - Integer.toString(getArchitectureId()) + "." + - Integer.toString(getTopologyId()) + "." + - Integer.toString(getHomologyId()); + return getClassId() + "." + + getArchitectureId() + "." + + getTopologyId() + "." + + getHomologyId(); } public void setSOLID(String cathCode) { @@ -296,11 +288,11 @@ public void setSOLID(String cathCode) { } public String getSOILD() { - return Integer.toString(getSequenceFamilyId()) + "." + - Integer.toString(getOrthologousSequenceFamilyId()) + "." + - Integer.toString(getLikeSequenceFamilyId()) + "." + - Integer.toString(getIdenticalSequenceFamilyId()) + "." + - Integer.toString(getDomainCounter()); + return getSequenceFamilyId() + "." + + getOrthologousSequenceFamilyId() + "." + + getLikeSequenceFamilyId() + "." + + getIdenticalSequenceFamilyId() + "." + + getDomainCounter(); } public Integer getClassificationId(CathCategory cathCategory) { @@ -422,7 +414,7 @@ public String toString() { * Returns the chains this domain is defined over; contains more than 1 element only if this domains is a multi-chain domain. */ public Set getChains() { - Set chains = new HashSet(); + Set chains = new HashSet<>(); List rrs = toCanonical().getResidueRanges(); for (ResidueRange rr : rrs) chains.add(rr.getChainName()); return chains; @@ -435,7 +427,7 @@ public String getIdentifier() { @Override public SubstructureIdentifier toCanonical() { - List ranges = new ArrayList(); + List ranges = new ArrayList<>(); String chain = String.valueOf(getDomainName().charAt(getDomainName().length() - 3)); for (CathSegment segment : this.getSegments()) { ranges.add(new ResidueRange(chain, segment.getStart(), segment.getStop())); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/cath/CathFactory.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/cath/CathFactory.java index 77fe36fd8e..55407aa93a 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/cath/CathFactory.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/cath/CathFactory.java @@ -45,7 +45,7 @@ public class CathFactory { private static CathDatabase cath; - private static Map versions = new HashMap(); + private static final Map versions = new HashMap<>(); /** * Sets the default (singleton) CathDatabase. diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/cath/CathInstallation.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/cath/CathInstallation.java index 45914f6208..5fa58a1cdb 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/cath/CathInstallation.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/cath/CathInstallation.java @@ -23,11 +23,11 @@ package org.biojava.nbio.structure.cath; +import org.biojava.nbio.core.util.Download; +import org.biojava.nbio.core.util.InputStreamProvider; import org.biojava.nbio.structure.align.util.UserConfiguration; -import org.biojava.nbio.core.util.FileDownloadUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.biojava.nbio.core.util.InputStreamProvider; import java.io.*; import java.net.URL; @@ -56,8 +56,8 @@ public class CathInstallation implements CathDatabase{ public static final String CATH_DOWNLOAD_ALL_RELEASES_DIR = "all-releases"; public static final String CATH_DOWNLOAD_CLASSIFICATION_DATA_DIR = "cath-classification-data"; - public static final String NEWLINE = System.getProperty("line.separator");; - public static final String FILESPLIT = System.getProperty("file.separator");; + public static final String NEWLINE = System.getProperty("line.separator"); + public static final String FILESPLIT = System.getProperty("file.separator"); private String cathVersion; @@ -74,9 +74,9 @@ public class CathInstallation implements CathDatabase{ private final boolean useCathDomainDescriptionFile; private final boolean parseCathFragments; - private Map> pdbMap; - private Map domainMap; - private Map cathTree; + private final Map> pdbMap; + private final Map domainMap; + private final Map cathTree; private Map> fragmentMap; @@ -95,11 +95,11 @@ public CathInstallation(String cacheLocation, boolean usingCDDF, boolean parseCF cathVersion = DEFAULT_VERSION; cathDownloadUrl = CATH_DOWNLOAD_URL; - pdbMap = new HashMap>(); - domainMap = new HashMap(); - cathTree = new HashMap(); + pdbMap = new HashMap<>(); + domainMap = new HashMap<>(); + cathTree = new HashMap<>(); - if (parseCathFragments) fragmentMap = new HashMap>(); + if (parseCathFragments) fragmentMap = new HashMap<>(); } @@ -205,10 +205,10 @@ public List getByCategory(CathCategory category) { ensureDomallInstalled(); } ensureNodeListInstalled(); - List matches = new ArrayList(); + List matches = new ArrayList<>(); CathNode node; - for ( String nodeId : cathTree.keySet() ) { - if ( (node = cathTree.get(nodeId)).getCategory() == category ) { + for (CathNode cathNode : cathTree.values()) { + if ( (node = cathNode).getCategory() == category ) { matches.add( domainMap.get( node.getRepresentative() ) ); } } @@ -222,10 +222,10 @@ public List filterByCathCode(String query) { } else { ensureDomallInstalled(); } - List matches = new ArrayList(); - for ( String k : domainMap.keySet() ) { - if ( domainMap.get(k).getCATH().startsWith(query) ) { - matches.add( domainMap.get(k) ); + List matches = new ArrayList<>(); + for (CathDomain cathDomain : domainMap.values()) { + if (cathDomain.getCATH().startsWith(query) ) { + matches.add(cathDomain); } } return matches; @@ -234,7 +234,7 @@ public List filterByCathCode(String query) { @Override public List getTree(CathDomain domain) { CathNode node = getCathNode( domain.getCATH() ); - List tree = new ArrayList(); + List tree = new ArrayList<>(); while (node != null) { node = getCathNode( node.getParentId() ); if (node != null) tree.add(node); @@ -246,14 +246,14 @@ public List getTree(CathDomain domain) { @Override public List filterByNodeName(String query) { ensureNodeListInstalled(); - List matchingNodes = new ArrayList(); + List matchingNodes = new ArrayList<>(); CathNode node; - for ( String nodeId : cathTree.keySet() ) { - if ( (node = cathTree.get(nodeId) ).getDescription().startsWith(query) ) { + for (CathNode cathNode : cathTree.values()) { + if ( (node = cathNode).getDescription().startsWith(query) ) { matchingNodes.add(node); } } - List matches = new ArrayList(); + List matches = new ArrayList<>(); for (CathNode n : matchingNodes) { matches.addAll(getDomainsByNodeId(n.getNodeId())); } @@ -267,10 +267,10 @@ public List filterByDescription(String query) { } else { ensureDomallInstalled(); } - List matches = new ArrayList(); - for ( String k : domainMap.keySet() ) { - if ( domainMap.get(k).getName().startsWith(query) ) { - matches.add( domainMap.get(k) ); + List matches = new ArrayList<>(); + for (CathDomain cathDomain : domainMap.values()) { + if (cathDomain.getName().startsWith(query) ) { + matches.add(cathDomain); } } return matches; @@ -326,10 +326,9 @@ public List getDomainsByNodeId(String nodeId) { } else { ensureDomallInstalled(); } - List domains = new ArrayList(); - for (String domainName : domainMap.keySet()) { - CathDomain description = domainMap.get(domainName); - if ( description.getCATH().startsWith(nodeId) ) { + List domains = new ArrayList<>(); + for (CathDomain description : domainMap.values()) { + if ( description.getCATH().startsWith(nodeId) ) { domains.add(description); } } @@ -343,12 +342,12 @@ public List getFragmentsByPdbId(String pdbId) { return fragmentMap.get(pdbId); } - private void parseCathDomainList() throws IOException { - File file = new File(getDomainListFileName()); - InputStreamProvider ips = new InputStreamProvider(); - BufferedReader buffer = new BufferedReader (new InputStreamReader(ips.getInputStream(file))); - parseCathDomainList(buffer); - } +// private void parseCathDomainList() throws IOException { +// File file = new File(getDomainListFileName()); +// InputStreamProvider ips = new InputStreamProvider(); +// BufferedReader buffer = new BufferedReader (new InputStreamReader(ips.getInputStream(file))); +// parseCathDomainList(buffer); +// } private void parseCathDomainList(BufferedReader bufferedReader) throws IOException{ String line; @@ -364,7 +363,7 @@ private void parseCathDomainList(BufferedReader bufferedReader) throws IOExcepti if ( pdbMap.containsKey(pdbId)){ domainList = pdbMap.get(pdbId); } else { - domainList = new ArrayList(); + domainList = new ArrayList<>(); pdbMap.put(pdbId,domainList); } @@ -445,15 +444,15 @@ private void parseCathDomainDescriptionFile(BufferedReader bufferedReader) throw } else if ( line.startsWith("DSEQS") ) { seqs = seqs.append( line.substring(10) ); } else if ( line.startsWith("NSEGMENTS") ) { - segments = new ArrayList(); + segments = new ArrayList<>(); } else if ( line.startsWith("SEGMENT") ) { segment = new CathSegment(); sseqh = new StringBuilder(); sseqs = new StringBuilder(); } else if ( line.startsWith("SRANGE") ) { - int startStart = line.indexOf("=",10) + 1; - int startStop = line.indexOf(" ",10); - int stopStart = line.indexOf("=",startStop) + 1; + int startStart = line.indexOf('=',10) + 1; + int startStop = line.indexOf(' ',10); + int stopStart = line.indexOf('=',startStop) + 1; // Integer start = Integer.parseInt( line.substring(startStart,startStop) ); // Integer stop = Integer.parseInt( line.substring(stopStart, line.length()) ); segment.setStart( line.substring(startStart,startStop) ); @@ -482,7 +481,7 @@ private void parseCathDomainDescriptionFile(BufferedReader bufferedReader) throw if ( pdbMap.containsKey(pdbId)){ domainList = pdbMap.get(pdbId); } else { - domainList = new ArrayList(); + domainList = new ArrayList<>(); pdbMap.put(pdbId,domainList); } @@ -525,7 +524,7 @@ private CathNode parseCathNamesFileLine(String line) { CathNode cathNode = new CathNode(); String[] token = line.split("\\s+",3); cathNode.setNodeId( token[0] ); - int idx = token[0].lastIndexOf("."); + int idx = token[0].lastIndexOf('.'); if ( idx == -1 ) idx = token[0].length(); cathNode.setParentId( token[0].substring( 0, idx ) ); cathNode.setRepresentative( token[1] ); @@ -547,15 +546,15 @@ private void parseCathDomall(BufferedReader bufferedReader) throws IOException{ if ( line.length() == 0 ) continue; String[] token = line.split("\\s+"); String chainId = token[0]; - Integer numberOfDomains = Integer.parseInt( token[1].substring(1) ); - Integer numberOfFragments = Integer.parseInt( token[2].substring(1) ); + int numberOfDomains = Integer.parseInt( token[1].substring(1) ); + int numberOfFragments = Integer.parseInt( token[2].substring(1) ); int domIdx = 3; int segIdx; - Integer sstop; - Integer sstart; - Integer fstart; - Integer fstop; - Integer flength; + int sstop; + int sstart; + int fstart; + int fstop; + int flength; for (int i=1; i<=numberOfDomains; i++) { DecimalFormat df = new DecimalFormat("00"); String domainId; @@ -575,14 +574,14 @@ private void parseCathDomall(BufferedReader bufferedReader) throws IOException{ domain = domainMap.get(domainId); } - Integer numberOfSegments = Integer.parseInt( token[domIdx] ); + int numberOfSegments = Integer.parseInt( token[domIdx] ); if ( domain == null ) { domIdx += 6*numberOfSegments + 1; continue; } - List segments = new ArrayList(numberOfSegments); + List segments = new ArrayList<>(numberOfSegments); segIdx = 1; // Offset from domIdx. for (int j=1; j<=numberOfSegments; j++) { CathSegment segment = new CathSegment(); @@ -609,7 +608,7 @@ private void parseCathDomall(BufferedReader bufferedReader) throws IOException{ domIdx += 6*numberOfSegments + 1; } if (parseCathFragments) { - List fragments = new ArrayList(numberOfFragments); + List fragments = new ArrayList<>(numberOfFragments); for (int i=1; i<=numberOfFragments; i++) { CathFragment fragment = new CathFragment(); fragment.setFragmentId(i); @@ -639,7 +638,7 @@ protected void downloadFileFromRemote(URL remoteURL, File localFile) throws IOEx LOGGER.info("Downloading file {} to local file {}", remoteURL, localFile); long timeS = System.currentTimeMillis(); - File tempFile = File.createTempFile(FileDownloadUtils.getFilePrefix(localFile), "."+ FileDownloadUtils.getFileExtension(localFile)); + File tempFile = File.createTempFile(Download.getFilePrefix(localFile), "."+ Download.getFileExtension(localFile)); FileOutputStream out = new FileOutputStream(tempFile); @@ -652,7 +651,7 @@ protected void downloadFileFromRemote(URL remoteURL, File localFile) throws IOEx in.close(); out.close(); - FileDownloadUtils.copy(tempFile,localFile); + Download.copy(tempFile,localFile); // delete the tmp file tempFile.delete(); @@ -669,7 +668,7 @@ protected void downloadFileFromRemote(URL remoteURL, File localFile) throws IOEx LOGGER.info("Downloaded {} in {} sec. to {}", String.format("%.1f",disp) + unit, (timeE - timeS)/1000, localFile); } - private boolean domainDescriptionFileAvailable(){ + @Deprecated private boolean domainDescriptionFileAvailable(){ String fileName = getDomainDescriptionFileName(); File f = new File(fileName); return f.exists(); @@ -693,15 +692,13 @@ private boolean domallFileAvailable() { return f.exists(); } - protected void downloadDomainListFile() throws IOException{ + protected void downloadAndParseDomainListFile() throws IOException{ String remoteFilename = domainListFileName; URL url = new URL(buildUrl(remoteFilename)); - String localFileName = getDomainListFileName(); - File localFile = new File(localFileName); - downloadFileFromRemote(url, localFile); + parseCathNames(Download.bufferedReader(url)); } - protected void downloadDomainDescriptionFile() throws IOException{ + @Deprecated protected void downloadDomainDescriptionFile() throws IOException{ String remoteFilename = domainDescriptionFileName; URL url = new URL(buildUrl(remoteFilename)); String localFileName = getDomainDescriptionFileName(); @@ -709,7 +706,7 @@ protected void downloadDomainDescriptionFile() throws IOException{ downloadFileFromRemote(url, localFile); } - protected void downloadNodeListFile() throws IOException{ + @Deprecated protected void downloadNodeListFile() throws IOException{ String remoteFilename = nodeListFileName; URL url = new URL(buildUrl(remoteFilename)); String localFileName = getNodeListFileName(); @@ -728,18 +725,19 @@ protected void downloadDomallFile() throws IOException { public void ensureDomainListInstalled(){ if ( installedDomainList.get() ) return; - if ( ! domainListFileAvailable() ){ - try { - downloadDomainListFile(); - } catch (Exception e){ - LOGGER.error("Could not download CATH domain list file. Error: {}", e.getMessage()); - installedDomainList.set(false); - return; - } - } +// if ( ! domainListFileAvailable() ){ +// try { +// downloadDomainListFile(); +// } catch (Exception e){ +// LOGGER.error("Could not download CATH domain list file. Error: {}", e.getMessage()); +// installedDomainList.set(false); +// return; +// } +// } try { - parseCathDomainList(); + downloadAndParseDomainListFile(); + //parseCathDomainList(); } catch (Exception e){ LOGGER.error(e.getMessage(), e); installedDomainList.set(false); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/cluster/Subunit.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/cluster/Subunit.java index 58b4845213..5aef2b6357 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/cluster/Subunit.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/cluster/Subunit.java @@ -43,11 +43,11 @@ public class Subunit { // Optional fields for Subunit annotation private String name; - private Structure structure; - private StructureIdentifier identifier; + private final Structure structure; + private final StructureIdentifier identifier; // Required fields for Subunit definition - private Atom[] reprAtoms; + private final Atom[] reprAtoms; private ProteinSequence sequence = null; /** diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/cluster/SubunitCluster.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/cluster/SubunitCluster.java index d73d747cb6..27b3d1fce0 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/cluster/SubunitCluster.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/cluster/SubunitCluster.java @@ -30,26 +30,14 @@ import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.EntityInfo; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.StructureAlignment; import org.biojava.nbio.structure.align.StructureAlignmentFactory; import org.biojava.nbio.structure.align.ce.ConfigStrucAligParams; import org.biojava.nbio.structure.align.model.AFPChain; -import org.biojava.nbio.structure.align.multiple.Block; -import org.biojava.nbio.structure.align.multiple.BlockImpl; -import org.biojava.nbio.structure.align.multiple.BlockSet; -import org.biojava.nbio.structure.align.multiple.BlockSetImpl; -import org.biojava.nbio.structure.align.multiple.MultipleAlignment; -import org.biojava.nbio.structure.align.multiple.MultipleAlignmentEnsembleImpl; -import org.biojava.nbio.structure.align.multiple.MultipleAlignmentImpl; +import org.biojava.nbio.structure.align.multiple.*; import org.biojava.nbio.structure.align.multiple.util.MultipleAlignmentScorer; import org.biojava.nbio.structure.align.multiple.util.ReferenceSuperimposer; -import org.biojava.nbio.structure.quaternary.BiologicalAssemblyBuilder; import org.biojava.nbio.structure.symmetry.core.QuatSymmetrySubunits; import org.biojava.nbio.structure.symmetry.internal.CESymmParameters; import org.biojava.nbio.structure.symmetry.internal.CeSymm; @@ -59,7 +47,10 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import java.util.stream.Collectors; /** @@ -80,7 +71,7 @@ public class SubunitCluster { private List subunits = new ArrayList<>(); private List> subunitEQR = new ArrayList<>(); - private int representative = -1; + private int representative; private SubunitClustererMethod method = SubunitClustererMethod.SEQUENCE; private boolean pseudoStoichiometric = false; @@ -393,12 +384,7 @@ public boolean mergeSequence(SubunitCluster other, SubunitClustererParameters pa .getPairwiseAligner(thisSequence, otherSequence, alignerType, gapPenalty, subsMatrix); - double sequenceIdentity; - if(params.isUseGlobalMetrics()) { - sequenceIdentity = aligner.getPair().getPercentageOfIdentity(true); - } else { - sequenceIdentity = aligner.getPair().getPercentageOfIdentity(false); - } + double sequenceIdentity = aligner.getPair().getPercentageOfIdentity(params.isUseGlobalMetrics()); if (sequenceIdentity < params.getSequenceIdentityThreshold()) return false; @@ -679,9 +665,9 @@ public boolean divideInternally(SubunitClustererParameters clusterParams) } // Divide the Subunits in their repeats - List newSubunits = new ArrayList(subunits.size() + List newSubunits = new ArrayList<>(subunits.size() * columns.size()); - List> newSubunitEQR = new ArrayList>( + List> newSubunitEQR = new ArrayList<>( subunits.size() * columns.size()); for (int s = 0; s < subunits.size(); s++) { @@ -700,7 +686,7 @@ public boolean divideInternally(SubunitClustererParameters clusterParams) .get(s).getStructure())); // Recalculate equivalent residues - List eqr = new ArrayList(); + List eqr = new ArrayList<>(); for (int p = 0; p < columns.get(r).size(); p++) { eqr.add(subunitEQR.get(s).get(columns.get(r).get(p)) - start); @@ -795,7 +781,7 @@ public MultipleAlignment getMultipleAlignment() throws StructureException { MultipleAlignment msa = new MultipleAlignmentImpl(); msa.setEnsemble(new MultipleAlignmentEnsembleImpl()); msa.getEnsemble().setAtomArrays( - subunits.stream().map(s -> s.getRepresentativeAtoms()) + subunits.stream().map(Subunit::getRepresentativeAtoms) .collect(Collectors.toList())); // Fill in the alignment information diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/cluster/SubunitClusterer.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/cluster/SubunitClusterer.java index 6295f8fdf0..8de30076dd 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/cluster/SubunitClusterer.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/cluster/SubunitClusterer.java @@ -20,9 +20,6 @@ */ package org.biojava.nbio.structure.cluster; -import java.util.ArrayList; -import java.util.List; - import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; @@ -30,6 +27,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.List; + /** * The SubunitClusterer takes as input a collection of {@link Subunit} and * returns a collection of {@link SubunitCluster}. diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/cluster/SubunitExtractor.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/cluster/SubunitExtractor.java index 7060037bfc..e3b7928cd6 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/cluster/SubunitExtractor.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/cluster/SubunitExtractor.java @@ -20,7 +20,10 @@ */ package org.biojava.nbio.structure.cluster; -import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.Atom; +import org.biojava.nbio.structure.Chain; +import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.StructureTools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -66,7 +69,7 @@ public static List extractSubunits(Structure structure, int absMinLen, double fraction, int minLen) { // The extracted subunit container - List subunits = new ArrayList(); + List subunits = new ArrayList<>(); for (Chain c : structure.getPolyChains()) { // Only take protein chains @@ -107,7 +110,7 @@ private static int calcAdjustedMinimumSequenceLength( int minLength = Integer.MAX_VALUE; // Extract the length List, the min and the max - List lengths = new ArrayList(); + List lengths = new ArrayList<>(); for (int i = 0; i < subunits.size(); i++) { if (subunits.get(i).size() >= absMinLen) { maxLength = Math.max(subunits.get(i).size(), maxLength); @@ -123,7 +126,7 @@ private static int calcAdjustedMinimumSequenceLength( return adjustedMinimumSequenceLength; // Calculate the median of the lengths - double median = 0; + double median; Collections.sort(lengths); if (lengths.size() % 2 == 1) { int middle = (lengths.size() - 1) / 2; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/AtomContact.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/AtomContact.java index 042ae7cc83..bb657cd80c 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/AtomContact.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/AtomContact.java @@ -20,10 +20,10 @@ */ package org.biojava.nbio.structure.contact; -import java.io.Serializable; - import org.biojava.nbio.structure.Atom; +import java.io.Serializable; + /** * A pair of atoms that are in contact * diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/AtomContactSet.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/AtomContactSet.java index e1297faec9..ab9d1c2fa0 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/AtomContactSet.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/AtomContactSet.java @@ -37,12 +37,12 @@ public class AtomContactSet implements Serializable, Iterable { private static final long serialVersionUID = 1L; - private HashMap, AtomContact> contacts; - private double cutoff; + private final HashMap, AtomContact> contacts; + private final double cutoff; public AtomContactSet(double cutoff) { this.cutoff = cutoff; - this.contacts = new HashMap,AtomContact>(); + this.contacts = new HashMap<>(); } public void add(AtomContact contact) { @@ -62,7 +62,7 @@ public boolean hasContact(Atom atom1, Atom atom2) { } public boolean hasContact(AtomIdentifier atomId1, AtomIdentifier atomId2) { - return contacts.containsKey(new Pair(atomId1,atomId2)); + return contacts.containsKey(new Pair<>(atomId1, atomId2)); } /** @@ -72,9 +72,9 @@ public boolean hasContact(AtomIdentifier atomId1, AtomIdentifier atomId2) { * @return */ public AtomContact getContact(Atom atom1, Atom atom2) { - return contacts.get(new Pair( - new AtomIdentifier(atom1.getPDBserial(),atom1.getGroup().getChainId()), - new AtomIdentifier(atom2.getPDBserial(),atom2.getGroup().getChainId()) )); + return contacts.get(new Pair<>( + new AtomIdentifier(atom1.getPDBserial(), atom1.getGroup().getChainId()), + new AtomIdentifier(atom2.getPDBserial(), atom2.getGroup().getChainId()))); } public int size() { @@ -86,12 +86,13 @@ public Iterator iterator() { return contacts.values().iterator(); } - private Pair getAtomIdPairFromContact(AtomContact contact) { - Pair pair = new Pair( - new AtomIdentifier(contact.getPair().getFirst().getPDBserial(),contact.getPair().getFirst().getGroup().getChainId()), - new AtomIdentifier(contact.getPair().getSecond().getPDBserial(),contact.getPair().getSecond().getGroup().getChainId())); - - return pair; + private static Pair getAtomIdPairFromContact(AtomContact contact) { + Pair pair = contact.getPair(); + Atom a = pair.getFirst(); + Atom b = pair.getSecond(); + return new Pair<>( + new AtomIdentifier(a.getPDBserial(), a.getGroup().getChainId()), + new AtomIdentifier(b.getPDBserial(), b.getGroup().getChainId())); } /** @@ -132,7 +133,7 @@ public List getContactsWithinDistance(double distance) { String.format("%.2f", distance)+" is larger than contacts' distance cutoff "+ String.format("%.2f", cutoff)); - List list = new ArrayList(); + List list = new ArrayList<>(); for (AtomContact contact:this.contacts.values()) { if (contact.getDistance() { - int cardinal; - double value; + private static class Bound implements Comparable { + final int cardinal; + final double value; public Bound(int cardinal,double value) { this.cardinal = cardinal; this.value = value; @@ -179,10 +179,10 @@ public boolean overlaps(BoundingBox o, double cutoff) { return true; } - private boolean areOverlapping(double imin, double imax, double jmin, double jmax, double cutoff) { + private static boolean areOverlapping(double imin, double imax, double jmin, double jmax, double cutoff) { - Bound[] bounds = {new Bound(0,imin), new Bound(1,imax), - new Bound(2,jmin), new Bound(3,jmax)}; + Bound[] bounds = {new Bound(0, imin), new Bound(1, imax), + new Bound(2, jmin), new Bound(3, jmax)}; Arrays.sort(bounds); @@ -228,7 +228,7 @@ public void translate(Vector3d translation) { * @param array * @return */ - public double[] getMinMax(double[] array) { + public static double[] getMinMax(double[] array) { double[] minmax = new double[2]; double max = Double.MIN_VALUE; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/Contact.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/Contact.java index 1a3c169ce2..1ca67c981b 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/Contact.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/Contact.java @@ -31,9 +31,9 @@ public class Contact implements Serializable { private static final long serialVersionUID = 5059569852079048728L; - private int i; - private int j; - private double distance; + private final int i; + private final int j; + private final double distance; public Contact(int i, int j, double distance) { this.i = i; @@ -42,7 +42,7 @@ public Contact(int i, int j, double distance) { } public Pair getIndexPair() { - return new Pair(i,j); + return new Pair<>(i, j); } public int getI() { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/Grid.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/Grid.java index 0047385ab2..943daacc38 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/Grid.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/Grid.java @@ -21,15 +21,16 @@ package org.biojava.nbio.structure.contact; +import org.biojava.nbio.structure.Atom; +import org.biojava.nbio.structure.Calc; + +import javax.vecmath.Point3d; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; -import javax.vecmath.Point3d; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Calc; +import static java.util.Collections.EMPTY_LIST; /** @@ -65,8 +66,8 @@ public class Grid { private GridCell[][][] cells; - private double cutoff; - private int cellSize; + private final double cutoff; + private final int cellSize; private Point3d[] iAtoms; private Point3d[] jAtoms; @@ -386,12 +387,12 @@ public AtomContactSet getAtomContacts() { if (jAtomObjects == null) { for (Contact cont : list) { - contacts.add(new AtomContact(new Pair(iAtomObjects[cont.getI()],iAtomObjects[cont.getJ()]),cont.getDistance())); + contacts.add(new AtomContact(new Pair<>(iAtomObjects[cont.getI()], iAtomObjects[cont.getJ()]),cont.getDistance())); } } else { for (Contact cont : list) { - contacts.add(new AtomContact(new Pair(iAtomObjects[cont.getI()],jAtomObjects[cont.getJ()]),cont.getDistance())); + contacts.add(new AtomContact(new Pair<>(iAtomObjects[cont.getI()], jAtomObjects[cont.getJ()]),cont.getDistance())); } } @@ -418,11 +419,11 @@ public AtomContactSet getContacts() { */ public List getIndicesContacts() { - List list = new ArrayList<>(); - // if the 2 sets of atoms are not overlapping they are too far away and no need to calculate anything // this won't apply if there's only one set of atoms (iAtoms), where we would want all-to-all contacts - if (noOverlap) return list; + if (noOverlap) return EMPTY_LIST; + + List list = new ArrayList<>(); for (int xind=0;xind getIndicesContacts() { } } - return list; + return list.isEmpty() ? EMPTY_LIST : list; } /** @@ -477,14 +478,16 @@ public boolean hasAnyContact(Collection atoms) { if( x<0 || cells.length<=x) continue; for (int y=yind-1;y<=yind+1;y++) { if( y<0 || cells[x].length<=y ) continue; + + GridCell[] cxy = cells[x][y]; + for (int z=zind-1;z<=zind+1;z++) { - if( z<0 || cells[x][y].length<=z ) continue; + if( z<0 || cxy.length<=z ) continue; - GridCell cell = cells[x][y][z]; // Check for contacts in this cell - if(cell != null && cell.hasContactToAtom(iAtoms, jAtoms, atom, cutoff)) { + GridCell cell = cxy[z]; + if(cell != null && cell.hasContactToAtom(iAtoms, jAtoms, atom, cutoff)) return true; - } } } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/GridCell.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/GridCell.java index 5123831ec6..05b6033a00 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/GridCell.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/GridCell.java @@ -20,11 +20,10 @@ */ package org.biojava.nbio.structure.contact; +import javax.vecmath.Point3d; import java.util.ArrayList; import java.util.List; -import javax.vecmath.Point3d; - /** * A grid cell to be used in contact calculation via spatial hashing algorithm. @@ -35,13 +34,13 @@ public class GridCell { - private Grid grid; - private ArrayList iIndices; - private ArrayList jIndices; + private final Grid grid; + private final ArrayList iIndices; + private final ArrayList jIndices; public GridCell(Grid parent){ - iIndices = new ArrayList(); - jIndices = new ArrayList(); + iIndices = new ArrayList<>(); + jIndices = new ArrayList<>(); this.grid = parent; } @@ -70,7 +69,7 @@ public int getNumJindices() { */ public List getContactsWithinCell(){ - List contacts = new ArrayList(); + List contacts = new ArrayList<>(); Point3d[] iAtoms = grid.getIAtoms(); Point3d[] jAtoms = grid.getJAtoms(); @@ -110,7 +109,7 @@ public List getContactsWithinCell(){ */ public List getContactsToOtherCell(GridCell otherCell){ - List contacts = new ArrayList(); + List contacts = new ArrayList<>(); Point3d[] iAtoms = grid.getIAtoms(); Point3d[] jAtoms = grid.getJAtoms(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/GroupContact.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/GroupContact.java index 16c0eb08c5..8740f8bdf9 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/GroupContact.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/GroupContact.java @@ -38,10 +38,10 @@ public class GroupContact implements Serializable { private Pair pair; - private List atomContacts; + private final List atomContacts; public GroupContact() { - atomContacts = new ArrayList(); + atomContacts = new ArrayList<>(); } public void addAtomContact(AtomContact atomContact) { @@ -82,7 +82,7 @@ public List getAtomContacts() { */ public List getContactsWithinDistance(double distance) { - List list = new ArrayList(); + List list = new ArrayList<>(); for (AtomContact contact:this.atomContacts) { if (contact.getDistance(){ private static final long serialVersionUID = 1L; - private HashMap, GroupContact> contacts; + private final HashMap, GroupContact> contacts; public GroupContactSet() { - contacts = new HashMap, GroupContact>(); + contacts = new HashMap<>(); } /** @@ -52,7 +52,7 @@ public GroupContactSet() { * @param atomContacts */ public GroupContactSet(AtomContactSet atomContacts) { - contacts = new HashMap, GroupContact>(); + contacts = new HashMap<>(); atoms2groups(atomContacts); } @@ -69,8 +69,8 @@ private void atoms2groups(AtomContactSet atomContacts) { // we skip the self-residue contacts if (iResidue.equals(jResidue)) continue; - Pair residuePair = new Pair (iResidue, jResidue); - Pair pair = new Pair(new ResidueIdentifier(iResidue), new ResidueIdentifier(jResidue)); + Pair residuePair = new Pair<>(iResidue, jResidue); + Pair pair = new Pair<>(new ResidueIdentifier(iResidue), new ResidueIdentifier(jResidue)); if (!contacts.containsKey(pair)) { @@ -114,7 +114,7 @@ public boolean hasContact(Group group1, Group group2) { * @return */ public boolean hasContact(ResidueNumber resNumber1, ResidueNumber resNumber2) { - return contacts.containsKey(new Pair(resNumber1, resNumber2)); + return contacts.containsKey(new Pair<>(resNumber1, resNumber2)); } /** @@ -128,7 +128,7 @@ public boolean hasContact(ResidueNumber resNumber1, ResidueNumber resNumber2) { */ public boolean hasContact(ResidueIdentifier resId1, ResidueIdentifier resId2) { - return contacts.containsKey(new Pair(resId1, resId2)); + return contacts.containsKey(new Pair<>(resId1, resId2)); } /** @@ -139,7 +139,7 @@ public boolean hasContact(ResidueIdentifier resId1, ResidueIdentifier resId2) { */ public GroupContact getContact(Group group1, Group group2) { return contacts.get( - new Pair(group1.getResidueNumber(),group2.getResidueNumber())); + new Pair<>(group1.getResidueNumber(), group2.getResidueNumber())); } public int size() { @@ -152,9 +152,9 @@ public Iterator iterator() { } private Pair getResIdPairFromContact(GroupContact groupContact) { - return new Pair( + return new Pair<>( new ResidueIdentifier(groupContact.getPair().getFirst()), - new ResidueIdentifier(groupContact.getPair().getSecond()) ); + new ResidueIdentifier(groupContact.getPair().getSecond())); } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/InterfaceFinder.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/InterfaceFinder.java new file mode 100644 index 0000000000..fbe6c34223 --- /dev/null +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/InterfaceFinder.java @@ -0,0 +1,91 @@ +package org.biojava.nbio.structure.contact; + +import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.xtal.CrystalTransform; +import org.biojava.nbio.structure.xtal.SpaceGroup; + +import javax.vecmath.Point3d; +import java.util.List; + +/** + * A class containing methods to find interfaces in a given structure. + * @author Jose Duarte + * @since 5.4.0 + */ +public class InterfaceFinder { + + public static final double DEFAULT_CONTACT_CUTOFF = 6; + + private static final CrystalTransform IDENTITY_TRANSFORM = new CrystalTransform((SpaceGroup) null); + private static final boolean INCLUDE_HETATOMS = true; + + private final Structure structure; + private double cutoff; + + private BoundingBox[] boundingBoxes; + + public InterfaceFinder(Structure structure) { + this.structure = structure; + this.cutoff = DEFAULT_CONTACT_CUTOFF; + } + + /** + * Set the contact distance cutoff. + * @param cutoff the distance value in Angstroms + */ + public void setCutoff(double cutoff) { + this.cutoff = cutoff; + } + + /** + * Find all inter polymer-chain interfaces in the structure. + * Two chains will be considered in contact if at least a pair of atoms (one from each chain) is within the + * contact cutoff. + * @return the list of all interfaces + */ + public StructureInterfaceList getAllInterfaces() { + initBoundingBoxes(); + + StructureInterfaceList list = new StructureInterfaceList(); + + List polyChains = structure.getPolyChains(); + for (int i = 0; i polyChains = structure.getPolyChains(); + boundingBoxes = new BoundingBox[polyChains.size()]; + for (int i = 0; i0) { + interf = new StructureInterface( + StructureTools.getAllNonHAtomArray(chain1, INCLUDE_HETATOMS), StructureTools.getAllNonHAtomArray(chain2, INCLUDE_HETATOMS), + chain1.getName(), chain2.getName(), + graph, + IDENTITY_TRANSFORM, IDENTITY_TRANSFORM); + } + + return interf; + } +} diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/Pair.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/Pair.java index 88f7d01b17..23a2cac4aa 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/Pair.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/Pair.java @@ -35,8 +35,8 @@ public final class Pair implements Serializable { private static final long serialVersionUID = 1L; - private T first; - private T second; + private final T first; + private final T second; /** * Creates a Pair from the specified elements. diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/ResidueIdentifier.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/ResidueIdentifier.java index 5fa0dbd179..073e4b4016 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/ResidueIdentifier.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/ResidueIdentifier.java @@ -20,14 +20,14 @@ */ package org.biojava.nbio.structure.contact; -import java.io.Serializable; - import org.biojava.nbio.structure.Chain; import org.biojava.nbio.structure.EntityInfo; import org.biojava.nbio.structure.Group; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.Serializable; + /** * A bean for identifying groups in GroupContactSets. * Used only within the contact package to be able to compare diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/StructureInterface.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/StructureInterface.java index e9150fcfbe..e2560a49a3 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/StructureInterface.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/StructureInterface.java @@ -20,20 +20,7 @@ */ package org.biojava.nbio.structure.contact; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.Element; -import org.biojava.nbio.structure.EntityInfo; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.GroupType; -import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.asa.AsaCalculator; import org.biojava.nbio.structure.asa.GroupAsa; import org.biojava.nbio.structure.io.FileConvert; @@ -47,6 +34,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + /** * An interface between 2 molecules (2 sets of atoms). @@ -285,12 +278,8 @@ protected Atom[] getAtomsForAsa(int cofactorSizeToUse) { Atom[] atoms2 = getSecondAtomsForAsa(cofactorSizeToUse); Atom[] atoms = new Atom[atoms1.length+atoms2.length]; - for (int i=0;i atoms = new ArrayList<>(); for (Atom a:m){ @@ -321,7 +310,7 @@ private static final Atom[] getAllNonHAtomArray(Atom[] m, int minSizeHetAtomToIn atoms.add(a); } - return atoms.toArray(new Atom[atoms.size()]); + return atoms.toArray(Atom.EmptyAtomArray); } /** @@ -348,7 +337,7 @@ private static boolean isInChain(Group g) { ChemComp chemComp = g.getChemComp(); if (chemComp==null) { - logger.warn("Warning: can't determine PolymerType for group "+g.getResidueNumber()+" ("+g.getPDBName()+"). Will consider it as non-nucleotide/non-protein type."); + logger.warn("Can't determine PolymerType for group "+g.getResidueNumber()+" ("+g.getPDBName()+"). Will consider it as non-nucleotide/non-protein type."); return false; } @@ -458,8 +447,8 @@ public GroupAsa getSecondGroupAsa(ResidueNumber resNum) { */ public Pair> getCoreResidues(double bsaToAsaCutoff, double minAsaForSurface) { - List core1 = new ArrayList(); - List core2 = new ArrayList(); + List core1 = new ArrayList<>(); + List core2 = new ArrayList<>(); for (GroupAsa groupAsa:groupAsas1.values()) { @@ -482,7 +471,7 @@ public Pair> getCoreResidues(double bsaToAsaCutoff, double minAsaFor } } - return new Pair>(core1, core2); + return new Pair<>(core1, core2); } /** @@ -494,8 +483,8 @@ public Pair> getCoreResidues(double bsaToAsaCutoff, double minAsaFor */ public Pair> getRimResidues(double bsaToAsaCutoff, double minAsaForSurface) { - List rim1 = new ArrayList(); - List rim2 = new ArrayList(); + List rim1 = new ArrayList<>(); + List rim2 = new ArrayList<>(); for (GroupAsa groupAsa:groupAsas1.values()) { @@ -518,7 +507,7 @@ public Pair> getRimResidues(double bsaToAsaCutoff, double minAsaForS } } - return new Pair>(rim1, rim2); + return new Pair<>(rim1, rim2); } /** @@ -529,8 +518,8 @@ public Pair> getRimResidues(double bsaToAsaCutoff, double minAsaForS */ public Pair> getInterfacingResidues(double minAsaForSurface) { - List interf1 = new ArrayList(); - List interf2 = new ArrayList(); + List interf1 = new ArrayList<>(); + List interf2 = new ArrayList<>(); for (GroupAsa groupAsa:groupAsas1.values()) { @@ -545,7 +534,7 @@ public Pair> getInterfacingResidues(double minAsaForSurface) { } } - return new Pair>(interf1, interf2); + return new Pair<>(interf1, interf2); } /** @@ -554,8 +543,8 @@ public Pair> getInterfacingResidues(double minAsaForSurface) { * @return */ public Pair> getSurfaceResidues(double minAsaForSurface) { - List surf1 = new ArrayList(); - List surf2 = new ArrayList(); + List surf1 = new ArrayList<>(); + List surf2 = new ArrayList<>(); for (GroupAsa groupAsa:groupAsas1.values()) { @@ -570,7 +559,7 @@ public Pair> getSurfaceResidues(double minAsaForSurface) { } } - return new Pair>(surf1, surf2); + return new Pair<>(surf1, surf2); } public StructureInterfaceCluster getCluster() { @@ -585,12 +574,12 @@ public void setCluster(StructureInterfaceCluster cluster) { * Calculates the contact overlap score between this StructureInterface and * the given one. * The two sides of the given StructureInterface need to match this StructureInterface - * in the sense that they must come from the same Compound (Entity), i.e. + * in the sense that they must come from the same Entity, i.e. * their residue numbers need to align with 100% identity, except for unobserved * density residues. The SEQRES indices obtained through {@link EntityInfo#getAlignedResIndex(Group, Chain)} are * used to match residues, thus if no SEQRES is present or if {@link FileParsingParameters#setAlignSeqRes(boolean)} * is not used, this calculation is not guaranteed to work properly. - * @param other + * @param other the interface to be compared to this one * @param invert if false the comparison will be done first-to-first and second-to-second, * if true the match will be first-to-second and second-to-first * @return the contact overlap score, range [0.0,1.0] @@ -619,8 +608,8 @@ public double getContactOverlapScore(StructureInterface other, boolean invert) { return 0; } - Pair thisCompounds = new Pair(thisChains.getFirst().getEntityInfo(), thisChains.getSecond().getEntityInfo()); - Pair otherCompounds = new Pair(otherChains.getFirst().getEntityInfo(), otherChains.getSecond().getEntityInfo()); + Pair thisCompounds = new Pair<>(thisChains.getFirst().getEntityInfo(), thisChains.getSecond().getEntityInfo()); + Pair otherCompounds = new Pair<>(otherChains.getFirst().getEntityInfo(), otherChains.getSecond().getEntityInfo()); if ( ( (thisCompounds.getFirst() == otherCompounds.getFirst()) && (thisCompounds.getSecond() == otherCompounds.getSecond()) ) || @@ -633,8 +622,8 @@ public double getContactOverlapScore(StructureInterface other, boolean invert) { for (GroupContact thisContact:thisContacts) { - ResidueIdentifier first = null; - ResidueIdentifier second = null; + ResidueIdentifier first; + ResidueIdentifier second; if (!invert) { first = new ResidueIdentifier(thisContact.getPair().getFirst()); @@ -668,7 +657,7 @@ public GroupContactSet getGroupContacts() { /** * Tell whether the interface is isologous, i.e. it is formed - * by the same patches of same Compound on both sides. + * by the same patches of same entity on both sides. * * @return true if isologous, false if heterologous */ @@ -691,11 +680,11 @@ public Pair getParentChains() { return null; } - return new Pair(firstMol[0].getGroup().getChain(), secondMol[0].getGroup().getChain()); + return new Pair<>(firstMol[0].getGroup().getChain(), secondMol[0].getGroup().getChain()); } /** - * Finds the parent compounds by looking up the references of first atom of each side of this interface + * Finds the parent entities by looking up the references of first atom of each side of this interface * @return */ public Pair getParentCompounds() { @@ -704,7 +693,7 @@ public Pair getParentCompounds() { logger.warn("Could not find parents chains, compounds will be null"); return null; } - return new Pair(chains.getFirst().getEntityInfo(), chains.getSecond().getEntityInfo()); + return new Pair<>(chains.getFirst().getEntityInfo(), chains.getSecond().getEntityInfo()); } private Structure getParentStructure() { @@ -720,7 +709,7 @@ private Structure getParentStructure() { * Return a String representing the 2 molecules of this interface in PDB format. * If the molecule ids (i.e. chain ids) are the same for both molecules, then the second * one will be replaced by the next letter in alphabet (or A for Z) - * @return + * @return the PDB-formatted string */ public String toPDB() { @@ -758,7 +747,7 @@ public String toPDB() { * Return a String representing the 2 molecules of this interface in mmCIF format. * If the molecule ids (i.e. chain ids) are the same for both molecules, then the second * one will be written as chainId_operatorId (with operatorId taken from {@link #getTransforms()} - * @return + * @return the mmCIF-formatted string */ public String toMMCIF() { StringBuilder sb = new StringBuilder(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/StructureInterfaceCluster.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/StructureInterfaceCluster.java index 5b1699bf8a..8743cdff9a 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/StructureInterfaceCluster.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/StructureInterfaceCluster.java @@ -40,7 +40,7 @@ public class StructureInterfaceCluster implements Serializable { public StructureInterfaceCluster() { - this.members = new ArrayList(); + this.members = new ArrayList<>(); } public List getMembers() { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/StructureInterfaceList.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/StructureInterfaceList.java index 8bc0b627d0..319de6b279 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/StructureInterfaceList.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/contact/StructureInterfaceList.java @@ -20,16 +20,6 @@ */ package org.biojava.nbio.structure.contact; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.TreeMap; - import org.biojava.nbio.core.util.SingleLinkageClusterer; import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Structure; @@ -38,6 +28,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.Serializable; +import java.util.*; + /** * A list of interfaces between 2 molecules (2 sets of atoms) @@ -74,7 +67,7 @@ public class StructureInterfaceList implements Serializable, Iterable list; + private final List list; private List clusters = null; private List clustersNcs = null; @@ -164,11 +157,12 @@ public void calcAsas(int nSpherePoints, int nThreads, int cofactorSizeToUse) { long start = System.currentTimeMillis(); // we only need to calculate ASA for that subset (any translation of those will have same values) - for (String molecId:uniqAsaChains.keySet()) { + for (Map.Entry entry : uniqAsaChains.entrySet()) { + String molecId = entry.getKey(); - logger.debug("Calculating uncomplexed ASA for molecId {}, with {} atoms", molecId, uniqAsaChains.get(molecId).length); + logger.debug("Calculating uncomplexed ASA for molecId {}, with {} atoms", molecId, entry.getValue().length); - AsaCalculator asaCalc = new AsaCalculator(uniqAsaChains.get(molecId), + AsaCalculator asaCalc = new AsaCalculator(entry.getValue(), AsaCalculator.DEFAULT_PROBE_SIZE, nSpherePoints, nThreads); double[] atomAsas = asaCalc.calculateAsas(); @@ -398,9 +392,9 @@ public List getClusters(double contactOverlapScoreClu SingleLinkageClusterer slc = new SingleLinkageClusterer(matrix, true); Map> clusteredIndices = slc.getClusters(contactOverlapScoreClusterCutoff); - for (int clusterIdx:clusteredIndices.keySet()) { + for (Set integers : clusteredIndices.values()) { List members = new ArrayList<>(); - for (int idx:clusteredIndices.get(clusterIdx)) { + for (int idx: integers) { members.add(list.get(idx)); } StructureInterfaceCluster cluster = new StructureInterfaceCluster(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/AssignmentXMLSerializer.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/AssignmentXMLSerializer.java index d6a75c6560..8f29abedee 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/AssignmentXMLSerializer.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/AssignmentXMLSerializer.java @@ -55,7 +55,7 @@ public class AssignmentXMLSerializer { } public AssignmentXMLSerializer(){ - assignments = new HashMap(); + assignments = new HashMap<>(); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/DomainProvider.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/DomainProvider.java index 044aaba4a5..81fb6f2754 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/DomainProvider.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/DomainProvider.java @@ -20,11 +20,11 @@ */ package org.biojava.nbio.structure.domain; +import org.biojava.nbio.structure.StructureException; + import java.io.IOException; import java.util.SortedSet; -import org.biojava.nbio.structure.StructureException; - /** * Decomposes a structure from the PDB into representative domains */ @@ -37,7 +37,7 @@ public interface DomainProvider { * @throws IOException For IO errors getting the domains * @throws StructureException For errors converting name to a valid identifier */ - public SortedSet getDomainNames(String name) throws IOException, StructureException; + SortedSet getDomainNames(String name) throws IOException, StructureException; /** * Get the full list of representative domains for the PDB. * @@ -46,5 +46,5 @@ public interface DomainProvider { * @return A full list of all representative domains recognized by this provider * @throws IOException For IO errors getting the representatives */ - public SortedSet getRepresentativeDomains() throws IOException; + SortedSet getRepresentativeDomains() throws IOException; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/LocalProteinDomainParser.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/LocalProteinDomainParser.java index 3b621d9be6..17a318e5b9 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/LocalProteinDomainParser.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/LocalProteinDomainParser.java @@ -23,7 +23,10 @@ */ package org.biojava.nbio.structure.domain; -import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.Atom; +import org.biojava.nbio.structure.Chain; +import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.domain.pdp.*; import java.util.List; @@ -60,9 +63,8 @@ private LocalProteinDomainParser(){ * * @param s the protein structure * @return a list of possible domains - * @throws StructureException - */ - public static List suggestDomains(Structure s) throws StructureException{ + */ + public static List suggestDomains(Structure s) { Atom[] ca = StructureTools.getRepresentativeAtomArray(s); @@ -74,13 +76,12 @@ public static List suggestDomains(Structure s) throws StructureException * * @param ca an array of Calpha atoms * @return a list of possible domains - * @throws StructureException - */ - public static List suggestDomains(Atom[] ca) throws StructureException{ + */ + public static List suggestDomains(Atom[] ca) { - GetDistanceMatrix distMaxCalculator = new GetDistanceMatrix(); + //GetDistanceMatrix distMaxCalculator = new GetDistanceMatrix(); - PDPDistanceMatrix pdpMatrix = distMaxCalculator.getDistanceMatrix(ca); + PDPDistanceMatrix pdpMatrix = GetDistanceMatrix.getDistanceMatrix(ca); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/PDBDomainProvider.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/PDBDomainProvider.java index adb7f2f6bf..ecc455ef20 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/PDBDomainProvider.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/PDBDomainProvider.java @@ -20,7 +20,7 @@ */ package org.biojava.nbio.structure.domain; -import org.biojava.nbio.structure.align.util.URLConnectionTools; +import org.biojava.nbio.core.util.Download; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; @@ -30,7 +30,6 @@ import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.*; -import java.net.MalformedURLException; import java.net.URL; import java.util.SortedSet; import java.util.TreeSet; @@ -46,8 +45,8 @@ public class PDBDomainProvider implements DomainProvider{ public static final String DEFAULT_PDB_HOST = "http://www.rcsb.org"; public static final String DEFAULT_PDB_API_URL = DEFAULT_PDB_HOST + "/pdb/rest/"; - private String base; - private int cutoff; + private final String base; + private final int cutoff; /** */ @@ -95,11 +94,11 @@ private SortedSet requestRepresentativeDomains(String url) { //System.out.println(url); - final SortedSet results = new TreeSet(); + final SortedSet results = new TreeSet<>(); DefaultHandler handler = new DefaultHandler() { @Override public void startElement(String uri, String localName,String qName, - Attributes attributes) throws SAXException { + Attributes attributes) { //System.out.println("Start Element :" + qName); @@ -111,13 +110,7 @@ public void startElement(String uri, String localName,String qName, }; handleRestRequest(url,handler); return results; - } catch (MalformedURLException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (SAXException e) { - e.printStackTrace(); - } catch (ParserConfigurationException e) { + } catch (ParserConfigurationException | SAXException | IOException e) { e.printStackTrace(); } return null; @@ -134,7 +127,7 @@ public void startElement(String uri, String localName,String qName, private static void handleRestRequest(String url, DefaultHandler handler) throws SAXException, IOException, ParserConfigurationException { // Fetch XML stream URL u = new URL(url); - InputStream response = URLConnectionTools.getInputStream(u); + InputStream response = Download.stream(u); InputSource xml = new InputSource(response); // Parse XML diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/PDPDomain.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/PDPDomain.java index fe3f6b6beb..7c45030995 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/PDPDomain.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/PDPDomain.java @@ -20,23 +20,18 @@ */ package org.biojava.nbio.structure.domain; -import java.io.IOException; +import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.align.util.AtomCache; + import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.biojava.nbio.structure.ResidueRange; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIdentifier; -import org.biojava.nbio.structure.SubstructureIdentifier; -import org.biojava.nbio.structure.align.util.AtomCache; - public class PDPDomain implements StructureIdentifier { private static final long serialVersionUID = 6894463080739943026L; - private String identifier; - private SubstructureIdentifier canonical; + private final String identifier; + private final SubstructureIdentifier canonical; public static final Pattern PDP_NAME_PATTERN = Pattern.compile("^(?:PDP:)([0-9][a-z0-9]{3})(\\w)(\\w)$",Pattern.CASE_INSENSITIVE); @@ -56,8 +51,8 @@ public String getIdentifier() { } public String getPdbId() { - return canonical.getPdbId(); - } + return canonical.pdbId; + } @Override public SubstructureIdentifier toCanonical() { @@ -75,8 +70,7 @@ public String toString() { } @Override - public Structure loadStructure(AtomCache cache) throws StructureException, - IOException { + public Structure loadStructure(AtomCache cache) throws StructureException { return canonical.loadStructure(cache); } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/PDPProvider.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/PDPProvider.java index d621373bb1..12b9569860 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/PDPProvider.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/PDPProvider.java @@ -24,13 +24,13 @@ */ package org.biojava.nbio.structure.domain; -import java.io.IOException; -import java.util.SortedSet; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.util.AtomCache; +import java.io.IOException; +import java.util.SortedSet; + /** * Decomposes a structure into representative PDP domains. * @@ -48,7 +48,7 @@ public interface PDPProvider { * @return Set of domain names, e.g. "PDP:4HHBAa" * @throws IOException */ - public SortedSet getPDPDomainNamesForPDB(String pdbId) throws IOException; + SortedSet getPDPDomainNamesForPDB(String pdbId) throws IOException; /** * Get the structure for a particular PDP domain * @param pdpDomainName PDP identifier, e.g. "PDP:4HHBAa" @@ -57,7 +57,7 @@ public interface PDPProvider { * @throws IOException For IO errors, e.g. when parsing PDP information * @throws StructureException For errors creating the structure */ - public Structure getDomain(String pdpDomainName, AtomCache cache) throws IOException, StructureException; + Structure getDomain(String pdpDomainName, AtomCache cache) throws IOException, StructureException; /** * Get a StructureIdentifier representing the specified PDP domain. * @@ -65,5 +65,5 @@ public interface PDPProvider { * @return a PDPDomain representing this domain name * @throws IOException */ - public PDPDomain getPDPDomain(String pdpDomainName) throws IOException; + PDPDomain getPDPDomain(String pdpDomainName) throws IOException; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/RemoteDomainProvider.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/RemoteDomainProvider.java index 5d5aaaefd6..c588f0a377 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/RemoteDomainProvider.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/RemoteDomainProvider.java @@ -20,19 +20,10 @@ */ package org.biojava.nbio.structure.domain; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.List; -import java.util.Map; -import java.util.SortedSet; -import java.util.TreeSet; - +import org.biojava.nbio.core.util.Download; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.client.JFatCatClient; import org.biojava.nbio.structure.align.client.StructureName; -import org.biojava.nbio.structure.align.util.URLConnectionTools; import org.biojava.nbio.structure.scop.ScopDatabase; import org.biojava.nbio.structure.scop.ScopDomain; import org.biojava.nbio.structure.scop.ScopFactory; @@ -40,6 +31,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.*; + /** * A DomainProvider that uses a mixture of SCOP and PDP domains. @@ -53,12 +50,12 @@ public class RemoteDomainProvider extends SerializableCache> implements DomainProvider{ private static final Logger logger = LoggerFactory.getLogger(RemoteDomainProvider.class); - public String url = RemotePDPProvider.DEFAULT_SERVER; + public final String url = RemotePDPProvider.DEFAULT_SERVER; ScopDatabase scop; PDPProvider pdp; - private static String CACHE_FILE_NAME = "remotedomaincache.ser"; + private static final String CACHE_FILE_NAME = "remotedomaincache.ser"; public RemoteDomainProvider(){ @@ -95,29 +92,25 @@ public RemoteDomainProvider(boolean cache) throws IOException{ * */ private void loadRepresentativeDomainAssignments() throws IOException { - AssignmentXMLSerializer results = null; + AssignmentXMLSerializer results; try { URL u = new URL(url + "getRepresentativeDomains"); logger.info("Fetching {}",u); - InputStream response = URLConnectionTools.getInputStream(u); + InputStream response = Download.stream(u); String xml = JFatCatClient.convertStreamToString(response); results = AssignmentXMLSerializer.fromXML(xml); Map data = results.getAssignments(); logger.info("got {} ranges from server.",data.size()); - for (String key: data.keySet()){ - String range = data.get(key); + for (Map.Entry entry : data.entrySet()){ + String range = entry.getValue(); // work around list in results; String[] spl = range.split(","); - SortedSet value = new TreeSet(); - - for (String s : spl){ - value.add(s); - } - serializedCache.put(key, value); + SortedSet value = new TreeSet<>(Arrays.asList(spl)); + serializedCache.put(entry.getKey(), value); } } catch (MalformedURLException e){ @@ -150,7 +143,7 @@ public SortedSet getDomainNames(String name) throws IOException, Structu cache(name,data); return data; } else { - SortedSet r = new TreeSet(); + SortedSet r = new TreeSet<>(); for ( ScopDomain d: scopDomains){ StructureName s = new StructureName(d.getScopId()); @@ -176,7 +169,7 @@ public SortedSet getDomainNames(String name) throws IOException, Structu private SortedSet getPDPDomains(StructureName n) throws IOException, StructureException { SortedSet pdpDomains = pdp.getPDPDomainNamesForPDB(n.getPdbId()); - SortedSet r = new TreeSet(); + SortedSet r = new TreeSet<>(); String chainID = n.getChainId(); for ( String s : pdpDomains){ StructureName d = new StructureName(s); @@ -213,11 +206,11 @@ public void flushCache() { public SortedSet getRepresentativeDomains() throws IOException { String url = "http://source.rcsb.org/jfatcatserver/domains/getRepresentativeDomainNames"; - SortedSet domainRanges = null; + SortedSet domainRanges; try { URL u = new URL(url); logger.info("Fetching {}",url); - InputStream response = URLConnectionTools.getInputStream(u); + InputStream response = Download.stream(u); String xml = JFatCatClient.convertStreamToString(response); //System.out.println(xml); domainRanges = XMLUtil.getDomainRangesFromXML(xml); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/RemotePDPProvider.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/RemotePDPProvider.java index d45a0285bd..06ef1bc3b2 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/RemotePDPProvider.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/RemotePDPProvider.java @@ -24,27 +24,23 @@ */ package org.biojava.nbio.structure.domain; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.SortedSet; -import java.util.TreeSet; - +import org.biojava.nbio.core.util.Download; import org.biojava.nbio.structure.ResidueRange; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.SubstructureIdentifier; import org.biojava.nbio.structure.align.client.JFatCatClient; import org.biojava.nbio.structure.align.util.AtomCache; -import org.biojava.nbio.structure.align.util.URLConnectionTools; import org.biojava.nbio.structure.scop.server.XMLUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.*; + /** A class that provided PDP assignments that are loaded from a remote web server * @@ -59,7 +55,7 @@ public class RemotePDPProvider extends SerializableCache data = results.getAssignments(); logger.info("got {} domain ranges for PDP domains from server.",data.size()); - for (String key: data.keySet()){ - String range = data.get(key); + for (Map.Entry entry : data.entrySet()){ + String range = entry.getValue(); // work around list in results; String[] spl = range.split(","); - SortedSet value = new TreeSet(); - - for (String s : spl){ - value.add(s); - } - serializedCache.put(key, value); + SortedSet value = new TreeSet<>(Arrays.asList(spl)); + serializedCache.put(entry.getKey(), value); } } catch (MalformedURLException e){ @@ -188,7 +180,7 @@ public PDPDomain getPDPDomain(String pdpDomainName) throws IOException{ if (shouldRequestDomainRanges){ URL u = new URL(server + "getPDPDomain?pdpId="+pdpDomainName); logger.info("Fetching {}",u); - InputStream response = URLConnectionTools.getInputStream(u); + InputStream response = Download.stream(u); String xml = JFatCatClient.convertStreamToString(response); domainRanges = XMLUtil.getDomainRangesFromXML(xml); if ( domainRanges != null) @@ -200,12 +192,12 @@ public PDPDomain getPDPDomain(String pdpDomainName) throws IOException{ } String pdbId = null; - List ranges = new ArrayList(); + List ranges = new ArrayList<>(); for(String domainRange : domainRanges) { SubstructureIdentifier strucId = new SubstructureIdentifier(domainRange); - if(pdbId == null) { - pdbId = strucId.getPdbId(); - } else if(!pdbId.equals(strucId.getPdbId())) { + if(pdbId == null) { + pdbId = strucId.pdbId; + } else if(!pdbId.equals(strucId.pdbId)) { // should never happen with correct server implementation throw new RuntimeException("Don't know how to take the union of domains from multiple PDB IDs."); } @@ -244,11 +236,11 @@ private boolean checkDomainRanges(SortedSet domainRanges) { */ @Override public SortedSet getPDPDomainNamesForPDB(String pdbId) throws IOException{ - SortedSet results = null; + SortedSet results; try { URL u = new URL(server + "getPDPDomainNamesForPDB?pdbId="+pdbId); logger.info("Fetching {}",u); - InputStream response = URLConnectionTools.getInputStream(u); + InputStream response = Download.stream(u); String xml = JFatCatClient.convertStreamToString(response); results = XMLUtil.getDomainRangesFromXML(xml); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/SerializableCache.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/SerializableCache.java index b653b73d52..33472d468d 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/SerializableCache.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/SerializableCache.java @@ -42,7 +42,7 @@ public class SerializableCache { private static final Logger logger = LoggerFactory.getLogger(SerializableCache.class); - protected String cacheFileName; + protected final String cacheFileName; protected Map serializedCache ; @@ -117,7 +117,7 @@ public Map reloadFromFile() { File f = getCacheFile(); - serializedCache = new HashMap(); + serializedCache = new HashMap<>(); // has never been cached here before if( ! f.exists()) { @@ -133,13 +133,10 @@ public Map reloadFromFile() { ObjectInputStream ois = new ObjectInputStream(fis); serializedCache = (HashMap) ois.readObject(); ois.close(); - } catch (IOException e){ + } catch (IOException | ClassNotFoundException e){ // TODO shouldn't this be thrown forward? logger.error("Exception caught while reading serialized file",e); return null; - } catch (ClassNotFoundException e) { - logger.error("Exception caught while reading serialized file",e); - return null; } //if ( debug ) diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/pdp/ClusterDomains.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/pdp/ClusterDomains.java index 9c80bc8b3a..6ffb9d594b 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/pdp/ClusterDomains.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/pdp/ClusterDomains.java @@ -28,7 +28,7 @@ public class ClusterDomains { - static private boolean verbose = CutDomain.verbose; + static private final boolean verbose = CutDomain.verbose; private static int ndom; public static List cluster(List domains, PDPDistanceMatrix pdpDistMatrix){ @@ -43,7 +43,7 @@ public static List cluster(List domains, PDPDistanceMatrix pdpDi int Sim = -1; int Sjm = -1; - long total_max_contacts = 0; + long total_max_contacts; double maximum_values = PDPParameters.CUT_OFF_VALUE1S; double maximum_valuem = PDPParameters.CUT_OFF_VALUE1M; @@ -144,7 +144,7 @@ public static List cluster(List domains, PDPDistanceMatrix pdpDi domains.get(Si).avd=domcont(domains.get(Si)); domains.get(Sj).avd=domcont(domains.get(Sj)); */ - if(verbose) System.out.println(String.format(" Listing the domains after combining...")); + if(verbose) System.out.println(" Listing the domains after combining..."); if(verbose) listdomains (domains); } else if (maximum_valuem > PDPParameters.CUT_OFF_VALUE1M) { @@ -162,7 +162,7 @@ else if (maximum_valuem > PDPParameters.CUT_OFF_VALUE1M) { domains[Sim].avd=domcont(domains[Sim]); domains[Sjm].avd=domcont(domains[Sjm]); */ - if(verbose) System.out.println(String.format(" Listing the domains after combining...")); + if(verbose) System.out.println(" Listing the domains after combining..."); if(verbose) listdomains (domains); } else if (maximum_values > PDPParameters.CUT_OFF_VALUE1S) { @@ -180,11 +180,11 @@ else if (maximum_values > PDPParameters.CUT_OFF_VALUE1S) { domains[Sis].avd=domcont(domains[Sis]); domains[Sjs].avd=domcont(domains[Sjs]); */ - if(verbose) System.out.println(String.format(" Listing the domains after combining...")); + if(verbose) System.out.println(" Listing the domains after combining..."); if(verbose) listdomains(domains); } else { - if(verbose) System.out.println(String.format(" Maximum value is less than cut off value. (max:" + maximum_value+")" )); + if(verbose) System.out.println(" Maximum value is less than cut off value. (max:" + maximum_value+")"); maximum_value = -1.0; maximum_values = -1.0; maximum_valuem = -1.0; @@ -192,7 +192,7 @@ else if (maximum_values > PDPParameters.CUT_OFF_VALUE1S) { } } while ( maximum_value > 0.0||maximum_values>0.0||maximum_valuem>0.0); - if(verbose) System.out.println(String.format(" The domains are:")); + if(verbose) System.out.println(" The domains are:"); if(verbose) listdomains(domains); return domains; } @@ -226,7 +226,7 @@ private static List combine(List domains,int Si, int Sj, double if ( verbose) System.out.println(" +++ combining domains " + Si + " " + Sj); - List newdoms = new ArrayList(); + List newdoms = new ArrayList<>(); //int ndom = domains.size(); for(int i=0;i domains){ + private static void listdomains(List domains){ int i = -1; for ( Domain dom : domains){ diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/pdp/Cut.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/pdp/Cut.java index 38bace0f14..03a849100e 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/pdp/Cut.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/pdp/Cut.java @@ -26,9 +26,9 @@ public class Cut { - static boolean verbose = CutDomain.verbose; + static final boolean verbose = CutDomain.verbose; - public int cut( Atom[] ca, Domain dom, CutValues val, int[][] dist, PDPDistanceMatrix pdpMatrix) { + public static int cut(Atom[] ca, Domain dom, CutValues val, int[][] dist, PDPDistanceMatrix pdpMatrix) { int nclose = pdpMatrix.getNclose(); @@ -59,7 +59,7 @@ public int cut( Atom[] ca, Domain dom, CutValues val, int[][] dist, PDPDistanceM List segments = dom.getSegments(); - java.util.Collections.sort(segments, new SegmentComparator()); + segments.sort(new SegmentComparator()); if ( verbose) System.out.println(" --- Cut.cut " + dom + " "); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/pdp/CutDomain.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/pdp/CutDomain.java index 839fdec1c4..be07f49992 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/pdp/CutDomain.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/pdp/CutDomain.java @@ -30,12 +30,12 @@ public class CutDomain { int ndom; - List domains; + final List domains; - public static boolean verbose = true; + public static final boolean verbose = true; - int[][] dist; - Atom[] ca; + final int[][] dist; + final Atom[] ca; public CutDomain(Atom[]ca, PDPDistanceMatrix pdpMatrix){ dist = pdpMatrix.getDist(); @@ -43,7 +43,7 @@ public CutDomain(Atom[]ca, PDPDistanceMatrix pdpMatrix){ ndom = 0; - domains = new ArrayList(); + domains = new ArrayList<>(); } @@ -67,9 +67,9 @@ public void cutDomain(Domain dom, CutSites cut_sites, PDPDistanceMatrix pdpMatr val.first_cut = true; - Cut cut = new Cut(); +// Cut cut = new Cut(); - site = cut.cut(ca,dom,val, dist, pdpMatrix); + site = Cut.cut(ca,dom,val, dist, pdpMatrix); if ( verbose ) System.out.println(" S ... site " + dom + " : site: " + site + " val : " + val); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/pdp/Domain.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/pdp/Domain.java index 878ec29686..c721fc5349 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/pdp/Domain.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/pdp/Domain.java @@ -48,7 +48,7 @@ public class Domain implements Comparable, Serializable{ int nseg; double score; - Listsegments = new ArrayList(); + Listsegments = new ArrayList<>(); public Domain(){ diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/pdp/GetDistanceMatrix.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/pdp/GetDistanceMatrix.java index be3ff6a987..149bf65430 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/pdp/GetDistanceMatrix.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/domain/pdp/GetDistanceMatrix.java @@ -20,169 +20,152 @@ */ package org.biojava.nbio.structure.domain.pdp; -import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.AminoAcid; +import org.biojava.nbio.structure.Atom; +import org.biojava.nbio.structure.Calc; +import org.biojava.nbio.structure.Group; public class GetDistanceMatrix { - - /** A set of Calpha atoms that are representing the protein - * - * @param protein - */ - public PDPDistanceMatrix getDistanceMatrix(Atom[] protein) throws StructureException{ - int[][] dist = new int[protein.length+3][protein.length+3]; - int i,j; - double d,dt1,dt2,dt3,dt4; - int nclose=0; - int[] iclose = new int[protein.length*protein.length]; - int[] jclose= new int[protein.length*protein.length]; - - if(protein.length >= PDPParameters.MAXLEN) { - System.err.println(String.format("%d protein.len > MAXLEN %d\n",protein.length,PDPParameters.MAXLEN)); - return null; - } - for(i=0;i= PDPParameters.MAXLEN) { + System.err.println(String.format("%d protein.len > MAXLEN %d\n", n, PDPParameters.MAXLEN)); + return null; + } + for (i = 0; i < n; i++) { + for (j = i; j < n; j++) { + dist[i][j] = 0; + dist[j][i] = 0; + + + Atom ca1 = protein[i]; + Atom ca2 = protein[j]; + Group g1 = ca1.getGroup(); + Group g2 = ca2.getGroup(); + + Atom cb1 = getCBeta(g1); + Atom cb2 = getCBeta(g2); + boolean hasCbeta1 = cb1 != null; + boolean hasCbeta2 = cb2 != null; + + double d = 0; + + double distance; + if (hasCbeta1 && hasCbeta2) { + distance = Calc.getDistance(cb1, cb2); + } else if (hasCbeta1 && !hasCbeta2) { distance = Calc.getDistance(cb1, ca2); - d += distance * distance; - } - else if(!hasCbeta1&&hasCbeta2) { - double distance = Calc.getDistance(ca1, cb2); - d += distance * distance; - } - else if( ! hasCbeta1&&!hasCbeta2) { - double distance = Calc.getDistance(ca1, ca2); - d += distance * distance; - } - - if(d35) { - iclose[nclose]=i; - jclose[nclose]=j; - nclose++; - } - if(d=2&&j-i>5) { - if(dist[i-1][j-1]>=2&&dist[i+1][j+1]>=2||dist[i-1][j+1]>=2&&dist[i+1][j-1]>=2) { - dist[i][j]+=4; - dist[j][i]+=4; + } else if (!hasCbeta1 && hasCbeta2) { + distance = Calc.getDistance(ca1, cb2); + } else /*if (!hasCbeta1 && !hasCbeta2)*/ { + distance = Calc.getDistance(ca1, ca2); + } + d += distance * distance; + + if (d < dt1) { + dist[i][j] = dist[j][i] = 1; + if (d < dt2) { + dist[i][j] = dist[j][i] = 2; + if (j - i > 35) { + iclose[nclose] = i; + jclose[nclose] = j; + nclose++; + } + if (d < dt3) { + dist[i][j] = dist[j][i] = 4; + if (d < dt4) { + dist[i][j] = dist[j][i] = 6; + } + } + } + } + } + } + /* secondary structure interaction */ + for (i = 1; i < n; i++) { + for (j = i; j < n - 1; j++) { + /* beta-sheet */ + if (dist[i][j] >= 2 && j - i > 5) { + if (dist[i - 1][j - 1] >= 2 && dist[i + 1][j + 1] >= 2 || dist[i - 1][j + 1] >= 2 && dist[i + 1][j - 1] >= 2) { + dist[i][j] += 4; + dist[j][i] += 4; /* printf("1: %d %d %d\n",i,j,dist[i][j]); */ - } - /* alpha-helices */ - else if(i>2&&j=1&&dist[i+3][j+3]>=1||dist[i-3][j+3]>=1&&dist[i+3][j-3]>=1) { - dist[i][j]+=4; - dist[j][i]+=4; + } + /* alpha-helices */ + else if (i > 2 && j < n - 2) { + if (dist[i - 3][j - 3] >= 1 && dist[i + 3][j + 3] >= 1 || dist[i - 3][j + 3] >= 1 && dist[i + 3][j - 3] >= 1) { + dist[i][j] += 4; + dist[j][i] += 4; /* printf("3: %d %d %d\n",i,j,dist[i][j]); */ - } - else if(i>3&&j=1||dist[i-3][j-4]>=1||dist[i-4][j-3]>=1||dist[i-4][j-4]>=1)&& - (dist[i+4][j+4]>=1||dist[i+4][j+3]>=1||dist[i+3][j+3]>=1||dist[i+3][j+4]>=1) - ||(dist[i-4][j+4]>=1||dist[i-4][j+3]>=1||dist[i-3][j+4]>=1||dist[i-3][j+3]>=1)&& - (dist[i+4][j-4]>=1||dist[i+4][j-3]>=1||dist[i+3][j-4]>=1||dist[i+3][j-3]>=1)) { - dist[i][j]+=4; - dist[j][i]+=4; + } else if (i > 3 && j < n - 3) { + if ((dist[i - 3][j - 3] >= 1 || dist[i - 3][j - 4] >= 1 || dist[i - 4][j - 3] >= 1 || dist[i - 4][j - 4] >= 1) && + (dist[i + 4][j + 4] >= 1 || dist[i + 4][j + 3] >= 1 || dist[i + 3][j + 3] >= 1 || dist[i + 3][j + 4] >= 1) + || (dist[i - 4][j + 4] >= 1 || dist[i - 4][j + 3] >= 1 || dist[i - 3][j + 4] >= 1 || dist[i - 3][j + 3] >= 1) && + (dist[i + 4][j - 4] >= 1 || dist[i + 4][j - 3] >= 1 || dist[i + 3][j - 4] >= 1 || dist[i + 3][j - 3] >= 1)) { + dist[i][j] += 4; + dist[j][i] += 4; /* printf("4: %d %d %d\n",i,j,dist[i][j]); */ - } - } - } - } - } - } - - PDPDistanceMatrix matrix = new PDPDistanceMatrix(); - - matrix.setNclose(nclose); - matrix.setIclose(iclose); - matrix.setJclose(jclose); - matrix.setDist(dist); - return matrix; - - } - - - - private Atom getCBeta(Group g1) { - Atom cb = null; - - - cb = g1.getAtom("CB"); - if ( cb == null) - { - if ( g1 instanceof AminoAcid) { - AminoAcid aa = (AminoAcid) g1; - - try { - cb = Calc.createVirtualCBAtom(aa); - } catch (StructureException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - } - } - return cb; - } - - - - - - - + } + } + } + } + } + } + + PDPDistanceMatrix matrix = new PDPDistanceMatrix(); + + matrix.setNclose(nclose); + matrix.setIclose(iclose); + matrix.setJclose(jclose); + matrix.setDist(dist); + return matrix; + + } + + + private static Atom getCBeta(Group g1) { + Atom cb; + + + cb = g1.getAtom("CB"); + if (cb == null) { + if (g1 instanceof AminoAcid) { + AminoAcid aa = (AminoAcid) g1; + +// try { + cb = Calc.createVirtualCBAtom(aa); +// } catch (StructureException e1) { +// // TODO Auto-generated catch block +// e1.printStackTrace(); +// } + } + } + return cb; + } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/ecod/EcodDatabase.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/ecod/EcodDatabase.java index d9170766b7..bc6b28d482 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/ecod/EcodDatabase.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/ecod/EcodDatabase.java @@ -34,7 +34,7 @@ public interface EcodDatabase { * @return version * @throws IOException */ - public String getVersion() throws IOException; + String getVersion() throws IOException; /** * Get a particular ECOD domain by the domain ID (e.g. "e4hhbA1") @@ -42,7 +42,7 @@ public interface EcodDatabase { * @return * @throws IOException */ - public EcodDomain getDomainsById(String ecodId) throws IOException; + EcodDomain getDomainsById(String ecodId) throws IOException; /** * Get a list of all ECOD domains for a particular PDB ID @@ -50,7 +50,7 @@ public interface EcodDatabase { * @return the list of domains, or null if no matching domains were found * @throws IOException */ - public List getDomainsForPdb(String pdbId) throws IOException; + List getDomainsForPdb(String pdbId) throws IOException; /** * Get a list of domains within a particular level of the hierarchy @@ -59,12 +59,12 @@ public interface EcodDatabase { * @return * @throws IOException */ - public List filterByHierarchy(String hierarchy) throws IOException; + List filterByHierarchy(String hierarchy) throws IOException; /** * Get all ECOD domains * @return * @throws IOException */ - public List getAllDomains() throws IOException; + List getAllDomains() throws IOException; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/ecod/EcodDomain.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/ecod/EcodDomain.java index 55ce880ec2..ae2d296f85 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/ecod/EcodDomain.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/ecod/EcodDomain.java @@ -22,7 +22,6 @@ import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; -import java.io.IOException; import java.io.Serializable; import java.util.HashSet; import java.util.List; @@ -150,13 +149,13 @@ public EcodDomain(EcodDomain o) { this.tGroupName = o.tGroupName; this.fGroupName = o.fGroupName; this.assemblyId = o.assemblyId; - this.ligands = new HashSet(o.ligands); + this.ligands = new HashSet<>(o.ligands); } @Override - protected Object clone() throws CloneNotSupportedException { + protected Object clone() { return new EcodDomain(this); } @@ -454,8 +453,7 @@ public Structure reduce(Structure input) throws StructureException { } @Override - public Structure loadStructure(AtomCache cache) throws StructureException, - IOException { + public Structure loadStructure(AtomCache cache) throws StructureException { return cache.getStructureForPdbId(pdbId); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/ecod/EcodFactory.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/ecod/EcodFactory.java index 89791c59e1..fad6f663b5 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/ecod/EcodFactory.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/ecod/EcodFactory.java @@ -20,20 +20,19 @@ */ package org.biojava.nbio.structure.ecod; -import java.io.IOException; -import java.lang.ref.SoftReference; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; - import org.biojava.nbio.structure.align.util.UserConfiguration; import org.biojava.nbio.structure.cath.CathFactory; import org.biojava.nbio.structure.scop.ScopFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.lang.ref.SoftReference; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; + /** * Controls global {@link EcodDatabase EcodDatabases} being used. * Implements a multiton pattern through {@link #getEcodDatabase(String)}, @@ -49,8 +48,9 @@ public class EcodFactory { public static final String DEFAULT_VERSION = EcodInstallation.DEFAULT_VERSION; - private static Map> versionedEcodDBs = - Collections.synchronizedMap(new HashMap>()); + private static final Map> versionedEcodDBs = + //Collections.synchronizedMap(new HashMap<>()); + new ConcurrentHashMap(); private static String defaultVersion = EcodInstallation.DEFAULT_VERSION; /** @@ -79,19 +79,19 @@ public static EcodDatabase getEcodDatabase(String version) { logger.debug("Creating new {}, version {}",EcodInstallation.class.getSimpleName(),version); String cacheDir = new UserConfiguration().getCacheFilePath(); ecod = new EcodInstallation(cacheDir, version); - versionedEcodDBs.put(version.toLowerCase(), new SoftReference(ecod)); + versionedEcodDBs.put(version.toLowerCase(), new SoftReference<>(ecod)); // If the parsed version differed from that requested, add that too // Note that getVersion() may trigger file parsing try { - if( ! versionedEcodDBs.containsKey(ecod.getVersion().toLowerCase()) ) { - versionedEcodDBs.put(ecod.getVersion().toLowerCase(),new SoftReference(ecod)); - } + + versionedEcodDBs.putIfAbsent(ecod.getVersion().toLowerCase(), new SoftReference<>(ecod)); + } catch (IOException e) { // For parsing errors, just use the requested version } } - logger.trace("Releasing EcodFactory lock after getting version "+version); + //logger.trace("Releasing EcodFactory lock after getting version "+version); return ecod; } @@ -107,7 +107,7 @@ private static void releaseReferences() { Entry> entry = it.next(); SoftReference ref = entry.getValue(); if(ref.get() == null) { - logger.debug("Removed version {} from EcodFactory to save memory.",entry.getKey()); + //logger.debug("Removed version {} from EcodFactory to save memory.",entry.getKey()); it.remove(); } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/ecod/EcodInstallation.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/ecod/EcodInstallation.java index 836d19f107..92cd5ebdbb 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/ecod/EcodInstallation.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/ecod/EcodInstallation.java @@ -20,33 +20,18 @@ package org.biojava.nbio.structure.ecod; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.Reader; -import java.net.MalformedURLException; +import org.biojava.nbio.core.util.Download; +import org.biojava.nbio.structure.align.util.UserConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; import java.net.URL; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.locks.ReadWriteLock; +import java.util.*; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.biojava.nbio.structure.align.util.UserConfiguration; -import org.biojava.nbio.core.util.FileDownloadUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Provides access to the Evolutionary Classification of Protein Domains (ECOD). * @@ -77,12 +62,12 @@ public class EcodInstallation implements EcodDatabase { private String cacheLocation; - private String requestedVersion; // version requested, e.g. "latest". Used for the paths + private final String requestedVersion; // version requested, e.g. "latest". Used for the paths private String parsedVersion; // actual version parsed // lock to prevent multiple threads from downloading simultaneously // Should hold the lock when reading/writing allDomains or domainMap - private ReadWriteLock domainsFileLock; + private final ReentrantReadWriteLock domainsFileLock; private List allDomains; private Map> domainMap;//PDB ID -> domains, lazily constructed from allDomains @@ -99,7 +84,7 @@ public class EcodInstallation implements EcodDatabase { * @param requestedVersion ECOD requestedVersion to fetch */ public EcodInstallation(String cacheLocation, String version) { - domainsFileLock = new ReentrantReadWriteLock(); + domainsFileLock = new ReentrantReadWriteLock(true); this.cacheLocation = cacheLocation; @@ -134,11 +119,11 @@ public List getDomainsForPdb(String pdbId) throws IOException { logger.trace("LOCK readlock"); while( domainMap == null ) { // unlock to allow ensureDomainsFileInstalled to get the write lock - logger.trace("UNLOCK readlock"); - domainsFileLock.readLock().unlock(); + //logger.trace("UNLOCK readlock"); + //domainsFileLock.readLock().unlock(); indexDomains(); - domainsFileLock.readLock().lock(); - logger.trace("LOCK readlock"); + //domainsFileLock.readLock().lock(); + //logger.trace("LOCK readlock"); } if(pdbId != null) @@ -148,7 +133,7 @@ public List getDomainsForPdb(String pdbId) throws IOException { return null; } // Deep clone - List clonedDoms = new ArrayList(doms.size()); + List clonedDoms = new ArrayList<>(doms.size()); for(EcodDomain d : doms) { clonedDoms.add( new EcodDomain(d) ); } @@ -173,7 +158,7 @@ public List filterByHierarchy(String hierarchy) throws IOException { Integer hGroup = xhtGroup.length>1 ? Integer.parseInt(xhtGroup[1]) : null; Integer tGroup = xhtGroup.length>2 ? Integer.parseInt(xhtGroup[2]) : null; - List filtered = new ArrayList(); + List filtered = new ArrayList<>(); for(EcodDomain d: getAllDomains()) { boolean match = true; if(xhtGroup.length>0) { @@ -232,8 +217,8 @@ public EcodDomain getDomainsById(String ecodId) throws IOException { */ @Override public List getAllDomains() throws IOException { - domainsFileLock.readLock().lock(); logger.trace("LOCK readlock"); + domainsFileLock.readLock().lock(); try { while( allDomains == null) { // unlock to allow ensureDomainsFileInstalled to get the write lock @@ -335,81 +320,80 @@ public void ensureDomainsFileInstalled() throws IOException{ if( allDomains != null ) { return; } - } finally { - logger.trace("UNLOCK readlock"); - domainsFileLock.readLock().unlock(); - } - // Download domains - domainsFileLock.writeLock().lock(); - logger.trace("LOCK writelock"); - try { - if( !domainsAvailable() ) { - downloadDomains(); + domainsFileLock.writeLock().lock(); + logger.trace("LOCK writelock"); + try { + parseDomains(new URL( url + DOMAINS_PATH + getDomainFilename())); + } finally { + logger.trace("UNLOCK writelock"); + domainsFileLock.writeLock().unlock(); } - parseDomains(); - } finally { - logger.trace("UNLOCK writelock"); - domainsFileLock.writeLock().unlock(); - } - } - /** - * Checks that the domains file has been downloaded - * @return - */ - private boolean domainsAvailable() { - domainsFileLock.readLock().lock(); - logger.trace("LOCK readlock"); - try { - File f = getDomainFile(); - - if (!f.exists() || f.length() <= 0 ) - return false; - - // Re-download old copies of "latest" - if(updateFrequency != null && requestedVersion == DEFAULT_VERSION ) { - long mod = f.lastModified(); - // Time of last update - Date lastUpdate = new Date(); - Calendar cal = Calendar.getInstance(); - cal.setTime(lastUpdate); - cal.add(Calendar.DAY_OF_WEEK, -updateFrequency); - long updateTime = cal.getTimeInMillis(); - // Check if file predates last update - if( mod < updateTime ) { - logger.info("{} is out of date.",f); - return false; - } - } - return true; } finally { logger.trace("UNLOCK readlock"); domainsFileLock.readLock().unlock(); } - } - /** - * Downloads the domains file, overwriting any existing file - * @throws IOException - */ - private void downloadDomains() throws IOException { - domainsFileLock.writeLock().lock(); - logger.trace("LOCK writelock"); - try { - URL domainsURL = new URL( url + DOMAINS_PATH + getDomainFilename()); - File localFile = getDomainFile(); - logger.info("Downloading {} to: {}",domainsURL, localFile); - FileDownloadUtils.downloadFile(domainsURL, localFile); - } catch (MalformedURLException e) { - logger.error("Malformed url: "+ url + DOMAINS_PATH + getDomainFilename(),e); - } finally { - logger.trace("UNLOCK writelock"); - domainsFileLock.writeLock().unlock(); - } } +// /** +// * Checks that the domains file has been downloaded +// * @return +// */ +// private boolean domainsAvailable() { +// domainsFileLock.readLock().lock(); +// logger.trace("LOCK readlock"); +// try { +// File f = getDomainFile(); +// +// if (!f.exists() || f.length() <= 0 ) +// return false; +// +// // Re-download old copies of "latest" +// if(updateFrequency != null && requestedVersion.equals(DEFAULT_VERSION)) { +// long mod = f.lastModified(); +// // Time of last update +// Date lastUpdate = new Date(); +// Calendar cal = Calendar.getInstance(); +// cal.setTime(lastUpdate); +// cal.add(Calendar.DAY_OF_WEEK, -updateFrequency); +// long updateTime = cal.getTimeInMillis(); +// // Check if file predates last update +// if( mod < updateTime ) { +// logger.info("{} is out of date.",f); +// return false; +// } +// } +// return true; +// } finally { +// logger.trace("UNLOCK readlock"); +// domainsFileLock.readLock().unlock(); +// } +// } + +// /** +// * Downloads the domains file, overwriting any existing file +// * @throws IOException +// */ +// private void downloadDomains() throws IOException { +// domainsFileLock.writeLock().lock(); +// logger.trace("LOCK writelock"); +// try { +// URL domainsURL = new URL( url + DOMAINS_PATH + getDomainFilename()); +// File localFile = getDomainFile(); +// +// logger.info("Downloading {} to: {}",domainsURL, localFile); +// Download.downloadFile(domainsURL, localFile); +// } catch (MalformedURLException e) { +// logger.error("Malformed url: "+ url + DOMAINS_PATH + getDomainFilename(),e); +// } finally { +// logger.trace("UNLOCK writelock"); +// domainsFileLock.writeLock().unlock(); +// } +// } + /** * Basename for the domains file with the current requestedVersion. * @return @@ -426,42 +410,35 @@ private File getDomainFile() { return new File(getCacheLocation(),getDomainFilename()); } - /** - * The expected ECOD update frequency determines whether the version - * "latest" should be re-downloaded - * @return the expected ECOD update frequency, in days - */ - public Integer getUpdateFrequency() { - return updateFrequency; - } - - /** - * The "latest" version will be re-downloaded if it is older than - * {@link #getUpdateFrequency()} days. Setting this to null disables - * re-downloading (delete $PDB_CACHE_DIR/ecod.latest.domains.txt manually - * to force updating). Setting to 0 will force downloading for every - * program execution. - * @param updateFrequency the updateFrequency to set - */ - public void setUpdateFrequency(Integer updateFrequency) { - this.updateFrequency = updateFrequency; - } +// /** +// * The expected ECOD update frequency determines whether the version +// * "latest" should be re-downloaded +// * @return the expected ECOD update frequency, in days +// */ +// public Integer getUpdateFrequency() { +// return updateFrequency; +// } +// +// /** +// * The "latest" version will be re-downloaded if it is older than +// * {@link #getUpdateFrequency()} days. Setting this to null disables +// * re-downloading (delete $PDB_CACHE_DIR/ecod.latest.domains.txt manually +// * to force updating). Setting to 0 will force downloading for every +// * program execution. +// * @param updateFrequency the updateFrequency to set +// */ +// public void setUpdateFrequency(Integer updateFrequency) { +// this.updateFrequency = updateFrequency; +// } /** * Parses the domains from the local file * @throws IOException */ - private void parseDomains() throws IOException { - domainsFileLock.writeLock().lock(); - logger.trace("LOCK writelock"); - try { - EcodParser parser = new EcodParser(getDomainFile()); - allDomains = parser.getDomains(); - parsedVersion = parser.getVersion(); - } finally { - logger.trace("UNLOCK writelock"); - domainsFileLock.writeLock().unlock(); - } + private void parseDomains(URL u) throws IOException { + EcodParser parser = new EcodParser(Download.bufferedReader(u)); + allDomains = parser.getDomains(); + parsedVersion = parser.getVersion(); } /** @@ -477,7 +454,7 @@ private void indexDomains() throws IOException { } // Leave enough space for all PDBs as of 2015 - domainMap = new HashMap>((int) (150000/.85),.85f); + domainMap = new HashMap<>((int) (150000 / .85), .85f); // Index with domainMap for(EcodDomain d : allDomains) { @@ -486,20 +463,12 @@ private void indexDomains() throws IOException { if( pdbId == null ) { String ecodId = d.getDomainId(); if( ecodId != null && !ecodId.isEmpty() ) { - Matcher match = ECOD_RE.matcher(ecodId); - pdbId = match.group(1); + pdbId = ECOD_RE.matcher(ecodId).group(1); } } // Add current domain to the map - List currDomains; - if( domainMap.containsKey(pdbId) ) { - currDomains = domainMap.get(pdbId); - } else { - currDomains = new LinkedList(); - domainMap.put(pdbId,currDomains); - } - currDomains.add(d); + domainMap.computeIfAbsent(pdbId, k -> new LinkedList<>()).add(d); } } finally { logger.trace("UNLOCK writelock"); @@ -574,7 +543,7 @@ public EcodParser(BufferedReader reader) throws IOException { private void parse(BufferedReader in) throws IOException { try { // Allocate plenty of space for ECOD as of 2015 - ArrayList domainsList = new ArrayList(500000); + ArrayList domainsList = new ArrayList<>(500000); Pattern versionRE = Pattern.compile("^\\s*#.*ECOD\\s*version\\s+(\\S+).*"); Pattern commentRE = Pattern.compile("^\\s*#.*"); @@ -692,12 +661,12 @@ private void parse(BufferedReader in) throws IOException { } String ligandStr = fields[i++]; - Set ligands = null; + Set ligands; if( ligandStr.equals("NO_LIGANDS_4A") || ligandStr.isEmpty() ) { ligands = Collections.emptySet(); } else { String[] ligSplit = ligandStr.split(","); - ligands = new LinkedHashSet(ligSplit.length); + ligands = new LinkedHashSet<>(ligSplit.length); for(String s : ligSplit) { ligands.add(s.intern()); } @@ -767,7 +736,7 @@ public String getVersion() { @Override public String toString() { - String version = null; + String version; try { version = getVersion(); } catch (IOException e) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/CalcPoint.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/CalcPoint.java index c1cfeb73e1..a114aac8be 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/CalcPoint.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/CalcPoint.java @@ -20,12 +20,12 @@ */ package org.biojava.nbio.structure.geometry; +import org.biojava.nbio.structure.jama.Matrix; + import javax.vecmath.Matrix4d; import javax.vecmath.Point3d; import javax.vecmath.Vector3d; -import org.biojava.nbio.structure.jama.Matrix; - /** * Utility operations on Point3d. * @@ -60,6 +60,9 @@ public static void center(Point3d[] x) { * @return centroid as Point3d */ public static Point3d centroid(Point3d[] x) { + if (x.length == 1) + return x[0]; + Point3d center = new Point3d(); for (Point3d p : x) { center.add(p); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/Matrices.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/Matrices.java index a00af40fd8..949347da46 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/Matrices.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/Matrices.java @@ -20,12 +20,12 @@ */ package org.biojava.nbio.structure.geometry; +import org.biojava.nbio.structure.jama.Matrix; + import javax.vecmath.Matrix3d; import javax.vecmath.Matrix4d; import javax.vecmath.Vector3d; -import org.biojava.nbio.structure.jama.Matrix; - /** * Matrices contains static methods to operate and transform matrices used in 3D * geometry (transformation matrices and rotation matrices). diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/MomentsOfInertia.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/MomentsOfInertia.java index 7d638bce65..f33d85516e 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/MomentsOfInertia.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/MomentsOfInertia.java @@ -27,7 +27,6 @@ import javax.vecmath.Matrix3d; import javax.vecmath.Point3d; import javax.vecmath.Vector3d; - import java.util.ArrayList; import java.util.List; @@ -46,19 +45,19 @@ */ public class MomentsOfInertia { - private List points = new ArrayList(); - private List masses = new ArrayList(); + private final List points = new ArrayList<>(); + private final List masses = new ArrayList<>(); private boolean modified = true; private double[] principalMomentsOfInertia = new double[3]; - private Vector3d[] principalAxes = new Vector3d[3]; + private final Vector3d[] principalAxes = new Vector3d[3]; - private Matrix3d orientation = new Matrix3d(); + private final Matrix3d orientation = new Matrix3d(); public enum SymmetryClass { LINEAR, PROLATE, OBLATE, SYMMETRIC, ASYMMETRIC - }; + } /** Creates a new empty instance of MomentsOfInertia */ public MomentsOfInertia() { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/SuperPosition.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/SuperPosition.java index f6b0d2dfb3..9fa91ad0ba 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/SuperPosition.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/SuperPosition.java @@ -51,7 +51,7 @@ public interface SuperPosition { * @return transformation matrix as a Matrix4d to superpose moved onto fixed * point arrays */ - public Matrix4d superpose(Point3d[] fixed, Point3d[] moved); + Matrix4d superpose(Point3d[] fixed, Point3d[] moved); /** * Transform an array of points so that the coordinates of its points @@ -71,7 +71,7 @@ public interface SuperPosition { * @return transformation matrix as a Matrix4d to superpose moved onto fixed * point arrays */ - public Matrix4d superposeAndTransform(Point3d[] fixed, Point3d[] moved); + Matrix4d superposeAndTransform(Point3d[] fixed, Point3d[] moved); /** * Calculate the RMSD between two arrays of equivalent points that are not @@ -94,6 +94,6 @@ public interface SuperPosition { * @return the minimum RMSD between the equivalent point arrays (after * superposition) */ - public double getRmsd(Point3d[] x, Point3d[] y); + double getRmsd(Point3d[] x, Point3d[] y); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/SuperPositionQCP.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/SuperPositionQCP.java index a3d5728f19..9ce2bdad6f 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/SuperPositionQCP.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/SuperPositionQCP.java @@ -21,14 +21,14 @@ package org.biojava.nbio.structure.geometry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import javax.vecmath.Matrix3d; import javax.vecmath.Matrix4d; import javax.vecmath.Point3d; import javax.vecmath.Vector3d; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Implementation of the Quaternion-Based Characteristic Polynomial algorithm * for RMSD and Superposition calculations. @@ -126,8 +126,8 @@ public final class SuperPositionQCP extends SuperPositionAbstract { private Point3d ytrans; private double e0; - private Matrix3d rotmat = new Matrix3d(); - private Matrix4d transformation = new Matrix4d(); + private final Matrix3d rotmat = new Matrix3d(); + private final Matrix4d transformation = new Matrix4d(); private double rmsd = 0; private double Sxy, Sxz, Syx, Syz, Szx, Szy; private double SxxpSyy, Szz, mxEigenV, SyzmSzy, SxzmSzx, SxymSyx; @@ -135,7 +135,7 @@ public final class SuperPositionQCP extends SuperPositionAbstract { private double Syy, Sxx, SyzpSzy; private boolean rmsdCalculated = false; private boolean transformationCalculated = false; - private boolean centered = false; + private final boolean centered = false; /** * Default constructor for the quaternion based superposition algorithm. diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/SuperPositionQuat.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/SuperPositionQuat.java index 6003530a39..9311dca32e 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/SuperPositionQuat.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/SuperPositionQuat.java @@ -20,7 +20,10 @@ */ package org.biojava.nbio.structure.geometry; -import javax.vecmath.*; +import javax.vecmath.Matrix4d; +import javax.vecmath.Point3d; +import javax.vecmath.Quat4d; +import javax.vecmath.Vector3d; /** * The SuperPositionQuat implements a quaternion based algorithm to superpose diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/SuperPositionSVD.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/SuperPositionSVD.java index d0fbb6adca..2a12d2dc11 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/SuperPositionSVD.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/SuperPositionSVD.java @@ -22,13 +22,13 @@ */ package org.biojava.nbio.structure.geometry; +import org.biojava.nbio.structure.jama.Matrix; +import org.biojava.nbio.structure.jama.SingularValueDecomposition; + import javax.vecmath.Matrix4d; import javax.vecmath.Point3d; import javax.vecmath.Vector3d; -import org.biojava.nbio.structure.jama.Matrix; -import org.biojava.nbio.structure.jama.SingularValueDecomposition; - /** * A class that calculates the superposition between two sets of points using an * SVD Matrix Decomposition. It was introduced by Wolfgang Kabsch, hence the diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/UnitQuaternions.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/UnitQuaternions.java index 0e31e101a5..81132dc6a7 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/UnitQuaternions.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/UnitQuaternions.java @@ -20,13 +20,13 @@ */ package org.biojava.nbio.structure.geometry; +import org.biojava.nbio.structure.jama.EigenvalueDecomposition; +import org.biojava.nbio.structure.jama.Matrix; + import javax.vecmath.AxisAngle4d; import javax.vecmath.Point3d; import javax.vecmath.Quat4d; -import org.biojava.nbio.structure.jama.EigenvalueDecomposition; -import org.biojava.nbio.structure.jama.Matrix; - /** * UnitQuaternions is a static Class that contains methods for calculating and * using unit quaternions. It assumes the use of {@link Quat4d} Class from @@ -178,10 +178,8 @@ public static double orientationAngle(Point3d[] fixed, Point3d[] moved) { public static double orientationAngle(Point3d[] fixed, Point3d[] moved, boolean centered) { if (!centered) { - fixed = CalcPoint.clonePoint3dArray(fixed); - moved = CalcPoint.clonePoint3dArray(moved); - CalcPoint.center(fixed); - CalcPoint.center(moved); + CalcPoint.center(fixed = CalcPoint.clonePoint3dArray(fixed)); + CalcPoint.center(moved = CalcPoint.clonePoint3dArray(moved)); } return orientationAngle(fixed, moved); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/BondMaker.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/BondMaker.java index bb92724aa4..22e523a64a 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/BondMaker.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/BondMaker.java @@ -32,12 +32,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; /** * Adds polymer bonds for peptides and nucleotides based on distance cutoffs and @@ -81,8 +76,8 @@ public class BondMaker { */ private static final double MAX_NUCLEOTIDE_BOND_LENGTH = 2.1; - private Structure structure; - private FileParsingParameters params; + private final Structure structure; + private final FileParsingParameters params; public BondMaker(Structure structure, FileParsingParameters params) { this.structure = structure; @@ -169,7 +164,7 @@ private void formIntraResidueBonds() { continue; } // Now add support for altLocGroup - List totList = new ArrayList(); + List totList = new ArrayList<>(); totList.add(mainGroup); totList.addAll(mainGroup.getAltLocs()); @@ -203,7 +198,7 @@ private void formIntraResidueBonds() { * @param maxAllowedLength max length, if atoms distance above this length no bond will be added. If negative no check on distance is performed. * @param bondOrder the bond order to be set in the created bond(s) */ - private void formBondAltlocAware(Group g1, String name1, Group g2, String name2, double maxAllowedLength, int bondOrder) { + private static void formBondAltlocAware(Group g1, String name1, Group g2, String name2, double maxAllowedLength, int bondOrder) { List a1s = getAtoms(g1, name1); List a2s = getAtoms(g2, name2); @@ -247,7 +242,7 @@ private void formBondAltlocAware(Group g1, String name1, Group g2, String name2, * @param name the atom name * @return list of all atoms, or empty list if no atoms with the name */ - private List getAtoms(Group g, String name) { + private static List getAtoms(Group g, String name) { List atoms = new ArrayList<>(); List groupsWithAltLocs = new ArrayList<>(); groupsWithAltLocs.add(g); @@ -410,8 +405,8 @@ public void formBondsFromStructConn(List structConn) { String altLocStr1 = altLoc1.isEmpty()? "" : "(alt loc "+altLoc1+")"; String altLocStr2 = altLoc2.isEmpty()? "" : "(alt loc "+altLoc2+")"; - Map a1 = null; - Map a2 = null; + Map a1; + Map a2; try { a1 = getAtomFromRecord(atomName1, altLoc1, resName1, chainId1, seqId1, insCode1); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/CAConverter.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/CAConverter.java index 4ffc5f1883..5b65b011d4 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/CAConverter.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/CAConverter.java @@ -42,7 +42,7 @@ public class CAConverter { * @since Biojava 4.1.0 */ public static List getRepresentativeAtomsOnly(List chains){ - List newChains = new ArrayList(); + List newChains = new ArrayList<>(); for (Chain chain : chains){ Chain newChain = getRepresentativeAtomsOnly(chain); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/ChargeAdder.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/ChargeAdder.java index 28fbddb9a9..3d52c88c55 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/ChargeAdder.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/ChargeAdder.java @@ -22,8 +22,6 @@ */ package org.biojava.nbio.structure.io; -import java.util.List; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Chain; import org.biojava.nbio.structure.Group; @@ -34,6 +32,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; + /** * A class to add appropriate charge information to a structure. * @author Anthony Bradley diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/EntityFinder.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/EntityFinder.java index c77f28d1a7..eda9cd9baf 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/EntityFinder.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/EntityFinder.java @@ -23,9 +23,9 @@ import org.biojava.nbio.alignment.Alignments; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; import org.biojava.nbio.alignment.SimpleGapPenalty; -import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.alignment.template.GapPenalty; import org.biojava.nbio.alignment.template.PairwiseSequenceAligner; +import org.biojava.nbio.core.alignment.matrices.SubstitutionMatrixHelper; import org.biojava.nbio.core.alignment.template.SequencePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; @@ -38,15 +38,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; -import java.util.TreeSet; +import java.util.*; /** * Heuristical finding of Entities (called Compounds in legacy PDB format) @@ -102,7 +94,7 @@ public static List findPolyEntities(List> polyModels) { */ private static List findUniqueEntities(TreeMap chainIds2entities) { - List list = new ArrayList(); + List list = new ArrayList<>(); for (EntityInfo cluster:chainIds2entities.values()) { boolean present = false; @@ -131,12 +123,7 @@ public static void createPurelyNonPolyEntities(List> nonPolyModels, // let's find first the max entity id to assign entity ids to the newly found entities int maxMolId = 0; if (!entities.isEmpty()) { - maxMolId = Collections.max(entities, new Comparator() { - @Override - public int compare(EntityInfo o1, EntityInfo o2) { - return new Integer(o1.getMolId()).compareTo(o2.getMolId()); - } - }).getMolId(); + maxMolId = Collections.max(entities, Comparator.comparingInt(EntityInfo::getMolId)).getMolId(); } // we go one over the max int molId = maxMolId + 1; @@ -200,7 +187,7 @@ private static boolean areResNumbersAligned(Chain c1, Chain c2) { // different kind of chain: we won't try to align them if (isC1prot != isC2prot ) return false; - List c1AtomGroups = null; + List c1AtomGroups; if (isC1prot) { c1AtomGroups = c1.getAtomGroups(GroupType.AMINOACID); } @@ -240,11 +227,11 @@ private static TreeMap findEntitiesFromAlignment(List chainIds2entities = new TreeMap(); + TreeMap chainIds2entities = new TreeMap<>(); if (polyModels.isEmpty()) return chainIds2entities; - Set polyChainIndices = new TreeSet(); + Set polyChainIndices = new TreeSet<>(); for (int i=0;i findEntitiesFromAlignment(List positionIndex1 = new HashMap(); - Map positionIndex2 = new HashMap(); + Map positionIndex1 = new HashMap<>(); + Map positionIndex2 = new HashMap<>(); // here we use false, which means that X will be used for unknown compounds String str1 = SeqRes2AtomAligner.getFullAtomSequence(c1.getAtomGroups(), positionIndex1, false); String str2 = SeqRes2AtomAligner.getFullAtomSequence(c2.getAtomGroups(), positionIndex2, false); - int seq1Length = 0; - int seq2Length = 0; + int seq1Length; + int seq2Length; - SequencePair pair = null; + SequencePair pair; if (isProteinSequence(str1) && isProteinSequence(str2)) { ProteinSequence s1 = getProteinSequence(str1); ProteinSequence s2 = getProteinSequence(str2); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/FastaAFPChainConverter.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/FastaAFPChainConverter.java index 6c6506504c..f736185867 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/FastaAFPChainConverter.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/FastaAFPChainConverter.java @@ -26,10 +26,6 @@ import org.biojava.nbio.core.alignment.template.AlignedSequence; import org.biojava.nbio.core.alignment.template.SequencePair; -import org.biojava.nbio.structure.*; -import org.biojava.nbio.structure.align.model.AFPChain; -import org.biojava.nbio.structure.align.util.AlignmentTools; -import org.biojava.nbio.structure.align.xml.AFPChainXMLConverter; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; @@ -41,6 +37,10 @@ import org.biojava.nbio.core.sequence.io.template.SequenceHeaderParserInterface; import org.biojava.nbio.core.sequence.template.Sequence; import org.biojava.nbio.core.util.SequenceTools; +import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.align.model.AFPChain; +import org.biojava.nbio.structure.align.util.AlignmentTools; +import org.biojava.nbio.structure.align.xml.AFPChainXMLConverter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -84,9 +84,9 @@ public static AFPChain cpFastaToAfpChain(String first, String second, Structure */ public static AFPChain cpFastaToAfpChain(File fastaFile, Structure structure, int cpSite) throws IOException, StructureException { InputStream inStream = new FileInputStream(fastaFile); - SequenceCreatorInterface creator = new CasePreservingProteinSequenceCreator(AminoAcidCompoundSet.getAminoAcidCompoundSet()); - SequenceHeaderParserInterface headerParser = new GenericFastaHeaderParser(); - FastaReader fastaReader = new FastaReader(inStream, headerParser, creator); + SequenceCreatorInterface creator = new CasePreservingProteinSequenceCreator(AminoAcidCompoundSet.aminoAcidCompoundSet); + SequenceHeaderParserInterface headerParser = new GenericFastaHeaderParser<>(); + FastaReader fastaReader = new FastaReader<>(inStream, headerParser, creator); LinkedHashMap sequences = fastaReader.process(); inStream.close(); Iterator iter = sequences.values().iterator(); @@ -194,10 +194,10 @@ public static AFPChain cpFastaToAfpChain(ProteinSequence first, ProteinSequence public static AFPChain fastaFileToAfpChain(File fastaFile, Structure structure1, Structure structure2) throws IOException, StructureException { InputStream inStream = new FileInputStream(fastaFile); - SequenceCreatorInterface creator = new CasePreservingProteinSequenceCreator( - AminoAcidCompoundSet.getAminoAcidCompoundSet()); - SequenceHeaderParserInterface headerParser = new GenericFastaHeaderParser(); - FastaReader fastaReader = new FastaReader( + SequenceCreatorInterface creator = new CasePreservingProteinSequenceCreator( + AminoAcidCompoundSet.aminoAcidCompoundSet); + SequenceHeaderParserInterface headerParser = new GenericFastaHeaderParser<>(); + FastaReader fastaReader = new FastaReader<>( inStream, headerParser, creator); LinkedHashMap sequences = fastaReader.process(); inStream.close(); @@ -236,8 +236,8 @@ public static AFPChain fastaToAfpChain(Map sequences, S throw new IllegalArgumentException("A structure is null"); } - List seqs = new ArrayList(); - List names = new ArrayList(2); + List seqs = new ArrayList<>(); + List names = new ArrayList<>(2); for (Map.Entry entry : sequences.entrySet()) { seqs.add(entry.getValue()); names.add(entry.getKey()); @@ -321,7 +321,7 @@ public static AFPChain fastaToAfpChain(SequencePair, sb1.append(a.getBase()); } ProteinSequence seq2 = new ProteinSequence(sb2.toString()); - LinkedHashMap map = new LinkedHashMap(); + LinkedHashMap map = new LinkedHashMap<>(); map.put(structure1.getName(), seq1); map.put(structure2.getName(), seq2); return fastaToAfpChain(map, structure1, structure2); @@ -349,8 +349,8 @@ private static AFPChain buildAlignment(Atom[] ca1, Atom[] ca2, ResidueNumber[] r // remove any gap // this includes the ones introduced by the nullifying above - List alignedResiduesList1 = new ArrayList(); - List alignedResiduesList2 = new ArrayList(); + List alignedResiduesList1 = new ArrayList<>(); + List alignedResiduesList2 = new ArrayList<>(); for (int i = 0; i < residues1.length; i++) { if (residues1[i] != null && residues2[i] != null) { alignedResiduesList1.add(residues1[i]); @@ -358,8 +358,8 @@ private static AFPChain buildAlignment(Atom[] ca1, Atom[] ca2, ResidueNumber[] r } } - ResidueNumber[] alignedResidues1 = alignedResiduesList1.toArray(new ResidueNumber[alignedResiduesList1.size()]); - ResidueNumber[] alignedResidues2 = alignedResiduesList2.toArray(new ResidueNumber[alignedResiduesList2.size()]); + ResidueNumber[] alignedResidues1 = alignedResiduesList1.toArray(new ResidueNumber[0]); + ResidueNumber[] alignedResidues2 = alignedResiduesList2.toArray(new ResidueNumber[0]); AFPChain afpChain = AlignmentTools.createAFPChain(ca1, ca2, alignedResidues1, alignedResidues2); afpChain.setAlgorithmName("unknown"); @@ -379,7 +379,7 @@ private static AFPChain buildAlignment(Atom[] ca1, Atom[] ca2, ResidueNumber[] r * @param sequence Make sure not to use {@link ProteinSequence#getSequenceAsString()} for this, as it won't preserve upper- and lower-case */ public static List getAlignedUserCollection(String sequence) { - List aligned = new ArrayList(sequence.length()); + List aligned = new ArrayList<>(sequence.length()); for (char c : sequence.toCharArray()) { aligned.add(Character.isUpperCase(c)); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/FastaStructureParser.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/FastaStructureParser.java index 29baf9d825..35f3836ddf 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/FastaStructureParser.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/FastaStructureParser.java @@ -20,15 +20,15 @@ */ package org.biojava.nbio.structure.io; -import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; import org.biojava.nbio.core.sequence.io.FastaReader; import org.biojava.nbio.core.sequence.io.template.SequenceCreatorInterface; import org.biojava.nbio.core.sequence.io.template.SequenceHeaderParserInterface; +import org.biojava.nbio.structure.ResidueNumber; +import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.StructureException; +import org.biojava.nbio.structure.align.util.AtomCache; import java.io.File; import java.io.FileNotFoundException; @@ -57,8 +57,8 @@ public class FastaStructureParser { // inputs - private FastaReader reader; - private AtomCache cache; + private final FastaReader reader; + private final AtomCache cache; // cache processed data private String[] accessions; @@ -71,7 +71,7 @@ public FastaStructureParser(InputStream is, SequenceCreatorInterface sequenceCreator, AtomCache cache) { - this(new FastaReader( + this(new FastaReader<>( is, headerParser, sequenceCreator),cache); } @@ -80,7 +80,7 @@ public FastaStructureParser(File file, SequenceCreatorInterface sequenceCreator, AtomCache cache) throws FileNotFoundException { - this(new FastaReader( + this(new FastaReader<>( file, headerParser, sequenceCreator), cache); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/FileConvert.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/FileConvert.java index 1b4ce20b58..7201f9c05b 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/FileConvert.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/FileConvert.java @@ -21,6 +21,14 @@ */ package org.biojava.nbio.structure.io; +import org.biojava.nbio.core.util.XMLWriter; +import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.io.mmcif.MMCIFFileTools; +import org.biojava.nbio.structure.io.mmcif.SimpleMMcifParser; +import org.biojava.nbio.structure.io.mmcif.model.AtomSite; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.IOException; import java.text.DateFormat; import java.text.DecimalFormat; @@ -29,23 +37,6 @@ import java.util.List; import java.util.Locale; -import org.biojava.nbio.core.util.XMLWriter; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Bond; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.DBRef; -import org.biojava.nbio.structure.Element; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.GroupType; -import org.biojava.nbio.structure.PDBHeader; -import org.biojava.nbio.structure.Site; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.io.mmcif.MMCIFFileTools; -import org.biojava.nbio.structure.io.mmcif.SimpleMMcifParser; -import org.biojava.nbio.structure.io.mmcif.model.AtomSite; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Methods to convert a structure object into different file formats. @@ -58,19 +49,19 @@ public class FileConvert { - private Structure structure ; + private final Structure structure ; private boolean printConnections; // Locale should be english, e.g. in DE separator is "," -> PDB files have "." ! - public static DecimalFormat d3 = (DecimalFormat)NumberFormat.getInstance(Locale.US); + public static final DecimalFormat d3 = (DecimalFormat)NumberFormat.getInstance(Locale.US); static { d3.setMaximumIntegerDigits(4); d3.setMinimumFractionDigits(3); d3.setMaximumFractionDigits(3); d3.setGroupingUsed(false); } - public static DecimalFormat d2 = (DecimalFormat)NumberFormat.getInstance(Locale.US); + public static final DecimalFormat d2 = (DecimalFormat)NumberFormat.getInstance(Locale.US); static { d2.setMaximumIntegerDigits(3); d2.setMinimumFractionDigits(2); @@ -187,13 +178,13 @@ public String toPDB() { // do for all models int nrModels = structure.nrModels() ; if ( structure.isNmr()) { - str.append("EXPDTA NMR, "+ nrModels+" STRUCTURES"+newline) ; + str.append("EXPDTA NMR, ").append(nrModels).append(" STRUCTURES").append(newline); } for (int m = 0 ; m < nrModels ; m++) { if ( nrModels>1 ) { - str.append("MODEL " + (m+1)+ newline); + str.append("MODEL ").append(m + 1).append(newline); } List polyChains = structure.getPolyChains(m); @@ -231,7 +222,7 @@ public String toPDB() { } } - if (nonPolyGroupsExist) str.append(String.format("%-80s","TER")).append(newline);; + if (nonPolyGroupsExist) str.append(String.format("%-80s","TER")).append(newline); boolean waterGroupsExist = false; for (Chain chain : waterChains) { @@ -248,7 +239,7 @@ public String toPDB() { } } - if (waterGroupsExist) str.append(String.format("%-80s","TER")).append(newline);; + if (waterGroupsExist) str.append(String.format("%-80s","TER")).append(newline); if ( nrModels>1) { @@ -271,7 +262,7 @@ private static void toPDB(Group g, StringBuffer str) { int groupsize = g.size(); for ( int atompos = 0 ; atompos < groupsize; atompos++) { - Atom a = null ; + Atom a; a = g.getAtom(atompos); if ( a == null) @@ -390,7 +381,7 @@ public static void toPDB(Atom a, StringBuffer str, String chainID) { GroupType type = g.getType() ; - String record = "" ; + String record; if ( type.equals(GroupType.HETATM) ) { record = "HETATM"; } else { @@ -411,7 +402,7 @@ record = "ATOM "; if ( altLoc == null) altLoc = ' '; - String resseq = "" ; + String resseq; if ( hasInsertionCode(pdbcode) ) resseq = String.format("%5s",pdbcode); else @@ -426,7 +417,7 @@ record = "ATOM "; String leftResName = String.format("%3s",resName); - StringBuffer s = new StringBuffer(); + StringBuilder s = new StringBuilder(); s.append(record); s.append(serial); s.append(" "); @@ -598,7 +589,7 @@ public String toMMCIF() { StringBuilder str = new StringBuilder(); - str.append(SimpleMMcifParser.MMCIF_TOP_HEADER+"BioJava_mmCIF_file"+newline); + str.append(SimpleMMcifParser.MMCIF_TOP_HEADER + "BioJava_mmCIF_file").append(newline); if (structure.getPDBHeader()!=null && structure.getPDBHeader().getCrystallographicInfo()!=null && structure.getPDBHeader().getCrystallographicInfo().getSpaceGroup()!=null && @@ -637,7 +628,7 @@ public static String toMMCIF(Chain chain, String authId, String asymId, boolean public static String toMMCIF(Chain chain, boolean writeHeader) { StringBuilder sb = new StringBuilder(); - sb.append(SimpleMMcifParser.MMCIF_TOP_HEADER+"BioJava_mmCIF_file"+newline); + sb.append(SimpleMMcifParser.MMCIF_TOP_HEADER + "BioJava_mmCIF_file").append(newline); sb.append(toMMCIF(chain, chain.getName(), chain.getId(),writeHeader)); return sb.toString(); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/FileParsingParameters.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/FileParsingParameters.java index 4f28294287..b39d4d5e70 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/FileParsingParameters.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/FileParsingParameters.java @@ -24,10 +24,10 @@ package org.biojava.nbio.structure.io; -import java.io.Serializable; - import org.biojava.nbio.structure.AminoAcid; +import java.io.Serializable; + /** * A class that configures parameters that can be sent to the PDB file parsers * diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/GroupToSDF.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/GroupToSDF.java index bbc277b89f..c14ac578ac 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/GroupToSDF.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/GroupToSDF.java @@ -20,13 +20,14 @@ */ package org.biojava.nbio.structure.io; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.List; import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Bond; import org.biojava.nbio.structure.Group; +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.List; + public class GroupToSDF { @@ -53,16 +54,16 @@ private String getCtab(Group thisGroup){ String spaceY = getSpace(10, df.format(a.getY())); String spaceZ = getSpace(10, df.format(a.getZ())); String spaceEle = getSpace(4, a.getElement().toString()); - atomList.append(spaceX+df.format(a.getX())+spaceY+df.format(a.getY())+spaceZ+df.format(a.getZ())+" "+a.getElement().toString()+spaceEle+"0 0 0 0 0 0 0 0 0 0 0 0\n"); + atomList.append(spaceX).append(df.format(a.getX())).append(spaceY).append(df.format(a.getY())).append(spaceZ).append(df.format(a.getZ())).append(" ").append(a.getElement().toString()).append(spaceEle).append("0 0 0 0 0 0 0 0 0 0 0 0\n"); for(Bond b: a.getBonds()){ Atom otherAtom = b.getOther(a); if(atoms.indexOf(otherAtom)>=atoms.indexOf(a)){ continue; } - if(atoms.indexOf(otherAtom)<0){ + if(!atoms.contains(otherAtom)){ continue; } - if(atoms.indexOf(a)<0){ + if(!atoms.contains(a)){ continue; } numBonds++; @@ -106,8 +107,8 @@ private Object getCharges(Group thisGroup) { if(chargeCount==0){ outS.append("M CHG N"); } - outS.append(getSpace(4, Integer.toString(i))+(i+1)); - outS.append(getSpace(4, Short.toString(charge))+charge); + outS.append(getSpace(4, Integer.toString(i))).append(i + 1); + outS.append(getSpace(4, Short.toString(charge))).append(charge); chargeCount++; } // @@ -130,7 +131,7 @@ private Object getCharges(Group thisGroup) { private static List getAtomCharges(Group group) { // The list to store the answer - List outArr = new ArrayList(); + List outArr = new ArrayList<>(); // Get the atom charge Information for(Atom a: group.getAtoms()){ outArr.add(a.getCharge()); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/LocalPDBDirectory.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/LocalPDBDirectory.java index 61735ecfa6..058fd0d8d9 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/LocalPDBDirectory.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/LocalPDBDirectory.java @@ -21,14 +21,14 @@ */ package org.biojava.nbio.structure.io; +import org.biojava.nbio.core.util.Download; +import org.biojava.nbio.core.util.InputStreamProvider; import org.biojava.nbio.structure.PDBStatus; import org.biojava.nbio.structure.PDBStatus.Status; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.util.UserConfiguration; -import org.biojava.nbio.core.util.FileDownloadUtils; import org.rcsb.mmtf.utils.CodecUtils; -import org.biojava.nbio.core.util.InputStreamProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -51,7 +51,7 @@ * @author Spencer Bliven * */ -public abstract class LocalPDBDirectory implements StructureIOFile { +@Deprecated public abstract class LocalPDBDirectory implements StructureIOFile { private static final Logger logger = LoggerFactory.getLogger(LocalPDBDirectory.class); @@ -68,7 +68,7 @@ public abstract class LocalPDBDirectory implements StructureIOFile { * @author Spencer Bliven * @see LocalPDBDirectory#setObsoleteBehavior(ObsoleteBehavior) */ - public static enum ObsoleteBehavior { + public enum ObsoleteBehavior { /** Fetch the most recent version of the PDB entry. */ FETCH_CURRENT, /** Fetch the obsolete entry from the PDB archives. */ @@ -84,7 +84,7 @@ public static enum ObsoleteBehavior { * @author Spencer Bliven * */ - public static enum FetchBehavior { + public enum FetchBehavior { /** Never fetch from the server; Throw errors for missing files */ LOCAL_ONLY, /** Fetch missing files from the server. Don't check for outdated files */ @@ -133,14 +133,14 @@ public static enum FetchBehavior { public static final long MIN_PDB_FILE_SIZE = 40; // Empty gzip files are 20bytes. Add a few more for buffer. private File path; - private List extensions; + private final List extensions; /** * The server name, prefixed by the protocol string (http:// or ftp://). * Note that we don't support file stamp retrieving for ftp protocol, thus some of the * fetch modes will not work properly with ftp protocol */ - private String serverName; + private final String serverName; private FileParsingParameters params; @@ -163,7 +163,7 @@ public static enum FetchBehavior { * @param path Path to the PDB file directory */ public LocalPDBDirectory(String path) { - extensions = new ArrayList(); + extensions = new ArrayList<>(); params = new FileParsingParameters(); @@ -172,7 +172,7 @@ public LocalPDBDirectory(String path) { path = config.getPdbFilePath(); logger.debug("Initialising from system property/environment variable to path: {}", path); } else { - path = FileDownloadUtils.expandUserHome(path); + path = Download.expandUserHome(path); logger.debug("Initialising with path {}", path); } this.path = new File(path); @@ -194,7 +194,7 @@ public LocalPDBDirectory() { * Sets the path for the directory where PDB files are read/written */ public void setPath(String p){ - path = new File(FileDownloadUtils.expandUserHome(p)) ; + path = new File(Download.expandUserHome(p)) ; initPaths(); } @@ -300,7 +300,7 @@ public void setFetchBehavior(FetchBehavior fetchBehavior) { @Override public Structure getStructure(String filename) throws IOException { - filename = FileDownloadUtils.expandUserHome(filename); + filename = Download.expandUserHome(filename); File f = new File(filename); return getStructure(f); @@ -324,9 +324,8 @@ public Structure getStructure(File filename) throws IOException { @Override public Structure getStructureById(String pdbId) throws IOException { - InputStream inStream = getInputStream(pdbId); - return getStructure(inStream); + return getStructure(structureInputStream(pdbId)); } /** @@ -344,44 +343,88 @@ public Structure getStructureById(String pdbId) throws IOException { * @return * @throws IOException */ - protected InputStream getInputStream(String pdbId) throws IOException{ + protected InputStream structureInputStream(String pdbId) throws IOException{ if ( pdbId.length() != 4) - throw new IOException("The provided ID does not look like a PDB ID : " + pdbId); - - // Check existing - File file = downloadStructure(pdbId); + throw new IOException("Invalid PDB ID : " + pdbId); - if(!file.exists()) { - throw new IOException("Structure "+pdbId+" not found and unable to download."); - } - - InputStreamProvider isp = new InputStreamProvider(); - - InputStream inputStream = isp.getInputStream(file); - - return inputStream; - } - - /** - * Download a structure, but don't parse it yet or store it in memory. - * - * Used to pre-fetch large numbers of structures. - * @param pdbId - * @throws IOException - */ - public void prefetchStructure(String pdbId) throws IOException { - if ( pdbId.length() != 4) - throw new IOException("The provided ID does not look like a PDB ID : " + pdbId); +// // Check existing +// if ( pdbId.length() != 4) +// throw new IOException("The provided ID does not look like a PDB ID : " + pdbId); - // Check existing - File file = downloadStructure(pdbId); + // decide whether download is required +// File existing = getLocalFile(pdbId); +// switch(fetchBehavior) { +// case LOCAL_ONLY: +// if( existing == null ) { +// throw new IOException(String.format("Structure %s not found in %s " +// + "and configured not to download.",pdbId,getPath())); +// } else { +// return existing; +// } +// case FETCH_FILES: +// // Use existing if present +// if( existing != null) { +// return existing; +// } +// // existing is null, downloadStructure(String,String,boolean,File) will download it +// break; +// case FETCH_IF_OUTDATED: +// // here existing can be null or not: +// // existing == null : downloadStructure(String,String,boolean,File) will download it +// // existing != null : downloadStructure(String,String,boolean,File) will check its date and download if older +// break; +// case FETCH_REMEDIATED: +// // Use existing if present and recent enough +// if( existing != null) { +// long lastModified = existing.lastModified(); +// +// if (lastModified < LAST_REMEDIATION_DATE) { +// // the file is too old, replace with newer version +// logger.warn("Replacing file {} with latest remediated (remediation of {}) file from PDB.", +// existing, LAST_REMEDIATION_DATE_STRING); +// existing = null; +// break; +// } else { +// return existing; +// } +// } +// case FORCE_DOWNLOAD: +// // discard the existing file to force redownload +// existing = null; // downloadStructure(String,String,boolean,File) will download it +// break; +// } - if(!file.exists()) { - throw new IOException("Structure "+pdbId+" not found and unable to download."); + // Force the download now + if(obsoleteBehavior == ObsoleteBehavior.FETCH_CURRENT) { + String current = PDBStatus.getCurrent(pdbId); // either an error or there is not current entry + return structureInputStream(current == null ? pdbId : current, splitDirURL); + } else if(obsoleteBehavior == ObsoleteBehavior.FETCH_OBSOLETE && PDBStatus.getStatus(pdbId) == Status.OBSOLETE) { + return structureInputStream(pdbId, obsoleteDirURL); + } else { + return structureInputStream(pdbId, splitDirURL); } } +// /** +// * Download a structure, but don't parse it yet or store it in memory. +// * +// * Used to pre-fetch large numbers of structures. +// * @param pdbId +// * @throws IOException +// */ +// public void prefetchStructure(String pdbId) throws IOException { +// if ( pdbId.length() != 4) +// throw new IOException("The provided ID does not look like a PDB ID : " + pdbId); +// +// // Check existing +// File file = downloadStructure(pdbId); +// +// if(!file.exists()) { +// throw new IOException("Structure "+pdbId+" not found and unable to download."); +// } +// } + /** * Attempts to delete all versions of a structure from the local directory. * @param pdbId @@ -428,126 +471,51 @@ public boolean deleteStructure(String pdbId) throws IOException{ } } - /** - * Downloads an MMCIF file from the PDB to the local path - * @param pdbId - * @return The file, or null if it was unavailable for download - * @throws IOException for errors downloading or writing, or if the - * fetchBehavior is {@link FetchBehavior#LOCAL_ONLY} - */ - protected File downloadStructure(String pdbId) throws IOException{ - if ( pdbId.length() != 4) - throw new IOException("The provided ID does not look like a PDB ID : " + pdbId); - - // decide whether download is required - File existing = getLocalFile(pdbId); - switch(fetchBehavior) { - case LOCAL_ONLY: - if( existing == null ) { - throw new IOException(String.format("Structure %s not found in %s " - + "and configured not to download.",pdbId,getPath())); - } else { - return existing; - } - case FETCH_FILES: - // Use existing if present - if( existing != null) { - return existing; - } - // existing is null, downloadStructure(String,String,boolean,File) will download it - break; - case FETCH_IF_OUTDATED: - // here existing can be null or not: - // existing == null : downloadStructure(String,String,boolean,File) will download it - // existing != null : downloadStructure(String,String,boolean,File) will check its date and download if older - break; - case FETCH_REMEDIATED: - // Use existing if present and recent enough - if( existing != null) { - long lastModified = existing.lastModified(); - - if (lastModified < LAST_REMEDIATION_DATE) { - // the file is too old, replace with newer version - logger.warn("Replacing file {} with latest remediated (remediation of {}) file from PDB.", - existing, LAST_REMEDIATION_DATE_STRING); - existing = null; - break; - } else { - return existing; - } - } - case FORCE_DOWNLOAD: - // discard the existing file to force redownload - existing = null; // downloadStructure(String,String,boolean,File) will download it - break; - } - - // Force the download now - if(obsoleteBehavior == ObsoleteBehavior.FETCH_CURRENT) { - String current = PDBStatus.getCurrent(pdbId); - - if(current == null) { - // either an error or there is not current entry - current = pdbId; - } - return downloadStructure(current, splitDirURL,false, existing); - } else if(obsoleteBehavior == ObsoleteBehavior.FETCH_OBSOLETE - && PDBStatus.getStatus(pdbId) == Status.OBSOLETE) { - return downloadStructure(pdbId, obsoleteDirURL, true, existing); - } else { - return downloadStructure(pdbId, splitDirURL, false, existing); - } - } - /** * Download a file from the ftp server, replacing any existing files if needed * @param pdbId PDB ID * @param pathOnServer Path on the FTP server, e.g. data/structures/divided/pdb - * @param obsolete Whether or not file should be saved to the obsolete location locally * @param existingFile if not null and checkServerFileDate is true, the last modified date of the * server file and this file will be compared to decide whether to download or not * @return * @throws IOException */ - private File downloadStructure(String pdbId, String pathOnServer, boolean obsolete, File existingFile) - throws IOException{ - - File dir = getDir(pdbId,obsolete); - File realFile = new File(dir,getFilename(pdbId)); - + private InputStream structureInputStream(String pdbId, String pathOnServer) throws IOException{ +// +//// File dir = getDir(pdbId,obsolete); +//// File realFile = new File(dir,getFilename(pdbId)); +// String ftp; - +// if (getFilename(pdbId).endsWith(".mmtf.gz")){ ftp = CodecUtils.getMmtfEntryUrl(pdbId, true, false); } else { - ftp = String.format("%s%s/%s/%s", - serverName, pathOnServer, pdbId.substring(1,3).toLowerCase(), getFilename(pdbId)); - } - - URL url = new URL(ftp); - - Date serverFileDate = null; - if (existingFile!=null) { - - serverFileDate = getLastModifiedTime(url); - - if (serverFileDate!=null) { - if (existingFile.lastModified()>=serverFileDate.getTime()) { - return existingFile; - } else { - // otherwise we go ahead and download, warning about it first - logger.warn("File {} is outdated, will download new one from PDB (updated on {})", - existingFile, serverFileDate.toString()); - } - } else { - logger.warn("Could not determine if file {} is outdated (could not get timestamp from server). Will force redownload", existingFile); - } + ftp = String.format("%s%s/%s/%s", serverName, pathOnServer, pdbId.substring(1,3).toLowerCase(), getFilename(pdbId)); } - logger.info("Fetching " + ftp); - logger.info("Writing to "+ realFile); + return Download.stream(new URL(ftp)); + +// Date serverFileDate; +// if (existingFile!=null) { +// +// serverFileDate = getLastModifiedTime(url); +// +// if (serverFileDate!=null) { +// if (existingFile.lastModified()>=serverFileDate.getTime()) { +// return existingFile; +// } else { +// // otherwise we go ahead and download, warning about it first +// logger.warn("File {} is outdated, will download new one from PDB (updated on {})", +// existingFile, serverFileDate.toString()); +// } +// } else { +// logger.warn("Could not determine if file {} is outdated (could not get timestamp from server). Will force redownload", existingFile); +// } +// } + +// logger.info("Fetching " + ftp); +// logger.info("Writing to "+ realFile); - FileDownloadUtils.downloadFile(url, realFile); // Commented out following code used for setting the modified date to the downloaded file - JD 2015-01-15 // The only reason to have it was in order to get an rsync-like behavior, respecting the timestamps @@ -564,7 +532,7 @@ private File downloadStructure(String pdbId, String pathOnServer, boolean obsole //} - return realFile; +// return realFile; } /** @@ -611,7 +579,7 @@ private Date getLastModifiedTime(URL url) { */ protected File getDir(String pdbId, boolean obsolete) { - File dir = null; + File dir; if (obsolete) { // obsolete is always split @@ -644,7 +612,7 @@ public File getLocalFile(String pdbId) throws IOException { // Search directories: // 1) LOCAL_MMCIF_SPLIT_DIR//(pdb)?. // 2) LOCAL_MMCIF_ALL_DIR//(pdb)?. - LinkedList searchdirs = new LinkedList(); + LinkedList searchdirs = new LinkedList<>(); String middle = pdbId.substring(1,3).toLowerCase(); File splitdir = new File(splitDirPath, middle); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/MMCIFFileReader.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/MMCIFFileReader.java index ca91f8d70d..d3c5ed4ea8 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/MMCIFFileReader.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/MMCIFFileReader.java @@ -97,13 +97,14 @@ public MMCIFFileReader(String path){ @Override public Structure getStructure(InputStream inStream) throws IOException{ - MMcifParser parser = new SimpleMMcifParser(); consumer = new SimpleMMcifConsumer(); consumer.setFileParsingParameters(getFileParsingParameters()); + MMcifParser parser = new SimpleMMcifParser(); + // The Consumer builds up the BioJava - structure object. // you could also hook in your own and build up you own data model. parser.addMMcifConsumer(consumer); @@ -112,14 +113,13 @@ public Structure getStructure(InputStream inStream) throws IOException{ // now get the protein structure. - Structure cifStructure = consumer.getStructure(); - return cifStructure; + return consumer.getStructure(); } - public SimpleMMcifConsumer getMMcifConsumer(){ - return consumer; - } +// public SimpleMMcifConsumer getMMcifConsumer(){ +// return consumer; +// } // public void setMMCifConsumer(SimpleMMcifConsumer consumer){ // this.consumer = consumer; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/MMTFFileReader.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/MMTFFileReader.java index e410d9f538..1d321c2cb7 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/MMTFFileReader.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/MMTFFileReader.java @@ -20,13 +20,13 @@ */ package org.biojava.nbio.structure.io; -import java.io.IOException; -import java.io.InputStream; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.align.util.UserConfiguration; import org.biojava.nbio.structure.io.mmtf.MmtfActions; +import java.io.IOException; +import java.io.InputStream; + /** * A class to read MMTF files and cache them locally. * @author Anthony Bradley diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/PDBBioAssemblyParser.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/PDBBioAssemblyParser.java index 22462bafe1..064993dd42 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/PDBBioAssemblyParser.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/PDBBioAssemblyParser.java @@ -23,11 +23,12 @@ import org.biojava.nbio.structure.jama.Matrix; import org.biojava.nbio.structure.quaternary.BioAssemblyInfo; import org.biojava.nbio.structure.quaternary.BiologicalAssemblyTransformation; -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; import java.util.*; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; + /** * Parses REMARK 350 records in a PDB file and creates transformations to * construct the quaternary structure of a protein from an asymmetric unit @@ -41,10 +42,10 @@ public class PDBBioAssemblyParser { //private static final Logger logger = LoggerFactory.getLogger(PDBBioAssemblyParser.class); private Integer currentBioMolecule = null; - private List currentChainIDs = new ArrayList(); + private final List currentChainIDs = new ArrayList<>(); private Matrix currentMatrix = null; private double[] shift = null; - private Map transformationMap = new HashMap(); + private final Map transformationMap = new HashMap<>(); private int modelNumber = 1; private List transformations; @@ -151,7 +152,7 @@ private void saveMatrix() { * Parses list of chain ids (A, B, C, etc.) */ private void addToCurrentChainList(String line) { - int index = line.indexOf(":"); + int index = line.indexOf(':'); String chainList = line.substring(index+1).trim(); // split by spaces or commas String[] chainIds = chainList.split("[ ,]+"); @@ -159,7 +160,7 @@ private void addToCurrentChainList(String line) { } private void initialize() { - transformations = new ArrayList(); + transformations = new ArrayList<>(); currentMatrix = Matrix.identity(3,3); currentBioMolecule = null; shift = new double[3]; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/PDBFileParser.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/PDBFileParser.java index 41014e1ec4..646f9d25e8 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/PDBFileParser.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/PDBFileParser.java @@ -21,8 +21,19 @@ */ package org.biojava.nbio.structure.io; -import static java.lang.Math.min; +import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.io.mmcif.ChemCompGroupFactory; +import org.biojava.nbio.structure.io.mmcif.model.ChemCompAtom; +import org.biojava.nbio.structure.io.util.PDBTemporaryStorageUtils.LinkRecord; +import org.biojava.nbio.structure.secstruc.SecStrucInfo; +import org.biojava.nbio.structure.secstruc.SecStrucType; +import org.biojava.nbio.structure.xtal.CrystalCell; +import org.biojava.nbio.structure.xtal.SpaceGroup; +import org.biojava.nbio.structure.xtal.SymoplibParser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import javax.vecmath.Matrix4d; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -30,55 +41,11 @@ import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.StringTokenizer; +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; -import javax.vecmath.Matrix4d; - -import org.biojava.nbio.structure.AminoAcid; -import org.biojava.nbio.structure.AminoAcidImpl; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.AtomImpl; -import org.biojava.nbio.structure.Author; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.ChainImpl; -import org.biojava.nbio.structure.DBRef; -import org.biojava.nbio.structure.Element; -import org.biojava.nbio.structure.EntityInfo; -import org.biojava.nbio.structure.EntityType; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.GroupIterator; -import org.biojava.nbio.structure.HetatomImpl; -import org.biojava.nbio.structure.JournalArticle; -import org.biojava.nbio.structure.NucleotideImpl; -import org.biojava.nbio.structure.PDBCrystallographicInfo; -import org.biojava.nbio.structure.PDBHeader; -import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.structure.Site; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureImpl; -import org.biojava.nbio.structure.StructureTools; -import org.biojava.nbio.structure.io.mmcif.ChemCompGroupFactory; -import org.biojava.nbio.structure.io.mmcif.model.ChemCompAtom; -import org.biojava.nbio.structure.io.util.PDBTemporaryStorageUtils.LinkRecord; -import org.biojava.nbio.structure.secstruc.SecStrucInfo; -import org.biojava.nbio.structure.secstruc.SecStrucType; -import org.biojava.nbio.structure.xtal.CrystalCell; -import org.biojava.nbio.structure.xtal.SpaceGroup; -import org.biojava.nbio.structure.xtal.SymoplibParser; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static java.lang.Math.min; /** @@ -158,34 +125,34 @@ public class PDBFileParser { //(pdb_COMPOUND_handler for example) private boolean isLegacyFormat = false; - private boolean blankChainIdsPresent = false; + private boolean blankChainIdsPresent; // for re-creating the biological assembly private PDBBioAssemblyParser bioAssemblyParser = null; private PDBHeader pdbHeader; - private PDBCrystallographicInfo crystallographicInfo; + private final PDBCrystallographicInfo crystallographicInfo; private JournalArticle journalArticle; private List> connects ; - private List> helixList; - private List> strandList; - private List> turnList; + private final List> helixList; + private final List> strandList; + private final List> turnList; private int lengthCheck ; private boolean isLastCompndLine = false; private boolean isLastSourceLine = false; private EntityInfo current_compound; - private List entities = new ArrayList(); - private HashMap> compoundMolIds2chainIds = new HashMap>(); - private List compndLines = new ArrayList(); - private List sourceLines = new ArrayList(); - private List journalLines = new ArrayList(); - private List dbrefs; - private Map siteMap = new LinkedHashMap(); - private Map> siteToResidueMap = new LinkedHashMap>(); + private List entities = new ArrayList<>(); + private final HashMap> compoundMolIds2chainIds = new HashMap<>(); + private final List compndLines = new ArrayList<>(); + private final List sourceLines = new ArrayList<>(); + private final List journalLines = new ArrayList<>(); + private final List dbrefs; + private Map siteMap; + private final Map> siteToResidueMap = new LinkedHashMap<>(); - private List ssbonds = new ArrayList<>(); + private final List ssbonds = new ArrayList<>(); // for storing LINK until we have all the atoms parsed private List linkRecords; @@ -199,31 +166,31 @@ public class PDBFileParser { private String continuationField; private String continuationString; - private DateFormat dateFormat; + private final DateFormat dateFormat; // for rfree parsing private float rfreeStandardLine = -1; private float rfreeNoCutoffLine = -1; - private static final List compndFieldValues = new ArrayList( + private static final List compndFieldValues = new ArrayList<>( Arrays.asList( "MOL_ID:", "MOLECULE:", "CHAIN:", "SYNONYM:", "EC:", "FRAGMENT:", "ENGINEERED:", "MUTATION:", "BIOLOGICAL_UNIT:", "OTHER_DETAILS:" - )); + )); - private static final List ignoreCompndFieldValues = new ArrayList( + private static final List ignoreCompndFieldValues = new ArrayList<>( Arrays.asList( - "HETEROGEN:","ENGINEEREED:","FRAGMENT,", - "MUTANT:","SYNTHETIC:" - )); + "HETEROGEN:", "ENGINEEREED:", "FRAGMENT,", + "MUTANT:", "SYNTHETIC:" + )); // ENGINEEREED in pdb219d - private static final List sourceFieldValues = new ArrayList( + private static final List sourceFieldValues = new ArrayList<>( Arrays.asList("ENGINEERED:", "MOL_ID:", "SYNTHETIC:", "FRAGMENT:", "ORGANISM_SCIENTIFIC:", "ORGANISM_COMMON:", - "ORGANISM_TAXID:","STRAIN:", + "ORGANISM_TAXID:", "STRAIN:", "VARIANT:", "CELL_LINE:", "ATCC:", "ORGAN:", "TISSUE:", "CELL:", "ORGANELLE:", "SECRETION:", "GENE:", "CELLULAR_LOCATION:", "EXPRESSION_SYSTEM:", @@ -272,14 +239,14 @@ public PDBFileParser() { pdbHeader = new PDBHeader(); crystallographicInfo = new PDBCrystallographicInfo(); - connects = new ArrayList>() ; + connects = new ArrayList<>() ; - helixList = new ArrayList>(); - strandList = new ArrayList>(); - turnList = new ArrayList>(); + helixList = new ArrayList<>(); + strandList = new ArrayList<>(); + turnList = new ArrayList<>(); current_compound = null; - dbrefs = new ArrayList(); + dbrefs = new ArrayList<>(); siteMap = null; dateFormat = new SimpleDateFormat("dd-MMM-yy", Locale.US); atomCount = 0; @@ -292,7 +259,7 @@ public PDBFileParser() { loadMaxAtoms = params.getMaxAtoms(); atomCAThreshold = params.getAtomCaThreshold(); - linkRecords = new ArrayList(); + linkRecords = new ArrayList<>(); blankChainIdsPresent = false; @@ -344,9 +311,9 @@ private Group getNewGroup(String recordName,Character aminoCode1, String aminoCo */ private void pdb_HEADER_Handler(String line) { - String classification = null; - String deposition_date = null; - String pdbCode = null; + String classification; + String deposition_date; + String pdbCode; int len = line.trim().length(); if(len > 10) { @@ -367,7 +334,7 @@ private void pdb_HEADER_Handler(String line) { pdbCode = line.substring (62, min(len,66)).trim() ; pdbId = pdbCode; - logger.debug("Parsing entry " + pdbId); + logger.debug("Parsing entry {}", pdbId); structure.setPDBCode(pdbCode); @@ -474,7 +441,7 @@ private void pdb_HELIX_Handler(String line){ //System.out.println(initResName + " " + initChainId + " " + initSeqNum + " " + initICode + " " + // endResName + " " + endChainId + " " + endSeqNum + " " + endICode); - Map m = new HashMap(); + Map m = new HashMap<>(); m.put("initResName",initResName); m.put("initChainId", initChainId); @@ -561,7 +528,7 @@ private void pdb_SHEET_Handler( String line){ //System.out.println(initResName + " " + initChainId + " " + initSeqNum + " " + initICode + " " + // endResName + " " + endChainId + " " + endSeqNum + " " + endICode); - Map m = new HashMap(); + Map m = new HashMap<>(); m.put("initResName",initResName); m.put("initChainId", initChainId); @@ -626,7 +593,7 @@ private void pdb_TURN_Handler( String line){ //System.out.println(initResName + " " + initChainId + " " + initSeqNum + " " + initICode + " " + // endResName + " " + endChainId + " " + endSeqNum + " " + endICode); - Map m = new HashMap(); + Map m = new HashMap<>(); m.put("initResName",initResName); m.put("initChainId", initChainId); @@ -769,7 +736,7 @@ private void pdb_SEQRES_Handler(String line) { StringTokenizer subSequenceResidues = new StringTokenizer(subSequence); - Character aminoCode1 = null; + Character aminoCode1; if (! recordName.equals(AminoAcid.SEQRESRECORD)) { // should not have been called return; @@ -847,10 +814,10 @@ private void pdb_TITLE_Handler(String line) { if ( line.length() > 79) title = line.substring(10,80).trim(); else - title = line.substring(10,line.length()).trim(); + title = line.substring(10).trim(); String t = pdbHeader.getTitle(); - if ( (t != null) && (! t.equals("")) ){ + if ( (t != null) && (!t.isEmpty()) ){ if (t.endsWith("-")) t += ""; // if last line ends with a hyphen then we don't add space else @@ -890,10 +857,8 @@ private void pdb_JRNL_Handler(String line) { logger.debug("trimming legacy PDB id from end of JRNL section line"); line = line.substring(0, line.length() - 8); - journalLines.add(line); - } else { - journalLines.add(line); } + journalLines.add(line); } /** @@ -905,14 +870,16 @@ private void pdb_JRNL_Handler(String line) { */ private void pdb_COMPND_Handler(String line) { - logger.debug("previousContinuationField is " + if (logger.isDebugEnabled()) { + logger.debug("previousContinuationField is " + previousContinuationField); - logger.debug("current continuationField is " + logger.debug("current continuationField is " + continuationField); - logger.debug("current continuationString is " + logger.debug("current continuationString is " + continuationString); - logger.debug("current compound is " + logger.debug("current compound is " + current_compound); + } // In legacy PDB files the line ends with the PDB code and a serial number, chop those off! @@ -926,7 +893,7 @@ private void pdb_COMPND_Handler(String line) { line = line.substring(0, 72); } - line = line.substring(10, line.length()); + line = line.substring(10); String[] fieldList = line.trim().split("\\s+"); @@ -934,7 +901,7 @@ private void pdb_COMPND_Handler(String line) { if ((fl >0 ) && compndFieldValues.contains(fieldList[0])) { continuationField = fieldList[0]; - if (previousContinuationField.equals("")) { + if (previousContinuationField.isEmpty()) { previousContinuationField = continuationField; } @@ -960,25 +927,24 @@ private void pdb_COMPND_Handler(String line) { while (compndTokens.hasMoreTokens()) { String token = compndTokens.nextToken(); - if (previousContinuationField.equals("")) { + if (previousContinuationField.isEmpty()) { previousContinuationField = continuationField; } if (previousContinuationField.equals(continuationField) && compndFieldValues.contains(continuationField)) { - logger.debug("Still in field " + continuationField); - logger.debug("token = " + token); + logger.debug("Still in field {}", continuationField); + logger.debug("token = {}", token); continuationString = continuationString.concat(token + " "); - logger.debug("continuationString = " - + continuationString); + logger.debug("continuationString = {}", continuationString); } if (!continuationField.equals(previousContinuationField)) { - if (continuationString.equals("")) { + if (continuationString.isEmpty()) { continuationString = token; } else { @@ -1014,7 +980,7 @@ private void compndValueSetter(String field, String value) { int i = -1; try { - i = Integer.valueOf(value); + i = Integer.parseInt(value); } catch (NumberFormatException e){ logger.warn("Value '{}' does not look like a number, while trying to parse COMPND MOL_ID line.",value); } @@ -1048,7 +1014,7 @@ private void compndValueSetter(String field, String value) { if (field.equals("CHAIN:")) { //System.out.println(value); StringTokenizer chainTokens = new StringTokenizer(value, ","); - List chains = new ArrayList(); + List chains = new ArrayList<>(); while (chainTokens.hasMoreTokens()) { String chainID = chainTokens.nextToken().trim(); @@ -1063,7 +1029,7 @@ private void compndValueSetter(String field, String value) { if (field.equals("SYNONYM:")) { StringTokenizer synonyms = new StringTokenizer(value, ","); - List names = new ArrayList(); + List names = new ArrayList<>(); while (synonyms.hasMoreTokens()) { names.add(synonyms.nextToken()); @@ -1076,7 +1042,7 @@ private void compndValueSetter(String field, String value) { if (field.equals("EC:")) { StringTokenizer ecNumTokens = new StringTokenizer(value, ","); - List ecNums = new ArrayList(); + List ecNums = new ArrayList<>(); while (ecNumTokens.hasMoreTokens()) { ecNums.add(ecNumTokens.nextToken()); @@ -1136,16 +1102,18 @@ private void pdb_SOURCE_Handler(String line) { - logger.debug("current continuationNo is " - + continuationNr); - logger.debug("previousContinuationField is " - + previousContinuationField); - logger.debug("current continuationField is " - + continuationField); - logger.debug("current continuationString is " - + continuationString); - logger.debug("current compound is " - + current_compound); + if (logger.isDebugEnabled()) { + logger.debug("current continuationNo is " + + continuationNr); + logger.debug("previousContinuationField is " + + previousContinuationField); + logger.debug("current continuationField is " + + continuationField); + logger.debug("current continuationString is " + + continuationString); + logger.debug("current compound is " + + current_compound); + } // following the docs, the last valid character should be 79, chop off the rest @@ -1153,34 +1121,34 @@ private void pdb_SOURCE_Handler(String line) { line = line.substring(0, 79); } - line = line.substring(10, line.length()); + line = line.substring(10); - logger.debug("LINE: >" + line + "<"); + logger.debug("LINE: >{}<", line); String[] fieldList = line.split("\\s+"); - if (!fieldList[0].equals("") + if (!fieldList[0].isEmpty() && sourceFieldValues.contains(fieldList[0])) { // System.out.println("[PDBFileParser.pdb_COMPND_Handler] Setting continuationField to '" + fieldList[0] + "'"); continuationField = fieldList[0]; - if (previousContinuationField.equals("")) { + if (previousContinuationField.isEmpty()) { previousContinuationField = continuationField; } } else if ((fieldList.length > 1) && ( sourceFieldValues.contains(fieldList[1]))) { // System.out.println("[PDBFileParser.pdb_COMPND_Handler] Setting continuationField to '" + fieldList[1] + "'"); continuationField = fieldList[1]; - if (previousContinuationField.equals("")) { + if (previousContinuationField.isEmpty()) { previousContinuationField = continuationField; } } else { - if (continuationNr.equals("")) { + if (continuationNr.isEmpty()) { logger.debug("looks like an old PDB file"); continuationField = "MOLECULE:"; - if (previousContinuationField.equals("")) { + if (previousContinuationField.isEmpty()) { previousContinuationField = continuationField; } } @@ -1196,7 +1164,7 @@ private void pdb_SOURCE_Handler(String line) { while (compndTokens.hasMoreTokens()) { String token = compndTokens.nextToken(); - if (previousContinuationField.equals("")) { + if (previousContinuationField.isEmpty()) { // System.out.println("previousContinuationField is empty. Setting to : " + continuationField); previousContinuationField = continuationField; } @@ -1204,16 +1172,15 @@ private void pdb_SOURCE_Handler(String line) { if (previousContinuationField.equals(continuationField) && sourceFieldValues.contains(continuationField)) { - logger.debug("Still in field " + continuationField); + //logger.debug("Still in field " + continuationField); continuationString = continuationString.concat(token + " "); - logger.debug("continuationString = " - + continuationString); + //logger.debug("continuationString = " + continuationString); } if (!continuationField.equals(previousContinuationField)) { - if (continuationString.equals("")) { + if (continuationString.isEmpty()) { continuationString = token; } else { @@ -1252,7 +1219,7 @@ private void sourceValueSetter(String field, String value) { if (field.equals("MOL_ID:")) { try { - current_compound = entities.get(Integer.valueOf(value) - 1); + current_compound = entities.get(Integer.parseInt(value) - 1); } catch (NumberFormatException e){ logger.info("could not process SOURCE MOL_ID record correctly:" + e.getMessage()); return; @@ -1262,74 +1229,111 @@ private void sourceValueSetter(String field, String value) { // System.out.println("[sourceValueSetter] Fetching compound " + value + " " + current_compound.getMolId()); } - if (field.equals("SYNTHETIC:")) { - current_compound.setSynthetic(value); - } else if (field.equals("FRAGMENT:")) { - current_compound.setFragment(value); - } else if (field.equals("ORGANISM_SCIENTIFIC:")) { - current_compound.setOrganismScientific(value); - } else if (field.equals("ORGANISM_TAXID:")) { - current_compound.setOrganismTaxId(value); - } else if (field.equals("ORGANISM_COMMON:")) { - current_compound.setOrganismCommon(value); - } else if (field.equals("STRAIN:")) { - current_compound.setStrain(value); - } else if (field.equals("VARIANT:")) { - current_compound.setVariant(value); - } else if (field.equals("CELL_LINE:")) { - current_compound.setCellLine(value); - } else if (field.equals("ATCC:")) { - current_compound.setAtcc(value); - } else if (field.equals("ORGAN:")) { - current_compound.setOrgan(value); - } else if (field.equals("TISSUE:")) { - current_compound.setTissue(value); - } else if (field.equals("CELL:")) { - current_compound.setCell(value); - } else if (field.equals("ORGANELLE:")) { - current_compound.setOrganelle(value); - } else if (field.equals("SECRETION:")) { - current_compound.setSecretion(value); - } else if (field.equals("GENE:")) { - current_compound.setGene(value); - } else if (field.equals("CELLULAR_LOCATION:")) { - current_compound.setCellularLocation(value); - } else if (field.equals("EXPRESSION_SYSTEM:")) { - current_compound.setExpressionSystem(value); - } else if (field.equals("EXPRESSION_SYSTEM_TAXID:")) { - current_compound.setExpressionSystemTaxId(value); - } else if (field.equals("EXPRESSION_SYSTEM_STRAIN:")) { - current_compound.setExpressionSystemStrain(value); - } else if (field.equals("EXPRESSION_SYSTEM_VARIANT:")) { - current_compound.setExpressionSystemVariant(value); - } else if (field.equals("EXPRESSION_SYSTEM_CELL_LINE:")) { - current_compound.setExpressionSystemCellLine(value); - } else if (field.equals("EXPRESSION_SYSTEM_ATCC_NUMBER:")) { - current_compound.setExpressionSystemAtccNumber(value); - } else if (field.equals("EXPRESSION_SYSTEM_ORGAN:")) { - current_compound.setExpressionSystemOrgan(value); - } else if (field.equals("EXPRESSION_SYSTEM_TISSUE:")) { - current_compound.setExpressionSystemTissue(value); - } else if (field.equals("EXPRESSION_SYSTEM_CELL:")) { - current_compound.setExpressionSystemCell(value); - } else if (field.equals("EXPRESSION_SYSTEM_ORGANELLE:")) { - current_compound.setExpressionSystemOrganelle(value); - } else if (field.equals("EXPRESSION_SYSTEM_CELLULAR_LOCATION:")) { - current_compound.setExpressionSystemCellularLocation(value); - } else if (field.equals("EXPRESSION_SYSTEM_VECTOR_TYPE:")) { - current_compound.setExpressionSystemVectorType(value); - } else if (field.equals("EXPRESSION_SYSTEM_VECTOR:")) { - current_compound.setExpressionSystemVector(value); - } else if (field.equals("EXPRESSION_SYSTEM_PLASMID:")) { - current_compound.setExpressionSystemPlasmid(value); - } else if (field.equals("EXPRESSION_SYSTEM_GENE:")) { - current_compound.setExpressionSystemGene(value); - } else if (field.equals("OTHER_DETAILS:")) { - current_compound.setExpressionSystemOtherDetails(value); + switch (field) { + case "SYNTHETIC:": + current_compound.setSynthetic(value); + break; + case "FRAGMENT:": + current_compound.setFragment(value); + break; + case "ORGANISM_SCIENTIFIC:": + current_compound.setOrganismScientific(value); + break; + case "ORGANISM_TAXID:": + current_compound.setOrganismTaxId(value); + break; + case "ORGANISM_COMMON:": + current_compound.setOrganismCommon(value); + break; + case "STRAIN:": + current_compound.setStrain(value); + break; + case "VARIANT:": + current_compound.setVariant(value); + break; + case "CELL_LINE:": + current_compound.setCellLine(value); + break; + case "ATCC:": + current_compound.setAtcc(value); + break; + case "ORGAN:": + current_compound.setOrgan(value); + break; + case "TISSUE:": + current_compound.setTissue(value); + break; + case "CELL:": + current_compound.setCell(value); + break; + case "ORGANELLE:": + current_compound.setOrganelle(value); + break; + case "SECRETION:": + current_compound.setSecretion(value); + break; + case "GENE:": + current_compound.setGene(value); + break; + case "CELLULAR_LOCATION:": + current_compound.setCellularLocation(value); + break; + case "EXPRESSION_SYSTEM:": + current_compound.setExpressionSystem(value); + break; + case "EXPRESSION_SYSTEM_TAXID:": + current_compound.setExpressionSystemTaxId(value); + break; + case "EXPRESSION_SYSTEM_STRAIN:": + current_compound.setExpressionSystemStrain(value); + break; + case "EXPRESSION_SYSTEM_VARIANT:": + current_compound.setExpressionSystemVariant(value); + break; + case "EXPRESSION_SYSTEM_CELL_LINE:": + current_compound.setExpressionSystemCellLine(value); + break; + case "EXPRESSION_SYSTEM_ATCC_NUMBER:": + current_compound.setExpressionSystemAtccNumber(value); + break; + case "EXPRESSION_SYSTEM_ORGAN:": + current_compound.setExpressionSystemOrgan(value); + break; + case "EXPRESSION_SYSTEM_TISSUE:": + current_compound.setExpressionSystemTissue(value); + break; + case "EXPRESSION_SYSTEM_CELL:": + current_compound.setExpressionSystemCell(value); + break; + case "EXPRESSION_SYSTEM_ORGANELLE:": + current_compound.setExpressionSystemOrganelle(value); + break; + case "EXPRESSION_SYSTEM_CELLULAR_LOCATION:": + current_compound.setExpressionSystemCellularLocation(value); + break; + case "EXPRESSION_SYSTEM_VECTOR_TYPE:": + current_compound.setExpressionSystemVectorType(value); + break; + case "EXPRESSION_SYSTEM_VECTOR:": + current_compound.setExpressionSystemVector(value); + break; + case "EXPRESSION_SYSTEM_PLASMID:": + current_compound.setExpressionSystemPlasmid(value); + break; + case "EXPRESSION_SYSTEM_GENE:": + current_compound.setExpressionSystemGene(value); + break; + case "OTHER_DETAILS:": + current_compound.setExpressionSystemOtherDetails(value); + break; } } + static final Pattern resolutionRangePattern = Pattern.compile("^REMARK 3 RESOLUTION RANGE HIGH \\(ANGSTROMS\\) :\\s+(\\d+\\.\\d+).*"); + static final Pattern remarkFreeRValue = Pattern.compile("^REMARK 3 FREE R VALUE\\s+:\\s+(\\d?\\.\\d+).*"); + static final Pattern remark3FreeRValueNoCutOff = Pattern.compile("^REMARK 3 FREE R VALUE\\s+(?:\\(NO CUTOFF\\))?\\s+:\\s+(\\d?\\.\\d+).*"); + /** * Handler for REMARK lines */ @@ -1363,8 +1367,8 @@ private void pdb_REMARK_Handler(String line) { // a) take the '(NO CUTOFF)' value if the only one available (shelx software, e.g. 1x7q) // b) don't take it if also a line without '(NO CUTOFF)' is present (CNX software, e.g. 3lak) - Pattern pR = Pattern.compile("^REMARK 3 FREE R VALUE\\s+(?:\\(NO CUTOFF\\))?\\s+:\\s+(\\d?\\.\\d+).*"); - Matcher mR = pR.matcher(line); + + Matcher mR = remark3FreeRValueNoCutOff.matcher(line); if (mR.matches()) { try { rfreeNoCutoffLine = Float.parseFloat(mR.group(1)); @@ -1372,8 +1376,8 @@ private void pdb_REMARK_Handler(String line) { logger.info("Rfree value "+mR.group(1)+" does not look like a number, will ignore it"); } } - pR = Pattern.compile("^REMARK 3 FREE R VALUE\\s+:\\s+(\\d?\\.\\d+).*"); - mR = pR.matcher(line); + + mR = remarkFreeRValue.matcher(line); if (mR.matches()) { try { rfreeStandardLine = Float.parseFloat(mR.group(1)); @@ -1386,8 +1390,7 @@ private void pdb_REMARK_Handler(String line) { // note: if more than 1 value present (occurring in hybrid experimental technique entries, e.g. 3ins, 4n9m) // then last one encountered will be taken } else if (line.startsWith("REMARK 3 RESOLUTION RANGE HIGH")){ - Pattern pR = Pattern.compile("^REMARK 3 RESOLUTION RANGE HIGH \\(ANGSTROMS\\) :\\s+(\\d+\\.\\d+).*"); - Matcher mR = pR.matcher(line); + Matcher mR = resolutionRangePattern.matcher(line); if (mR.matches()) { try { float res = Float.parseFloat(mR.group(1)); @@ -1480,7 +1483,7 @@ private void pdb_CRYST1_Handler(String line) { float alpha; float beta; float gamma; - String spaceGroup = ""; + String spaceGroup; try { a = Float.parseFloat(line.substring(6,15).trim()); @@ -1498,7 +1501,7 @@ private void pdb_CRYST1_Handler(String line) { spaceGroup = line.substring(55,66).trim(); } else { // for not-so-well formatted files, e.g. phenix-produced ones: they lack a Z value - spaceGroup = line.substring(55,line.length()).trim(); + spaceGroup = line.substring(55).trim(); } CrystalCell xtalCell = new CrystalCell(); @@ -1575,7 +1578,7 @@ private void pdb_MTRIXn_Handler(String line) { if (ncsOperators==null) { // we initialise on first pass - ncsOperators = new ArrayList(); + ncsOperators = new ArrayList<>(); } if (currentNcsOp==null) { @@ -1717,7 +1720,7 @@ private void pdb_ATOM_Handler(String line) { startOfMolecule = false; - Character altLoc = new Character(line.substring (16, 17).charAt(0)); + Character altLoc = line.substring(16, 17).charAt(0); Group altGroup = null; @@ -1738,7 +1741,8 @@ private void pdb_ATOM_Handler(String line) { // test altLoc if ( ! altLoc.equals(' ')) { - logger.debug("found altLoc! " + currentGroup + " " + altGroup); + logger.debug("found altLoc! {} {}", currentGroup, altGroup); + altGroup = getCorrectAltLocGroup( altLoc,recordName,aminoCode1,groupCode3); if ( altGroup.getChain() == null) { // need to set current chain @@ -1965,7 +1969,7 @@ private Group getCorrectAltLocGroup( Character altLoc, Group altLocG = (Group) currentGroup.clone(); // drop atoms from cloned group... // https://redmine.open-bio.org/issues/3307 - altLocG.setAtoms(new ArrayList()); + altLocG.setAtoms(new ArrayList<>()); altLocG.getAltLocs().clear(); currentGroup.addAltLoc(altLocG); return altLocG; @@ -2002,15 +2006,15 @@ private void switchCAOnly(){ /** safes repeating a few lines ... */ private Integer conect_helper (String line,int start,int end) { - if (line.length() < end) return null; + if (line.length() < start || line.length() < end) return null; String sbond = line.substring(start,end).trim(); - int bond = -1 ; + int bond; Integer b = null ; - if ( ! sbond.equals("")) { + if (!sbond.isEmpty()) { bond = Integer.parseInt(sbond); - b = new Integer(bond); + b = bond; } return b ; @@ -2066,8 +2070,8 @@ private void pdb_CONECT_Handler(String line) { //System.out.println(atomserial+ " "+ bond1 +" "+bond2+ " " +bond3+" "+bond4+" "+ // hyd1+" "+hyd2 +" "+salt1+" "+hyd3+" "+hyd4+" "+salt2); - HashMap cons = new HashMap(); - cons.put("atomserial",new Integer(atomserial)); + HashMap cons = new HashMap<>(); + cons.put("atomserial", atomserial); if ( bond1 != null) cons.put("bond1",bond1); if ( bond2 != null) cons.put("bond2",bond2); @@ -2150,7 +2154,7 @@ private void pdb_TER_Handler() { */ private void pdb_DBREF_Handler(String line){ - logger.debug("Parsing DBREF " + line); + logger.debug("Parsing DBREF {}", line); DBRef dbref = new DBRef(); String idCode = line.substring(7,11); @@ -2232,7 +2236,7 @@ private void pdb_SSBOND_Handler(String line){ String symop2 = line.substring(66, 72).trim(); // until we implement proper treatment of symmetry in biojava #220, we can't deal with sym-related parteners properly, skipping them - if (!symop1.equals("") && !symop2.equals("") && // in case the field is missing + if (!symop1.isEmpty() && !symop2.isEmpty() && // in case the field is missing (!symop1.equals("1555") || !symop2.equals("1555")) ) { logger.info("Skipping ss bond between groups {} and {} belonging to different symmetry partners, because it is not supported yet", seqNum1+icode1, seqNum2+icode2); return; @@ -2361,7 +2365,7 @@ private void pdb_SITE_Handler(String line){ // make a map of: SiteId to List - logger.debug("Site Line:"+line); + //logger.debug("Site Line: "+line); String siteID = line.substring(11, 14); @@ -2370,27 +2374,27 @@ private void pdb_SITE_Handler(String line){ //if the siteResidues doesn't yet exist, make a new one. if (siteResidues == null || ! siteToResidueMap.containsKey(siteID.trim())){ - siteResidues = new ArrayList(); + siteResidues = new ArrayList<>(); siteToResidueMap.put(siteID.trim(), siteResidues); - logger.debug(String.format("New Site made: %s %s", siteID, siteResidues)); - logger.debug("Now made " + siteMap.size() + " sites"); + //logger.debug(String.format("New Site made: %s %s", siteID, siteResidues)); + //logger.debug("Now made " + siteMap.size() + " sites"); } - logger.debug(String.format("SiteId: %s", siteID)); + //logger.debug(String.format("SiteId: %s", siteID)); //line = 'SITE 1 AC1 6 ARG H 221A LYS H 224 HOH H 403 HOH H 460' //line.substring(18) = 'ARG H 221A LYS H 224 HOH H 403 HOH H 460' line = line.substring(18); - String groupString = null; + String groupString; //groupString = 'ARG H 221A' //keep iterating through chunks of 10 characters - these are the groups in the siteResidues while (!(groupString = line.substring(0, 10)).equals(" ")) { //groupstring: 'ARG H 221A' - logger.debug("groupString: '" + groupString + "'"); + //logger.debug("groupString: '" + groupString + "'"); //set the residue name //residueName = 'ARG' @@ -2414,13 +2418,13 @@ private void pdb_SITE_Handler(String line){ // insCode = null; // } - logger.debug(String.format("Site: %s: 'resName:%s resNum:%s insCode:%s'", siteID, residueName, resNum, insCode)); + //logger.debug(String.format("Site: %s: 'resName:%s resNum:%s insCode:%s'", siteID, residueName, resNum, insCode)); //make a new resNum with the data - this will be linked up with a site later ResidueNumber residueNumber = new ResidueNumber(); - logger.debug("pdbCode: '" + resNum + insCode + "'"); + //logger.debug("pdbCode: '" + resNum + insCode + "'"); residueNumber.setChainName(chainId); residueNumber.setSeqNum(resNum); @@ -2428,15 +2432,15 @@ private void pdb_SITE_Handler(String line){ //add the resNum to the groups siteResidues.add(residueNumber); - logger.debug("Adding residueNumber " + residueNumber + " to site " + siteID); + //logger.debug("Adding residueNumber " + residueNumber + " to site " + siteID); line = line.substring(11); } - logger.debug("Current SiteMap (contains "+ siteToResidueMap.keySet().size() + " sites):"); - for (String key : siteToResidueMap.keySet()) { - logger.debug(key + " : " + siteToResidueMap.get(key)); - } +// logger.debug("Current SiteMap (contains "+ siteToResidueMap.keySet().size() + " sites):"); +// for (Map.Entry> entry : siteToResidueMap.entrySet()) { +// logger.debug(entry.getKey() + " : " + entry.getValue()); +// } } @@ -2455,18 +2459,18 @@ private void pdb_REMARK_800_Handler(String line){ // remark800Counter++; String siteID = fields[1].trim(); - logger.debug("siteID: '" + siteID +"'"); + //logger.debug("siteID: '" + siteID +"'"); //fetch the siteResidues from the map site = siteMap.get(siteID); //if the siteResidues doesn't yet exist, make a new one. if (site == null || !siteID.equals(site.getSiteID())) { - site = new Site(siteID, new ArrayList()); + site = new Site(siteID, new ArrayList<>()); siteMap.put(site.getSiteID(), site); - logger.debug("New Site made: " + site); - logger.debug("Now made " + siteMap.size() + " sites"); + //logger.debug("New Site made: " + site); + //logger.debug("Now made " + siteMap.size() + " sites"); } } @@ -2474,7 +2478,7 @@ private void pdb_REMARK_800_Handler(String line){ // remark800Counter++; String evCode = fields[1].trim(); - logger.debug("evCode: '" + evCode +"'"); + //logger.debug("evCode: '" + evCode +"'"); //fetch the siteResidues from the map site.setEvCode(evCode); @@ -2483,13 +2487,13 @@ private void pdb_REMARK_800_Handler(String line){ // remark800Counter++; String desc = fields[1].trim(); - logger.debug("desc: '" + desc +"'"); + //logger.debug("desc: '" + desc +"'"); //fetch the siteResidues from the map site.setDescription(desc); - logger.debug("Finished making REMARK 800 for site " + site.getSiteID()); - logger.debug(site.remark800toPDB()); + //logger.debug("Finished making REMARK 800 for site " + site.getSiteID()); + //logger.debug(site.remark800toPDB()); } } @@ -2585,10 +2589,10 @@ public Structure parsePDBFile(BufferedReader buf) startOfMolecule = true; startOfModel = true; - seqResChains = new ArrayList(); - siteMap = new LinkedHashMap(); + seqResChains = new ArrayList<>(); + siteMap = new LinkedHashMap<>(); pdbHeader = new PDBHeader(); - connects = new ArrayList>(); + connects = new ArrayList<>(); previousContinuationField = ""; continuationField = ""; continuationString = ""; @@ -2605,19 +2609,19 @@ public Structure parsePDBFile(BufferedReader buf) lengthCheck = -1; atomCount = 0; atomOverflow = false; - linkRecords = new ArrayList(); + linkRecords = new ArrayList<>(); siteToResidueMap.clear(); blankChainIdsPresent = false; parseCAonly = params.isParseCAOnly(); - String line = null; + String line; while ((line = buf.readLine()) != null) { // ignore empty lines - if ( line.equals("") || + if (line.isEmpty() || (line.equals(NEWLINE))){ continue; } @@ -2633,13 +2637,14 @@ public Structure parsePDBFile(BufferedReader buf) continue; } - String recordName = null; + String recordName; if (line.length()<6) recordName = line.trim(); else recordName = line.substring (0, 6).trim (); try { + //TODO switch(recordName) if (recordName.equals("ATOM")) pdb_ATOM_Handler(line); else if (recordName.equals("SEQRES")) @@ -2682,10 +2687,20 @@ else if (recordName.equals("SSBOND")) pdb_SSBOND_Handler(line); else if (recordName.equals("LINK")) pdb_LINK_Handler(line); - else if ( params.isParseSecStruc()) { - if ( recordName.equals("HELIX") ) pdb_HELIX_Handler ( line ) ; - else if (recordName.equals("SHEET")) pdb_SHEET_Handler(line ) ; - else if (recordName.equals("TURN")) pdb_TURN_Handler( line ) ; + else { + if ( params.isParseSecStruc()) { + switch (recordName) { + case "HELIX": + pdb_HELIX_Handler(line); + break; + case "SHEET": + pdb_SHEET_Handler(line); + break; + case "TURN": + pdb_TURN_Handler(line); + break; + } + } } } catch (StringIndexOutOfBoundsException | NullPointerException ex) { logger.info("Unable to parse [" + line + "]"); @@ -2712,7 +2727,7 @@ else if ( params.isParseSecStruc()) { return structure; - } + } /** @@ -2834,12 +2849,12 @@ private void triggerEndFileChecks(){ // Only align if requested (default) and not when headerOnly mode with no Atoms. // Otherwise, we store the empty SeqRes Groups unchanged in the right chains. if ( params.isAlignSeqRes() && !params.isHeaderOnly() && !seqResChains.isEmpty()){ - logger.debug("Parsing mode align_seqres, will parse SEQRES and align to ATOM sequence"); + //logger.debug("Parsing mode align_seqres, will parse SEQRES and align to ATOM sequence"); SeqRes2AtomAligner aligner = new SeqRes2AtomAligner(); aligner.align(structure,seqResChains); } else { - logger.debug("Parsing mode unalign_seqres, will parse SEQRES but not align it to ATOM sequence"); + //logger.debug("Parsing mode unalign_seqres, will parse SEQRES but not align it to ATOM sequence"); SeqRes2AtomAligner.storeUnAlignedSeqRes(structure, seqResChains, params.isHeaderOnly()); } @@ -2858,7 +2873,7 @@ private void triggerEndFileChecks(){ if (ncsOperators !=null && ncsOperators.size()>0) { crystallographicInfo.setNcsOperators( - ncsOperators.toArray(new Matrix4d[ncsOperators.size()])); + ncsOperators.toArray(new Matrix4d[0])); } @@ -3249,53 +3264,55 @@ private void linkSitesToGroups() { return; } - List sites = null; + List sites; //check that there are chains with which to associate the groups if (structure.getChains().isEmpty()) { - sites = new ArrayList(siteMap.values()); + sites = new ArrayList<>(siteMap.values()); logger.info("No chains to link Site Groups with - Sites will not be present in the Structure"); - return; - } + } else { - //check that the keys in the siteMap and SiteToResidueMap are equal - if (! siteMap.keySet().equals(siteToResidueMap.keySet())) { - logger.info("Not all sites have been properly described in the PDB " + pdbId + " header - some Sites will not be present in the Structure"); - logger.debug(siteMap.keySet() + " | " + siteToResidueMap.keySet()); - //return; - } + if (logger.isInfoEnabled()) { + if (!siteMap.keySet().equals(siteToResidueMap.keySet())) { + //check that the keys in the siteMap and SiteToResidueMap are equal + logger.info("Not all sites have been properly described in the PDB {} header - some Sites will not be present in the Structure", pdbId); + //logger.debug("{} | {}", siteMap, siteToResidueMap.keySet()); + //return; + } + } - //so we have chains - associate the siteResidues-related groups with the ones - //already in in the chains - for (String key : siteMap.keySet()) { - Site currentSite = siteMap.get(key); - List linkedGroups = siteToResidueMap.get(key); - if ( linkedGroups == null) - continue; - for (ResidueNumber residueNumber : linkedGroups) { + //so we have chains - associate the siteResidues-related groups with the ones + //already in in the chains + for (Map.Entry entry : siteMap.entrySet()) { + Site currentSite = entry.getValue(); + List linkedGroups = siteToResidueMap.get(entry.getKey()); + if (linkedGroups == null) + continue; + for (ResidueNumber residueNumber : linkedGroups) { - String pdbCode = residueNumber.toString(); - String chain = residueNumber.getChainName(); - // System.out.println("chain: '" + chain + "'"); - // String resNum = resNum.getSeqNum().toString(); - // System.out.println("resNum: '" + resNum + "'"); + String pdbCode = residueNumber.toString(); + String chain = residueNumber.getChainName(); + // System.out.println("chain: '" + chain + "'"); + // String resNum = resNum.getSeqNum().toString(); + // System.out.println("resNum: '" + resNum + "'"); - Group linkedGroup = null; - try { - //TODO: implement findGroup(ResidueNumber resNum) - linkedGroup = structure.findGroup(chain, pdbCode); - } catch (StructureException ex) { - logger.info("Can't find group " + pdbCode + " in chain " + chain + " in order to link up SITE records (PDB ID " + pdbId +")"); - continue; - } - // System.out.println("Adding group: " + linkedGroup.getSeqNum() + " to site " + site.getSiteID()); - currentSite.getGroups().add(linkedGroup); + try { + //TODO: implement findGroup(ResidueNumber resNum) + Group linkedGroup = structure.findGroup(chain, pdbCode); + currentSite.getGroups().add(linkedGroup); + } catch (StructureException ex) { + logger.info("Can't find group {} in chain {} in order to link up SITE records (PDB ID {})", pdbCode, chain, pdbId); + } + + // System.out.println("Adding group: " + linkedGroup.getSeqNum() + " to site " + site.getSiteID()); + } } - } - //System.out.println("SITEMAP: " + siteMap); + //System.out.println("SITEMAP: " + siteMap); + + sites = new ArrayList<>(siteMap.values()); + } - sites = new ArrayList(siteMap.values()); structure.setSites(sites); //System.out.println("STRUCTURE SITES: " + structure.getSites().size()); // for (Site site : structure.getSites()) { @@ -3321,14 +3338,14 @@ private void buildjournalArticle() { // JRNL REFN ISSN 1529-2908 // JRNL PMID 17351618 // JRNL DOI 10.1038/NI1450 - StringBuffer auth = new StringBuffer(); - StringBuffer titl = new StringBuffer(); - StringBuffer edit = new StringBuffer(); - StringBuffer ref = new StringBuffer(); - StringBuffer publ = new StringBuffer(); - StringBuffer refn = new StringBuffer(); - StringBuffer pmid = new StringBuffer(); - StringBuffer doi = new StringBuffer(); + StringBuilder auth = new StringBuilder(); + StringBuilder titl = new StringBuilder(); + StringBuilder edit = new StringBuilder(); + StringBuilder ref = new StringBuilder(); + StringBuilder publ = new StringBuilder(); + StringBuilder refn = new StringBuilder(); + StringBuilder pmid = new StringBuilder(); + StringBuilder doi = new StringBuilder(); for (String line : journalLines) { if ( line.length() < 19 ) { @@ -3339,36 +3356,36 @@ private void buildjournalArticle() { String subField = line.substring(12, 16); // System.out.println("'" + subField + "'"); if (subField.equals("AUTH")) { - auth.append(line.substring(19, line.length()).trim()); + auth.append(line.substring(19).trim()); - logger.debug("AUTH '" + auth.toString() + "'"); + //logger.debug("AUTH '" + auth + "'"); } if (subField.equals("TITL")) { //add a space to the end of a line so that when wrapped the //words on the join won't be concatenated - titl.append(line.substring(19, line.length()).trim()).append(" "); + titl.append(line.substring(19).trim()).append(" "); - logger.debug("TITL '" + titl.toString() + "'"); + //logger.debug("TITL '" + titl + "'"); } if (subField.equals("EDIT")) { - edit.append(line.substring(19, line.length()).trim()); + edit.append(line.substring(19).trim()); - logger.debug("EDIT '" + edit.toString() + "'"); + //logger.debug("EDIT '" + edit + "'"); } // JRNL REF NAT.IMMUNOL. V. 8 430 2007 if (subField.equals("REF ")) { - ref.append(line.substring(19, line.length()).trim()).append(" "); + ref.append(line.substring(19).trim()).append(" "); - logger.debug("REF '" + ref.toString() + "'"); + //logger.debug("REF '" + ref + "'"); } if (subField.equals("PUBL")) { - publ.append(line.substring(19, line.length()).trim()).append(" "); + publ.append(line.substring(19).trim()).append(" "); - logger.debug("PUBL '" + publ.toString() + "'"); + //logger.debug("PUBL '" + publ + "'"); } // JRNL REFN ISSN 1529-2908 @@ -3377,23 +3394,23 @@ private void buildjournalArticle() { logger.info("can not process Journal REFN line: " + line); continue; } - refn.append(line.substring(35, line.length()).trim()); + refn.append(line.substring(35).trim()); - logger.debug("REFN '" + refn.toString() + "'"); + //logger.debug("REFN '" + refn + "'"); } // JRNL PMID 17351618 if (subField.equals("PMID")) { - pmid.append(line.substring(19, line.length()).trim()); + pmid.append(line.substring(19).trim()); - logger.debug("PMID '" + pmid.toString() + "'"); + //logger.debug("PMID '" + pmid + "'"); } // JRNL DOI 10.1038/NI1450 if (subField.equals("DOI ")) { - doi.append(line.substring(19, line.length()).trim()); + doi.append(line.substring(19).trim()); - logger.debug("DOI '" + doi.toString() + "'"); + //logger.debug("DOI '" + doi + "'"); } } @@ -3417,13 +3434,11 @@ private void buildjournalArticle() { journalArticle.setDoi(doi.toString().trim()); - logger.debug("Made JournalArticle:"); - logger.debug(journalArticle.toString()); - + logger.debug("Made JournalArticle: {}", journalArticle); } //inner class to deal with all the journal info - private class JournalParser { + private static class JournalParser { private String journalName; private String volume; @@ -3433,13 +3448,13 @@ private class JournalParser { public JournalParser(String ref) { - logger.debug("JournalParser init '" + ref + "'"); + logger.debug("JournalParser init '{}'", ref); if (ref.equals("TO BE PUBLISHED ")) { journalName = ref.trim(); - logger.debug(String.format("JournalParser found journalString '%s'", journalName)); + logger.debug("JournalParser found journalString '{}'", journalName); return; } @@ -3474,7 +3489,7 @@ public JournalParser(String ref) { //'NAT.STRUCT.MOL.BIOL. V. 16 238 2009' String volumeInformation = ref.substring(30, 48); - logger.debug(String.format("Parsing volumeInformation: '%s'", volumeInformation)); + logger.debug("Parsing volumeInformation: '{}'", volumeInformation); //volumeInformation: 'V. 293 53 1981 ' // String dateString = ref.substring(ref.length() - 5 , ref.length() - 1).trim(); @@ -3489,15 +3504,17 @@ public JournalParser(String ref) { journalString = journalString.trim(); // System.out.println("journalString: " + journalString); - logger.debug(String.format("JournalParser found volumeString '%s'", volumeString)); - logger.debug(String.format("JournalParser found startPageString '%s'", startPageString)); - logger.debug(String.format("JournalParser found dateString '%s'", dateString)); - logger.debug(String.format("JournalParser found journalString '%s'", journalString)); + if (logger.isDebugEnabled()) { + logger.debug(String.format("JournalParser found volumeString '%s'", volumeString)); + logger.debug(String.format("JournalParser found startPageString '%s'", startPageString)); + logger.debug(String.format("JournalParser found dateString '%s'", dateString)); + logger.debug(String.format("JournalParser found journalString '%s'", journalString)); + } if (!dateString.equals(" ")) { try { - publicationDate = Integer.valueOf(dateString); + publicationDate = Integer.parseInt(dateString); } catch (NumberFormatException nfe) { logger.info(dateString + " is not a valid integer for a date in JRNL sub-section REF line 1"); } @@ -3523,7 +3540,7 @@ public JournalParser(String ref) { if (!journalString.equals(" ")) { journalName = journalString; - logger.debug("JournalParser set journalName " + journalName); + logger.debug("JournalParser set journalName {}", journalName); } } @@ -3546,9 +3563,9 @@ private String getVolume() { } private List authorBuilder(String authorString) { - ArrayList authorList = new ArrayList(); + ArrayList authorList = new ArrayList<>(); - if (authorString.equals("")) { + if (authorString.isEmpty()) { return authorList; } @@ -3573,14 +3590,14 @@ private List authorBuilder(String authorString) { Author author = new Author(); author.setSurname(authors[0]); - logger.debug("Set consortium author name " + author.getSurname()); + logger.debug("Set consortium author name {}", author.getSurname()); authorList.add(author); } else { for (int i = 0; i < authors.length; i++) { String authorFullName = authors[i]; - logger.debug("Building author " + authorFullName); + logger.debug("Building author {}", authorFullName); Author author = new Author(); String regex = "\\."; @@ -3596,15 +3613,14 @@ private List authorBuilder(String authorString) { if (authorNames.length == 0) { author.setSurname(authorFullName); - logger.debug("Unable to split using '" + regex + "' Setting whole name " + author.getSurname()); + logger.debug("Unable to split using '{}' Setting whole name {}", regex, author.getSurname()); } //again there might be a consortium name so there may be no elements else if (authorNames.length == 1) { author.setSurname(authorNames[0]); - logger.debug("Set consortium author name in multiple author block " + author.getSurname - ()); + logger.debug("Set consortium author name in multiple author block {}", author.getSurname()); } else { String initials = ""; @@ -3617,14 +3633,14 @@ else if (authorNames.length == 1) { initials += initial + "."; } - logger.debug("built initials '" + initials + "'"); + logger.debug("built initials '{}'", initials); author.setInitials(initials); //surname is always last int lastName = authorNames.length - 1; String surname = authorNames[lastName]; - logger.debug("built author surname " + surname); + logger.debug("built author surname {}", surname); author.setSurname(surname); @@ -3651,4 +3667,4 @@ public FileParsingParameters getFileParsingParameters(){ } -} \ No newline at end of file +} diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/PDBFileReader.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/PDBFileReader.java index 5591fbdd84..fa1dcecd14 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/PDBFileReader.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/PDBFileReader.java @@ -26,6 +26,7 @@ import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.align.util.UserConfiguration; + import java.io.IOException; import java.io.InputStream; @@ -137,8 +138,7 @@ public Structure getStructure(InputStream inStream) throws IOException { PDBFileParser pdbpars = new PDBFileParser(); pdbpars.setFileParsingParameters(getFileParsingParameters()); - Structure struc = pdbpars.parsePDBFile(inStream) ; - return struc ; + return pdbpars.parsePDBFile(inStream); } @Override diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/PDBParseException.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/PDBParseException.java index 150201027f..4b0c6d11b2 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/PDBParseException.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/PDBParseException.java @@ -28,7 +28,7 @@ */ public class PDBParseException extends Exception{ - public static final long serialVersionUID = 219047230178423923l; + public static final long serialVersionUID = 219047230178423923L; /** * Constructs a PDBParseException object. * diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/SSBondImpl.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/SSBondImpl.java index ae3aaab9ae..2392e8ac3f 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/SSBondImpl.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/SSBondImpl.java @@ -23,12 +23,12 @@ package org.biojava.nbio.structure.io; -import java.util.ArrayList; -import java.util.List; - import org.biojava.nbio.structure.Bond; import org.biojava.nbio.structure.PDBRecord; +import java.util.ArrayList; +import java.util.List; + /** * A simple bean to store disulfide bridge information, the SSBOND records in the PDB files. * The two residues specified here are CYS residues that form a Disulfide bridge. diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/SandboxStyleStructureProvider.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/SandboxStyleStructureProvider.java index 6dc3b9a1f0..fe7cc98034 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/SandboxStyleStructureProvider.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/SandboxStyleStructureProvider.java @@ -20,10 +20,10 @@ */ package org.biojava.nbio.structure.io; +import org.biojava.nbio.core.util.InputStreamProvider; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.util.UserConfiguration; -import org.biojava.nbio.core.util.InputStreamProvider; import java.io.File; import java.io.IOException; @@ -187,7 +187,7 @@ public List getAllPDBIDs() throws IOException{ String[] dirName = f.list(); - ListpdbIds = new ArrayList(); + ListpdbIds = new ArrayList<>(); for (String dir : dirName) { File d2= new File(f,dir); if ( ! d2.isDirectory()) diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/SeqRes2AtomAligner.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/SeqRes2AtomAligner.java index 580a8af158..c0296d6fc6 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/SeqRes2AtomAligner.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/SeqRes2AtomAligner.java @@ -24,12 +24,6 @@ package org.biojava.nbio.structure.io; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - import org.biojava.nbio.alignment.Alignments; import org.biojava.nbio.alignment.Alignments.PairwiseSequenceAlignerType; import org.biojava.nbio.alignment.SimpleGapPenalty; @@ -42,30 +36,21 @@ import org.biojava.nbio.core.sequence.DNASequence; import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.RNASequence; -import org.biojava.nbio.core.sequence.compound.AmbiguityDNACompoundSet; -import org.biojava.nbio.core.sequence.compound.AmbiguityDNARNAHybridCompoundSet; -import org.biojava.nbio.core.sequence.compound.AmbiguityRNACompoundSet; -import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; -import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; -import org.biojava.nbio.core.sequence.compound.DNACompoundSet; -import org.biojava.nbio.core.sequence.compound.NucleotideCompound; +import org.biojava.nbio.core.sequence.compound.*; import org.biojava.nbio.core.sequence.template.Compound; import org.biojava.nbio.core.sequence.template.Sequence; -import org.biojava.nbio.structure.AminoAcid; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.GroupType; -import org.biojava.nbio.structure.HetatomImpl; -import org.biojava.nbio.structure.NucleotideImpl; -import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.io.mmcif.chem.PolymerType; import org.biojava.nbio.structure.io.mmcif.chem.ResidueType; import org.biojava.nbio.structure.io.mmcif.model.ChemComp; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + /** * Aligns the SEQRES residues to the ATOM residues. @@ -82,7 +67,7 @@ public class SeqRes2AtomAligner { - private String alignmentString; + private final String alignmentString; public SeqRes2AtomAligner(){ logger.debug("initialising SeqRes2AtomAligner"); @@ -103,12 +88,9 @@ public String getAlignmentString() { */ public static Chain getMatchingAtomRes(Chain seqRes, List atomList, boolean useChainId) { - Iterator iter = atomList.iterator(); - while(iter.hasNext()){ - Chain atomChain = iter.next(); - - String atomChainId = null; - String seqResChainId = null; + for (Chain atomChain : atomList) { + String atomChainId; + String seqResChainId; if (useChainId) { atomChainId = atomChain.getId(); seqResChainId = seqRes.getId(); @@ -118,7 +100,7 @@ public static Chain getMatchingAtomRes(Chain seqRes, List atomList, boole } - if ( atomChainId.equals(seqResChainId)){ + if (atomChainId.equals(seqResChainId)) { return atomChain; } @@ -189,13 +171,12 @@ public void mapSeqresRecords(Chain atomRes, Chain seqRes) { logger.debug("SEQRES chain {} is a nucleotide chain ({} nucleotides), aligning nucleotides...", seqRes.getId(), numNucleotidesSeqres); alignNucleotideChains(seqRes,atomRes); - return; } else { logger.debug("SEQRES chain {} contains {} amino acids and {} nucleotides, ignoring...", seqRes.getId(),numAminosSeqres,numNucleotidesSeqres); - return; } + return; } if ( atomRes.getAtomGroups(GroupType.AMINOACID).size() < 1) { @@ -367,7 +348,7 @@ private List trySimpleMatch(List seqResGroups,List atmResGr */ public static String getFullAtomSequence(List groups, Map positionIndex, boolean isNucleotideChain){ - StringBuffer sequence = new StringBuffer() ; + StringBuilder sequence = new StringBuilder() ; int seqIndex = 0; // track sequence.length() for ( int i=0 ; i< groups.size(); i++){ Group g = groups.get(i); @@ -453,8 +434,8 @@ public static String getFullAtomSequence(List groups, Map seqRes, List atomRes) { - Map seqresIndexPosition = new HashMap(); - Map atomIndexPosition = new HashMap(); + Map seqresIndexPosition = new HashMap<>(); + Map atomIndexPosition = new HashMap<>(); String seq1 = getFullAtomSequence(seqRes, seqresIndexPosition, true); // @@ -531,7 +512,7 @@ private boolean alignNucleotideGroups(List seqRes, List atomRes) { } private Sequence getNucleotideSequence(String seq) { - Sequence s = null; + Sequence s; // first we try DNA, then RNA, them hybrid @@ -573,8 +554,8 @@ private Sequence getNucleotideSequence(String seq) { */ private boolean alignProteinChains(List seqRes, List atomRes) { - Map seqresIndexPosition = new HashMap(); - Map atomIndexPosition = new HashMap(); + Map seqresIndexPosition = new HashMap<>(); + Map atomIndexPosition = new HashMap<>(); String seq1 = getFullAtomSequence(seqRes, seqresIndexPosition, false); // @@ -643,7 +624,7 @@ private boolean mapChains(List seqResGroups, List atomRes, // make sure we actually find an alignment boolean noMatchFound = true; - Compound gapSymbol = AminoAcidCompoundSet.getAminoAcidCompoundSet().getCompoundForString("-"); + Compound gapSymbol = AminoAcidCompoundSet.aminoAcidCompoundSet.getCompoundForString("-"); mainLoop: for (int i = 1; i <= aligLength ; i++) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/StructureIOFile.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/StructureIOFile.java index 91e22b8b3c..294566f9e3 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/StructureIOFile.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/StructureIOFile.java @@ -42,13 +42,13 @@ public interface StructureIOFile extends StructureProvider { * called only in the constructor of the implementing class. * @param ext a String ... */ - public void addExtension(String ext); + void addExtension(String ext); /** * Returns a list of extensions supported by this class * @return a (potentially empty) list of strings */ - public List getExtensions(); + List getExtensions(); /** * Open filename and return a Structure object. @@ -59,7 +59,7 @@ public interface StructureIOFile extends StructureProvider { * @return a Structure object * @throws IOException ... */ - public Structure getStructure(String filename) throws IOException ; + Structure getStructure(String filename) throws IOException ; /** * Read file from File and returns @@ -69,5 +69,5 @@ public interface StructureIOFile extends StructureProvider { * @return a Structure object * @throws IOException ... */ - public Structure getStructure(File file) throws IOException ; + Structure getStructure(File file) throws IOException ; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/StructureSequenceMatcher.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/StructureSequenceMatcher.java index 3c884bbc2d..e71e4dd19f 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/StructureSequenceMatcher.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/StructureSequenceMatcher.java @@ -29,12 +29,12 @@ import org.biojava.nbio.core.alignment.template.AlignedSequence; import org.biojava.nbio.core.alignment.template.SequencePair; import org.biojava.nbio.core.alignment.template.SubstitutionMatrix; -import org.biojava.nbio.structure.*; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.core.sequence.compound.AminoAcidCompound; import org.biojava.nbio.core.sequence.compound.AminoAcidCompoundSet; import org.biojava.nbio.core.sequence.template.CompoundSet; +import org.biojava.nbio.structure.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -119,7 +119,7 @@ public static ProteinSequence getProteinSequenceForStructure(Structure struct, M for(Chain chain : struct.getChains()) { List groups = chain.getAtomGroups(); - Map chainIndexPosition = new HashMap(); + Map chainIndexPosition = new HashMap<>(); int prevLen = seqStr.length(); // get the sequence for this chain @@ -128,9 +128,9 @@ public static ProteinSequence getProteinSequenceForStructure(Structure struct, M // fix up the position to include previous chains, and map the value back to a Group - for(Integer seqIndex : chainIndexPosition.keySet()) { - Integer groupIndex = chainIndexPosition.get(seqIndex); - groupIndexPosition.put(prevLen + seqIndex, groups.get(groupIndex)); + for(Map.Entry entry : chainIndexPosition.entrySet()) { + Integer groupIndex = entry.getValue(); + groupIndexPosition.put(prevLen + entry.getKey(), groups.get(groupIndex)); } } @@ -163,7 +163,7 @@ public static ProteinSequence getProteinSequenceForStructure(Structure struct, M public static ResidueNumber[] matchSequenceToStructure(ProteinSequence seq, Structure struct) { //1. Create ProteinSequence for struct while remembering to which group each residue corresponds - Map atomIndexPosition = new HashMap(); + Map atomIndexPosition = new HashMap<>(); ProteinSequence structSeq = getProteinSequenceForStructure(struct,atomIndexPosition); @@ -171,15 +171,15 @@ public static ResidueNumber[] matchSequenceToStructure(ProteinSequence seq, Stru //2. Run Smith-Waterman to get the alignment // Identity substitution matrix with +1 for match, -1 for mismatch // TODO - SubstitutionMatrix matrix = - new SimpleSubstitutionMatrix( - AminoAcidCompoundSet.getAminoAcidCompoundSet(), - (short)1, (short)-1 ); - matrix = new SimpleSubstitutionMatrix( - AminoAcidCompoundSet.getAminoAcidCompoundSet(), + SubstitutionMatrix matrix = + new SimpleSubstitutionMatrix<>( + AminoAcidCompoundSet.aminoAcidCompoundSet, + (short) 1, (short) -1); + matrix = new SimpleSubstitutionMatrix<>( + AminoAcidCompoundSet.aminoAcidCompoundSet, new InputStreamReader( SimpleSubstitutionMatrix.class.getResourceAsStream("/matrices/blosum100.txt")), - "blosum100"); + "blosum100"); SequencePair pair = Alignments.getPairwiseAlignment(seq, structSeq, PairwiseSequenceAlignerType.GLOBAL, new SimpleGapPenalty(), matrix); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/cif/CifFileConsumer.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/cif/CifFileConsumer.java index 0a0c0e3fb5..4a58833f38 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/cif/CifFileConsumer.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/cif/CifFileConsumer.java @@ -1,50 +1,6 @@ package org.biojava.nbio.structure.io.cif; -import org.rcsb.cif.model.generated.AtomSite; -import org.rcsb.cif.model.generated.AtomSites; -import org.rcsb.cif.model.generated.AuditAuthor; -import org.rcsb.cif.model.generated.Cell; -import org.rcsb.cif.model.generated.ChemComp; -import org.rcsb.cif.model.generated.ChemCompBond; -import org.rcsb.cif.model.generated.DatabasePDBRemark; -import org.rcsb.cif.model.generated.DatabasePDBRev; -import org.rcsb.cif.model.generated.DatabasePDBRevRecord; -import org.rcsb.cif.model.generated.Entity; -import org.rcsb.cif.model.generated.EntityPoly; -import org.rcsb.cif.model.generated.EntityPolySeq; -import org.rcsb.cif.model.generated.EntitySrcGen; -import org.rcsb.cif.model.generated.EntitySrcNat; -import org.rcsb.cif.model.generated.Exptl; -import org.rcsb.cif.model.generated.PdbxAuditRevisionHistory; -import org.rcsb.cif.model.generated.PdbxChemCompIdentifier; -import org.rcsb.cif.model.generated.PdbxDatabaseStatus; -import org.rcsb.cif.model.generated.PdbxEntityDescriptor; -import org.rcsb.cif.model.generated.PdbxEntitySrcSyn; -import org.rcsb.cif.model.generated.PdbxMolecule; -import org.rcsb.cif.model.generated.PdbxMoleculeFeatures; -import org.rcsb.cif.model.generated.PdbxNonpolyScheme; -import org.rcsb.cif.model.generated.PdbxReferenceEntityLink; -import org.rcsb.cif.model.generated.PdbxReferenceEntityList; -import org.rcsb.cif.model.generated.PdbxReferenceEntityPolyLink; -import org.rcsb.cif.model.generated.PdbxStructAssembly; -import org.rcsb.cif.model.generated.PdbxStructAssemblyGen; -import org.rcsb.cif.model.generated.PdbxStructModResidue; -import org.rcsb.cif.model.generated.PdbxStructOperList; -import org.rcsb.cif.model.generated.Refine; -import org.rcsb.cif.model.generated.Struct; -import org.rcsb.cif.model.generated.StructAsym; -import org.rcsb.cif.model.generated.StructConf; -import org.rcsb.cif.model.generated.StructConn; -import org.rcsb.cif.model.generated.StructConnType; -import org.rcsb.cif.model.generated.StructKeywords; -import org.rcsb.cif.model.generated.StructNcsOper; -import org.rcsb.cif.model.generated.StructRef; -import org.rcsb.cif.model.generated.StructRefSeq; -import org.rcsb.cif.model.generated.StructRefSeqDif; -import org.rcsb.cif.model.generated.StructSheetRange; -import org.rcsb.cif.model.generated.StructSite; -import org.rcsb.cif.model.generated.StructSiteGen; -import org.rcsb.cif.model.generated.Symmetry; +import org.rcsb.cif.model.generated.*; /** * Defines a rather generic interface which allows to populate some data structure with data parsed from a CIF file. diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/cif/CifFileConsumerImpl.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/cif/CifFileConsumerImpl.java index 66e2b6be04..82cc9c076b 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/cif/CifFileConsumerImpl.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/cif/CifFileConsumerImpl.java @@ -1,34 +1,7 @@ package org.biojava.nbio.structure.io.cif; -import org.biojava.nbio.structure.AminoAcid; -import org.biojava.nbio.structure.AminoAcidImpl; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.AtomImpl; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.ChainImpl; -import org.biojava.nbio.structure.DBRef; -import org.biojava.nbio.structure.Element; -import org.biojava.nbio.structure.EntityInfo; -import org.biojava.nbio.structure.EntityType; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.GroupType; -import org.biojava.nbio.structure.HetatomImpl; -import org.biojava.nbio.structure.NucleotideImpl; -import org.biojava.nbio.structure.PDBCrystallographicInfo; -import org.biojava.nbio.structure.PDBHeader; -import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.structure.SeqMisMatch; -import org.biojava.nbio.structure.SeqMisMatchImpl; -import org.biojava.nbio.structure.Site; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureImpl; -import org.biojava.nbio.structure.StructureTools; -import org.biojava.nbio.structure.io.BondMaker; -import org.biojava.nbio.structure.io.ChargeAdder; -import org.biojava.nbio.structure.io.EntityFinder; -import org.biojava.nbio.structure.io.FileParsingParameters; -import org.biojava.nbio.structure.io.SeqRes2AtomAligner; +import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.io.*; import org.biojava.nbio.structure.io.mmcif.ChemCompGroupFactory; import org.biojava.nbio.structure.io.mmcif.model.DatabasePdbrevRecord; import org.biojava.nbio.structure.quaternary.BioAssemblyInfo; @@ -40,51 +13,7 @@ import org.rcsb.cif.model.FloatColumn; import org.rcsb.cif.model.IntColumn; import org.rcsb.cif.model.StrColumn; -import org.rcsb.cif.model.generated.AtomSite; -import org.rcsb.cif.model.generated.AtomSites; -import org.rcsb.cif.model.generated.AuditAuthor; -import org.rcsb.cif.model.generated.Cell; -import org.rcsb.cif.model.generated.ChemComp; -import org.rcsb.cif.model.generated.ChemCompBond; -import org.rcsb.cif.model.generated.DatabasePDBRemark; -import org.rcsb.cif.model.generated.DatabasePDBRev; -import org.rcsb.cif.model.generated.DatabasePDBRevRecord; -import org.rcsb.cif.model.generated.Entity; -import org.rcsb.cif.model.generated.EntityPoly; -import org.rcsb.cif.model.generated.EntityPolySeq; -import org.rcsb.cif.model.generated.EntitySrcGen; -import org.rcsb.cif.model.generated.EntitySrcNat; -import org.rcsb.cif.model.generated.Exptl; -import org.rcsb.cif.model.generated.PdbxAuditRevisionHistory; -import org.rcsb.cif.model.generated.PdbxChemCompIdentifier; -import org.rcsb.cif.model.generated.PdbxDatabaseStatus; -import org.rcsb.cif.model.generated.PdbxEntityDescriptor; -import org.rcsb.cif.model.generated.PdbxEntitySrcSyn; -import org.rcsb.cif.model.generated.PdbxMolecule; -import org.rcsb.cif.model.generated.PdbxMoleculeFeatures; -import org.rcsb.cif.model.generated.PdbxNonpolyScheme; -import org.rcsb.cif.model.generated.PdbxReferenceEntityLink; -import org.rcsb.cif.model.generated.PdbxReferenceEntityList; -import org.rcsb.cif.model.generated.PdbxReferenceEntityPolyLink; -import org.rcsb.cif.model.generated.PdbxStructAssembly; -import org.rcsb.cif.model.generated.PdbxStructAssemblyGen; -import org.rcsb.cif.model.generated.PdbxStructModResidue; -import org.rcsb.cif.model.generated.PdbxStructOperList; -import org.rcsb.cif.model.generated.Refine; -import org.rcsb.cif.model.generated.Struct; -import org.rcsb.cif.model.generated.StructAsym; -import org.rcsb.cif.model.generated.StructConf; -import org.rcsb.cif.model.generated.StructConn; -import org.rcsb.cif.model.generated.StructConnType; -import org.rcsb.cif.model.generated.StructKeywords; -import org.rcsb.cif.model.generated.StructNcsOper; -import org.rcsb.cif.model.generated.StructRef; -import org.rcsb.cif.model.generated.StructRefSeq; -import org.rcsb.cif.model.generated.StructRefSeqDif; -import org.rcsb.cif.model.generated.StructSheetRange; -import org.rcsb.cif.model.generated.StructSite; -import org.rcsb.cif.model.generated.StructSiteGen; -import org.rcsb.cif.model.generated.Symmetry; +import org.rcsb.cif.model.generated.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -144,7 +73,7 @@ class CifFileConsumerImpl implements CifFileConsumer { private Map asymId2authorId; private Matrix4d parsedScaleMatrix; - private FileParsingParameters params; + private final FileParsingParameters params; public CifFileConsumerImpl(FileParsingParameters params) { this.params = params; @@ -517,7 +446,7 @@ public void consumeAuditAuthor(AuditAuthor auditAuthor) { if (auth == null) { pdbHeader.setAuthors(newaa.toString()); } else { - auth += "," + newaa.toString(); + auth += "," + newaa; pdbHeader.setAuthors(auth); } } @@ -1260,14 +1189,15 @@ public void finish() { seqMisMatches.add(seqMisMatch); } - for (String chainId : misMatchMap.keySet()){ + for (Map.Entry> entry : misMatchMap.entrySet()){ + String chainId = entry.getKey(); Chain chain = structure.getPolyChainByPDB(chainId); if (chain == null) { logger.warn("Could not set mismatches for chain with author id {}", chainId); continue; } - chain.setSeqMisMatches(misMatchMap.get(chainId)); + chain.setSeqMisMatches(entry.getValue()); } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/cif/CifFileSupplierImpl.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/cif/CifFileSupplierImpl.java index 9d839de4f2..1f8e069a3e 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/cif/CifFileSupplierImpl.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/cif/CifFileSupplierImpl.java @@ -1,22 +1,11 @@ package org.biojava.nbio.structure.io.cif; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.Element; -import org.biojava.nbio.structure.EntityType; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.GroupType; -import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.xtal.CrystalCell; import org.biojava.nbio.structure.xtal.SpaceGroup; import org.rcsb.cif.model.Category; import org.rcsb.cif.model.CifFile; -import org.rcsb.cif.model.builder.BlockBuilder; -import org.rcsb.cif.model.builder.CategoryBuilder; -import org.rcsb.cif.model.builder.CifBuilder; -import org.rcsb.cif.model.builder.FloatColumnBuilder; -import org.rcsb.cif.model.builder.IntColumnBuilder; -import org.rcsb.cif.model.builder.StrColumnBuilder; +import org.rcsb.cif.model.builder.*; import java.util.ArrayList; import java.util.LinkedHashMap; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/AllChemCompProvider.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/AllChemCompProvider.java index b2b3222d58..6c1301e9f0 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/AllChemCompProvider.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/AllChemCompProvider.java @@ -21,10 +21,10 @@ */ package org.biojava.nbio.structure.io.mmcif; +import org.biojava.nbio.core.util.InputStreamProvider; import org.biojava.nbio.structure.align.util.UserConfiguration; import org.biojava.nbio.structure.io.LocalPDBDirectory; import org.biojava.nbio.structure.io.mmcif.model.ChemComp; -import org.biojava.nbio.core.util.InputStreamProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -57,8 +57,8 @@ public class AllChemCompProvider implements ChemCompProvider, Runnable{ static ChemicalComponentDictionary dict; // flags to make sure there is only one thread running that is loading the dictionary - static AtomicBoolean loading = new AtomicBoolean(false); - static AtomicBoolean isInitialized = new AtomicBoolean(false); + static final AtomicBoolean loading = new AtomicBoolean(false); + static final AtomicBoolean isInitialized = new AtomicBoolean(false); public AllChemCompProvider(){ @@ -132,7 +132,7 @@ public static void downloadFile() throws IOException { } - private static void downloadFileFromRemote(URL remoteURL, File localFile) throws FileNotFoundException, IOException{ + private static void downloadFileFromRemote(URL remoteURL, File localFile) throws IOException{ logger.info("Downloading " + remoteURL + " to: " + localFile); FileOutputStream out = new FileOutputStream(localFile); @@ -168,7 +168,7 @@ private static String getLocalFileName(){ */ private void loadAllChemComps() throws IOException { String fileName = getLocalFileName(); - logger.debug("Loading " + fileName); + logger.debug("Loading {}", fileName); InputStreamProvider isp = new InputStreamProvider(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ChemCompConsumer.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ChemCompConsumer.java index f2d043a5b9..b6cd7bfad4 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ChemCompConsumer.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ChemCompConsumer.java @@ -32,7 +32,7 @@ public class ChemCompConsumer implements MMcifConsumer { private static final Logger logger = LoggerFactory.getLogger(ChemCompConsumer.class); - ChemicalComponentDictionary dictionary; + final ChemicalComponentDictionary dictionary; String latestChemCompId; public ChemCompConsumer(){ diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ChemCompGroupFactory.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ChemCompGroupFactory.java index 87f6408e86..34de9704f8 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ChemCompGroupFactory.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ChemCompGroupFactory.java @@ -23,11 +23,7 @@ package org.biojava.nbio.structure.io.mmcif; import org.biojava.nbio.core.util.SoftHashMap; -import org.biojava.nbio.structure.AminoAcid; -import org.biojava.nbio.structure.AminoAcidImpl; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.HetatomImpl; -import org.biojava.nbio.structure.NucleotideImpl; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.io.mmcif.chem.PolymerType; import org.biojava.nbio.structure.io.mmcif.model.ChemComp; import org.slf4j.Logger; @@ -40,26 +36,18 @@ public class ChemCompGroupFactory { private static ChemCompProvider chemCompProvider = new DownloadChemCompProvider(); - private static SoftHashMap cache = new SoftHashMap(0); + private static final SoftHashMap cache = new SoftHashMap<>(0); public static ChemComp getChemComp(String recordName){ - - recordName = recordName.toUpperCase().trim(); - // we are using the cache, to avoid hitting the file system too often. - ChemComp cc = cache.get(recordName); - if ( cc != null) { - logger.debug("Chem comp "+cc.getThree_letter_code()+" read from cache"); - return cc; - } - - // not cached, get the chem comp from the provider - logger.debug("Chem comp "+recordName+" read from provider "+chemCompProvider.getClass().getCanonicalName()); - cc = chemCompProvider.getChemComp(recordName); - // Note that this also caches null or empty responses - cache.put(recordName, cc); - return cc; + return cache.computeIfAbsent(recordName.toUpperCase().trim(), r -> { + // not cached, get the chem comp from the provider + if (logger.isDebugEnabled()) + logger.debug("Chem comp " + r + " read from provider " + chemCompProvider.getClass().getCanonicalName()); + + return chemCompProvider.getChemComp(r); + }); } /** @@ -98,7 +86,7 @@ public static Group getGroupFromChemCompDictionary(String recordName) { // make sure we work with upper case records recordName = recordName.toUpperCase().trim(); - Group g = null; + Group g; ChemComp cc = getChemComp(recordName); @@ -121,7 +109,8 @@ public static Group getGroupFromChemCompDictionary(String recordName) { if ( one_letter == null || one_letter.length()==0 || one_letter.equals("?")) { // e.g. problem with PRR, which probably should have a parent of ALA, but as of 20110127 does not. - logger.warn("Problem with chemical component: " + recordName + " Did not find one letter code! Setting it to 'X'"); + if (logger.isWarnEnabled()) + logger.warn("Problem with chemical component: " + recordName + " Did not find one letter code! Setting it to 'X'"); aa.setAminoType('X'); } else { @@ -131,9 +120,9 @@ public static Group getGroupFromChemCompDictionary(String recordName) { g = aa; } else if ( PolymerType.POLYNUCLEOTIDE_ONLY.contains(cc.getPolymerType())) { - NucleotideImpl nuc = new NucleotideImpl(); - g = nuc; + + g = new NucleotideImpl(); } else { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ChemicalComponentDictionary.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ChemicalComponentDictionary.java index 19c97f9aed..79ec004df5 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ChemicalComponentDictionary.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ChemicalComponentDictionary.java @@ -36,14 +36,14 @@ */ public class ChemicalComponentDictionary { - private Map dictionary; - private Map replaces; - private Map isreplacedby; + private final Map dictionary; + private final Map replaces; + private final Map isreplacedby; public ChemicalComponentDictionary(){ - dictionary = new HashMap(); - replaces = new HashMap(); - isreplacedby = new HashMap(); + dictionary = new HashMap<>(); + replaces = new HashMap<>(); + isreplacedby = new HashMap<>(); } public boolean isReplaced(ChemComp c){ diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/DownloadChemCompProvider.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/DownloadChemCompProvider.java index 86355e40b6..03864ef7b5 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/DownloadChemCompProvider.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/DownloadChemCompProvider.java @@ -20,33 +20,26 @@ */ package org.biojava.nbio.structure.io.mmcif; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileOutputStream; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.io.StringWriter; +import org.biojava.nbio.core.util.InputStreamProvider; +import org.biojava.nbio.structure.align.util.URLConnectionTools; +import org.biojava.nbio.structure.align.util.UserConfiguration; +import org.biojava.nbio.structure.io.LocalPDBDirectory; +import org.biojava.nbio.structure.io.mmcif.model.ChemComp; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; import java.net.URL; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.zip.GZIPOutputStream; -import org.biojava.nbio.core.util.InputStreamProvider; -import org.biojava.nbio.structure.align.util.URLConnectionTools; -import org.biojava.nbio.structure.align.util.UserConfiguration; -import org.biojava.nbio.structure.io.LocalPDBDirectory; -import org.biojava.nbio.structure.io.mmcif.model.ChemComp; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** @@ -85,14 +78,16 @@ public class DownloadChemCompProvider implements ChemCompProvider { // flags to make sure there is only one thread running that is loading the dictionary - static AtomicBoolean loading = new AtomicBoolean(false); + static final AtomicBoolean loading = new AtomicBoolean(false); - static final List protectedIDs = new ArrayList (); + static final List protectedIDs; static { - protectedIDs.add("CON"); - protectedIDs.add("PRN"); - protectedIDs.add("AUX"); - protectedIDs.add("NUL"); + ArrayList p = new ArrayList<>(4); + p.add("CON"); + p.add("PRN"); + p.add("AUX"); + p.add("NUL"); + protectedIDs = Collections.unmodifiableList(p); } private static ChemCompProvider fallback = null; // Fallback provider if the download fails @@ -151,13 +146,7 @@ public void checkDoFirstInstall(){ } else { // file exists.. did it get extracted? - FilenameFilter filter =new FilenameFilter() { - - @Override - public boolean accept(File dir, String file) { - return file.endsWith(".cif.gz"); - } - }; + FilenameFilter filter = (dir1, file) -> file.endsWith(".cif.gz"); String[] files = dir.list(filter); if ( files.length < 500) { // not all did get unpacked @@ -182,9 +171,9 @@ private void split() throws IOException { int counter = 0; InputStreamProvider prov = new InputStreamProvider(); - try( BufferedReader buf = new BufferedReader (new InputStreamReader (prov.getInputStream(f))); - ) { - String line = null; + try( BufferedReader buf = new BufferedReader (new InputStreamReader (prov.getInputStream(f))) + ) { + String line; line = buf.readLine (); StringWriter writer = new StringWriter(); @@ -404,8 +393,8 @@ private static boolean downloadChemCompRecord(String recordName) { URLConnection uconn = URLConnectionTools.openURLConnection(url); try( PrintWriter pw = new PrintWriter(new GZIPOutputStream(new FileOutputStream(newFile))); - BufferedReader fileBuffer = new BufferedReader(new InputStreamReader(uconn.getInputStream())); - ) { + BufferedReader fileBuffer = new BufferedReader(new InputStreamReader(uconn.getInputStream())) + ) { String line; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/MMCIFFileTools.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/MMCIFFileTools.java index 14fdac7d3e..82c4dde9ce 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/MMCIFFileTools.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/MMCIFFileTools.java @@ -21,28 +21,17 @@ package org.biojava.nbio.structure.io.mmcif; -import java.lang.reflect.Field; -import java.util.*; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.Element; -import org.biojava.nbio.structure.EntityType; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.GroupType; -import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.io.FileConvert; -import org.biojava.nbio.structure.io.mmcif.model.AbstractBean; -import org.biojava.nbio.structure.io.mmcif.model.AtomSite; -import org.biojava.nbio.structure.io.mmcif.model.CIFLabel; -import org.biojava.nbio.structure.io.mmcif.model.Cell; -import org.biojava.nbio.structure.io.mmcif.model.IgnoreField; -import org.biojava.nbio.structure.io.mmcif.model.Symmetry; +import org.biojava.nbio.structure.io.mmcif.model.*; import org.biojava.nbio.structure.xtal.CrystalCell; import org.biojava.nbio.structure.xtal.SpaceGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.lang.reflect.Field; +import java.util.*; + /** * Some tools for mmCIF file writing. * @@ -87,12 +76,12 @@ public class MMCIFFileTools { public static String toLoopMmCifHeaderString(String categoryName, String className) throws ClassNotFoundException { StringBuilder str = new StringBuilder(); - str.append(SimpleMMcifParser.LOOP_START+newline); + str.append(SimpleMMcifParser.LOOP_START).append(newline); Class c = Class.forName(className); for (Field f : getFields(c)) { - str.append(categoryName+"."+f.getName()+newline); + str.append(categoryName).append(".").append(f.getName()).append(newline); } return str.toString(); @@ -148,7 +137,7 @@ public static String toMMCIF(String categoryName, Object o) { } - sb.append(SimpleMMcifParser.COMMENT_CHAR+newline); + sb.append(SimpleMMcifParser.COMMENT_CHAR).append(newline); return sb.toString(); } @@ -220,7 +209,7 @@ public static String toMMCIF(List list, Class klass) { sb.append(toSingleLoopLineMmCifString(o, fields, sizes)); } - sb.append(SimpleMMcifParser.COMMENT_CHAR+newline); + sb.append(SimpleMMcifParser.COMMENT_CHAR).append(newline); return sb.toString(); } @@ -497,7 +486,7 @@ public static List convertChainToAtomSites(Chain c, int model, String * @return */ public static List convertStructureToAtomSites(Structure s) { - List list = new ArrayList(); + List list = new ArrayList<>(); for (int m=0;m loopFields, List lineData); + void newGenericData(String category, List loopFields, List lineData); - public void setFileParsingParameters(FileParsingParameters params); - public FileParsingParameters getFileParsingParameters(); + void setFileParsingParameters(FileParsingParameters params); + FileParsingParameters getFileParsingParameters(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/MMcifParser.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/MMcifParser.java index e20a35d87c..a6c8655ece 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/MMcifParser.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/MMcifParser.java @@ -36,31 +36,31 @@ public interface MMcifParser { * * @param consumer a consumer object. */ - public void addMMcifConsumer(MMcifConsumer consumer); + void addMMcifConsumer(MMcifConsumer consumer); /** Remove all consumers from the parser. * */ - public void clearConsumers(); + void clearConsumers(); /** remove a single consumer from the parser * * @param consumer */ - public void removeMMcifConsumer(MMcifConsumer consumer); + void removeMMcifConsumer(MMcifConsumer consumer); /** Start the actual parsing. The parser will trigger events that are defined by the MMcifConsumer class. * * @param buf a BufferedReader. */ - public void parse(BufferedReader buf) throws IOException; + void parse(BufferedReader buf) throws IOException; /** Start the actual parsing. The parser will trigger events that are defined by the MMcifConsumer class. * * @param inStream InputStream to parse from. */ - public void parse(InputStream inStream) throws IOException; + void parse(InputStream inStream) throws IOException; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/MetalBondConsumer.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/MetalBondConsumer.java index dbb91bd71f..19b6a35ffb 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/MetalBondConsumer.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/MetalBondConsumer.java @@ -35,7 +35,7 @@ public class MetalBondConsumer implements MMcifConsumer{ - Map> definitions = new HashMap<>(); + final Map> definitions = new HashMap<>(); @Override public void documentStart() { @@ -255,14 +255,9 @@ public void newGenericData(String category, List loopFields, List defs = definitions.get(d.getAtomType1()); + List defs = definitions.computeIfAbsent(d.getAtomType1(), k -> new ArrayList<>()); - if ( defs == null){ - defs = new ArrayList<>(); - definitions.put(d.getAtomType1(),defs); - } - - defs.add(d); + defs.add(d); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/MetalBondParser.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/MetalBondParser.java index 03d6789c5c..3fbd0cd2f6 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/MetalBondParser.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/MetalBondParser.java @@ -25,8 +25,8 @@ import org.slf4j.LoggerFactory; import java.io.InputStream; -import java.util.*; - +import java.util.List; +import java.util.Map; import java.util.zip.GZIPInputStream; /** @@ -39,7 +39,7 @@ public class MetalBondParser { private static final String BONDS_FILE = "org/biojava/nbio/structure/bond_distance_limits.cif.gz"; - static Map> definitions; + static final Map> definitions; static { definitions = init(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ReducedChemCompProvider.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ReducedChemCompProvider.java index 0d752cea04..cef70f04cd 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ReducedChemCompProvider.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ReducedChemCompProvider.java @@ -20,16 +20,16 @@ */ package org.biojava.nbio.structure.io.mmcif; +import org.biojava.nbio.structure.io.mmcif.model.ChemComp; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.zip.GZIPInputStream; -import org.biojava.nbio.structure.io.mmcif.model.ChemComp; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** Unlike the {@link DownloadChemCompProvider}, this {@link ChemCompProvider} does not download any chem comp definitions. * It has access to a limited set of files that are part of the biojava distribution. diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/SimpleMMcifConsumer.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/SimpleMMcifConsumer.java index b0cdecdc14..4461ab4b01 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/SimpleMMcifConsumer.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/SimpleMMcifConsumer.java @@ -21,87 +21,9 @@ */ package org.biojava.nbio.structure.io.mmcif; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.vecmath.Matrix4d; - -import org.biojava.nbio.structure.AminoAcid; -import org.biojava.nbio.structure.AminoAcidImpl; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.AtomImpl; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.ChainImpl; -import org.biojava.nbio.structure.EntityInfo; -import org.biojava.nbio.structure.EntityType; -import org.biojava.nbio.structure.DBRef; -import org.biojava.nbio.structure.Element; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.GroupType; -import org.biojava.nbio.structure.HetatomImpl; -import org.biojava.nbio.structure.NucleotideImpl; -import org.biojava.nbio.structure.PDBCrystallographicInfo; -import org.biojava.nbio.structure.PDBHeader; -import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.structure.SeqMisMatch; -import org.biojava.nbio.structure.SeqMisMatchImpl; -import org.biojava.nbio.structure.Site; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureImpl; -import org.biojava.nbio.structure.StructureTools; -import org.biojava.nbio.structure.io.BondMaker; -import org.biojava.nbio.structure.io.ChargeAdder; -import org.biojava.nbio.structure.io.EntityFinder; -import org.biojava.nbio.structure.io.FileParsingParameters; -import org.biojava.nbio.structure.io.SeqRes2AtomAligner; -import org.biojava.nbio.structure.io.mmcif.model.AtomSite; -import org.biojava.nbio.structure.io.mmcif.model.AtomSites; -import org.biojava.nbio.structure.io.mmcif.model.AuditAuthor; -import org.biojava.nbio.structure.io.mmcif.model.Cell; -import org.biojava.nbio.structure.io.mmcif.model.ChemComp; -import org.biojava.nbio.structure.io.mmcif.model.ChemCompAtom; -import org.biojava.nbio.structure.io.mmcif.model.ChemCompBond; -import org.biojava.nbio.structure.io.mmcif.model.ChemCompDescriptor; -import org.biojava.nbio.structure.io.mmcif.model.DatabasePDBremark; -import org.biojava.nbio.structure.io.mmcif.model.DatabasePDBrev; -import org.biojava.nbio.structure.io.mmcif.model.DatabasePdbrevRecord; -import org.biojava.nbio.structure.io.mmcif.model.Entity; -import org.biojava.nbio.structure.io.mmcif.model.EntityPoly; -import org.biojava.nbio.structure.io.mmcif.model.EntityPolySeq; -import org.biojava.nbio.structure.io.mmcif.model.EntitySrcGen; -import org.biojava.nbio.structure.io.mmcif.model.EntitySrcNat; -import org.biojava.nbio.structure.io.mmcif.model.EntitySrcSyn; -import org.biojava.nbio.structure.io.mmcif.model.Exptl; -import org.biojava.nbio.structure.io.mmcif.model.PdbxAuditRevisionHistory; -import org.biojava.nbio.structure.io.mmcif.model.PdbxChemCompDescriptor; -import org.biojava.nbio.structure.io.mmcif.model.PdbxChemCompIdentifier; -import org.biojava.nbio.structure.io.mmcif.model.PdbxDatabaseStatus; -import org.biojava.nbio.structure.io.mmcif.model.PdbxEntityNonPoly; -import org.biojava.nbio.structure.io.mmcif.model.PdbxNonPolyScheme; -import org.biojava.nbio.structure.io.mmcif.model.PdbxPolySeqScheme; -import org.biojava.nbio.structure.io.mmcif.model.PdbxStructAssembly; -import org.biojava.nbio.structure.io.mmcif.model.PdbxStructAssemblyGen; -import org.biojava.nbio.structure.io.mmcif.model.PdbxStructOperList; -import org.biojava.nbio.structure.io.mmcif.model.Refine; -import org.biojava.nbio.structure.io.mmcif.model.Struct; -import org.biojava.nbio.structure.io.mmcif.model.StructAsym; -import org.biojava.nbio.structure.io.mmcif.model.StructConn; -import org.biojava.nbio.structure.io.mmcif.model.StructKeywords; -import org.biojava.nbio.structure.io.mmcif.model.StructNcsOper; -import org.biojava.nbio.structure.io.mmcif.model.StructRef; -import org.biojava.nbio.structure.io.mmcif.model.StructRefSeq; -import org.biojava.nbio.structure.io.mmcif.model.StructRefSeqDif; -import org.biojava.nbio.structure.io.mmcif.model.StructSite; -import org.biojava.nbio.structure.io.mmcif.model.StructSiteGen; -import org.biojava.nbio.structure.io.mmcif.model.Symmetry; +import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.io.*; +import org.biojava.nbio.structure.io.mmcif.model.*; import org.biojava.nbio.structure.quaternary.BioAssemblyInfo; import org.biojava.nbio.structure.quaternary.BiologicalAssemblyBuilder; import org.biojava.nbio.structure.quaternary.BiologicalAssemblyTransformation; @@ -111,6 +33,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.vecmath.Matrix4d; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; + /** * A MMcifConsumer implementation that builds an in-memory representation of the * content of a mmcif file as a BioJava Structure object. @@ -352,7 +279,7 @@ public void newAtomSite(AtomSite atom) { boolean isHetAtomInFile = false; - Character aminoCode1 = null; + Character aminoCode1; if ( recordName.equals("ATOM") ) aminoCode1 = StructureTools.get1LetterCodeAmino(groupCode3); else { @@ -399,7 +326,7 @@ public void newAtomSite(AtomSite atom) { // we came to the beginning of a new NMR model allModels.add(currentModel); - currentModel = new ArrayList(); + currentModel = new ArrayList<>(); currentChain = null; currentGroup = null; } @@ -569,9 +496,9 @@ private Atom convertAtom(AtomSite atom){ String alt = atom.getLabel_alt_id(); if (( alt != null ) && ( alt.length() > 0) && (! alt.equals("."))){ - a.setAltLoc(new Character(alt.charAt(0))); + a.setAltLoc(alt.charAt(0)); } else { - a.setAltLoc(new Character(' ')); + a.setAltLoc(' '); } Element element = Element.R; @@ -630,7 +557,7 @@ private Group getCorrectAltLocGroup( Character altLoc, Group altLocG = (Group) currentGroup.clone(); // drop atoms from cloned group... // https://redmine.open-bio.org/issues/3307 - altLocG.setAtoms(new ArrayList()); + altLocG.setAtoms(new ArrayList<>()); altLocG.getAltLocs().clear(); currentGroup.addAltLoc(altLocG); return altLocG; @@ -658,27 +585,27 @@ public void documentStart() { currentNmrModelNumber = null; //atomCount = 0; - allModels = new ArrayList>(); - currentModel = new ArrayList(); - entities = new ArrayList(); + allModels = new ArrayList<>(); + currentModel = new ArrayList<>(); + entities = new ArrayList<>(); entityPolys = new ArrayList<>(); - strucRefs = new ArrayList(); - seqResChains = new ArrayList(); - entityChains = new ArrayList(); - structAsyms = new ArrayList(); + strucRefs = new ArrayList<>(); + seqResChains = new ArrayList<>(); + entityChains = new ArrayList<>(); + structAsyms = new ArrayList<>(); - asymId2entityId = new HashMap(); + asymId2entityId = new HashMap<>(); asymId2authorId = new HashMap<>(); - structOpers = new ArrayList(); - strucAssemblies = new ArrayList(); - strucAssemblyGens = new ArrayList(); - entitySrcGens = new ArrayList(); - entitySrcNats = new ArrayList(); - entitySrcSyns = new ArrayList(); - structConn = new ArrayList(); - structNcsOper = new ArrayList(); - sequenceDifs = new ArrayList(); - structSiteGens = new ArrayList(); + structOpers = new ArrayList<>(); + strucAssemblies = new ArrayList<>(); + strucAssemblyGens = new ArrayList<>(); + entitySrcGens = new ArrayList<>(); + entitySrcNats = new ArrayList<>(); + entitySrcSyns = new ArrayList<>(); + structConn = new ArrayList<>(); + structNcsOper = new ArrayList<>(); + sequenceDifs = new ArrayList<>(); + structSiteGens = new ArrayList<>(); } @@ -791,11 +718,11 @@ public void documentEnd() { // the more detailed mapping of chains to rotation operations happens in StructureIO... - Map bioAssemblies = new LinkedHashMap(); + Map bioAssemblies = new LinkedHashMap<>(); for ( PdbxStructAssembly psa : strucAssemblies){ - List psags = new ArrayList(1); + List psags = new ArrayList<>(1); for ( PdbxStructAssemblyGen psag: strucAssemblyGens ) { if ( psag.getAssembly_id().equals(psa.getId())) { @@ -853,7 +780,7 @@ public void documentEnd() { setCrystallographicInfoMetadata(); - Map> misMatchMap = new HashMap>(); + Map> misMatchMap = new HashMap<>(); for (StructRefSeqDif sdif : sequenceDifs) { SeqMisMatch misMatch = new SeqMisMatchImpl(); misMatch.setDetails(sdif.getDetails()); @@ -869,16 +796,13 @@ public void documentEnd() { misMatch.setSeqNum(sdif.getSeq_num()); - List mms = misMatchMap.get(sdif.getPdbx_pdb_strand_id()); - if ( mms == null) { - mms = new ArrayList(); - misMatchMap.put(sdif.getPdbx_pdb_strand_id(),mms); - } + List mms = misMatchMap.computeIfAbsent(sdif.getPdbx_pdb_strand_id(), k -> new ArrayList<>()); mms.add(misMatch); } - for (String chainId : misMatchMap.keySet()){ + for (Map.Entry> entry : misMatchMap.entrySet()){ + String chainId = entry.getKey(); Chain chain = structure.getPolyChainByPDB(chainId); @@ -887,7 +811,7 @@ public void documentEnd() { continue; } - chain.setSeqMisMatches(misMatchMap.get(chainId)); + chain.setSeqMisMatches(entry.getValue()); } @@ -1070,7 +994,7 @@ private void alignSeqRes() { //map the atoms to the seqres... // we need to first clone the seqres so that they stay independent for different models - List seqResGroups = new ArrayList(); + List seqResGroups = new ArrayList<>(); for (int i=0;i ncsOperators = new ArrayList(); + ArrayList ncsOperators = new ArrayList<>(); for (StructNcsOper sNcsOper:structNcsOper) { @@ -1322,7 +1246,7 @@ private void setStructNcsOps() { // we only set it if not empty, otherwise remains null if (ncsOperators.size()>0) { structure.getCrystallographicInfo().setNcsOperators( - ncsOperators.toArray(new Matrix4d[ncsOperators.size()])); + ncsOperators.toArray(new Matrix4d[0])); } } @@ -1362,7 +1286,7 @@ public void newDatabasePDBrevRecord(DatabasePdbrevRecord record) { List revRecords = header.getRevisionRecords(); if ( revRecords == null) { - revRecords = new ArrayList(); + revRecords = new ArrayList<>(); header.setRevisionRecords(revRecords); } revRecords.add(record); @@ -1491,7 +1415,7 @@ public void newDatabasePDBremark(DatabasePDBremark remark) { // line contains ANGSTROM info... String resolution = line.substring(i-5,i).trim(); // convert string to float - float res = 99 ; + float res; try { res = Float.parseFloat(resolution); @@ -1573,8 +1497,8 @@ public void newAuditAuthor(AuditAuthor aa){ String name = aa.getName(); - StringBuffer famName = new StringBuffer(); - StringBuffer initials = new StringBuffer(); + StringBuilder famName = new StringBuilder(); + StringBuilder initials = new StringBuilder(); boolean afterComma = false; for ( char c: name.toCharArray()) { if ( c == ' ') @@ -1590,7 +1514,7 @@ public void newAuditAuthor(AuditAuthor aa){ famName.append(c); } - StringBuffer newaa = new StringBuffer(); + StringBuilder newaa = new StringBuilder(); newaa.append(initials); newaa.append(famName); @@ -1599,7 +1523,7 @@ public void newAuditAuthor(AuditAuthor aa){ if (auth == null) { header.setAuthors(newaa.toString()); }else { - auth += "," + newaa.toString(); + auth += "," + newaa; header.setAuthors(auth); } @@ -1757,14 +1681,14 @@ public void newStructRefSeq(StructRefSeq sref) { return; } - Character begin_ins_code = ' '; + char begin_ins_code = ' '; if (sref.getPdbx_seq_align_beg_ins_code() != null ) { - begin_ins_code = new Character(sref.getPdbx_seq_align_beg_ins_code().charAt(0)); + begin_ins_code = sref.getPdbx_seq_align_beg_ins_code().charAt(0); } - Character end_ins_code = ' '; + char end_ins_code = ' '; if (sref.getPdbx_seq_align_end_ins_code() != null) { - end_ins_code = new Character(sref.getPdbx_seq_align_end_ins_code().charAt(0)); + end_ins_code = sref.getPdbx_seq_align_end_ins_code().charAt(0); } if (begin_ins_code == '?') @@ -1782,14 +1706,14 @@ public void newStructRefSeq(StructRefSeq sref) { int dbseqbegin = Integer.parseInt(sref.getDb_align_beg()); int dbseqend = Integer.parseInt(sref.getDb_align_end()); - Character db_begin_in_code = ' '; + char db_begin_in_code = ' '; if (sref.getPdbx_db_align_beg_ins_code() != null) { - db_begin_in_code = new Character(sref.getPdbx_db_align_beg_ins_code().charAt(0)); + db_begin_in_code = sref.getPdbx_db_align_beg_ins_code().charAt(0); } - Character db_end_in_code = ' '; + char db_end_in_code = ' '; if (sref.getPdbx_db_align_end_ins_code() != null) { - db_end_in_code = new Character(sref.getPdbx_db_align_end_ins_code().charAt(0)); + db_end_in_code = sref.getPdbx_db_align_end_ins_code().charAt(0); } if (db_begin_in_code == '?') @@ -1807,7 +1731,7 @@ public void newStructRefSeq(StructRefSeq sref) { List dbrefs = structure.getDBRefs(); if ( dbrefs == null) - dbrefs = new ArrayList(); + dbrefs = new ArrayList<>(); dbrefs.add(r); logger.debug(r.toPDB()); @@ -2072,7 +1996,7 @@ public void newStructSite(StructSite structSite) { // Simply implement the method. List sites = structure.getSites(); - if (sites == null) sites = new ArrayList(); + if (sites == null) sites = new ArrayList<>(); Site site = null; for (Site asite : sites) { @@ -2096,7 +2020,7 @@ public void newStructSite(StructSite structSite) { */ private void addSites() { List sites = structure.getSites(); - if (sites == null) sites = new ArrayList(); + if (sites == null) sites = new ArrayList<>(); for (StructSiteGen siteGen : structSiteGens) { // For each StructSiteGen, find the residues involved, if they exist then @@ -2150,7 +2074,7 @@ private void addSites() { } List groups = site.getGroups(); - if (groups == null) groups = new ArrayList(); + if (groups == null) groups = new ArrayList<>(); // Check the self-consistency of the residue reference from auth_seq_id and chain_id if (!comp_id.equals(g.getPDBName())) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/SimpleMMcifParser.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/SimpleMMcifParser.java index 7e9b23d3c2..2cb7ae6258 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/SimpleMMcifParser.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/SimpleMMcifParser.java @@ -21,6 +21,13 @@ */ package org.biojava.nbio.structure.io.mmcif; +import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.io.MMCIFFileReader; +import org.biojava.nbio.structure.io.StructureIOFile; +import org.biojava.nbio.structure.io.mmcif.model.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -28,61 +35,7 @@ import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - - -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.io.MMCIFFileReader; -import org.biojava.nbio.structure.io.StructureIOFile; -import org.biojava.nbio.structure.io.mmcif.model.AtomSite; -import org.biojava.nbio.structure.io.mmcif.model.AtomSites; -import org.biojava.nbio.structure.io.mmcif.model.AuditAuthor; -import org.biojava.nbio.structure.io.mmcif.model.CIFLabel; -import org.biojava.nbio.structure.io.mmcif.model.Cell; -import org.biojava.nbio.structure.io.mmcif.model.ChemComp; -import org.biojava.nbio.structure.io.mmcif.model.ChemCompAtom; -import org.biojava.nbio.structure.io.mmcif.model.ChemCompBond; -import org.biojava.nbio.structure.io.mmcif.model.ChemCompDescriptor; -import org.biojava.nbio.structure.io.mmcif.model.DatabasePDBremark; -import org.biojava.nbio.structure.io.mmcif.model.DatabasePDBrev; -import org.biojava.nbio.structure.io.mmcif.model.DatabasePdbrevRecord; -import org.biojava.nbio.structure.io.mmcif.model.Entity; -import org.biojava.nbio.structure.io.mmcif.model.EntityPoly; -import org.biojava.nbio.structure.io.mmcif.model.EntityPolySeq; -import org.biojava.nbio.structure.io.mmcif.model.EntitySrcGen; -import org.biojava.nbio.structure.io.mmcif.model.EntitySrcNat; -import org.biojava.nbio.structure.io.mmcif.model.EntitySrcSyn; -import org.biojava.nbio.structure.io.mmcif.model.Exptl; -import org.biojava.nbio.structure.io.mmcif.model.IgnoreField; -import org.biojava.nbio.structure.io.mmcif.model.PdbxAuditRevisionHistory; -import org.biojava.nbio.structure.io.mmcif.model.PdbxChemCompDescriptor; -import org.biojava.nbio.structure.io.mmcif.model.PdbxChemCompIdentifier; -import org.biojava.nbio.structure.io.mmcif.model.PdbxDatabaseStatus; -import org.biojava.nbio.structure.io.mmcif.model.PdbxEntityNonPoly; -import org.biojava.nbio.structure.io.mmcif.model.PdbxNonPolyScheme; -import org.biojava.nbio.structure.io.mmcif.model.PdbxPolySeqScheme; -import org.biojava.nbio.structure.io.mmcif.model.PdbxStructAssembly; -import org.biojava.nbio.structure.io.mmcif.model.PdbxStructAssemblyGen; -import org.biojava.nbio.structure.io.mmcif.model.PdbxStructOperList; -import org.biojava.nbio.structure.io.mmcif.model.Refine; -import org.biojava.nbio.structure.io.mmcif.model.Struct; -import org.biojava.nbio.structure.io.mmcif.model.StructAsym; -import org.biojava.nbio.structure.io.mmcif.model.StructConn; -import org.biojava.nbio.structure.io.mmcif.model.StructKeywords; -import org.biojava.nbio.structure.io.mmcif.model.StructNcsOper; -import org.biojava.nbio.structure.io.mmcif.model.StructRef; -import org.biojava.nbio.structure.io.mmcif.model.StructRefSeq; -import org.biojava.nbio.structure.io.mmcif.model.StructRefSeqDif; -import org.biojava.nbio.structure.io.mmcif.model.StructSite; -import org.biojava.nbio.structure.io.mmcif.model.StructSiteGen; -import org.biojava.nbio.structure.io.mmcif.model.Symmetry; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.util.*; /** * A simple mmCif file parser @@ -138,14 +91,14 @@ public class SimpleMMcifParser implements MMcifParser { public static final String STRING_LIMIT = ";"; - private List consumers ; + private final List consumers ; private Struct struct ; private static final Logger logger = LoggerFactory.getLogger(SimpleMMcifParser.class); public SimpleMMcifParser(){ - consumers = new ArrayList(); + consumers = new ArrayList<>(); struct = null; } @@ -200,15 +153,15 @@ public void parse(BufferedReader buf) // init container objects... struct = new Struct(); - String line = null; + String line; boolean inLoop = false; boolean inLoopData = false; - List loopFields = new ArrayList(); - List lineData = new ArrayList(); - Set loopWarnings = new HashSet(); // used only to reduce logging statements + List loopFields = new ArrayList<>(); + List lineData = new ArrayList<>(); + Set loopWarnings = new HashSet<>(); // used only to reduce logging statements String category = null; @@ -272,7 +225,7 @@ public void parse(BufferedReader buf) continue; } String key = data.get(0); - int pos = key.indexOf("."); + int pos = key.indexOf('.'); if ( pos < 0 ) { // looks like a chem_comp file // line should start with data, otherwise something is wrong! @@ -288,7 +241,7 @@ public void parse(BufferedReader buf) } category = key.substring(0,pos); String value = data.get(1); - loopFields.add(key.substring(pos+1,key.length())); + loopFields.add(key.substring(pos+1)); lineData.add(value); logger.debug("Found data for category {}: {}", key, value); @@ -358,7 +311,7 @@ public void parse(BufferedReader buf) continue; } String key = data.get(0); - int pos = key.indexOf("."); + int pos = key.indexOf('.'); if ( pos < 0 ) { // looks like a chem_comp file // line should start with data, otherwise something is wrong! @@ -382,7 +335,7 @@ public void parse(BufferedReader buf) category = key.substring(0,pos); String value = data.get(1); - loopFields.add(key.substring(pos+1,key.length())); + loopFields.add(key.substring(pos+1)); lineData.add(value); logger.debug("Found data for category {}: {}", key, value); @@ -405,15 +358,15 @@ public void parse(BufferedReader buf) } - private void resetBuffers(List loopFields, List lineData, Set loopWarnings) { + private static void resetBuffers(List loopFields, List lineData, Set loopWarnings) { loopFields.clear(); lineData.clear(); loopWarnings.clear(); } - private List processSingleLine(String line){ + private static List processSingleLine(String line){ - List data = new ArrayList(); + List data = new ArrayList<>(); if ( line.trim().length() == 0){ return data; @@ -426,11 +379,11 @@ private List processSingleLine(String line){ boolean inString = false; // semicolon (;) quoting boolean inS1 = false; // single quote (') quoting boolean inS2 = false; // double quote (") quoting - String word = ""; + StringBuilder word = new StringBuilder(); for (int i=0; i< line.length(); i++ ){ - Character c = line.charAt(i); + char c = line.charAt(i); Character nextC = null; if (i < line.length() - 1) @@ -443,12 +396,12 @@ private List processSingleLine(String line){ if (c == ' ') { if ( ! inString){ - if ( ! word.equals("")) - data.add(word.trim()); - word = ""; + if (word.length() > 0) + data.add(word.toString().trim()); + word = new StringBuilder(); } else { // we are in a string, add the space - word += c; + word.append(c); } } else if (c == S1 ) { @@ -467,13 +420,13 @@ private List processSingleLine(String line){ if ( wordEnd ) { // at end of string - if ( ! word.equals("")) - data.add(word.trim()); - word = ""; + if (word.length() > 0) + data.add(word.toString().trim()); + word = new StringBuilder(); inString = false; inS1 = false; } else { - word += c; + word.append(c); } } else if (prevC==null || prevC==' ') { @@ -481,7 +434,7 @@ private List processSingleLine(String line){ inString = true; inS1 = true; } else { - word += c; + word.append(c); } } else if ( c == S2 ){ if ( inString){ @@ -497,28 +450,28 @@ private List processSingleLine(String line){ if ( wordEnd ) { // at end of string - if ( ! word.equals("")) - data.add(word.trim()); - word = ""; + if (word.length() > 0) + data.add(word.toString().trim()); + word = new StringBuilder(); inString = false; inS2 = false; } else { - word += c; + word.append(c); } } else if (prevC==null || prevC==' ') { // the beginning of a new string inString = true; inS2 = true; } else { - word += c; + word.append(c); } } else { - word += c; + word.append(c); } } - if ( ! word.trim().equals("")) - data.add(word); + if (!word.toString().trim().isEmpty()) + data.add(word.toString()); return data; @@ -532,14 +485,14 @@ private List processSingleLine(String line){ * @param buf * @return */ - private List processLine(String line, - BufferedReader buf, - int fieldLength) + private static List processLine(String line, + BufferedReader buf, + int fieldLength) throws IOException{ //System.out.println("XX processLine " + fieldLength + " " + line); // go through the line and process each character - List lineData = new ArrayList(); + List lineData = new ArrayList<>(); boolean inString = false; @@ -554,7 +507,7 @@ private List processLine(String line, if ( line.length() > 1) bigWord = new StringBuilder(line.substring(1)); else - bigWord = new StringBuilder(""); + bigWord = new StringBuilder(); } else { @@ -571,9 +524,7 @@ private List processLine(String line, List dat = processSingleLine(line); - for (String d : dat){ - lineData.add(d); - } + lineData.addAll(dat); } } @@ -616,258 +567,270 @@ private void endLineChecks(String category,List loopFields, List lineData ); } - if ( category.equals("_entity")){ + switch (category) { + case "_entity": + + triggerNewEntity(buildObject( + Entity.class, + loopFields, lineData, loopWarnings)); + + break; + case "_entity_poly": + triggerNewEntityPoly(buildObject(EntityPoly.class, loopFields, lineData, loopWarnings)); - Entity e = (Entity) buildObject( - Entity.class.getName(), - loopFields,lineData, loopWarnings); - triggerNewEntity(e); + break; + case "_struct": - } else if (category.equals("_entity_poly")) { - EntityPoly ep = (EntityPoly) buildObject(EntityPoly.class.getName(), loopFields, lineData, loopWarnings); - triggerNewEntityPoly(ep); + struct = buildObject(Struct.class, loopFields, lineData, loopWarnings); - } else if ( category.equals("_struct")){ + break; + case "_atom_site": - struct = (Struct) buildObject( - Struct.class.getName(), - loopFields, lineData, loopWarnings); + triggerNewAtomSite(buildObject( + AtomSite.class, + loopFields, lineData, loopWarnings)); - } else if ( category.equals("_atom_site")){ + break; + case "_database_PDB_rev": { - AtomSite a = (AtomSite) buildObject( - AtomSite.class.getName(), - loopFields, lineData, loopWarnings); - triggerNewAtomSite(a); + triggerNewDatabasePDBrev(buildObject( + DatabasePDBrev.class, + loopFields, lineData, loopWarnings)); - } else if ( category.equals("_database_PDB_rev")){ - DatabasePDBrev dbrev = (DatabasePDBrev) buildObject( - DatabasePDBrev.class.getName(), - loopFields, lineData, loopWarnings); + break; + } + case "_database_PDB_rev_record": { - triggerNewDatabasePDBrev(dbrev); - - } else if ( category.equals("_database_PDB_rev_record")){ - DatabasePdbrevRecord dbrev = (DatabasePdbrevRecord) buildObject( - DatabasePdbrevRecord.class.getName(), - loopFields, lineData, loopWarnings); - - triggerNewDatabasePDBrevRecord(dbrev); - - // MMCIF version 5 dates - } else if ( category.equals("_pdbx_audit_revision_history")) { - PdbxAuditRevisionHistory history = (PdbxAuditRevisionHistory) buildObject( - PdbxAuditRevisionHistory.class.getName(), - loopFields, lineData, loopWarnings); - - triggerNewPdbxAuditRevisionHistory(history); - - // MMCIF version 5 dates - } else if ( category.equals("_pdbx_database_status")) { - PdbxDatabaseStatus status = (PdbxDatabaseStatus) buildObject( - PdbxDatabaseStatus.class.getName(), - loopFields, lineData, loopWarnings); - - triggerNewPdbxDatabaseStatus(status); - - }else if ( category.equals("_database_PDB_remark")){ - DatabasePDBremark remark = (DatabasePDBremark) buildObject( - DatabasePDBremark.class.getName(), - loopFields, lineData, loopWarnings); - - triggerNewDatabasePDBremark(remark); - - } else if ( category.equals("_exptl")){ - Exptl exptl = (Exptl) buildObject( - Exptl.class.getName(), - loopFields,lineData, loopWarnings); - - triggerExptl(exptl); - - } else if ( category.equals("_cell")){ - Cell cell = (Cell) buildObject( - Cell.class.getName(), - loopFields,lineData, loopWarnings); - - triggerNewCell(cell); - - } else if ( category.equals("_symmetry")){ - Symmetry symmetry = (Symmetry) buildObject( - Symmetry.class.getName(), - loopFields,lineData, loopWarnings); - - triggerNewSymmetry(symmetry); - } else if ( category.equals("_struct_ncs_oper")) { - - StructNcsOper sNcsOper = (StructNcsOper) buildObject( - StructNcsOper.class.getName(), - loopFields, lineData, loopWarnings); - triggerNewStructNcsOper(sNcsOper); - } else if ( category.equals("_atom_sites")) { - - AtomSites atomSites = (AtomSites) buildObject( - AtomSites.class.getName(), - loopFields, lineData, loopWarnings); - triggerNewAtomSites(atomSites); - - } else if ( category.equals("_struct_ref")){ - StructRef sref = (StructRef) buildObject( - StructRef.class.getName(), - loopFields,lineData, loopWarnings); - - triggerNewStrucRef(sref); - - } else if ( category.equals("_struct_ref_seq")){ - StructRefSeq sref = (StructRefSeq) buildObject( - StructRefSeq.class.getName(), - loopFields,lineData, loopWarnings); - - triggerNewStrucRefSeq(sref); - } else if ( category.equals("_struct_ref_seq_dif")) { - StructRefSeqDif sref = (StructRefSeqDif) buildObject( - StructRefSeqDif.class.getName(), - loopFields, lineData, loopWarnings); - - triggerNewStrucRefSeqDif(sref); - } else if ( category.equals("_struct_site_gen")) { - StructSiteGen sref = (StructSiteGen) buildObject( - StructSiteGen.class.getName(), - loopFields, lineData, loopWarnings); - - triggerNewStructSiteGen(sref); - } else if ( category.equals("_struct_site")) { - StructSite sref = (StructSite) buildObject( - StructSite.class.getName(), - loopFields, lineData, loopWarnings); - triggerNewStructSite(sref); - } else if ( category.equals("_entity_poly_seq")){ - EntityPolySeq exptl = (EntityPolySeq) buildObject( - EntityPolySeq.class.getName(), - loopFields,lineData, loopWarnings); - - triggerNewEntityPolySeq(exptl); - } else if ( category.equals("_entity_src_gen")){ - EntitySrcGen entitySrcGen = (EntitySrcGen) buildObject( - EntitySrcGen.class.getName(), - loopFields,lineData, loopWarnings); - triggerNewEntitySrcGen(entitySrcGen); - } else if ( category.equals("_entity_src_nat")){ - EntitySrcNat entitySrcNat = (EntitySrcNat) buildObject( - EntitySrcNat.class.getName(), - loopFields,lineData, loopWarnings); - triggerNewEntitySrcNat(entitySrcNat); - } else if ( category.equals("_pdbx_entity_src_syn")){ - EntitySrcSyn entitySrcSyn = (EntitySrcSyn) buildObject( - EntitySrcSyn.class.getName(), - loopFields,lineData, loopWarnings); - triggerNewEntitySrcSyn(entitySrcSyn); - } else if ( category.equals("_struct_asym")){ - StructAsym sasym = (StructAsym) buildObject( - StructAsym.class.getName(), - loopFields,lineData, loopWarnings); - - triggerNewStructAsym(sasym); - - } else if ( category.equals("_pdbx_poly_seq_scheme")){ - PdbxPolySeqScheme ppss = (PdbxPolySeqScheme) buildObject( - PdbxPolySeqScheme.class.getName(), - loopFields,lineData, loopWarnings); - - triggerNewPdbxPolySeqScheme(ppss); - - } else if ( category.equals("_pdbx_nonpoly_scheme")){ - PdbxNonPolyScheme ppss = (PdbxNonPolyScheme) buildObject( - PdbxNonPolyScheme.class.getName(), - loopFields,lineData, loopWarnings); - - triggerNewPdbxNonPolyScheme(ppss); - - } else if ( category.equals("_pdbx_entity_nonpoly")){ - PdbxEntityNonPoly pen = (PdbxEntityNonPoly) buildObject( - PdbxEntityNonPoly.class.getName(), - loopFields,lineData, loopWarnings - ); - triggerNewPdbxEntityNonPoly(pen); - } else if ( category.equals("_struct_keywords")){ - StructKeywords kw = (StructKeywords)buildObject( - StructKeywords.class.getName(), - loopFields,lineData, loopWarnings - ); - triggerNewStructKeywords(kw); - } else if (category.equals("_refine")){ - Refine r = (Refine)buildObject( - Refine.class.getName(), - loopFields,lineData, loopWarnings - ); - triggerNewRefine(r); - } else if (category.equals("_chem_comp")){ - ChemComp c = (ChemComp)buildObject( - ChemComp.class.getName(), - loopFields, lineData, loopWarnings - ); - triggerNewChemComp(c); - } else if (category.equals("_audit_author")) { - AuditAuthor aa = (AuditAuthor)buildObject( - AuditAuthor.class.getName(), - loopFields, lineData, loopWarnings); - triggerNewAuditAuthor(aa); - } else if (category.equals("_pdbx_chem_comp_descriptor")) { - ChemCompDescriptor ccd = (ChemCompDescriptor) buildObject( - ChemCompDescriptor.class.getName(), - loopFields, lineData, loopWarnings); - triggerNewChemCompDescriptor(ccd); - } else if (category.equals("_pdbx_struct_oper_list")) { - - PdbxStructOperList structOper = (PdbxStructOperList) buildObject( - PdbxStructOperList.class.getName(), - loopFields, lineData, loopWarnings - ); - triggerNewPdbxStructOper(structOper); - - } else if (category.equals("_pdbx_struct_assembly")) { - PdbxStructAssembly sa = (PdbxStructAssembly) buildObject( - PdbxStructAssembly.class.getName(), - loopFields, lineData, loopWarnings); - triggerNewPdbxStructAssembly(sa); - - } else if (category.equals("_pdbx_struct_assembly_gen")) { - PdbxStructAssemblyGen sa = (PdbxStructAssemblyGen) buildObject( - PdbxStructAssemblyGen.class.getName(), - loopFields, lineData, loopWarnings); - triggerNewPdbxStructAssemblyGen(sa); - } else if ( category.equals("_chem_comp_atom")){ - ChemCompAtom atom = (ChemCompAtom)buildObject( - ChemCompAtom.class.getName(), - loopFields,lineData, loopWarnings); - triggerNewChemCompAtom(atom); - - }else if ( category.equals("_chem_comp_bond")){ - ChemCompBond bond = (ChemCompBond)buildObject( - ChemCompBond.class.getName(), - loopFields,lineData, loopWarnings); - triggerNewChemCompBond(bond); - } else if ( category.equals("_pdbx_chem_comp_identifier")){ - PdbxChemCompIdentifier id = (PdbxChemCompIdentifier)buildObject( - PdbxChemCompIdentifier.class.getName(), - loopFields,lineData, loopWarnings); - triggerNewPdbxChemCompIdentifier(id); - } else if ( category.equals("_pdbx_chem_comp_descriptor")){ - PdbxChemCompDescriptor id = (PdbxChemCompDescriptor)buildObject( - PdbxChemCompDescriptor.class.getName(), - loopFields,lineData, loopWarnings); - triggerNewPdbxChemCompDescriptor(id); - } else if ( category.equals("_struct_conn")){ - StructConn id = (StructConn)buildObject( - StructConn.class.getName(), - loopFields,lineData, loopWarnings); - triggerNewStructConn(id); + triggerNewDatabasePDBrevRecord(buildObject( + DatabasePdbrevRecord.class, + loopFields, lineData, loopWarnings)); - } else { + // MMCIF version 5 dates + break; + } + case "_pdbx_audit_revision_history": + + triggerNewPdbxAuditRevisionHistory(buildObject( + PdbxAuditRevisionHistory.class, + loopFields, lineData, loopWarnings)); + + // MMCIF version 5 dates + break; + case "_pdbx_database_status": - logger.debug("Using a generic bean for category {}",category); + triggerNewPdbxDatabaseStatus(buildObject( + PdbxDatabaseStatus.class, + loopFields, lineData, loopWarnings)); - // trigger a generic bean that can deal with all missing data types... - triggerGeneric(category,loopFields,lineData); + break; + case "_database_PDB_remark": + + triggerNewDatabasePDBremark(buildObject( + DatabasePDBremark.class, + loopFields, lineData, loopWarnings)); + + break; + case "_exptl": { + + triggerExptl(buildObject( + Exptl.class, + loopFields, lineData, loopWarnings)); + + break; + } + case "_cell": + + triggerNewCell(buildObject( + Cell.class, + loopFields, lineData, loopWarnings)); + + break; + case "_symmetry": + + triggerNewSymmetry(buildObject( + Symmetry.class, + loopFields, lineData, loopWarnings)); + break; + case "_struct_ncs_oper": + + triggerNewStructNcsOper(buildObject( + StructNcsOper.class, + loopFields, lineData, loopWarnings)); + break; + case "_atom_sites": + + triggerNewAtomSites(buildObject( + AtomSites.class, + loopFields, lineData, loopWarnings)); + + break; + case "_struct_ref": { + + triggerNewStrucRef(buildObject( + StructRef.class, + loopFields, lineData, loopWarnings)); + + break; + } + case "_struct_ref_seq": { + + triggerNewStrucRefSeq(buildObject( + StructRefSeq.class, + loopFields, lineData, loopWarnings)); + break; + } + case "_struct_ref_seq_dif": { + + triggerNewStrucRefSeqDif(buildObject( + StructRefSeqDif.class, + loopFields, lineData, loopWarnings)); + break; + } + case "_struct_site_gen": { + + triggerNewStructSiteGen(buildObject( + StructSiteGen.class, + loopFields, lineData, loopWarnings)); + break; + } + case "_struct_site": { + triggerNewStructSite(buildObject( + StructSite.class, + loopFields, lineData, loopWarnings)); + break; + } + case "_entity_poly_seq": { + + triggerNewEntityPolySeq(buildObject( + EntityPolySeq.class, + loopFields, lineData, loopWarnings)); + break; + } + case "_entity_src_gen": + triggerNewEntitySrcGen(buildObject( + EntitySrcGen.class, + loopFields, lineData, loopWarnings)); + break; + case "_entity_src_nat": + triggerNewEntitySrcNat(buildObject( + EntitySrcNat.class, + loopFields, lineData, loopWarnings)); + break; + case "_pdbx_entity_src_syn": + triggerNewEntitySrcSyn(buildObject( + EntitySrcSyn.class, + loopFields, lineData, loopWarnings)); + break; + case "_struct_asym": + + triggerNewStructAsym(buildObject( + StructAsym.class, + loopFields, lineData, loopWarnings)); + + break; + case "_pdbx_poly_seq_scheme": { + + triggerNewPdbxPolySeqScheme(buildObject( + PdbxPolySeqScheme.class, + loopFields, lineData, loopWarnings)); + + break; + } + case "_pdbx_nonpoly_scheme": { + + triggerNewPdbxNonPolyScheme(buildObject( + PdbxNonPolyScheme.class, + loopFields, lineData, loopWarnings)); + + break; + } + case "_pdbx_entity_nonpoly": + triggerNewPdbxEntityNonPoly(buildObject( + PdbxEntityNonPoly.class, + loopFields, lineData, loopWarnings + )); + break; + case "_struct_keywords": + triggerNewStructKeywords(buildObject( + StructKeywords.class, + loopFields, lineData, loopWarnings + )); + break; + case "_refine": + triggerNewRefine(buildObject( + Refine.class, + loopFields, lineData, loopWarnings + )); + break; + case "_chem_comp": + triggerNewChemComp(buildObject( + ChemComp.class, + loopFields, lineData, loopWarnings + )); + break; + case "_audit_author": + triggerNewAuditAuthor(buildObject( + AuditAuthor.class, + loopFields, lineData, loopWarnings)); + break; + case "_pdbx_chem_comp_descriptor": + triggerNewChemCompDescriptor(buildObject( + ChemCompDescriptor.class, + loopFields, lineData, loopWarnings)); + break; + case "_pdbx_struct_oper_list": + + triggerNewPdbxStructOper(buildObject( + PdbxStructOperList.class, + loopFields, lineData, loopWarnings + )); + + break; + case "_pdbx_struct_assembly": { + triggerNewPdbxStructAssembly(buildObject( + PdbxStructAssembly.class, + loopFields, lineData, loopWarnings)); + + break; + } + case "_pdbx_struct_assembly_gen": { + triggerNewPdbxStructAssemblyGen(buildObject( + PdbxStructAssemblyGen.class, + loopFields, lineData, loopWarnings)); + break; + } + case "_chem_comp_atom": + ChemCompAtom atom = buildObject( + ChemCompAtom.class, + loopFields, lineData, loopWarnings); + triggerNewChemCompAtom(atom); + + break; + case "_chem_comp_bond": + triggerNewChemCompBond(buildObject( + ChemCompBond.class, + loopFields, lineData, loopWarnings)); + break; + case "_pdbx_chem_comp_identifier": { + triggerNewPdbxChemCompIdentifier(buildObject( + PdbxChemCompIdentifier.class, + loopFields, lineData, loopWarnings)); + break; + } + case "_struct_conn": { + triggerNewStructConn(buildObject( + StructConn.class, + loopFields, lineData, loopWarnings)); + + break; + } + default: + + logger.debug("Using a generic bean for category {}", category); + + // trigger a generic bean that can deal with all missing data types... + triggerGeneric(category, loopFields, lineData); + break; } @@ -950,39 +913,49 @@ public void triggerNewAtomSites(AtomSites atomSites) { * @param warnings * @return */ - private Object buildObject(String className, List loopFields, List lineData, Set warnings) { + @Deprecated private Object buildObject(String className, List loopFields, List lineData, Set warnings) { - Object o = null; - Class c = null; + Class c; try { // build up the Entity object from the line data... c = Class.forName(className); - o = c.newInstance(); + } catch (ClassNotFoundException e){ + logger.error( "{} {}", className, e); + return null; + } + + return buildObject(c, loopFields, lineData, warnings); + } + + private static X buildObject(Class c, List loopFields, List lineData, Set warnings) { + + Object o; - } catch (InstantiationException|ClassNotFoundException|IllegalAccessException e){ - logger.error( "Error while constructing {}: {}", className, e.getMessage()); + try { + o = c.newInstance(); + } catch (InstantiationException | IllegalAccessException e) { + logger.error( "{} {}", c, e); return null; } // these methods get the fields but also looking at the IgnoreField and CIFLabel annotations - Field[] fields = MMCIFFileTools.getFields(c); - String[] names = MMCIFFileTools.getFieldNames(fields); // let's build a map of all methods so that we can look up the setter methods later Method[] methods = c.getMethods(); - Map methodMap = new HashMap(); - for (Method m : methods) { + Map methodMap = new HashMap<>(methods.length); + for (Method m : methods) methodMap.put(m.getName(),m); - } + + Field[] fields = MMCIFFileTools.getFields(c); + String[] names = MMCIFFileTools.getFieldNames(fields); // and a map of all the fields so that we can lookup them up later - Map names2fields = new HashMap<>(); - for (int i=0;i names2fields = new HashMap<>(fields.length); + for (int i=0;i loopFields, List loopFields, List[] pType = setter.getParameterTypes(); - - try { if ( pType[0].getName().equals(Integer.class.getName())) { if ( val != null && ! val.equals("?") && !val.equals(".")) { - - Integer intVal = Integer.parseInt(val); - setter.invoke(o, intVal); - + setter.invoke(o, Integer.parseInt(val)); } } else { // default val is a String setter.invoke(o, val); } - } catch (IllegalAccessException|InvocationTargetException e) { - logger.error("Could not invoke setter {} with value {} for class {}", setterMethodName, val, className); + } catch (IllegalAccessException| InvocationTargetException e) { + logger.error("Could not invoke setter {} with value {} for class {}", setterMethodName, val, c); } } - return o; + return (X) o; } - private void produceWarning(String key, String val, Class c, Set warnings) { + private static void produceWarning(String key, String val, Class c, Set warnings) { String warning = "Trying to set field " + key + " in "+ c.getName() +" found in file, but no corresponding field could be found in model class (value:" + val + ")"; String warnkey = key+"-"+c.getName(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ZipChemCompProvider.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ZipChemCompProvider.java index ef7c984946..d9c7c79330 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ZipChemCompProvider.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/ZipChemCompProvider.java @@ -20,30 +20,21 @@ */ package org.biojava.nbio.structure.io.mmcif; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.InputStream; +import org.biojava.nbio.structure.io.mmcif.chem.PolymerType; +import org.biojava.nbio.structure.io.mmcif.chem.ResidueType; +import org.biojava.nbio.structure.io.mmcif.model.ChemComp; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; import java.nio.file.FileSystem; -import java.nio.file.FileSystems; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; +import java.nio.file.*; import java.util.HashSet; import java.util.Set; import java.util.zip.GZIPInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; -import org.biojava.nbio.structure.io.mmcif.chem.PolymerType; -import org.biojava.nbio.structure.io.mmcif.chem.ResidueType; -import org.biojava.nbio.structure.io.mmcif.model.ChemComp; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** This chemical component provider retrieves and caches chemical component definition files from a * zip archive specified in its construction. If the archive does not contain the record, an attempt is * made to download it using DownloadChemCompProvider. The downloaded file is then added to the archive. @@ -67,7 +58,7 @@ public class ZipChemCompProvider implements ChemCompProvider{ private boolean m_removeCif; // Missing IDs from library that cannot be download added here to prevent delays. - private Set unavailable = new HashSet(); + private final Set unavailable = new HashSet<>(); /** * ZipChemCompProvider is a Chemical Component provider that stores chemical components @@ -82,7 +73,7 @@ public ZipChemCompProvider(String chemicalComponentDictionaryFile, String tempDi this.m_zipFile = Paths.get(chemicalComponentDictionaryFile); // Use a default temporary directory if not passed a value. - if (tempDir == null || tempDir.equals("")) { + if (tempDir == null || tempDir.isEmpty()) { this.m_tempDir = Paths.get(System.getProperty("java.io.tmpdir")); } else { this.m_tempDir = Paths.get(tempDir); @@ -104,12 +95,9 @@ private void initializeZip() throws IOException { if (!f.exists()) { s_logger.info("Creating missing zip archive: " + m_zipFile.toString()); FileOutputStream fo = new FileOutputStream(f); - ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(fo)); - try { + try (ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(fo))) { zip.putNextEntry(new ZipEntry("chemcomp/")); zip.closeEntry(); - } finally { - zip.close(); } } } @@ -218,11 +206,7 @@ static private File[] finder( String dirName, final String suffix){ } final File dir = new File(dirName); - return dir.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String filename) - { return filename.endsWith(suffix); } - } ); + return dir.listFiles((dir1, filename) -> filename.endsWith(suffix)); } /** @@ -236,7 +220,7 @@ private synchronized ChemComp getFromZip(String recordName) { final String filename = "chemcomp/" + recordName+".cif.gz"; // try with resources block to read from the filesystem. - try (FileSystem fs = FileSystems.newFileSystem(m_zipFile, null)) { + try (FileSystem fs = FileSystems.newFileSystem(m_zipFile, (ClassLoader)null)) { Path cif = fs.getPath(filename); if (Files.exists(cif)) { @@ -269,7 +253,7 @@ private synchronized ChemComp getFromZip(String recordName) { * @return true if successfully appended these files. */ private synchronized boolean addToZipFileSystem(Path zipFile, File[] files, Path pathWithinArchive) { - boolean ret = false; + boolean ret; /* URIs in Java 7 cannot have spaces, must use Path instead * and so, cannot use the properties map to describe need to create @@ -293,7 +277,7 @@ private synchronized boolean addToZipFileSystem(Path zipFile, File[] files, Path */ // Copy in each file. - try (FileSystem zipfs = FileSystems.newFileSystem(zipFile, null)) { + try (FileSystem zipfs = FileSystems.newFileSystem(zipFile, (ClassLoader)null)) { Files.createDirectories(pathWithinArchive); for (File f : files) { if (!f.isDirectory() && f.exists()) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/chem/ChemCompTools.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/chem/ChemCompTools.java index d1392f5117..d04eeb3ba5 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/chem/ChemCompTools.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/chem/ChemCompTools.java @@ -44,6 +44,7 @@ public class ChemCompTools { /** * Lookup table to convert standard amino acid's one-letter-codes to monomer ids + * TODO use an array since there are only alphabetic keys */ private static final Map AMINO_ACID_LOOKUP_1TO3; @@ -52,17 +53,15 @@ public class ChemCompTools { */ private static final Map DNA_LOOKUP_2TO1; - /** - * Lookup table to convert standard nucleic acid's one-letter-codes to monomer ids - */ - private static final Map DNA_LOOKUP_1TO2; + + /** * Static block that initializes lookup maps and initializes their ResidueInfo instances */ static { - Map foo = new HashMap(); + Map foo = new HashMap<>(); foo.put("ALA", 'A'); foo.put("ASP", 'D'); foo.put("ASN", 'N'); @@ -85,9 +84,9 @@ public class ChemCompTools { foo.put("TRP", 'W'); foo.put("TYR", 'Y'); foo.put("VAL", 'V'); - AMINO_ACID_LOOKUP_3TO1 = Collections.unmodifiableMap((Collections.synchronizedMap(foo))); + AMINO_ACID_LOOKUP_3TO1 = Collections.unmodifiableMap(foo); - Map bar = new HashMap(); + Map bar = new HashMap<>(); bar.put('A', "ALA"); bar.put('D', "ASP"); bar.put('N', "ASN"); @@ -110,29 +109,21 @@ public class ChemCompTools { bar.put('W', "TRP"); bar.put('Y', "TYR"); bar.put('V', "VAL"); - AMINO_ACID_LOOKUP_1TO3 = Collections.unmodifiableMap(Collections.synchronizedMap(bar)); + AMINO_ACID_LOOKUP_1TO3 = Collections.unmodifiableMap(bar); - foo = new HashMap(); + foo = new HashMap<>(); foo.put("DA",'A'); foo.put("DC",'C'); foo.put("DG",'G'); foo.put("DI",'I'); foo.put("DU",'U'); foo.put("DT",'T'); - DNA_LOOKUP_2TO1 = Collections.unmodifiableMap((Collections.synchronizedMap(foo))); + DNA_LOOKUP_2TO1 = Collections.unmodifiableMap(foo); - bar = new HashMap(); - bar.put('A',"DA"); - bar.put('C',"DC"); - bar.put('G',"DG"); - bar.put('I',"DI"); - bar.put('U',"DU"); - bar.put('T',"DT"); - DNA_LOOKUP_1TO2 = Collections.unmodifiableMap(Collections.synchronizedMap(bar)); // initialise standard chemical components - List stdMonIds = new ArrayList(); + List stdMonIds = new ArrayList<>(); stdMonIds.addAll(AMINO_ACID_LOOKUP_3TO1.keySet()); stdMonIds.addAll(DNA_LOOKUP_2TO1.keySet()); @@ -140,24 +131,36 @@ public class ChemCompTools { } - public static Character getAminoOneLetter(String chemCompId){ - return AMINO_ACID_LOOKUP_3TO1.get(chemCompId); + public static char getAminoOneLetter(String chemCompId){ + return AMINO_ACID_LOOKUP_3TO1.getOrDefault(chemCompId, (char)0); } - public static Character getDNAOneLetter(String chemCompId){ - return DNA_LOOKUP_2TO1.get(chemCompId) ; + public static char getDNAOneLetter(String chemCompId){ + return DNA_LOOKUP_2TO1.getOrDefault(chemCompId, (char)0) ; } public static String getAminoThreeLetter(Character c){ return AMINO_ACID_LOOKUP_1TO3.get(c); } - public static String getDNATwoLetter(Character c){ - return DNA_LOOKUP_1TO2.get(c); + /** + * Lookup table to convert standard nucleic acid's one-letter-codes to monomer ids + * TODO use an array since there are only alphabetic keys + */ + public static String getDNATwoLetter(char c){ + switch (c) { + case 'A': return "DA"; + case 'C': return "DC"; + case 'G': return "DG"; + case 'I': return "DI"; + case 'U': return "DU"; + case 'T': return "DT"; + default: return null; + } } - public static final boolean isStandardChemComp(ChemComp cc){ + public static boolean isStandardChemComp(ChemComp cc){ String pid = cc.getMon_nstd_parent_comp_id(); String one = cc.getOne_letter_code(); @@ -168,7 +171,7 @@ public static final boolean isStandardChemComp(ChemComp cc){ if ((pid == null) || (pid.equals("?"))){ // and they have a one letter code - if ( ( one != null) && ( ! one.equals("?") )){ + if ( ( one != null) && ( !one.equals("?") )){ // peptides and dpeptides must not have X if ( (polymerType == PolymerType.peptide) || @@ -180,9 +183,7 @@ public static final boolean isStandardChemComp(ChemComp cc){ return performRNACheck(cc); } if (polymerType == PolymerType.dna) { - return performDNACheck(cc); - } //System.err.println("Non standard chem comp: " + cc); @@ -194,10 +195,7 @@ public static final boolean isStandardChemComp(ChemComp cc){ private static boolean performRNACheck(ChemComp cc) { - if (cc.getId().length() == 1) - return true; - else - return false; + return cc.getId().length() == 1; } @@ -205,25 +203,19 @@ private static boolean performDNACheck(ChemComp cc) { if ( cc.getId().equals(UNKNOWN_NUCLEOTIDE.toString())) return false; - Character c = getDNAOneLetter(cc.getId()); - if ( c==null){ - // we did not find it in the list of standard nucleotides - return false; - } - return true; + char c = getDNAOneLetter(cc.getId()); + // we did not find it in the list of standard nucleotides? + return c != 0; } private static boolean performPeptideCheck(ChemComp cc, String one) { - if (one.equals(UNKNOWN_ONE_LETTER_CODE.toString())) { + if (one.equals(UNKNOWN_ONE_LETTER_CODE.toString())) return false; - } - Character c = getAminoOneLetter(cc.getId()); - if ( c==null){ - // we did not find it in the list of standard aminos - return false; - } - return true; + + char c = getAminoOneLetter(cc.getId()); + // we did not find it in the list of standard aminos? + return c != 0; } @@ -244,16 +236,12 @@ public static Character getOneLetterCode(ChemComp cc, ChemicalComponentDictionar } PolymerType poly = cc.getPolymerType(); if (( poly == PolymerType.peptide) || ( poly == PolymerType.dpeptide)){ - Character c = getAminoOneLetter(parent.getId()); - if ( c == null) - c = UNKNOWN_ONE_LETTER_CODE; - return c; + char c = getAminoOneLetter(parent.getId()); + return c == 0 ? UNKNOWN_ONE_LETTER_CODE : Character.valueOf(c); } if ( poly == PolymerType.dna){ - Character c = getDNAOneLetter(parent.getId()); - if (c == null) - c = UNKNOWN_NUCLEOTIDE; - return c; + char c = getDNAOneLetter(parent.getId()); + return c == 0 ? UNKNOWN_NUCLEOTIDE : Character.valueOf(c); } return cc.getMon_nstd_parent_comp_id().charAt(0); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/chem/PolymerType.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/chem/PolymerType.java index d7b4853cf0..a309ff5cf1 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/chem/PolymerType.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/chem/PolymerType.java @@ -90,7 +90,7 @@ public enum PolymerType implements Serializable */ unknown(null); - static Map lookupTable = new HashMap<>(); + static final Map lookupTable = new HashMap<>(); static { @@ -167,25 +167,25 @@ public static PolymerType polymerTypeFromString(String polymerType) static { Set tmp; - tmp = new HashSet(); + tmp = new HashSet<>(); tmp.add(peptide); PROTEIN_ONLY = Collections.unmodifiableSet(tmp); - tmp = new HashSet(); + tmp = new HashSet<>(); tmp.add(dna); DNA_ONLY = Collections.unmodifiableSet(tmp); - tmp = new HashSet(); + tmp = new HashSet<>(); tmp.add(rna); RNA_ONLY = Collections.unmodifiableSet(tmp); - tmp = new HashSet(); + tmp = new HashSet<>(); tmp.add(dna); tmp.add(rna); tmp.add(dnarna); POLYNUCLEOTIDE_ONLY = Collections.unmodifiableSet(tmp); - ALL_POLYMER_TYPES = Collections.unmodifiableSet(new HashSet(Arrays.asList(values()))); + ALL_POLYMER_TYPES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(values()))); } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/chem/ResidueType.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/chem/ResidueType.java index e1d7e55b25..5680120dd2 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/chem/ResidueType.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/chem/ResidueType.java @@ -75,7 +75,7 @@ public enum ResidueType implements Serializable { otherChemComp(null, "other"); - static Map lookupTable = new HashMap<>(); + static final Map lookupTable = new HashMap<>(); static { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/AbstractBean.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/AbstractBean.java index 7dc7b869f5..f39d31d812 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/AbstractBean.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/AbstractBean.java @@ -41,7 +41,7 @@ public abstract class AbstractBean { @Override @SuppressWarnings({ "unchecked" }) public String toString(){ - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); buf.append(this.getClass().getName()).append(": "); /* disabled for the moment @@ -61,14 +61,14 @@ public String toString(){ Method m = methods[i]; String name = m.getName(); - if ( name.substring(0,3).equals("get")) { + if ( name.startsWith("get")) { - Object o = m.invoke(this, new Object[]{}); + Object o = m.invoke(this); if ( o instanceof String){ - buf.append(name.substring(3, name.length())+": "+ o + " "); + buf.append(name.substring(3)).append(": ").append(o).append(" "); } else if ( o instanceof List){ - buf.append(name.substring(3, name.length())).append(": "); + buf.append(name.substring(3)).append(": "); Listlst = (List)o; for (Object obj : lst){ @@ -86,9 +86,7 @@ else if ( o instanceof List){ } - } catch (InvocationTargetException e){ - logger.error("Exception caught while producing toString",e); - } catch (IllegalAccessException e) { + } catch (InvocationTargetException | IllegalAccessException e){ logger.error("Exception caught while producing toString",e); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/ChemComp.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/ChemComp.java index cb38de1755..292c63df3a 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/ChemComp.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/ChemComp.java @@ -27,6 +27,7 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.List; +import java.util.Objects; /** A definition for a Chemical Component, as maintained by the wwPDB. For access to all definitions, * please download the components.cif.gz file from the wwPDB website. @@ -67,11 +68,11 @@ public class ChemComp implements Serializable, Comparable{ private String mon_nstd_flag; @IgnoreField - private List descriptors = new ArrayList(); + private List descriptors = new ArrayList<>(); @IgnoreField - private List bonds = new ArrayList(); + private List bonds = new ArrayList<>(); @IgnoreField - private List atoms = new ArrayList(); + private List atoms = new ArrayList<>(); // and some derived data for easier processing... @IgnoreField @@ -83,7 +84,7 @@ public class ChemComp implements Serializable, Comparable{ @Override public String toString(){ - StringBuffer buf = new StringBuffer("ChemComp "); + StringBuilder buf = new StringBuilder("ChemComp "); buf.append(id); buf.append(" "); buf.append(one_letter_code); @@ -111,10 +112,7 @@ public String toString(){ public boolean hasParent(){ String pid = mon_nstd_parent_comp_id; - if ((pid != null ) && (! pid.equals("?"))){ - return true; - } - return false; + return (pid != null) && (!pid.equals("?")); } public boolean isStandard(){ @@ -584,12 +582,7 @@ public boolean equals(Object obj) { return false; } else if (!three_letter_code.equals(other.three_letter_code)) return false; - if (type == null) { - if (other.type != null) - return false; - } else if (!type.equals(other.type)) - return false; - return true; + return Objects.equals(type, other.type); } /** diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/ChemCompBond.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/ChemCompBond.java index cd49d3b116..0c502c743d 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/ChemCompBond.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/ChemCompBond.java @@ -24,11 +24,11 @@ */ package org.biojava.nbio.structure.io.mmcif.model; -import java.io.Serializable; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.Serializable; + /* * _chem_comp_bond.comp_id @@ -116,18 +116,19 @@ public void setPdbx_ordinal(String pdbx_ordinal) { * the value is non-numeric or unknown. */ public int getNumericalBondOrder() { - if (value_order.equals("SING")) { - return 1; - } else if (value_order.equals("DOUB")) { - return 2; - } else if (value_order.equals("TRIP")) { - return 3; - } else if (value_order.equals("QUAD")) { - return 4; - } else { - logger.error("Unknown or non-numeric value for value_order: " - + value_order); - return -1; - } + switch (value_order) { + case "SING": + return 1; + case "DOUB": + return 2; + case "TRIP": + return 3; + case "QUAD": + return 4; + default: + logger.error("Unknown or non-numeric value for value_order: " + + value_order); + return -1; + } } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/DatabasePDBrev.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/DatabasePDBrev.java index ef884327e3..d57c98b90d 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/DatabasePDBrev.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/DatabasePDBrev.java @@ -31,7 +31,7 @@ public class DatabasePDBrev { @Override public String toString(){ - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); buf.append("DatabasePDBrev "); buf.append("mod_type :"); buf.append(mod_type); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/Entity.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/Entity.java index cae779dee2..3256a41dcd 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/Entity.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/model/Entity.java @@ -41,7 +41,7 @@ public class Entity { @Override public String toString(){ - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); buf.append("Entity - id:").append(id); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfActions.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfActions.java index 7b9cd4642f..4e9da53e67 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfActions.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfActions.java @@ -20,18 +20,18 @@ */ package org.biojava.nbio.structure.io.mmtf; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.file.Path; - import org.biojava.nbio.structure.Structure; import org.rcsb.mmtf.decoder.GenericDecoder; -import org.rcsb.mmtf.decoder.StructureDataToAdapter; import org.rcsb.mmtf.decoder.ReaderUtils; +import org.rcsb.mmtf.decoder.StructureDataToAdapter; import org.rcsb.mmtf.encoder.AdapterToStructureData; import org.rcsb.mmtf.encoder.WriterUtils; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Path; + /** * A class of functions for reading and writing Biojava structures using MMTF * @author Anthony Bradley diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfStructureReader.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfStructureReader.java index 7c7c24e9ec..39e9f7a240 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfStructureReader.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfStructureReader.java @@ -20,36 +20,7 @@ */ package org.biojava.nbio.structure.io.mmtf; -import java.io.Serializable; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.vecmath.Matrix4d; - -import org.biojava.nbio.structure.AminoAcid; -import org.biojava.nbio.structure.AminoAcidImpl; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.AtomImpl; -import org.biojava.nbio.structure.BondImpl; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.ChainImpl; -import org.biojava.nbio.structure.Element; -import org.biojava.nbio.structure.EntityInfo; -import org.biojava.nbio.structure.EntityType; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.HetatomImpl; -import org.biojava.nbio.structure.NucleotideImpl; -import org.biojava.nbio.structure.PDBCrystallographicInfo; -import org.biojava.nbio.structure.PDBHeader; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureImpl; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.io.mmcif.chem.PolymerType; import org.biojava.nbio.structure.io.mmcif.chem.ResidueType; import org.biojava.nbio.structure.io.mmcif.model.ChemComp; @@ -62,6 +33,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.vecmath.Matrix4d; +import java.io.Serializable; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; + /** * A biojava specific structure inflator for MMTF. @@ -80,7 +57,7 @@ public class MmtfStructureReader implements StructureAdapterInterface, Serializa private static final Logger logger = LoggerFactory.getLogger(MmtfStructureReader.class); /** The structure. */ - private Structure structure; + private final Structure structure; /** The model number. */ private int modelNumber; @@ -99,19 +76,19 @@ public class MmtfStructureReader implements StructureAdapterInterface, Serializa private int atomCounter; /** The list of EntityInformation */ - private List entityInfoList; + private final List entityInfoList; /** All the chains */ - private List chainList; + private final List chainList; /** All the chains as a list of maps */ - private List> chainMap; + private final List> chainMap; private List transformList; private int bioassIndex; - private Map chainSequenceMap; + private final Map chainSequenceMap; /** * Instantiates a new bio java structure decoder. @@ -177,7 +154,7 @@ public void initStructure(int totalNumBonds, int totalNumAtoms, int totalNumGrou public void setModelInfo(int inputModelNumber, int chainCount) { modelNumber = inputModelNumber; - structure.addModel(new ArrayList(chainCount)); + structure.addModel(new ArrayList<>(chainCount)); chainMap.add(new HashMap<>()); } @@ -293,7 +270,7 @@ public void setAtomInfo(String atomName, altGroup = getCorrectAltLocGroup(alternativeLocationId); atom.setAltLoc(alternativeLocationId); } else { - atom.setAltLoc(Character.valueOf(' ')); + atom.setAltLoc(' '); } atom.setX(x); atom.setY(y); @@ -395,7 +372,7 @@ private Group getCorrectAltLocGroup(Character altLoc) { Group altLocG = (Group) group.clone(); // drop atoms from cloned group... // https://redmine.open-bio.org/issues/3307 - altLocG.setAtoms(new ArrayList()); + altLocG.setAtoms(new ArrayList<>()); altLocG.getAltLocs().clear(); group.addAltLoc(altLocG); return altLocG; @@ -458,19 +435,19 @@ public void setBioAssemblyTrans(int bioAssemblyId, int[] inputChainIndices, doub } else{ bioAssInfo = new BioAssemblyInfo(); - bioAssInfo.setTransforms(new ArrayList()); + bioAssInfo.setTransforms(new ArrayList<>()); bioAssemblies.put(bioAssemblyId, bioAssInfo); bioAssInfo.setId(bioAssemblyId); } for(int currChainIndex : inputChainIndices){ BiologicalAssemblyTransformation bioAssTrans = new BiologicalAssemblyTransformation(); - Integer transId = transformList.indexOf(inputTransform)+1; + int transId = transformList.indexOf(inputTransform)+1; if(transId==0){ transformList.add(inputTransform); transId = transformList.indexOf(inputTransform)+1; } - bioAssTrans.setId(transId.toString()); + bioAssTrans.setId(Integer.toString(transId)); // If it actually has an index - if it doesn't it is because the chain has no density. if (currChainIndex!=-1){ bioAssTrans.setChainId(chainList.get(currChainIndex).getId()); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfStructureWriter.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfStructureWriter.java index dbc14ebbe4..272f6b1a9b 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfStructureWriter.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfStructureWriter.java @@ -20,24 +20,16 @@ */ package org.biojava.nbio.structure.io.mmtf; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Bond; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.ChainImpl; -import org.biojava.nbio.structure.EntityInfo; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.PDBCrystallographicInfo; -import org.biojava.nbio.structure.PDBHeader; -import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.io.mmcif.model.ChemComp; import org.biojava.nbio.structure.quaternary.BioAssemblyInfo; import org.rcsb.mmtf.api.StructureAdapterInterface; import org.rcsb.mmtf.dataholders.MmtfStructure; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + /** * Class to take Biojava structure data and covert to the DataApi for encoding. * Must implement all the functions in {@link StructureAdapterInterface}. @@ -48,7 +40,7 @@ */ public class MmtfStructureWriter { - private StructureAdapterInterface mmtfDecoderInterface; + private final StructureAdapterInterface mmtfDecoderInterface; /** * Pass data from Biojava structure to another generic output type. Loops through the data @@ -102,14 +94,14 @@ public MmtfStructureWriter(Structure structure, StructureAdapterInterface dataTr if (chemComp.getOne_letter_code().length()==1){ singleLetterCode = chemComp.getOne_letter_code().charAt(0); } - mmtfDecoderInterface.setGroupInfo(group.getPDBName(), group.getResidueNumber().getSeqNum(), insCode.charValue(), + mmtfDecoderInterface.setGroupInfo(group.getPDBName(), group.getResidueNumber().getSeqNum(), insCode, chemComp.getType().toUpperCase(), atomsInGroup.size(), MmtfUtils.getNumBondsInGroup(atomsInGroup), singleLetterCode, sequenceGroups.indexOf(group), MmtfUtils.getSecStructType(group)); for (Atom atom : atomsInGroup){ char altLoc = MmtfStructure.UNAVAILABLE_CHAR_VALUE; if(atom.getAltLoc()!=null){ - if(atom.getAltLoc().charValue()!=' '){ - altLoc=atom.getAltLoc().charValue(); + if(atom.getAltLoc() !=' '){ + altLoc= atom.getAltLoc(); } } mmtfDecoderInterface.setAtomInfo(atom.getName(), atom.getPDBserial(), altLoc, (float) atom.getX(), @@ -138,9 +130,9 @@ private void addBonds(Atom atom, List atomsInGroup, List allAtoms) { // Now set the bonding information. Atom other = bond.getOther(atom); // If both atoms are in the group - if (atomsInGroup.indexOf(other)!=-1){ - Integer firstBondIndex = atomsInGroup.indexOf(atom); - Integer secondBondIndex = atomsInGroup.indexOf(other); + if (atomsInGroup.contains(other)){ + int firstBondIndex = atomsInGroup.indexOf(atom); + int secondBondIndex = atomsInGroup.indexOf(other); // Don't add the same bond twice if(firstBondIndex>secondBondIndex){ int bondOrder = bond.getBondOrder(); @@ -149,8 +141,8 @@ private void addBonds(Atom atom, List atomsInGroup, List allAtoms) { } // Otherwise it's an inter group bond - so add it here else { - Integer firstBondIndex = allAtoms.indexOf(atom); - Integer secondBondIndex = allAtoms.indexOf(other); + int firstBondIndex = allAtoms.indexOf(atom); + int secondBondIndex = allAtoms.indexOf(other); if(firstBondIndex>secondBondIndex){ // Don't add the same bond twice int bondOrder = bond.getBondOrder(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfSummaryDataBean.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfSummaryDataBean.java index 45b702657c..cbb63345e2 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfSummaryDataBean.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfSummaryDataBean.java @@ -20,12 +20,12 @@ */ package org.biojava.nbio.structure.io.mmtf; -import java.util.List; -import java.util.Map; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Chain; +import java.util.List; +import java.util.Map; + /** * Class to store the summary data for a given structure. * @author Anthony Bradley diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfUtils.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfUtils.java index bbd34c9610..3b4121cbc8 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfUtils.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmtf/MmtfUtils.java @@ -20,38 +20,12 @@ */ package org.biojava.nbio.structure.io.mmtf; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import javax.vecmath.Matrix4d; - -import org.biojava.nbio.structure.AminoAcid; -import org.biojava.nbio.structure.AminoAcidImpl; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Bond; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.ExperimentalTechnique; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.GroupType; -import org.biojava.nbio.structure.NucleotideImpl; -import org.biojava.nbio.structure.PDBCrystallographicInfo; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.FileParsingParameters; import org.biojava.nbio.structure.io.mmcif.ChemCompGroupFactory; import org.biojava.nbio.structure.io.mmcif.DownloadChemCompProvider; import org.biojava.nbio.structure.io.mmcif.chem.ChemCompTools; -import org.biojava.nbio.structure.io.mmcif.model.ChemComp; import org.biojava.nbio.structure.quaternary.BioAssemblyInfo; import org.biojava.nbio.structure.quaternary.BiologicalAssemblyTransformation; import org.biojava.nbio.structure.secstruc.DSSPParser; @@ -65,6 +39,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.vecmath.Matrix4d; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.Map.Entry; + /** * A utils class of functions needed for Biojava to read and write to mmtf. * @author Anthony Bradley @@ -310,8 +290,8 @@ public static int getNumGroups(Structure structure) { * @return the atoms for the input Biojava Group */ public static List getAtomsForGroup(Group inputGroup) { - Set uniqueAtoms = new HashSet(); - List theseAtoms = new ArrayList(); + Set uniqueAtoms = new HashSet<>(); + List theseAtoms = new ArrayList<>(); for(Atom a: inputGroup.getAtoms()){ theseAtoms.add(a); uniqueAtoms.add(a); @@ -343,9 +323,9 @@ public static int getNumBondsInGroup(List atomsInGroup) { // Now set the bonding information. Atom other = bond.getOther(atom); // If both atoms are in the group - if (atomsInGroup.indexOf(other)!=-1){ - Integer firstBondIndex = atomsInGroup.indexOf(atom); - Integer secondBondIndex = atomsInGroup.indexOf(other); + if (atomsInGroup.contains(other)){ + int firstBondIndex = atomsInGroup.indexOf(atom); + int secondBondIndex = atomsInGroup.indexOf(other); // Don't add the same bond twice if (firstBondIndex void addGroupAtId(List seqResGroups, T group, int sequence private static Group getSeqResGroup(char singleLetterCode, GroupType type) { - if(type==GroupType.AMINOACID){ - String threeLetter = ChemCompTools.getAminoThreeLetter(singleLetterCode); - if (threeLetter == null) return null; - ChemComp chemComp = ChemCompGroupFactory.getChemComp(threeLetter); - - AminoAcidImpl a = new AminoAcidImpl(); - a.setRecordType(AminoAcid.SEQRESRECORD); - a.setAminoType(singleLetterCode); - a.setPDBName(threeLetter); - a.setChemComp(chemComp); - return a; - - } else if (type==GroupType.NUCLEOTIDE) { - String twoLetter = ChemCompTools.getDNATwoLetter(singleLetterCode); - if (twoLetter == null) return null; - ChemComp chemComp = ChemCompGroupFactory.getChemComp(twoLetter); - - NucleotideImpl n = new NucleotideImpl(); - n.setPDBName(twoLetter); - n.setChemComp(chemComp); - return n; - } - else{ - return null; + switch (type) { + case AMINOACID: + String threeLetter = ChemCompTools.getAminoThreeLetter(singleLetterCode); + if (threeLetter != null) { + AminoAcidImpl a = new AminoAcidImpl(); + a.setRecordType(AminoAcid.SEQRESRECORD); + a.setAminoType(singleLetterCode); + a.setPDBName(threeLetter); + a.setChemComp(ChemCompGroupFactory.getChemComp(threeLetter)); + return a; + } + + break; + case NUCLEOTIDE: + String twoLetter = ChemCompTools.getDNATwoLetter(singleLetterCode); + if (twoLetter != null) { + NucleotideImpl n = new NucleotideImpl(); + n.setPDBName(twoLetter); + n.setChemComp(ChemCompGroupFactory.getChemComp(twoLetter)); + return n; + } + break; } + return null; + } } \ No newline at end of file diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsChainToUniprotMapping.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsChainToUniprotMapping.java index 84cd9ae138..6a487a9a44 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsChainToUniprotMapping.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsChainToUniprotMapping.java @@ -23,8 +23,8 @@ */ package org.biojava.nbio.structure.io.sifts; -import org.biojava.nbio.structure.align.util.UserConfiguration; import org.biojava.nbio.core.sequence.io.util.IOUtils; +import org.biojava.nbio.structure.align.util.UserConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -121,7 +121,7 @@ public static SiftsChainToUniprotMapping load(boolean useOnlyLocal) throws IOExc protected static SiftsChainToUniprotMapping build() throws IOException { SiftsChainToUniprotMapping sifts = new SiftsChainToUniprotMapping(); BufferedReader br = new BufferedReader(new FileReader(DEFAULT_FILE)); - String line = ""; + String line; while ((line = br.readLine()) != null) { if (line.isEmpty() || line.startsWith("#") || line.startsWith("PDB")) continue; String[] parts = line.split("\t"); @@ -147,8 +147,8 @@ private static void download() throws IOException { logger.info("Downloading {} to {}",DEFAULT_URL.toString(),DEFAULT_FILE); - InputStream in = null; - OutputStream out = null; + InputStream in; + OutputStream out; in = new GZIPInputStream(DEFAULT_URL.openStream()); out = new FileOutputStream(DEFAULT_FILE); @@ -156,9 +156,9 @@ private static void download() throws IOException { } - private Map byChainId = new HashMap(); + private final Map byChainId = new HashMap<>(); - private Map byUniProtId = new HashMap(); + private final Map byUniProtId = new HashMap<>(); private SiftsChainToUniprotMapping() { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsEntity.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsEntity.java index 34b2ba1bc4..20e1008859 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsEntity.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsEntity.java @@ -46,7 +46,7 @@ public SiftsEntity(){ public SiftsEntity(String type, String entityId) { this.type = type; this.entityId = entityId; - segments = new ArrayList(); + segments = new ArrayList<>(); } public void addSegment(SiftsSegment s) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsMappingProvider.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsMappingProvider.java index 7c67305f3c..e878ef511b 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsMappingProvider.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsMappingProvider.java @@ -24,9 +24,9 @@ */ package org.biojava.nbio.structure.io.sifts; -import org.biojava.nbio.structure.align.util.AtomCache; -import org.biojava.nbio.core.util.FileDownloadUtils; +import org.biojava.nbio.core.util.Download; import org.biojava.nbio.core.util.InputStreamProvider; +import org.biojava.nbio.structure.align.util.AtomCache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -88,7 +88,7 @@ public static List getSiftsMapping(String pdbId) throws IOException String u = String.format(fileLoc,pdbId); URL url = new URL(u); logger.debug("Downloading SIFTS file {} to {}",url,dest); - FileDownloadUtils.downloadFile(url, dest); + Download.downloadFile(url, dest); } InputStreamProvider prov = new InputStreamProvider(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsSegment.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsSegment.java index 1594228a05..e582a3881a 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsSegment.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsSegment.java @@ -49,7 +49,7 @@ public SiftsSegment(String segId, String start, String end) { this.segId = segId; this.start = start; this.end = end; - residues = new ArrayList(); + residues = new ArrayList<>(); } public String getSegId() { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsXMLParser.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsXMLParser.java index a563aca4ff..1f5b835c22 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsXMLParser.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/sifts/SiftsXMLParser.java @@ -34,7 +34,6 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; - import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; @@ -49,9 +48,9 @@ public class SiftsXMLParser { Document dom; List entities; - static boolean debug = false; + static final boolean debug = false; public SiftsXMLParser(){ - entities = new ArrayList(); + entities = new ArrayList<>(); } public List getEntities(){ @@ -60,7 +59,7 @@ public List getEntities(){ public void parseXmlFile(InputStream is){ - entities = new ArrayList(); + entities = new ArrayList<>(); //get the factory DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); @@ -75,12 +74,8 @@ public void parseXmlFile(InputStream is){ parseDocument(); - }catch(ParserConfigurationException pce) { + }catch(ParserConfigurationException | IOException | SAXException pce) { pce.printStackTrace(); - }catch(SAXException se) { - se.printStackTrace(); - }catch(IOException ioe) { - ioe.printStackTrace(); } } @@ -269,7 +264,7 @@ private String getTextValue(Element ele, String tagName) { } private List getTextValues(Element ele, String tagName) { - Listvalues = new ArrayList(); + Listvalues = new ArrayList<>(); NodeList nl = ele.getElementsByTagName(tagName); if(nl != null && nl.getLength() > 0) { for ( int i = 0 ;i < nl.getLength() ; i ++) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/util/PDBTemporaryStorageUtils.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/util/PDBTemporaryStorageUtils.java index 7ca25d24bc..1ab75c40a9 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/io/util/PDBTemporaryStorageUtils.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/io/util/PDBTemporaryStorageUtils.java @@ -40,22 +40,22 @@ public class PDBTemporaryStorageUtils { * @author Ulysse Carion */ public static class LinkRecord { - private String name1; - private String altLoc1; - private String resName1; - private String chainID1; - private String resSeq1; - private String iCode1; - - private String name2; - private String altLoc2; - private String resName2; - private String chainID2; - private String resSeq2; - private String iCode2; - - private String sym1; - private String sym2; + private final String name1; + private final String altLoc1; + private final String resName1; + private final String chainID1; + private final String resSeq1; + private final String iCode1; + + private final String name2; + private final String altLoc2; + private final String resName2; + private final String chainID2; + private final String resSeq2; + private final String iCode2; + + private final String sym1; + private final String sym2; public LinkRecord(String name1, String altLoc1, String resName1, String chainID1, String resSeq1, String iCode1, String name2, diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/jama/CholeskyDecomposition.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/jama/CholeskyDecomposition.java index 0a57710d3e..8e157da9a3 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/jama/CholeskyDecomposition.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/jama/CholeskyDecomposition.java @@ -32,7 +32,7 @@ be queried by the isSPD() method. public class CholeskyDecomposition implements java.io.Serializable { - static final long serialVersionUID = 224348942390823l; + static final long serialVersionUID = 224348942390823L; /* ------------------------ Class variables @@ -41,12 +41,12 @@ public class CholeskyDecomposition implements java.io.Serializable { /** Array for internal storage of decomposition. @serial internal array storage. */ - private double[][] L; + private final double[][] L; /** Row and column dimension (square matrix). @serial matrix dimension. */ - private int n; + private final int n; /** Symmetric and positive definite flag. @serial is symmetric and positive definite flag. diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/jama/EigenvalueDecomposition.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/jama/EigenvalueDecomposition.java index 13665270cf..96d67edae2 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/jama/EigenvalueDecomposition.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/jama/EigenvalueDecomposition.java @@ -51,7 +51,7 @@ public class EigenvalueDecomposition implements java.io.Serializable { /** Row and column dimension (square matrix). @serial matrix dimension. */ - private int n; + private final int n; /** Symmetry flag. @serial internal symmetry flag. @@ -61,12 +61,13 @@ public class EigenvalueDecomposition implements java.io.Serializable { /** Arrays for internal storage of eigenvalues. @serial internal storage of eigenvalues. */ - private double[] d, e; + private final double[] d; + private final double[] e; /** Array for internal storage of eigenvectors. @serial internal storage of eigenvectors. */ - private double[][] V; + private final double[][] V; /** Array for internal storage of nonsymmetric Hessenberg form. @serial internal storage of nonsymmetric Hessenberg form. @@ -91,9 +92,7 @@ private void tred2 () { // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding // Fortran subroutine in EISPACK. - for (int j = 0; j < n; j++) { - d[j] = V[n-1][j]; - } + if (n >= 0) System.arraycopy(V[n - 1], 0, d, 0, n); // Householder reduction to tridiagonal form. @@ -208,9 +207,7 @@ private void tql2 () { // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding // Fortran subroutine in EISPACK. - for (int i = 1; i < n; i++) { - e[i-1] = e[i]; - } + if (n - 1 >= 0) System.arraycopy(e, 1, e, 0, n - 1); e[n-1] = 0.0; double f = 0.0; @@ -855,9 +852,7 @@ private void hqr2 () { for (int i = 0; i < nn; i++) { if (i < low || i > high) { - for (int j = i; j < nn; j++) { - V[i][j] = H[i][j]; - } + System.arraycopy(H[i], i, V[i], i, nn - i); } } @@ -900,9 +895,7 @@ public EigenvalueDecomposition (Matrix Arg) { if (issymmetric) { for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) { - V[i][j] = A[i][j]; - } + System.arraycopy(A[i], 0, V[i], 0, n); } // Tridiagonalize. diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/jama/LUDecomposition.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/jama/LUDecomposition.java index 00f5d302ec..b9a2b7791e 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/jama/LUDecomposition.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/jama/LUDecomposition.java @@ -35,7 +35,7 @@ linear equations. This will fail if isNonsingular() returns false. public class LUDecomposition implements java.io.Serializable { - static final long serialVersionUID = 9271028462937843l; + static final long serialVersionUID = 9271028462937843L; /* ------------------------ Class variables @@ -44,19 +44,21 @@ public class LUDecomposition implements java.io.Serializable { /** Array for internal storage of decomposition. @serial internal array storage. */ - private double[][] LU; + private final double[][] LU; /** Row and column dimensions, and pivot sign. @serial column dimension. @serial row dimension. @serial pivot sign. */ - private int m, n, pivsign; + private final int m; + private final int n; + private int pivsign; /** Internal storage of pivot vector. @serial pivot vector. */ - private int[] piv; + private final int[] piv; /* ------------------------ Constructor @@ -254,9 +256,7 @@ public Matrix getU () { public int[] getPivot () { int[] p = new int[m]; - for (int i = 0; i < m; i++) { - p[i] = piv[i]; - } + if (m >= 0) System.arraycopy(piv, 0, p, 0, m); return p; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/jama/Matrix.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/jama/Matrix.java index 15bd130b99..164f211f44 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/jama/Matrix.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/jama/Matrix.java @@ -80,7 +80,9 @@ public class Matrix implements Cloneable, java.io.Serializable { - static final long serialVersionUID = 8492558293015348719l; + static final long serialVersionUID = 8492558293015348719L; + + public static final Matrix[] EmptyMatrixArray = new Matrix[0]; /* ------------------------ @@ -90,13 +92,14 @@ public class Matrix implements Cloneable, java.io.Serializable { /** Array for internal storage of elements. @serial internal array storage. */ - private double[][] A; + private final double[][] A; /** Row and column dimensions. @serial row dimension. @serial column dimension. */ - private int m, n; + private final int m; + private final int n; /* ------------------------ Constructors @@ -199,9 +202,7 @@ public static Matrix constructWithCopy(double[][] A) { throw new IllegalArgumentException ("All rows must have the same length."); } - for (int j = 0; j < n; j++) { - C[i][j] = A[i][j]; - } + System.arraycopy(A[i], 0, C[i], 0, n); } return X; } @@ -214,9 +215,7 @@ public Matrix copy () { Matrix X = new Matrix(m,n); double[][] C = X.getArray(); for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - C[i][j] = A[i][j]; - } + if (n >= 0) System.arraycopy(A[i], 0, C[i], 0, n); } return X; } @@ -244,9 +243,7 @@ public double[][] getArray () { public double[][] getArrayCopy () { double[][] C = new double[m][n]; for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - C[i][j] = A[i][j]; - } + if (n >= 0) System.arraycopy(A[i], 0, C[i], 0, n); } return C; } @@ -272,9 +269,7 @@ public double[] getColumnPackedCopy () { public double[] getRowPackedCopy () { double[] vals = new double[m*n]; for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - vals[i*n+j] = A[i][j]; - } + if (n >= 0) System.arraycopy(A[i], 0, vals, i * n + 0, n); } return vals; } @@ -320,9 +315,7 @@ public Matrix getMatrix (int i0, int i1, int j0, int j1) { double[][] B = X.getArray(); try { for (int i = i0; i <= i1; i++) { - for (int j = j0; j <= j1; j++) { - B[i-i0][j-j0] = A[i][j]; - } + if (j1 + 1 - j0 >= 0) System.arraycopy(A[i], j0, B[i - i0], j0 - j0, j1 + 1 - j0); } } catch(ArrayIndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException("Submatrix indices"); @@ -388,9 +381,7 @@ public Matrix getMatrix (int[] r, int j0, int j1) { double[][] B = X.getArray(); try { for (int i = 0; i < r.length; i++) { - for (int j = j0; j <= j1; j++) { - B[i][j-j0] = A[r[i]][j]; - } + if (j1 + 1 - j0 >= 0) System.arraycopy(A[r[i]], j0, B[i], j0 - j0, j1 + 1 - j0); } } catch(ArrayIndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException("Submatrix indices"); @@ -1050,7 +1041,7 @@ public static Matrix read (BufferedReader input) throws java.io.IOException { int n = v.size(); // Now we've got the number of columns! double[] row = new double[n]; for (int j=0; j symbolTable; // the vector, represented by index-value pairs + private final SymbolTable symbolTable; // the vector, represented by index-value pairs /** Constructor. initialize the all 0s vector of length N @@ -54,7 +54,7 @@ public class SparseVector implements Serializable{ */ public SparseVector(int N) { this.N = N; - this.symbolTable = new SymbolTable(); + this.symbolTable = new SymbolTable<>(); } /** Setter method (should it be renamed to set?) diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/math/SymbolTable.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/math/SymbolTable.java index 39d7926d9f..8f4b90b426 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/math/SymbolTable.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/math/SymbolTable.java @@ -63,13 +63,13 @@ public class SymbolTable, Value> implements Iterable */ private static final long serialVersionUID = -4417561575046471931L; - private TreeMap st; + private final TreeMap st; /** * Create an empty symbol table. */ public SymbolTable() { - st = new TreeMap(); + st = new TreeMap<>(); } /** diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/quaternary/BioAssemblyTools.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/quaternary/BioAssemblyTools.java index 9cd5d72d10..24f57e0381 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/quaternary/BioAssemblyTools.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/quaternary/BioAssemblyTools.java @@ -22,12 +22,11 @@ import org.biojava.nbio.structure.*; +import javax.vecmath.Point3d; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import javax.vecmath.Point3d; - @@ -50,8 +49,8 @@ public class BioAssemblyTools { * @return true if expression is a unary operator expression */ public static boolean isUnaryExpression(String expression) { - int first = expression.indexOf("("); - int last = expression.lastIndexOf("("); + int first = expression.indexOf('('); + int last = expression.lastIndexOf('('); if (first < 0 || last < 0) { return true; } @@ -68,7 +67,7 @@ private static List parseSubExpression(String expression) throws Illegal tmp = tmp.replace(")", ""); // separate the operators - List components = null; + List components; try { components = Arrays.asList(tmp.split(",")); } catch (Exception e) { @@ -76,7 +75,7 @@ private static List parseSubExpression(String expression) throws Illegal } // expand ranges if present, i.e. 1-60 -> 1, 2, 3, ..., 60 - List operators = new ArrayList(); + List operators = new ArrayList<>(); for (String component : components) { if (component.contains("-")) { operators.addAll(expandRange(component)); @@ -94,8 +93,8 @@ private static List parseSubExpression(String expression) throws Illegal * @throws IllegalArgumentException */ private static List expandRange(String expression) throws IllegalArgumentException { - int first = 0; - int last = 0; + int first; + int last; try { String[] range = expression.split("-"); first = Integer.parseInt(range[0]); @@ -104,7 +103,7 @@ private static List expandRange(String expression) throws IllegalArgumen throw new IllegalArgumentException("Invalid range specification in oper_expression: " + expression); } - List expandedExpression = new ArrayList(last-first+1); + List expandedExpression = new ArrayList<>(last - first + 1); for (int i = first; i <= last; i++) { expandedExpression.add(String.valueOf(i)); } @@ -114,7 +113,7 @@ private static List expandRange(String expression) throws IllegalArgumen public static List> parseBinaryOperatorExpression(String expression) throws IllegalArgumentException { // split operator expression, i.e. (1,2,3)(4,5) into two subexpressions - String[] subExpressions = null; + String[] subExpressions; try { subExpressions = expression.split("\\)\\("); } catch (Exception e) { @@ -127,7 +126,7 @@ public static List> parseBinaryOperatorExpression(String exp List rightSide = parseSubExpression(subExpressions[1]); // form the cartesian product of the two lists - CartesianProduct product = new CartesianProduct(leftSide, rightSide); + CartesianProduct product = new CartesianProduct<>(leftSide, rightSide); return product.getOrderedPairs(); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/quaternary/BiologicalAssemblyBuilder.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/quaternary/BiologicalAssemblyBuilder.java index 502730dcf3..44413c260e 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/quaternary/BiologicalAssemblyBuilder.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/quaternary/BiologicalAssemblyBuilder.java @@ -32,7 +32,10 @@ import org.slf4j.LoggerFactory; import javax.vecmath.Matrix4d; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * Reconstructs the quaternary structure of a protein from an asymmetric unit @@ -65,7 +68,7 @@ public class BiologicalAssemblyBuilder { */ private Map allTransformations; - private List modelIndex = new ArrayList<>(); + private final List modelIndex = new ArrayList<>(); public BiologicalAssemblyBuilder(){ init(); @@ -164,16 +167,13 @@ public Structure rebuildQuaternaryStructure(Structure asymUnit, List transformations) { final List chainIds = getChainIds(asymUnit); - Collections.sort(transformations, new Comparator() { - @Override - public int compare(BiologicalAssemblyTransformation t1, BiologicalAssemblyTransformation t2) { - // set sort order only if the two ids are identical - if (t1.getId().equals(t2.getId())) { - return chainIds.indexOf(t1.getChainId()) - chainIds.indexOf(t2.getChainId()); - } else { - return t1.getId().compareTo(t2.getId()); - } - } + transformations.sort((t1, t2) -> { + // set sort order only if the two ids are identical + if (t1.getId().equals(t2.getId())) { + return chainIds.indexOf(t1.getChainId()) - chainIds.indexOf(t2.getChainId()); + } else { + return t1.getId().compareTo(t2.getId()); + } }); } @@ -184,7 +184,7 @@ public int compare(BiologicalAssemblyTransformation t1, BiologicalAssemblyTransf * @return */ private List getChainIds(Structure asymUnit) { - List chainIds = new ArrayList(); + List chainIds = new ArrayList<>(); for ( Chain c : asymUnit.getChains()){ String intChainID = c.getId(); chainIds.add(intChainID); @@ -300,7 +300,7 @@ private ArrayList getBioUnitTransformationsLis for ( PdbxStructAssemblyGen psag : psags){ if ( psag.getAssembly_id().equals(assemblyId)) { - ListasymIds= Arrays.asList(psag.getAsym_id_list().split(",")); + String[] asymIds= psag.getAsym_id_list().split(","); operatorResolver.parseOperatorExpressionString(psag.getOper_expression()); @@ -332,7 +332,7 @@ private ArrayList getBioUnitTransformationsLis } private ArrayList getBioUnitTransformationsListUnaryOperators(String assemblyId, List psags) { - ArrayList transformations = new ArrayList(); + ArrayList transformations = new ArrayList<>(); for ( PdbxStructAssemblyGen psag : psags){ @@ -341,7 +341,7 @@ private ArrayList getBioUnitTransformationsLis operatorResolver.parseOperatorExpressionString(psag.getOper_expression()); List operators = operatorResolver.getUnaryOperators(); - ListasymIds= Arrays.asList(psag.getAsym_id_list().split(",")); + String[] asymIds= psag.getAsym_id_list().split(","); // apply unary operators to the specified chains for (String chainId : asymIds) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/quaternary/BiologicalAssemblyTransformation.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/quaternary/BiologicalAssemblyTransformation.java index cf5a7a1ea4..40164e2d39 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/quaternary/BiologicalAssemblyTransformation.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/quaternary/BiologicalAssemblyTransformation.java @@ -20,9 +20,9 @@ */ package org.biojava.nbio.structure.quaternary; +import org.biojava.nbio.core.util.PrettyXMLWriter; import org.biojava.nbio.structure.xtal.CrystalCell; import org.biojava.nbio.structure.xtal.CrystalTransform; -import org.biojava.nbio.core.util.PrettyXMLWriter; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; @@ -236,7 +236,7 @@ public static BiologicalAssemblyTransformation fromXML(String xml) public static List fromMultiXML(String xml) throws ParserConfigurationException, SAXException, IOException{ - List transformations = new ArrayList(); + List transformations = new ArrayList<>(); // read the XML of a string and returns a ModelTransformationmatrix DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); @@ -247,7 +247,7 @@ public static List fromMultiXML(String xml) th Document doc = db.parse(inStream); // normalize text representation - doc.getDocumentElement().normalize();; + doc.getDocumentElement().normalize(); NodeList listOfTransforms = doc.getElementsByTagName("transformation"); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/quaternary/CartesianProduct.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/quaternary/CartesianProduct.java index da6853a6fb..76dceed781 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/quaternary/CartesianProduct.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/quaternary/CartesianProduct.java @@ -21,7 +21,6 @@ package org.biojava.nbio.structure.quaternary; import java.util.ArrayList; -import java.util.Collections; import java.util.List; @@ -43,8 +42,8 @@ */ public class CartesianProduct { - private List list1 = Collections.emptyList(); - private List list2 = Collections.emptyList(); + private final List list1; + private final List list2; /** * Class constructor specifying the two lists of a cartesian product. @@ -60,11 +59,11 @@ public CartesianProduct(List list1, List list2) { * @return the list of ordered pairs */ public List> getOrderedPairs() { - List> pairs = new ArrayList>(list1.size()*list2.size()); + List> pairs = new ArrayList<>(list1.size() * list2.size()); for (T element1: list1) { for (T element2: list2) { - pairs.add(new OrderedPair(element1, element2)); + pairs.add(new OrderedPair<>(element1, element2)); } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/GetRepresentatives.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/GetRepresentatives.java index c3bbf1b907..5b4ccd0b6b 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/GetRepresentatives.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/GetRepresentatives.java @@ -39,11 +39,11 @@ */ public class GetRepresentatives { - private static String clusterUrl = "http://www.rcsb.org/pdb/rest/representatives?cluster="; - private static String allUrl = "http://www.rcsb.org/pdb/rest/getCurrent/"; + private static final String clusterUrl = "http://www.rcsb.org/pdb/rest/representatives?cluster="; + private static final String allUrl = "http://www.rcsb.org/pdb/rest/getCurrent/"; // available sequence clusters - private static List seqIdentities = Arrays.asList(30, 40, 50, 70, 90, 95, 100); + private static final List seqIdentities = Arrays.asList(30, 40, 50, 70, 90, 95, 100); /** @@ -54,7 +54,7 @@ public class GetRepresentatives { * @return PdbChainKey set of representatives */ public static SortedSet getRepresentatives(int sequenceIdentity) { - SortedSet representatives = new TreeSet(); + SortedSet representatives = new TreeSet<>(); if (!seqIdentities.contains(sequenceIdentity)) { System.err.println("Error: representative chains are not available for %sequence identity: " @@ -69,7 +69,7 @@ public static SortedSet getRepresentatives(int sequenceIdentity) InputStream stream = URLConnectionTools.getInputStream(u, 60000); - String xml = null; + String xml; if (stream != null) { xml = JFatCatClient.convertStreamToString(stream); @@ -95,7 +95,7 @@ public static SortedSet getRepresentatives(int sequenceIdentity) * @return PdbChainKey set of all PDB IDs. */ public static SortedSet getAll() { - SortedSet representatives = new TreeSet(); + SortedSet representatives = new TreeSet<>(); try { @@ -107,7 +107,7 @@ public static SortedSet getAll() { BufferedReader reader = new BufferedReader( new InputStreamReader(stream)); - String line = null; + String line; while ((line = reader.readLine()) != null) { int index = line.lastIndexOf("structureId="); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/PdbIdLists.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/PdbIdLists.java index 78f1ea8c9e..1827dc6188 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/PdbIdLists.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/PdbIdLists.java @@ -24,7 +24,8 @@ import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; -import java.util.*; +import java.util.Set; +import java.util.TreeSet; /** * Utility classes for retrieving lists of PDB IDs. @@ -226,7 +227,7 @@ public static Set postQuery(String xml) InputStream in = doPOST(u,encodedXML); - Set pdbIds = new TreeSet(); + Set pdbIds = new TreeSet<>(); try (BufferedReader rd = new BufferedReader(new InputStreamReader(in))) { @@ -237,7 +238,6 @@ public static Set postQuery(String xml) pdbIds.add(line); } - rd.close(); } @@ -275,7 +275,7 @@ public static InputStream doPOST(URL url, String data) // Get the response return conn.getInputStream(); - }; + } public static void main(String[] args){ try { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBDescription.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBDescription.java index 6c738697c9..e6eb75bddf 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBDescription.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBDescription.java @@ -39,10 +39,10 @@ public class RCSBDescription { private String pdbId; - private List polymers; + private final List polymers; public RCSBDescription() { - polymers = new ArrayList(); + polymers = new ArrayList<>(); } public void addPolymer(RCSBPolymer polymer) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBDescriptionFactory.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBDescriptionFactory.java index f181a39e6b..8c1f75e40f 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBDescriptionFactory.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBDescriptionFactory.java @@ -86,7 +86,7 @@ public static RCSBDescription get(InputStream stream) { // now get polymers data = structureIdE.getChildNodes(); - Element polymerE = null; + Element polymerE; for (int i = 0; i < data.getLength(); i++) { if (data.item(i).getNodeType() != 1) continue; polymerE = (Element) data.item(i); @@ -121,7 +121,7 @@ public static RCSBDescription get(String pdbId) { private static RCSBMacromolecule makeMolecule(Element moleculeE) { RCSBMacromolecule molecule = new RCSBMacromolecule(); molecule.setName(moleculeE.getAttribute("name")); - Element element = null; + Element element; NodeList data = moleculeE.getChildNodes(); for (int i = 0; i < data.getLength(); i++) { if (data.item(i).getNodeType() != 1) continue; @@ -141,28 +141,35 @@ private static RCSBPolymer makePolymer(Element polymerE) { polymer.setWeight(ReadUtils.toDouble(polymerE.getAttribute("weight"))); polymer.setType(ReadUtils.toStr(polymerE.getAttribute("type"))); - Element element = null; + Element element; NodeList data = polymerE.getChildNodes(); for (int i = 0; i < data.getLength(); i++) { if (data.item(i).getNodeType() != 1) continue; element = (Element) data.item(i); - if (element.getNodeName().equals("chain")) { - parseChains(polymer, element.getAttribute("id")); - } else if (element.getNodeName().equals("Taxonomy")) { - String name = element.getAttribute("name"); - int id = ReadUtils.toInt(element.getAttribute("id")); - RCSBTaxonomy taxonomy = new RCSBTaxonomy(name, id); - polymer.setTaxonomy(taxonomy); - } else if (element.getNodeName().equals("macroMolecule")) { - RCSBMacromolecule molecule = makeMolecule(element); - polymer.setMolecule(molecule); - } else if (element.getNodeName().equals("polymerDescription")) { - polymer.setDescription(element.getAttribute("description")); - } else if (element.getNodeName().equals("enzClass")) { - polymer.setEnzClass(element.getAttribute("ec")); - } else if (element.getNodeName().equals("synonym")) { - parseSynonyms(polymer, element.getAttribute("name")); - } + switch (element.getNodeName()) { + case "chain": + parseChains(polymer, element.getAttribute("id")); + break; + case "Taxonomy": + String name = element.getAttribute("name"); + int id = ReadUtils.toInt(element.getAttribute("id")); + RCSBTaxonomy taxonomy = new RCSBTaxonomy(name, id); + polymer.setTaxonomy(taxonomy); + break; + case "macroMolecule": + RCSBMacromolecule molecule = makeMolecule(element); + polymer.setMolecule(molecule); + break; + case "polymerDescription": + polymer.setDescription(element.getAttribute("description")); + break; + case "enzClass": + polymer.setEnzClass(element.getAttribute("ec")); + break; + case "synonym": + parseSynonyms(polymer, element.getAttribute("name")); + break; + } } return polymer; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBLigands.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBLigands.java index 2b06448fd0..e8d92c1683 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBLigands.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBLigands.java @@ -39,10 +39,10 @@ public class RCSBLigands { private String pdbId; - private List ligands; + private final List ligands; public RCSBLigands() { - ligands = new ArrayList(); + ligands = new ArrayList<>(); } public void addLigand(RCSBLigand ligand) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBLigandsFactory.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBLigandsFactory.java index 723bbfac5a..e2f145a277 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBLigandsFactory.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBLigandsFactory.java @@ -96,7 +96,7 @@ public static List getFromHeteroAtomIds(InputStream stream) { return null; } - List ligands = new ArrayList(); + List ligands = new ArrayList<>(); // first get the ligandInfo Element structureIdE = null; @@ -110,7 +110,7 @@ public static List getFromHeteroAtomIds(InputStream stream) { // now get individual ligands data = structureIdE.getChildNodes(); - Element ligandE = null; + Element ligandE; for (int i = 0; i < data.getLength(); i++) { if (data.item(i).getNodeType() != 1) continue; ligandE = (Element) data.item(i); @@ -150,7 +150,7 @@ public static List getFromHeteroAtomIds(String... heteroAtomIds) { } InputStream is; try { - URL url = new URL(HET_URL_STUB + sb.toString()); + URL url = new URL(HET_URL_STUB + sb); is = url.openConnection().getInputStream(); } catch (IOException e) { logger.warn("Couldn't open connection", e); @@ -187,7 +187,7 @@ public static RCSBLigands getFromPdbId(InputStream stream) { // now get individual ligands data = structureIdE.getChildNodes(); - Element ligandE = null; + Element ligandE; for (int i = 0; i < data.getLength(); i++) { if (data.item(i).getNodeType() != 1) continue; ligandE = (Element) data.item(i); @@ -239,9 +239,9 @@ public static List getFromPdbIds(InputStream stream) { // first we have to handle the element "ligandsInEntry", which is not present if we have only 1 structure - List ligandsList = new ArrayList(); + List ligandsList = new ArrayList<>(); - Element structureIdE = null; + Element structureIdE; for (int k = 0; k < dataaa.getLength(); k++) { @@ -263,7 +263,7 @@ public static List getFromPdbIds(InputStream stream) { // now get individual ligands data = ligandIdE.getChildNodes(); - Element ligandE = null; + Element ligandE; for (int i = 0; i < data.getLength(); i++) { if (data.item(i).getNodeType() != 1) continue; ligandE = (Element) data.item(i); @@ -329,7 +329,7 @@ public static List getFromPdbIds(String... pdbIds) { sb.append(pdbIds[i]); } try { - URL url = new URL(PDB_URL_STUB + sb.toString()); + URL url = new URL(PDB_URL_STUB + sb); is = url.openConnection().getInputStream(); } catch (IOException e) { logger.warn("Couldn't open connection", e); @@ -343,21 +343,27 @@ private static RCSBLigand makeLigand(Element ligandE) { ligand.setId(ligandE.getAttribute("chemicalID")); ligand.setType(ligandE.getAttribute("type")); ligand.setWeight(ReadUtils.toDouble(ligandE.getAttribute("molecularWeight"))); - Element element = null; + Element element; NodeList data = ligandE.getChildNodes(); for (int i = 0; i < data.getLength(); i++) { if (data.item(i).getNodeType() != 1) continue; element = (Element) data.item(i); - if (element.getNodeName().equals("chemicalName")) { - ligand.setName(element.getTextContent()); - } else if (element.getNodeName().equals("formula")) { - ligand.setFormula(element.getTextContent()); - } else if (element.getNodeName().equals("InChIKey")) { - ligand.setInChIKey(element.getTextContent()); - } else if (element.getNodeName().equals("InChI")) { - ligand.setInChI(element.getTextContent()); - } else if (element.getNodeName().equals("smiles")) { - ligand.setSmiles(element.getTextContent()); + switch (element.getNodeName()) { + case "chemicalName": + ligand.setName(element.getTextContent()); + break; + case "formula": + ligand.setFormula(element.getTextContent()); + break; + case "InChIKey": + ligand.setInChIKey(element.getTextContent()); + break; + case "InChI": + ligand.setInChI(element.getTextContent()); + break; + case "smiles": + ligand.setSmiles(element.getTextContent()); + break; } } return ligand; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBMacromolecule.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBMacromolecule.java index 5ab13502fa..31be20a33d 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBMacromolecule.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBMacromolecule.java @@ -37,11 +37,11 @@ */ public class RCSBMacromolecule { - private List accessions; + private final List accessions; private String name; public RCSBMacromolecule() { - accessions = new ArrayList(); + accessions = new ArrayList<>(); } public List getAccessions() { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBPolymer.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBPolymer.java index 1d3113e73b..f3cbfcf34f 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBPolymer.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBPolymer.java @@ -37,7 +37,7 @@ */ public class RCSBPolymer { - private List chains; + private final List chains; private String description; @@ -49,7 +49,7 @@ public class RCSBPolymer { private RCSBMacromolecule molecule; - private List synonyms; + private final List synonyms; private RCSBTaxonomy taxonomy; @@ -58,8 +58,8 @@ public class RCSBPolymer { private Double weight; public RCSBPolymer() { - chains = new ArrayList(); - synonyms = new ArrayList(); + chains = new ArrayList<>(); + synonyms = new ArrayList<>(); } public List getChains() { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBUpdates.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBUpdates.java index b4860b2cf1..b14f1efbc8 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBUpdates.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/RCSBUpdates.java @@ -44,12 +44,12 @@ public class RCSBUpdates { */ public Map getUpdates() throws IOException{ - Map outMap = new HashMap(); + Map outMap = new HashMap<>(); // A list of files to get String[] newStringList = {"added.models","added.nmr","added.pdb","added.sf","modified.cs","modified.models", "modified.nmr","modified.pdb","modified.sf","obsolete.cs","obsolete.models","obsolete.nmr","obsolete.pdb","obsolete.sf"}; for(String fileName: newStringList){ - String[] thisList = readURL(baseURL+""+fileName); + String[] thisList = readURL(baseURL + fileName); outMap.put(fileName, thisList); } return outMap; @@ -64,7 +64,7 @@ public Map getUpdates() throws IOException{ * @throws IOException */ private String[] readURL(String urlIn) throws IOException{ - List outList = new ArrayList(); + List outList = new ArrayList<>(); // create a url object URL url = new URL(urlIn); @@ -84,6 +84,6 @@ private String[] readURL(String urlIn) throws IOException{ } - return outList.toArray(new String[outList.size()]); + return outList.toArray(new String[0]); } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/ReadUtils.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/ReadUtils.java index 27efb2e36d..e3d0ab4e6a 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/ReadUtils.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/rcsb/ReadUtils.java @@ -70,8 +70,8 @@ static NodeList getNodes(InputStream stream) throws IOException { documentBuilderFactorySet = true; } DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = null; - Document document = null; + DocumentBuilder builder; + Document document; try { builder = builderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/Astral.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/Astral.java index d7c1ebe5d5..6d875a2ef4 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/Astral.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/Astral.java @@ -59,7 +59,7 @@ public class Astral { * @author dmyersturnbull * */ - public static enum AstralSet { + public enum AstralSet { FORTY_175("1.75_40", "http://scop.berkeley.edu/downloads/scopseq-1.75/astral-scopdom-seqres-gd-sel-gs-bib-40-1.75.fa"), NINETY_FIVE_175("1.75_95", "http://scop.berkeley.edu/downloads/scopseq-1.75/astral-scopdom-seqres-gd-sel-gs-bib-95-1.75.fa"), FORTY_175A("1.75A_40", "http://scop.berkeley.edu/downloads/scopeseq-2.01/astral-scopedom-seqres-gd-sel-gs-bib-40-2.01.fa"), @@ -72,8 +72,8 @@ public static enum AstralSet { NINETY_FIVE_202("2.02_95", "http://scop.berkeley.edu/downloads/scopeseq-2.02/astral-scopedom-seqres-gd-sel-gs-bib-95-2.02.fa"), FORTY_203("2.03_40", "http://scop.berkeley.edu/downloads/scopeseq-2.03/astral-scopedom-seqres-gd-sel-gs-bib-40-2.03.fa"), NINETY_FIVE_203("2.03_95", "http://scop.berkeley.edu/downloads/scopeseq-2.03/astral-scopedom-seqres-gd-sel-gs-bib-95-2.03.fa"); - private String id; - private String url; + private final String id; + private final String url; public static AstralSet parse(String str) { for (AstralSet c : AstralSet.class.getEnumConstants()) { @@ -101,7 +101,7 @@ public String toString() { } } - private static Map> instances = new HashMap>(); + private static final Map> instances = new HashMap<>(); private static final Logger logger = LoggerFactory.getLogger(Astral.class); @@ -116,7 +116,7 @@ public static Set getRepresentatives(AstralSet cutoff) { return instances.get(cutoff.getId()).get().getNames(); } Astral astral = new Astral(cutoff); - instances.put(cutoff.getId(), new SoftReference(astral)); + instances.put(cutoff.getId(), new SoftReference<>(astral)); return astral.getNames(); } @@ -203,8 +203,8 @@ public LinkedHashMap getFailedLines() { * Parses the FASTA file opened by reader. */ private void init(Reader reader) { - names = new TreeSet(); - failedLines = new LinkedHashMap(); + names = new TreeSet<>(); + failedLines = new LinkedHashMap<>(); BufferedReader br = null; @@ -214,7 +214,7 @@ private void init(Reader reader) { logger.info("Reading ASTRAL file..."); - String line = ""; + String line; int i = 0; while ((line = br.readLine()) != null) { if (line.startsWith(">")) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/BerkeleyScopInstallation.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/BerkeleyScopInstallation.java index f0aab86b95..1beaac2811 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/BerkeleyScopInstallation.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/BerkeleyScopInstallation.java @@ -38,14 +38,14 @@ public class BerkeleyScopInstallation extends ScopInstallation { - String defaultBerkeleyDownloadURL = "http://scop.berkeley.edu/downloads/parse/"; - String defaultBerkeleyScopVersion=ScopFactory.LATEST_VERSION; + final String defaultBerkeleyDownloadURL = "http://scop.berkeley.edu/downloads/parse/"; + final String defaultBerkeleyScopVersion=ScopFactory.LATEST_VERSION; /** * A map from SCOP version names which the Berkeley server offers as a * download to an array of equivalent deprecated SCOP version names. */ - public static final Map EQUIVALENT_VERSIONS = new HashMap(); + public static final Map EQUIVALENT_VERSIONS = new HashMap<>(); static { EQUIVALENT_VERSIONS.put("2.01", new String[] {"1.75A"}); @@ -62,7 +62,7 @@ public BerkeleyScopInstallation() { } private static class BerkeleyScopMirror extends ScopMirror { - private String rootURL; + private final String rootURL; public BerkeleyScopMirror(String url) { super(url); rootURL = url; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/CachedRemoteScopInstallation.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/CachedRemoteScopInstallation.java index 5f7ca94589..74d81c3a18 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/CachedRemoteScopInstallation.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/CachedRemoteScopInstallation.java @@ -24,8 +24,8 @@ */ package org.biojava.nbio.structure.scop; +import org.biojava.nbio.core.util.Download; import org.biojava.nbio.structure.align.client.JFatCatClient; -import org.biojava.nbio.structure.align.util.URLConnectionTools; import org.biojava.nbio.structure.domain.SerializableCache; import org.biojava.nbio.structure.scop.server.ScopDomains; import org.slf4j.Logger; @@ -50,9 +50,9 @@ public class CachedRemoteScopInstallation extends SerializableCache scopDescriptionCache ; + final SerializableCache scopDescriptionCache ; public CachedRemoteScopInstallation() throws IOException { this(true); @@ -64,7 +64,7 @@ public CachedRemoteScopInstallation(boolean useCache) throws IOException { proxy = new RemoteScopInstallation(); - scopDescriptionCache = new SerializableCache("scopDescriptionCache.ser"); + scopDescriptionCache = new SerializableCache<>("scopDescriptionCache.ser"); if ( ! useCache) { logger.warn(getClass().getSimpleName() + " disabling cache"); @@ -85,23 +85,23 @@ public CachedRemoteScopInstallation(boolean useCache) throws IOException { */ private void loadRepresentativeDomains() throws IOException { - URL u = null; + URL u; try { u = new URL(RemoteScopInstallation.DEFAULT_SERVER + "getRepresentativeScopDomains"); } catch (MalformedURLException e) { throw new IOException("URL " + RemoteScopInstallation.DEFAULT_SERVER + "getRepresentativeScopDomains" + " is wrong", e); } - logger.info("Using " + u + " to download representative domains"); - InputStream response = URLConnectionTools.getInputStream(u); - String xml = JFatCatClient.convertStreamToString(response); - ScopDomains results = ScopDomains.fromXML(xml); - - logger.info("got " + results.getScopDomain().size() + " domain ranges for Scop domains from server."); - for (ScopDomain dom : results.getScopDomain()){ - String scopId = dom.getScopId(); - serializedCache.put(scopId, dom); - } + logger.info("Using {} to download representative domains", u); + + InputStream response = Download.stream(u); + + ScopDomains results = ScopDomains.fromXML(JFatCatClient.convertStreamToString(response)); + + logger.info("got {} domain ranges for Scop domains from server.", results.getScopDomain().size()); + + for (ScopDomain dom : results.getScopDomain()) + serializedCache.put(dom.getScopId(), dom); } @@ -212,7 +212,7 @@ public void flushCache() { @Override public List getComments(int sunid) { - return new ArrayList(1); + return new ArrayList<>(1); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/RemoteScopInstallation.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/RemoteScopInstallation.java index a1534f0071..2c044b2055 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/RemoteScopInstallation.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/RemoteScopInstallation.java @@ -24,8 +24,8 @@ */ package org.biojava.nbio.structure.scop; +import org.biojava.nbio.core.util.Download; import org.biojava.nbio.structure.align.client.JFatCatClient; -import org.biojava.nbio.structure.align.util.URLConnectionTools; import org.biojava.nbio.structure.scop.server.ScopDescriptions; import org.biojava.nbio.structure.scop.server.ScopDomains; import org.biojava.nbio.structure.scop.server.ScopNodes; @@ -74,7 +74,7 @@ public List getByCategory(ScopCategory category) { List results = null; try { URL u = new URL(server + "getByCategory?category="+category+"&version="+getScopVersion()); - InputStream response = URLConnectionTools.getInputStream(u); + InputStream response = Download.stream(u); String xml = JFatCatClient.convertStreamToString(response); if(! xml.trim().isEmpty()) { @@ -92,7 +92,7 @@ public List filterByClassificationId(String query) { List results = null; try { URL u = new URL(server + "filterByClassificationId?query="+query+"&version="+getScopVersion()); - InputStream response = URLConnectionTools.getInputStream(u); + InputStream response = Download.stream(u); String xml = JFatCatClient.convertStreamToString(response); if(! xml.trim().isEmpty()) { @@ -110,7 +110,7 @@ public List getTree(ScopDomain domain) { List results = null; try { URL u = new URL(server + "getTree?scopId="+domain.getScopId()+"&version="+getScopVersion()); - InputStream response = URLConnectionTools.getInputStream(u); + InputStream response = Download.stream(u); String xml = JFatCatClient.convertStreamToString(response); if(! xml.trim().isEmpty()) { @@ -130,7 +130,7 @@ public List filterByDomainName(String query) { try { URL u = new URL(server + "filterByDomainName?query="+query+"&version="+getScopVersion()); //System.out.println(u); - InputStream response = URLConnectionTools.getInputStream(u); + InputStream response = Download.stream(u); String xml = JFatCatClient.convertStreamToString(response); if(! xml.trim().isEmpty()) { @@ -148,7 +148,7 @@ public List filterByDescription(String query) { List results = null; try { URL u = new URL(server + "filterByDescription?query="+query+"&version="+getScopVersion()); - InputStream response = URLConnectionTools.getInputStream(u); + InputStream response = Download.stream(u); String xml = JFatCatClient.convertStreamToString(response); if(! xml.trim().isEmpty()) { @@ -170,7 +170,7 @@ public ScopDescription getScopDescriptionBySunid(int sunid) { try { URL u = new URL(server + "getScopDescriptionBySunid?sunid="+sunid+"&version="+getScopVersion()); - InputStream response = URLConnectionTools.getInputStream(u); + InputStream response = Download.stream(u); String xml = JFatCatClient.convertStreamToString(response); if(! xml.trim().isEmpty()) { @@ -185,39 +185,31 @@ public ScopDescription getScopDescriptionBySunid(int sunid) { @Override public List getDomainsForPDB(String pdbId) { - List results = null; + String urlString = server + "getDomainsForPDB?pdbId=" + pdbId + "&version=" + getScopVersion(); + try { - URL u = new URL(server + "getDomainsForPDB?pdbId="+pdbId+"&version="+getScopVersion()); - InputStream response = URLConnectionTools.getInputStream(u); + InputStream response = Download.stream(new URL(urlString)); String xml = JFatCatClient.convertStreamToString(response); - if( !xml.trim().isEmpty()) { - ScopDomains container = ScopDomains.fromXML(xml); - results = container.getScopDomain(); - } + if( !xml.trim().isEmpty()) + return ScopDomains.fromXML(xml).getScopDomain(); + } catch (Exception e){ - throw new RuntimeException("Unable to reach "+ server + "getDomainsForPDB?pdbId="+pdbId+"&version="+getScopVersion(), e); + throw new RuntimeException("Unable to reach "+ urlString); //server + "getDomainsForPDB?pdbId="+pdbId+"&version="+getScopVersion(), e); } - return results; - } - private ScopDomain requestRemoteDomainByScopID(String scopId) - throws IOException{ - scopId = scopId.trim(); - URL u = new URL(server + "getDomainByScopID?scopId="+scopId+"&version="+getScopVersion()); - InputStream response = URLConnectionTools.getInputStream(u); - String xml = JFatCatClient.convertStreamToString(response); - - if( !xml.trim().isEmpty()) { - return XMLUtil.getScopDomainFromXML(xml); - } return null; } @Override public ScopDomain getDomainByScopID(String scopId) { try { - return requestRemoteDomainByScopID(scopId); + String scopId1 = scopId; + scopId1 = scopId1.trim(); + URL u = new URL(server + "getDomainByScopID?scopId="+ scopId1 +"&version="+getScopVersion()); +// String xml = JFatCatClient.convertStreamToString(Download.stream(u)); + + return XMLUtil.getScopDomainFromXML(Download.stream(u)); } catch (Exception e){ throw new RuntimeException("Unable to reach "+ server + "getDomainByScopID?scopId="+scopId+"&version="+getScopVersion(), e); } @@ -225,19 +217,20 @@ public ScopDomain getDomainByScopID(String scopId) { @Override public ScopNode getScopNode(int sunid) { - ScopNode desc = null; + + String uu = server + "getScopNode?sunid=" + sunid + "&version=" + getScopVersion(); try { - URL u = new URL(server + "getScopNode?sunid="+sunid+"&version="+getScopVersion()); - InputStream response = URLConnectionTools.getInputStream(u); + InputStream response = Download.stream(new URL(uu)); String xml = JFatCatClient.convertStreamToString(response); - if( !xml.trim().isEmpty()) { - desc = XMLUtil.getScopNodeFromXML(xml); - } + if( !xml.trim().isEmpty()) + return XMLUtil.getScopNodeFromXML(xml); + } catch (Exception e){ - throw new RuntimeException("Unable to reach "+ server + "getScopNode?sunid="+sunid+"&version="+getScopVersion(), e); + throw new RuntimeException("Unable to reach "+ uu); } - return desc; + + return null; } @Override @@ -246,7 +239,7 @@ public String getScopVersion() { if( version == null) { try { URL u = new URL(server + "getScopVersion"); - InputStream response = URLConnectionTools.getInputStream(u); + InputStream response = Download.stream(u); version = JFatCatClient.convertStreamToString(response); if( version != null) version = version.trim(); @@ -268,12 +261,11 @@ public List getScopDomainsBySunid(Integer sunid) { List results = null; try { URL u = new URL(server + "getScopDomainsBySunid?sunid="+sunid+"&version="+getScopVersion()); - InputStream response = URLConnectionTools.getInputStream(u); + InputStream response = Download.stream(u); String xml = JFatCatClient.convertStreamToString(response); if( !xml.trim().isEmpty()) { - ScopDomains container = ScopDomains.fromXML(xml); - results = container.getScopDomain(); + results = ScopDomains.fromXML(xml).getScopDomain(); } } catch (Exception e){ throw new RuntimeException("Unable to reach "+ server + "getScopDomainsBySunid?sunid="+sunid+"&version="+getScopVersion(), e); @@ -287,7 +279,7 @@ public List getComments(int sunid) { List results = null; try { URL u = new URL(server + "getComments?sunid="+sunid+"&version="+getScopVersion()); - InputStream response = URLConnectionTools.getInputStream(u); + InputStream response = Download.stream(u); String xml = JFatCatClient.convertStreamToString(response); if( !xml.trim().isEmpty()) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopCategory.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopCategory.java index c60e2c06e5..e140bb5d7e 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopCategory.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopCategory.java @@ -41,20 +41,22 @@ public enum ScopCategory implements Serializable Class,Fold, Superfamily, Family, Domain, Species, Px; public static ScopCategory fromString(String type){ - if ( type.equals("cl")) - return Class; - else if ( type.equals("cf")) - return Fold; - else if ( type.equals("sf")) - return Superfamily; - else if ( type.equals("fa")) - return Family; - else if ( type.equals("dm")) - return Domain; - else if ( type.equals("sp")) - return Species; - else - return Px; + switch (type) { + case "cl": + return Class; + case "cf": + return Fold; + case "sf": + return Superfamily; + case "fa": + return Family; + case "dm": + return Domain; + case "sp": + return Species; + default: + return Px; + } } @Override diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopDatabase.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopDatabase.java index ee3706cc76..6999069bee 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopDatabase.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopDatabase.java @@ -35,21 +35,21 @@ public interface ScopDatabase { * @param category e.g. "superfamily" * @return all records of this type */ - public abstract List getByCategory(ScopCategory category); + List getByCategory(ScopCategory category); /** Get all scop descriptions that start with a classification ID, e.g. b.1.18 * * @param query * @return list of scop descriptions */ - public abstract List filterByClassificationId(String query); + List filterByClassificationId(String query); /** get the SCOP sub-tree for a particular domain. * * @param domain * @return list of ScopNodes providing the path to this domain */ - public abstract List getTree(ScopDomain domain); + List getTree(ScopDomain domain); /** search through SCOP and filter based on domain name @@ -57,28 +57,28 @@ public interface ScopDatabase { * @param query a (part) of a name * @return list of matchin ScopDomains */ - public abstract List filterByDomainName(String query); + List filterByDomainName(String query); /** Get all scop descriptions that start with a certain name. e.g. Globin * * @param query * @return list of scop descriptions */ - public abstract List filterByDescription(String query); + List filterByDescription(String query); /** Return the SCOP description for a node in the hierarchy by its "sunid" id. * * @param sunid * @return a ScopDescription object */ - public abstract ScopDescription getScopDescriptionBySunid(int sunid); + ScopDescription getScopDescriptionBySunid(int sunid); /** Get a list of ScopDomains that have been assigned to a PDB ID * * @param pdbId the PDB entry * @return a list of ScopDomains */ - public abstract List getDomainsForPDB(String pdbId); + List getDomainsForPDB(String pdbId); /** get a ScopDomain by its SCOP ID (warning, they are not stable between releases!) * @@ -86,40 +86,40 @@ public interface ScopDatabase { * @param scopId e.g. d2bq6a1 * @return a ScopDomain or null if no domain with the particular ID could be found */ - public abstract ScopDomain getDomainByScopID(String scopId); + ScopDomain getDomainByScopID(String scopId); /** Access a particular ScopNode. The scopNode then allows to traverse through the scop hierarchy... * * @param sunid the scop unique id * @return a ScopNode that matches this sunid */ - public abstract ScopNode getScopNode(int sunid); + ScopNode getScopNode(int sunid); /** Returns the SCOP version * * @return version of SCOP */ - public abstract String getScopVersion(); + String getScopVersion(); /** * Sets the scop version used. * @param version * @throws UnsupportedOperationException If the version cannot be changed */ - public abstract void setScopVersion(String version); + void setScopVersion(String version); /** Get a SCOP domain by its sunid * * @param sunid the scop unique id * @return a list of scop domains that match this sunid */ - public abstract List getScopDomainsBySunid(Integer sunid); + List getScopDomainsBySunid(Integer sunid); /** * Get comments about a SCOP domain by its sunid * @param sunid * @return */ - public abstract List getComments(int sunid); + List getComments(int sunid); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopDescription.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopDescription.java index b85845ce2c..07d2704af3 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopDescription.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopDescription.java @@ -55,7 +55,7 @@ public class ScopDescription implements Serializable,Cloneable{ public String toString(){ StringBuilder buf = new StringBuilder(); - buf.append(String.valueOf(sunID)); + buf.append(sunID); buf.append("\t"); buf.append(category); buf.append("\t"); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopDomain.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopDomain.java index 121498f03d..723c21b3a6 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopDomain.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopDomain.java @@ -20,22 +20,16 @@ */ package org.biojava.nbio.structure.scop; -import java.io.IOException; -import java.io.Serializable; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.align.util.AtomCache; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; - -import org.biojava.nbio.structure.ResidueRange; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIdentifier; -import org.biojava.nbio.structure.SubstructureIdentifier; -import org.biojava.nbio.structure.align.util.AtomCache; +import java.io.Serializable; +import java.util.HashSet; +import java.util.List; +import java.util.Set; /** Container for the information for a domain. Contains a line in the file @@ -90,23 +84,23 @@ public String toString() { buf.append("\t") ; buf.append(classificationId); buf.append("\t") ; - buf.append(String.valueOf(sunid)); + buf.append(sunid); buf.append("\t") ; buf.append("cl="); - buf.append(String.valueOf(classId)); + buf.append(classId); buf.append(",cf="); - buf.append(String.valueOf(foldId)); + buf.append(foldId); buf.append(",sf="); - buf.append(String.valueOf(superfamilyId)); + buf.append(superfamilyId); buf.append(",fa="); - buf.append(String.valueOf(familyId)); + buf.append(familyId); buf.append(",dm="); - buf.append(String.valueOf(domainId)); + buf.append(domainId); buf.append(",sp="); - buf.append(String.valueOf(speciesId)); + buf.append(speciesId); buf.append(",px="); - buf.append(String.valueOf(px)); + buf.append(px); return buf.toString(); @@ -214,7 +208,7 @@ protected Object clone() throws CloneNotSupportedException { * Returns the chains this domain is defined over; contains more than 1 element only if this domains is a multi-chain domain. */ public Set getChains() { - Set chains = new HashSet(); + Set chains = new HashSet<>(); List rrs = ResidueRange.parseMultiple(getRanges()); for (ResidueRange rr : rrs) chains.add(rr.getChainName()); return chains; @@ -240,8 +234,7 @@ public Structure reduce(Structure input) throws StructureException { } @Override - public Structure loadStructure(AtomCache cache) throws StructureException, - IOException { + public Structure loadStructure(AtomCache cache) throws StructureException { return cache.getStructureForPdbId(pdbId); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopFactory.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopFactory.java index 15363bd3e7..1e2443549b 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopFactory.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopFactory.java @@ -23,9 +23,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.HashMap; import java.util.Map; - +import java.util.concurrent.ConcurrentHashMap; /** @@ -83,7 +82,7 @@ public class ScopFactory { public static final String LATEST_VERSION = VERSION_2_0_7; // Hold one instance for each version - private static Map versionedScopDBs = new HashMap(); + private static final Map versionedScopDBs = new ConcurrentHashMap<>(); private static String defaultVersion = LATEST_VERSION; /** @@ -140,14 +139,13 @@ public static ScopDatabase getSCOP(String version, boolean forceLocalData){ ScopDatabase scop = versionedScopDBs.get(version); if ( forceLocalData) { // Use a local installation - if( scop == null || !(scop instanceof LocalScopDatabase) ) { + if(!(scop instanceof LocalScopDatabase)) { logger.info("Creating new {}, version {}", BerkeleyScopInstallation.class.getSimpleName(), version); BerkeleyScopInstallation berkeley = new BerkeleyScopInstallation(); berkeley.setScopVersion(version); versionedScopDBs.put(version,berkeley); return berkeley; } - return scop; } else { // Use a remote installation if( scop == null ) { @@ -156,8 +154,8 @@ public static ScopDatabase getSCOP(String version, boolean forceLocalData){ scop.setScopVersion(version); versionedScopDBs.put(version,scop); } - return scop; } + return scop; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopInstallation.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopInstallation.java index bb65b81341..de9eb04962 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopInstallation.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopInstallation.java @@ -24,15 +24,18 @@ package org.biojava.nbio.structure.scop; +import org.biojava.nbio.core.util.Download; +import org.biojava.nbio.core.util.InputStreamProvider; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.align.util.UserConfiguration; -import org.biojava.nbio.core.util.FileDownloadUtils; -import org.biojava.nbio.core.util.InputStreamProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; import java.net.URL; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; @@ -82,15 +85,15 @@ public class ScopInstallation implements LocalScopDatabase { private String cacheLocation ; - private AtomicBoolean installedCla; - private AtomicBoolean installedDes; - private AtomicBoolean installedHie; - private AtomicBoolean installedCom; + private final AtomicBoolean installedCla; + private final AtomicBoolean installedDes; + private final AtomicBoolean installedHie; + private final AtomicBoolean installedCom; private Map> commentsMap; - private Map> domainMap; - private Map sunidMap; - private Map scopTree; + private final Map> domainMap; + private final Map sunidMap; + private final Map scopTree; /** @@ -112,12 +115,12 @@ public ScopInstallation(String cacheLocation){ installedCom.set(false); scopVersion = DEFAULT_VERSION; - mirrors = new ArrayList(1); + mirrors = new ArrayList<>(1); - domainMap = new HashMap>(); + domainMap = new HashMap<>(); - sunidMap = new HashMap(); - scopTree = new TreeMap(); + sunidMap = new HashMap<>(); + scopTree = new TreeMap<>(); } @@ -178,10 +181,9 @@ public List getByCategory(ScopCategory category){ throw new ScopIOException(e); } - List matches = new ArrayList(); - for (Integer i : sunidMap.keySet()){ - ScopDescription sc = sunidMap.get(i); - if ( sc.getCategory().equals(category)) + List matches = new ArrayList<>(); + for (ScopDescription sc : sunidMap.values()){ + if ( sc.getCategory().equals(category)) try { matches.add((ScopDescription)sc.clone()); @@ -205,12 +207,11 @@ public List filterByClassificationId(String query){ throw new ScopIOException(e); } - List matches = new ArrayList(); - for (Integer i : sunidMap.keySet()){ - ScopDescription sc = sunidMap.get(i); + List matches = new ArrayList<>(); + for (ScopDescription sc : sunidMap.values()){ - if( sc.getClassificationId().startsWith(query)){ + if( sc.getClassificationId().startsWith(query)){ matches.add(sc); } } @@ -227,7 +228,7 @@ public List getTree(ScopDomain domain){ ScopNode node = getScopNode(domain.getSunid()); - List tree = new ArrayList(); + List tree = new ArrayList<>(); while (node != null){ //System.out.println("This node: sunid:" + node.getSunid() ); @@ -246,7 +247,7 @@ public List getTree(ScopDomain domain){ @Override public List filterByDomainName(String query) { - List domains = new ArrayList(); + List domains = new ArrayList<>(); if (query.length() <5){ return domains; } @@ -281,11 +282,10 @@ public List filterByDescription(String query) throws ScopIOExce } query = query.toLowerCase(); - List matches = new ArrayList(); - for (Integer i : sunidMap.keySet()){ - ScopDescription sc = sunidMap.get(i); + List matches = new ArrayList<>(); + for (ScopDescription sc : sunidMap.values()){ - if( sc.getDescription().toLowerCase().startsWith(query)){ + if( sc.getDescription().toLowerCase().startsWith(query)){ matches.add(sc); } } @@ -321,7 +321,7 @@ public List getDomainsForPDB(String pdbId) { List doms = domainMap.get(pdbId.toLowerCase()); - List retdoms = new ArrayList(); + List retdoms = new ArrayList<>(); if ( doms == null) return retdoms; @@ -428,7 +428,7 @@ private void parseHierarchy(BufferedReader buffer) throws IOException { String children = spl[2]; String[] childIds = children.split(","); - List chis = new ArrayList(); + List chis = new ArrayList<>(); for ( String id : childIds){ if ( id.equals("-")) @@ -472,7 +472,7 @@ private void parseComments() throws IOException{ private void parseComments(BufferedReader buffer) throws IOException { - commentsMap = new HashMap>(); + commentsMap = new HashMap<>(); int counter = 0; String line; @@ -481,10 +481,10 @@ private void parseComments(BufferedReader buffer) throws IOException { String[] parts = line.split("!"); int sunId = Integer.parseInt(parts[0].trim()); if (parts.length == 1) { - commentsMap.put(sunId, new ArrayList(1)); + commentsMap.put(sunId, new ArrayList<>(1)); continue; } - List comments = new ArrayList(parts.length - 1); + List comments = new ArrayList<>(parts.length - 1); for (int i = 1; i < parts.length; i++) { String trimmed = parts[i].trim(); if( !trimmed.isEmpty() ) { @@ -499,7 +499,7 @@ private void parseComments(BufferedReader buffer) throws IOException { } private void parseDescriptions(BufferedReader buffer) throws IOException { - String line = null; + String line; int counter = 0; while ((line = buffer.readLine ()) != null) { @@ -536,7 +536,7 @@ private void parseDescriptions(BufferedReader buffer) throws IOException { private void parseClassification(BufferedReader buffer) throws IOException { - String line = null; + String line; int counter = 0; while ((line = buffer.readLine ()) != null) { @@ -594,7 +594,7 @@ private void parseClassification(BufferedReader buffer) throws IOException { if ( domainMap.containsKey(pdbId)){ domainList = domainMap.get(pdbId); } else { - domainList = new ArrayList(); + domainList = new ArrayList<>(); domainMap.put(pdbId,domainList); } @@ -637,7 +637,7 @@ private List extractRanges(String range) { return ranges; } - protected void downloadClaFile() throws FileNotFoundException, IOException{ + protected void downloadClaFile() throws IOException{ if(mirrors.size()<1) { initScopURLs(); } @@ -658,7 +658,7 @@ protected void downloadClaFile() throws FileNotFoundException, IOException{ throw new IOException("Unable to download SCOP .cla file",exception); } - protected void downloadDesFile() throws FileNotFoundException, IOException{ + protected void downloadDesFile() throws IOException{ if(mirrors.size()<1) { initScopURLs(); } @@ -701,7 +701,7 @@ protected void downloadHieFile() throws IOException{ } - protected void downloadComFile() throws FileNotFoundException, IOException{ + protected void downloadComFile() throws IOException{ if(mirrors.size()<1) { initScopURLs(); } @@ -724,7 +724,7 @@ protected void downloadComFile() throws FileNotFoundException, IOException{ protected void downloadFileFromRemote(URL remoteURL, File localFile) throws IOException{ logger.info("Downloading " + remoteURL + " to: " + localFile); - FileDownloadUtils.downloadFile(remoteURL, localFile); + Download.downloadFile(remoteURL, localFile); } private boolean claFileAvailable(){ @@ -836,10 +836,10 @@ public List getScopDomainsBySunid(Integer sunid) throw new ScopIOException(e); } - List domains = new ArrayList(); + List domains = new ArrayList<>(); - for (String pdbId: domainMap.keySet()){ - for (ScopDomain d : domainMap.get(pdbId)){ + for (List scopDomains : domainMap.values()){ + for (ScopDomain d : scopDomains){ try { if ( d.getPx() == sunid) { domains.add((ScopDomain)d.clone()); @@ -874,7 +874,7 @@ public List getComments(int sunid) { } catch (IOException e) { throw new ScopIOException(e); } - if (!commentsMap.containsKey(sunid)) return new ArrayList(1); + if (!commentsMap.containsKey(sunid)) return new ArrayList<>(1); return commentsMap.get(sunid); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopMirror.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopMirror.java index bd7ffa8175..5eff7e4db1 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopMirror.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/ScopMirror.java @@ -20,7 +20,7 @@ */ package org.biojava.nbio.structure.scop; -import org.biojava.nbio.core.util.FileDownloadUtils; +import org.biojava.nbio.core.util.Download; import java.net.URI; import java.net.URISyntaxException; @@ -86,12 +86,12 @@ public String getComURL(String scopVersion) { public boolean isReachable() { final int timeout = 800; if(rootURL != null) { - return FileDownloadUtils.ping(getRootURL(),timeout); + return Download.ping(getRootURL(),timeout); } else { try { URI cla = new URI(getClaURL("VERSION")); String host = cla.getHost(); - return FileDownloadUtils.ping(host,timeout); + return Download.ping(host,timeout); } catch (URISyntaxException e) { return false; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/ListStringWrapper.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/ListStringWrapper.java index 574052b86b..0f3ea6f6bb 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/ListStringWrapper.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/ListStringWrapper.java @@ -50,7 +50,7 @@ public class ListStringWrapper implements Serializable{ private static final long serialVersionUID = 4193799052494327416L; List data; - static JAXBContext jaxbContext; + static final JAXBContext jaxbContext; static { try { jaxbContext= JAXBContext.newInstance(ListStringWrapper.class); @@ -60,7 +60,7 @@ public class ListStringWrapper implements Serializable{ } public ListStringWrapper(){ - data = new ArrayList(); + data = new ArrayList<>(); } public List getData() { @@ -95,7 +95,7 @@ public String toXML(){ public static ListStringWrapper fromXML(String xml){ - ListStringWrapper job = null; + ListStringWrapper job; try { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/ScopDescriptions.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/ScopDescriptions.java index 8d618f710e..74925bf5dd 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/ScopDescriptions.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/ScopDescriptions.java @@ -47,7 +47,7 @@ public class ScopDescriptions implements Serializable{ private static final long serialVersionUID = 4924350548761431852L; - static JAXBContext jaxbContext; + static final JAXBContext jaxbContext; static { try { jaxbContext= JAXBContext.newInstance(ScopDescriptions.class); @@ -92,7 +92,7 @@ public String toXML(){ public static ScopDescriptions fromXML(String xml){ - ScopDescriptions job = null; + ScopDescriptions job; try { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/ScopDomains.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/ScopDomains.java index c9e8f8422b..5360b6808d 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/ScopDomains.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/ScopDomains.java @@ -28,14 +28,13 @@ import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; -import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.Serializable; +import java.io.StringReader; import java.util.List; @XmlRootElement(name = "ScopDomains", namespace ="http://source.rcsb.org") @@ -49,7 +48,7 @@ public class ScopDomains implements Serializable{ List domains ; - static JAXBContext jaxbContext; + static final JAXBContext jaxbContext; static { try { jaxbContext= JAXBContext.newInstance(ScopDomains.class); @@ -93,21 +92,15 @@ public String toXML(){ public static ScopDomains fromXML(String xml){ - ScopDomains job = null; try { - Unmarshaller un = jaxbContext.createUnmarshaller(); - - ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes()); - - job = (ScopDomains) un.unmarshal(bais); + return (ScopDomains) jaxbContext.createUnmarshaller().unmarshal(new StringReader(xml)); } catch (Exception e){ throw new RuntimeException("Could not parse " + ScopDomains.class + " from XML", e); } - return job; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/ScopNodes.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/ScopNodes.java index 70e9965a5b..cdd5c99ca4 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/ScopNodes.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/ScopNodes.java @@ -50,7 +50,7 @@ public class ScopNodes implements Serializable { List scopNodes ; - static JAXBContext jaxbContext; + static final JAXBContext jaxbContext; static { try { jaxbContext= JAXBContext.newInstance(ScopNodes.class); @@ -92,7 +92,7 @@ public String toXML(){ public static ScopNodes fromXML(String xml){ - ScopNodes job = null; + ScopNodes job; try { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/TreeSetStringWrapper.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/TreeSetStringWrapper.java index 004b81c069..d81ae886ce 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/TreeSetStringWrapper.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/TreeSetStringWrapper.java @@ -49,7 +49,7 @@ public class TreeSetStringWrapper implements Serializable{ private static final long serialVersionUID = 4193799052494327416L; TreeSet data; - static JAXBContext jaxbContext; + static final JAXBContext jaxbContext; static { try { jaxbContext= JAXBContext.newInstance(TreeSetStringWrapper.class); @@ -59,7 +59,7 @@ public class TreeSetStringWrapper implements Serializable{ } public TreeSetStringWrapper(){ - data = new TreeSet(); + data = new TreeSet<>(); } public TreeSet getData() { @@ -94,7 +94,7 @@ public String toXML(){ public static TreeSetStringWrapper fromXML(String xml){ - TreeSetStringWrapper job = null; + TreeSetStringWrapper job; try { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/XMLUtil.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/XMLUtil.java index 8061e6ef6e..39acb9982a 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/XMLUtil.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/scop/server/XMLUtil.java @@ -35,6 +35,7 @@ import javax.xml.bind.Unmarshaller; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.InputStream; import java.io.PrintStream; import java.util.List; import java.util.SortedSet; @@ -49,7 +50,7 @@ */ public class XMLUtil { - static JAXBContext jaxbContextScopDescription; + static final JAXBContext jaxbContextScopDescription; static { try { jaxbContextScopDescription= JAXBContext.newInstance(ScopDescription.class); @@ -58,7 +59,7 @@ public class XMLUtil { } } - static JAXBContext jaxbContextScopDomain; + static final JAXBContext jaxbContextScopDomain; static { try { jaxbContextScopDomain= JAXBContext.newInstance(ScopDomain.class); @@ -67,7 +68,7 @@ public class XMLUtil { } } - static JAXBContext jaxbContextScopNode; + static final JAXBContext jaxbContextScopNode; static { try { jaxbContextScopNode= JAXBContext.newInstance(ScopNode.class); @@ -76,7 +77,7 @@ public class XMLUtil { } } - static JAXBContext jaxbContextDomains; + static final JAXBContext jaxbContextDomains; static { try { jaxbContextDomains= JAXBContext.newInstance(TreeSet.class); @@ -85,7 +86,7 @@ public class XMLUtil { } } - static JAXBContext jaxbContextStringSortedSet; + static final JAXBContext jaxbContextStringSortedSet; static { try { jaxbContextStringSortedSet= JAXBContext.newInstance(TreeSetStringWrapper.class); @@ -94,7 +95,7 @@ public class XMLUtil { } } - static JAXBContext jaxbContextComments; + static final JAXBContext jaxbContextComments; static { try { jaxbContextComments = JAXBContext.newInstance(ListStringWrapper.class); @@ -112,7 +113,7 @@ public static String getScopDescriptionXML(ScopDescription desc){ public static ScopDescription getScopDescriptionFromXML(String xml){ - ScopDescription job = null; + ScopDescription job; try { @@ -186,7 +187,7 @@ public static String getCommentsXML(List comments ){ } public static List getCommentsFromXML(String xml){ - List comments = null; + List comments; try { @@ -227,7 +228,7 @@ public static String getScopNodeXML(ScopNode scopNode){ } public static ScopNode getScopNodeFromXML(String xml){ - ScopNode job = null; + ScopNode job; try { @@ -272,16 +273,16 @@ public static String getScopDomainXML(ScopDomain domain){ return baos.toString(); } - public static ScopDomain getScopDomainFromXML(String xml){ - ScopDomain job = null; + public static ScopDomain getScopDomainFromXML(InputStream xml){ + ScopDomain job; try { Unmarshaller un = jaxbContextScopDomain.createUnmarshaller(); - ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes()); + //ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes()); - job = (ScopDomain) un.unmarshal(bais); + job = (ScopDomain) un.unmarshal(xml); } catch (JAXBException e){ throw new RuntimeException("Could not serialize to XML", e); @@ -321,7 +322,7 @@ public static String getDomainsXML(SortedSet domains){ @SuppressWarnings("unchecked") public static SortedSet getDomainsFromXML(String xml) { - SortedSet domains = null; + SortedSet domains; try { Unmarshaller un = jaxbContextDomains.createUnmarshaller(); @@ -364,7 +365,7 @@ public static String getDomainRangesXML(SortedSet domainRanges){ } public static SortedSet getDomainRangesFromXML(String xml){ - SortedSet domains = null; + SortedSet domains; try { Unmarshaller un = jaxbContextStringSortedSet.createUnmarshaller(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/BetaBridge.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/BetaBridge.java index 552b509a23..066d7e38a3 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/BetaBridge.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/BetaBridge.java @@ -34,9 +34,9 @@ public class BetaBridge implements Serializable { private static final long serialVersionUID = -5097435425455958487L; - BridgeType type; - int partner1; - int partner2; + final BridgeType type; + final int partner1; + final int partner2; public BetaBridge(int i, int j, BridgeType t) { partner1 = Math.min(i, j); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/BridgeType.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/BridgeType.java index 04e35fe14d..39791b56e7 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/BridgeType.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/BridgeType.java @@ -40,7 +40,7 @@ public enum BridgeType { public final Character type; public final String name; - private BridgeType(String name, Character stype) { + BridgeType(String name, Character stype) { this.name = name; this.type = stype; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/DSSPParser.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/DSSPParser.java index 519aef812d..897618ce9e 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/DSSPParser.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/DSSPParser.java @@ -20,19 +20,6 @@ */ package org.biojava.nbio.structure.secstruc; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.zip.GZIPInputStream; - import org.biojava.nbio.structure.Group; import org.biojava.nbio.structure.ResidueNumber; import org.biojava.nbio.structure.Structure; @@ -40,6 +27,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.*; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import java.util.zip.GZIPInputStream; + /** * Class to parse a DSSP file (output of the DSSP program), * that contains the secondary structure assignment of a structure. @@ -152,7 +145,7 @@ private static List generalParse(BufferedReader reader, String startLine = " # RESIDUE AA STRUCTURE BP1 BP2 ACC"; String line; - List secstruc = new ArrayList(); + List secstruc = new ArrayList<>(); //Find the first line of the DSSP output while((line = reader.readLine()) != null) { @@ -165,7 +158,7 @@ private static List generalParse(BufferedReader reader, String resNumStr = line.substring(5,10).trim(); //Only happens if dssp inserts a line indicating a chain break - if(!resNumStr.equals("")) { + if(!resNumStr.isEmpty()) { int index = Integer.parseInt(indexStr); //Get the group of the structure corresponding to the residue @@ -183,16 +176,16 @@ private static List generalParse(BufferedReader reader, //Parse the Bridge partners - TODO parallel or antiparallel? String bp = line.substring(25,29).trim(); - if (bp != "") { + if (!bp.isEmpty()) { BetaBridge bb = new BetaBridge( - index, Integer.valueOf(bp), BridgeType.parallel); + index, Integer.parseInt(bp), BridgeType.parallel); ss.addBridge(bb); } else logger.warn("Unable to parse beta Bridge for resn "+index); bp = line.substring(29,33).trim(); - if (bp != "") { + if (!bp.isEmpty()) { BetaBridge bb = new BetaBridge( - index, Integer.valueOf(bp), BridgeType.parallel); + index, Integer.parseInt(bp), BridgeType.parallel); ss.addBridge(bb); } else logger.warn("Unable to parse beta Bridge for resn "+index); @@ -203,7 +196,7 @@ private static List generalParse(BufferedReader reader, int b = a + 8; String val = line.substring(a,b).trim(); - if (val == "") { + if (val.isEmpty()) { logger.warn("Unable to parse energy for resn "+index); continue; } @@ -212,7 +205,7 @@ private static List generalParse(BufferedReader reader, int partner = Integer.parseInt(p[0]); if (partner != 0) partner += index; - double energy = Double.valueOf(p[1]) * 1000.0; + double energy = Double.parseDouble(p[1]) * 1000.0; switch(i){ case 0: @@ -236,15 +229,15 @@ private static List generalParse(BufferedReader reader, //Angle properties String val = line.substring(91,97).trim(); - if (val != "") ss.setKappa(Float.valueOf(val)); + if (!val.isEmpty()) ss.setKappa(Float.parseFloat(val)); else logger.warn("Unable to parse kappa for resn "+index); val = line.substring(103,109).trim(); - if (val != "") ss.setPhi(Float.valueOf(val)); + if (!val.isEmpty()) ss.setPhi(Float.parseFloat(val)); else logger.warn("Unable to parse phi for resn "+index); val = line.substring(109,116).trim(); - if (val != "") ss.setPsi(Float.valueOf(val)); + if (!val.isEmpty()) ss.setPsi(Float.parseFloat(val)); else logger.warn("Unable to parse psi for resn "+index); if (assign) parent.setProperty(Group.SEC_STRUC, ss); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/SecStrucCalc.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/SecStrucCalc.java index 4696f3dc43..c70f3f3cb5 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/SecStrucCalc.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/SecStrucCalc.java @@ -28,14 +28,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.util.*; /** * Calculate and assign the secondary structure (SS) to the @@ -103,8 +96,8 @@ public class SecStrucCalc { private AtomContactSet contactSet; private Map indResMap; public SecStrucCalc(){ - ladders = new ArrayList(); - bridges = new ArrayList(); + ladders = new ArrayList<>(); + bridges = new ArrayList<>(); } @@ -119,11 +112,11 @@ public SecStrucCalc(){ public List calculate(Structure s, boolean assign) throws StructureException { - List secstruc = new ArrayList(); + List secstruc = new ArrayList<>(); for(int i=0; i(); - bridges = new ArrayList(); + ladders = new ArrayList<>(); + bridges = new ArrayList<>(); groups = initGroupArray(s, i); // Initialise the contact set for this structure initContactSet(); @@ -423,7 +416,7 @@ private boolean shouldExtendLadder(Ladder ladder, BetaBridge b) { private void findBridges() { // Get the interator of contacts Iterator myIter = contactSet.iterator(); - List> outList = new ArrayList>(); + List> outList = new ArrayList<>(); // Now iterate through this while(myIter.hasNext()){ @@ -460,30 +453,17 @@ private void findBridges() { continue; } - Pair thisPair = new Pair(i,j); + Pair thisPair = new Pair<>(i, j); outList.add(thisPair); } // - Collections.sort(outList, new Comparator>() { - @Override - public int compare(Pair o1, Pair o2) { - if(o1.getFirst()o2.getFirst()){ - return +1; - } - else{ - if(o1.getSecond()o2.getSecond()){ - return 1; - } - else{ - return 0; - } - } + outList.sort((o1, o2) -> { + if (o1.getFirst() < o2.getFirst()) { + return -1; + } else if (o1.getFirst() > o2.getFirst()) { + return +1; + } else { + return o1.getSecond().compareTo(o2.getSecond()); } }); @@ -601,12 +581,11 @@ public String toString() { */ public String printDSSP() { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); String nl = System.getProperty("line.separator"); //Header Line - buf.append("==== Secondary Structure Definition by BioJava" - + " DSSP implementation, Version October 2015 ===="+nl); + buf.append("==== Secondary Structure Definition by BioJava" + " DSSP implementation, Version October 2015 ====").append(nl); //First line with column definition buf.append(" # RESIDUE AA STRUCTURE BP1 BP2 ACC " @@ -634,11 +613,11 @@ public String printDSSP() { */ public String printHelixSummary() { - StringBuffer g = new StringBuffer(); //3-10 helix - StringBuffer h = new StringBuffer(); //alpha helix - StringBuffer i = new StringBuffer(); //pi-helix - StringBuffer ss = new StringBuffer(); //SS summary - StringBuffer aa = new StringBuffer(); //AA one-letter + StringBuilder g = new StringBuilder(); //3-10 helix + StringBuilder h = new StringBuilder(); //alpha helix + StringBuilder i = new StringBuilder(); //pi-helix + StringBuilder ss = new StringBuilder(); //SS summary + StringBuilder aa = new StringBuilder(); //AA one-letter String nl = System.getProperty("line.separator"); g.append( "3 turn: "); @@ -657,8 +636,8 @@ public String printHelixSummary() { aa.append(StructureTools.get1LetterCode(groups[k].getPDBName())); } - return g.toString()+nl+h.toString()+nl+ - i.toString()+nl+ss.toString()+nl+aa.toString(); + return g +nl+ h +nl+ + i +nl+ ss +nl+ aa; } /** @@ -668,9 +647,9 @@ public String printHelixSummary() { */ public String printFASTA() { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); String nl = System.getProperty("line.separator"); - buf.append(">"+groups[0].getChain().getStructure().getIdentifier()+nl); + buf.append(">").append(groups[0].getChain().getStructure().getIdentifier()).append(nl); for (int g = 0; g < groups.length; g++){ buf.append(getSecStrucState(g).getType()); @@ -704,7 +683,7 @@ public boolean equals(Object o){ } private static SecStrucGroup[] initGroupArray(Structure s, int modelId) { - List groupList = new ArrayList(); + List groupList = new ArrayList<>(); // for ( Chain c : s.getChains(modelId)){ @@ -742,7 +721,7 @@ private static SecStrucGroup[] initGroupArray(Structure s, int modelId) { } } - return groupList.toArray(new SecStrucGroup[groupList.size()]); + return groupList.toArray(new SecStrucGroup[0]); } /** @@ -750,7 +729,7 @@ private static SecStrucGroup[] initGroupArray(Structure s, int modelId) { * missing in the PDB files as only few experimental methods allow * to resolve their location. */ - private void calculateHAtoms() throws StructureException { + private void calculateHAtoms() { for ( int i = 0 ; i < groups.length-1 ; i++) { @@ -777,9 +756,7 @@ private void calculateHBonds() { * More efficient method for calculating C-Alpha pairs */ if (groups.length < 5) return; - Iterator otu = contactSet.iterator(); - while(otu.hasNext()){ - AtomContact ac = otu.next(); + for (AtomContact ac : contactSet) { Pair pair = ac.getPair(); Group g1 = pair.getFirst().getGroup(); Group g2 = pair.getSecond().getGroup(); @@ -787,9 +764,9 @@ private void calculateHBonds() { int i = indResMap.get(g1.getResidueNumber()); int j = indResMap.get(g2.getResidueNumber()); // Now check this - checkAddHBond(i,j); + checkAddHBond(i, j); //"backwards" hbonds are not allowed - if (j!=(i+1)) checkAddHBond(j,i); + if (j != (i + 1)) checkAddHBond(j, i); } } @@ -808,7 +785,7 @@ private void checkAddHBond(int i, int j){ SecStrucGroup two = groups[j]; - double energy = 0; + double energy; try { energy = calculateHBondEnergy(one,two); @@ -816,7 +793,7 @@ private void checkAddHBond(int i, int j){ logger.warn("Energy calculation failed", e); return; } - logger.debug("Energy between positions ({},{}): ",i,j,energy); + logger.debug("Energy between positions ({},{}={}): ",i,j,energy); trackHBondEnergy(i,j,energy); } @@ -842,32 +819,31 @@ private static double calculateHBondEnergy(SecStrucGroup one, Atom O = two.getO(); Atom C = two.getC(); - double dno = Calc.getDistance(O,N); - double dhc = Calc.getDistance(C,H); - double dho = Calc.getDistance(O,H); - double dnc = Calc.getDistance(C,N); + double dno = Calc.getDistance(O,N); if (dno < MINDIST) return HBONDLOWENERGY; + double dhc = Calc.getDistance(C,H); if (dhc < MINDIST) return HBONDLOWENERGY; + double dho = Calc.getDistance(O,H); if (dho < MINDIST) return HBONDLOWENERGY; + double dnc = Calc.getDistance(C,N); if (dnc < MINDIST) return HBONDLOWENERGY; - logger.debug(" cccc: {} {} {} {} O ({})..N ({}):{} | ho:{} - hc:{} + nc:{} - no:{}", - one.getResidueNumber(),one.getPDBName(),two.getResidueNumber(),two.getPDBName(), - O.getPDBserial(),N.getPDBserial(),dno,dho,dhc,dnc,dno); + if (logger.isDebugEnabled()) { + logger.debug(" cccc: {} {} {} {} O ({})..N ({}):{} | ho:{} - hc:{} + nc:{} - no:{}", + one.getResidueNumber(), one.getPDBName(), two.getResidueNumber(), two.getPDBName(), + O.getPDBserial(), N.getPDBserial(), dno, dho, dhc, dnc, dno); + } //there seems to be a contact! - if ( (dno < MINDIST) || (dhc < MINDIST) || - (dnc < MINDIST) || (dno < MINDIST)) { - return HBONDLOWENERGY; - } double e1 = Q / dho - Q / dhc; double e2 = Q / dnc - Q / dno; double energy = e1 + e2; - logger.debug(" N ({}) O({}): {} : {} ",N.getPDBserial(),O.getPDBserial(),(float) dno,energy); + if (logger.isDebugEnabled()) { + logger.debug(" N ({}) O({}): {} : {} ", N.getPDBserial(), O.getPDBserial(), (float) dno, energy); + } - //Avoid too strong energy - if (energy > HBONDLOWENERGY) return energy; + //Avoid too strong energy? + return energy > HBONDLOWENERGY ? energy : HBONDLOWENERGY; - return HBONDLOWENERGY ; } /** @@ -951,8 +927,8 @@ private void calculateTurns(){ getSecStrucState(i+turn).setTurn('<', turn); //Bracketed residues get the helix number for (int j=i+1; j', ending '<', or both 'X'. // Number means bracketed n-turn residue without h-bond - private char[] turn; + private final char[] turn; private boolean bend; private BetaBridge bridge1; @@ -226,7 +226,7 @@ public void setBridge2(BetaBridge bridge2) { public String printDSSPline(int index) { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); // # if (index < 9) diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/SecStrucTools.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/SecStrucTools.java index e2d1efd6ab..05736aeb62 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/SecStrucTools.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/SecStrucTools.java @@ -20,16 +20,16 @@ */ package org.biojava.nbio.structure.secstruc; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - import org.biojava.nbio.structure.Group; import org.biojava.nbio.structure.GroupIterator; import org.biojava.nbio.structure.ResidueNumber; import org.biojava.nbio.structure.Structure; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; + /** * This class contains methods for obtaining and converting secondary structure * information from BioJava {@link Structure}s. @@ -50,7 +50,7 @@ public class SecStrucTools { */ public static List getSecStrucInfo(Structure s) { - List listSSI = new ArrayList(); + List listSSI = new ArrayList<>(); GroupIterator iter = new GroupIterator(s); while (iter.hasNext()) { @@ -88,7 +88,7 @@ public static void assignSecStruc( Structure s,List listSSI){ */ public static List getSecStrucElements(Structure s) { - List listSSE = new ArrayList(); + List listSSE = new ArrayList<>(); GroupIterator iter = new GroupIterator(s); // SecStruc information - initialize @@ -99,7 +99,7 @@ public static List getSecStrucElements(Structure s) { int count = 0; // counts the number of residues in SSE // Create a map for the IDs of the SSE in the structure - Map ids = new TreeMap(); + Map ids = new EnumMap<>(SecStrucType.class); for (SecStrucType t : SecStrucType.values()) ids.put(t, 1); @@ -114,7 +114,7 @@ public static List getSecStrucElements(Structure s) { if (count > 0) { // If chain and type are equal increment counter - if (ss.type == type && chainId == g.getChainId()) { + if (ss.type == type && chainId.equals(g.getChainId())) { previous = g.getResidueNumber(); count++; continue; @@ -161,7 +161,7 @@ public static List getSecStrucElements(Structure s) { */ public static List getSecStrucElements(List groups) { - List listSSE = new ArrayList(); + List listSSE = new ArrayList<>(); // SecStruc information - initialize SecStrucType type = SecStrucType.coil; @@ -171,7 +171,7 @@ public static List getSecStrucElements(List groups) { int count = 0; // counts the number of residues in SSE // Create a map for the IDs of the SSE in the structure - Map ids = new TreeMap(); + Map ids = new EnumMap<>(SecStrucType.class); for (SecStrucType t : SecStrucType.values()) ids.put(t, 1); @@ -185,7 +185,7 @@ public static List getSecStrucElements(List groups) { if (count > 0) { // If chain and type are equal increment counter - if (ss.type == type && chainId == g.getChainId()) { + if (ss.type == type && chainId.equals(g.getChainId())) { previous = g.getResidueNumber(); count++; continue; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/SecStrucType.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/SecStrucType.java index 0def2da13e..2633a384ee 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/SecStrucType.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/secstruc/SecStrucType.java @@ -45,7 +45,7 @@ public enum SecStrucType { public final Character type; public final String name; - private SecStrucType(String name, Character stype) { + SecStrucType(String name, Character stype) { this.name = name; this.type = stype; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/axis/AxisAligner.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/axis/AxisAligner.java index 4721f101b3..8d44a0ef14 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/axis/AxisAligner.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/axis/AxisAligner.java @@ -20,14 +20,13 @@ */ package org.biojava.nbio.structure.symmetry.axis; +import org.biojava.nbio.structure.symmetry.core.QuatSymmetryResults; +import org.biojava.nbio.structure.symmetry.core.QuatSymmetrySubunits; + import javax.vecmath.Matrix3d; import javax.vecmath.Matrix4d; import javax.vecmath.Point3d; import javax.vecmath.Vector3d; - -import org.biojava.nbio.structure.symmetry.core.QuatSymmetryResults; -import org.biojava.nbio.structure.symmetry.core.QuatSymmetrySubunits; - import java.util.List; public abstract class AxisAligner { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/axis/HelixAxisAligner.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/axis/HelixAxisAligner.java index b76e844965..a52fba61fe 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/axis/HelixAxisAligner.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/axis/HelixAxisAligner.java @@ -30,7 +30,6 @@ import org.slf4j.LoggerFactory; import javax.vecmath.*; - import java.util.*; public class HelixAxisAligner extends AxisAligner { @@ -42,18 +41,18 @@ public class HelixAxisAligner extends AxisAligner { private static final Vector3d Y_AXIS = new Vector3d(0,1,0); private static final Vector3d Z_AXIS = new Vector3d(0,0,1); - private QuatSymmetrySubunits subunits = null; - private HelixLayers helixLayers = null; + private final QuatSymmetrySubunits subunits; + private final HelixLayers helixLayers; private Matrix4d transformationMatrix = new Matrix4d(); - private Matrix4d reverseTransformationMatrix = new Matrix4d(); + private final Matrix4d reverseTransformationMatrix = new Matrix4d(); private Vector3d referenceVector = new Vector3d(); private Vector3d principalRotationVector = new Vector3d(); private Vector3d[] principalAxesOfInertia = null; private List> alignedOrbits = null; - private Vector3d minBoundary = new Vector3d(); - private Vector3d maxBoundary = new Vector3d(); + private final Vector3d minBoundary = new Vector3d(); + private final Vector3d maxBoundary = new Vector3d(); private double xzRadiusMax = Double.MIN_VALUE; boolean modified = true; @@ -276,7 +275,7 @@ public Point3d calcCenterOfRotation() { } // average over all midpoints to find best center of rotation - centerOfRotation.scale(1/(line.size()-2)); + centerOfRotation.scale(1.0/(line.size()-2)); // since helix is aligned along the y-axis, with an origin at y = 0, place the center of rotation there centerOfRotation.y = 0; // transform center of rotation to the original coordinate frame @@ -356,7 +355,7 @@ private Matrix4d reorientHelix(int index) { * @return list of orbits ordered by z-depth */ private void calcAlignedOrbits() { - Map> depthMap = new TreeMap>(); + Map> depthMap = new TreeMap<>(); double[] depth = getSubunitZDepth(); alignedOrbits = calcOrbits(); @@ -378,13 +377,11 @@ private void calcAlignedOrbits() { // now fill orbits back into list ordered by depth alignedOrbits.clear(); - for (List orbit: depthMap.values()) { - // order subunit in a clockwise rotation around the z-axis - /// starting at the 12 O-clock position (+y position) - // TODO how should this be aligned?? - // alignWithReferenceAxis(orbit); - alignedOrbits.add(orbit); - } + // order subunit in a clockwise rotation around the z-axis + /// starting at the 12 O-clock position (+y position) + // TODO how should this be aligned?? + // alignWithReferenceAxis(orbit); + alignedOrbits.addAll(depthMap.values()); } @@ -429,7 +426,7 @@ private void calcTransformationBySymmetryAxes() { * @param referenceVectors * @return */ - private Matrix4d alignAxes(Vector3d[] axisVectors, Vector3d[] referenceVectors) { + private static Matrix4d alignAxes(Vector3d[] axisVectors, Vector3d[] referenceVectors) { Matrix4d m1 = new Matrix4d(); AxisAngle4d a = new AxisAngle4d(); Vector3d axis = new Vector3d(); @@ -585,7 +582,7 @@ private double[] getSubunitZDepth() { private List> calcOrbits() { int n = subunits.getSubunitCount(); - List> orbits = new ArrayList>(); + List> orbits = new ArrayList<>(); for (int i = 0; i < n; i++) { orbits.add(Collections.singletonList(i)); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/axis/RotationAxisAligner.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/axis/RotationAxisAligner.java index 30539a98ca..bb0631d577 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/axis/RotationAxisAligner.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/axis/RotationAxisAligner.java @@ -23,14 +23,13 @@ import org.biojava.nbio.structure.geometry.CalcPoint; import org.biojava.nbio.structure.geometry.MomentsOfInertia; import org.biojava.nbio.structure.symmetry.core.QuatSymmetryResults; +import org.biojava.nbio.structure.symmetry.core.QuatSymmetrySubunits; import org.biojava.nbio.structure.symmetry.core.Rotation; import org.biojava.nbio.structure.symmetry.core.RotationGroup; -import org.biojava.nbio.structure.symmetry.core.QuatSymmetrySubunits; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.vecmath.*; - import java.util.*; public class RotationAxisAligner extends AxisAligner{ @@ -42,18 +41,18 @@ public class RotationAxisAligner extends AxisAligner{ private static final Vector3d Y_AXIS = new Vector3d(0,1,0); private static final Vector3d Z_AXIS = new Vector3d(0,0,1); - private QuatSymmetrySubunits subunits = null; - private RotationGroup rotationGroup = null; + private final QuatSymmetrySubunits subunits; + private final RotationGroup rotationGroup; private Matrix4d transformationMatrix = new Matrix4d(); - private Matrix4d reverseTransformationMatrix = new Matrix4d(); + private final Matrix4d reverseTransformationMatrix = new Matrix4d(); private Vector3d referenceVector = new Vector3d(); private Vector3d principalRotationVector = new Vector3d(); private Vector3d[] principalAxesOfInertia = null; List> alignedOrbits = null; - private Vector3d minBoundary = new Vector3d(); - private Vector3d maxBoundary = new Vector3d(); + private final Vector3d minBoundary = new Vector3d(); + private final Vector3d maxBoundary = new Vector3d(); private double xyRadiusMax = Double.MIN_VALUE; boolean modified = true; @@ -236,7 +235,7 @@ private void run () { * @return list of orbits ordered by z-depth */ private void calcAlignedOrbits() { - Map> depthMap = new TreeMap>(); + Map> depthMap = new TreeMap<>(); double[] depth = getSubunitZDepth(); alignedOrbits = calcOrbits(); @@ -539,7 +538,7 @@ private void calcZDirection() { * */ private List> getOrbitsByXYWidth() { - Map> widthMap = new TreeMap>(); + Map> widthMap = new TreeMap<>(); double[] width = getSubunitXYWidth(); List> orbits = calcOrbits(); @@ -559,9 +558,7 @@ private List> getOrbitsByXYWidth() { // now fill orbits back into list ordered by width orbits.clear(); - for (List orbit: widthMap.values()) { - orbits.add(orbit); - } + orbits.addAll(widthMap.values()); return orbits; } @@ -608,14 +605,14 @@ private List> calcOrbits() { int n = subunits.getSubunitCount(); int fold = rotationGroup.getRotation(0).getFold(); - List> orbits = new ArrayList>(); + List> orbits = new ArrayList<>(); boolean[] used = new boolean[n]; Arrays.fill(used, false); for (int i = 0; i < n; i++) { if (! used[i]) { // determine the equivalent subunits - List orbit = new ArrayList(fold); + List orbit = new ArrayList<>(fold); for (int j = 0; j < fold; j++) { List permutation = rotationGroup.getRotation(j).getPermutation(); orbit.add(permutation.get(i)); @@ -637,7 +634,7 @@ private List deconvolute(List orbit) { // System.out.println("Permutation0: " + p0); // System.out.println("Permutation1: " + p1); - List inRotationOrder = new ArrayList(orbit.size()); + List inRotationOrder = new ArrayList<>(orbit.size()); inRotationOrder.add(orbit.get(0)); for (int i = 1; i < orbit.size(); i++) { int current = inRotationOrder.get(i-1); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/C2RotationSolver.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/C2RotationSolver.java index 90b3a3f6e1..a9ed913875 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/C2RotationSolver.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/C2RotationSolver.java @@ -24,12 +24,7 @@ import org.biojava.nbio.structure.geometry.CalcPoint; import org.biojava.nbio.structure.geometry.UnitQuaternions; -import javax.vecmath.AxisAngle4d; -import javax.vecmath.Matrix4d; -import javax.vecmath.Point3d; -import javax.vecmath.Quat4d; -import javax.vecmath.Vector3d; - +import javax.vecmath.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -39,12 +34,12 @@ * @author Peter */ public class C2RotationSolver implements QuatSymmetrySolver { - private QuatSymmetrySubunits subunits; - private QuatSymmetryParameters parameters; + private final QuatSymmetrySubunits subunits; + private final QuatSymmetryParameters parameters; private Vector3d centroid = new Vector3d(); - private Matrix4d centroidInverse = new Matrix4d(); + private final Matrix4d centroidInverse = new Matrix4d(); - private RotationGroup rotations = new RotationGroup(); + private final RotationGroup rotations = new RotationGroup(); public C2RotationSolver(QuatSymmetrySubunits subunits, QuatSymmetryParameters parameters) { @@ -153,9 +148,9 @@ private void combineWithTranslation(Matrix4d rotation) { rotation.mul(rotation, centroidInverse); } - private Rotation createSymmetryOperation(List permutation, Matrix4d transformation, AxisAngle4d axisAngle, int fold, QuatSymmetryScores scores) { + private static Rotation createSymmetryOperation(List permutation, Matrix4d transformation, AxisAngle4d axisAngle, int fold, QuatSymmetryScores scores) { Rotation s = new Rotation(); - s.setPermutation(new ArrayList(permutation)); + s.setPermutation(new ArrayList<>(permutation)); s.setTransformation(new Matrix4d(transformation)); s.setAxisAngle(new AxisAngle4d(axisAngle)); s.setFold(fold); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/HelicalRepeatUnit.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/HelicalRepeatUnit.java index f62208aadf..0a679c33e4 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/HelicalRepeatUnit.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/HelicalRepeatUnit.java @@ -21,16 +21,16 @@ package org.biojava.nbio.structure.symmetry.core; import org.biojava.nbio.structure.geometry.CalcPoint; -import javax.vecmath.Point3d; +import javax.vecmath.Point3d; import java.util.*; import java.util.Map.Entry; public class HelicalRepeatUnit { - private QuatSymmetrySubunits subunits = null; - private List repeatUnitCenters = new ArrayList(); - private List repeatUnits = new ArrayList(); - private List> repeatUnitIndices = new ArrayList>(); + private final QuatSymmetrySubunits subunits; + private List repeatUnitCenters = new ArrayList<>(); + private List repeatUnits = new ArrayList<>(); + private final List> repeatUnitIndices = new ArrayList<>(); private Map interactingNeighbors = Collections.emptyMap(); public HelicalRepeatUnit(QuatSymmetrySubunits subunits) { @@ -74,23 +74,23 @@ private void run() { private List calcRepeatUnitCenters() { // TODO why do we use models here? it should not matter. Setting to 0 all - List models = new ArrayList(subunits.getSubunitCount()); + List models = new ArrayList<>(subunits.getSubunitCount()); for (int s = 0; s uniqueModels = new HashSet(Arrays.asList(1)); + Set uniqueModels = new HashSet<>(Collections.singletonList(1)); int modelCount = uniqueModels.size(); List folds = this.subunits.getFolds(); int maxFold = folds.get(folds.size()-1); - List repeatCenters = new ArrayList(); + List repeatCenters = new ArrayList<>(); List centers = subunits.getCenters(); // if (modelCount == maxFold && subunits.getSubunitCount() > 3) { if (maxFold%modelCount == 0 && modelCount > 1 && subunits.getSubunitCount() > 3) { // System.out.println("calcRepeatUnitCenters case 1"); for (int i = 0; i < modelCount; i++) { - List subunitIndices = new ArrayList(); + List subunitIndices = new ArrayList<>(); Point3d p = new Point3d(); int count = 0; // System.out.println("Models: " + models.size()); @@ -113,7 +113,7 @@ private List calcRepeatUnitCenters() { // Case of 3B5U: A14, but seems to form (A2)*7 and symmetry related subunits don't have direct contact List sequenceClusterIds = subunits.getClusterIds(); for (int i = 0; i < subunits.getSubunitCount(); i++) { - List subunitIndices = new ArrayList(1); + List subunitIndices = new ArrayList<>(1); if (sequenceClusterIds.get(i) == 0) { repeatCenters.add(new Point3d(centers.get(i))); // System.out.println("Orig Repeat unit: " + centers.get(i)); @@ -135,23 +135,23 @@ private List calcRepeatUnitCenters() { private List calcRepeatUnits() { // TODO why do we use models here? it should not matter. Setting to 0 all - List models = new ArrayList( + List models = new ArrayList<>( subunits.getSubunitCount()); for (int s = 0; s < subunits.getSubunitCount(); s++) models.add(0); - Set uniqueModels = new HashSet(Arrays.asList(1)); + Set uniqueModels = new HashSet<>(Collections.singletonList(1)); int modelCount = uniqueModels.size(); List folds = this.subunits.getFolds(); int maxFold = folds.get(folds.size()-1); - List repeatTraces = new ArrayList(); + List repeatTraces = new ArrayList<>(); List traces = subunits.getTraces(); // if (modelCount == maxFold && subunitCount > 3) { if (maxFold%modelCount == 0 && modelCount > 1 && subunits.getSubunitCount() > 3) { for (int i = 0; i < modelCount; i++) { - List coords = new ArrayList(); + List coords = new ArrayList<>(); for (int j = 0; j < models.size(); j++) { if (models.get(j) == i) { coords.addAll(Arrays.asList(traces.get(j))); @@ -180,12 +180,12 @@ private List calcRepeatUnits() { } private Map findInteractingNeigbors() { - Map contactMap = new HashMap(); + Map contactMap = new HashMap<>(); Map> distanceMap = findClosestPairs(8); for (List pairs: distanceMap.values()) for (Integer[] pair: pairs) { - Integer contacts = calcContactNumber(repeatUnits.get(pair[0]), repeatUnits.get(pair[1])); + int contacts = calcContactNumber(repeatUnits.get(pair[0]), repeatUnits.get(pair[1])); // System.out.println("contacts: " + pair[0] + "-" + pair[1] + ": " + contacts); if (contacts > 0) { contactMap.put(pair, contacts); @@ -196,9 +196,9 @@ private Map findInteractingNeigbors() { } private Map> findClosestPairs(int maxNeighbors) { - Map> reducedMap = new TreeMap>(); + Map> reducedMap = new TreeMap<>(); - Map> distanceMap = new TreeMap>(); + Map> distanceMap = new TreeMap<>(); int nCenters = repeatUnitCenters.size(); // System.out.println("repeatUnitCenters: " + repeatUnitCenters); @@ -212,7 +212,7 @@ private Map> findClosestPairs(int maxNeighbors) { List pairs = distanceMap.get(intDist); // save only one representative pair for each distance if (pairs == null) { - pairs = new ArrayList(); + pairs = new ArrayList<>(); } Integer[] pair = new Integer[2]; pair[0] = i; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/Helix.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/Helix.java index d25f14ec34..d2e9161dc2 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/Helix.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/Helix.java @@ -24,7 +24,6 @@ import javax.vecmath.AxisAngle4d; import javax.vecmath.Matrix4d; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; /** @@ -152,16 +151,16 @@ public void setContacts(int contacts) { @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("Permutation : " + getPermutation() + "\n"); - sb.append("Repeat units : " + getRepeatUnits() + "\n"); - sb.append("Rise : " + getRise() + "\n"); - sb.append("Angle : " + Math.toDegrees(getAngle()) +"\n"); - sb.append("Fold : " + getFold() + "\n"); + sb.append("Permutation : ").append(getPermutation()).append("\n"); + sb.append("Repeat units : ").append(getRepeatUnits()).append("\n"); + sb.append("Rise : ").append(getRise()).append("\n"); + sb.append("Angle : ").append(Math.toDegrees(getAngle())).append("\n"); + sb.append("Fold : ").append(getFold()).append("\n"); return sb.toString(); } public List> getLayerLines() { - List> layerLines = new ArrayList>(); + List> layerLines = new ArrayList<>(); createLineSegments(permutation, layerLines); @@ -170,7 +169,7 @@ public List> getLayerLines() { // System.out.println(lineSegment); // } - int count = layerLines.size(); + int count; // iteratively join line segments do { @@ -192,7 +191,7 @@ private static void createLineSegments(List permutation, List> layerLines) { for (int i = 0; i < permutation.size(); i++) { if (permutation.get(i) != -1 ) { - List lineSegment = new ArrayList(); + List lineSegment = new ArrayList<>(); lineSegment.add(i); lineSegment.add(permutation.get(i)); layerLines.add(lineSegment); @@ -225,10 +224,6 @@ private static void joinLineSegments(List> layerLines) { } private static void trimEmptyLineSegments(List> layerLines) { - for (Iterator> iter = layerLines.iterator(); iter.hasNext();) { - if (iter.next().isEmpty()) { - iter.remove(); - } - } + layerLines.removeIf(List::isEmpty); } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/HelixExtender.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/HelixExtender.java index 30d799b6f3..ee035a2ee6 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/HelixExtender.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/HelixExtender.java @@ -21,15 +21,16 @@ package org.biojava.nbio.structure.symmetry.core; import org.biojava.nbio.structure.geometry.CalcPoint; + import javax.vecmath.Matrix4d; import javax.vecmath.Point3d; - import java.util.ArrayList; +import java.util.Arrays; import java.util.List; public class HelixExtender { - private QuatSymmetrySubunits subunits = null; - private Helix helix = null; + private final QuatSymmetrySubunits subunits; + private final Helix helix; public HelixExtender(QuatSymmetrySubunits subunits, Helix helix) { this.subunits = subunits; @@ -40,7 +41,7 @@ public Point3d[] extendHelix(int steps) { List> layerLines = helix.getLayerLines(); // get list of subunit indices to be used for helix extension - List indices = new ArrayList(); + List indices = new ArrayList<>(); for (List line: layerLines) { if (steps < 0) { indices.add(line.get(0)); @@ -50,7 +51,7 @@ public Point3d[] extendHelix(int steps) { } System.out.println("Extending subunits: " + indices); - List points = new ArrayList(); + List points = new ArrayList<>(); Matrix4d transformation = helix.getTransformation(); for (int index: indices) { Point3d[] trace = subunits.getTraces().get(index); @@ -58,9 +59,7 @@ public Point3d[] extendHelix(int steps) { for (int i = 0; i < Math.abs(steps); i++) { CalcPoint.transform(transformation, copy); } - for (Point3d p: copy) { - points.add(p); - } + points.addAll(Arrays.asList(copy)); } return points.toArray(new Point3d[0]); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/HelixLayers.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/HelixLayers.java index a42958d062..527f324ecb 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/HelixLayers.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/HelixLayers.java @@ -29,7 +29,7 @@ * @author Peter */ public class HelixLayers { - private List helices = new ArrayList(); + private final List helices = new ArrayList<>(); private double symmetryDeviation = 0; public int size() { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/HelixSolver.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/HelixSolver.java index 9576c248f6..e591fae1e0 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/HelixSolver.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/HelixSolver.java @@ -29,7 +29,6 @@ import javax.vecmath.Matrix4d; import javax.vecmath.Point3d; import javax.vecmath.Vector3d; - import java.util.*; import java.util.Map.Entry; @@ -44,10 +43,10 @@ public class HelixSolver { private static final Logger logger = LoggerFactory .getLogger(HelixSolver.class); - private QuatSymmetrySubunits subunits = null; - private int fold = 1; - private HelixLayers helixLayers = new HelixLayers(); - private QuatSymmetryParameters parameters = null; + private final QuatSymmetrySubunits subunits; + private final int fold; + private final HelixLayers helixLayers = new HelixLayers(); + private final QuatSymmetryParameters parameters; boolean modified = true; public HelixSolver(QuatSymmetrySubunits subunits, int fold, @@ -73,7 +72,7 @@ private void solve() { HelicalRepeatUnit unit = new HelicalRepeatUnit(subunits); List repeatUnitCenters = unit.getRepeatUnitCenters(); List repeatUnits = unit.getRepeatUnits(); - Set> permutations = new HashSet>(); + Set> permutations = new HashSet<>(); double minRise = parameters.getMinimumHelixRise() * fold; // for n-start // helix, @@ -129,7 +128,7 @@ private void solve() { // keep track of which subunits are permuted - Set permSet = new HashSet(); + Set permSet = new HashSet<>(); int count = 0; boolean valid = true; for (int i = 0; i < permutation.size(); i++) { @@ -164,8 +163,8 @@ private void solve() { } // superpose all permuted subunits - List point1 = new ArrayList(); - List point2 = new ArrayList(); + List point1 = new ArrayList<>(); + List point2 = new ArrayList<>(); List centers = subunits.getOriginalCenters(); for (int j = 0; j < permutation.size(); j++) { if (permutation.get(j) != -1) { @@ -355,7 +354,7 @@ private List getPermutation(Matrix4d transformation) { List centers = subunits.getOriginalCenters(); List seqClusterId = subunits.getClusterIds(); - List permutations = new ArrayList(centers.size()); + List permutations = new ArrayList<>(centers.size()); double[] dSqs = new double[centers.size()]; boolean[] used = new boolean[centers.size()]; Arrays.fill(used, false); @@ -366,7 +365,7 @@ private List getPermutation(Matrix4d transformation) { int permutation = -1; double minDistSq = Double.MAX_VALUE; for (int j = 0; j < centers.size(); j++) { - if (seqClusterId.get(i) == seqClusterId.get(j)) { + if (seqClusterId.get(i).equals(seqClusterId.get(j))) { if (!used[j]) { double dSq = tCenter.distanceSquared(centers.get(j)); if (dSq < minDistSq && dSq <= rmsdThresholdSq) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/PermutationGroup.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/PermutationGroup.java index 8bbcb5a650..5d286c9bcd 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/PermutationGroup.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/PermutationGroup.java @@ -21,18 +21,14 @@ package org.biojava.nbio.structure.symmetry.core; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; +import java.util.*; /** * * @author Peter */ public class PermutationGroup implements Iterable> { - List> permutations = new ArrayList>(); + final List> permutations = new ArrayList<>(); public void addPermutation(List permutation) { if (!permutations.contains(permutation)) { @@ -60,13 +56,13 @@ public int getOrder() { */ public void completeGroup() { // Copy initial set to allow permutations to grow - List> gens = new ArrayList>(permutations); + List> gens = new ArrayList<>(permutations); // Keep HashSet version of permutations for fast lookup. - Set> known = new HashSet>(permutations); + Set> known = new HashSet<>(permutations); //breadth-first search through the map of all members - List> currentLevel = new ArrayList>(permutations); + List> currentLevel = new ArrayList<>(permutations); while( currentLevel.size() > 0) { - List> nextLevel = new ArrayList>(); + List> nextLevel = new ArrayList<>(); for( List p : currentLevel) { for(List gen : gens) { List y = combine(p,gen); @@ -85,7 +81,7 @@ public void completeGroup() { @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("Permutation Group: " + permutations.size() + " permutation"); + sb.append("Permutation Group: ").append(permutations.size()).append(" permutation"); for (List permutation : permutations) { sb.append(permutation.toString()); } @@ -93,7 +89,7 @@ public String toString() { } public static List combine(List permutation1, List permutation2) { - List intermediate = new ArrayList(permutation1.size()); + List intermediate = new ArrayList<>(permutation1.size()); for (int i = 0, n = permutation1.size(); i < n; i++) { intermediate.add(permutation2.get(permutation1.get(i))); } @@ -101,7 +97,7 @@ public static List combine(List permutation1, List pe } public static int getOrder(List permutation) { - List copy = new ArrayList(permutation); + List copy = new ArrayList<>(permutation); for (int i = 0, n = permutation.size(); i < n; i++) { copy = combine(copy, permutation); if (copy.equals(permutation)) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/QuatSuperpositionScorer.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/QuatSuperpositionScorer.java index 5df1278563..ed4569d522 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/QuatSuperpositionScorer.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/QuatSuperpositionScorer.java @@ -25,7 +25,6 @@ import javax.vecmath.Matrix4d; import javax.vecmath.Point3d; - import java.util.List; /** diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/QuatSymmetryDetector.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/QuatSymmetryDetector.java index 4b26906ffd..7f6c183700 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/QuatSymmetryDetector.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/QuatSymmetryDetector.java @@ -24,18 +24,20 @@ import org.biojava.nbio.structure.Calc; import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.cluster.*; +import org.biojava.nbio.structure.cluster.Subunit; +import org.biojava.nbio.structure.cluster.SubunitCluster; +import org.biojava.nbio.structure.cluster.SubunitClusterer; +import org.biojava.nbio.structure.cluster.SubunitClustererParameters; import org.biojava.nbio.structure.contact.BoundingBox; import org.biojava.nbio.structure.contact.Grid; +import org.jgrapht.Graph; +import org.jgrapht.alg.clique.CliqueMinimalSeparatorDecomposition; +import org.jgrapht.graph.AsSubgraph; +import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.SimpleGraph; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.jgrapht.alg.clique.CliqueMinimalSeparatorDecomposition; -import org.jgrapht.graph.DefaultEdge; -import org.jgrapht.graph.AsSubgraph; -import org.jgrapht.Graph; - import javax.vecmath.Point3d; import java.util.*; import java.util.stream.Collectors; @@ -340,9 +342,9 @@ private static List calcLocalSymmetriesCluster(Stoichiometr map(QuatSymmetryResults::getStoichiometry). reduce(Stoichiometry::combineWith).get(); - if (groupComposition.numberOfComponents() < 2) { + if (groupComposition.numberOfComponents() < 2) continue; - } + //check if grouped clusters also have symmetry QuatSymmetryResults localResult = calcQuatSymmetry(groupComposition,symmParams); @@ -351,10 +353,11 @@ private static List calcLocalSymmetriesCluster(Stoichiometr clusterSymmetries.add(localResult); // find subunit ids in this cluster list Set knownResult = new HashSet<>(); - for (SubunitCluster cluster: groupComposition.getClusters()) { - int i = nontrivialComposition.getClusters().indexOf(cluster); - knownResult.addAll(clusterIdToSubunitIds.get(i)); - } + List nc = nontrivialComposition.getClusters(); + for (SubunitCluster cluster: groupComposition.getClusters()) + knownResult.addAll(clusterIdToSubunitIds.get(nc.indexOf(cluster))); + if (knownResult.isEmpty()) + knownResult = Collections.EMPTY_SET; // since symmetry is found, // do not try graph decomposition of this set of subunits later knownCombinations.add(knownResult); @@ -372,12 +375,13 @@ private static List calcLocalSymmetriesGraph(final Stoichio Set> knownCombinations, Graph graph) { - List localSymmetries = new ArrayList<>(); - // do not go any deeper into recursion if over the time/combinations limit if(symmParams.isLocalLimitsExceeded(knownCombinations)) { - return localSymmetries; + return Collections.EMPTY_LIST; } + + List localSymmetries = new ArrayList<>(); + // extract components of a (sub-)graph CliqueMinimalSeparatorDecomposition cmsd = new CliqueMinimalSeparatorDecomposition<>(graph); @@ -400,20 +404,16 @@ private static List calcLocalSymmetriesGraph(final Stoichio Stoichiometry localStoichiometry = trimSubunitClusters(globalComposition, allSubunitClusterIds, clusterIdToSubunitIds, usedSubunitIds); - if (localStoichiometry.numberOfComponents()==0) { + if (localStoichiometry.numberOfComponents()==0) continue; - } + //NB: usedSubunitIds might have changed when trimming clusters // if a subunit belongs to a cluster with no other subunits, // it is removed inside trimSubunitClusters Set usedSubunitIdsSet = new HashSet<>(usedSubunitIds); - if(!graphComponent.equals(usedSubunitIdsSet)) { - if(knownCombinations.contains(usedSubunitIdsSet)) { - continue; - } else { - knownCombinations.add(usedSubunitIdsSet); - } + if (!graphComponent.equals(usedSubunitIdsSet) && !knownCombinations.add(usedSubunitIdsSet)) { + continue; } QuatSymmetryResults localResult = calcQuatSymmetry(localStoichiometry,symmParams); @@ -432,10 +432,9 @@ private static List calcLocalSymmetriesGraph(final Stoichio // try removing subunits one by one and decompose the sub-graph recursively Set prunedGraphVertices = new HashSet<>(usedSubunitIds); prunedGraphVertices.remove(removeSubunitId); - if (knownCombinations.contains(prunedGraphVertices)) { + if (!knownCombinations.add(prunedGraphVertices)) continue; - } - knownCombinations.add(prunedGraphVertices); + Graph subGraph = new AsSubgraph<>(graph,prunedGraphVertices); @@ -463,7 +462,6 @@ private static Stoichiometry trimSubunitClusters(Stoichiometry globalComposition Set usedClusterIds = usedSubunitIds.stream(). map(allSubunitClusterIds::get). - distinct(). collect(Collectors.toSet()); // for each used cluster, remove unused subunits @@ -501,8 +499,8 @@ private static QuatSymmetryResults calcQuatSymmetry(Stoichiometry composition, Q if (subunits.getSubunitCount() == 0) return null; - RotationGroup rotationGroup = null; - SymmetryPerceptionMethod method = null; + RotationGroup rotationGroup; + SymmetryPerceptionMethod method; if (subunits.getFolds().size() == 1) { // no symmetry possible, create empty ("C1") rotation group method = SymmetryPerceptionMethod.NO_ROTATION; @@ -526,7 +524,7 @@ private static QuatSymmetryResults calcQuatSymmetry(Stoichiometry composition, Q String symmetry = results.getSymmetry(); // Check structures with Cn symmetry (n = 1, ...) for helical symmetry - if (symmetry.startsWith("C")) { + if (symmetry.startsWith("C")) { HelixSolver hc = new HelixSolver(subunits, rotationGroup.getOrder(), parameters); HelixLayers helixLayers = hc.getSymmetryOperations(); @@ -544,9 +542,7 @@ private static QuatSymmetryResults calcQuatSymmetry(Stoichiometry composition, Q double hRmsd = helixLayers.getScores().getRmsd(); // System.out.println("cRMSD: " + cRmsd + " hRMSD: " + hRmsd); double deltaRmsd = hRmsd - cRmsd; - if (symmetry.equals("C1") - || (!symmetry.equals("C1") && deltaRmsd <= parameters - .getHelixRmsdThreshold())) { + if (symmetry.equals("C1") || deltaRmsd <= parameters.getHelixRmsdThreshold()) { method = SymmetryPerceptionMethod.ROTO_TRANSLATION; results = new QuatSymmetryResults(composition, helixLayers, method); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/QuatSymmetryResults.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/QuatSymmetryResults.java index cdc7341c4b..9e9bc9f571 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/QuatSymmetryResults.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/QuatSymmetryResults.java @@ -44,15 +44,15 @@ public class QuatSymmetryResults { private Structure structure; // Information about the clustering process - private Stoichiometry stoichiometry; + private final Stoichiometry stoichiometry; private boolean local = false; // Cached properties - private List clusters; - private List subunits; + private final List clusters; + private final List subunits; // Information about the symmetry - private SymmetryPerceptionMethod method; + private final SymmetryPerceptionMethod method; private HelixLayers helixLayers; private RotationGroup rotationGroup = new RotationGroup(); @@ -72,7 +72,7 @@ public QuatSymmetryResults(Stoichiometry stoichiometry, this.stoichiometry = stoichiometry; this.clusters = stoichiometry.getClusters(); - subunits = new ArrayList(); + subunits = new ArrayList<>(); for (SubunitCluster c : clusters) { subunits.addAll(c.getSubunits()); } @@ -95,7 +95,7 @@ public QuatSymmetryResults(Stoichiometry stoichiometry, this.stoichiometry = stoichiometry; this.clusters = stoichiometry.getClusters(); - subunits = new ArrayList(); + subunits = new ArrayList<>(); for (SubunitCluster c : clusters) { subunits.addAll(c.getSubunits()); } @@ -200,12 +200,12 @@ public SymmetryPerceptionMethod getMethod() { * group symbol and for helical symmetry returns "H". */ public String getSymmetry() { - if (helixLayers != null && helixLayers.size() > 0) { + if (helixLayers != null && helixLayers.size() > 0) return "H"; - } else if (rotationGroup != null && rotationGroup.getOrder() > 0) { + else if (rotationGroup != null && rotationGroup.getOrder() > 0) return rotationGroup.getPointGroup(); - } - return ""; + else + return ""; } /** diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/QuatSymmetrySubunits.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/QuatSymmetrySubunits.java index 27d16cd6fe..47f9b3fa68 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/QuatSymmetrySubunits.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/QuatSymmetrySubunits.java @@ -30,8 +30,8 @@ import javax.vecmath.Point3d; import javax.vecmath.Vector3d; - -import java.util.*; +import java.util.ArrayList; +import java.util.List; import java.util.stream.Collectors; /** @@ -46,17 +46,17 @@ */ public class QuatSymmetrySubunits { - private List caCoords = new ArrayList<>(); - private List originalCenters = new ArrayList<>(); - private List centers = new ArrayList<>(); - private List unitVectors = new ArrayList<>(); + private final List caCoords = new ArrayList<>(); + private final List originalCenters = new ArrayList<>(); + private final List centers = new ArrayList<>(); + private final List unitVectors = new ArrayList<>(); - private List folds = new ArrayList<>(); - private List clusterIds = new ArrayList<>(); - private List clusters; + private final List folds; + private final List clusterIds = new ArrayList<>(); + private final List clusters; private Point3d centroid; - private MomentsOfInertia momentsOfInertia = new MomentsOfInertia(); + private final MomentsOfInertia momentsOfInertia = new MomentsOfInertia(); /** * Converts the List of {@link SubunitCluster} to a Subunit object. @@ -83,7 +83,7 @@ public QuatSymmetrySubunits(List clusters) { } // List number of members in each cluster - List stoichiometries = clusters.stream().map(c -> c.size()) + List stoichiometries = clusters.stream().map(SubunitCluster::size) .collect(Collectors.toList()); folds = SymmetryTools.getValidFolds(stoichiometries); } @@ -105,7 +105,7 @@ public List getClusterIds() { */ public List getChainIds() { - List chains = new ArrayList(getSubunitCount()); + List chains = new ArrayList<>(getSubunitCount()); // Loop through all subunits in the clusters and fill Lists for (int c = 0; c < clusters.size(); c++) { @@ -125,7 +125,7 @@ public List getChainIds() { */ public List getModelNumbers() { - List models = new ArrayList(getSubunitCount()); + List models = new ArrayList<>(getSubunitCount()); // Loop through all subunits in the clusters and fill Lists for (int c = 0; c < clusters.size(); c++) { @@ -224,8 +224,7 @@ private void calcOriginalCenters() { } private void calcCentroid() { - Point3d[] orig = originalCenters.toArray(new Point3d[originalCenters - .size()]); + Point3d[] orig = originalCenters.toArray(new Point3d[0]); centroid = CalcPoint.centroid(orig); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/RotationGroup.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/RotationGroup.java index 9a13d35813..552a55f3f2 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/RotationGroup.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/RotationGroup.java @@ -25,17 +25,17 @@ import javax.vecmath.Matrix4d; import javax.vecmath.Vector3d; import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; import java.util.Iterator; import java.util.List; +import static java.lang.System.identityHashCode; + /** * @see http://en.wikipedia.org/wiki/Rotation_group_SO(3) * @author Peter */ public class RotationGroup implements Iterable { - private List rotations = new ArrayList(); + private final List rotations = new ArrayList<>(); private int principalAxisIndex = 0; private int higherOrderRotationAxis = 0; private int twoFoldsPerpendicular = 0; @@ -61,7 +61,7 @@ public void addRotation(Rotation rotation) { public void setC1(int n) { Rotation r = new Rotation(); - List permutation = new ArrayList(n); + List permutation = new ArrayList<>(n); for (int i = 0; i < n; i++) { permutation.add(i); } @@ -90,7 +90,7 @@ public void complete() { findHigherOrderAxes(); findTwoFoldsPerpendicular(); calcPointGroup(); - sortByFoldDecending(); + sortByFoldDescending(); } modified = false; } @@ -192,7 +192,7 @@ public boolean isComplete() { @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("Rotations: " + rotations.size() + "\n"); + sb.append("Rotations: ").append(rotations.size()).append("\n"); for (Rotation s: rotations) { sb.append(s.toString()).append("\n"); } @@ -352,23 +352,24 @@ private void calcPointGroup() { } } - public void sortByFoldDecending() { - Collections.sort(rotations, new Comparator() { - @Override - public int compare(Rotation o1, Rotation o2) { - int delta = o1.getDirection() - o2.getDirection(); - if (delta != 0) { - return delta; - } - delta = Math.round(Math.signum(o2.getFold() - o1.getFold())); - if (delta != 0) { - return delta; - } - - delta = (int)(Math.signum(o1.getAxisAngle().angle - o2.getAxisAngle().angle)); - return delta; - } - }); + public void sortByFoldDescending() { + if (rotations.size() > 1) { + rotations.sort((o1, o2) -> { + + if (o1 == o2) return 0; + + int delta = Integer.compare(o1.getDirection(), o2.getDirection()); + if (delta != 0) return delta; + + delta = Integer.compare(o1.getFold(), o2.getFold()); + if (delta != 0) return delta; + + delta = Double.compare(o1.getAxisAngle().angle, o2.getAxisAngle().angle); + if (delta != 0) return delta; + + return Integer.compare(identityHashCode(o1), identityHashCode(o2)); + }); + } } @Override diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/RotationSolver.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/RotationSolver.java index d03c1d36da..19b136c2db 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/RotationSolver.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/RotationSolver.java @@ -21,44 +21,34 @@ package org.biojava.nbio.structure.symmetry.core; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.vecmath.AxisAngle4d; -import javax.vecmath.Matrix4d; -import javax.vecmath.Point3d; -import javax.vecmath.Quat4d; -import javax.vecmath.Vector3d; - import org.biojava.nbio.structure.geometry.CalcPoint; import org.biojava.nbio.structure.geometry.MomentsOfInertia; import org.biojava.nbio.structure.geometry.UnitQuaternions; import org.biojava.nbio.structure.symmetry.geometry.DistanceBox; import org.biojava.nbio.structure.symmetry.geometry.SphereSampler; +import javax.vecmath.*; +import java.util.*; + /** * * @author Peter */ public class RotationSolver implements QuatSymmetrySolver { - private QuatSymmetrySubunits subunits = null; - private QuatSymmetryParameters parameters = null; + private final QuatSymmetrySubunits subunits; + private final QuatSymmetryParameters parameters; private double distanceThreshold = 0.0f; private DistanceBox box = null; private Vector3d centroid = new Vector3d(); - private Matrix4d centroidInverse = new Matrix4d(); + private final Matrix4d centroidInverse = new Matrix4d(); private Point3d[] originalCoords = null; private Point3d[] transformedCoords = null; // Cache whether a permutation is invalid (null) vs has been added to rotations - private Map,Rotation> evaluatedPermutations = new HashMap<>(); + private final Map,Rotation> evaluatedPermutations = new HashMap<>(); - private RotationGroup rotations = new RotationGroup(); + private final RotationGroup rotations = new RotationGroup(); public RotationSolver(QuatSymmetrySubunits subunits, QuatSymmetryParameters parameters) { if (subunits.getSubunitCount()== 2) { @@ -280,7 +270,7 @@ private List getAngles() { n = 60; } List folds = subunits.getFolds(); - List angles = new ArrayList(folds.size()-1); + List angles = new ArrayList<>(folds.size() - 1); // note this loop starts at 1, we do ignore 1-fold symmetry, which is the first entry for (int fold: folds) { @@ -334,7 +324,7 @@ private boolean isAllowedPermutation(List permutation) { int selfaligned = 0; for (int i = 0; i < permutation.size(); i++) { int j = permutation.get(i); - if ( seqClusterId.get(i) != seqClusterId.get(j)) { + if (!seqClusterId.get(i).equals(seqClusterId.get(j))) { return false; } if(i == j ) { @@ -356,7 +346,7 @@ private void combineWithTranslation(Matrix4d rotation) { private static Rotation createSymmetryOperation(List permutation, Matrix4d transformation, AxisAngle4d axisAngle, int fold, QuatSymmetryScores scores) { Rotation s = new Rotation(); - s.setPermutation(new ArrayList(permutation)); + s.setPermutation(new ArrayList<>(permutation)); s.setTransformation(new Matrix4d(transformation)); s.setAxisAngle(new AxisAngle4d(axisAngle)); s.setFold(fold); @@ -367,7 +357,7 @@ private static Rotation createSymmetryOperation(List permutation, Matri private void setupDistanceBox() { distanceThreshold = calcDistanceThreshold(); - box = new DistanceBox(distanceThreshold); + box = new DistanceBox<>(distanceThreshold); for (int i = 0; i < originalCoords.length; i++) { box.addPoint(originalCoords[i], i); @@ -399,7 +389,7 @@ private double calcDistanceThreshold() { * @return A list mapping each subunit to the closest transformed subunit */ private List getPermutation() { - List permutation = new ArrayList(transformedCoords.length); + List permutation = new ArrayList<>(transformedCoords.length); double sum = 0.0f; for (Point3d t: transformedCoords) { @@ -429,7 +419,7 @@ private List getPermutation() { } // check uniqueness of indices - Set set = new HashSet(permutation); + Set set = new HashSet<>(permutation); // if size mismatch, clear permutation (its invalid) if (set.size() != originalCoords.length) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/Stoichiometry.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/Stoichiometry.java index dc6a09053f..435dfce949 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/Stoichiometry.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/core/Stoichiometry.java @@ -204,17 +204,12 @@ private String generateAlpha(int clusterInd) { } break; - case QUESTIONMARK: - key = "?"; - if(clusterInd> hashCodes = new HashSet>(); + private final Matrix4d centroidInverse = new Matrix4d(); + private final Set> hashCodes = new HashSet<>(); public SystematicSolver(QuatSymmetrySubunits subunits, QuatSymmetryParameters parameters) { if (subunits.getSubunitCount()== 2) { @@ -77,7 +72,7 @@ private void solve() { // loop over all permutations while (g.hasMore()) { int[] perm = g.getNext(); - List permutation = new ArrayList(perm.length); + List permutation = new ArrayList<>(perm.length); for (int j = 0; j < n; j++) { permutation.add(perm[j]); } @@ -110,7 +105,7 @@ private void combineWithTranslation(Matrix4d rotation) { private Rotation createSymmetryOperation(List permutation, Matrix4d transformation, AxisAngle4d axisAngle, int fold, QuatSymmetryScores scores) { Rotation s = new Rotation(); - s.setPermutation(new ArrayList(permutation)); + s.setPermutation(new ArrayList<>(permutation)); s.setTransformation(new Matrix4d(transformation)); s.setAxisAngle(new AxisAngle4d(axisAngle)); s.setFold(fold); @@ -176,7 +171,7 @@ private boolean isAllowedPermuation(List permutation) { List seqClusterId = subunits.getClusterIds(); for (int i = 0; i < permutation.size(); i++) { int j = permutation.get(i); - if (seqClusterId.get(i) != seqClusterId.get(j)) { + if (!seqClusterId.get(i).equals(seqClusterId.get(j))) { return false; } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/DistanceBox.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/DistanceBox.java index 37430260ca..7791aee231 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/DistanceBox.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/DistanceBox.java @@ -28,10 +28,10 @@ * @author Peter */ public class DistanceBox { - private Map> map; - private Map> layerMap; + private final Map> map; + private final Map> layerMap; private boolean modified; - private double inverseBinWidth; + private final double inverseBinWidth; // relative locations of 26 boxes surrounding a box at (0, 0, 0) private static final long[] offset = new long[] { 0 + ( 0 * 10000) + ( 0 * 1000000000L), @@ -63,12 +63,12 @@ public class DistanceBox { 1 + ( 1 * 10000) + ( 1 * 1000000000L) }; - private List tempBox = new ArrayList(offset.length); + private final List tempBox = new ArrayList<>(offset.length); /** Creates a new instance of DistanceBox */ public DistanceBox(double binWidth) { - map = new HashMap>(); - layerMap = new HashMap>(); + map = new HashMap<>(); + layerMap = new HashMap<>(); this.inverseBinWidth = 1.0f/binWidth; this.modified = true; } @@ -79,12 +79,7 @@ public void addPoint(Point3d point, T object) { long k = (long) StrictMath.rint(point.z * inverseBinWidth); long location = i + (j * 10000L) + (k * 1000000000L); - List box = map.get(location); - - if (box == null) { - box = new ArrayList(); - map.put(location, box); - } + List box = map.computeIfAbsent(location, k1 -> new ArrayList<>()); box.add(object); modified = true; @@ -127,8 +122,8 @@ public List getNeighbors(Point3d point) { } public List getIntersection(DistanceBox distanceBox) { - List intersection = new ArrayList(); - HashSet checkedLocations = new HashSet(); + List intersection = new ArrayList<>(); + HashSet checkedLocations = new HashSet<>(); for (Iterator iter = map.keySet().iterator(); iter.hasNext();) { long location = iter.next(); @@ -165,13 +160,13 @@ private List getBoxTwo(long location) { } } // ensure that boxTwo has no empty element by copying from tempBox of defined size - List boxTwo = null; + List boxTwo; if (tempBox.size() == 0) { boxTwo = Collections.emptyList(); } else if (tempBox.size() == 1) { boxTwo = Collections.singletonList(tempBox.get(0)); } else { - boxTwo = new ArrayList(tempBox); + boxTwo = new ArrayList<>(tempBox); } return boxTwo; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/IcosahedralSampler.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/IcosahedralSampler.java index 96b4758fc4..4ba6629de4 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/IcosahedralSampler.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/IcosahedralSampler.java @@ -31,7 +31,7 @@ */ // This would be better named HexacosichoronSampler, since it's sampling 4D space. -SB public final class IcosahedralSampler { - private static Quat4d quat = new Quat4d(); + private static final Quat4d quat = new Quat4d(); // this class cannot be instantiated private IcosahedralSampler() { @@ -57,7 +57,7 @@ public static void getAxisAngle(int index, AxisAngle4d axisAngle) { // format quaternion // The fifth column gives a weighting factor. Since the 600-cell is regular, all // orientations cover an equal fraction of orientation space and have equal weight. - private static double[][] orientations = { + private static final double[][] orientations = { {1.000000000f, 0.000000000f, 0.000000000f, 0.000000000f, 1.000000f}, {0.000000000f, 1.000000000f, 0.000000000f, 0.000000000f, 1.000000f}, {0.000000000f, 0.000000000f, 1.000000000f, 0.000000000f, 1.000000f}, diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/Icosahedron.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/Icosahedron.java index 7de37ee842..6712075b08 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/Icosahedron.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/Icosahedron.java @@ -27,12 +27,12 @@ public class Icosahedron implements Polyhedron { - private static int[] lineLoop1 = {4,0,1,2,3,4,5,1}; - private static int[] lineLoop2 = {3,0,2}; - private static int[] lineLoop3 = {0,5}; - private static int[] lineLoop4 = {11,3,7,4,8,6,7,8,9,10,11,7}; - private static int[] lineLoop5 = {6,11,2,10,1,9,6,10}; - private static int[] lineLoop6 = {8,5,9}; + private static final int[] lineLoop1 = {4,0,1,2,3,4,5,1}; + private static final int[] lineLoop2 = {3,0,2}; + private static final int[] lineLoop3 = {0,5}; + private static final int[] lineLoop4 = {11,3,7,4,8,6,7,8,9,10,11,7}; + private static final int[] lineLoop5 = {6,11,2,10,1,9,6,10}; + private static final int[] lineLoop6 = {8,5,9}; private double circumscribedRadius = 1.0; @@ -124,7 +124,7 @@ public Point3d[] getVertices() { } return icosahedron; - }; + } @Override public List getLineLoops() { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/Octahedron.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/Octahedron.java index 6cc5842dda..9256188b8a 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/Octahedron.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/Octahedron.java @@ -22,13 +22,13 @@ import javax.vecmath.Matrix3d; import javax.vecmath.Point3d; -import java.util.Arrays; +import java.util.Collections; import java.util.List; public class Octahedron implements Polyhedron { - private static double TETRAHEDRAL_ANGLE = Math.acos(-1.0/3.0); - private static int[] lineLoop1 = {2,4,3,5,2,1,3,0,5,1,4,0,2}; + private static final double TETRAHEDRAL_ANGLE = Math.acos(-1.0/3.0); + private static final int[] lineLoop1 = {2,4,3,5,2,1,3,0,5,1,4,0,2}; private double cirumscribedRadius = 1.0; /** @@ -108,11 +108,11 @@ public Point3d[] getVertices() { octahedron[5] = new Point3d(0, 0, cirumscribedRadius); return octahedron; - }; + } @Override public List getLineLoops() { - return Arrays.asList(lineLoop1); + return Collections.singletonList(lineLoop1); } public Point3d getC4Axis(double scale) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/Polyhedron.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/Polyhedron.java index 286c784225..fcb015a7d1 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/Polyhedron.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/Polyhedron.java @@ -33,10 +33,10 @@ */ public interface Polyhedron { - public Point3d[] getVertices(); - public List getLineLoops(); - public double getCirumscribedRadius(); - public int getViewCount(); - public String getViewName(int index); - public Matrix3d getViewMatrix(int index); + Point3d[] getVertices(); + List getLineLoops(); + double getCirumscribedRadius(); + int getViewCount(); + String getViewName(int index); + Matrix3d getViewMatrix(int index); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/Prism.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/Prism.java index 6b5d7edacf..94a1338497 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/Prism.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/Prism.java @@ -34,7 +34,7 @@ * */ public class Prism implements Polyhedron { - private int n = 3; + private final int n; private double circumscribedRadius = 1.0; private double height = 1.0; @@ -115,11 +115,11 @@ public Point3d[] getVertices() { } return polygon; - }; + } @Override public List getLineLoops() { - List list = new ArrayList(); + List list = new ArrayList<>(); int[] l1 = new int[2*n+2]; for (int i = 0; i < n; i++) { l1[i] = i; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/RectangularPrism.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/RectangularPrism.java index 45d32828c3..b6c3f1099b 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/RectangularPrism.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/RectangularPrism.java @@ -27,14 +27,14 @@ public class RectangularPrism implements Polyhedron { - private static int[] lineLoop1 = {0,1,2,3,0,4,5,6,7,4}; - private static int[] lineLoop2 = {1,5}; - private static int[] lineLoop3 = {2,6}; - private static int[] lineLoop4 = {3,7}; - private double length = 1.0; - private double width = 1.0; - private double height = 1.0; - private static String[] viewNames = {"Front", "Left", "Back", "Right", "Top", "Bottom"}; + private static final int[] lineLoop1 = {0,1,2,3,0,4,5,6,7,4}; + private static final int[] lineLoop2 = {1,5}; + private static final int[] lineLoop3 = {2,6}; + private static final int[] lineLoop4 = {3,7}; + private final double length; + private final double width; + private final double height; + private static final String[] viewNames = {"Front", "Left", "Back", "Right", "Top", "Bottom"}; public RectangularPrism(double length, double width, double height) { this.length = length; @@ -103,7 +103,7 @@ public Point3d[] getVertices() { vertices[7] = new Point3d( x, -y, -z); return vertices; - }; + } @Override public List getLineLoops() { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/SphereSampler.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/SphereSampler.java index e36e942d89..e953a94c47 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/SphereSampler.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/SphereSampler.java @@ -32,7 +32,7 @@ */ class Permute { - private List triples = new ArrayList(); + private final List triples = new ArrayList<>(); Permute(Point3i t) { Point3i tmp = new Point3i(); @@ -98,7 +98,7 @@ public int size() { public Point3i get(int i) { return triples.get(i); } -}; +} /** * Sample possible orientations. An orientation can be represented as a @@ -154,7 +154,7 @@ public final class SphereSampler { static { - List myorientations = new ArrayList(); + List myorientations = new ArrayList<>(); // 60 equally spaced grid points covering all quaternions // This could be removed, since the 48-cell bcc lattice has lower angle error -SB @@ -173,7 +173,7 @@ public final class SphereSampler { // This is the c48u309 lattice from Karney 2006, with a max error of 10.07 // degrees. - List grid = new ArrayList(); + List grid = new ArrayList<>(); int ncell1 = 0; for (int n = 0; n < nent; ++n) { // for each tuple (k,l,m) above Permute p = new Permute(new Point3i(k[n], l[n], m[n])); @@ -209,7 +209,7 @@ public final class SphereSampler { // this class cannot be instantiated private SphereSampler() { - }; + } public static int getSphereCount() { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/Tetrahedron.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/Tetrahedron.java index 7effd81cbe..38a848805b 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/Tetrahedron.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/geometry/Tetrahedron.java @@ -20,18 +20,18 @@ */ package org.biojava.nbio.structure.symmetry.geometry; +import org.biojava.nbio.structure.geometry.CalcPoint; + import javax.vecmath.Matrix3d; import javax.vecmath.Point3d; - -import org.biojava.nbio.structure.geometry.CalcPoint; import java.util.Arrays; import java.util.List; public class Tetrahedron implements Polyhedron { - private static double TETRAHEDRAL_ANGLE = Math.acos(-1.0/3.0); - private static int[] lineLoop1 = {0,1,2,3,0,2}; - private static int[] lineLoop2 = {1,3}; + private static final double TETRAHEDRAL_ANGLE = Math.acos(-1.0/3.0); + private static final int[] lineLoop1 = {0,1,2,3,0,2}; + private static final int[] lineLoop2 = {1,3}; private double circumscribedRadius = 1.0; @@ -120,7 +120,7 @@ public Point3d[] getVertices() { m.transform(p); } return tetrahedron; - }; + } @Override public List getLineLoops() { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/AngleOrderDetectorPlus.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/AngleOrderDetectorPlus.java index 96b41f48e9..f971d0bdd8 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/AngleOrderDetectorPlus.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/AngleOrderDetectorPlus.java @@ -20,13 +20,12 @@ */ package org.biojava.nbio.structure.symmetry.internal; -import static java.lang.Math.*; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.util.RotationAxis; -import org.biojava.nbio.structure.symmetry.internal.OrderDetector; -import org.biojava.nbio.structure.symmetry.internal.RefinerFailedException; + +import static java.lang.Math.PI; +import static java.lang.Math.abs; /** * Guesses an order of rotational symmetry from the angle. @@ -40,9 +39,9 @@ */ public class AngleOrderDetectorPlus implements OrderDetector { - private int maxOrder; + private final int maxOrder; private final double error; - private boolean normalizeError; + private final boolean normalizeError; /** * @param error diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/CESymmParameters.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/CESymmParameters.java index 863826103d..f12bf4ec0d 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/CESymmParameters.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/CESymmParameters.java @@ -20,11 +20,11 @@ */ package org.biojava.nbio.structure.symmetry.internal; +import org.biojava.nbio.structure.align.ce.CeParameters; + import java.util.List; import java.util.Random; -import org.biojava.nbio.structure.align.ce.CeParameters; - /** * Provides parameters to {@link CeSymm}. * @@ -51,12 +51,12 @@ public class CESymmParameters extends CeParameters { private boolean gaps; private int optimizationSteps; - public static enum OrderDetectorMethod { + public enum OrderDetectorMethod { SEQUENCE_FUNCTION, GRAPH_COMPONENT, ANGLE, USER_INPUT; public static final OrderDetectorMethod DEFAULT = SEQUENCE_FUNCTION; } - public static enum RefineMethod { + public enum RefineMethod { NOT_REFINED, SEQUENCE_FUNCTION, GRAPH_COMPONENT; public static final RefineMethod DEFAULT = SEQUENCE_FUNCTION; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/CeSymm.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/CeSymm.java index f81bd25dda..bf75f843a3 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/CeSymm.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/CeSymm.java @@ -20,16 +20,7 @@ */ package org.biojava.nbio.structure.symmetry.internal; -import java.util.ArrayList; -import java.util.List; - -import javax.vecmath.Matrix4d; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIdentifier; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.ce.CECalculator; import org.biojava.nbio.structure.align.ce.CeCPMain; import org.biojava.nbio.structure.align.ce.MatrixListener; @@ -44,6 +35,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.vecmath.Matrix4d; +import java.util.ArrayList; +import java.util.List; + /** * Identify the symmetries in a structure by running an alignment of the * structure against itself disabling the diagonal of the identity alignment. @@ -189,8 +184,8 @@ protected static CeSymmResult align(Atom[] atoms, CESymmParameters params) CECalculator calculator = new CECalculator(params); Matrix lastMatrix = null; - List selfAlignments = new ArrayList(); - AFPChain optimalAFP = null; + List selfAlignments = new ArrayList<>(); + AFPChain optimalAFP; // STEP 2: perform the self-alignments of the structure int i = 0; @@ -270,7 +265,7 @@ protected static CeSymmResult align(Atom[] atoms, CESymmParameters params) // STEP 3: order detection & symmetry refinement, apply consistency try { // ORDER DETECTION - OrderDetector orderDetector = null; + OrderDetector orderDetector; int order = 1; switch (params.getOrderDetectorMethod()) { case USER_INPUT: @@ -424,12 +419,12 @@ public static CeSymmResult analyzeLevel(Atom[] atoms, // STEP 5: symmetry alignment optimization if (result.getParams().getOptimization()) { try { - MultipleAlignment msa = result.getMultipleAlignment(); + MultipleAlignment msa; SymmOptimizer optimizer = new SymmOptimizer(result); msa = optimizer.optimize(); result.setMultipleAlignment(msa); } catch (RefinerFailedException e) { - logger.debug("Optimization failed:" + e.getMessage()); + logger.debug("Optimization failed {}", e.getMessage()); } } } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/CeSymmIterative.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/CeSymmIterative.java index c007319f6e..3362b502df 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/CeSymmIterative.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/CeSymmIterative.java @@ -20,23 +20,9 @@ */ package org.biojava.nbio.structure.symmetry.internal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -import javax.vecmath.Matrix4d; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIdentifier; -import org.biojava.nbio.structure.align.multiple.Block; -import org.biojava.nbio.structure.align.multiple.BlockImpl; -import org.biojava.nbio.structure.align.multiple.BlockSet; -import org.biojava.nbio.structure.align.multiple.BlockSetImpl; -import org.biojava.nbio.structure.align.multiple.MultipleAlignment; -import org.biojava.nbio.structure.align.multiple.MultipleAlignmentImpl; +import org.biojava.nbio.structure.align.multiple.*; import org.biojava.nbio.structure.align.multiple.util.MultipleAlignmentScorer; import org.biojava.nbio.structure.secstruc.SecStrucElement; import org.biojava.nbio.structure.secstruc.SecStrucTools; @@ -45,12 +31,15 @@ import org.biojava.nbio.structure.symmetry.internal.CESymmParameters.SymmetryType; import org.biojava.nbio.structure.symmetry.utils.SymmetryTools; import org.jgrapht.Graph; -import org.jgrapht.alg.ConnectivityInspector; +import org.jgrapht.alg.connectivity.ConnectivityInspector; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.SimpleGraph; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.vecmath.Matrix4d; +import java.util.*; + /** * Iterative version of CeSymm that aims at identifying all symmetry axis of a * structure. @@ -74,9 +63,9 @@ public class CeSymmIterative { private static final Logger logger = LoggerFactory .getLogger(CeSymmIterative.class); - private CESymmParameters params; - private Graph alignGraph; // cumulative - private List levels; // symmetry at each level + private final CESymmParameters params; + private final Graph alignGraph; // cumulative + private final List levels; // symmetry at each level /** * For the iterative algorithm to work properly the refinement and @@ -88,8 +77,8 @@ public class CeSymmIterative { */ public CeSymmIterative(CESymmParameters param) { params = param; - alignGraph = new SimpleGraph(DefaultEdge.class); - levels = new ArrayList(); + alignGraph = new SimpleGraph<>(DefaultEdge.class); + levels = new ArrayList<>(); } /** @@ -218,21 +207,21 @@ private CeSymmResult reconstructSymmResult(Atom[] atoms) // Initialize a new multiple alignment MultipleAlignment msa = new MultipleAlignmentImpl(); - msa.getEnsemble().setAtomArrays(new ArrayList()); + msa.getEnsemble().setAtomArrays(new ArrayList<>()); msa.getEnsemble().setStructureIdentifiers( - new ArrayList()); + new ArrayList<>()); msa.getEnsemble().setAlgorithmName(CeSymm.algorithmName); msa.getEnsemble().setVersion(CeSymm.version); BlockSet bs = new BlockSetImpl(msa); Block b = new BlockImpl(bs); - b.setAlignRes(new ArrayList>()); + b.setAlignRes(new ArrayList<>()); // Calculate the connected groups of the alignment graph - ConnectivityInspector inspector = new ConnectivityInspector( + ConnectivityInspector inspector = new ConnectivityInspector<>( alignGraph); List> comps = inspector.connectedSets(); - List groups = new ArrayList(comps.size()); + List groups = new ArrayList<>(comps.size()); for (Set comp : comps) groups.add(new ResidueGroup(comp)); @@ -241,7 +230,7 @@ private CeSymmResult reconstructSymmResult(Atom[] atoms) for (CeSymmResult sr : levels) order *= sr.getMultipleAlignment().size(); for (int su = 0; su < order; su++) - b.getAlignRes().add(new ArrayList()); + b.getAlignRes().add(new ArrayList<>()); // Construct the resulting MultipleAlignment from ResidueGroups for (ResidueGroup group : groups) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/CeSymmResult.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/CeSymmResult.java index b88ad1e112..b3111e47cd 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/CeSymmResult.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/CeSymmResult.java @@ -20,16 +20,7 @@ */ package org.biojava.nbio.structure.symmetry.internal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.structure.ResidueRange; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIdentifier; -import org.biojava.nbio.structure.SubstructureIdentifier; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.multiple.Block; import org.biojava.nbio.structure.align.multiple.MultipleAlignment; @@ -38,6 +29,10 @@ import org.biojava.nbio.structure.symmetry.internal.CESymmParameters.SymmetryType; import org.biojava.nbio.structure.symmetry.utils.SymmetryTools; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + /** * This Class stores all the relevant information of an internal symmetry result * obtained with CeSymm. The purpose is to carry all the information packed @@ -105,10 +100,10 @@ public List getRepeatsID() throws StructureException { if (!isRefined()) return null; - List repeats = new ArrayList( + List repeats = new ArrayList<>( numRepeats); - String pdbId = structureId.toCanonical().getPdbId(); + String pdbId = structureId.toCanonical().pdbId; Block align = multipleAlignment.getBlocks().get(0); for (int su = 0; su < numRepeats; su++) { @@ -120,7 +115,7 @@ public List getRepeatsID() throws StructureException { ResidueRange range = new ResidueRange(res1.getChainName(), res1, res2); StructureIdentifier id = new SubstructureIdentifier(pdbId, - Arrays.asList(range)); + Collections.singletonList(range)); repeats.add(id); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/GraphComponentOrderDetector.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/GraphComponentOrderDetector.java index f6accbfb96..3b310c8869 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/GraphComponentOrderDetector.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/GraphComponentOrderDetector.java @@ -20,18 +20,18 @@ */ package org.biojava.nbio.structure.symmetry.internal; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.symmetry.utils.SymmetryTools; import org.jgrapht.Graph; -import org.jgrapht.alg.ConnectivityInspector; +import org.jgrapht.alg.connectivity.ConnectivityInspector; import org.jgrapht.graph.DefaultEdge; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + /** * The GraphOrderDetector transforms the self-alignment into a Graph and * extracts its maximally connected Components. @@ -46,8 +46,7 @@ public class GraphComponentOrderDetector implements OrderDetector { @Override - public int calculateOrder(AFPChain selfAlignment, Atom[] ca) - throws RefinerFailedException { + public int calculateOrder(AFPChain selfAlignment, Atom[] ca) { // Construct the alignment graph with jgrapht Graph graph = SymmetryTools @@ -55,11 +54,11 @@ public int calculateOrder(AFPChain selfAlignment, Atom[] ca) // Find the maximally connected components of the graph ConnectivityInspector inspector = - new ConnectivityInspector(graph); + new ConnectivityInspector<>(graph); List> components = inspector.connectedSets(); // The order maximizes the residues aligned - Map counts = new HashMap(); + Map counts = new HashMap<>(); for (Set c : components) { if (counts.containsKey(c.size())) counts.put(c.size(), counts.get(c.size()) + c.size()); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/GraphComponentRefiner.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/GraphComponentRefiner.java index 375d0dd61b..99ef318557 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/GraphComponentRefiner.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/GraphComponentRefiner.java @@ -20,14 +20,6 @@ */ package org.biojava.nbio.structure.symmetry.internal; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -import javax.vecmath.GMatrix; -import javax.vecmath.GVector; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.model.AFPChain; @@ -35,9 +27,16 @@ import org.biojava.nbio.structure.align.util.AlignmentTools; import org.biojava.nbio.structure.symmetry.utils.SymmetryTools; import org.jgrapht.Graph; -import org.jgrapht.alg.ConnectivityInspector; +import org.jgrapht.alg.connectivity.ConnectivityInspector; import org.jgrapht.graph.DefaultEdge; +import javax.vecmath.GMatrix; +import javax.vecmath.GVector; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Set; + /** * The GraphRefiner transforms the self-alignment into a Graph and extracts its * maximally connected Components. It then refines the alignment by combining @@ -63,12 +62,12 @@ public MultipleAlignment refine(AFPChain selfAlignment, Atom[] atoms, int order) .buildSymmetryGraph(selfAlignment); // Find the maximally connected components of the graph - ConnectivityInspector inspector = new ConnectivityInspector( + ConnectivityInspector inspector = new ConnectivityInspector<>( graph); List> components = inspector.connectedSets(); // Filter components with size != order, and transform to ResidueGroups - List groups = new ArrayList(); + List groups = new ArrayList<>(); for (Set comp : components) { if (comp.size() == order) { ResidueGroup group = new ResidueGroup(comp); @@ -103,7 +102,7 @@ public MultipleAlignment refine(AFPChain selfAlignment, Atom[] atoms, int order) } // The compatibility score is the sum of rows of the matrix - List rowScores = new ArrayList(size); + List rowScores = new ArrayList<>(size); for (int i = 0; i < size; i++) { GVector row = new GVector(size); matrix.getRow(i, row); @@ -113,9 +112,9 @@ public MultipleAlignment refine(AFPChain selfAlignment, Atom[] atoms, int order) } // Refined multiple alignment Block as a result - List> alignRes = new ArrayList>(order); + List> alignRes = new ArrayList<>(order); for (int i = 0; i < order; i++) - alignRes.add(new ArrayList()); + alignRes.add(new ArrayList<>()); // Iterate until no more groups left to add (all groups score 0) while (true) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/OrderDetector.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/OrderDetector.java index a33c3b575f..36e448e37c 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/OrderDetector.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/OrderDetector.java @@ -33,7 +33,7 @@ */ public interface OrderDetector { - public int calculateOrder(AFPChain afpChain, Atom[] ca) + int calculateOrder(AFPChain afpChain, Atom[] ca) throws RefinerFailedException; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/ResidueGroup.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/ResidueGroup.java index 2fb0b0e64e..a9e1bcdeb5 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/ResidueGroup.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/ResidueGroup.java @@ -48,7 +48,7 @@ public class ResidueGroup { */ public ResidueGroup(Set component) { // Transform component into sorted List of residues - residues = new ArrayList(component); + residues = new ArrayList<>(component); Collections.sort(residues); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/SequenceFunctionOrderDetector.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/SequenceFunctionOrderDetector.java index eb34659b5d..1d9e05b031 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/SequenceFunctionOrderDetector.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/SequenceFunctionOrderDetector.java @@ -20,13 +20,13 @@ */ package org.biojava.nbio.structure.symmetry.internal; -import java.util.Map; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.util.AlignmentTools; +import java.util.Map; + /** * Calls Spencer's method for determining order. * This method uses the sequence alignment information @@ -56,7 +56,7 @@ public int calculateOrder(AFPChain afpChain, Atom[] ca) AlignmentTools.alignmentAsMap(afpChain); return AlignmentTools.getSymmetryOrder(alignment, - new AlignmentTools.IdentityMap(), + new AlignmentTools.IdentityMap<>(), maxSymmetry, minimumMetricChange); } catch (StructureException e) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/SequenceFunctionRefiner.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/SequenceFunctionRefiner.java index 9635debb05..2272406d5d 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/SequenceFunctionRefiner.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/SequenceFunctionRefiner.java @@ -20,15 +20,6 @@ */ package org.biojava.nbio.structure.symmetry.internal; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.NavigableSet; -import java.util.TreeSet; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.model.AFPChain; @@ -36,6 +27,8 @@ import org.biojava.nbio.structure.align.util.AlignmentTools; import org.biojava.nbio.structure.symmetry.utils.SymmetryTools; +import java.util.*; + /** * Creates a refined alignment with the CE-Symm alternative self-alignment. * Needs the order of symmetry and assumes that the last repeat aligns @@ -103,9 +96,8 @@ public static AFPChain refineSymmetry(AFPChain afpChain, Atom[] ca1, Atom[] ca2, * @param alignment The input alignment, as a map. This will be modified. * @param k Symmetry order. This can be guessed by {@link CeSymm#getSymmetryOrder(AFPChain)} * @return A modified map with the refined alignment - * @throws StructureException */ - public static Map refineSymmetry(Map alignment,int k) throws StructureException { + public static Map refineSymmetry(Map alignment,int k) { // Store scores Map scores = null; @@ -117,8 +109,8 @@ public static Map refineSymmetry(Map alignme // 2. f^K-1(x) is defined // 3. score(f^K-1(x))>0 - TreeSet forwardLoops = new TreeSet(); - TreeSet backwardLoops = new TreeSet(); + TreeSet forwardLoops = new TreeSet<>(); + TreeSet backwardLoops = new TreeSet<>(); List eligible = null; @@ -184,9 +176,10 @@ public static Map refineSymmetry(Map alignme if (scores.size() != virginScores.size()) { System.out.println("Size missmatch"); } else { - for (Integer key : scores.keySet()) { - if (!virginScores.containsKey(key) || !scores.get(key).equals(virginScores.get(key))) { - System.out.format("Mismatch %d -> %f/%f%n", key, scores.get(key), virginScores.get(key)); + for (Map.Entry entry : scores.entrySet()) { + Integer key = entry.getKey(); + if (!virginScores.containsKey(key) || !entry.getValue().equals(virginScores.get(key))) { + System.out.format("Mismatch %d -> %f/%f%n", key, entry.getValue(), virginScores.get(key)); } } } @@ -240,7 +233,7 @@ private static List initializeEligible(Map alignment, // Assume all residues are eligible to start if(eligible == null) { - eligible = new LinkedList(alignment.keySet()); + eligible = new LinkedList<>(alignment.keySet()); } // Precalculate f^K-1(x) @@ -334,8 +327,8 @@ private static List initializeEligible(Map alignment, private static Map applyAlignmentAndCheckCycles(Map alignmentMap, int k, List eligible) { // Convert to lists to establish a fixed order (avoid concurrent modification) - List preimage = new ArrayList(alignmentMap.keySet()); // currently unmodified - List image = new ArrayList(preimage); + List preimage = new ArrayList<>(alignmentMap.keySet()); // currently unmodified + List image = new ArrayList<>(preimage); for (int n = 1; n <= k; n++) { // apply alignment @@ -351,7 +344,7 @@ private static Map applyAlignmentAndCheckCycles(Map imageMap = new HashMap(alignmentMap.size()); + Map imageMap = new HashMap<>(alignmentMap.size()); // now populate with actual values for (int i = 0; i < preimage.size(); i++) { @@ -372,7 +365,7 @@ private static Map applyAlignmentAndCheckCycles(Map initializeScores(Map alignment, Map scores, int k) { if(scores == null) { - scores = new HashMap(alignment.size()); + scores = new HashMap<>(alignment.size()); } else { scores.clear(); } @@ -444,7 +437,7 @@ private static AFPChain partitionAFPchain(AFPChain afpChain, int repeatLen = afpChain.getOptLength()/order; //Extract all the residues considered in the first chain of the alignment - List alignedRes = new ArrayList(); + List alignedRes = new ArrayList<>(); for (int su=0; su(); - lengthHistory = new ArrayList(); - rmsdHistory = new ArrayList(); - mcScoreHistory = new ArrayList(); - tmScoreHistory = new ArrayList(); + timeHistory = new ArrayList<>(); + lengthHistory = new ArrayList<>(); + rmsdHistory = new ArrayList<>(); + mcScoreHistory = new ArrayList<>(); + tmScoreHistory = new ArrayList<>(); C = 20 * order; // Initialize alignment variables block = msa.getBlock(0).getAlignRes(); - freePool = new ArrayList(); + freePool = new ArrayList<>(); length = block.get(0).size(); // Store the residues aligned in the block - List aligned = new ArrayList(); + List aligned = new ArrayList<>(); for (int su = 0; su < order; su++) aligned.addAll(block.get(su)); @@ -196,12 +196,10 @@ public MultipleAlignment optimize() throws StructureException, initialize(); // Save the optimal alignment - List> optBlock = new ArrayList>(); - List optFreePool = new ArrayList(); - optFreePool.addAll(freePool); + List> optBlock = new ArrayList<>(); + List optFreePool = new ArrayList<>(freePool); for (int k = 0; k < order; k++) { - List b = new ArrayList(); - b.addAll(block.get(k)); + List b = new ArrayList<>(block.get(k)); optBlock.add(b); } double optScore = mcScore; @@ -214,12 +212,10 @@ public MultipleAlignment optimize() throws StructureException, while (i < maxIter && conv < stepsToConverge) { // Save the state of the system - List> lastBlock = new ArrayList>(); - List lastFreePool = new ArrayList(); - lastFreePool.addAll(freePool); + List> lastBlock = new ArrayList<>(); + List lastFreePool = new ArrayList<>(freePool); for (int k = 0; k < order; k++) { - List b = new ArrayList(); - b.addAll(block.get(k)); + List b = new ArrayList<>(block.get(k)); lastBlock.add(b); } double lastScore = mcScore; @@ -281,12 +277,10 @@ public MultipleAlignment optimize() throws StructureException, // Store as the optimal alignment if better if (mcScore > optScore) { - optBlock = new ArrayList>(); - optFreePool = new ArrayList(); - optFreePool.addAll(freePool); + optBlock = new ArrayList<>(); + optFreePool = new ArrayList<>(freePool); for (int k = 0; k < order; k++) { - List b = new ArrayList(); - b.addAll(block.get(k)); + List b = new ArrayList<>(block.get(k)); optBlock.add(b); } optScore = mcScore; @@ -366,7 +360,7 @@ private void updateMultipleAlignment() throws StructureException, */ private boolean checkGaps() { - List shrinkColumns = new ArrayList(); + List shrinkColumns = new ArrayList<>(); // Loop for each column for (int res = 0; res < length; res++) { int gapCount = 0; @@ -842,12 +836,12 @@ private void saveHistory(String folder) throws IOException { writer.append("Step,Time,RepeatLength,RMSD,TMscore,MCscore\n"); for (int i = 0; i < lengthHistory.size(); i++) { - writer.append(i * saveStep + ","); - writer.append(timeHistory.get(i) + ","); - writer.append(lengthHistory.get(i) + ","); - writer.append(rmsdHistory.get(i) + ","); - writer.append(tmScoreHistory.get(i) + ","); - writer.append(mcScoreHistory.get(i) + "\n"); + writer.append(String.valueOf(i * saveStep)).append(","); + writer.append(String.valueOf(timeHistory.get(i))).append(","); + writer.append(String.valueOf(lengthHistory.get(i))).append(","); + writer.append(String.valueOf(rmsdHistory.get(i))).append(","); + writer.append(String.valueOf(tmScoreHistory.get(i))).append(","); + writer.append(String.valueOf(mcScoreHistory.get(i))).append("\n"); } writer.flush(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/SymmetryAxes.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/SymmetryAxes.java index fcf9ff29d0..6f69aef4b9 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/SymmetryAxes.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/SymmetryAxes.java @@ -20,17 +20,16 @@ */ package org.biojava.nbio.structure.symmetry.internal; +import org.biojava.nbio.structure.align.multiple.MultipleAlignment; +import org.biojava.nbio.structure.align.util.RotationAxis; +import org.biojava.nbio.structure.symmetry.internal.CESymmParameters.SymmetryType; + +import javax.vecmath.Matrix4d; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; -import javax.vecmath.Matrix4d; - -import org.biojava.nbio.structure.align.multiple.MultipleAlignment; -import org.biojava.nbio.structure.align.util.RotationAxis; -import org.biojava.nbio.structure.symmetry.internal.CESymmParameters.SymmetryType; - /** * Data Structure that stores all the symmetry axis that describe * the symmetry of a structure. Generalizes to all types of symmetry, @@ -75,8 +74,8 @@ public class SymmetryAxes { */ public static class Axis { private Matrix4d operator; - private int order; - private SymmetryType symmType; + private final int order; + private final SymmetryType symmType; private int level; //private int indexInLevel; private int firstRepeat; @@ -261,7 +260,7 @@ public void updateAxis(Integer index, Matrix4d newAxis){ * @return axes elementary axes of symmetry. */ public List getElementaryAxes(){ - List ops = new ArrayList(getNumLevels()); + List ops = new ArrayList<>(getNumLevels()); for(Axis axis : axes) { ops.add(axis.getOperator()); } @@ -541,7 +540,7 @@ private int getNumRepeats(int level) { * @return List of first Repeats of each index, sorted in ascending order */ public List getFirstRepeats(int level) { - List firstRepeats = new ArrayList(); + List firstRepeats = new ArrayList<>(); int m = getNumRepeats(level+1); //size of the level int d = axes.get(level).getOrder(); //degree of this level int n = m*d; // number of repeats included in each axis diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/SymmetryRefiner.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/SymmetryRefiner.java index c21f51b30f..e16a72206a 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/SymmetryRefiner.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/SymmetryRefiner.java @@ -48,7 +48,7 @@ public interface SymmetryRefiner { * @throws RefinerFailedException * @throws StructureException */ - public MultipleAlignment refine(AFPChain selfAlignment, Atom[] atoms, int order) + MultipleAlignment refine(AFPChain selfAlignment, Atom[] atoms, int order) throws RefinerFailedException, StructureException; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/misc/ChainSignature.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/misc/ChainSignature.java index e60a507bce..96f717a1c1 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/misc/ChainSignature.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/misc/ChainSignature.java @@ -23,10 +23,10 @@ import java.util.List; public class ChainSignature implements Comparable { - private int chainCount = 0; - private String representative = ""; + private final int chainCount; + private final String representative; private String compositionId = ""; - private List chainIds = null; + private final List chainIds; public ChainSignature(String representative, int chainCount, List chainIds) { this.representative = representative; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/misc/ProteinComplexSignature.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/misc/ProteinComplexSignature.java index 492e1485e1..9f6ac18721 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/misc/ProteinComplexSignature.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/misc/ProteinComplexSignature.java @@ -26,10 +26,10 @@ import java.util.Map.Entry; public class ProteinComplexSignature { - private BlastClustReader blastClust = null; - private String pdbId = ""; - private List chainIds = null; - private List chainSignatures = new ArrayList(); + private final BlastClustReader blastClust; + private final String pdbId; + private final List chainIds; + private final List chainSignatures = new ArrayList<>(); public ProteinComplexSignature(String pdbId, List chainIds, BlastClustReader blastClust) { @@ -75,15 +75,15 @@ public int getSubunitTypeCount() { private List getChainSignatures() { String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - Map mapCounts = new TreeMap(); - Map> mapChainIds = new TreeMap>(); + Map mapCounts = new TreeMap<>(); + Map> mapChainIds = new TreeMap<>(); for (String chainId: chainIds) { String rep = blastClust.getRepresentativeChain(pdbId, chainId); Integer value = mapCounts.get(rep); if (value == null) { mapCounts.put(rep, 1); - List list = new ArrayList(); + List list = new ArrayList<>(); list.add(chainId); mapChainIds.put(rep, list); } else { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/utils/BlastClustReader.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/utils/BlastClustReader.java index a0653c2055..fb5975c0d7 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/utils/BlastClustReader.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/utils/BlastClustReader.java @@ -23,11 +23,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Serializable; +import java.io.*; import java.net.URL; import java.util.*; @@ -38,8 +34,8 @@ public class BlastClustReader implements Serializable { private static final Logger logger = LoggerFactory.getLogger(BlastClustReader.class); - private int sequenceIdentity = 0; - private List> clusters = new ArrayList<>(); + private final int sequenceIdentity; + private final List> clusters = new ArrayList<>(); // https://cdn.rcsb.org/resources/sequence/clusters/bc-95.out private static final String coreUrl = "https://cdn.rcsb.org/resources/sequence/clusters/"; @@ -102,7 +98,7 @@ public List> getPdbChainIdClusters(String pdbId) { loadClusters(sequenceIdentity); String pdbIdUpper = pdbId.toUpperCase(); - List> matches = new ArrayList>(); + List> matches = new ArrayList<>(); for (List cluster: clusters) { for (String chainId: cluster) { if (chainId.startsWith(pdbIdUpper)) { @@ -117,14 +113,14 @@ public List> getPdbChainIdClusters(String pdbId) { public List> getChainIdsInEntry(String pdbId) { loadClusters(sequenceIdentity); - List> matches = new ArrayList>(); + List> matches = new ArrayList<>(); List match = null; for (List cluster: clusters) { for (String chainId: cluster) { if (chainId.startsWith(pdbId)) { if (match == null) { - match = new ArrayList(); + match = new ArrayList<>(); } match.add(chainId.substring(5)); } @@ -159,11 +155,10 @@ private void loadClusters(int sequenceIdentity) { if (stream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); - String line = null; + String line; while ((line = reader.readLine()) != null) { line = line.replaceAll("_", "."); - List cluster = Arrays.asList(line.split(" ")); - clusters.add(cluster); + clusters.add(Arrays.asList(line.split(" "))); } reader.close(); stream.close(); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/utils/PermutationGenerator.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/utils/PermutationGenerator.java index 5a8a778017..2a23cb5ab5 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/utils/PermutationGenerator.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/utils/PermutationGenerator.java @@ -34,9 +34,9 @@ public class PermutationGenerator { // http://www.merriampark.com/perm.htm // The PermutationGenerator Java class systematically generates permutations. It relies on the fact that any set with n elements can be placed in one-to-one correspondence with the set {1, 2, 3, ..., n}. The algorithm is described by Kenneth H. Rosen, Discrete Mathematics and Its Applications, 2nd edition (NY: McGraw-Hill, 1991), pp. 282-284. - private int[] a; + private final int[] a; private BigInteger numLeft; - private BigInteger total; + private final BigInteger total; //----------------------------------------------------------- // Constructor. WARNING: Don't make n too large. diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/utils/PowerSet.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/utils/PowerSet.java index 10b5652ea1..03bae032f2 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/utils/PowerSet.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/utils/PowerSet.java @@ -20,13 +20,13 @@ */ package org.biojava.nbio.structure.symmetry.utils; +import org.biojava.nbio.structure.symmetry.core.QuatSymmetryDetector; + import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; -import org.biojava.nbio.structure.symmetry.core.QuatSymmetryDetector; - /** * In mathematics, the power set (or powerset) of any set S, written P(S), is * the set of all subsets of S, including the empty set and S itself. @@ -52,16 +52,16 @@ public PowerSet() { * @return the set of power Sets of the original Set */ public Set> powerSet(Set originalSet) { - Set> sets = new LinkedHashSet>(); + Set> sets = new LinkedHashSet<>(); if (originalSet.isEmpty()) { - sets.add(new LinkedHashSet()); + sets.add(new LinkedHashSet<>()); return sets; } - List list = new ArrayList(originalSet); + List list = new ArrayList<>(originalSet); T head = list.get(0); - Set rest = new LinkedHashSet(list.subList(1, list.size())); + Set rest = new LinkedHashSet<>(list.subList(1, list.size())); for (Set set : powerSet(rest)) { - Set newSet = new LinkedHashSet(); + Set newSet = new LinkedHashSet<>(); newSet.add(head); newSet.addAll(set); sets.add(newSet); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/utils/SymmetryTools.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/utils/SymmetryTools.java index 3cac9be3f1..75283deba8 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/utils/SymmetryTools.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/utils/SymmetryTools.java @@ -20,37 +20,11 @@ */ package org.biojava.nbio.structure.symmetry.utils; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; -import java.util.stream.Collectors; - -import javax.vecmath.Matrix4d; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Calc; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.GroupType; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIdentifier; -import org.biojava.nbio.structure.StructureImpl; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.ce.CECalculator; import org.biojava.nbio.structure.align.helper.AlignUtils; import org.biojava.nbio.structure.align.model.AFPChain; -import org.biojava.nbio.structure.align.multiple.Block; -import org.biojava.nbio.structure.align.multiple.BlockImpl; -import org.biojava.nbio.structure.align.multiple.BlockSet; -import org.biojava.nbio.structure.align.multiple.BlockSetImpl; -import org.biojava.nbio.structure.align.multiple.MultipleAlignment; -import org.biojava.nbio.structure.align.multiple.MultipleAlignmentEnsemble; -import org.biojava.nbio.structure.align.multiple.MultipleAlignmentEnsembleImpl; -import org.biojava.nbio.structure.align.multiple.MultipleAlignmentImpl; +import org.biojava.nbio.structure.align.multiple.*; import org.biojava.nbio.structure.align.multiple.util.CoreSuperimposer; import org.biojava.nbio.structure.align.multiple.util.MultipleAlignmentScorer; import org.biojava.nbio.structure.align.multiple.util.MultipleSuperimposer; @@ -70,6 +44,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.vecmath.Matrix4d; +import java.util.*; +import java.util.stream.Collectors; + /** * Utility methods for symmetry (quaternary and internal) detection and result * manipulation. @@ -443,17 +421,17 @@ public static double getAngle(AFPChain afpChain, Atom[] ca1, Atom[] ca2) { public static List> buildSymmetryGraph(List afps, Atom[] atoms, boolean undirected) { - List> graph = new ArrayList>(); + List> graph = new ArrayList<>(); for (int n = 0; n < atoms.length; n++) { - graph.add(new ArrayList()); + graph.add(new ArrayList<>()); } for (int k = 0; k < afps.size(); k++) { for (int i = 0; i < afps.get(k).getOptAln().length; i++) { for (int j = 0; j < afps.get(k).getOptAln()[i][0].length; j++) { - Integer res1 = afps.get(k).getOptAln()[i][0][j]; - Integer res2 = afps.get(k).getOptAln()[i][1][j]; + int res1 = afps.get(k).getOptAln()[i][0][j]; + int res2 = afps.get(k).getOptAln()[i][1][j]; graph.get(res1).add(res2); if (undirected) graph.get(res2).add(res1); @@ -476,7 +454,7 @@ public static List> buildSymmetryGraph(List afps, public static Graph buildSymmetryGraph( AFPChain selfAlignment) { - Graph graph = new SimpleGraph( + Graph graph = new SimpleGraph<>( DefaultEdge.class); for (int i = 0; i < selfAlignment.getOptAln().length; i++) { @@ -512,13 +490,13 @@ public static List divideStructure(CeSymmResult symmetry) Atom[] atoms = symmetry.getAtoms(); Set allGroups = StructureTools.getAllGroupsFromSubset(atoms, GroupType.HETATM); List repeatsId = symmetry.getRepeatsID(); - List repeats = new ArrayList(order); + List repeats = new ArrayList<>(order); // Create new structure containing the repeat atoms for (int i = 0; i < order; i++) { Structure s = new StructureImpl(); - s.addModel(new ArrayList(1)); + s.addModel(new ArrayList<>(1)); s.setStructureIdentifier(repeatsId.get(i)); Block align = symmetry.getMultipleAlignment().getBlock(0); @@ -542,7 +520,7 @@ public static List divideStructure(CeSymmResult symmetry) List ligands = StructureTools.getLigandsByProximity( allGroups, - repeat.toArray(new Atom[repeat.size()]), + repeat.toArray(Atom.EmptyAtomArray), StructureTools.DEFAULT_LIGAND_PROXIMITY_CUTOFF); logger.warn("Adding {} ligands to {}",ligands.size(), symmetry.getMultipleAlignment().getStructureIdentifier(i)); @@ -613,7 +591,7 @@ public static MultipleAlignment toRepeatsAlignment(CeSymmResult result) MultipleAlignment repeats = newEnsemble.getMultipleAlignment(0); Block block = repeats.getBlock(0); - List atomArrays = new ArrayList(); + List atomArrays = new ArrayList<>(); for (Structure s : repSt) atomArrays.add(StructureTools.getRepresentativeAtomArray(s)); @@ -621,7 +599,7 @@ public static MultipleAlignment toRepeatsAlignment(CeSymmResult result) newEnsemble.setAtomArrays(atomArrays); for (int su = 0; su < block.size(); su++) { - Integer start = block.getStartResidue(su); + int start = block.getStartResidue(su); // Normalize aligned residues for (int res = 0; res < block.length(); res++) { @@ -658,7 +636,7 @@ public static MultipleAlignment fromAFP(AFPChain symm, Atom[] atoms) MultipleAlignmentEnsemble e = new MultipleAlignmentEnsembleImpl(symm, atoms, atoms, false); - e.setAtomArrays(new ArrayList()); + e.setAtomArrays(new ArrayList<>()); StructureIdentifier name = null; if (e.getStructureIdentifiers() != null) { if (!e.getStructureIdentifiers().isEmpty()) @@ -667,12 +645,12 @@ public static MultipleAlignment fromAFP(AFPChain symm, Atom[] atoms) name = atoms[0].getGroup().getChain().getStructure() .getStructureIdentifier(); - e.setStructureIdentifiers(new ArrayList()); + e.setStructureIdentifiers(new ArrayList<>()); MultipleAlignment result = new MultipleAlignmentImpl(); BlockSet bs = new BlockSetImpl(result); Block b = new BlockImpl(bs); - b.setAlignRes(new ArrayList>()); + b.setAlignRes(new ArrayList<>()); int order = symm.getBlockNum(); for (int su = 0; su < order; su++) { @@ -737,7 +715,7 @@ public static QuatSymmetryResults getQuaternarySymmetry(CeSymmResult result) */ public static List getGroups(Atom[] rAtoms) { - List groups = new ArrayList(rAtoms.length); + List groups = new ArrayList<>(rAtoms.length); for (Atom a : rAtoms) { Group g = a.getGroup(); @@ -774,8 +752,8 @@ public static void updateSymmetryTransformation(SymmetryAxes axes, for (int level = 0; level < axes.getNumLevels(); level++) { // Calculate the aligned atom arrays to superimpose - List list1 = new ArrayList(); - List list2 = new ArrayList(); + List list1 = new ArrayList<>(); + List list2 = new ArrayList<>(); for (int firstRepeat : axes.getFirstRepeats(level)) { @@ -805,8 +783,8 @@ public static void updateSymmetryTransformation(SymmetryAxes axes, } } - Atom[] arr1 = list1.toArray(new Atom[list1.size()]); - Atom[] arr2 = list2.toArray(new Atom[list2.size()]); + Atom[] arr1 = list1.toArray(Atom.EmptyAtomArray); + Atom[] arr2 = list2.toArray(Atom.EmptyAtomArray); // Calculate the new transformation information if (arr1.length > 0 && arr2.length > 0) { @@ -817,7 +795,7 @@ public static void updateSymmetryTransformation(SymmetryAxes axes, } // Get the transformations from the SymmetryAxes - List transformations = new ArrayList(); + List transformations = new ArrayList<>(); for (int su = 0; su < msa.size(); su++) { transformations.add(axes.getRepeatTransform(su)); } @@ -866,13 +844,13 @@ public static Atom[] getRepresentativeAtoms(Structure structure) { else { // Get Atoms of all models - List atomList = new ArrayList(); + List atomList = new ArrayList<>(); for (int m = 0; m < structure.nrModels(); m++) { for (Chain c : structure.getModel(m)) atomList.addAll(Arrays.asList(StructureTools .getRepresentativeAtomArray(c))); } - return atomList.toArray(new Atom[0]); + return atomList.toArray(Atom.EmptyAtomArray); } } @@ -888,7 +866,7 @@ public static Atom[] getRepresentativeAtoms(Structure structure) { */ public static List getValidFolds(List stoichiometry) { - List denominators = new ArrayList(); + List denominators = new ArrayList<>(); if (stoichiometry.isEmpty()) return denominators; @@ -896,7 +874,7 @@ public static List getValidFolds(List stoichiometry) { int nChains = Collections.max(stoichiometry); // Remove duplicate stoichiometries - Set nominators = new TreeSet(stoichiometry); + Set nominators = new TreeSet<>(stoichiometry); // find common denominators for (int d = 1; d <= nChains; d++) { diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/validation/ModelledSubgroup.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/validation/ModelledSubgroup.java index 310bb9e1af..19d5d307e0 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/validation/ModelledSubgroup.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/validation/ModelledSubgroup.java @@ -204,7 +204,7 @@ public class ModelledSubgroup { */ public List getAngleOutlier() { if (angleOutlier == null) { - angleOutlier = new ArrayList(); + angleOutlier = new ArrayList<>(); } return this.angleOutlier; } @@ -233,7 +233,7 @@ public List getAngleOutlier() { */ public List getClash() { if (clash == null) { - clash = new ArrayList(); + clash = new ArrayList<>(); } return this.clash; } @@ -262,7 +262,7 @@ public List getClash() { */ public List getBondOutlier() { if (bondOutlier == null) { - bondOutlier = new ArrayList(); + bondOutlier = new ArrayList<>(); } return this.bondOutlier; } @@ -291,7 +291,7 @@ public List getBondOutlier() { */ public List getMogAngleOutlier() { if (mogAngleOutlier == null) { - mogAngleOutlier = new ArrayList(); + mogAngleOutlier = new ArrayList<>(); } return this.mogAngleOutlier; } @@ -320,7 +320,7 @@ public List getMogAngleOutlier() { */ public List getSymmClash() { if (symmClash == null) { - symmClash = new ArrayList(); + symmClash = new ArrayList<>(); } return this.symmClash; } @@ -349,7 +349,7 @@ public List getSymmClash() { */ public List getMogBondOutlier() { if (mogBondOutlier == null) { - mogBondOutlier = new ArrayList(); + mogBondOutlier = new ArrayList<>(); } return this.mogBondOutlier; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/validation/Programs.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/validation/Programs.java index afd4ac4876..f6bdb256f6 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/validation/Programs.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/validation/Programs.java @@ -86,7 +86,7 @@ public class Programs { */ public List getProgram() { if (program == null) { - program = new ArrayList(); + program = new ArrayList<>(); } return this.program; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/validation/WwPDBValidationInformation.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/validation/WwPDBValidationInformation.java index 85585a9770..3a2a043b48 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/validation/WwPDBValidationInformation.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/validation/WwPDBValidationInformation.java @@ -29,7 +29,6 @@ package org.biojava.nbio.structure.validation; import javax.xml.bind.annotation.*; - import java.io.Serializable; import java.util.ArrayList; import java.util.List; @@ -122,7 +121,7 @@ public void setEntry(Entry value) { */ public List getModelledSubgroup() { if (modelledSubgroup == null) { - modelledSubgroup = new ArrayList(); + modelledSubgroup = new ArrayList<>(); } return this.modelledSubgroup; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/BravaisLattice.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/BravaisLattice.java index 02efe5be5a..7585053c02 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/BravaisLattice.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/BravaisLattice.java @@ -38,12 +38,12 @@ public enum BravaisLattice { HEXAGONAL (6, "HEXAGONAL", new CrystalCell(1.00,1.00,1.25, 90,90,120)),// a=b!=c, alpha=beta=90, gamma=120 CUBIC (7, "CUBIC", new CrystalCell(1.00,1.00,1.00, 90,90,90)); // a=b=c, alpha=beta=gamma=90 - private static HashMap name2bl = initname2bl(); - private String name; - private int id; - private CrystalCell exampleUnitCell; + private static final HashMap name2bl = initname2bl(); + private final String name; + private final int id; + private final CrystalCell exampleUnitCell; - private BravaisLattice(int id, String name, CrystalCell exampleUnitCell) { + BravaisLattice(int id, String name, CrystalCell exampleUnitCell) { this.name = name; this.id = id; this.exampleUnitCell = exampleUnitCell; @@ -62,7 +62,7 @@ public CrystalCell getExampleUnitCell() { } private static HashMap initname2bl(){ - HashMap name2bl = new HashMap(); + HashMap name2bl = new HashMap<>(); for (BravaisLattice bl:BravaisLattice.values()) { name2bl.put(bl.getName(), bl); } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/CrystalBuilder.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/CrystalBuilder.java index 2bc6806b77..07836e405d 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/CrystalBuilder.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/CrystalBuilder.java @@ -78,10 +78,10 @@ public class CrystalBuilder { */ private static final boolean INCLUDE_HETATOMS = true; - private Structure structure; - private PDBCrystallographicInfo crystallographicInfo; - private int numPolyChainsAu; - private int numOperatorsSg; + private final Structure structure; + private final PDBCrystallographicInfo crystallographicInfo; + private final int numPolyChainsAu; + private final int numOperatorsSg; private Map chainNcsOps = null; private Map chainOrigNames = null; @@ -93,7 +93,7 @@ public class CrystalBuilder { private Map> visitedNcsChainPairs = null; private boolean searchBeyondAU; - private Matrix4d[] ops; + private final Matrix4d[] ops; /** * Special constructor for NCS-aware CrystalBuilder. @@ -256,7 +256,7 @@ private void calcInterfacesCrystal(StructureInterfaceList set, double cutoff) { // initialising debugging vars long start = -1; - long end = -1; + long end; int trialCount = 0; int skippedRedundant = 0; int skippedAUsNoOverlap = 0; @@ -264,7 +264,7 @@ private void calcInterfacesCrystal(StructureInterfaceList set, double cutoff) { int skippedSelfEquivalent = 0; // The bounding boxes of all AUs of the unit cell - UnitCellBoundingBox bbGrid = new UnitCellBoundingBox(numOperatorsSg, numPolyChainsAu);; + UnitCellBoundingBox bbGrid = new UnitCellBoundingBox(numOperatorsSg, numPolyChainsAu); // we calculate all the bounds of each of the asym units, those will then be reused and translated bbGrid.setBbs(structure, ops, INCLUDE_HETATOMS); @@ -390,11 +390,11 @@ private void calcInterfacesCrystal(StructureInterfaceList set, double cutoff) { if( verbose ) { if (a==0 && b==0 && c==0 && n==0) - builder.append(" "+contactsFound+"("+(numPolyChainsAu*(numPolyChainsAu-1))/2+")"); + builder.append(" ").append(contactsFound).append("(").append((numPolyChainsAu * (numPolyChainsAu - 1)) / 2).append(")"); else if (selfEquivalent) - builder.append(" "+contactsFound+"("+(numPolyChainsAu*(numPolyChainsAu+1))/2+")"); + builder.append(" ").append(contactsFound).append("(").append((numPolyChainsAu * (numPolyChainsAu + 1)) / 2).append(")"); else - builder.append(" "+contactsFound+"("+numPolyChainsAu*numPolyChainsAu+")"); + builder.append(" ").append(contactsFound).append("(").append(numPolyChainsAu * numPolyChainsAu).append(")"); logger.debug(builder.toString()); } @@ -466,8 +466,7 @@ private StructureInterface findNcsRef(StructureInterface interf) { // same original chain names Optional matchDirect = - visitedNcsChainPairs.computeIfAbsent(matchChainIdsIJ, k-> new HashMap<>()).entrySet().stream(). - map(r->r.getKey()). + visitedNcsChainPairs.computeIfAbsent(matchChainIdsIJ, k-> new HashMap<>()).keySet().stream(). filter(r->r.epsilonEquals(j2iNcsOrigin,0.01)). findFirst(); @@ -477,8 +476,7 @@ private StructureInterface findNcsRef(StructureInterface interf) { if(matchMatrix == null) { // reversed original chain names with inverted transform Optional matchInverse = - visitedNcsChainPairs.computeIfAbsent(matchChainIdsJI, k-> new HashMap<>()).entrySet().stream(). - map(r->r.getKey()). + visitedNcsChainPairs.computeIfAbsent(matchChainIdsJI, k-> new HashMap<>()).keySet().stream(). filter(r->r.epsilonEquals(i2jNcsOrigin,0.01)). findFirst(); matchMatrix = matchInverse.orElse(null); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/CrystalCell.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/CrystalCell.java index 3850c0b87b..e5d1478435 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/CrystalCell.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/CrystalCell.java @@ -488,7 +488,7 @@ public double getMaxDimension() { Point3d vert7 = new Point3d(1,1,1); transfToOrthonormal(vert7); - ArrayList vertDists = new ArrayList(); + ArrayList vertDists = new ArrayList<>(); vertDists.add(vert0.distance(vert7)); vertDists.add(vert3.distance(vert4)); vertDists.add(vert1.distance(vert6)); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/CrystalTransform.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/CrystalTransform.java index df3938fca6..93ecaf2766 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/CrystalTransform.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/CrystalTransform.java @@ -72,7 +72,7 @@ public class CrystalTransform implements Serializable { /** * The crystal translation (always integer) */ - private Point3i crystalTranslation; + private final Point3i crystalTranslation; /** @@ -467,7 +467,7 @@ public static Vector3d getTranslScrewComponent(Matrix4d m) { // For reference see: // http://www.crystallography.fr/mathcryst/pdf/Gargnano/Aroyo_Gargnano_1.pdf - Vector3d transl = null; + Vector3d transl; Matrix3d W = new Matrix3d(m.m00,m.m01,m.m02, diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/SpaceGroup.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/SpaceGroup.java index e2e713c023..4ac9ba66b5 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/SpaceGroup.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/SpaceGroup.java @@ -37,7 +37,6 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.Serializable; @@ -103,8 +102,8 @@ public SpaceGroup(int id, int multiplicity, int primitiveMultiplicity, String sh this.primitiveMultiplicity = primitiveMultiplicity; this.shortSymbol = shortSymbol; this.altShortSymbol = altShortSymbol; - transformations = new ArrayList(multiplicity); - transfAlgebraic = new ArrayList(multiplicity); + transformations = new ArrayList<>(multiplicity); + transfAlgebraic = new ArrayList<>(multiplicity); cellTranslations = new Vector3d[multiplicity/primitiveMultiplicity]; this.bravLattice = bravLattice; } @@ -188,7 +187,7 @@ public static Matrix4d getMatrixFromAlgebraic(String transfAlgebraic) { } private static double[] convertAlgebraicStrToCoefficients(String algString) { - String letters = null; + String letters; String noLetters = null; Matcher m = splitPat1.matcher(algString); if (m.matches()) { @@ -215,12 +214,16 @@ private static double[] convertAlgebraicStrToCoefficients(String algString) { s = -1.0; } String coord = m.group(2); - if (coord.equals("X")) { - coefficients[0] = s; - } else if (coord.equals("Y")) { - coefficients[1] = s; - } else if (coord.equals("Z")) { - coefficients[2] = s; + switch (coord) { + case "X": + coefficients[0] = s; + break; + case "Y": + coefficients[1] = s; + break; + case "Z": + coefficients[2] = s; + break; } } if (noLetters!=null) { @@ -272,7 +275,7 @@ public String getAltShortSymbol() { * @return */ public List getTransformations() { - List transfs = new ArrayList(); + List transfs = new ArrayList<>(); for (int i=1;i getTransfAlgebraic() { public void setTransfAlgebraic(List transfAlgebraic) { //System.out.println("setting transfAlgebraic " + transfAlgebraic); if ( transformations == null || transformations.size() == 0) - transformations = new ArrayList(transfAlgebraic.size()); + transformations = new ArrayList<>(transfAlgebraic.size()); if ( this.transfAlgebraic == null || this.transfAlgebraic.size() == 0) - this.transfAlgebraic = new ArrayList(transfAlgebraic.size()); + this.transfAlgebraic = new ArrayList<>(transfAlgebraic.size()); for ( String transf : transfAlgebraic){ addTransformation(transf); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/SymoplibParser.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/SymoplibParser.java index 93896000b1..0781471deb 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/SymoplibParser.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/SymoplibParser.java @@ -55,7 +55,7 @@ public class SymoplibParser { private static final Pattern namePat = Pattern.compile(".*\\s([A-Z]+)(\\s'.+')?\\s+'(.+)'.*"); - private static TreeMap sgs = parseSpaceGroupsXML(); + private static final TreeMap sgs = parseSpaceGroupsXML(); private static HashMap name2sgs; // map for lookups based on short names @@ -98,7 +98,7 @@ private static TreeMap parseSpaceGroupsXML() { System.exit(1); } - TreeMap map = new TreeMap(); + TreeMap map = new TreeMap<>(); try { map = parseSpaceGroupsXML(spaceGroupIS); @@ -110,7 +110,7 @@ private static TreeMap parseSpaceGroupsXML() { System.exit(1); } - name2sgs = new HashMap(); + name2sgs = new HashMap<>(); for (SpaceGroup sg:map.values()) { @@ -147,7 +147,7 @@ private static String convertStreamToString(InputStream stream) throws IOExcepti BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder sb = new StringBuilder(); - String line = null; + String line; while ((line = reader.readLine()) != null) { sb.append(line).append(newline); @@ -193,8 +193,8 @@ public static TreeMap getAllSpaceGroups() { * @return */ public static TreeMap parseSymopLib(InputStream symoplibIS) { - TreeMap map = new TreeMap(); - name2sgs = new HashMap(); + TreeMap map = new TreeMap<>(); + name2sgs = new HashMap<>(); try { BufferedReader br = new BufferedReader(new InputStreamReader(symoplibIS)); String line; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/TransformType.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/TransformType.java index a73ddb68cd..14ef3cb964 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/TransformType.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/TransformType.java @@ -52,13 +52,13 @@ public enum TransformType { - private int id; - private int foldType; - private boolean isScrew; - private boolean isInfinite; - private String shortName; + private final int id; + private final int foldType; + private final boolean isScrew; + private final boolean isInfinite; + private final String shortName; - private TransformType(int id, int foldType, boolean isScrew, boolean isInfinite, String shortName) { + TransformType(int id, int foldType, boolean isScrew, boolean isInfinite, String shortName) { this.id = id; this.foldType = foldType; this.isScrew = isScrew; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/UnitCellBoundingBox.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/UnitCellBoundingBox.java index fef02ce5cb..33963396f4 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/UnitCellBoundingBox.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/UnitCellBoundingBox.java @@ -26,10 +26,9 @@ import org.biojava.nbio.structure.StructureTools; import org.biojava.nbio.structure.contact.BoundingBox; -import java.util.List; - import javax.vecmath.Matrix4d; import javax.vecmath.Vector3d; +import java.util.List; /** * A class to contain the BoundingBoxes of all polymeric molecules in a full unit cell. @@ -44,16 +43,16 @@ public class UnitCellBoundingBox { * bounding boxes of all chains of all AUs in unit cell * e.g. chainBbs[0] would be the bounding boxes for all chains in the original AU */ - private BoundingBox[][] chainBbs; + private final BoundingBox[][] chainBbs; /** * An array with dimensions numOperatorsSg to contain all bounding boxes of * all AUs in unit cell */ - private BoundingBox[] auBbs; + private final BoundingBox[] auBbs; - private int numOperatorsSg; // i.e. multiplicity of space group - private int numPolyChainsAu; + private final int numOperatorsSg; // i.e. multiplicity of space group + private final int numPolyChainsAu; public UnitCellBoundingBox(int numOperatorsSg, int numPolyChainsAu) { this.numOperatorsSg = numOperatorsSg; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/io/SpaceGroupMapAdapter.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/io/SpaceGroupMapAdapter.java index 6c068f51e3..a3766ad9f6 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/io/SpaceGroupMapAdapter.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/io/SpaceGroupMapAdapter.java @@ -31,7 +31,7 @@ class SpaceGroupMapAdapter extends XmlAdapter> { @Override - public SpaceGroupMapElements[] marshal(Map arg0) throws Exception { + public SpaceGroupMapElements[] marshal(Map arg0) { SpaceGroupMapElements[] mapElements = new SpaceGroupMapElements[arg0.size()]; int i = 0; for (Map.Entry entry : arg0.entrySet()) @@ -41,8 +41,8 @@ public SpaceGroupMapElements[] marshal(Map arg0) throws Exc } @Override - public Map unmarshal(SpaceGroupMapElements[] arg0) throws Exception { - Map r = new TreeMap(); + public Map unmarshal(SpaceGroupMapElements[] arg0) { + Map r = new TreeMap<>(); for (SpaceGroupMapElements mapelement : arg0) r.put(mapelement.key, mapelement.value); return r; diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/io/SpaceGroupMapRoot.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/io/SpaceGroupMapRoot.java index e7998ee8dd..b457415f4a 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/io/SpaceGroupMapRoot.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/io/SpaceGroupMapRoot.java @@ -43,7 +43,7 @@ public class SpaceGroupMapRoot { private TreeMap mapProperty; public SpaceGroupMapRoot() { - mapProperty = new TreeMap(); + mapProperty = new TreeMap<>(); } @XmlJavaTypeAdapter(SpaceGroupMapAdapter.class) @@ -72,7 +72,7 @@ public String toXML() throws JAXBException { } public static SpaceGroupMapRoot fromXML(String xml) throws JAXBException{ - SpaceGroupMapRoot job = null; + SpaceGroupMapRoot job; JAXBContext jaxbContext = JAXBContext.newInstance(SpaceGroupMapRoot.class); diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/io/TransfAlgebraicAdapter.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/io/TransfAlgebraicAdapter.java index 7e707002d8..93a57ab686 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/io/TransfAlgebraicAdapter.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/io/TransfAlgebraicAdapter.java @@ -26,12 +26,13 @@ import javax.xml.bind.annotation.adapters.XmlAdapter; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; public class TransfAlgebraicAdapter extends XmlAdapter>{ @Override - public String[] marshal(List arg0) throws Exception { + public String[] marshal(List arg0) { String[] elements = new String[arg0.size()]; int i = 0; for (String s : arg0) @@ -40,10 +41,8 @@ public String[] marshal(List arg0) throws Exception { } @Override - public List unmarshal(String[] arg0) throws Exception { - List l = new ArrayList(); - for (String s : arg0) - l.add(s); + public List unmarshal(String[] arg0) { + List l = new ArrayList<>(Arrays.asList(arg0)); return l; } diff --git a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/io/TreeMapSpaceGroupWrapper.java b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/io/TreeMapSpaceGroupWrapper.java index 8aabe9b2f1..3a4d068cc4 100644 --- a/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/io/TreeMapSpaceGroupWrapper.java +++ b/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/io/TreeMapSpaceGroupWrapper.java @@ -52,7 +52,7 @@ public class TreeMapSpaceGroupWrapper implements Serializable{ public TreeMapSpaceGroupWrapper(){ - data = new TreeMap(); + data = new TreeMap<>(); } public TreeMap getData() { @@ -85,7 +85,7 @@ public String toXML() throws JAXBException{ public static TreeMapSpaceGroupWrapper fromXML(String xml) throws JAXBException{ - TreeMapSpaceGroupWrapper job = null; + TreeMapSpaceGroupWrapper job; JAXBContext jaxbContext = JAXBContext.newInstance(TreeMapSpaceGroupWrapper.class); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/AtomPositionMapTest.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/AtomPositionMapTest.java index f2b9a43437..31b92dd39f 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/AtomPositionMapTest.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/AtomPositionMapTest.java @@ -29,10 +29,11 @@ import org.junit.Test; import java.io.IOException; +import java.util.Map; import java.util.NavigableMap; import static org.junit.Assert.*; -import static org.junit.Assume.*; +import static org.junit.Assume.assumeTrue; /** * A unit test for {@link org.biojava.nbio.structure.AtomPositionMap}. @@ -41,7 +42,7 @@ public class AtomPositionMapTest { @Before - public void setUp() throws Exception { + public void setUp() { cache = new AtomCache(); // TODO Should mock instead of depending on real data from AtomCache cache.setObsoleteBehavior(LocalPDBDirectory.ObsoleteBehavior.FETCH_OBSOLETE); } @@ -62,8 +63,8 @@ public void testEasy() throws IOException, StructureException { // no insertion ResidueNumber end = new ResidueNumber("A", 117, null); AtomPositionMap map = new AtomPositionMap(cache.getAtoms(pdbId)); NavigableMap navMap = map.getNavMap(); - for (ResidueNumber n : navMap.keySet()) { - assertEquals("An element is missing", map.getPosition(n).intValue(), navMap.get(n).intValue()); + for (Map.Entry entry : navMap.entrySet()) { + assertEquals("An element is missing", map.getPosition(entry.getKey()).intValue(), entry.getValue().intValue()); } int realLength = map.getLength(start, end); assertEquals("Real atom length is wrong", length, realLength); @@ -186,8 +187,8 @@ public void testInsertionCodes() throws IOException, StructureException { AtomPositionMap map = new AtomPositionMap(cache.getAtoms(pdbId)); NavigableMap navMap = map.getNavMap(); - for (ResidueNumber n : navMap.keySet()) { - assertEquals("An element is missing", map.getPosition(n).intValue(), navMap.get(n).intValue()); + for (Map.Entry entry : navMap.entrySet()) { + assertEquals("An element is missing", map.getPosition(entry.getKey()).intValue(), entry.getValue().intValue()); } int length1 = 60; // 2+37+21 diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/ChemCompTest.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/ChemCompTest.java index fd37644fd4..87a0da7ace 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/ChemCompTest.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/ChemCompTest.java @@ -45,7 +45,7 @@ public void testALA(){ assertNotNull("residue type has not been set!", cc.getResidueType()); - assertTrue (" is not amino ", cc.getResidueType().equals(ResidueType.lPeptideLinking)); + assertEquals(" is not amino ", cc.getResidueType(), ResidueType.lPeptideLinking); } @Test @@ -67,7 +67,7 @@ public void testMEA(){ assertNotNull(cc); - assertTrue(" is not mea" , cc.getId().equals(chemID)); + assertEquals(" is not mea", cc.getId(), chemID); assertEquals(" one letter code is not correct", "F", cc.getOne_letter_code()); @@ -79,11 +79,11 @@ public void testMEA(){ assertNotNull("residue type has not been set!", cc.getResidueType()); - assertTrue (" is not amino ", cc.getResidueType().equals(ResidueType.lPeptideLinking)); + assertEquals(" is not amino ", cc.getResidueType(), ResidueType.lPeptideLinking); Group g = ChemCompGroupFactory.getGroupFromChemCompDictionary(chemID); - assertTrue( g.getType().equals(GroupType.AMINOACID)); + assertEquals(g.getType(), GroupType.AMINOACID); ChemCompGroupFactory.setChemCompProvider(oldProvider); } @@ -107,7 +107,7 @@ public void testPRR(){ assertNotNull(aa.getAminoType()); - assertTrue(aa.getAminoType().equals('X')); + assertEquals('X', (char) aa.getAminoType()); ChemCompGroupFactory.setChemCompProvider(oldProvider); @@ -127,7 +127,7 @@ public void testChangingProviders(){ assertNotNull(cc); - assertTrue(" is not mea" , cc.getId().equals(chemID)); + assertEquals(" is not mea", cc.getId(), chemID); assertTrue(cc.isEmpty()); @@ -139,7 +139,7 @@ public void testChangingProviders(){ assertNotNull(cc); - assertTrue(" is not mea" , cc.getId().equals(chemID)); + assertEquals(" is not mea", cc.getId(), chemID); assertEquals("MEA",cc.getThree_letter_code()); @@ -155,7 +155,7 @@ public void testChangingProviders(){ assertNotNull(cc); - assertTrue(" is not mea" , cc.getId().equals(chemID)); + assertEquals(" is not mea", cc.getId(), chemID); assertEquals("MEA",cc.getThree_letter_code()); @@ -166,7 +166,7 @@ public void testChangingProviders(){ assertNotNull(cc); - assertTrue(" is not mea" , cc.getId().equals(chemID)); + assertEquals(" is not mea", cc.getId(), chemID); //the cached description contains all information even with the ReducedProvider assertNotNull(cc.getThree_letter_code()); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/ElementTest.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/ElementTest.java index 81ce22d087..cef25fb307 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/ElementTest.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/ElementTest.java @@ -21,7 +21,6 @@ package org.biojava.nbio.structure; -import junit.framework.TestCase; import org.junit.Assert; import org.junit.Test; @@ -57,9 +56,9 @@ public void testIsMetal() { Assert.assertTrue(la.isMetal()); Element ac = Element.Ac; Assert.assertTrue(ac.isMetal()); - }; + } - @Test + @Test public void testIsMetalloid() { Element h = Element.H; Assert.assertFalse(h.isMetalloid()); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/HetatomImplTest.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/HetatomImplTest.java index 74556c2434..3c9b89e49b 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/HetatomImplTest.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/HetatomImplTest.java @@ -33,18 +33,18 @@ */ public class HetatomImplTest { - private int bigTestNumber = 60000; + private final int bigTestNumber = 60000; public HetatomImplTest() { } @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { } @AfterClass - public static void tearDownClass() throws Exception { + public static void tearDownClass() { } @Before @@ -520,7 +520,7 @@ public void testSetGetResidueNumber() { @Test public void testGetResidueNumberUsage() { // System.out.println("testGetResidueNumberUsage"); - List resNumgroups = new ArrayList(); + List resNumgroups = new ArrayList<>(); for (int i = 0; i < bigTestNumber; i++) { ResidueNumber resNum = new ResidueNumber("A", i, ' '); @@ -529,7 +529,7 @@ public void testGetResidueNumberUsage() { resNumgroups.add(hetAtom); } - List integers = new ArrayList(); + List integers = new ArrayList<>(); for (Group group : resNumgroups) { ResidueNumber resnum = group.getResidueNumber(); @@ -541,7 +541,7 @@ public void testGetResidueNumberUsage() { @Test public void testSetResidueNumberUsage() { - List resNumgroups = new ArrayList(); + List resNumgroups = new ArrayList<>(); for (int i = 0; i < bigTestNumber; i++) { ResidueNumber resNum = new ResidueNumber("A", i, ' '); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/PDBStatusTest.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/PDBStatusTest.java index 8bcd2d1e98..4d4813ff10 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/PDBStatusTest.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/PDBStatusTest.java @@ -54,15 +54,15 @@ public void testGetStatus() { @Test public void testGetReplacement() { - Assert.assertFalse(Arrays.asList("YES").equals(Arrays.asList("NO"))); //check for deep equals + Assert.assertNotEquals(Arrays.asList("YES"), Arrays.asList("NO")); //check for deep equals // 1CMW is replacedBy NONE - Assert.assertEquals(Arrays.asList(), PDBStatus.getReplacement("1CMW", true, false)); - Assert.assertEquals(Arrays.asList("1CMW"), PDBStatus.getReplacement("1CMW", true, true)); + Assert.assertEquals(Collections.emptyList(), PDBStatus.getReplacement("1CMW", true, false)); + Assert.assertEquals(Collections.singletonList("1CMW"), PDBStatus.getReplacement("1CMW", true, true)); // 1HHB is replacedBy 2-4HHB - Assert.assertEquals(Arrays.asList("3HHB"), PDBStatus.getReplacement("3HHB", false, false)); - Assert.assertEquals(Arrays.asList("3HHB"), PDBStatus.getReplacement("3HHB", false, true)); + Assert.assertEquals(Collections.singletonList("3HHB"), PDBStatus.getReplacement("3HHB", false, false)); + Assert.assertEquals(Collections.singletonList("3HHB"), PDBStatus.getReplacement("3HHB", false, true)); Assert.assertEquals(Arrays.asList("4HHB", "3HHB", "2HHB"), PDBStatus.getReplacement("1HHB", false, false)); Assert.assertEquals(Arrays.asList("4HHB", "3HHB", "2HHB", "1HHB"), PDBStatus.getReplacement("1HHB", false, true)); @@ -78,7 +78,7 @@ public void testGetReplacement() { public void testGetCurrent() { Assert.assertEquals("4HHB", PDBStatus.getCurrent("1HHB")); Assert.assertEquals("3HHB", PDBStatus.getCurrent("3HHB")); - Assert.assertEquals(null, PDBStatus.getCurrent("1CMW")); + Assert.assertNull(PDBStatus.getCurrent("1CMW")); Assert.assertEquals("3ENI", PDBStatus.getCurrent("1KSA")); Assert.assertEquals("8CAT", PDBStatus.getCurrent("1CAT")); Assert.assertEquals("8CAT", PDBStatus.getCurrent("3CAT")); @@ -87,14 +87,14 @@ public void testGetCurrent() { @Test public void testGetReplaces() { - Assert.assertEquals(new ArrayList(), Arrays.asList(new String[]{})); + Assert.assertEquals(new ArrayList(), Collections.emptyList()); - Assert.assertEquals(Arrays.asList("1HHB"), PDBStatus.getReplaces("4HHB", false)); - Assert.assertEquals(Arrays.asList("1HHB"), PDBStatus.getReplaces("3HHB", false)); - Assert.assertEquals(Arrays.asList(), PDBStatus.getReplaces("1HHB", false)); + Assert.assertEquals(Collections.singletonList("1HHB"), PDBStatus.getReplaces("4HHB", false)); + Assert.assertEquals(Collections.singletonList("1HHB"), PDBStatus.getReplaces("3HHB", false)); + Assert.assertEquals(Collections.emptyList(), PDBStatus.getReplaces("1HHB", false)); Assert.assertEquals(Arrays.asList("1M50", "1KSA"), PDBStatus.getReplaces("3ENI", false)); Assert.assertEquals(Arrays.asList("1M50", "1KSA"), PDBStatus.getReplaces("3ENI", true)); - Assert.assertEquals(Arrays.asList("3CAT"), PDBStatus.getReplaces("8CAT", false)); + Assert.assertEquals(Collections.singletonList("3CAT"), PDBStatus.getReplaces("8CAT", false)); Assert.assertEquals(Arrays.asList("3CAT", "1CAT"), PDBStatus.getReplaces("8CAT", true)); } @@ -113,37 +113,37 @@ public void testMergeReversed() { List a,b; b = Arrays.asList("F","A"); - a = new LinkedList(); + a = new LinkedList<>(); mergeReversed.invoke(null, a,b); Assert.assertEquals(Arrays.asList("F", "A"), a); - a = new LinkedList(); + a = new LinkedList<>(); a.add("B"); mergeReversed.invoke(null, a,b); Assert.assertEquals(Arrays.asList("F", "B", "A"), a); - a = new LinkedList(); + a = new LinkedList<>(); a.add("G"); mergeReversed.invoke(null, a,b); Assert.assertEquals(Arrays.asList("G", "F", "A"), a); - a = new LinkedList(); + a = new LinkedList<>(); a.add("1"); mergeReversed.invoke(null, a,b); Assert.assertEquals(Arrays.asList("F", "A", "1"), a); - a = new LinkedList(); + a = new LinkedList<>(); a.add("G"); a.add("1"); mergeReversed.invoke(null, a,b); Assert.assertEquals(Arrays.asList("G", "F", "A", "1"), a); - b = Arrays.asList(); + b = Collections.emptyList(); mergeReversed.invoke(null, a,b); Assert.assertEquals(Arrays.asList("G", "F", "A", "1"), a); b = Arrays.asList("G","D","C","A"); - a = new LinkedList(); + a = new LinkedList<>(); a.add("F"); a.add("B"); a.add("1"); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/PdbFileFormat30Test.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/PdbFileFormat30Test.java index 9daf7d7e18..c1398dbeb1 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/PdbFileFormat30Test.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/PdbFileFormat30Test.java @@ -27,13 +27,12 @@ import org.biojava.nbio.structure.io.PDBFileParser; import org.biojava.nbio.structure.io.mmcif.ChemCompGroupFactory; import org.biojava.nbio.structure.io.mmcif.ReducedChemCompProvider; +import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; -import org.junit.Test; - import static org.junit.Assert.*; @@ -114,7 +113,7 @@ private Structure getStructure(String fileName) throws IOException{ FileParsingParameters params = new FileParsingParameters(); params.setAlignSeqRes(false); pdbpars.setFileParsingParameters(params); - Structure structure = null; + Structure structure; structure = pdbpars.parsePDBFile(inStream) ; @@ -153,7 +152,7 @@ public void testIsLegacyFormat_pdb_COMPND_handler() throws IOException{ // thus here we have the one specified in header plus a SO4 nonpolymer entity assertEquals(2, compounds.size()); EntityInfo mol = compounds.get(0); - assertTrue(mol.getDescription().equals("6,7-DIMETHYL-8-RIBITYLLUMAZINE SYNTHASE")); + assertEquals("6,7-DIMETHYL-8-RIBITYLLUMAZINE SYNTHASE", mol.getDescription()); assertEquals(60, mol.getChainIds().size()); assertEquals(60, mol.getChains().size()); assertTrue(isChainNameInEntity(mol,"S")); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/ResidueNumberTest.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/ResidueNumberTest.java index c594f0dd18..5790756cb6 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/ResidueNumberTest.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/ResidueNumberTest.java @@ -37,11 +37,11 @@ public ResidueNumberTest() { } @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { } @AfterClass - public static void tearDownClass() throws Exception { + public static void tearDownClass() { } @Before @@ -102,7 +102,7 @@ public void testEquals() { boolean result = number2.equals(number1); Assert.assertEquals(expResult, result); - Set numberSet= new HashSet(); + Set numberSet= new HashSet<>(); numberSet.add(number1); numberSet.add(number2); Assert.assertEquals(1, numberSet.size()); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/ResidueRangeTest.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/ResidueRangeTest.java index 7e5d7aeaa1..721d19d41c 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/ResidueRangeTest.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/ResidueRangeTest.java @@ -46,7 +46,7 @@ public class ResidueRangeTest { private AtomCache cache; @Before - public void setUp() throws Exception { + public void setUp() { cache = new AtomCache(); // TODO Should mock instead of depending on // real data from AtomCache cache.setObsoleteBehavior(ObsoleteBehavior.FETCH_OBSOLETE); @@ -90,7 +90,7 @@ public void testWholeChainWithMap() throws IOException, StructureException { * Tests creating ResidueRanges and calculating their lengths. */ @Test - public void testWithLengths() throws IOException, StructureException { + public void testWithLengths() { String[] ids = new String[] { "1w0p", "3qq3", "3chc", "2ei7" }; // more: // , // "2qbr" @@ -107,7 +107,7 @@ public void testWithLengths() throws IOException, StructureException { new ResidueNumber("L", 254, 't') }; int[] lengths = new int[] { 117 - 5, 200 - 10, 111, 55 }; int totalLength = 0; - List ranges = new ArrayList( + List ranges = new ArrayList<>( ids.length); for (int i = 0; i < ids.length; i++) { ResidueRangeAndLength rr = new ResidueRangeAndLength(chains[i], @@ -261,12 +261,12 @@ public void testParseAndEqual() { } @Test(expected=IllegalArgumentException.class) - public void testBadSyntax() throws IOException, StructureException { + public void testBadSyntax() { ResidueRange.parse("-"); } @Test - public void testPartialRange() throws IOException, StructureException { + public void testPartialRange() { String rangeStr = "C_1023-"; ResidueRange range = ResidueRange.parse(rangeStr); assertEquals(rangeStr,1023,(int)range.getStart().getSeqNum()); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/SiteTest.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/SiteTest.java index d7a64d0017..98db2c906f 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/SiteTest.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/SiteTest.java @@ -63,7 +63,7 @@ public SiteTest() { ser195.setResidueNumber("H", 195, ' '); ser195.setPDBName("SER"); ser195.setChain(chain); - List catSiteGroups = new ArrayList(); + List catSiteGroups = new ArrayList<>(); catSiteGroups.add(his57); catSiteGroups.add(asp102); catSiteGroups.add(ser195); @@ -99,7 +99,7 @@ public SiteTest() { hoh497.setPDBName("HOH"); hoh497.setChain(chain); - bindingSiteGroups = new ArrayList(); + bindingSiteGroups = new ArrayList<>(); bindingSiteGroups.add(arg221a); bindingSiteGroups.add(lys224); @@ -118,11 +118,11 @@ public SiteTest() { } @BeforeClass - public static void setUpClass() throws Exception { + public static void setUpClass() { } @AfterClass - public static void tearDownClass() throws Exception { + public static void tearDownClass() { } @Before @@ -155,7 +155,7 @@ public void testToPDB_0args() { @Test public void testToPDB_StringBuffer() { // System.out.println("toPDB"); - StringBuffer buf = new StringBuffer(""); + StringBuffer buf = new StringBuffer(); String expResult = "SITE 1 AC1 6 ARG H 221A LYS H 224 HOH H 403 HOH H 460 " + newline + "SITE 2 AC1 6 HOH H 464 HOH H 497 "+ newline; bindingSite.toPDB(buf); @@ -188,7 +188,7 @@ public void testRemark800ToPDB_0args() { @Test public void testRemark800ToPDB_StringBuffer() { // System.out.println("remark800toPDB"); - StringBuffer buf = new StringBuffer(""); + StringBuffer buf = new StringBuffer(); String expResult = "REMARK 800 SITE_IDENTIFIER: CAT " + newline + "REMARK 800 EVIDENCE_CODE: UNKNOWN " + newline + "REMARK 800 SITE_DESCRIPTION: ACTIVE SITE " + newline; diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/Test2JA5.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/Test2JA5.java index 8d42461300..172cd9b5a3 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/Test2JA5.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/Test2JA5.java @@ -20,14 +20,14 @@ */ package org.biojava.nbio.structure; -import static org.junit.Assert.*; - -import java.io.IOException; - import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.FileParsingParameters; import org.junit.Test; +import java.io.IOException; + +import static org.junit.Assert.*; + /** * Created by andreas on 9/16/15. */ diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/Test4hhb.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/Test4hhb.java index afb5de1d59..920346c1a9 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/Test4hhb.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/Test4hhb.java @@ -49,7 +49,7 @@ public class Test4hhb { public void test4hhbPDBFile() throws IOException { - Structure structure = null; + Structure structure; InputStream inStream = new GZIPInputStream(this.getClass().getResourceAsStream("/4hhb.pdb.gz")); assertNotNull(inStream); @@ -70,7 +70,7 @@ public void test4hhbPDBFile() throws IOException testStructure(structure); - Structure structure2 = null; + Structure structure2; inStream = new GZIPInputStream(this.getClass().getResourceAsStream("/4hhb.cif.gz")); assertNotNull(inStream); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestAltLocs.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestAltLocs.java index d1c6779e7c..ef2d0967c0 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestAltLocs.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestAltLocs.java @@ -26,8 +26,6 @@ import org.biojava.nbio.structure.io.mmcif.MMCIFFileTools; import org.biojava.nbio.structure.io.mmcif.SimpleMMcifConsumer; import org.biojava.nbio.structure.io.mmcif.SimpleMMcifParser; -import org.biojava.nbio.structure.io.mmcif.chem.PolymerType; -import org.biojava.nbio.structure.io.mmcif.chem.ResidueType; import org.biojava.nbio.structure.io.mmcif.model.AtomSite; import org.biojava.nbio.structure.io.mmcif.model.ChemComp; import org.biojava.nbio.structure.io.mmcif.model.ChemCompBond; @@ -58,28 +56,11 @@ public void testAltLocParsing() throws StructureException, IOException{ List groups = a.getAtomGroups(); for (Group g : groups){ ChemComp cc = g.getChemComp(); - if ( ResidueType.lPeptideLinking.equals(cc.getResidueType()) || - PolymerType.PROTEIN_ONLY.contains(cc.getPolymerType()) || - PolymerType.POLYNUCLEOTIDE_ONLY.contains(cc.getPolymerType()) - ){ - if (! g.isWater()) { - //System.out.println(g); - groupCount ++; - } - } else { - // when using the Reduced Chem Comp provider - // there are 3 groups in 2CI1 which are non-standard: SNC, KOR, CIT - // they are not in the reduced set of standard definitions that will - // be shipped in the .jar file. - - // if the download chem comp provider is used - // there will be CIT, which is not a peptide, but - // should still be counted as a valid HETATOM group... - if (! g.isWater()) { - //System.out.println(cc); - //System.out.println(g); - groupCount++; - } + //System.out.println(cc); + //System.out.println(g); + if (! g.isWater()) { + //System.out.println(g); + groupCount ++; } } @@ -274,7 +255,7 @@ public void test3PIUpdb() throws IOException, StructureException{ //System.out.println(structure.getPdbId() + " has # CA atoms: " + ca.length); - List caList = new ArrayList(); + List caList = new ArrayList<>(); for ( Chain c: structure.getChains()){ for (Group g: c.getAtomGroups()){ @@ -384,9 +365,7 @@ public void testAddBondsDoesntChangeGroups() throws IOException, StructureExcept // Now add support for altLocGroup List atomsList = new ArrayList<>(mainGroup.getAtoms()); for(Group altLocOne: mainGroup.getAltLocs()){ - for(Atom atomAltLocOne: altLocOne.getAtoms()){ - atomsList.add(atomAltLocOne); - } + atomsList.addAll(altLocOne.getAtoms()); } // Get the chem copm ChemComp aminoChemComp = ChemCompGroupFactory.getChemComp(mainGroup @@ -439,7 +418,7 @@ public void test4CUPBonds() throws IOException, StructureException{ Atom[] ca = StructureTools.getAtomCAArray(structure); - List caList = new ArrayList(); + List caList = new ArrayList<>(); for ( Chain c: structure.getChains()){ for (Group g: c.getAtomGroups()){ @@ -501,7 +480,7 @@ public void test3PIUmmcif() throws IOException, StructureException{ //System.out.println(structure.getPdbId() + " has # CA atoms: " + ca.length); - List caList = new ArrayList(); + List caList = new ArrayList<>(); for ( Chain c: structure.getChains()){ for (Group g: c.getAtomGroups()){ @@ -564,7 +543,7 @@ public void test3U7Tmmcif() throws IOException, StructureException{ //System.out.println(structure.getPdbId() + " has # CA atoms: " + ca.length); - List caList = new ArrayList(); + List caList = new ArrayList<>(); for ( Chain c: structure.getChains()){ // notice here we test the seqresgroups, because we want to check if microheterogeinity is treated correctly for (Group g: c.getSeqResGroups()){ diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestAtomCache.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestAtomCache.java index bb46670bae..0c04a68383 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestAtomCache.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestAtomCache.java @@ -42,7 +42,7 @@ // TODO dmyersturnbull: we should merge TestAtomCache and AtomCacheTest public class TestAtomCache { - public static final String lineSplit = System.getProperty("file.separator"); +// public static final String lineSplit = System.getProperty("file.separator"); private AtomCache cache; @Before @@ -54,7 +54,7 @@ public void setUp() throws IOException { "1cmw", "1hhb","4hhb" }; - List readers = new ArrayList(); + List readers = new ArrayList<>(); readers.add(new MMCIFFileReader(cache.getPath()) ); readers.add(new PDBFileReader(cache.getPath()) ); for(LocalPDBDirectory reader : readers) { @@ -162,7 +162,7 @@ public void testObsoleteId() throws StructureException, IOException { // note: we expect an IOException because 1CMW is obsolete and hasn't got a replacement @Test - public void testFetchCurrent1CMW() throws IOException, StructureException { + public void testFetchCurrent1CMW() throws StructureException { cache.setFetchBehavior(FetchBehavior.FETCH_FILES); cache.setObsoleteBehavior(ObsoleteBehavior.FETCH_CURRENT); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestAtomIterator.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestAtomIterator.java index 7d4fea963d..e4bcf8b874 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestAtomIterator.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestAtomIterator.java @@ -20,18 +20,13 @@ */ package org.biojava.nbio.structure; -import static org.junit.Assert.*; +import org.junit.Test; import java.io.IOException; import java.util.NoSuchElementException; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.AtomIterator; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; -import org.biojava.nbio.structure.StructureTools; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; public class TestAtomIterator { @Test diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestBioAssemblyIdentifier.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestBioAssemblyIdentifier.java index 845ea0f51c..332a4e0a07 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestBioAssemblyIdentifier.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestBioAssemblyIdentifier.java @@ -20,12 +20,13 @@ */ package org.biojava.nbio.structure; -import static org.junit.Assert.*; +import org.biojava.nbio.structure.align.util.AtomCache; +import org.junit.Test; import java.io.IOException; -import org.biojava.nbio.structure.align.util.AtomCache; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; public class TestBioAssemblyIdentifier { diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestBond.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestBond.java index 1140a14738..260b7307a9 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestBond.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestBond.java @@ -20,10 +20,6 @@ */ package org.biojava.nbio.structure; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.FileParsingParameters; import org.biojava.nbio.structure.io.mmcif.ChemCompGroupFactory; @@ -33,7 +29,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.junit.Assert.*; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class TestBond { diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestCalc.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestCalc.java index 5a9838cc2e..ae31b9911a 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestCalc.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestCalc.java @@ -20,15 +20,16 @@ */ package org.biojava.nbio.structure; -import static org.junit.Assert.*; +import org.biojava.nbio.structure.geometry.Matrices; +import org.biojava.nbio.structure.jama.Matrix; +import org.junit.Test; import javax.vecmath.Matrix4d; import javax.vecmath.Point3d; import javax.vecmath.Vector3d; -import org.biojava.nbio.structure.geometry.Matrices; -import org.biojava.nbio.structure.jama.Matrix; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class TestCalc { diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestChargeAdder.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestChargeAdder.java index f814a600db..c22442f213 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestChargeAdder.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestChargeAdder.java @@ -20,12 +20,12 @@ */ package org.biojava.nbio.structure; -import static org.junit.Assert.assertEquals; +import org.biojava.nbio.structure.io.ChargeAdder; +import org.junit.Test; import java.io.IOException; -import org.biojava.nbio.structure.io.ChargeAdder; -import org.junit.Test; +import static org.junit.Assert.assertEquals; /** * Class of functions to test the charge adder. diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestCloning.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestCloning.java index ac8b728d93..d77a84e9ac 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestCloning.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestCloning.java @@ -24,14 +24,14 @@ */ package org.biojava.nbio.structure; -import java.io.IOException; -import java.util.Iterator; -import java.util.List; - import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.FileParsingParameters; import org.junit.Test; +import java.io.IOException; +import java.util.Iterator; +import java.util.List; + import static org.junit.Assert.*; public class TestCloning { @@ -107,7 +107,7 @@ public void testBiounitEntitiesFlatChains() throws StructureException, IOExcepti } @Test - public void testBiounitEntitiesMultimodel() throws StructureException, IOException { + public void testBiounitEntitiesMultimodel() throws StructureException { Structure s; s = StructureIO.getBiologicalAssembly("1stp", 1, true); @@ -149,7 +149,7 @@ public void test3piuCloning() throws StructureException, IOException { compareCloned(s, c); } - private void compareCloned(final Structure s, final Structure c) throws StructureException { + private void compareCloned(final Structure s, final Structure c) { assertEquals(s.getChains().size(), c.getChains().size()); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestDNAAlignment.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestDNAAlignment.java index 1324832866..3a22386273 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestDNAAlignment.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestDNAAlignment.java @@ -24,15 +24,16 @@ package org.biojava.nbio.structure; -import java.io.IOException; - -import static org.junit.Assert.*; - import org.biojava.nbio.structure.align.ce.CeMain; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.util.AtomCache; import org.junit.Test; +import java.io.IOException; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + /** make sure DNA alignments fail gracefully * * @author Andreas Prlic diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestDownloadChemCompProvider.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestDownloadChemCompProvider.java index bc2a8dcd41..53e6fe5510 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestDownloadChemCompProvider.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestDownloadChemCompProvider.java @@ -21,11 +21,9 @@ package org.biojava.nbio.structure; import org.biojava.nbio.core.util.FlatFileCache; -import org.biojava.nbio.structure.io.LocalPDBDirectory; import org.biojava.nbio.structure.io.mmcif.DownloadChemCompProvider; import org.biojava.nbio.structure.io.mmcif.model.ChemComp; import org.junit.Test; -import static org.junit.Assert.*; import java.io.File; import java.io.FileOutputStream; @@ -33,6 +31,8 @@ import java.io.PrintWriter; import java.util.zip.GZIPOutputStream; +import static org.junit.Assert.*; + public class TestDownloadChemCompProvider { @Test @@ -96,7 +96,7 @@ public void testWeDontCacheGarbage() { ChemComp cc = prov.getChemComp("HEM"); // we got a 404 back from server so we shouldn't have cached a file - assertTrue(!file.exists()); + assertFalse(file.exists()); file.delete(); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestEntityHeuristics.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestEntityHeuristics.java index 4f798834d3..9913e3dd92 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestEntityHeuristics.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestEntityHeuristics.java @@ -26,12 +26,12 @@ import java.io.IOException; import java.io.InputStream; -import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.zip.GZIPInputStream; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; public class TestEntityHeuristics { @@ -49,7 +49,7 @@ public class TestEntityHeuristics { //} @Test - public void test1b8gRaw() throws IOException, StructureException { + public void test1b8gRaw() throws IOException { Structure s = getStructure("1b8g_raw.pdb.gz", true); @@ -81,7 +81,7 @@ public void test1b8gRaw() throws IOException, StructureException { @Test - public void test2m7yRaw() throws IOException, StructureException { + public void test2m7yRaw() throws IOException { Structure s = getStructure("2m7y_raw.pdb.gz", true); @@ -112,7 +112,7 @@ public void test2m7yRaw() throws IOException, StructureException { } @Test - public void test3c5fRaw() throws IOException, StructureException { + public void test3c5fRaw() throws IOException { Structure s = getStructure("3c5f_raw.pdb.gz", true); @@ -153,7 +153,7 @@ public void test3c5fRaw() throws IOException, StructureException { } @Test - public void test4b19Raw() throws IOException, StructureException { + public void test4b19Raw() throws IOException { Structure s = getStructure("4b19_raw.pdb.gz", true); @@ -184,7 +184,7 @@ public void test4b19Raw() throws IOException, StructureException { } @Test - public void test3ddoNoseqres() throws IOException, StructureException { + public void test3ddoNoseqres() throws IOException { // 3ddo contains 6 chains in 1 entity, with residue numbering completely different in each of the chains @@ -207,7 +207,7 @@ public void test3ddoNoseqres() throws IOException, StructureException { } @Test - public void test3ddoSeqres() throws IOException, StructureException { + public void test3ddoSeqres() throws IOException { // 3ddo contains 6 chains in 1 entity, with residue numbering completely different in each of the chains @@ -245,13 +245,7 @@ private Structure getStructure(String fileName, boolean setAlignSeqRes) throws I private void checkEntitiesNumbered(List entities) { - Collections.sort(entities, new Comparator() { - - @Override - public int compare(EntityInfo o1, EntityInfo o2) { - return new Integer(o1.getMolId()).compareTo(o2.getMolId()); - } - }); + entities.sort(Comparator.comparingInt(EntityInfo::getMolId)); int id = 1; for (EntityInfo compound:entities) { diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestEntityResIndexMapping.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestEntityResIndexMapping.java index f0926364b9..c336834eb6 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestEntityResIndexMapping.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestEntityResIndexMapping.java @@ -20,7 +20,11 @@ */ package org.biojava.nbio.structure; -import static org.junit.Assert.*; +import org.biojava.nbio.structure.align.util.AtomCache; +import org.biojava.nbio.structure.io.FileParsingParameters; +import org.biojava.nbio.structure.io.PDBFileParser; +import org.junit.Ignore; +import org.junit.Test; import java.io.IOException; import java.io.InputStream; @@ -28,11 +32,7 @@ import java.util.List; import java.util.zip.GZIPInputStream; -import org.biojava.nbio.structure.align.util.AtomCache; -import org.biojava.nbio.structure.io.FileParsingParameters; -import org.biojava.nbio.structure.io.PDBFileParser; -import org.junit.Ignore; -import org.junit.Test; +import static org.junit.Assert.*; /** * Various tests for functionality in {@link EntityInfo} and {@link org.biojava.nbio.structure.io.EntityFinder} diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestNucleotides.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestNucleotides.java index dc865eb366..abb78dcaad 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestNucleotides.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestNucleotides.java @@ -137,7 +137,7 @@ private Structure getStructure(String pdbId) throws IOException, StructureExcept } @Test - public void test1REP() throws StructureException, IOException{ + public void test1REP() throws IOException{ PDBFileReader reader = new PDBFileReader(); FileParsingParameters params = new FileParsingParameters(); @@ -164,16 +164,16 @@ public void test1REP() throws StructureException, IOException{ assertNotNull("Could not acces Chem Comp file!" , n1.getChemComp()); - assertTrue("ChemComp is not DC",n1.getChemComp().getId().equals("DC")); + assertEquals("ChemComp is not DC", "DC", n1.getChemComp().getId()); assertNotNull("Could not determine polymer type " , n1.getChemComp().getPolymerType()); //System.out.println(n1.getChemComp().getPolymerType()); - assertTrue(n1.getChemComp().getPolymerType().equals(PolymerType.dna)); + assertEquals(n1.getChemComp().getPolymerType(), PolymerType.dna); assertNotNull(n1.getPDBName()); assertNotNull(n1.getResidueNumber()); assertNotNull(n2.getResidueNumber()); assertEquals("23", n2.getResidueNumber().toString()); - assertTrue(n1.getResidueNumber().equals(n2.getResidueNumber())); + assertEquals(n1.getResidueNumber(), n2.getResidueNumber()); } diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestParsingCalcium.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestParsingCalcium.java index 783ca74dba..88faee44f8 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestParsingCalcium.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestParsingCalcium.java @@ -29,8 +29,7 @@ import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; public class TestParsingCalcium { @@ -81,15 +80,15 @@ public void testCAreturnsCalpha() throws IOException, StructureException { Atom[] atoms = StructureTools.getRepresentativeAtomArray(s); for (Atom atom:atoms) { - assertTrue("atom "+atom.getPDBserial()+" of residue "+atom.getGroup().getResidueNumber()+"-"+atom.getGroup().getPDBName()+ - " is not a Carbon alpha", atom.getElement()==Element.C); + assertSame("atom " + atom.getPDBserial() + " of residue " + atom.getGroup().getResidueNumber() + "-" + atom.getGroup().getPDBName() + + " is not a Carbon alpha", atom.getElement(), Element.C); } for (Chain c:s.getChains()) { atoms = StructureTools.getRepresentativeAtomArray(c); for (Atom atom:atoms) { - assertTrue("atom "+atom.getPDBserial()+" of residue "+atom.getGroup().getResidueNumber()+"-"+atom.getGroup().getPDBName()+ - " is not a Carbon alpha", atom.getElement()==Element.C); + assertSame("atom " + atom.getPDBserial() + " of residue " + atom.getGroup().getResidueNumber() + "-" + atom.getGroup().getPDBName() + + " is not a Carbon alpha", atom.getElement(), Element.C); } } @@ -104,7 +103,7 @@ public void testCAreturnsCalpha() throws IOException, StructureException { atom.getElement()==Element.O || atom.getElement()==Element.N ); - assertTrue("backbone atoms should not contain CB atoms",!atom.getName().equals("CB")); + assertNotEquals("backbone atoms should not contain CB atoms", "CB", atom.getName()); if (atom.getGroup().getPDBName().equals("GLY")) { hasGlycine = true; diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestStructureCrossReferences.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestStructureCrossReferences.java index d2c5b2d0b8..0f31936360 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestStructureCrossReferences.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestStructureCrossReferences.java @@ -20,15 +20,6 @@ */ package org.biojava.nbio.structure; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.List; - import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.contact.StructureInterface; import org.biojava.nbio.structure.contact.StructureInterfaceList; @@ -38,6 +29,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.util.List; + +import static org.junit.Assert.*; + public class TestStructureCrossReferences { private static final Logger logger = LoggerFactory.getLogger(TestStructureCrossReferences.class); @@ -139,11 +135,11 @@ public void testCrossReferencesPdbAlignSeqRes() throws IOException, StructureExc } //@Test - public void testCrossReferencesRawFile() throws IOException, StructureException { + public void testCrossReferencesRawFile() { // TODO implement } - private void doFullTest(Structure structure, boolean emptySeqRes) throws StructureException { + private void doFullTest(Structure structure, boolean emptySeqRes) { //System.out.println("Testing references in original structure"); @@ -194,7 +190,7 @@ private void doFullTest(Structure structure, boolean emptySeqRes) throws Structu testStructureRefs(structure, emptySeqRes); } - private void testStructureRefs(Structure s, boolean emptySeqRes) throws StructureException { + private void testStructureRefs(Structure s, boolean emptySeqRes) { // structure, chain, group, atom linking for (Chain c:s.getChains()) { @@ -265,7 +261,7 @@ private void testAtomArrayRefs(Atom[] atoms, Chain c) { } - private void testInterfaceRefs(Structure s, StructureInterface i) throws StructureException { + private void testInterfaceRefs(Structure s, StructureInterface i) { for (Atom a:i.getMolecules().getFirst()) { assertNotNull(a.getGroup().getChain().getEntityInfo()); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestStructureImpl.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestStructureImpl.java index b38fbd95de..446d69fbbc 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestStructureImpl.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestStructureImpl.java @@ -20,11 +20,11 @@ */ package org.biojava.nbio.structure; -import static org.junit.Assert.*; +import org.junit.Test; import java.util.ArrayList; -import org.junit.Test; +import static org.junit.Assert.assertEquals; /** * This tests the correctness of the {@link Structure} data structure, in terms @@ -47,7 +47,7 @@ public void testLinks() { // Create new Structure and assign one Chain to it Structure s1 = new StructureImpl(); - s1.addModel(new ArrayList(1)); + s1.addModel(new ArrayList<>(1)); Chain c1 = new ChainImpl(); s1.addChain(c1); @@ -73,7 +73,7 @@ public void testLinks() { Atom a2 = (Atom) a1.clone(); Structure s2 = new StructureImpl(); - s2.addModel(new ArrayList(1)); + s2.addModel(new ArrayList<>(1)); Chain c2 = new ChainImpl(); s2.addChain(c2); Group g2 = new HetatomImpl(); @@ -88,7 +88,7 @@ public void testLinks() { Group g3 = (Group) g1.clone(); Atom a3 = g3.getAtom(0); Structure s3 = new StructureImpl(); - s3.addModel(new ArrayList(1)); + s3.addModel(new ArrayList<>(1)); Chain c3 = new ChainImpl(); s3.addChain(c3); c3.addGroup(g3); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestStructureSerialization.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestStructureSerialization.java index f0a3e89bee..fae48c638e 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestStructureSerialization.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestStructureSerialization.java @@ -23,13 +23,9 @@ import org.biojava.nbio.structure.io.PDBFileReader; import org.junit.Test; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; +import java.io.*; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; /** * Test the serialization and deserialization of BioJava structure objects. @@ -40,7 +36,7 @@ public class TestStructureSerialization { @Test - public void testSerializeStructure() throws IOException, StructureException, ClassNotFoundException { + public void testSerializeStructure() throws IOException, ClassNotFoundException { PDBFileReader reader = new PDBFileReader(); reader.getFileParsingParameters().setParseSecStruc(true); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestURLIdentifier.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestURLIdentifier.java index cfa32a1cc2..8252b8c04d 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestURLIdentifier.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestURLIdentifier.java @@ -20,17 +20,17 @@ */ package org.biojava.nbio.structure; -import static org.junit.Assert.*; +import org.biojava.nbio.structure.align.util.AtomCache; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URL; import java.net.UnknownHostException; import java.util.Arrays; -import org.biojava.nbio.structure.align.util.AtomCache; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.junit.Assert.*; public class TestURLIdentifier { private static final Logger logger = LoggerFactory.getLogger(TestURLIdentifier.class); @@ -79,7 +79,7 @@ public void testURLParameters() throws StructureException, IOException { full = id.loadStructure(cache); assertNotNull(full); - assertEquals("2POS",id.toCanonical().getPdbId()); + assertEquals("2POS", id.toCanonical().pdbId); // assertEquals("2POS",full.getName()); // What should this get set to with identifiers? url = new URL("file://" + base + "?residues=A:1-5"); @@ -106,7 +106,7 @@ public void testURLParameters() throws StructureException, IOException { full = id.loadStructure(cache); assertNotNull(full); - assertEquals("1B8G",id.toCanonical().getPdbId()); + assertEquals("1B8G", id.toCanonical().pdbId); } catch(UnknownHostException e) { logger.error("Unable to connect to rcsb.org"); // still pass diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestVeryLongFileName.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestVeryLongFileName.java index 4fe347e3b8..10fdc35a38 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/TestVeryLongFileName.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/TestVeryLongFileName.java @@ -20,7 +20,6 @@ */ package org.biojava.nbio.structure; -import org.junit.Assert; import org.junit.Test; diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/TestAlignmentConsistency.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/TestAlignmentConsistency.java index 4cdd29eae9..0d1da5b6d1 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/TestAlignmentConsistency.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/TestAlignmentConsistency.java @@ -29,12 +29,13 @@ import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.util.AtomCache; import org.junit.Test; -import static org.junit.Assert.*; import java.io.IOException; import java.util.Arrays; import java.util.List; +import static org.junit.Assert.assertEquals; + public class TestAlignmentConsistency { // Check that indices of the aligned residues are unique diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/ce/CeCPMainTest.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/ce/CeCPMainTest.java index 0d76dc98ce..87d95dc57b 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/ce/CeCPMainTest.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/ce/CeCPMainTest.java @@ -28,12 +28,10 @@ import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.util.AtomCache; -import org.biojava.nbio.structure.io.PDBParseException; import org.junit.Assert; import org.junit.Test; import java.io.IOException; -import java.lang.reflect.InvocationTargetException; import java.util.Arrays; @@ -81,12 +79,12 @@ public void testFilterDuplicateAFPs() throws Exception { int[] expectedLen = new int[] { expected[0][0].length, expected[1][0].length }; Assert.assertTrue(Arrays.deepEquals(expected, align)); - Assert.assertTrue(Arrays.equals(expectedLen, blkLen)); + Assert.assertArrayEquals(expectedLen, blkLen); } @Test - public void testFilterDuplicateAFPsMinLenCTerm() throws PDBParseException, StructureException { + public void testFilterDuplicateAFPsMinLenCTerm() throws StructureException { int[][][] startAln, filteredAln; int[] filteredLen; int ca2len; @@ -129,7 +127,7 @@ public void testFilterDuplicateAFPsMinLenCTerm() throws PDBParseException, Struc result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params); Assert.assertTrue("Wrong optAln for minCPlength=" + minCPlength, Arrays.deepEquals(filteredAln, result.getOptAln())); - Assert.assertTrue("Wrong optLen for minCPlength=" + minCPlength, Arrays.equals(filteredLen, result.getOptLen())); + Assert.assertArrayEquals("Wrong optLen for minCPlength=" + minCPlength, filteredLen, result.getOptLen()); } // For minCPlength=4, filtering changes @@ -149,7 +147,7 @@ public void testFilterDuplicateAFPsMinLenCTerm() throws PDBParseException, Struc result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params); Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln())); - Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen())); + Assert.assertArrayEquals("Wrong optLen for minCPlength=" + params.getMinCPLength(), filteredLen, result.getOptLen()); // For minCPlength=5, filtering changes params.setMinCPLength(5); @@ -164,13 +162,13 @@ public void testFilterDuplicateAFPsMinLenCTerm() throws PDBParseException, Struc result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params); Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln())); - Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen())); + Assert.assertArrayEquals("Wrong optLen for minCPlength=" + params.getMinCPLength(), filteredLen, result.getOptLen()); params.setMinCPLength(7); result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params); Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln())); - Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen())); + Assert.assertArrayEquals("Wrong optLen for minCPlength=" + params.getMinCPLength(), filteredLen, result.getOptLen()); // Eventually, no alignment! params.setMinCPLength(8); @@ -181,12 +179,12 @@ public void testFilterDuplicateAFPsMinLenCTerm() throws PDBParseException, Struc result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params); Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln())); - Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen())); + Assert.assertArrayEquals("Wrong optLen for minCPlength=" + params.getMinCPLength(), filteredLen, result.getOptLen()); } @Test - public void testFilterDuplicateAFPsMinLenNTerm() throws PDBParseException, StructureException { + public void testFilterDuplicateAFPsMinLenNTerm() throws StructureException { int[][][] startAln, filteredAln; int ca2len; @@ -228,7 +226,7 @@ public void testFilterDuplicateAFPsMinLenNTerm() throws PDBParseException, Struc result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params); Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln())); - Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen())); + Assert.assertArrayEquals("Wrong optLen for minCPlength=" + params.getMinCPLength(), filteredLen, result.getOptLen()); } // For minCPlength=3, filtering changes @@ -248,7 +246,7 @@ public void testFilterDuplicateAFPsMinLenNTerm() throws PDBParseException, Struc result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params); Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln())); - Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen())); + Assert.assertArrayEquals("Wrong optLen for minCPlength=" + params.getMinCPLength(), filteredLen, result.getOptLen()); // For minCPlength=4, filtering changes params.setMinCPLength(5); @@ -263,13 +261,13 @@ public void testFilterDuplicateAFPsMinLenNTerm() throws PDBParseException, Struc result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params); Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln())); - Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen())); + Assert.assertArrayEquals("Wrong optLen for minCPlength=" + params.getMinCPLength(), filteredLen, result.getOptLen()); params.setMinCPLength(8); result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params); Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln())); - Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen())); + Assert.assertArrayEquals("Wrong optLen for minCPlength=" + params.getMinCPLength(), filteredLen, result.getOptLen()); // Eventually, no alignment! params.setMinCPLength(9); @@ -280,7 +278,7 @@ public void testFilterDuplicateAFPsMinLenNTerm() throws PDBParseException, Struc result = CeCPMain.filterDuplicateAFPs(afpChain, new CECalculator(null), ca1, ca2,params); Assert.assertTrue("Wrong optAln for minCPlength=" + params.getMinCPLength(), Arrays.deepEquals(filteredAln, result.getOptAln())); - Assert.assertTrue("Wrong optLen for minCPlength=" + params.getMinCPLength(), Arrays.equals(filteredLen, result.getOptLen())); + Assert.assertArrayEquals("Wrong optLen for minCPlength=" + params.getMinCPLength(), filteredLen, result.getOptLen()); } @@ -305,7 +303,7 @@ private AFPChain makeDummyAFPChain(int[][][] dupAlign, Atom[] ca1,Atom[] ca2) { @Test - public void testCalculateMinCP() throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { + public void testCalculateMinCP() throws SecurityException, IllegalArgumentException { int[] block; int ca2len; @@ -380,9 +378,8 @@ public void testCalculateMinCP() throws SecurityException, NoSuchMethodException * * @param len * @return - * @throws PDBParseException - */ - private Atom[] makeDummyCA(int len) throws PDBParseException { + */ + private Atom[] makeDummyCA(int len) { Atom[] ca1; Chain chain1 = new ChainImpl(); chain1.setId("A"); @@ -395,7 +392,7 @@ private Atom[] makeDummyCA(int len) throws PDBParseException { ca1[i].setCoords(new double[] { i, 0, 0 }); Group aa = new AminoAcidImpl(); aa.setPDBName("GLY"); - aa.setResidueNumber( ResidueNumber.fromString(i+"")); + aa.setResidueNumber( ResidueNumber.fromString(String.valueOf(i))); aa.addAtom(ca1[i]); chain1.addGroup(aa); } diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/ce/TestSmallAlignment.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/ce/TestSmallAlignment.java index 476b8bafb8..bf48dd2e6c 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/ce/TestSmallAlignment.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/ce/TestSmallAlignment.java @@ -52,18 +52,18 @@ public void test1a4w() throws IOException, StructureException { AFPChain afpChain = ce.align(ca1, ca2); - Assert.assertTrue(afpChain != null); + Assert.assertNotNull(afpChain); afpChain.setName1(name1); afpChain.setName2(name2); - Assert.assertTrue(afpChain.getNrEQR() == 0); + Assert.assertEquals(0, afpChain.getNrEQR()); String xml = AFPChainXMLConverter.toXML(afpChain,ca1,ca2); AFPChain newChain = AFPChainXMLParser.fromXML(xml, ca1, ca2); - Assert.assertTrue(newChain != null); + Assert.assertNotNull(newChain); String xml2 = AFPChainXMLConverter.toXML(newChain,ca1,ca2); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/ce/TestWebStartClient.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/ce/TestWebStartClient.java index f62b4b7beb..2884534205 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/ce/TestWebStartClient.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/ce/TestWebStartClient.java @@ -24,6 +24,7 @@ package org.biojava.nbio.structure.align.ce; +import org.biojava.nbio.core.util.PrettyXMLWriter; import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.StructureAlignment; @@ -34,7 +35,6 @@ import org.biojava.nbio.structure.align.xml.AFPChainFlipper; import org.biojava.nbio.structure.align.xml.AFPChainXMLConverter; import org.biojava.nbio.structure.align.xml.AFPChainXMLParser; -import org.biojava.nbio.core.util.PrettyXMLWriter; import org.junit.Assert; import org.junit.Test; @@ -88,7 +88,7 @@ private void align(String name1, String name2, StructureAlignment algorithm) Assert.assertNotNull(afpChain); Assert.assertNotNull(afpChain.getAlgorithmName()); - Assert.assertTrue(afpChain.getAlgorithmName().equals(algorithm.getAlgorithmName())); + Assert.assertEquals(afpChain.getAlgorithmName(), algorithm.getAlgorithmName()); String xml = AFPChainXMLConverter.toXML(afpChain,ca1,ca2); @@ -97,7 +97,7 @@ private void align(String name1, String name2, StructureAlignment algorithm) AFPChain afpServer = JFatCatClient.getAFPChainFromServer(serverLocation,algorithm.getAlgorithmName(), name1, name2, ca1, ca2, 5000); Assert.assertNotNull(afpServer); - Assert.assertTrue("Algorithm names don't match!", afpServer.getAlgorithmName().equals(algorithm.getAlgorithmName())); + Assert.assertEquals("Algorithm names don't match!", afpServer.getAlgorithmName(), algorithm.getAlgorithmName()); Assert.assertTrue("Alignment blockNum < 1", afpServer.getBlockNum() >= 1); String xml2 = AFPChainXMLConverter.toXML(afpServer, ca1, ca2); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/client/TestStructureName.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/client/TestStructureName.java index 3b197d733f..dc61324d0b 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/client/TestStructureName.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/client/TestStructureName.java @@ -20,17 +20,16 @@ */ package org.biojava.nbio.structure.align.client; -import static org.biojava.nbio.structure.align.client.StructureName.Source.*; -import static org.junit.Assert.*; +import org.biojava.nbio.structure.StructureException; +import org.junit.Ignore; +import org.junit.Test; import java.io.File; -import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; -import org.biojava.nbio.structure.StructureException; -import org.junit.Ignore; -import org.junit.Test; +import static org.biojava.nbio.structure.align.client.StructureName.Source.*; +import static org.junit.Assert.*; public class TestStructureName { @@ -95,7 +94,7 @@ public void testSingleCharChainIds() throws StructureException { } @Test - public void testFiles() throws IOException { + public void testFiles() { File f = new File("hopefully_this_doesnt_exist_nalkjas3"); assertFalse(f.exists()); assertNull(f.getParentFile()); @@ -114,72 +113,72 @@ public void testPrefixes() throws StructureException { // Basic case sn = new StructureName("PDB:4hhb"); assertTrue(sn.isPdbId()); - assertTrue(sn.getSource() == PDB); + assertSame(sn.getSource(), PDB); assertEquals("4HHB",sn.getPdbId()); sn = new StructureName("PDB:4hhb.A:1-50"); assertTrue(sn.isPdbId()); - assertTrue(sn.getSource() == PDB); + assertSame(sn.getSource(), PDB); assertEquals("4HHB",sn.getPdbId()); // Invalid strings work too, they just don't load sn = new StructureName("PDB:x"); assertTrue(sn.isPdbId()); - assertTrue(sn.getSource() == PDB); + assertSame(sn.getSource(), PDB); assertEquals("x",sn.getPdbId()); // SCOP sn = new StructureName("SCOP:d2gs2a_"); assertTrue(sn.isScopName()); - assertTrue(sn.getSource() == SCOP); + assertSame(sn.getSource(), SCOP); assertEquals("2GS2",sn.getPdbId()); // CATH sn = new StructureName("CATH:1qvrC03"); assertTrue(sn.isCathID()); - assertTrue(sn.getSource() == CATH); + assertSame(sn.getSource(), CATH); assertEquals("1QVR",sn.getPdbId()); // PDP sn = new StructureName("PDP:4HHBAa"); assertTrue(sn.isPDPDomain()); - assertTrue(sn.getSource() == PDP); + assertSame(sn.getSource(), PDP); assertEquals("4HHB",sn.getPdbId()); // URL sn = new StructureName("URL:http://www.rcsb.org/pdb/files/1B8G.pdb.gz"); assertTrue(sn.isURL()); - assertTrue(sn.getSource() == URL); + assertSame(sn.getSource(), URL); assertEquals("1B8G",sn.getPdbId()); sn = new StructureName("URL:file:///4hhb.pdb"); assertTrue(sn.isURL()); - assertTrue(sn.getSource() == URL); + assertSame(sn.getSource(), URL); assertEquals("4HHB",sn.getPdbId()); // File: expand home directory (invalid URL) sn = new StructureName("FILE:~/4hhb.pdb"); assertTrue(sn.isFile()); - assertTrue(sn.getSource() == FILE); + assertSame(sn.getSource(), FILE); assertEquals("4HHB",sn.getPdbId()); // Relative file (invalid URL) sn = new StructureName("file:4hhb.pdb"); assertTrue(sn.isFile()); - assertTrue(sn.getSource() == FILE); + assertSame(sn.getSource(), FILE); assertEquals("4HHB",sn.getPdbId()); // Absolute paths are valid URLs sn = new StructureName("file:/4hhb_other.pdb"); assertTrue(sn.isURL()); - assertTrue(sn.getSource() == URL); + assertSame(sn.getSource(), URL); assertEquals("4HHB",sn.getPdbId()); // ECOD sn = new StructureName("e1lyw.1"); assertTrue(sn.isEcodDomain()); - assertTrue(sn.getSource() == ECOD); + assertSame(sn.getSource(), ECOD); assertEquals("1LYW",sn.getPdbId()); // BIO sn = new StructureName("BIO:2ehz:1"); assertTrue(sn.isBioAssembly()); - assertTrue(sn.getSource() == BIO); + assertSame(sn.getSource(), BIO); assertEquals("2EHZ",sn.getPdbId()); // Invalid prefix sn = new StructureName("XXX:2ehz"); assertTrue(sn.isPdbId()); - assertTrue(sn.getSource() == PDB); + assertSame(sn.getSource(), PDB); assertEquals("XXX:2ehz",sn.getPdbId()); } @@ -194,40 +193,40 @@ public void testGuesses() throws StructureException { // Basic case sn = new StructureName("4hhb"); assertTrue(sn.isPdbId()); - assertTrue(sn.getSource() == PDB); + assertSame(sn.getSource(), PDB); assertEquals("4HHB",sn.getPdbId()); sn = new StructureName("4hhb.A:1-50"); assertTrue(sn.isPdbId()); - assertTrue(sn.getSource() == PDB); + assertSame(sn.getSource(), PDB); assertEquals("4HHB",sn.getPdbId()); // Invalid strings work too, they just don't load sn = new StructureName("x"); assertTrue(sn.isPdbId()); - assertTrue(sn.getSource() == PDB); + assertSame(sn.getSource(), PDB); assertEquals("x",sn.getPdbId()); // SCOP sn = new StructureName("d2gs2a_"); assertTrue(sn.isScopName()); - assertTrue(sn.getSource() == SCOP); + assertSame(sn.getSource(), SCOP); assertEquals("2GS2",sn.getPdbId()); // CATH sn = new StructureName("1qvrC03"); assertTrue(sn.isCathID()); - assertTrue(sn.getSource() == CATH); + assertSame(sn.getSource(), CATH); assertEquals("1QVR",sn.getPdbId()); // PDP is not guessed sn = new StructureName("4HHBAa"); assertFalse(sn.isPDPDomain()); - assertTrue(sn.getSource() == PDB); + assertSame(sn.getSource(), PDB); assertEquals("4HHBAa",sn.getPdbId()); // URL sn = new StructureName("http://www.rcsb.org/pdb/files/1B8G.pdb.gz"); assertTrue(sn.isURL()); - assertTrue(sn.getSource() == URL); + assertSame(sn.getSource(), URL); assertEquals("1B8G",sn.getPdbId()); sn = new StructureName("file:///4hhb.pdb"); assertTrue(sn.isURL()); - assertTrue(sn.getSource() == URL); + assertSame(sn.getSource(), URL); assertEquals("4HHB",sn.getPdbId()); @@ -249,12 +248,12 @@ public void testGuesses() throws StructureException { // ECOD sn = new StructureName("e1lyw.1"); assertTrue(sn.isEcodDomain()); - assertTrue(sn.getSource() == ECOD); + assertSame(sn.getSource(), ECOD); assertEquals("1LYW",sn.getPdbId()); // BIO is not guessed sn = new StructureName("2ehz:1"); assertFalse(sn.isBioAssembly()); - assertTrue(sn.getSource() == PDB); + assertSame(sn.getSource(), PDB); assertEquals("2ehz:1",sn.getPdbId()); } diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/multiple/TestAFPChainConversion.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/multiple/TestAFPChainConversion.java index bc9837f5a3..49ce1102df 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/multiple/TestAFPChainConversion.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/multiple/TestAFPChainConversion.java @@ -28,7 +28,7 @@ import org.biojava.nbio.structure.jama.Matrix; import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; /** * Test that all relevant information (except scores and cache) is correctly @@ -40,7 +40,7 @@ public class TestAFPChainConversion { @Test - public void testAFPconversion() throws Exception{ + public void testAFPconversion() { //Fill an AFPChain with the general information AFPChain afp = new AFPChain("algorithm"); @@ -82,8 +82,7 @@ public void testAFPconversion() throws Exception{ assertEquals(afp.getName2(), ensemble.getStructureIdentifiers().get(1).getIdentifier()); assertEquals(afp.getAlgorithmName(), ensemble.getAlgorithmName()); assertEquals(afp.getVersion(),ensemble.getVersion()); - assertTrue(ensemble.getCalculationTime().equals( - afp.getCalculationTime())); + assertEquals((long) ensemble.getCalculationTime(), afp.getCalculationTime()); assertEquals(afp.getBlockNum(), msa.getBlockSets().size()); for (int b = 0; b atomArrays = new ArrayList(3); + List atomArrays = new ArrayList<>(3); for (int str=0; str<3; str++){ Atom[] atoms = StructureTools. getRepresentativeAtomArray(structure); @@ -89,16 +85,16 @@ public static MultipleAlignment testAlignment1() ensemble.setAlgorithmName("testAlignment"); ensemble.setVersion("1.0"); ensemble.setCalculationTime((long) 1000000000); - ensemble.setStructureIdentifiers(Arrays.asList(new StructureName("2gox"),new StructureName("2gox"),new StructureName("2gox"))); + ensemble.setStructureIdentifiers(Arrays.asList(new StructureName("2gox"),new StructureName("2gox"),new StructureName("2gox"))); //Generate the MultipleAlignment - 2 blocks with 2 blocksets each int[] nextResidue = new int[3]; for (int bs=0; bs<2; bs++){ BlockSet blockSet = new BlockSetImpl(msa); for (int b=0; b<2; b++){ - List> alnRes = new ArrayList>(3); + List> alnRes = new ArrayList<>(3); for (int str=0; str<3; str++){ - List chain = new ArrayList(50); + List chain = new ArrayList<>(50); for (int res=0; res<10; res++){ //Introduce gaps and discontinuities if (nextResidue[str] % (2+str) == str)chain.add(null); @@ -138,11 +134,11 @@ public static MultipleAlignment testAlignment2() throws StructureException, IOException { //Download the globin structures - List names = Arrays.asList( + List names = Arrays.asList( new StructureName("1mbc"), new StructureName("1hlb"), new StructureName("1thb.A"), new StructureName("1ith.A")); AtomCache cache = new AtomCache(); - List atomArrays = new ArrayList(); + List atomArrays = new ArrayList<>(); for (StructureIdentifier name:names) atomArrays.add(cache.getAtoms(name)); MultipleAlignmentEnsemble ensemble = @@ -165,9 +161,9 @@ public static MultipleAlignment testAlignment2() Block block1 = new BlockImpl(blockSet1); Block block2 = new BlockImpl(blockSet1); Block block3 = new BlockImpl(blockSet2); - block1.setAlignRes(new ArrayList>()); - block2.setAlignRes(new ArrayList>()); - block3.setAlignRes(new ArrayList>()); + block1.setAlignRes(new ArrayList<>()); + block2.setAlignRes(new ArrayList<>()); + block3.setAlignRes(new ArrayList<>()); List aligned11 = Arrays.asList( 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/multiple/util/TestMultipleAlignmentScorer.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/multiple/util/TestMultipleAlignmentScorer.java index b080daf0b5..8f271acadc 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/multiple/util/TestMultipleAlignmentScorer.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/multiple/util/TestMultipleAlignmentScorer.java @@ -20,31 +20,16 @@ */ package org.biojava.nbio.structure.align.multiple.util; +import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.align.multiple.*; +import org.junit.Test; + +import javax.vecmath.Matrix4d; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import javax.vecmath.Matrix4d; - -import org.biojava.nbio.structure.AminoAcidImpl; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.AtomImpl; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.ChainImpl; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.align.multiple.Block; -import org.biojava.nbio.structure.align.multiple.BlockImpl; -import org.biojava.nbio.structure.align.multiple.BlockSet; -import org.biojava.nbio.structure.align.multiple.BlockSetImpl; -import org.biojava.nbio.structure.align.multiple.MultipleAlignment; -import org.biojava.nbio.structure.align.multiple.MultipleAlignmentImpl; -import org.biojava.nbio.structure.align.multiple.util.MultipleAlignmentScorer; -import org.biojava.nbio.structure.align.multiple.util.ReferenceSuperimposer; -import org.junit.Test; - -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; /** * Test the correctness of various Score calculations for @@ -62,7 +47,7 @@ public class TestMultipleAlignmentScorer { @Test - public void testRefRMSD() throws Exception{ + public void testRefRMSD() { //Identity Test: RefRMSD has to be equal to 0.0 MultipleAlignment identMSA = identityMSTA(); @@ -81,7 +66,7 @@ public void testRefRMSD() throws Exception{ } @Test - public void testRMSD() throws Exception{ + public void testRMSD() { //Identity Test: RMSD has to be equal to 0.0 MultipleAlignment identMSA = identityMSTA(); @@ -138,7 +123,7 @@ public void testAvgTMScore() throws Exception{ } @Test - public void testMCScore() throws Exception { + public void testMCScore() { //Identity Test: MultipleMC-Score has to be equal to 576.21 MultipleAlignment identMSA = identityMSTA(); @@ -161,18 +146,17 @@ public void testMCScore() throws Exception { * the same Atoms and perfectly aligned, so that TM-score = 1 * and RMSD = 0. * @return MultipleAlignment identity - * @throws StructureException - */ - private MultipleAlignment identityMSTA() throws StructureException { + */ + private MultipleAlignment identityMSTA() { //Generate the identical Atom arrays - List atomArrays = new ArrayList(20); + List atomArrays = new ArrayList<>(20); for (int i=0; i<3; i++) atomArrays.add(makeDummyCA(20)); //Generate the identity alignment (1-1-1,2-2-2,etc) - List> alnRes = new ArrayList>(3); + List> alnRes = new ArrayList<>(3); for (int str=0; str<3; str++){ - List chain = new ArrayList(20); + List chain = new ArrayList<>(20); for (int res=0; res<20; res++) chain.add(res); alnRes.add(chain); } @@ -196,18 +180,17 @@ private MultipleAlignment identityMSTA() throws StructureException { * Atoms but incorreclty aligned (offset of 1 position) without gaps. * * @return MultipleAlignment simple MSTA - * @throws StructureException */ - private MultipleAlignment simpleMSTA() throws StructureException{ + private MultipleAlignment simpleMSTA() { //Generate three identical Atom arrays - List atomArrays = new ArrayList(52); + List atomArrays = new ArrayList<>(52); for (int i=0; i<3; i++) atomArrays.add(makeDummyCA(52)); //Generate the incorrect alignment (0-1-2,1-2-3,etc) - List> alnRes = new ArrayList>(3); + List> alnRes = new ArrayList<>(3); for (int str=0; str<3; str++){ - List chain = new ArrayList(50); + List chain = new ArrayList<>(50); for (int res=0; res<50; res++) chain.add(res+str); alnRes.add(chain); } @@ -232,16 +215,15 @@ private MultipleAlignment simpleMSTA() throws StructureException{ * same Atoms but incorreclty aligned with gaps. * * @return MultipleAlignment gapped MSTA - * @throws StructureException */ - private MultipleAlignment gappedMSTA() throws StructureException{ + private MultipleAlignment gappedMSTA() { //Generate three identical Atom arrays - List atomArrays = new ArrayList(30); + List atomArrays = new ArrayList<>(30); for (int i=0; i<3; i++) atomArrays.add(makeDummyCA(30)); //Generate alignment with nulls and some missalignments - List> alnRes = new ArrayList>(3); + List> alnRes = new ArrayList<>(3); List chain1 = Arrays.asList( 1, 2, 3, 5, 8, 10, 12, 15, 17, 19, 22, null, 24, 27); List chain2 = Arrays.asList( @@ -282,7 +264,7 @@ private Atom[] makeDummyCA(int len) { ca1[i].setCoords(new double[] { i, 0, 0 }); Group aa = new AminoAcidImpl(); aa.setPDBName("GLY"); - aa.setResidueNumber( ResidueNumber.fromString(i+"")); + aa.setResidueNumber( ResidueNumber.fromString(String.valueOf(i))); aa.addAtom(ca1[i]); chain1.addGroup(aa); } diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/multiple/util/TestMultipleAlignmentTools.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/multiple/util/TestMultipleAlignmentTools.java index 12cf116f48..ea660480ed 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/multiple/util/TestMultipleAlignmentTools.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/multiple/util/TestMultipleAlignmentTools.java @@ -20,19 +20,14 @@ */ package org.biojava.nbio.structure.align.multiple.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import org.biojava.nbio.structure.align.multiple.*; +import org.junit.Test; import java.util.Arrays; import java.util.List; -import org.biojava.nbio.structure.align.multiple.Block; -import org.biojava.nbio.structure.align.multiple.BlockImpl; -import org.biojava.nbio.structure.align.multiple.BlockSet; -import org.biojava.nbio.structure.align.multiple.BlockSetImpl; -import org.biojava.nbio.structure.align.multiple.MultipleAlignment; -import org.biojava.nbio.structure.align.multiple.MultipleAlignmentImpl; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; /** * @@ -48,7 +43,7 @@ public class TestMultipleAlignmentTools { */ public static class NamedBlock extends BlockImpl { private static final long serialVersionUID = 5060618718423340848L; - private String name; + private final String name; public NamedBlock(String name, BlockSet bs) { super(bs); this.name = name; @@ -88,7 +83,7 @@ public void testSortBlocks() { Arrays.asList( 20, 21, 22), Arrays.asList( 10, 11, 12), Arrays.asList( 10, null, 12), - Arrays.asList( (Integer)null,null,null), + Arrays.asList(null,null,null), Arrays.asList( 10, 11, 12), Arrays.asList( 10, 11, 12) )); @@ -106,7 +101,7 @@ public void testSortBlocks() { Arrays.asList( 40, 41, 42), Arrays.asList( 30, 31, 32), Arrays.asList( null, 31, 32), - Arrays.asList( (Integer)null,null,null), + Arrays.asList(null,null,null), Arrays.asList( 30, 51, 52), Arrays.asList( 30, 31, 32) )); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/multiple/util/TestMultipleAlignmentWriter.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/multiple/util/TestMultipleAlignmentWriter.java index c7f427e9c5..3f89012228 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/multiple/util/TestMultipleAlignmentWriter.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/multiple/util/TestMultipleAlignmentWriter.java @@ -20,17 +20,16 @@ */ package org.biojava.nbio.structure.align.multiple.util; -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; - import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.multiple.MultipleAlignment; import org.biojava.nbio.structure.align.multiple.TestSampleGenerator; -import org.biojava.nbio.structure.align.multiple.util.MultipleAlignmentWriter; import org.junit.Test; -import static org.junit.Assert.*; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +import static org.junit.Assert.assertEquals; /** * Test the correctness of various Text outputs for {@link MultipleAlignment}s. @@ -47,8 +46,8 @@ */ public class TestMultipleAlignmentWriter { - private MultipleAlignment alignment1; - private MultipleAlignment alignment2; + private final MultipleAlignment alignment1; + private final MultipleAlignment alignment2; /** * Build the alignments in common for every writer output, so that they do @@ -70,7 +69,7 @@ public void testFASTA1() throws IOException { FileReader file = new FileReader("src/test/resources/testMSTA1.fasta"); BufferedReader reader = new BufferedReader(file); - String line = null; + String line; StringBuilder stringBuilder = new StringBuilder(); while ((line = reader.readLine()) != null) { @@ -90,7 +89,7 @@ public void testFASTA2() throws IOException { FileReader file = new FileReader("src/test/resources/testMSTA2.fasta"); BufferedReader reader = new BufferedReader(file); - String line = null; + String line; StringBuilder stringBuilder = new StringBuilder(); while ((line = reader.readLine()) != null) { @@ -110,7 +109,7 @@ public void testFatCat1() throws IOException { FileReader file = new FileReader("src/test/resources/testMSTA1.fatcat"); BufferedReader reader = new BufferedReader(file); - String line = null; + String line; StringBuilder stringBuilder = new StringBuilder(); while ((line = reader.readLine()) != null) { @@ -130,7 +129,7 @@ public void testFatCat2() throws IOException { FileReader file = new FileReader("src/test/resources/testMSTA2.fatcat"); BufferedReader reader = new BufferedReader(file); - String line = null; + String line; StringBuilder stringBuilder = new StringBuilder(); while ((line = reader.readLine()) != null) { @@ -151,7 +150,7 @@ public void testAlignedResidues1() throws IOException { FileReader file = new FileReader( "src/test/resources/testMSTA1_alnres.tsv"); BufferedReader reader = new BufferedReader(file); - String line = null; + String line; StringBuilder stringBuilder = new StringBuilder(); while ((line = reader.readLine()) != null) { @@ -172,7 +171,7 @@ public void testAlignedResidues2() throws IOException { FileReader file = new FileReader( "src/test/resources/testMSTA2_alnres.tsv"); BufferedReader reader = new BufferedReader(file); - String line = null; + String line; StringBuilder stringBuilder = new StringBuilder(); while ((line = reader.readLine()) != null) { diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/multiple/util/TestMultipleAlignmentXMLParser.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/multiple/util/TestMultipleAlignmentXMLParser.java index 195e1015c8..343f719b32 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/multiple/util/TestMultipleAlignmentXMLParser.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/multiple/util/TestMultipleAlignmentXMLParser.java @@ -20,25 +20,19 @@ */ package org.biojava.nbio.structure.align.multiple.util; -import static org.junit.Assert.*; - -import java.io.IOException; -import java.util.List; - -import javax.vecmath.Matrix4d; -import javax.xml.parsers.ParserConfigurationException; - import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.align.multiple.Block; -import org.biojava.nbio.structure.align.multiple.BlockSet; -import org.biojava.nbio.structure.align.multiple.MultipleAlignment; -import org.biojava.nbio.structure.align.multiple.MultipleAlignmentEnsemble; -import org.biojava.nbio.structure.align.multiple.TestSampleGenerator; -import org.biojava.nbio.structure.align.multiple.util.MultipleAlignmentWriter; +import org.biojava.nbio.structure.align.multiple.*; import org.biojava.nbio.structure.align.xml.MultipleAlignmentXMLParser; import org.junit.Test; import org.xml.sax.SAXException; +import javax.vecmath.Matrix4d; +import javax.xml.parsers.ParserConfigurationException; +import java.io.IOException; +import java.util.List; + +import static org.junit.Assert.assertTrue; + /** * Test the correctness of converting and parsing a MultipleAlignment * into an XML format. It checks that the alignments before converting diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/util/AtomCacheTest.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/util/AtomCacheTest.java index 58a2623062..73275bd149 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/util/AtomCacheTest.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/util/AtomCacheTest.java @@ -20,37 +20,8 @@ */ package org.biojava.nbio.structure.align.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.zip.GZIPOutputStream; - -import org.biojava.nbio.core.util.FileDownloadUtils; -import org.biojava.nbio.structure.AtomPositionMap; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.ResidueRangeAndLength; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; -import org.biojava.nbio.structure.StructureIdentifier; -import org.biojava.nbio.structure.StructureTools; -import org.biojava.nbio.structure.SubstructureIdentifier; +import org.biojava.nbio.core.util.Download; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.io.LocalPDBDirectory; import org.biojava.nbio.structure.io.LocalPDBDirectory.FetchBehavior; import org.biojava.nbio.structure.io.LocalPDBDirectory.ObsoleteBehavior; @@ -67,6 +38,22 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.zip.GZIPOutputStream; + +import static org.junit.Assert.*; + /** * A test for {@link AtomCache}. @@ -75,7 +62,7 @@ */ public class AtomCacheTest { - private static Logger logger = LoggerFactory.getLogger(AtomCacheTest.class); + private static final Logger logger = LoggerFactory.getLogger(AtomCacheTest.class); private AtomCache cache; @Before @@ -187,14 +174,14 @@ public void testGetStructureForChainlessDomains() throws IOException, StructureE } @Test - public void testSetPath_withTilde() throws Exception { + public void testSetPath_withTilde() { cache.setPath("~" + File.separator); assertEquals(System.getProperty("user.home") + File.separator, cache.getPath()); } @Test - public void testNewInstanceWithTilder() throws Exception { + public void testNewInstanceWithTilder() { AtomCache cache1 = new AtomCache("~" + File.separator); assertEquals(System.getProperty("user.home") + File.separator, cache1.getPath()); @@ -367,7 +354,7 @@ public void testEmptyChemComp() throws IOException, StructureException { System.setProperty(UserConfiguration.PDB_DIR, tmpCache.toString()); System.setProperty(UserConfiguration.PDB_CACHE_DIR, tmpCache.toString()); - FileDownloadUtils.deleteDirectory(tmpCache); + Download.deleteDirectory(tmpCache); Files.createDirectory(tmpCache); try { cache.setPath(tmpCache.toString()); @@ -387,7 +374,7 @@ public void testEmptyChemComp() throws IOException, StructureException { Files.createDirectories(testCif.getParent()); URL resource = AtomCacheTest.class.getResource("/atp.cif.gz"); File src = new File(resource.getPath()); - FileDownloadUtils.copy(src, testCif.toFile()); + Download.copy(src, testCif.toFile()); // Load structure Structure s = cache.getStructure("1ABC"); @@ -399,7 +386,7 @@ public void testEmptyChemComp() throws IOException, StructureException { assertNotNull(s); Group g = s.getChain("A").getAtomGroup(0); - assertTrue(g.getPDBName().equals("ATP")); + assertEquals("ATP", g.getPDBName()); // should be unknown ChemComp chem = g.getChemComp(); @@ -407,7 +394,7 @@ public void testEmptyChemComp() throws IOException, StructureException { assertTrue(chem.getAtoms().size() > 0); assertEquals("NON-POLYMER", chem.getType()); } finally { - FileDownloadUtils.deleteDirectory(tmpCache); + Download.deleteDirectory(tmpCache); } } @@ -426,7 +413,7 @@ public void testEmptyGZChemComp() throws IOException, StructureException { System.setProperty(UserConfiguration.PDB_DIR, tmpCache.toString()); System.setProperty(UserConfiguration.PDB_CACHE_DIR, tmpCache.toString()); - FileDownloadUtils.deleteDirectory(tmpCache); + Download.deleteDirectory(tmpCache); Files.createDirectory(tmpCache); try { cache.setPath(tmpCache.toString()); @@ -450,7 +437,7 @@ public void testEmptyGZChemComp() throws IOException, StructureException { Files.createDirectories(testCif.getParent()); URL resource = AtomCacheTest.class.getResource("/atp.cif.gz"); File src = new File(resource.getPath()); - FileDownloadUtils.copy(src, testCif.toFile()); + Download.copy(src, testCif.toFile()); // Load structure Structure s = cache.getStructure("1ABC"); @@ -462,7 +449,7 @@ public void testEmptyGZChemComp() throws IOException, StructureException { assertNotNull(s); Group g = s.getChain("A").getAtomGroup(0); - assertTrue(g.getPDBName().equals("ATP")); + assertEquals("ATP", g.getPDBName()); // should be unknown ChemComp chem = g.getChemComp(); @@ -470,7 +457,7 @@ public void testEmptyGZChemComp() throws IOException, StructureException { assertTrue(chem.getAtoms().size() > 0); assertEquals("NON-POLYMER", chem.getType()); } finally { - FileDownloadUtils.deleteDirectory(tmpCache); + Download.deleteDirectory(tmpCache); } } diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/util/RotationAxisTest.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/util/RotationAxisTest.java index e610242b23..85ba3cf6cf 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/align/util/RotationAxisTest.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/align/util/RotationAxisTest.java @@ -51,12 +51,12 @@ import org.biojava.nbio.structure.AtomImpl; import org.junit.Test; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - import javax.vecmath.AxisAngle4d; import javax.vecmath.Matrix4d; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + /** * @author blivens * @@ -64,7 +64,7 @@ public class RotationAxisTest { @Test - public void testProjection() throws Exception{ + public void testProjection() { RotationAxis axis; Atom dir,pos,projected; diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/asa/TestAsaCalc.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/asa/TestAsaCalc.java index 79598bd410..eef49daeb3 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/asa/TestAsaCalc.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/asa/TestAsaCalc.java @@ -20,24 +20,17 @@ */ package org.biojava.nbio.structure.asa; -import org.biojava.nbio.structure.AminoAcidImpl; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.AtomImpl; -import org.biojava.nbio.structure.Element; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.io.mmcif.ChemCompGroupFactory; import org.biojava.nbio.structure.io.mmcif.DownloadChemCompProvider; -import static org.junit.Assert.*; - import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import java.util.List; +import static org.junit.Assert.*; + /** * Testing of Accessible Surface Area calculations * @@ -248,7 +241,7 @@ private Atom getAtom(double x, double y, double z) { public void testNoAtomsAsaCalc() { // in case of no atoms at all, the calculation should not fail and return an empty array - Atom[] atoms = new Atom[0]; + Atom[] atoms = Atom.EmptyAtomArray; AsaCalculator asaCalc = new AsaCalculator(atoms, AsaCalculator.DEFAULT_PROBE_SIZE, diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/basepairs/TestBasePairParameters.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/basepairs/TestBasePairParameters.java index 0b5c3d0349..f430fd40af 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/basepairs/TestBasePairParameters.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/basepairs/TestBasePairParameters.java @@ -24,12 +24,11 @@ import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; -import org.biojava.nbio.structure.basepairs.BasePairParameters; import org.junit.Test; import java.io.IOException; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; /** * This class tests the implementations of the search for base pairs for different RCSB structures diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/cluster/TestSubunitCluster.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/cluster/TestSubunitCluster.java index 4b6e55ee28..ebb2d11ccf 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/cluster/TestSubunitCluster.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/cluster/TestSubunitCluster.java @@ -20,27 +20,15 @@ */ package org.biojava.nbio.structure.cluster; -import static org.junit.Assert.*; +import org.biojava.nbio.core.exceptions.CompoundNotFoundException; +import org.biojava.nbio.structure.*; +import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import java.util.List; -import org.biojava.nbio.core.exceptions.CompoundNotFoundException; -import org.biojava.nbio.structure.AminoAcidImpl; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.AtomImpl; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.ChainImpl; -import org.biojava.nbio.structure.EntityInfo; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; -import org.biojava.nbio.structure.StructureImpl; -import org.biojava.nbio.structure.StructureTools; -import org.junit.Test; +import static org.junit.Assert.*; /** * Test the {@link SubunitCluster} merge and divide methods, one test specific @@ -305,7 +293,7 @@ private Atom[] mockAtomArray(int size1, String type1, int size2, String type2) { atoms.add(a); } } - return atoms.toArray(new Atom[0]); + return atoms.toArray(Atom.EmptyAtomArray); } /** diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/cluster/TestSubunitExtractor.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/cluster/TestSubunitExtractor.java index e80f4c3b1d..c0ea6c45f9 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/cluster/TestSubunitExtractor.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/cluster/TestSubunitExtractor.java @@ -20,16 +20,17 @@ */ package org.biojava.nbio.structure.cluster; -import static org.junit.Assert.*; - -import java.io.IOException; -import java.util.List; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; +import org.biojava.nbio.structure.align.util.AtomCache; import org.junit.Test; +import java.io.IOException; +import java.util.List; + +import static org.junit.Assert.assertEquals; + /** * Test the {@link SubunitExtractor} correctness on different real structures * with different types of difficulties. @@ -85,6 +86,7 @@ public void testHistone() throws StructureException, IOException { @Test public void testBioAssembly() throws StructureException, IOException { + StructureIO.setAtomCache(new AtomCache()); Structure s = StructureIO.getStructure("BIO:4E3E:1"); List subunits = SubunitExtractor.extractSubunits(s, 5, 0.75, 20); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/contact/TestContactCalc.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/contact/TestContactCalc.java index 7d8cf1bfad..f1c5a0fa8d 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/contact/TestContactCalc.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/contact/TestContactCalc.java @@ -30,7 +30,6 @@ import java.io.IOException; - import static org.junit.Assert.*; @@ -88,7 +87,7 @@ public void testIntraChainContacts() throws StructureException, IOException { for (int i = 0; i < cts.length; i++) { logger.info((cts[i] == null ? "ALL" : cts[i][0]) + "\t" + cutoffs[i] + "\t"); - AtomContactSet atomContacts = null; + AtomContactSet atomContacts; if (cts[i] != null && cts[i][0].equals("CA")) { atomContacts = StructureTools.getRepresentativeAtomsInContact(chain, cutoffs[i]); } else { @@ -276,24 +275,28 @@ public void testInterChainContactsVsDistMatrix2TRX() throws IOException, Structu private double[][] calcDistanceMatrix(Atom[] atoms) { - double[][] distMatrix = new double[atoms.length][atoms.length]; + int n = atoms.length; + double[][] distMatrix = new double[n][n]; - for (int i=0;i> unique = new HashSet<>(); + + for (StructureInterface interf : list) { + System.out.println("Interface " + interf.getMoleculeIds()); + AtomContactSet set = interf.getContacts(); + for (AtomContact c : set) + System.out.println(c.getPair() +" - " + c.getDistance()); + + unique.add(interf.getMoleculeIds()); + + } + assertEquals(3, unique.size()); + } + + /** + * Create a mock structure with 2 entities 1 (chains A, B) and 2 (chain C). + * @return a structure + */ + private Structure mockStructure() { + Structure structure = new StructureImpl(); + EntityInfo entity1 = new EntityInfo(); + entity1.setMolId(1); + EntityInfo entity2 = new EntityInfo(); + entity2.setMolId(2); + structure.addEntityInfo(entity1); + structure.addEntityInfo(entity2); + + Chain chainA = new ChainImpl(); + chainA.setId("A"); + chainA.setName("A"); + Chain chainB = new ChainImpl(); + chainB.setId("B"); + chainB.setName("B"); + entity1.addChain(chainA); + entity1.addChain(chainB); + Chain chainC = new ChainImpl(); + chainC.setId("C"); + chainC.setName("C"); + entity2.addChain(chainC); + + structure.addChain(chainA); + structure.addChain(chainB); + structure.addChain(chainC); + + // entity 1: chain A 10 observed residues, chain B 9 observed residues (first unobserved) + List aGroups = getGroupList(10, "ALA", chainA, new Point3d(0,0,0)); + chainA.setAtomGroups(new ArrayList<>(aGroups)); + chainA.setSeqResGroups(aGroups); + chainA.setEntityInfo(entity1); + + List bGroups = getGroupList(10, "ALA", chainB, new Point3d(4, 0, 0)); + chainB.setAtomGroups(new ArrayList<>(bGroups.subList(1,10))); + chainB.setSeqResGroups(bGroups); + chainB.setEntityInfo(entity1); + + List cGroups = getGroupList(20, "GLY", chainC, new Point3d(0, 4, 0)); + chainC.setAtomGroups(new ArrayList<>(cGroups)); + chainC.setSeqResGroups(cGroups); + chainC.setEntityInfo(entity2); + + return structure; + } + + private List getGroupList(int size, String type, Chain chain, Point3d center) { + List list = new ArrayList<>(); + double offsetx = 0; + double offsety = 0; + double offsetz = 0; + for (int i=0;i(5); - cloud2 = new ArrayList(5); + cloud1 = new ArrayList<>(5); + cloud2 = new ArrayList<>(5); Random rnd = new Random(0); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/geometry/TestSuperPositionQCP.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/geometry/TestSuperPositionQCP.java index 8928c26cbd..d86ecd1d6e 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/geometry/TestSuperPositionQCP.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/geometry/TestSuperPositionQCP.java @@ -20,20 +20,18 @@ */ package org.biojava.nbio.structure.geometry; -import static org.junit.Assert.*; - -import java.util.Random; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.vecmath.AxisAngle4d; import javax.vecmath.Matrix4d; import javax.vecmath.Point3d; import javax.vecmath.Vector3d; +import java.util.Random; -import org.biojava.nbio.structure.geometry.SuperPositionQuat; -import org.biojava.nbio.structure.geometry.SuperPositionQCP; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; /** * Test the Quaternion-Based Characteristic Polynomial {@link SuperPositionQCP} diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/geometry/TestUnitQuaternions.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/geometry/TestUnitQuaternions.java index b7456dde1f..1357f9d713 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/geometry/TestUnitQuaternions.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/geometry/TestUnitQuaternions.java @@ -20,23 +20,15 @@ */ package org.biojava.nbio.structure.geometry; -import static org.junit.Assert.*; +import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.align.util.AtomCache; +import org.junit.Test; +import javax.vecmath.*; import java.io.IOException; -import javax.vecmath.AxisAngle4d; -import javax.vecmath.Matrix4d; -import javax.vecmath.Point3d; -import javax.vecmath.Quat4d; -import javax.vecmath.Vector3d; - -import org.biojava.nbio.structure.Calc; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; -import org.biojava.nbio.structure.StructureTools; -import org.biojava.nbio.structure.geometry.UnitQuaternions; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; /** * Test the methods in the {@link UnitQuaternions} class. @@ -170,6 +162,7 @@ public void testOrientationMetricIncrement() throws IOException, transform.rotZ(Math.PI / 15); // Get points from a structure. + StructureIO.setAtomCache(new AtomCache()); Structure pdb = StructureIO.getStructure("4hhb.A"); Point3d[] cloud = Calc.atomsToPoints(StructureTools .getRepresentativeAtomArray(pdb)); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/FastaAFPChainConverterTest.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/FastaAFPChainConverterTest.java index 8ae41a91cd..90aa73f6c4 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/FastaAFPChainConverterTest.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/FastaAFPChainConverterTest.java @@ -24,6 +24,7 @@ */ package org.biojava.nbio.structure.io; +import org.biojava.nbio.core.sequence.ProteinSequence; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureTools; @@ -31,8 +32,6 @@ import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.align.xml.AFPChainXMLConverter; import org.biojava.nbio.structure.scop.ScopFactory; -import org.biojava.nbio.core.exceptions.CompoundNotFoundException; -import org.biojava.nbio.core.sequence.ProteinSequence; import org.custommonkey.xmlunit.DetailedDiff; import org.custommonkey.xmlunit.Diff; import org.custommonkey.xmlunit.Difference; @@ -86,12 +85,10 @@ public static boolean compareXml(File expectedFile, File actualFile) { expectedFr.close(); actualFr.close(); return isSimilar; - } catch (IOException e) { - throw new RuntimeException(e); - } catch (SAXException e) { + } catch (IOException | SAXException e) { throw new RuntimeException(e); } - } + } private AtomCache cache; @@ -102,7 +99,7 @@ public void setUp() { } @Test - public void testCpAsymmetric() throws IOException, StructureException, CompoundNotFoundException { + public void testCpAsymmetric() throws IOException, StructureException { Structure structure = cache.getStructure("1w0p"); String first = ("alfdynatgdtefdspakqgwmqdntnngsgvltnadgmpawlvqgiggraqwtyslstnqhaqassfgwrmttemkvlsggmitnyyangtqrvlpiisldssgnlvvefegqtgrtvlatgtaateyhkfelvflpgsnpsasfyfdgklirdniqptaskQNMIVWGNGSSntdgvaayrdikfei------------------------------------------------------------------------------------------------------------------QGDVIf------------RGPDRIPSIVASsvTPGVVTAFAEKRVGGgdpgalsntNDIITRTSRDGGITWDTELNLTEQinvsdeFDFSDPRPIYDPs---SNTVLVSYARWPtdaaqngdrikpwmpNGIFYSVYDVASgnWQAPIDVTdqvkersfqiagwggselyrrntslnsqqdwqsnakirivdgaanqiqvadgsrkyvvtlsidesgglvanlngvsapiilqsehakvhsfhdyelqysalnhtttlfvdgqqittwagevsqenniqfgnadaqidgrlhvqkivltqqghnlvefdafylaqqtpevekdleklgwtkiktgntmslygNASVNPGpgHGITLtrqqnisgsqNGRLIYPAIVLdrfFLNVMSIYSDDGgsnwq-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------TGSTLpipfrwksssileTLEPSEADMVELQN--GDLLLTARLDFNQivngvny--SPRQQFLSKDGGITWSLLEANNANvfsnistgTVDASITRFEqsdgSHFLLFTNPQGnpagTNgr------------QNLGLWFSFDEG--VTWKGPIQ--LVNGasaysdiyqldsenaivivetdnsnmrilrmpitllkqklt"); String second = ("--------------------------------------------------------------------------------------------kirivdgaanqiqvadgsrkyvvtlsidesgglvanlngvsapiilqsehakvhsfhdyelqysalnhtttLFVDGQQITTWagevsqenniqfgnadaqidgrlhvqkivltqqghnlvefdafylaqqtpevekdleklgwtkiktgntmslygnasvnpgpghgitltrqqnisgsqngrliypaivldrfflnvmsiysddggsnwqTGSTLpipfrwksssileTLEPSEADMVEL--QNGDLLLTARLDFNQivngvny--SPRQQFLSKDGGITWSLLEANNANvfsnisTGTVDASITRFEqsdgSHFLLFTNPQGNpagtngr--------QNLGLWFSFDEG--VTWKGPIQlv---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------NGASAYS--DIYQLd---------SENAIVIVETD---NSNMRILRMPITllkqkltalfdynatgdtefdspakqgwmqdntnngsgvltnadgmpawlvqgiggraqwtyslstnqhaqassfgwrmttemkvlsggmitnyyangtqrvlpiisldssgnlvvefegqtgrtvlatgtaateyhkfelvflpgsnpsasfyfdgklirdniqptaskqnmivwgngssntdgvaayrdikfeiQGDVIf------------RGPDRIPSIVASSVtpGVVTAFAEKRVGGgdpgalsntNDIITRTSRDGGITWDTELNLTEQinvsdefdFSDPRPIYDPs---SNTVLVSYARW----PTdaaqngdrikpwmpNGIFYSVYDVASgnWQAPIDVTdqVKERsfqiagwggselyrrntslnsqqdwqsna------------"); @@ -112,7 +109,7 @@ public void testCpAsymmetric() throws IOException, StructureException, CompoundN } @Test - public void testCpSymmetric2() throws IOException,StructureException, CompoundNotFoundException { + public void testCpSymmetric2() throws IOException,StructureException { String a = "--vRSLNCTLRDSQQ-KSLVMSG---PYELKALHLQgqdmeq-----QVVFSMSFVQGeesndkiPVALGLKEK-NLYLSSVLKdDKPTLQLESVdpknypkkkmekRFVFNKIEInn--KLEFESAQFpnWYISTSqAENmPVFLGGT----KGgqDITDFTMQFV---"; String b = "esnDKIPVALGLKEKnLYLSSVLkddKPTLQLESVDpknypkkkmekRFVFNKIEINN-------KLEFESAQFpNWYISTSQA-ENMPVFLGGTkggqd-------ITDFTMQFVvrslNCTLRDSQQ--KSLVMS-GPY-ELKALHLqgqdME--QQVVFSMSFVqge"; Structure structure = StructureTools.getStructure("31BI"); @@ -122,7 +119,7 @@ public void testCpSymmetric2() throws IOException,StructureException, CompoundNo } @Test - public void testBug1() throws IOException, StructureException, CompoundNotFoundException { + public void testBug1() throws IOException, StructureException { /* * From CriteriaDifference: * [d3er9b_: TM-score=0.6984812617301941, Tmpr=0.14740000665187836] @@ -141,7 +138,7 @@ public void testBug1() throws IOException, StructureException, CompoundNotFoundE } @Test - public void testCpSymmetric1() throws IOException,StructureException, CompoundNotFoundException { + public void testCpSymmetric1() throws IOException,StructureException { //cat 2GG6-best.fasta |tr -d \\n|pbcopy String a = "-SSRPATAR-KSSGLSGTVRIPGDKSISHRSFMFGGLA-SGETRITGLLEG-EDvINTGKAMQAMGARIRKEGd---------TWIIDGVgngglLAPEAPLD---FGNAATGCRLTMGLVGvydFDSTFIGDASLtkrp---MGRVLNPLREMGVQVKSEDgdrLPVTLRGPK---TPT---PITYRVpMASAQVKSAVLLAGLNTPGITTVIEpi---MTRDHTEKMLQGFGANLTVEtdadGVRTIRLEgRGKLTGQVIDVPGDPSSTAFPLVAALLVpGSDVTILNVLMNpTR-TGLILTLQEMGADIEVINprlaggedvaDLRVRSS-----TLKGVTVPedrAPSMIDEYPILAVAAAFAEGATVMNGLEELrvkesdrLSAVANGLKLNGVDCDEGE---TSLVVRGRPdgkGLGNasgAAVAT-HLDHRIAMSFLVMGLVSENPVTVDDatmIATSFPEFMDLMAGLGAKIELS---"; String b = "dGVRTIRLEgRGKLTGQVIDVPGDPSSTAFPLVAALLVpGSDVTILNVLMNpTR-TGLILTLQEMGADIEVINprlaggedvaDLRVRSS-----TLKGVTVPedrAPSMIDEYPILAVAAAfaeGATVMNGLEELrvkesdrLSAVANGLKLNGVDCDEGE---TSLVVRGRPdgkGLGnasGAAVAT-HLDHRIAMSFLVMGLVSENPVTVDDatmiaTSFPEFMDLMAGLGAKIELS----SSRPATAR-KSSGLSGTVRIPGDKSISHRSFMFGGLA-SGETRITGLLEG-EDvINTGKAMQAMGARIRKEGd---------TWIIDGVgngglLAPEAPLD---FGNAATGCRLTMGLVGVYDFDSTFIGDASLtkrp---MGRVLNPLREMGVQVKSEDgdrLPVTLRGPK---TPTP---ITYRVpMASAQVKSAVLLAGLNTPGITTVIE---PIMTRDHTEKMLQGFGANLTVEtda"; @@ -152,7 +149,7 @@ public void testCpSymmetric1() throws IOException,StructureException, CompoundNo } @Test - public void testFromFasta() throws IOException, StructureException, CompoundNotFoundException { + public void testFromFasta() throws IOException, StructureException { Structure s1 = cache.getStructure("1w0p"); Structure s2 = cache.getStructure("1qdm"); ProteinSequence seq1 = new ProteinSequence("GWGG----SEL--YRRNTSLNS--QQDW-------QSNAKIRIVDGAA-----NQIQ"); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/StructureSequenceMatcherTest.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/StructureSequenceMatcherTest.java index ed42a802de..44434bc6e2 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/StructureSequenceMatcherTest.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/StructureSequenceMatcherTest.java @@ -23,10 +23,10 @@ package org.biojava.nbio.structure.io; -import org.biojava.nbio.structure.*; -import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.core.exceptions.CompoundNotFoundException; import org.biojava.nbio.core.sequence.ProteinSequence; +import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.align.util.AtomCache; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -92,7 +92,7 @@ public void setUp() throws IOException, StructureException { //>2PTC:I|PDBID|CHAIN|SEQUENCE "RPDFCLEPPYTGPCKARIIRYFYNAKAGLCQTFVYGGCRAKRNNFKSAEDCMRTCGGA"; - Assert.assertTrue(seq1.length() == pdbNum1.length); + Assert.assertEquals(seq1.length(), pdbNum1.length); /*// report some stats System.out.println("The SEQRES and ATOM information is available via the chains:"); @@ -133,7 +133,7 @@ public void testSubstructureMatchingProteinSequence() throws CompoundNotFoundExc @Test public void testGetProteinSequenceForStructure() { - Map groupIndexPos = new HashMap(); + Map groupIndexPos = new HashMap<>(); ProteinSequence prot = StructureSequenceMatcher.getProteinSequenceForStructure(struct1, groupIndexPos); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestDBRefParsing.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestDBRefParsing.java index 80df942d0f..350bff61e3 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestDBRefParsing.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestDBRefParsing.java @@ -20,20 +20,19 @@ */ package org.biojava.nbio.structure.io; -import static org.junit.Assert.assertEquals; +import org.biojava.nbio.structure.Structure; +import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.junit.Test; +import static org.junit.Assert.assertEquals; public class TestDBRefParsing { @Test - public void testShortLine() throws IOException, StructureException { + public void testShortLine() throws IOException { Structure s,ref; PDBFileParser pdbPars = new PDBFileParser(); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestDifficultMmCIFFiles.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestDifficultMmCIFFiles.java index 5007db9b43..1982839130 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestDifficultMmCIFFiles.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestDifficultMmCIFFiles.java @@ -20,29 +20,7 @@ */ package org.biojava.nbio.structure.io; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeNotNull; -import static org.junit.Assume.assumeTrue; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.List; -import java.util.Map; - -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.mmcif.MMcifParser; import org.biojava.nbio.structure.io.mmcif.SimpleMMcifConsumer; @@ -50,6 +28,16 @@ import org.biojava.nbio.structure.quaternary.BioAssemblyInfo; import org.junit.Test; +import java.io.*; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.*; +import static org.junit.Assume.assumeNotNull; +import static org.junit.Assume.assumeTrue; + /** * Testing parsing of some difficult mmCIF files. * For instance those containing multi-line quoting using ";\n" as delimiters @@ -184,7 +172,7 @@ public void testResidueNumbers() throws IOException, StructureException { } @Test - public void test4letterChains() throws IOException, StructureException, URISyntaxException { + public void test4letterChains() throws IOException, URISyntaxException { String filename = "/1hh0_4char.cif.gz"; URL url = getClass().getResource(filename); assumeNotNull("Can't find resource "+filename,url); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestHardBioUnits.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestHardBioUnits.java index 6362dc2a84..f583889a2c 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestHardBioUnits.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestHardBioUnits.java @@ -20,27 +20,21 @@ */ package org.biojava.nbio.structure.io; -import org.biojava.nbio.structure.Calc; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.geometry.CalcPoint; import org.biojava.nbio.structure.geometry.SuperPosition; import org.biojava.nbio.structure.geometry.SuperPositionQCP; import org.junit.Test; -import static org.junit.Assert.*; - +import javax.vecmath.Matrix4d; +import javax.vecmath.Point3d; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Set; -import javax.vecmath.Matrix4d; -import javax.vecmath.Point3d; +import static org.junit.Assert.*; public class TestHardBioUnits { @@ -136,7 +130,7 @@ public void test4A1I() throws IOException, StructureException { assertEquals(2, bioAssembly.getPolyChains().size()); // here we'll store all author chain ids without the operator id part - Set chainIdsNoOps = new HashSet(); + Set chainIdsNoOps = new HashSet<>(); for (Chain poly:bioAssembly.getPolyChains()) { chainIdsNoOps.add(poly.getName().split("_")[0]); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestHeaderOnly.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestHeaderOnly.java index 9d4c764690..2e23c803f4 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestHeaderOnly.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestHeaderOnly.java @@ -20,18 +20,7 @@ */ package org.biojava.nbio.structure.io; -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import java.util.zip.GZIPInputStream; - -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.LocalPDBDirectory.FetchBehavior; import org.biojava.nbio.structure.io.mmcif.MMcifParser; @@ -43,6 +32,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.zip.GZIPInputStream; + +import static org.junit.Assert.assertNotNull; + public class TestHeaderOnly { private static final Logger logger = LoggerFactory.getLogger(TestHeaderOnly.class); @@ -73,13 +69,13 @@ public void testHeaderOnly() throws StructureException, IOException { Structure sPDB = StructureIO.getStructure(pdbID); - Assert.assertEquals(false, doSeqResHaveAtoms(sPDB)); + Assert.assertFalse(doSeqResHaveAtoms(sPDB)); // Test 2: with mmCIF cache.setUseMmCif(true); Structure sCIF = StructureIO.getStructure(pdbID); - Assert.assertEquals(false, doSeqResHaveAtoms(sCIF)); + Assert.assertFalse(doSeqResHaveAtoms(sCIF)); } @@ -107,14 +103,14 @@ public void testAlignSeqres() throws StructureException, IOException { StructureIO.setAtomCache(cache); Structure sPDB = StructureIO.getStructure(pdbID); - Assert.assertEquals(true, doSeqResHaveAtoms(sPDB)); + Assert.assertTrue(doSeqResHaveAtoms(sPDB)); check1REPChainC(sPDB); // Check particular residues to be aligned. // Test 2: with mmCIF cache.setUseMmCif(true); Structure sCIF = StructureIO.getStructure(pdbID); - Assert.assertEquals(true, doSeqResHaveAtoms(sCIF)); + Assert.assertTrue(doSeqResHaveAtoms(sCIF)); check1REPChainC(sCIF); // Check particular residues to be aligned. } @@ -148,7 +144,7 @@ public void testSpeed() { // Test using local files. @Test - public void testSpeed2() throws StructureException, IOException { + public void testSpeed2() throws IOException { // Test the file parsing speed when the files are already downloaded. InputStream cifStream = new GZIPInputStream(this.getClass().getResourceAsStream("/4hhb.cif.gz")); @@ -222,7 +218,7 @@ public boolean hasAtoms(Group g) { * * @param s: Structure to test. */ - public void check1REPChainC(Structure s) throws StructureException { + public void check1REPChainC(Structure s) { String sequence = "MAETAVINHKKRKNSPRIVQSNDLTEAAYSLSRDQKRMLYLFVDQIRK" + "SDGTLQEHDGICEIHVAKYAEIFGLTSAEASKDIRQALKSFAGKEVVFYRPEEDAGDE" + "KGYESFPWFIKPAHSPSRGLYSVHINPYLIPFFIGLQNRFTQFRLSETKEITNPYAMR" + diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestMMCIFWriting.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestMMCIFWriting.java index f64d5595a5..9f63489022 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestMMCIFWriting.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestMMCIFWriting.java @@ -20,29 +20,7 @@ */ package org.biojava.nbio.structure.io; -import static org.junit.Assert.*; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.util.Arrays; - -import org.biojava.nbio.structure.AminoAcidImpl; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.AtomImpl; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.ChainImpl; -import org.biojava.nbio.structure.Element; -import org.biojava.nbio.structure.EntityInfo; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; -import org.biojava.nbio.structure.StructureImpl; -import org.biojava.nbio.structure.StructureTools; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.mmcif.MMCIFFileTools; import org.biojava.nbio.structure.io.mmcif.MMcifParser; @@ -52,6 +30,12 @@ import org.biojava.nbio.structure.io.mmcif.model.IgnoreField; import org.junit.Test; +import java.io.*; +import java.util.Arrays; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + public class TestMMCIFWriting { @Test diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestMMcifOrganismParsing.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestMMcifOrganismParsing.java index 71733aabaa..c3e24df943 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestMMcifOrganismParsing.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestMMcifOrganismParsing.java @@ -24,20 +24,14 @@ package org.biojava.nbio.structure.io; -import org.biojava.nbio.structure.EntityInfo; -import org.biojava.nbio.structure.EntityType; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; public class TestMMcifOrganismParsing { @@ -45,7 +39,7 @@ public class TestMMcifOrganismParsing { @BeforeClass - public static void setUp() throws Exception { + public static void setUp() { AtomCache cache = new AtomCache(); cache.setUseMmCif(true); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestMmCIFSpecialCases.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestMmCIFSpecialCases.java index 95bb0c29b9..83bab6f865 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestMmCIFSpecialCases.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestMmCIFSpecialCases.java @@ -22,13 +22,13 @@ //import static org.junit.Assert.*; +import org.biojava.nbio.structure.io.mmcif.SimpleMMcifParser; +import org.junit.Test; + import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; -import org.biojava.nbio.structure.io.mmcif.SimpleMMcifParser; -import org.junit.Test; - public class TestMmCIFSpecialCases { /** diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestNonDepositedFiles.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestNonDepositedFiles.java index f5e8e5c27e..86b6e57832 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestNonDepositedFiles.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestNonDepositedFiles.java @@ -20,22 +20,7 @@ */ package org.biojava.nbio.structure.io; -import static org.junit.Assert.*; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.List; -import java.util.zip.GZIPInputStream; - -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.EntityInfo; -import org.biojava.nbio.structure.EntityType; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.mmcif.MMcifParser; import org.biojava.nbio.structure.io.mmcif.SimpleMMcifConsumer; @@ -43,6 +28,12 @@ import org.biojava.nbio.structure.xtal.CrystalCell; import org.junit.Test; +import java.io.*; +import java.util.List; +import java.util.zip.GZIPInputStream; + +import static org.junit.Assert.*; + /** * Tests for non-deposited PDB/mmCIF files, i.e. any kind of "raw" file * lacking significant parts of the headers. @@ -56,7 +47,7 @@ public class TestNonDepositedFiles { @Test - public void test1B8GnoSeqresPdb() throws IOException, StructureException { + public void test1B8GnoSeqresPdb() throws IOException { InputStream inStream = new GZIPInputStream(this.getClass().getResourceAsStream("/org/biojava/nbio/structure/io/1b8g_raw.pdb.gz")); assertNotNull(inStream); @@ -72,7 +63,7 @@ public void test1B8GnoSeqresPdb() throws IOException, StructureException { assertTrue(s.isCrystallographic()); assertFalse(s.isNmr()); - assertTrue(s.nrModels()==1); + assertEquals(1, s.nrModels()); assertNull(s.getPDBHeader().getExperimentalTechniques()); assertNotNull(s.getCrystallographicInfo().getCrystalCell()); @@ -126,7 +117,7 @@ public void test1B8G() throws IOException, StructureException { } @Test - public void test3C5F() throws IOException, StructureException { + public void test3C5F() throws IOException { InputStream inStream = new GZIPInputStream(this.getClass().getResourceAsStream("/org/biojava/nbio/structure/io/3c5f_raw.pdb.gz")); assertNotNull(inStream); @@ -146,7 +137,7 @@ public void test3C5F() throws IOException, StructureException { } @Test - public void test4B19() throws IOException, StructureException { + public void test4B19() throws IOException { InputStream inStream = new GZIPInputStream(this.getClass().getResourceAsStream("/org/biojava/nbio/structure/io/4b19_raw.pdb.gz")); assertNotNull(inStream); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestParseMmCIFFeatures.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestParseMmCIFFeatures.java index f0c10f5e17..197d9dc854 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestParseMmCIFFeatures.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestParseMmCIFFeatures.java @@ -20,20 +20,14 @@ */ package org.biojava.nbio.structure.io; -import static org.junit.Assert.*; +import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.align.util.AtomCache; +import org.junit.Test; import java.io.IOException; import java.util.List; -import org.biojava.nbio.structure.Bond; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.structure.Site; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; -import org.biojava.nbio.structure.align.util.AtomCache; -import org.junit.Test; +import static org.junit.Assert.*; /** * Created by larsonmattr on 10/31/2015. diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestParseMmCIFLigands.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestParseMmCIFLigands.java index c97aed8d88..239ad05b9a 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestParseMmCIFLigands.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestParseMmCIFLigands.java @@ -20,22 +20,17 @@ */ package org.biojava.nbio.structure.io; -import static org.junit.Assert.*; - -import java.io.IOException; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.mmcif.ChemCompGroupFactory; import org.biojava.nbio.structure.io.mmcif.DownloadChemCompProvider; import org.biojava.nbio.structure.io.mmcif.chem.PolymerType; import org.junit.Test; +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + /** * Created by edlunde-dnastar * @since 10/30/2015. diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestParseOnAsymId.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestParseOnAsymId.java index 448aed4750..8d92429b18 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestParseOnAsymId.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestParseOnAsymId.java @@ -20,10 +20,6 @@ */ package org.biojava.nbio.structure.io; -import java.io.IOException; -import java.util.List; -import static org.junit.Assert.*; - import org.biojava.nbio.structure.Chain; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; @@ -31,6 +27,12 @@ import org.biojava.nbio.structure.align.util.AtomCache; import org.junit.Test; +import java.io.IOException; +import java.util.List; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + public class TestParseOnAsymId { diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestQuaternaryStructureProviders.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestQuaternaryStructureProviders.java index c2d4ec71ad..664237b100 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestQuaternaryStructureProviders.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestQuaternaryStructureProviders.java @@ -31,8 +31,7 @@ import java.util.List; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; public class TestQuaternaryStructureProviders { @@ -66,7 +65,7 @@ public void test5LDH() throws IOException, StructureException{ gotException = true; } - assertTrue("Bioassembly 3 for PDB id 5LDH should fail with a StructureException!", !gotException); + assertFalse("Bioassembly 3 for PDB id 5LDH should fail with a StructureException!", gotException); // bioassembly 2 does exist in mmcif file, let's check that gotException = false; @@ -78,7 +77,7 @@ public void test5LDH() throws IOException, StructureException{ } catch (StructureException e) { gotException = true; } - assertTrue("Bioassembly 2 for PDB id 5LDH should not fail with a StructureException!", !gotException); + assertFalse("Bioassembly 2 for PDB id 5LDH should not fail with a StructureException!", gotException); } @@ -139,10 +138,11 @@ private void comparePdbVsMmcif(String pdbId, int bioMolecule, int mmSize) throws assertEquals(mmSize, mMap.get(bioMolecule).getMacromolecularSize()); - for ( int k : pMap.keySet()) { - assertTrue(mMap.containsKey(k)); + for (Map.Entry entry : pMap.entrySet()) { + int k = entry.getKey(); + assertTrue(mMap.containsKey(k)); - BioAssemblyInfo pBioAssemb = pMap.get(k); + BioAssemblyInfo pBioAssemb = entry.getValue(); BioAssemblyInfo mBioAssemb = mMap.get(k); assertEquals("Macromolecular sizes don't coincide!",pBioAssemb.getMacromolecularSize(), mBioAssemb.getMacromolecularSize()); @@ -195,7 +195,7 @@ private void comparePdbVsMmcif(String pdbId, int bioMolecule, int mmSize) throws } - private Structure getPdbBioAssembly(String pdbId, int bioMolecule, boolean multiModel) throws IOException, StructureException { + private Structure getPdbBioAssembly(String pdbId, int bioMolecule, boolean multiModel) throws StructureException { // get bio assembly from PDB file AtomCache cache = new AtomCache(); cache.setUseMmCif(false); @@ -204,7 +204,7 @@ private Structure getPdbBioAssembly(String pdbId, int bioMolecule, boolean multi return pdbS; } - private Structure getMmcifBioAssembly(String pdbId, int bioMolecule, boolean multiModel) throws IOException, StructureException { + private Structure getMmcifBioAssembly(String pdbId, int bioMolecule, boolean multiModel) throws StructureException { // get bio assembly from mmcif file AtomCache cache = new AtomCache(); cache.setUseMmCif(true); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestShortLines.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestShortLines.java index 6f16f478fe..bd1dbbba80 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestShortLines.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestShortLines.java @@ -20,19 +20,19 @@ */ package org.biojava.nbio.structure.io; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Chain; import org.biojava.nbio.structure.Group; import org.biojava.nbio.structure.Structure; import org.junit.Test; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + /** * This class will test parsing short CONECT lines. * @since Nov 30, 2016 diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestSiftsParsing.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestSiftsParsing.java index f34cca7454..6fffc52d61 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestSiftsParsing.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestSiftsParsing.java @@ -84,8 +84,10 @@ public void test4jn3() throws Exception { //System.out.println(e.getEntityId() + " " +e.getType()); - Assert.assertTrue(e.getSegments().size() > 0); - for (SiftsSegment seg : e.getSegments()) { + List segments = e.getSegments(); + + Assert.assertTrue(segments.size() > 0); + for (SiftsSegment seg : segments) { Assert.assertTrue(seg.getResidues().size() > 0); //System.out.println(seg.getResidues().size()); //System.out.println(" Segment: " + seg.getSegId() + " " + seg.getStart() + " " + seg.getEnd()) ; diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestURLBasedFileParsing.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestURLBasedFileParsing.java index 0d07e77c6e..b61434e63a 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestURLBasedFileParsing.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestURLBasedFileParsing.java @@ -21,13 +21,14 @@ package org.biojava.nbio.structure.io; -import java.io.IOException; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; import org.junit.Test; -import static org.junit.Assert.*; + +import java.io.IOException; + +import static org.junit.Assert.assertNotNull; /** * Created by ap3 on 31/07/2015. diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestWriteLargeCoordinatePDB.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestWriteLargeCoordinatePDB.java index 78137f73e2..8bf3ec9bf9 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestWriteLargeCoordinatePDB.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/TestWriteLargeCoordinatePDB.java @@ -20,17 +20,13 @@ */ package org.biojava.nbio.structure.io; -import static org.junit.Assert.fail; +import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.align.util.AtomCache; +import org.junit.Test; import java.io.IOException; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; -import org.biojava.nbio.structure.align.util.AtomCache; -import org.junit.Test; +import static org.junit.Assert.fail; public class TestWriteLargeCoordinatePDB { diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmcif/TestChemCompProvider.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmcif/TestChemCompProvider.java index 4791f21fe7..288d850589 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmcif/TestChemCompProvider.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmcif/TestChemCompProvider.java @@ -20,14 +20,6 @@ */ package org.biojava.nbio.structure.io.mmcif; -import static org.junit.Assert.assertEquals; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Path; -import java.nio.file.Paths; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; @@ -39,11 +31,19 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static org.junit.Assert.assertEquals; + public class TestChemCompProvider { private static final Logger s_logger = LoggerFactory.getLogger(TestChemCompProvider.class); // Short test with bad ligand name (QNA is bogus) - final String DNAexample = + static final String DNAexample = "ATOM 1 H MET A 1 11.756 -15.759 11.647 1.00 7.95\n" + "ATOM 2 N MET A 1 12.461 -16.373 11.329 1.00 7.95\n" + @@ -186,7 +186,7 @@ public void testNormalStructure() throws StructureException, IOException { } @Test - public void testGetOneLetterCode() throws Exception { + public void testGetOneLetterCode() { String oneLetter; diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmcif/TestEntityNameAndType.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmcif/TestEntityNameAndType.java index 780aad41c4..9900b69174 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmcif/TestEntityNameAndType.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmcif/TestEntityNameAndType.java @@ -20,18 +20,14 @@ */ package org.biojava.nbio.structure.io.mmcif; -import static org.junit.Assert.assertArrayEquals; - -import java.io.IOException; - -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.EntityInfo; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.FileParsingParameters; import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertArrayEquals; /** * Test to ensure the entity name and type * @author Anthony Bradley diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmcif/TestMmcifV5Changes.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmcif/TestMmcifV5Changes.java index 3a1aeef824..2dfc1077f4 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmcif/TestMmcifV5Changes.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmcif/TestMmcifV5Changes.java @@ -20,7 +20,11 @@ */ package org.biojava.nbio.structure.io.mmcif; -import static org.junit.Assert.*; +import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.StructureException; +import org.biojava.nbio.structure.StructureIO; +import org.junit.Before; +import org.junit.Test; import java.io.IOException; import java.text.ParseException; @@ -28,11 +32,7 @@ import java.util.Date; import java.util.Locale; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertEquals; /** * Test date related changes in mmCIF 5.0 format. diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmcif/TestParseInternalChainId.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmcif/TestParseInternalChainId.java index 0132d29de4..98ead0071b 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmcif/TestParseInternalChainId.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmcif/TestParseInternalChainId.java @@ -21,14 +21,16 @@ package org.biojava.nbio.structure.io.mmcif; -import java.io.IOException; - import org.biojava.nbio.structure.Chain; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.util.AtomCache; import org.junit.Test; -import static org.junit.Assert.*; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; /** * Created by andreas on 5/3/16. diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmcif/TestParseMmcifHeader.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmcif/TestParseMmcifHeader.java index 52c76422ec..7e4e902de3 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmcif/TestParseMmcifHeader.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmcif/TestParseMmcifHeader.java @@ -20,7 +20,12 @@ */ package org.biojava.nbio.structure.io.mmcif; -import static org.junit.Assert.assertEquals; +import org.biojava.nbio.structure.PDBHeader; +import org.biojava.nbio.structure.Structure; +import org.biojava.nbio.structure.StructureException; +import org.biojava.nbio.structure.StructureIO; +import org.biojava.nbio.structure.align.util.AtomCache; +import org.junit.Test; import java.io.IOException; import java.text.ParseException; @@ -28,12 +33,7 @@ import java.util.Date; import java.util.Locale; -import org.biojava.nbio.structure.PDBHeader; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; -import org.biojava.nbio.structure.align.util.AtomCache; -import org.junit.Test; +import static org.junit.Assert.assertEquals; /** * Test parsing header information from MmCif files. diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestBondFinding.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestBondFinding.java index ab5268578c..6c75e70742 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestBondFinding.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestBondFinding.java @@ -20,24 +20,18 @@ */ package org.biojava.nbio.structure.io.mmtf; -import org.junit.Test; -import static org.junit.Assert.*; - -import java.io.IOException; -import java.util.List; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Bond; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.FileParsingParameters; import org.biojava.nbio.structure.io.LocalPDBDirectory.FetchBehavior; import org.biojava.nbio.structure.io.mmcif.ChemCompGroupFactory; import org.biojava.nbio.structure.io.mmcif.DownloadChemCompProvider; +import org.junit.Test; + +import java.io.IOException; +import java.util.List; + +import static org.junit.Assert.assertEquals; /** * Test bond finding in BioJava diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestMmtfPerformance.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestMmtfPerformance.java index e0b576d79a..4b27f09b3f 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestMmtfPerformance.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestMmtfPerformance.java @@ -20,14 +20,16 @@ */ package org.biojava.nbio.structure.io.mmtf; +import org.biojava.nbio.core.util.Download; import org.biojava.nbio.structure.io.PDBFileParser; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.*; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; import java.net.URL; -import java.util.zip.GZIPInputStream; import static org.junit.Assert.assertTrue; @@ -72,33 +74,34 @@ public void test3HBX() throws Exception{ pdbId = pdbId.toUpperCase(); - URL url = new URL("https://files.rcsb.org/download/"+pdbId+".pdb.gz"); + URL pdbURL = new URL("https://files.rcsb.org/download/"+pdbId+".pdb.gz"); - String pdbFile = convertStreamToString(new GZIPInputStream(url.openStream())); +// String pdbFile = convertStreamToString(new GZIPInputStream(pdbURL.openStream())); long totalTimePDB = 0; long totalTimeMMTF = 0; - byte[] pdbBytes = pdbFile.getBytes(); +// byte[] pdbBytes = pdbFile.getBytes(); PDBFileParser parser = new PDBFileParser(); URL mmtfURL = new URL("https://mmtf.rcsb.org/v1.0/full/" + pdbId + ".mmtf.gz"); - byte[] mmtfdata = getByteArrayFromInputStream(new GZIPInputStream((mmtfURL.openStream()))); + // first make sure chemcomp cache is warmed up (chemcomp files are parsed). Like that we count the parsing time without the influence of chemcomp parsing - MmtfActions.readFromInputStream(new ByteArrayInputStream(mmtfdata)); - parser.parsePDBFile(new ByteArrayInputStream(pdbBytes)); + MmtfActions.readFromInputStream(Download.stream(mmtfURL)); + + parser.parsePDBFile(Download.stream(pdbURL)); for ( int i =0 ; i< NUMBER_OF_REPEATS ; i++) { long mmtfStart = System.nanoTime(); - MmtfActions.readFromInputStream(new ByteArrayInputStream(mmtfdata)); + MmtfActions.readFromInputStream(Download.stream(mmtfURL)); long mmtfEnd = System.nanoTime(); long pdbStart = System.nanoTime(); - parser.parsePDBFile(new ByteArrayInputStream(pdbBytes)); + parser.parsePDBFile(Download.stream(pdbURL)); long pdbEnd = System.nanoTime(); totalTimePDB += (pdbEnd - pdbStart); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestMmtfRoundTrip.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestMmtfRoundTrip.java index d9bdb05bc0..b80b4dc62e 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestMmtfRoundTrip.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestMmtfRoundTrip.java @@ -20,25 +20,7 @@ */ package org.biojava.nbio.structure.io.mmtf; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Map; - -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.Bond; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.io.FileParsingParameters; import org.biojava.nbio.structure.io.mmcif.ChemCompGroupFactory; @@ -49,6 +31,14 @@ import org.rcsb.mmtf.decoder.StructureDataToAdapter; import org.rcsb.mmtf.encoder.AdapterToStructureData; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.*; + /** * Tests to see if roundtripping of MMTF can be done. * @@ -139,7 +129,7 @@ private boolean checkIfAtomsSame(Structure structOne, Structure structTwo) { if(!groupOne.getType().equals(groupTwo.getType())){ System.out.println("Error - diff group type: "+structOne.getPDBCode()); System.out.println(groupOne.getPDBName() + " and type: "+groupOne.getType()); - System.out.println(groupTwo.getPDBName() + " and type: "+groupTwo.getType());; + System.out.println(groupTwo.getPDBName() + " and type: "+groupTwo.getType()); } // Check the single letter amino acid is correct if(groupOne.getChemComp().getOne_letter_code().length()==1 && groupTwo.getChemComp().getOne_letter_code().length()==1){ @@ -164,14 +154,10 @@ private boolean checkIfAtomsSame(Structure structOne, Structure structTwo) { List atomsTwo = new ArrayList<>(groupTwo.getAtoms()); for(Group altLocOne: groupOne.getAltLocs()){ - for(Atom atomAltLocOne: altLocOne.getAtoms()){ - atomsOne.add(atomAltLocOne); - } + atomsOne.addAll(altLocOne.getAtoms()); } for(Group altLocTwo: groupTwo.getAltLocs()){ - for(Atom atomAltLocTwo: altLocTwo.getAtoms()){ - atomsTwo.add(atomAltLocTwo); - } + atomsTwo.addAll(altLocTwo.getAtoms()); } if(atomsOne.size()!=atomsTwo.size()){ System.out.println("Error - diff number atoms: "+structOne.getPDBCode()); @@ -246,28 +232,22 @@ private void checkDiffChains(Structure structOne, Structure structTwo, int i) { * @param atomsTwo the second list */ private void sortAtoms(List atomsOne, List atomsTwo) { - atomsOne.sort(new Comparator() { - @Override - public int compare(Atom o1, Atom o2) { - // - if (o1.getPDBserial() { + // + if (o1.getPDBserial()() { - @Override - public int compare(Atom o1, Atom o2) { - // - if (o1.getPDBserial() { + // + if (o1.getPDBserial() chainsOne, List chainsTwo) { - Collections.sort(chainsOne, new Comparator() { - @Override - public int compare(Chain o1, Chain o2) { - return o1.getId().compareTo(o2.getId()); - } - }); - Collections.sort(chainsTwo, new Comparator() { - @Override - public int compare(Chain o1, Chain o2) { - return o1.getId().compareTo(o2.getId()); - } - }); + chainsOne.sort(Comparator.comparing(Chain::getId)); + chainsTwo.sort(Comparator.comparing(Chain::getId)); } @@ -324,7 +294,7 @@ private void checkSeqresGroups(Chain chainOne, Chain chainTwo) { * @param structOne the first input structure * @param structTwo the second input structure */ - private void checkBioAssemblies1(Structure structOne, Structure structTwo) throws IOException { + private void checkBioAssemblies1(Structure structOne, Structure structTwo) { Map expecteds = structOne.getPDBHeader().getBioAssemblies(); Map actuals = structTwo.getPDBHeader().getBioAssemblies(); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestMmtfStructureReader.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestMmtfStructureReader.java index ac2d81e8d5..7f45ffb884 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestMmtfStructureReader.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestMmtfStructureReader.java @@ -1,11 +1,5 @@ package org.biojava.nbio.structure.io.mmtf; -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.nio.file.Paths; -import java.util.List; - import org.biojava.nbio.structure.Group; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; @@ -16,7 +10,13 @@ import org.biojava.nbio.structure.io.mmcif.DownloadChemCompProvider; import org.junit.Ignore; import org.junit.Test; -import static org.junit.Assert.*; + +import java.io.IOException; +import java.nio.file.Paths; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; /** * Test the Biojava MMTF reader. diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestMmtfStructureWriter.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestMmtfStructureWriter.java index 6f98b250d3..84a9f1a9f7 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestMmtfStructureWriter.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestMmtfStructureWriter.java @@ -20,28 +20,18 @@ */ package org.biojava.nbio.structure.io.mmtf; +import org.biojava.nbio.structure.*; +import org.biojava.nbio.structure.io.mmcif.model.ChemComp; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; -import org.biojava.nbio.structure.AminoAcidImpl; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.AtomImpl; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.ChainImpl; -import org.biojava.nbio.structure.Element; -import org.biojava.nbio.structure.EntityInfo; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.PDBHeader; -import org.biojava.nbio.structure.ResidueNumber; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureImpl; -import org.biojava.nbio.structure.io.mmcif.model.ChemComp; -import org.junit.Rule; -import org.junit.Test; -import static org.junit.Assert.*; -import org.junit.rules.TemporaryFolder; +import static org.junit.Assert.assertEquals; /** * Test the Biojava MMTF writer. @@ -87,7 +77,7 @@ public void testWrite() throws IOException { structure.setPDBHeader(pdbHeader); // Create one chain - structure.setEntityInfos(new ArrayList()); + structure.setEntityInfos(new ArrayList<>()); Chain chain = new ChainImpl(); chain.setId("A"); chain.setName("A"); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestMmtfUtils.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestMmtfUtils.java index ed86712893..e3f3692da0 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestMmtfUtils.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/mmtf/TestMmtfUtils.java @@ -20,43 +20,19 @@ */ package org.biojava.nbio.structure.io.mmtf; -import org.junit.Test; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.vecmath.Matrix4d; - -import org.biojava.nbio.structure.AminoAcidImpl; -import org.biojava.nbio.structure.Atom; -import org.biojava.nbio.structure.AtomImpl; -import org.biojava.nbio.structure.BondImpl; -import org.biojava.nbio.structure.Chain; -import org.biojava.nbio.structure.ChainImpl; -import org.biojava.nbio.structure.ExperimentalTechnique; -import org.biojava.nbio.structure.Group; -import org.biojava.nbio.structure.HetatomImpl; -import org.biojava.nbio.structure.NucleotideImpl; -import org.biojava.nbio.structure.PDBCrystallographicInfo; -import org.biojava.nbio.structure.Structure; -import org.biojava.nbio.structure.StructureException; -import org.biojava.nbio.structure.StructureIO; -import org.biojava.nbio.structure.StructureImpl; -import org.biojava.nbio.structure.io.mmtf.MmtfUtils; +import org.biojava.nbio.structure.*; import org.biojava.nbio.structure.quaternary.BioAssemblyInfo; import org.biojava.nbio.structure.quaternary.BiologicalAssemblyTransformation; import org.biojava.nbio.structure.xtal.BravaisLattice; import org.biojava.nbio.structure.xtal.CrystalCell; import org.biojava.nbio.structure.xtal.SpaceGroup; +import org.junit.Test; + +import javax.vecmath.Matrix4d; +import java.io.IOException; +import java.util.*; + +import static org.junit.Assert.*; /** * Test the MMTF utils class. @@ -139,14 +115,12 @@ public void microHeterogenity() throws IOException, StructureException { */ private List getAllAtoms(Structure bioJavaStruct) { // Get all the atoms - List theseAtoms = new ArrayList(); + List theseAtoms = new ArrayList<>(); for (int i=0; i chains = bioJavaStruct.getModel(i); for (Chain c : chains) { for (Group g : c.getAtomGroups()) { - for(Atom a: MmtfUtils.getAtomsForGroup(g)){ - theseAtoms.add(a); - } + theseAtoms.addAll(MmtfUtils.getAtomsForGroup(g)); } } } @@ -187,7 +161,7 @@ public void testGetUnitCellAsArray() { */ @Test public void testGetExperimentalMethods() { - Set experimentalTechniques = new HashSet<>(); + Set experimentalTechniques = EnumSet.noneOf(ExperimentalTechnique.class); experimentalTechniques.add(ExperimentalTechnique.XRAY_DIFFRACTION); experimentalTechniques.add(ExperimentalTechnique.ELECTRON_MICROSCOPY); String[] techniques = MmtfUtils.techniquesToStringArray(experimentalTechniques); @@ -381,8 +355,8 @@ public void testGetSecStructTypeFromDsspIndex(){ assertEquals(MmtfUtils.getSecStructTypeFromDsspIndex(5).name,"Bridge"); assertEquals(MmtfUtils.getSecStructTypeFromDsspIndex(6).name,"Turn"); assertEquals(MmtfUtils.getSecStructTypeFromDsspIndex(7).name,"Coil"); - assertEquals(MmtfUtils.getSecStructTypeFromDsspIndex(-1), null); - assertEquals(MmtfUtils.getSecStructTypeFromDsspIndex(10), null); + assertNull(MmtfUtils.getSecStructTypeFromDsspIndex(-1)); + assertNull(MmtfUtils.getSecStructTypeFromDsspIndex(10)); } diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/sifts/SiftsChainToUniprotMappingTest.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/sifts/SiftsChainToUniprotMappingTest.java index 66f3485248..563e2c0614 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/io/sifts/SiftsChainToUniprotMappingTest.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/io/sifts/SiftsChainToUniprotMappingTest.java @@ -25,11 +25,7 @@ import org.junit.Test; -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; +import java.io.*; import static org.junit.Assert.assertEquals; diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/rcsb/RCSBDescriptionFactoryTest.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/rcsb/RCSBDescriptionFactoryTest.java index bef0e232c1..0dca56f12c 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/rcsb/RCSBDescriptionFactoryTest.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/rcsb/RCSBDescriptionFactoryTest.java @@ -32,6 +32,7 @@ import java.util.List; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; /** * Tests {@link RCSBDescriptionFactory}. @@ -134,17 +135,17 @@ public void testAlmostEmpty() { assertEquals("notype", polymer.getType()); assertEquals(1, polymer.getIndex().intValue()); assertEquals("really close to empty", polymer.getDescription()); - assertEquals(null, polymer.getEnzClass()); + assertNull(polymer.getEnzClass()); assertEquals(10, polymer.getLength().intValue()); assertEquals(0, polymer.getWeight(), 0); polymer = polymers.get(1); - assertEquals(null, polymer.getType()); // make sure these are null and not "" - assertEquals(null, polymer.getIndex()); - assertEquals(null, polymer.getDescription()); - assertEquals(null, polymer.getEnzClass()); - assertEquals(null, polymer.getLength()); - assertEquals(null, polymer.getWeight()); + assertNull(polymer.getType()); // make sure these are null and not "" + assertNull(polymer.getIndex()); + assertNull(polymer.getDescription()); + assertNull(polymer.getEnzClass()); + assertNull(polymer.getLength()); + assertNull(polymer.getWeight()); } @@ -163,7 +164,7 @@ public void test2() { assertEquals("protein", polymer.getType()); assertEquals(1, polymer.getIndex().intValue()); assertEquals("HEMOGLOBIN (DEOXY) (ALPHA CHAIN)", polymer.getDescription()); - assertEquals(null, polymer.getEnzClass()); + assertNull(polymer.getEnzClass()); assertEquals(141, polymer.getLength().intValue()); assertEquals(15150.5, polymer.getWeight(), 0); @@ -197,7 +198,7 @@ public void test2() { assertEquals("protein", polymer.getType()); assertEquals(2, polymer.getIndex().intValue()); assertEquals("HEMOGLOBIN (DEOXY) (BETA CHAIN)", polymer.getDescription()); - assertEquals(null, polymer.getEnzClass()); + assertNull(polymer.getEnzClass()); assertEquals(146, polymer.getLength().intValue()); assertEquals(15890.4, polymer.getWeight(), 0); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/redmine/Test1DARSeqAlign.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/redmine/Test1DARSeqAlign.java index 4f351d3c74..defe255958 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/redmine/Test1DARSeqAlign.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/redmine/Test1DARSeqAlign.java @@ -28,10 +28,11 @@ import org.biojava.nbio.structure.io.mmcif.ChemCompProvider; import org.biojava.nbio.structure.io.mmcif.DownloadChemCompProvider; import org.junit.Test; -import static org.junit.Assert.*; import java.io.IOException; +import static org.junit.Assert.*; + /** test for https://redmine.open-bio.org/issues/3282 * * @author Andreas Prlic @@ -72,13 +73,13 @@ public void test1DAR() throws StructureException, IOException { //System.out.println(g3); //System.out.println(FileConvert.toPDB(g3.getAtom(0))); - assertTrue(! a.getSeqResGroups().contains(g)); + assertFalse(a.getSeqResGroups().contains(g)); assertTrue( g instanceof NucleotideImpl); - assertTrue(g.getType().equals(GroupType.NUCLEOTIDE)); + assertEquals(g.getType(), GroupType.NUCLEOTIDE); - assertTrue( g3.getPDBName().equals("LYS")); + assertEquals("LYS", g3.getPDBName()); assertTrue( a.getSeqResGroups().contains(g3)); assertTrue( g3 instanceof AminoAcid); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/secstruc/TestDSSPParser.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/secstruc/TestDSSPParser.java index d79db697d7..bc46d01ba8 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/secstruc/TestDSSPParser.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/secstruc/TestDSSPParser.java @@ -20,17 +20,18 @@ */ package org.biojava.nbio.structure.secstruc; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.zip.GZIPInputStream; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.util.AtomCache; import org.junit.Test; -import static org.junit.Assert.*; +import java.io.IOException; +import java.util.Collections; +import java.util.List; +import java.util.zip.GZIPInputStream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; /** * Test all the options for writting and fetching DSSP file formats. Also @@ -45,7 +46,7 @@ public class TestDSSPParser { public void testDSSPParser() throws IOException, StructureException { // List of names to test the DSSP prediction - List names = Arrays.asList("5pti"); + List names = Collections.singletonList("5pti"); for (String name : names) { diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/secstruc/TestSecStrucCalc.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/secstruc/TestSecStrucCalc.java index a2d2708448..7448b888bf 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/secstruc/TestSecStrucCalc.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/secstruc/TestSecStrucCalc.java @@ -20,17 +20,17 @@ */ package org.biojava.nbio.structure.secstruc; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.zip.GZIPInputStream; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.util.AtomCache; import org.junit.Test; -import static org.junit.Assert.*; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.zip.GZIPInputStream; + +import static org.junit.Assert.assertEquals; /** * Test the correctness of the DSSP implementation in BioJava diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/symmetry/internal/TestCeSymm.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/symmetry/internal/TestCeSymm.java index f9d829b5c3..349ffaa95e 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/symmetry/internal/TestCeSymm.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/symmetry/internal/TestCeSymm.java @@ -20,17 +20,17 @@ */ package org.biojava.nbio.structure.symmetry.internal; -import static org.junit.Assert.*; - -import java.io.IOException; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureTools; -import org.biojava.nbio.structure.symmetry.internal.CeSymm; import org.junit.Test; +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + /** * Run two easy cases of internal symmetry and test that results are significant * and order is correct. diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/symmetry/internal/TestSequenceFunctionOrderDetector.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/symmetry/internal/TestSequenceFunctionOrderDetector.java index 6df1faf477..f5cb5589d4 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/symmetry/internal/TestSequenceFunctionOrderDetector.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/symmetry/internal/TestSequenceFunctionOrderDetector.java @@ -20,22 +20,19 @@ */ package org.biojava.nbio.structure.symmetry.internal; -import static org.junit.Assert.*; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - import org.biojava.nbio.structure.Atom; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.model.AFPChain; import org.biojava.nbio.structure.align.util.AtomCache; -import org.biojava.nbio.structure.symmetry.internal.CeSymm; -import org.biojava.nbio.structure.symmetry.internal.RefinerFailedException; -import org.biojava.nbio.structure.symmetry.internal.SequenceFunctionOrderDetector; import org.biojava.nbio.structure.symmetry.internal.CESymmParameters.RefineMethod; import org.junit.Test; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + /** * Originally part of {@link CeSymmTest}. * @author Spencer Bliven @@ -45,7 +42,7 @@ public class TestSequenceFunctionOrderDetector { @Test public void testGetSymmetryOrder() throws IOException, StructureException, RefinerFailedException { // List of alignments to try, along with proper symmetry - Map orderMap = new HashMap(); + Map orderMap = new HashMap<>(); orderMap.put("1itb.A",3); // b-trefoil, C3 orderMap.put("1tim.A",2); // tim-barrel, C8 //orderMap.put("d1p9ha_",-1); // not rotational symmetry @@ -54,8 +51,9 @@ public void testGetSymmetryOrder() throws IOException, StructureException, Refin AtomCache cache = new AtomCache(); - for(String name : orderMap.keySet()) { - CESymmParameters params = new CESymmParameters(); + for(Map.Entry entry : orderMap.entrySet()) { + String name = entry.getKey(); + CESymmParameters params = new CESymmParameters(); params.setRefineMethod(RefineMethod.NOT_REFINED); Atom[] ca1 = cache.getAtoms(name); @@ -64,7 +62,7 @@ public void testGetSymmetryOrder() throws IOException, StructureException, Refin int order = new SequenceFunctionOrderDetector().calculateOrder(afpChain, ca1); - assertEquals("Wrong order for "+name,orderMap.get(name).intValue(), order); + assertEquals("Wrong order for "+name, entry.getValue().intValue(), order); } } diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/symmetry/internal/TestSingleRefiner.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/symmetry/internal/TestSingleRefiner.java index 89c0140ed1..d31a94f2ad 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/symmetry/internal/TestSingleRefiner.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/symmetry/internal/TestSingleRefiner.java @@ -20,17 +20,16 @@ */ package org.biojava.nbio.structure.symmetry.internal; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.align.util.AlignmentTools; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + /** * @author blivens * @@ -41,7 +40,7 @@ public class TestSingleRefiner { List> expecteds; @Before - public void setUp() throws Exception { + public void setUp() { Map align; Map expect; @@ -49,9 +48,9 @@ public void setUp() throws Exception { // Note that all the expecteds rely on scoreAbsError being used internally // by refineSymmetry - alignments = new ArrayList>(); - orders = new ArrayList(); - expecteds = new ArrayList>(); + alignments = new ArrayList<>(); + orders = new ArrayList<>(); + expecteds = new ArrayList<>(); /* 0. Chained alignment * 1\ @@ -60,7 +59,7 @@ public void setUp() throws Exception { * 4>8>129>13<-- */ - align = new HashMap(); + align = new HashMap<>(); align.put( 1, 6); align.put( 2, 6); align.put( 3, 7); @@ -82,7 +81,7 @@ public void setUp() throws Exception { * 4>8>12<-- * 5>9>13<-- */ - expect = new HashMap(); + expect = new HashMap<>(); expect.put( 2, 6); expect.put( 3, 7); expect.put( 4, 8); @@ -102,7 +101,7 @@ public void setUp() throws Exception { * 1->5->9<-- * 4->8<\ */ - align = new HashMap(); + align = new HashMap<>(); align.put( 1, 5); align.put( 5, 9); align.put( 9, 1); @@ -113,7 +112,7 @@ public void setUp() throws Exception { /* 1. Expect * 1->5->9<-- */ - expect = new HashMap(); + expect = new HashMap<>(); expect.put( 1, 5); expect.put( 5, 9); expect.put( 9, 1); @@ -123,7 +122,7 @@ public void setUp() throws Exception { * 1->5->9<-- * 2->6->10<\ */ - align = new HashMap(); + align = new HashMap<>(); align.put( 1, 5); align.put( 5, 9); align.put( 9, 1); @@ -136,7 +135,7 @@ public void setUp() throws Exception { * 1->5->9<-- * 2->6->10<-- */ - expect = new HashMap(); + expect = new HashMap<>(); expect.put( 1, 5); expect.put( 5, 9); expect.put( 9, 1); @@ -149,7 +148,7 @@ public void setUp() throws Exception { * 1->5->9<-- * 2/^6->10<-- */ - align = new HashMap(); + align = new HashMap<>(); align.put( 1, 5); align.put( 5, 9); align.put( 9, 1); @@ -162,7 +161,7 @@ public void setUp() throws Exception { * 1->5->9<-- * 2->6->10<-- */ - expect = new HashMap(); + expect = new HashMap<>(); expect.put( 1, 5); expect.put( 5, 9); expect.put( 9, 1); @@ -174,7 +173,7 @@ public void setUp() throws Exception { /* 4. Wrong order * 3->7<-- */ - align = new HashMap(); + align = new HashMap<>(); align.put( 3, 7); align.put( 7, 3); alignments.add(align); @@ -182,14 +181,14 @@ public void setUp() throws Exception { /* * 4. Expect empty */ - expect = new HashMap(); + expect = new HashMap<>(); expecteds.add(expect); /* 5. Prioritize score over chain length * 1->5->96->10 */ - align = new HashMap(); + align = new HashMap<>(); align.put( 1, 5); align.put( 5, 9); align.put( 9, 3); @@ -200,7 +199,7 @@ public void setUp() throws Exception { /* 5. Expect * 3->5->9<-- */ - expect = new HashMap(); + expect = new HashMap<>(); expect.put( 3, 5); expect.put( 5, 9); expect.put( 9, 3); @@ -211,7 +210,7 @@ public void setUp() throws Exception { /* * 6. Small cycles can be repaired. 3>5>7>5 */ - align = new HashMap(); + align = new HashMap<>(); align.put(3, 5); align.put(5, 7); align.put(7, 5); @@ -220,7 +219,7 @@ public void setUp() throws Exception { /* * 6. Expect 3>5>7<-- */ - expect = new HashMap(); + expect = new HashMap<>(); expect.put(3, 5); expect.put(5, 7); expect.put(7, 3); @@ -230,7 +229,7 @@ public void setUp() throws Exception { * 7. It might be a good idea to allow cycles if their length divides the order. However, this isn't allowed * yet. 3>5< */ - align = new HashMap(); + align = new HashMap<>(); align.put(3, 5); align.put(5, 3); alignments.add(align); @@ -238,12 +237,12 @@ public void setUp() throws Exception { /* * 7. Expect empty, but could argue for 3>5<-- */ - expect = new HashMap(); + expect = new HashMap<>(); expecteds.add(expect); } @Test - public void testExpected() throws StructureException { + public void testExpected() { for(int i=0;i align = alignments.get(i); @@ -263,15 +262,16 @@ public void testExpected() throws StructureException { * @param align */ private void testAutomorphism(Map align) { - for(Integer pre:align.keySet()) { - Integer post = align.get(pre); + for(Map.Entry entry : align.entrySet()) { + Integer pre = entry.getKey(); + Integer post = entry.getValue(); Assert.assertNotNull("Not automorphic: f(" + pre + ") not defined", post); Assert.assertTrue("not automorphic: f(" + pre + ") = " + post + " but f(" + post + ") undefined", align.containsKey(post)); } } @Test - public void testAutomorphism() throws StructureException { + public void testAutomorphism() { for(int i=0;i align = alignments.get(i); @@ -285,15 +285,16 @@ private void testSymmetric(Map align, int k) { Assert.assertEquals(align.size(), alignK.size()); // Assumption; Should be tested by AlignmentToolsTest int refinementNum = 0; - for(Integer res : alignK.keySet()) { - Integer resK = alignK.get(res); + for(Map.Entry entry : alignK.entrySet()) { + Integer res = entry.getKey(); + Integer resK = entry.getValue(); Assert.assertEquals(String.format("Asymmetric alignment in #%d. f^%d(%d)=%d", refinementNum++, k, res, resK), res, resK); } } @Test - public void testSymmetric() throws StructureException { + public void testSymmetric() { for(int i=0;i align = alignments.get(i); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/symmetry/internal/TestSymmetryAxes.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/symmetry/internal/TestSymmetryAxes.java index 89455bab86..b3a2c57ff9 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/symmetry/internal/TestSymmetryAxes.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/symmetry/internal/TestSymmetryAxes.java @@ -20,19 +20,19 @@ */ package org.biojava.nbio.structure.symmetry.internal; -import static org.junit.Assert.*; - -import java.util.Arrays; -import java.util.List; +import org.biojava.nbio.structure.symmetry.internal.CESymmParameters.SymmetryType; +import org.biojava.nbio.structure.symmetry.internal.SymmetryAxes.Axis; +import org.junit.Test; import javax.vecmath.AxisAngle4d; import javax.vecmath.Matrix4d; import javax.vecmath.Point3d; import javax.vecmath.Vector3d; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; -import org.biojava.nbio.structure.symmetry.internal.CESymmParameters.SymmetryType; -import org.biojava.nbio.structure.symmetry.internal.SymmetryAxes.Axis; -import org.junit.Test; +import static org.junit.Assert.*; public class TestSymmetryAxes { @@ -103,13 +103,13 @@ public void testClosedCase() { Arrays.asList(1,3,5,7) ); assertEquals(relation,axes.getRepeatsCyclicForm(0)); - relation = Arrays.asList( - Arrays.asList(0,1) - ); + relation = Collections.singletonList( + Arrays.asList(0, 1) + ); assertEquals(relation,axes.getRepeatsCyclicForm(1)); - relation = Arrays.asList( - Arrays.asList(2,3) - ); + relation = Collections.singletonList( + Arrays.asList(2, 3) + ); assertEquals(relation,axes.getRepeatsCyclicForm(1,2)); try { axes.getRepeatsCyclicForm(2); @@ -245,13 +245,13 @@ public void testOpenCase() { Arrays.asList(1,3,5,7) ); assertEquals(relation,axes.getRepeatsCyclicForm(0)); - relation = Arrays.asList( - Arrays.asList(0,1) - ); + relation = Collections.singletonList( + Arrays.asList(0, 1) + ); assertEquals(relation,axes.getRepeatsCyclicForm(1)); - relation = Arrays.asList( - Arrays.asList(2,3) - ); + relation = Collections.singletonList( + Arrays.asList(2, 3) + ); assertEquals(relation,axes.getRepeatsCyclicForm(1,2)); try { axes.getRepeatsCyclicForm(2); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/symmetry/utils/TestSymmetryTools.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/symmetry/utils/TestSymmetryTools.java index aa0c26ddcc..a230c84e3b 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/symmetry/utils/TestSymmetryTools.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/symmetry/utils/TestSymmetryTools.java @@ -20,12 +20,13 @@ */ package org.biojava.nbio.structure.symmetry.utils; -import static org.junit.Assert.*; +import org.junit.Test; import java.util.Arrays; +import java.util.Collections; import java.util.List; -import org.junit.Test; +import static org.junit.Assert.assertEquals; /** * Test the methods in {@link SymmetryTools} class. @@ -62,7 +63,7 @@ public void testValidFolds() { assertEquals("Wrong folds for " + stoich, expected, folds); stoich = Arrays.asList(6, 5); - expected = Arrays.asList(1); + expected = Collections.singletonList(1); folds = SymmetryTools.getValidFolds(stoich); assertEquals("Wrong folds for " + stoich, expected, folds); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/test/util/GlobalsHelper.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/test/util/GlobalsHelper.java index 9d7e5ae57d..c769fa771b 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/test/util/GlobalsHelper.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/test/util/GlobalsHelper.java @@ -20,11 +20,6 @@ */ package org.biojava.nbio.structure.test.util; -import java.util.Deque; -import java.util.LinkedList; -import java.util.List; -import java.util.NoSuchElementException; - import org.biojava.nbio.structure.StructureIO; import org.biojava.nbio.structure.align.util.AtomCache; import org.biojava.nbio.structure.align.util.UserConfiguration; @@ -34,6 +29,10 @@ import org.biojava.nbio.structure.scop.ScopDatabase; import org.biojava.nbio.structure.scop.ScopFactory; +import java.util.Deque; +import java.util.LinkedList; +import java.util.NoSuchElementException; + /** * Helper class to manage all the global state changes in BioJava. * For instance, this should be used in tests before modifying PDB_PATH. @@ -65,7 +64,7 @@ public PathInfo() { } // Saves defaults as stack - private static Deque stack = new LinkedList<>(); + private static final Deque stack = new LinkedList<>(); static { // Save default state pushState(); @@ -79,7 +78,7 @@ private GlobalsHelper() {} /** * Save current global state to the stack */ - public static void pushState() { + public synchronized static void pushState() { PathInfo paths = new PathInfo(); stack.addFirst(paths); } diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/validation/TestValidationReportParsing.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/validation/TestValidationReportParsing.java index da1b9a9b02..010d256ec5 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/validation/TestValidationReportParsing.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/validation/TestValidationReportParsing.java @@ -83,7 +83,7 @@ public void test() { private void testPDB(String pdbId) { try { - JAXBContext ctx = JAXBContext.newInstance(new Class[] {WwPDBValidationInformation.class}); + JAXBContext ctx = JAXBContext.newInstance(WwPDBValidationInformation.class); Unmarshaller um = ctx.createUnmarshaller(); diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/xtal/TestCrystalCell.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/xtal/TestCrystalCell.java index 37e51a7b6a..d0194d8140 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/xtal/TestCrystalCell.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/xtal/TestCrystalCell.java @@ -20,21 +20,22 @@ */ package org.biojava.nbio.structure.xtal; -import static org.junit.Assert.*; +import org.junit.Before; +import org.junit.Test; import javax.vecmath.AxisAngle4d; import javax.vecmath.Matrix4d; import javax.vecmath.Point3d; import javax.vecmath.Point3i; -import static java.lang.Math.sqrt; -import org.junit.Before; -import org.junit.Test; +import static java.lang.Math.sqrt; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class TestCrystalCell { @Before - public void setUp() throws Exception { + public void setUp() { } @Test diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/xtal/TestCrystalInfo.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/xtal/TestCrystalInfo.java index 501d6eb2af..f891b15a59 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/xtal/TestCrystalInfo.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/xtal/TestCrystalInfo.java @@ -153,8 +153,8 @@ private void testCrystallographicInfo(Structure s1, Structure s2) { CrystalCell cell1 = xtalInfo.getCrystalCell(); CrystalCell cell2 = xtalInfo2.getCrystalCell(); - if (s1.isNmr()) assertTrue(cell1==null); - if (s2.isNmr()) assertTrue(cell2==null); + if (s1.isNmr()) assertNull(cell1); + if (s2.isNmr()) assertNull(cell2); if (cell1==null && cell2==null) return; diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/xtal/TestInterfaceClustering.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/xtal/TestInterfaceClustering.java index af80c99ae1..1dfee68774 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/xtal/TestInterfaceClustering.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/xtal/TestInterfaceClustering.java @@ -20,16 +20,6 @@ */ package org.biojava.nbio.structure.xtal; -import static org.junit.Assert.*; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.zip.GZIPInputStream; - import org.biojava.nbio.structure.Structure; import org.biojava.nbio.structure.StructureException; import org.biojava.nbio.structure.StructureIO; @@ -43,6 +33,15 @@ import org.junit.Test; import javax.vecmath.Matrix4d; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.zip.GZIPInputStream; + +import static org.junit.Assert.*; public class TestInterfaceClustering { @@ -176,7 +175,7 @@ public void test1AUY() throws IOException, StructureException { @Test - public void test3C5FWithSeqresPdb() throws IOException, StructureException { + public void test3C5FWithSeqresPdb() throws IOException { InputStream inStream = new GZIPInputStream(this.getClass().getResourceAsStream("/org/biojava/nbio/structure/io/3c5f_raw.pdb.gz")); assertNotNull(inStream); @@ -224,7 +223,7 @@ public void test3C5FWithSeqresPdb() throws IOException, StructureException { // see https://github.com/eppic-team/eppic/issues/39 // See also TestCompoundResIndexMapping //@Test - public void test3DDONoSeqresPdb() throws IOException, StructureException { + public void test3DDONoSeqresPdb() throws IOException { // 3ddo contains 6 chains in 1 entity, with residue numbering completely different in each of the chains diff --git a/biojava-structure/src/test/java/org/biojava/nbio/structure/xtal/TestSpaceGroup.java b/biojava-structure/src/test/java/org/biojava/nbio/structure/xtal/TestSpaceGroup.java index 79413317bf..9480bd78b0 100644 --- a/biojava-structure/src/test/java/org/biojava/nbio/structure/xtal/TestSpaceGroup.java +++ b/biojava-structure/src/test/java/org/biojava/nbio/structure/xtal/TestSpaceGroup.java @@ -40,10 +40,10 @@ public class TestSpaceGroup { private static final double DELTA = 0.000001; // use true for printing operators of all space groups (including non-enantiomorphics), or false to print only enantiomorphics - private static boolean PRINT_OPERATORS_FROM_ALL_SGS = false; + private static final boolean PRINT_OPERATORS_FROM_ALL_SGS = false; // print information per operator - private static boolean VERBOSE = false; + private static final boolean VERBOSE = false; @Test public void testTransfConversion() { @@ -101,9 +101,9 @@ public void testTransfConversion() { Assert.assertFalse(diffz>1 && diffz<0); // they are integer, i.e. 0 or 1 - Assert.assertTrue(diffx == (int)diffx); - Assert.assertTrue(diffy == (int)diffy); - Assert.assertTrue(diffz == (int)diffz); + Assert.assertEquals(diffx, (int) diffx, 0.0); + Assert.assertEquals(diffy, (int) diffy, 0.0); + Assert.assertEquals(diffz, (int) diffz, 0.0); } } @@ -172,11 +172,11 @@ public void testTransfConversion() { if (i==0) { Assert.assertTrue(ct.isIdentity()); Assert.assertFalse(ct.isPureCrystalTranslation()); - Assert.assertTrue(ct.getTransformType()==TransformType.AU); + Assert.assertSame(ct.getTransformType(), TransformType.AU); } Assert.assertFalse(ct.isPureCrystalTranslation()); - Assert.assertFalse(ct.getTransformType()==TransformType.XTALTRANSL); + Assert.assertNotSame(ct.getTransformType(), TransformType.XTALTRANSL); // rotation axes and type @@ -206,7 +206,10 @@ public void testTransfConversion() { } else { // i.e. determinant -1 switch (foldType) { case -1: - Assert.assertEquals(0,axisAngle.angle,DELTA); + case -6: + case -4: + case -3: + Assert.assertEquals(0,axisAngle.angle,DELTA); // no glide planes Assert.assertTrue(ct.getTranslScrewComponent().epsilonEquals(new Vector3d(0,0,0), DELTA)); break; @@ -214,23 +217,11 @@ public void testTransfConversion() { Assert.assertEquals(0,axisAngle.angle,DELTA); // glide planes can happen break; - case -3: - Assert.assertEquals(0,axisAngle.angle,DELTA); - // no glide planes - Assert.assertTrue(ct.getTranslScrewComponent().epsilonEquals(new Vector3d(0,0,0), DELTA)); - break; - case -4: - Assert.assertEquals(0,axisAngle.angle,DELTA); - // no glide planes - Assert.assertTrue(ct.getTranslScrewComponent().epsilonEquals(new Vector3d(0,0,0), DELTA)); - break; - case -6: - Assert.assertEquals(0,axisAngle.angle,DELTA); - // no glide planes - Assert.assertTrue(ct.getTranslScrewComponent().epsilonEquals(new Vector3d(0,0,0), DELTA)); - break; + // no glide planes + // no glide planes + // no glide planes - } + } } @@ -288,14 +279,14 @@ public void testTransfConversion() { } Assert.assertTrue(ct.isFractionalTranslation()); - Assert.assertTrue(ct.getTransformType()==TransformType.CELLTRANSL); + Assert.assertSame(ct.getTransformType(), TransformType.CELLTRANSL); } if (ct.isRotation() && !ct.isFractionalTranslation()) { Assert.assertTrue(ct.getTransformType()==TransformType.TWOFOLD || ct.getTransformType()==TransformType.THREEFOLD || ct.getTransformType()==TransformType.FOURFOLD || ct.getTransformType()==TransformType.SIXFOLD); - Assert.assertTrue(!ct.getTransformType().isScrew()); + Assert.assertFalse(ct.getTransformType().isScrew()); } if (spaceGroup.isEnantiomorphic() || PRINT_OPERATORS_FROM_ALL_SGS) { @@ -332,7 +323,7 @@ private static boolean eq(double d1, double d2) { } // to debug the testing code (run as java program so that we can use normal debugger) - public static void main(String[] args) throws Exception { + public static void main(String[] args) { TestSpaceGroup test = new TestSpaceGroup(); test.testTransfConversion(); } diff --git a/biojava-survival/pom.xml b/biojava-survival/pom.xml index 479b57276b..598c868930 100644 --- a/biojava-survival/pom.xml +++ b/biojava-survival/pom.xml @@ -60,15 +60,7 @@ - - org.apache.maven.plugins - maven-jar-plugin - - - demo/** - - - + org.apache.maven.plugins diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxCC.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxCC.java index 728e6e925c..fce2e76c0a 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxCC.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxCC.java @@ -27,6 +27,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; +import java.util.Map; /** * @@ -42,9 +43,9 @@ public class CoxCC { static public void process(CoxInfo ci) throws Exception { ArrayList survivalInfoList = ci.survivalInfoList; //r - ArrayList variables = new ArrayList(ci.getCoefficientsList().keySet()); + ArrayList variables = new ArrayList<>(ci.getCoefficientsList().keySet()); - ArrayList strataClass = new ArrayList(survivalInfoList.size()); + ArrayList strataClass = new ArrayList<>(survivalInfoList.size()); double[] wt = new double[survivalInfoList.size()]; for (int i = 0; i < survivalInfoList.size(); i++) { SurvivalInfo si = survivalInfoList.get(i); @@ -67,7 +68,7 @@ static public void process(CoxInfo ci) throws Exception { // } // } - double[][] rvar = null; + double[][] rvar; if (ci.getNaiveVariance() != null) { rvar = ci.getNaiveVariance(); @@ -75,7 +76,7 @@ static public void process(CoxInfo ci) throws Exception { rvar = ci.getVariance(); } //nj - LinkedHashMap nj = new LinkedHashMap(); + LinkedHashMap nj = new LinkedHashMap<>(); Collections.sort(strataClass); for (Integer value : strataClass) { Double count = nj.get(value); @@ -86,7 +87,7 @@ static public void process(CoxInfo ci) throws Exception { nj.put(value, count); } //Nj - LinkedHashMap Nj = new LinkedHashMap(); + LinkedHashMap Nj = new LinkedHashMap<>(); //N = N + Nj[key]; double N = 0; for (int i = 0; i < survivalInfoList.size(); i++) { @@ -106,9 +107,10 @@ static public void process(CoxInfo ci) throws Exception { N = N + value; } - LinkedHashMap k1j = new LinkedHashMap(); - for (Integer key : nj.keySet()) { - double _nj = (nj.get(key)); //trying to copy what R is doing on precision + LinkedHashMap k1j = new LinkedHashMap<>(); + for (Map.Entry entry : nj.entrySet()) { + Integer key = entry.getKey(); + double _nj = (entry.getValue()); //trying to copy what R is doing on precision double _Nj = (Nj.get(key)); // System.out.println("nj=" + _nj + " Nj=" + _Nj); k1j.put(key, _Nj * ((_Nj / _nj) - 1)); @@ -116,10 +118,11 @@ static public void process(CoxInfo ci) throws Exception { double[][] V = new double[variables.size()][variables.size()]; - for (Integer i : k1j.keySet()) { - // System.out.println("Strata=" + i + " " + k1j.get(i) + " " + Nj.get(i) + " " + nj.get(i)); + for (Map.Entry entry : k1j.entrySet()) { + Integer i = entry.getKey(); + // System.out.println("Strata=" + i + " " + k1j.get(i) + " " + Nj.get(i) + " " + nj.get(i)); if (nj.get(i) > 1) { - LinkedHashMap variableStatsMap = new LinkedHashMap(); + LinkedHashMap variableStatsMap = new LinkedHashMap<>(); for (int p = 0; p < survivalInfoList.size(); p++) { SurvivalInfo si = survivalInfoList.get(p); @@ -161,7 +164,7 @@ static public void process(CoxInfo ci) throws Exception { // System.out.println("sstrat=" + i); // StdArrayIO.print(var_covar); - V = Matrix.add(V, Matrix.scale(var_covar, k1j.get(i)) ); + V = Matrix.add(V, Matrix.scale(var_covar, entry.getValue()) ); // for (int m = 0; m < V.length; m++) { // for (int n = 0; n < V.length; n++) { diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxCoefficient.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxCoefficient.java index a8023284b5..6befe1e2f5 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxCoefficient.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxCoefficient.java @@ -222,7 +222,7 @@ public void setStandardDeviation(double standardDeviation) { * @return */ public static String fmt(Double d, int precision, int pad) { - String value = ""; + String value; DecimalFormat dfe = new DecimalFormat("0.00E0"); String dpad = "0."; double p = 1.0; diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxHelper.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxHelper.java index 920fd3cc33..dfc149c54e 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxHelper.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxHelper.java @@ -71,7 +71,7 @@ public static CoxInfo process(String datafile, String timeColumn, String statusC public static CoxInfo process(WorkSheet worksheet, String timeColumn, String statusColumn, String weightColumn, String strataColumn, String clusterColumn, ArrayList variables, boolean useStrata, boolean useWeights) { try { - ArrayList survivalInfoList = new ArrayList(); + ArrayList survivalInfoList = new ArrayList<>(); int i = 1; for (String row : worksheet.getRows()) { @@ -152,7 +152,7 @@ public static void main(String[] args) { try { if (true) { String datafile = "/Users/Scooter/scripps/ngs/DataSets/E2197/misc/ecoglabtransfer/500790/2013.05.10.12.28.58.313/clindasl0228.txt"; - ArrayList variables = new ArrayList(); + ArrayList variables = new ArrayList<>(); variables.add("nndpos"); variables.add("meno"); // variables.add("er1"); diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxInfo.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxInfo.java index d60d8a316e..80b5929c5a 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxInfo.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxInfo.java @@ -27,6 +27,7 @@ import java.text.DecimalFormat; import java.util.ArrayList; import java.util.LinkedHashMap; +import java.util.Map; //import org.biojava.nbio.survival.cox.comparators.SurvivalInfoComparator; @@ -59,9 +60,9 @@ public class CoxInfo { int numSamples = 0; int numEvents = 0; private LinkedHashMap metaDataFilter = null; - private LinkedHashMap coefficientsList = new LinkedHashMap(); - LinkedHashMap baselineSurvivorFunction = new LinkedHashMap(); - ArrayList survivalInfoList = new ArrayList(); + private final LinkedHashMap coefficientsList = new LinkedHashMap<>(); + final LinkedHashMap baselineSurvivorFunction = new LinkedHashMap<>(); + ArrayList survivalInfoList = new ArrayList<>(); /** * */ @@ -82,18 +83,15 @@ public ArrayList getSurvivalInfoList() { /** * * @param var - * @throws Exception */ - public void setVariance(double[][] var) throws Exception { + public void setVariance(double[][] var) { // if (Math.abs(var[0][1] - var[1][0]) > .0000000000001) { //in the CoxCC correction looks like a precision error keeps these from being equal 10-19 // throw new Exception("Expecting diagonal to be equal"); // } imat = new double[var.length][var[0].length]; for (int i = 0; i < var.length; i++) { - for (int j = 0; j < var[0].length; j++) { - imat[i][j] = var[i][j]; - } + System.arraycopy(var[i], 0, imat[i], 0, var[0].length); } calcSummaryValues(); } @@ -105,9 +103,7 @@ public void setVariance(double[][] var) throws Exception { public double[][] getVariance() { double[][] var = new double[imat.length][imat[0].length]; for (int i = 0; i < var.length; i++) { - for (int j = 0; j < var[0].length; j++) { - var[i][j] = imat[i][j]; - } + System.arraycopy(imat[i], 0, var[i], 0, var[0].length); } return var; @@ -116,9 +112,8 @@ public double[][] getVariance() { /** * * @param var - * @throws Exception */ - public void setNaiveVariance(double[][] var) throws Exception { + public void setNaiveVariance(double[][] var) { // if (var[0][1] != var[1][0]) { // throw new Exception("Expecting diagonal to be equal"); // } @@ -126,9 +121,7 @@ public void setNaiveVariance(double[][] var) throws Exception { naive_imat = new double[var.length][var[0].length]; for (int i = 0; i < var.length; i++) { - for (int j = 0; j < var[0].length; j++) { - naive_imat[i][j] = var[i][j]; - } + System.arraycopy(var[i], 0, naive_imat[i], 0, var[0].length); } calcSummaryValues(); @@ -141,9 +134,7 @@ public void setNaiveVariance(double[][] var) throws Exception { public double[][] getNaiveVariance() { double[][] var = new double[imat.length][imat[0].length]; for (int i = 0; i < var.length; i++) { - for (int j = 0; j < var[0].length; j++) { - var[i][j] = naive_imat[i][j]; - } + System.arraycopy(naive_imat[i], 0, var[i], 0, var[0].length); } return var; @@ -184,7 +175,7 @@ public double[] getWeighted() { * @return */ public double[][] getVariableResiduals() { - ArrayList variables = new ArrayList(coefficientsList.keySet()); + ArrayList variables = new ArrayList<>(coefficientsList.keySet()); double[][] rr = new double[survivalInfoList.size()][variables.size()]; int p = 0; for (SurvivalInfo si : this.survivalInfoList) { @@ -204,7 +195,7 @@ public double[][] getVariableResiduals() { * @param rr */ public void setVariableResiduals(double[][] rr) { - ArrayList variables = new ArrayList(coefficientsList.keySet()); + ArrayList variables = new ArrayList<>(coefficientsList.keySet()); int p = 0; for (SurvivalInfo si : this.survivalInfoList) { @@ -265,7 +256,7 @@ public String getCoefficientText(boolean header, String beginLine, String beginC for (CoxCoefficient coe : coefficientsList.values()) { String robust = ""; - String stderror = ""; + String stderror; if (naive_imat != null) { stderror = beginCell + fmt(coe.getRobustStdError(), 5, 9) + endCell; robust = beginCell + fmt(coe.getStdError(), 5, 9) + endCell; @@ -289,7 +280,7 @@ public static String fmt(Double d, int precision, int pad) { return ""; if(Double.isNaN(d)) return ""; - String value = ""; + String value; DecimalFormat dfe = new DecimalFormat("0.00E0"); String dpad = "0."; double p = 1.0; @@ -320,7 +311,7 @@ private void calcSummaryValues() { //beta - ArrayList variables = new ArrayList(coefficientsList.keySet()); + ArrayList variables = new ArrayList<>(coefficientsList.keySet()); for (int i = 0; i < variables.size(); i++) { String variable = variables.get(i); CoxCoefficient coe = coefficientsList.get(variable); @@ -507,9 +498,9 @@ public String toString(String beginLine, String del, String endLine) { if (baselineSurvivorFunction.size() > 0) { o = o + beginLine + "Baseline Survivor Function (at predictor means)" + endLine; - for (Double time : baselineSurvivorFunction.keySet()) { - Double mean = baselineSurvivorFunction.get(time); - o = o + beginLine + fmt(time, 4, 10) + fmt(mean, 4, 10) + endLine; + for (Map.Entry entry : baselineSurvivorFunction.entrySet()) { + Double mean = entry.getValue(); + o = o + beginLine + fmt(entry.getKey(), 4, 10) + fmt(mean, 4, 10) + endLine; } } diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxMart.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxMart.java index d49545efa6..0dd7064b69 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxMart.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxMart.java @@ -59,7 +59,7 @@ static public double[] process(CoxMethod method, ArrayList surviva int i, j; int lastone; int n = survivalInfoList.size(); - double deaths, denom = 0, e_denom = 0; + double deaths, denom = 0, e_denom; double hazard; double temp, wtsum; double downwt; diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxR.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxR.java index 6a3002f492..9a7437c3f2 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxR.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxR.java @@ -155,7 +155,7 @@ public CoxInfo process(ArrayList variables, ArrayList data SurvivalInfoHelper.categorizeData(data); //create variables if testing for interaction for (String variable : variables) { - if (variable.indexOf(":") != -1) { + if (variable.contains(":")) { String[] d = variable.split(":"); SurvivalInfoHelper.addInteraction(d[0], d[1], data); } @@ -203,7 +203,7 @@ public CoxInfo process(ArrayList variables, ArrayList data double sctest; - int flag = 0; + int flag; int iter = 0; //SEXP rlist, rlistnames; // int nprotect; /* number of protect calls I have issued */ @@ -273,7 +273,7 @@ public CoxInfo process(ArrayList variables, ArrayList data ArrayList clusterList = null; if(cluster){ - clusterList = new ArrayList(); + clusterList = new ArrayList<>(); } //copy data over to local arrays to minimuze changing code for (person = 0; person < nused; person++) { @@ -303,7 +303,7 @@ public CoxInfo process(ArrayList variables, ArrayList data } } - double tempsd = 0; + double tempsd; i = 0; for (i = 0; i < nvar; i++) { @@ -797,13 +797,14 @@ public void coxphfitSCleanup(CoxInfo ci, boolean useWeighted,boolean robust, Arr double[] infs = Matrix.abs(Matrix.multiply(ci.u, ci.getVariance())); // StdArrayIO.print(infs); - ArrayList coxCoefficients = new ArrayList(ci.getCoefficientsList().values()); + ArrayList coxCoefficients = new ArrayList<>(ci.getCoefficientsList().values()); for (int i = 0; i < infs.length; i++) { double inf = infs[i]; double coe = coxCoefficients.get(i).getCoeff(); if (inf > ci.eps && inf > (ci.toler * Math.abs(coe))) { ci.message = "Loglik converged before variable "; + break; } } @@ -958,7 +959,7 @@ public static void main(String[] args) { WorkSheet worksheet = WorkSheet.readCSV(is, '\t'); - ArrayList survivalInfoList = new ArrayList(); + ArrayList survivalInfoList = new ArrayList<>(); int i = 0; for (String row : worksheet.getRows()) { double time = worksheet.getCellDouble(row, "TIME"); @@ -977,7 +978,7 @@ public static void main(String[] args) { } CoxR cox = new CoxR(); - ArrayList variables = new ArrayList(); + ArrayList variables = new ArrayList<>(); // variables.add("AGE"); variables.add("AGE"); diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxScore.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxScore.java index dd8e73822e..cc51ec4d3f 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxScore.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxScore.java @@ -41,7 +41,7 @@ public static double[][] process(CoxMethod method, ArrayList survi double temp; int n = survivalInfoList.size(); - ArrayList variables = new ArrayList(coxInfo.getCoefficientsList().keySet()); + ArrayList variables = new ArrayList<>(coxInfo.getCoefficientsList().keySet()); int nvar = variables.size(); double deaths; diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxVariables.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxVariables.java index bfcaa5bd97..e40724bbe7 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxVariables.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/CoxVariables.java @@ -30,9 +30,9 @@ public class CoxVariables { // public GeneSetResults gsr; - private String cohortName = ""; - private String geneSet = ""; - private String genes = ""; + private final String cohortName; + private final String geneSet; + private final String genes; /** * @@ -55,7 +55,7 @@ public int getUniqueID() { String link = geneSet + "_" + cohortName; return link.hashCode(); } - private LinkedHashMap coxInfoHashMap = new LinkedHashMap(); + private final LinkedHashMap coxInfoHashMap = new LinkedHashMap<>(); /** * @@ -98,7 +98,7 @@ public String encodeFileURL(String file) { * @return */ public static String fmt(Double d, int precision, int pad) { - String value = ""; + String value; DecimalFormat dfe = new DecimalFormat("0.00E0"); String dpad = "0."; double p = 1.0; @@ -128,10 +128,9 @@ public String toString() { // co = co + genes + "\r\n"; coxOutput = coxOutput + cohortName + "," + genes.replace(',', ' ') + "\r\n"; coxOutput = coxOutput + ",Coe,StdErr,p-value,HR,HR Lo 95%,HR Hi 95%\r\n"; - for (String variables : coxInfoHashMap.keySet()) { - CoxInfo ci = coxInfoHashMap.get(variables); + for (CoxInfo ci : coxInfoHashMap.values()) { - coxOutput = coxOutput + "Overall Model Fit p-value=" + fmt(ci.getOverallModelFitPvalue(), 5, 0) + "\r\n"; + coxOutput = coxOutput + "Overall Model Fit p-value=" + fmt(ci.getOverallModelFitPvalue(), 5, 0) + "\r\n"; coxOutput = coxOutput + ci.getCoefficientText(false, "", ",", "", ""); coxOutput = coxOutput + "\r\n"; diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/ResidualsCoxph.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/ResidualsCoxph.java index 819ad24e0b..b155e45916 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/ResidualsCoxph.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/ResidualsCoxph.java @@ -49,7 +49,7 @@ public enum Type { /** * */ - score; + score } /** @@ -86,7 +86,7 @@ public static double[][] process(CoxInfo ci, Type type, boolean useWeighted, Arr // } - double[][] vv = null; + double[][] vv; if (ci.getNaiveVariance() != null) { vv = ci.getNaiveVariance(); } else { @@ -124,7 +124,7 @@ public static double[][] process(CoxInfo ci, Type type, boolean useWeighted, Arr * @return */ private static double[][] rowsum(double[][] rr, ArrayList sets) throws Exception { - LinkedHashMap sumMap = new LinkedHashMap(); + LinkedHashMap sumMap = new LinkedHashMap<>(); if (rr.length != sets.size()) { throw new Exception("Cluster value for each sample are not of equal length n=" + rr.length + " cluster length=" + sets.size()); } @@ -144,7 +144,7 @@ private static double[][] rowsum(double[][] rr, ArrayList sets) throws E sum = new double[sumMap.size()][rr[0].length]; } - ArrayList index = new ArrayList(sumMap.keySet()); + ArrayList index = new ArrayList<>(sumMap.keySet()); //sorting does seem to make a difference in test cases at the .0000000001 // ArrayList in = new ArrayList(); // for (String s : index) { diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/StrataInfo.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/StrataInfo.java index 11b01cf41c..3725ffdb91 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/StrataInfo.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/StrataInfo.java @@ -31,20 +31,20 @@ */ public class StrataInfo { - private ArrayList time = new ArrayList(); - private ArrayList status = new ArrayList(); - private ArrayList nevent = new ArrayList(); - private ArrayList ncens = new ArrayList(); - private ArrayList nrisk = new ArrayList(); - private ArrayList weight = new ArrayList(); - private ArrayList surv = new ArrayList(); - private ArrayList varhaz = new ArrayList(); - private ArrayList stderr = new ArrayList(); - private ArrayList stdlow = new ArrayList(); - private ArrayList upper = new ArrayList(); - private ArrayList lower = new ArrayList(); - private LinkedHashMap ndead = new LinkedHashMap(); - DecimalFormat df = new DecimalFormat("#.######"); + private final ArrayList time = new ArrayList<>(); + private final ArrayList status = new ArrayList<>(); + private final ArrayList nevent = new ArrayList<>(); + private final ArrayList ncens = new ArrayList<>(); + private final ArrayList nrisk = new ArrayList<>(); + private final ArrayList weight = new ArrayList<>(); + private final ArrayList surv = new ArrayList<>(); + private final ArrayList varhaz = new ArrayList<>(); + private final ArrayList stderr = new ArrayList<>(); + private ArrayList stdlow = new ArrayList<>(); + private final ArrayList upper = new ArrayList<>(); + private final ArrayList lower = new ArrayList<>(); + private final LinkedHashMap ndead = new LinkedHashMap<>(); + final DecimalFormat df = new DecimalFormat("#.######"); DecimalFormat dfe = new DecimalFormat("0.000000E0"); /** @@ -67,7 +67,7 @@ public Double getNearestTime(double timePercentage) { maxTime = t; } } - Double timeRange = maxTime - minTime; + double timeRange = maxTime - minTime; Double targetTime = minTime + timePercentage * timeRange; Double previousTime = null; for (Double t : time) { @@ -89,7 +89,7 @@ public Double getNearestTime(double timePercentage) { * @return */ public Double getNearestAtRisk(double t) { - Integer index = 0; + int index = 0; /* String timeValue = t + ""; String format = "#"; int numDecimals = 0; diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/SurvFitInfo.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/SurvFitInfo.java index 0d2567a78b..abe1be095e 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/SurvFitInfo.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/SurvFitInfo.java @@ -21,6 +21,7 @@ package org.biojava.nbio.survival.cox; import java.util.LinkedHashMap; +import java.util.Map; /** * Contains info for graphing km figures @@ -29,8 +30,8 @@ */ public class SurvFitInfo { - private LinkedHashMap strataInfoHashMap = new LinkedHashMap(); - private LinkedHashMap unweightedStrataInfoHashMap = new LinkedHashMap(); + private LinkedHashMap strataInfoHashMap = new LinkedHashMap<>(); + private LinkedHashMap unweightedStrataInfoHashMap = new LinkedHashMap<>(); private boolean weighted = false; @@ -70,9 +71,9 @@ public void setStrataInfoHashMap(LinkedHashMap strataInfoHas * @param label */ public void addStrataInfoHashMap(LinkedHashMap siHashMap, String label) { - for (String key : siHashMap.keySet()) { - StrataInfo si = siHashMap.get(key); - strataInfoHashMap.put(label + " " + key, si); + for (Map.Entry entry : siHashMap.entrySet()) { + StrataInfo si = entry.getValue(); + strataInfoHashMap.put(label + " " + entry.getKey(), si); } } diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/SurvivalInfo.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/SurvivalInfo.java index 6d4455193e..9c7e475107 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/SurvivalInfo.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/SurvivalInfo.java @@ -22,6 +22,7 @@ import java.util.ArrayList; import java.util.LinkedHashMap; +import java.util.Map; /** * Data class to represent a single sample where time and event/censor status is required @@ -45,12 +46,12 @@ public class SurvivalInfo implements Comparable { private double residual = 0.0; private String clusterValue = ""; - LinkedHashMap residualVariableMap = new LinkedHashMap(); + final LinkedHashMap residualVariableMap = new LinkedHashMap<>(); - LinkedHashMap data = new LinkedHashMap(); + LinkedHashMap data = new LinkedHashMap<>(); // LinkedHashMap discreteData = new LinkedHashMap(); - LinkedHashMap unknownDataType = new LinkedHashMap(); - LinkedHashMap originalMetaData = new LinkedHashMap(); + final LinkedHashMap unknownDataType = new LinkedHashMap<>(); + final LinkedHashMap originalMetaData = new LinkedHashMap<>(); /** * @@ -74,9 +75,9 @@ public SurvivalInfo(double t, int e, LinkedHashMap d) { status = e; data = d; - for(String key : d.keySet()){ - Double value = d.get(key); - originalMetaData.put(key, value + ""); + for(Map.Entry entry : d.entrySet()){ + Double value = entry.getValue(); + originalMetaData.put(entry.getKey(), String.valueOf(value)); } } @@ -158,7 +159,7 @@ public void updateContinousVariable(String variable, Double value){ * @param value */ public void addContinuousVariable(String variable, Double value) { - originalMetaData.put(variable, value + ""); + originalMetaData.put(variable, String.valueOf(value)); data.put(variable, value); } @@ -177,7 +178,7 @@ public Double getContinuousVariable(String variable) { * @return */ public ArrayList getGroupCategories(String groupName) { - ArrayList groupNameList = new ArrayList(); + ArrayList groupNameList = new ArrayList<>(); for (String key : data.keySet()) { if (key.startsWith(groupName + "_")) { groupNameList.add(key); @@ -199,7 +200,7 @@ public ArrayList getGroupCategories(String groupName) { * @return */ public ArrayList getDataVariables(){ - ArrayList v = new ArrayList(); + ArrayList v = new ArrayList<>(); v.addAll(data.keySet()); v.addAll(unknownDataType.keySet()); diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/SurvivalInfoHelper.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/SurvivalInfoHelper.java index 4e5c0981c0..dec820aa25 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/SurvivalInfoHelper.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/SurvivalInfoHelper.java @@ -24,6 +24,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; +import java.util.Map; /** * Used to work with SurvivalInfo @@ -86,23 +87,18 @@ private static boolean isCategorical(LinkedHashMap values) { public static void categorizeData(ArrayList DataT) { //Go through and get all variable value pairs - LinkedHashMap> valueMap = new LinkedHashMap>(); + LinkedHashMap> valueMap = new LinkedHashMap<>(); for (SurvivalInfo si : DataT) { - for (String key : si.unknownDataType.keySet()) { - LinkedHashMap map = valueMap.get(key); - if (map == null) { - map = new LinkedHashMap(); - valueMap.put(key, map); - } - map.put(si.unknownDataType.get(key), null); + for (Map.Entry entry : si.unknownDataType.entrySet()) { + LinkedHashMap map = valueMap.computeIfAbsent(entry.getKey(), k -> new LinkedHashMap<>()); + map.put(entry.getValue(), null); } } - for (String variable : valueMap.keySet()) { - LinkedHashMap values = valueMap.get(variable); - if (isCategorical(values)) { - ArrayList categories = new ArrayList(values.keySet()); + for (LinkedHashMap values : valueMap.values()) { + if (isCategorical(values)) { + ArrayList categories = new ArrayList<>(values.keySet()); Collections.sort(categories); //go ahead and put in alphabetical order if (categories.size() == 2) { for (String value : values.keySet()) { @@ -125,9 +121,10 @@ public static void categorizeData(ArrayList DataT) { } for (SurvivalInfo si : DataT) { - for (String key : si.unknownDataType.keySet()) { - LinkedHashMap map = valueMap.get(key); - String value = si.unknownDataType.get(key); + for (Map.Entry entry : si.unknownDataType.entrySet()) { + String key = entry.getKey(); + LinkedHashMap map = valueMap.get(key); + String value = entry.getValue(); Double d = map.get(value); si.data.put(key, d); } @@ -147,7 +144,7 @@ public static void categorizeData(ArrayList DataT) { * @return */ public static ArrayList addInteraction(String variable1, String variable2, ArrayList survivalInfoList) { - ArrayList variables = new ArrayList(); + ArrayList variables = new ArrayList<>(); variables.add(variable1); variables.add(variable2); variables.add(variable1 + ":" + variable2); @@ -170,9 +167,9 @@ public static ArrayList addInteraction(String variable1, String variable * @throws Exception */ public static void groupByRange(double[] range, String variable, String groupName, ArrayList survivalInfoList) throws Exception { - ArrayList labels = new ArrayList(); + ArrayList labels = new ArrayList<>(); for (int i = 0; i < range.length; i++) { - String label = ""; + String label; if (i == 0) { label = "[<=" + range[i] + "]"; } else if (i == range.length - 1) { @@ -184,7 +181,7 @@ public static void groupByRange(double[] range, String variable, String groupNam } labels.add(label); } - ArrayList validLabels = new ArrayList(); + ArrayList validLabels = new ArrayList<>(); //need to find the categories so we can set 1 and 0 and not include ranges with no values for (SurvivalInfo si : survivalInfoList) { diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/SurvivalInfoIndex.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/SurvivalInfoIndex.java index 51c443b0b7..3894425fc8 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/SurvivalInfoIndex.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/SurvivalInfoIndex.java @@ -26,9 +26,9 @@ */ public class SurvivalInfoIndex implements Comparable { - private double time; - private int event; - private int index; + private final double time; + private final int event; + private final int index; private double[] data; /** diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/WaldTest.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/WaldTest.java index fb011e3cf4..b6d9d811b1 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/WaldTest.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/WaldTest.java @@ -41,9 +41,7 @@ public class WaldTest { public static WaldTestInfo process(double[][] var, double[] b, double toler_chol) { double[][] b_ = new double[1][b.length]; - for(int i = 0; i < b.length; i++){ - b_[0][i] = b[i]; - } + System.arraycopy(b, 0, b_[0], 0, b.length); return process(var,b_,toler_chol); @@ -59,7 +57,7 @@ public static WaldTestInfo process(double[][] var, double[] b, double toler_chol public static WaldTestInfo process(double[][] var, double[][] b, double toler_chol) { - int i = 0; + int i; // if(ci.coefficientsList.size() == 1){ // double b_ = b[0][i]; @@ -71,7 +69,7 @@ public static WaldTestInfo process(double[][] var, double[][] b, double toler_ch // double toler_chol = ci.toler; int ntest = 1; int nvar = b[0].length; - double sum = 0; + double sum; double[][] solve = new double[ntest][nvar]; double[] bsum = new double[ntest]; @@ -85,9 +83,7 @@ public static WaldTestInfo process(double[][] var, double[][] b, double toler_ch } for (i = 0; i < ntest; i++) { - for (int j = 0; j < nvar; j++) { - solve[i][j] = b[i][j]; - } + System.arraycopy(b[i], 0, solve[i], 0, nvar); Chsolve2.process(var, nvar, solve, i); /*solve now has b* var-inverse */ sum = 0; diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/comparators/CoxComparatorInterface.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/comparators/CoxComparatorInterface.java index 703936e751..0bd486a0de 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/comparators/CoxComparatorInterface.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/comparators/CoxComparatorInterface.java @@ -30,8 +30,8 @@ * @author Scooter Willis */ public interface CoxComparatorInterface extends Comparator { - public String getDescription(); - public void setDescription(String description); - public String getModelVariables(); - public String getSortVariable(); + String getDescription(); + void setDescription(String description); + String getModelVariables(); + String getSortVariable(); } diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/comparators/CoxVariablesOverallModelFitComparator.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/comparators/CoxVariablesOverallModelFitComparator.java index 964b1e254f..0f6df69bb8 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/comparators/CoxVariablesOverallModelFitComparator.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/comparators/CoxVariablesOverallModelFitComparator.java @@ -33,7 +33,7 @@ public class CoxVariablesOverallModelFitComparator implements Comparator, Serializable { private static final long serialVersionUID = 1; - String variables = ""; + final String variables; /** * Variables are stored as a string representation of an ArrayList @@ -49,13 +49,7 @@ public int compare(CoxVariables coxVariables1, CoxVariables coxVariables2) { CoxInfo ci1 = coxVariables1.getCoxInfo(variables); CoxInfo ci2 = coxVariables2.getCoxInfo(variables); - if (ci1.getWaldTestInfo().getPvalue() < ci2.getWaldTestInfo().getPvalue()) { - return -1; - } else if (ci1.getWaldTestInfo().getPvalue() > ci2.getWaldTestInfo().getPvalue()) { - return 1; - } else { - return 0; - } + return Double.compare(ci1.getWaldTestInfo().getPvalue(), ci2.getWaldTestInfo().getPvalue()); //ascending order // return coxVariables1.compareTo(coxVariables2); } diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/comparators/CoxVariablesVariableComparator.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/comparators/CoxVariablesVariableComparator.java index 1c48b2dcf0..445fb7d21c 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/comparators/CoxVariablesVariableComparator.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/comparators/CoxVariablesVariableComparator.java @@ -29,8 +29,8 @@ */ public class CoxVariablesVariableComparator implements CoxComparatorInterface { - String variables = ""; - String variable = ""; + final String variables; + final String variable; /** * @@ -55,13 +55,7 @@ public int compare(CoxVariables coxVariables1, CoxVariables coxVariables2) { return 1; if(ci2 == null && ci1 != null) return -1; - if (ci1.getCoefficientsList().get(variable).getPvalue() < ci2.getCoefficientsList().get(variable).getPvalue()) { - return -1; - } else if (ci1.getCoefficientsList().get(variable).getPvalue() > ci2.getCoefficientsList().get(variable).getPvalue()) { - return 1; - } else { - return 0; - } + return Double.compare(ci1.getCoefficientsList().get(variable).getPvalue(), ci2.getCoefficientsList().get(variable).getPvalue()); //ascending order // return coxVariables1.compareTo(coxVariables2); } @@ -70,7 +64,7 @@ public int compare(CoxVariables coxVariables1, CoxVariables coxVariables2) { public String getDescription() { return description; } - String description = "Signatures ranked by p-value "; + String description; @Override public void setDescription(String description) { diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/comparators/MeanModelComparator.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/comparators/MeanModelComparator.java index 5f61766a25..b962d399d2 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/comparators/MeanModelComparator.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/comparators/MeanModelComparator.java @@ -33,7 +33,7 @@ public class MeanModelComparator implements Comparator, Serializable { private static final long serialVersionUID = 1; - String variable = ""; + final String variable; /** * @@ -64,13 +64,7 @@ public int compare(CoxVariables coxVariables1, CoxVariables coxVariables2) { double c2ratio = Math.min(c2LTpvalue, c2GTpvalue) / Math.max(c2LTpvalue, c2GTpvalue); - if (c1ratio > c2ratio) { - return 1; - } else if (c1ratio < c2ratio) { - return -1; - } else { - return 0; - } + return Double.compare(c1ratio, c2ratio); //ascending order // return coxVariables1.compareTo(coxVariables2); } diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/comparators/SurvivalInfoValueComparator.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/comparators/SurvivalInfoValueComparator.java index 81098c46cf..d0418db509 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/comparators/SurvivalInfoValueComparator.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/comparators/SurvivalInfoValueComparator.java @@ -32,7 +32,7 @@ public class SurvivalInfoValueComparator implements Comparator, Serializable { private static final long serialVersionUID = 1; - String variable = ""; + final String variable; /** * @@ -46,12 +46,7 @@ public SurvivalInfoValueComparator(String variable){ public int compare(SurvivalInfo t, SurvivalInfo t1) { double v = t.getContinuousVariable(variable); double v1 = t1.getContinuousVariable(variable); - if(v < v1) - return -1; - else if(v > v1) - return 1; - else - return 0; + return Double.compare(v, v1); } } diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/stats/AgScore.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/stats/AgScore.java index ba85c9084b..5cd339bc29 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/stats/AgScore.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/cox/stats/AgScore.java @@ -45,7 +45,7 @@ public static double[][] process(CoxMethod method, ArrayList survi //double temp; int n = survivalInfoList.size(); - ArrayList variables = new ArrayList(coxInfo.getCoefficientsList().keySet()); + ArrayList variables = new ArrayList<>(coxInfo.getCoefficientsList().keySet()); int nvar = variables.size(); @@ -66,11 +66,11 @@ public static double[][] process(CoxMethod method, ArrayList survi double[] mh2 = new double[nvar]; double[] mh3 = new double[nvar]; - double denom = 0; - double time = 0; - double e_denom = 0; - double meanwt = 0; - double deaths = 0; + double denom; + double time; + double e_denom; + double meanwt; + double deaths; double risk; double[][] covar = new double[nvar][n]; double[][] resid = new double[nvar][n]; @@ -78,7 +78,7 @@ public static double[][] process(CoxMethod method, ArrayList survi double downwt, temp1, temp2, d2; - int person = 0; + int person; // n = *nx; // nvar = *nvarx; diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/data/ChangeValue.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/data/ChangeValue.java index b5841d9f63..eb5d7b8a56 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/data/ChangeValue.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/data/ChangeValue.java @@ -32,5 +32,5 @@ public interface ChangeValue { * @param originalValue * @return */ - public String change(String originalValue); + String change(String originalValue); } diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/data/WorkSheet.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/data/WorkSheet.java index 57f0e983ce..24573c3b4f 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/data/WorkSheet.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/data/WorkSheet.java @@ -31,10 +31,10 @@ */ public class WorkSheet { - private LinkedHashMap columnLookup = new LinkedHashMap(); - private LinkedHashMap rowLookup = new LinkedHashMap(); + private final LinkedHashMap columnLookup = new LinkedHashMap<>(); + private final LinkedHashMap rowLookup = new LinkedHashMap<>(); private CompactCharSequence[][] data = new CompactCharSequence[1][1]; - HashMap dataGrid = new HashMap(); + final HashMap dataGrid = new HashMap<>(); private String indexColumnName = ""; /** @@ -233,14 +233,14 @@ public WorkSheet(CompactCharSequence[][] values) { data = values; } - private LinkedHashMap metaDataColumnsHashMap = new LinkedHashMap(); + private final LinkedHashMap metaDataColumnsHashMap = new LinkedHashMap<>(); /** * * @return */ public ArrayList getMetaDataColumns() { - ArrayList metaColumns = new ArrayList(); + ArrayList metaColumns = new ArrayList<>(); for (String key : metaDataColumnsHashMap.keySet()) { HeaderInfo hi = columnLookup.get(key); if (!hi.isHide()) { @@ -255,7 +255,7 @@ public ArrayList getMetaDataColumns() { * @return */ public ArrayList getMetaDataRows() { - ArrayList metaRows = new ArrayList(); + ArrayList metaRows = new ArrayList<>(); for (String key : metaDataRowsHashMap.keySet()) { HeaderInfo hi = rowLookup.get(key); if (!hi.isHide()) { @@ -270,7 +270,7 @@ public ArrayList getMetaDataRows() { * @return */ public ArrayList getDataColumns() { - ArrayList dataColumns = new ArrayList(); + ArrayList dataColumns = new ArrayList<>(); ArrayList columns = this.getColumns(); for (String column : columns) { if (!metaDataColumnsHashMap.containsKey(column)) { @@ -292,7 +292,7 @@ public void shuffleColumnsAndThenRows(ArrayList columns, ArrayList rowIndex = new ArrayList(); + ArrayList rowIndex = new ArrayList<>(); for (int i = 0; i < rows.size(); i++) { rowIndex.add(i); } @@ -311,7 +311,7 @@ public void shuffleColumnsAndThenRows(ArrayList columns, ArrayList columnIndex = new ArrayList(); + ArrayList columnIndex = new ArrayList<>(); for (int i = 0; i < columns.size(); i++) { columnIndex.add(i); } @@ -344,7 +344,7 @@ public void shuffleColumnValues(ArrayList columns) throws Exception { doubleValues.clear(); ArrayList rows = this.getDataRows(); for (String column : columns) { //shuffle all values in the column - ArrayList rowIndex = new ArrayList(); + ArrayList rowIndex = new ArrayList<>(); for (int i = 0; i < rows.size(); i++) { rowIndex.add(i); } @@ -375,7 +375,7 @@ public void shuffleRowValues(ArrayList rows) throws Exception { doubleValues.clear(); ArrayList columns = this.getColumns(); for (String row : rows) { - ArrayList columnIndex = new ArrayList(); + ArrayList columnIndex = new ArrayList<>(); for (int i = 0; i < columns.size(); i++) { columnIndex.add(i); } @@ -521,7 +521,7 @@ public boolean isMetaDataRow(String row) { return true; } } - private LinkedHashMap metaDataRowsHashMap = new LinkedHashMap(); + private final LinkedHashMap metaDataRowsHashMap = new LinkedHashMap<>(); /** * @@ -646,7 +646,7 @@ public void applyColumnFilter(String column, ChangeValue changeValue) throws Exc * @param defaultValue */ public void addColumn(String column, String defaultValue) { - ArrayList columns = new ArrayList(); + ArrayList columns = new ArrayList<>(); columns.add(column); addColumns(columns, defaultValue); } @@ -694,7 +694,7 @@ public void addColumns(ArrayList columns, String defaultValue) { * @param defaultValue */ public void addRow(String row, String defaultValue) { - ArrayList rows = new ArrayList(); + ArrayList rows = new ArrayList<>(); rows.add(row); addRows(rows, defaultValue); } @@ -808,7 +808,7 @@ public boolean isValidColumn(String col) { } } //When we do gene signatures we ask for the same data value often. This method took up 50% of the time. - HashMap doubleValues = new HashMap(); + final HashMap doubleValues = new HashMap<>(); boolean cacheDoubleValues = false; /** @@ -871,9 +871,9 @@ public String getCell(String row, String col) throws Exception { if (rowIndex == null) { //allow for case insentive search - for (String rowtable : rowLookup.keySet()) { - if (row.equalsIgnoreCase(rowtable)) { - rowIndex = rowLookup.get(rowtable); + for (Map.Entry entry : rowLookup.entrySet()) { + if (row.equalsIgnoreCase(entry.getKey())) { + rowIndex = entry.getValue(); break; } } @@ -883,9 +883,9 @@ public String getCell(String row, String col) throws Exception { } if (colIndex == null) { //allow for case insentive search - for (String coltable : columnLookup.keySet()) { - if (col.equalsIgnoreCase(coltable)) { - colIndex = columnLookup.get(coltable); + for (Map.Entry entry : columnLookup.entrySet()) { + if (col.equalsIgnoreCase(entry.getKey())) { + colIndex = entry.getValue(); break; } } @@ -909,7 +909,7 @@ public String getCell(String row, String col) throws Exception { * @param changeValue */ public void changeRowHeader(ChangeValue changeValue) { - ArrayList rows = new ArrayList(rowLookup.keySet()); + ArrayList rows = new ArrayList<>(rowLookup.keySet()); for (String row : rows) { String newRow = changeValue.change(row); HeaderInfo value = rowLookup.get(row); @@ -923,7 +923,7 @@ public void changeRowHeader(ChangeValue changeValue) { * @param changeValue */ public void changeColumnHeader(ChangeValue changeValue) { - ArrayList columns = new ArrayList(columnLookup.keySet()); + ArrayList columns = new ArrayList<>(columnLookup.keySet()); for (String col : columns) { String newCol = changeValue.change(col); HeaderInfo value = columnLookup.get(col); @@ -958,9 +958,9 @@ public void changeRowHeader(String row, String newRow) throws Exception { * @throws Exception */ public void changeColumnsHeaders(LinkedHashMap newColumnValues) throws Exception { - for (String oldColumn : newColumnValues.keySet()) { - String newColumn = newColumnValues.get(oldColumn); - changeColumnHeader(oldColumn, newColumn); + for (Map.Entry entry : newColumnValues.entrySet()) { + String newColumn = entry.getValue(); + changeColumnHeader(entry.getKey(), newColumn); } } @@ -1030,8 +1030,8 @@ public ArrayList getRandomDataColumns(int number) { * @return */ public ArrayList getRandomDataColumns(int number, ArrayList columns) { - ArrayList randomColumns = new ArrayList(); - HashMap picked = new HashMap(); + ArrayList randomColumns = new ArrayList<>(); + HashMap picked = new HashMap<>(); while (picked.size() < number) { double v = Math.random(); int index = (int) (v * columns.size()); @@ -1051,10 +1051,7 @@ public ArrayList getRandomDataColumns(int number, ArrayList colu * @return */ public ArrayList getAllColumns() { - ArrayList columns = new ArrayList(); - for (String col : columnLookup.keySet()) { - columns.add(col); - } + ArrayList columns = new ArrayList<>(columnLookup.keySet()); return columns; } @@ -1064,11 +1061,11 @@ public ArrayList getAllColumns() { * @return */ public ArrayList getColumns() { - ArrayList columns = new ArrayList(); - for (String col : columnLookup.keySet()) { - HeaderInfo hi = columnLookup.get(col); + ArrayList columns = new ArrayList<>(); + for (Map.Entry entry : columnLookup.entrySet()) { + HeaderInfo hi = entry.getValue(); if (!hi.isHide()) { - columns.add(col); + columns.add(entry.getKey()); } } return columns; @@ -1082,8 +1079,8 @@ public ArrayList getColumns() { * @throws Exception */ public ArrayList getDiscreteColumnValues(String column) throws Exception { - HashMap hashMapValues = new HashMap(); - ArrayList values = new ArrayList(); + HashMap hashMapValues = new HashMap<>(); + ArrayList values = new ArrayList<>(); ArrayList rows = getDataRows(); for (String row : rows) { String value = getCell(row, column); @@ -1103,8 +1100,8 @@ public ArrayList getDiscreteColumnValues(String column) throws Exception * @throws Exception */ public ArrayList getDiscreteRowValues(String row) throws Exception { - HashMap hashMapValues = new HashMap(); - ArrayList values = new ArrayList(); + HashMap hashMapValues = new HashMap<>(); + ArrayList values = new ArrayList<>(); for (String column : getColumns()) { String value = getCell(row, column); if (!hashMapValues.containsKey(value)) { @@ -1121,10 +1118,7 @@ public ArrayList getDiscreteRowValues(String row) throws Exception { * @return */ public ArrayList getAllRows() { - ArrayList rows = new ArrayList(); - for (String row : rowLookup.keySet()) { - rows.add(row); - } + ArrayList rows = new ArrayList<>(rowLookup.keySet()); return rows; } @@ -1135,11 +1129,11 @@ public ArrayList getAllRows() { * @return */ public ArrayList getRows() { - ArrayList rows = new ArrayList(); - for (String row : rowLookup.keySet()) { - HeaderInfo hi = rowLookup.get(row); + ArrayList rows = new ArrayList<>(); + for (Map.Entry entry : rowLookup.entrySet()) { + HeaderInfo hi = entry.getValue(); if (!hi.isHide()) { - rows.add(row); + rows.add(entry.getKey()); } } return rows; @@ -1151,12 +1145,13 @@ public ArrayList getRows() { * @return */ public ArrayList getDataRows() { - ArrayList rows = new ArrayList(); - for (String row : rowLookup.keySet()) { + ArrayList rows = new ArrayList<>(); + for (Map.Entry entry : rowLookup.entrySet()) { + String row = entry.getKey(); if (this.isMetaDataRow(row)) { continue; } - HeaderInfo hi = rowLookup.get(row); + HeaderInfo hi = entry.getValue(); if (!hi.isHide()) { rows.add(row); } @@ -1198,13 +1193,13 @@ public WorkSheet getLogScale(double base, double zeroValue) throws Exception { } else { String value = getCell(row, col); try { - Double d = Double.parseDouble(value); + double d = Double.parseDouble(value); if (d == 0.0) { d = zeroValue; } else { d = Math.log(d) / Math.log(base); } - workSheet.addCell(row, col, d + ""); + workSheet.addCell(row, col, String.valueOf(d)); } catch (Exception e) { workSheet.addCell(row, col, value); } @@ -1262,7 +1257,7 @@ static CompactCharSequence[][] getAllValuesCompactCharSequence(InputStream is, c BufferedReader br = new BufferedReader(new InputStreamReader(is)); - ArrayList rows = new ArrayList(); + ArrayList rows = new ArrayList<>(); String line = br.readLine(); int numcolumns = -1; @@ -1309,7 +1304,7 @@ static CompactCharSequence[][] getAllValuesCompactCharSequence(InputStream is, c static String[][] getAllValues(String fileName, char delimiter) throws Exception { FileReader reader = new FileReader(fileName); BufferedReader br = new BufferedReader(reader); - ArrayList rows = new ArrayList(); + ArrayList rows = new ArrayList<>(); String line = br.readLine(); int numcolumns = -1; @@ -1388,7 +1383,7 @@ static public WorkSheet unionWorkSheetsRowJoin(WorkSheet w1, WorkSheet w2, boole } } - ArrayList joinedColumns = new ArrayList(); + ArrayList joinedColumns = new ArrayList<>(); joinedColumns.addAll(w1DataColumns); joinedColumns.addAll(w2DataColumns); if (!joinedColumns.contains("META_DATA") && (w1MetaDataColumns.size() > 0 || w2MetaDataColumns.size() > 0)) { @@ -1406,9 +1401,9 @@ static public WorkSheet unionWorkSheetsRowJoin(WorkSheet w1, WorkSheet w2, boole } ArrayList w1Rows = w1.getRows(); ArrayList w2Rows = w2.getRows(); - ArrayList rows = new ArrayList(); + ArrayList rows = new ArrayList<>(); - HashSet w1Key = new HashSet(w1Rows); + HashSet w1Key = new HashSet<>(w1Rows); for (String key : w2Rows) { if (w1Key.contains(key)) { rows.add(key); diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/CensorStatusSelect.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/CensorStatusSelect.java index 067a8814c9..073a163f5b 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/CensorStatusSelect.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/CensorStatusSelect.java @@ -34,7 +34,6 @@ public interface CensorStatusSelect { * @param worksheet * @param row * @return - * @throws Exception */ - public CensorStatus select(WorkSheet worksheet,String row) throws Exception; + CensorStatus select(WorkSheet worksheet, String row); } diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/ExpressionFigure.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/ExpressionFigure.java index a6fda3f095..933ee57d95 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/ExpressionFigure.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/ExpressionFigure.java @@ -31,7 +31,6 @@ import java.io.File; import java.text.DecimalFormat; import java.util.ArrayList; -import java.util.Collections; /** * @@ -41,7 +40,7 @@ public class ExpressionFigure extends JPanel { private static final long serialVersionUID = 1L; - ArrayList title = new ArrayList(); + ArrayList title = new ArrayList<>(); /** * */ @@ -70,8 +69,8 @@ public class ExpressionFigure extends JPanel { FontMetrics fm; KMFigureInfo kmfi = new KMFigureInfo(); // LinkedHashMap> survivalData = new LinkedHashMap>(); - ArrayList lineInfoList = new ArrayList(); - ArrayList siList = new ArrayList(); + ArrayList lineInfoList = new ArrayList<>(); + ArrayList siList = new ArrayList<>(); String variable = ""; private String fileName = ""; @@ -120,7 +119,7 @@ public void setFigureLineInfo(ArrayList lineInfoList) { * @param variable */ public void setSurvivalInfo(ArrayList title, ArrayList _siList, String variable) { - this.siList = new ArrayList(); + this.siList = new ArrayList<>(); this.title = title; this.variable = variable; @@ -132,7 +131,7 @@ public void setSurvivalInfo(ArrayList title, ArrayList _si for (SurvivalInfo si : _siList) { this.siList.add(si); String v = si.getOriginalMetaData(variable); - Double value = Double.parseDouble(v); + double value = Double.parseDouble(v); ds.addValue(value); if (maxTime == null || maxTime < si.getTime()) { maxTime = si.getTime(); @@ -140,17 +139,17 @@ public void setSurvivalInfo(ArrayList title, ArrayList _si } SurvivalInfoValueComparator sivc = new SurvivalInfoValueComparator(variable); - Collections.sort(this.siList, sivc); + this.siList.sort(sivc); mean = ds.getMean(); minY = ds.getMin(); maxY = ds.getMax(); - minY = (double) Math.floor(minY); - maxY = (double) Math.ceil(maxY); + minY = Math.floor(minY); + maxY = Math.ceil(maxY); this.repaint(); } - DecimalFormat df = new DecimalFormat("#.#"); + final DecimalFormat df = new DecimalFormat("#.#"); private void setRenderingHints(Graphics2D g) { RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); @@ -278,7 +277,7 @@ private void drawLegend(Graphics g) { // increment = increment * 10.0; double d = minY + increment; //double graphHeight = top - bottom; - String label = ""; + String label; while (d < maxY) { int yvalue = getY(maxY - d); label = df.format(d); @@ -372,13 +371,13 @@ public static void main(String[] args) { application.setSize(500, 400); // window is 500 pixels wide, 400 high application.setVisible(true); - ArrayList titles = new ArrayList(); + ArrayList titles = new ArrayList<>(); titles.add("Line 1"); titles.add("line 2"); - ArrayList figureInfo = new ArrayList(); + ArrayList figureInfo = new ArrayList<>(); - ArrayList survivalInfoList = new ArrayList(); + ArrayList survivalInfoList = new ArrayList<>(); for (int i = 0; i < 600; i++) { double r = Math.random(); diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/KMFigureInfo.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/KMFigureInfo.java index 24f053d592..9545f2b185 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/KMFigureInfo.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/KMFigureInfo.java @@ -34,31 +34,31 @@ public class KMFigureInfo { /** * */ - public int titleHeight = 40; + public final int titleHeight = 40; /** * */ - public int padding = 20; + public final int padding = 20; /** * */ - public Integer width = 600; + public final Integer width = 600; /** * */ - public Integer height = 400; + public final Integer height = 400; /** * */ - public double timeScale = 1.0; //multiplier to change time from days to months etc + public final double timeScale = 1.0; //multiplier to change time from days to months etc /** * */ - public double yaxisPercentIncrement = .2; + public final double yaxisPercentIncrement = .2; /** * */ - public double xaxisPercentIncrement = .25; + public final double xaxisPercentIncrement = .25; /** * */ @@ -70,24 +70,24 @@ public class KMFigureInfo { /** * */ - public double figureLineInfoLowerPercentX = .01; + public final double figureLineInfoLowerPercentX = .01; /** * */ - public double figureLineInfoLowerPercentY = .01; + public final double figureLineInfoLowerPercentY = .01; /** * */ - public BasicStroke axisStroke = new BasicStroke(2); + public final BasicStroke axisStroke = new BasicStroke(2); /** * */ - public BasicStroke kmStroke = new BasicStroke(3); + public final BasicStroke kmStroke = new BasicStroke(3); /** * */ - public Color[] legendColor = {Color.RED, Color.BLUE, Color.GREEN, Color.CYAN, Color.ORANGE, Color.YELLOW, Color.MAGENTA, Color.PINK}; - public ArrayList xAxisLabels = new ArrayList();//new ArrayList(Arrays.asList(0.0, 5.0, 10.0, 15.0, 20.0)); + public final Color[] legendColor = {Color.RED, Color.BLUE, Color.GREEN, Color.CYAN, Color.ORANGE, Color.YELLOW, Color.MAGENTA, Color.PINK}; + public final ArrayList xAxisLabels = new ArrayList<>();//new ArrayList(Arrays.asList(0.0, 5.0, 10.0, 15.0, 20.0)); public String xAxisLegend = ""; public String yAxisLegend = ""; public Color getColor(int index) { @@ -114,7 +114,7 @@ public void init(String propertyFileName) throws Exception { if (properties.containsKey("xAxisLabels")) { String values = properties.getProperty("xAxisLabels").trim(); if (values.startsWith("[") || values.startsWith("(") || values.startsWith("{")) { - values = values.substring(1, values.length()).trim(); + values = values.substring(1).trim(); } if (values.endsWith("]") || values.endsWith(")") || values.endsWith("}")) { values = values.substring(0, values.length() - 1).trim(); diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/KaplanMeierFigure.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/KaplanMeierFigure.java index c5d358cbeb..7206b1b036 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/KaplanMeierFigure.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/KaplanMeierFigure.java @@ -42,7 +42,7 @@ public class KaplanMeierFigure extends JPanel { private static final long serialVersionUID = 1L; - ArrayList title = new ArrayList(); + ArrayList title = new ArrayList<>(); /** * */ @@ -55,7 +55,7 @@ public class KaplanMeierFigure extends JPanel { * */ private int left; - private int yaxisLabel = 20; + private final int yaxisLabel = 20; /** * */ @@ -65,16 +65,16 @@ public class KaplanMeierFigure extends JPanel { int labelWidth; double minTime = 0.0; double maxTime = 10.0; - double minPercentage = 0.0; - double maxPercentage = 1.0; + final double minPercentage = 0.0; + final double maxPercentage = 1.0; FontMetrics fm; KMFigureInfo kmfi = new KMFigureInfo(); - LinkedHashMap> survivalData = new LinkedHashMap>(); - ArrayList lineInfoList = new ArrayList(); + LinkedHashMap> survivalData = new LinkedHashMap<>(); + ArrayList lineInfoList = new ArrayList<>(); SurvFitInfo sfi = new SurvFitInfo(); private String fileName = ""; - private ArrayList xAxisTimeValues = new ArrayList(); - private ArrayList xAxisTimeCoordinates = new ArrayList(); + private final ArrayList xAxisTimeValues = new ArrayList<>(); + private final ArrayList xAxisTimeCoordinates = new ArrayList<>(); /** * @@ -91,7 +91,7 @@ public KaplanMeierFigure() { * @return */ public ArrayList getGroups() { - return new ArrayList(survivalData.keySet()); + return new ArrayList<>(survivalData.keySet()); } /** @@ -160,7 +160,7 @@ public void setFigureLineInfo(ArrayList lineInfoList) { * @throws Exception */ public void setCoxInfo(ArrayList title, CoxInfo ci, String strataVariable, LinkedHashMap legendMap, Boolean useWeighted) throws Exception { - LinkedHashMap> survivalData = new LinkedHashMap>(); + LinkedHashMap> survivalData = new LinkedHashMap<>(); ArrayList siList = ci.getSurvivalInfoList(); int n = 0; int event = 0; @@ -171,12 +171,8 @@ public void setCoxInfo(ArrayList title, CoxInfo ci, String strataVariabl legend = strata; } - ArrayList censorStatusList = survivalData.get(legend); - if (censorStatusList == null) { - censorStatusList = new ArrayList(); - survivalData.put(legend, censorStatusList); - } - CensorStatus cs = new CensorStatus(strata, si.getTime(), si.getStatus() + ""); + ArrayList censorStatusList = survivalData.computeIfAbsent(legend, k -> new ArrayList<>()); + CensorStatus cs = new CensorStatus(strata, si.getTime(), String.valueOf(si.getStatus())); cs.weight = si.getWeight(); censorStatusList.add(cs); n++; @@ -195,7 +191,7 @@ public void setCoxInfo(ArrayList title, CoxInfo ci, String strataVariabl // System.out.println("setCoxInfo=" + cc.pvalue + " " + title); - ArrayList lines = new ArrayList(); + ArrayList lines = new ArrayList<>(); lines.add(line1); lines.add(line2); lines.add(line3); @@ -210,7 +206,7 @@ public void setCoxInfo(ArrayList title, CoxInfo ci, String strataVariabl * @return */ public static String fmt(Double d, int precision, int pad) { - String value = ""; + String value; DecimalFormat dfe = new DecimalFormat("0.00E0"); String dpad = "0."; double p = 1.0; @@ -303,7 +299,7 @@ public void setSurvivalData(ArrayList title, LinkedHashMap labels = new ArrayList(survivalData.keySet()); + ArrayList labels = new ArrayList<>(survivalData.keySet()); Collections.sort(labels); for (String legend : labels) { ArrayList censorStatusList = survivalData.get(legend); @@ -341,8 +337,7 @@ public void saveSurvivalData(String fileName) throws Exception { FileWriter fw = new FileWriter(fileName); fw.write("index\tTIME\tSTATUS\tGROUP\r\n"); int index = 0; - for (String group : survivalData.keySet()) { - ArrayList sd = survivalData.get(group); + for (ArrayList sd : survivalData.values()) { for (CensorStatus cs : sd) { String line = index + "\t" + cs.time + "\t" + cs.censored + "\t" + cs.group + "\r\n"; index++; @@ -351,7 +346,7 @@ public void saveSurvivalData(String fileName) throws Exception { } fw.close(); } - DecimalFormat df = new DecimalFormat("#.#"); + final DecimalFormat df = new DecimalFormat("#.#"); @Override public void paintComponent(Graphics g) // draw graphics in the panel @@ -394,7 +389,7 @@ private void drawSurvivalCurves(Graphics g) { int colorIndex = 0; - ArrayList labels = new ArrayList(sfi.getStrataInfoHashMap().keySet()); + ArrayList labels = new ArrayList<>(sfi.getStrataInfoHashMap().keySet()); Collections.sort(labels); LinkedHashMap strataInfoHashMap = sfi.getStrataInfoHashMap(); @@ -521,7 +516,7 @@ public ArrayList getxAxisTimeCoordinates() { return xAxisTimeCoordinates; } - class PlotInfo { + static class PlotInfo { double time; double atRisk; @@ -763,7 +758,7 @@ public static void main(String[] args) { try { KaplanMeierFigure kaplanMeierFigure = new KaplanMeierFigure(); - LinkedHashMap> survivalDataHashMap = new LinkedHashMap>(); + LinkedHashMap> survivalDataHashMap = new LinkedHashMap<>(); // if (false) { //http://sph.bu.edu/otlt/MPH-Modules/BS/BS704_Survival/ // ArrayList graph1 = new ArrayList(); @@ -801,7 +796,7 @@ public static void main(String[] args) { - ArrayList graph1 = new ArrayList(); + ArrayList graph1 = new ArrayList<>(); graph1.add(new CensorStatus("A", 1.0, "1")); graph1.add(new CensorStatus("A", 1.0, "1")); graph1.add(new CensorStatus("A", 1.0, "1")); @@ -841,7 +836,7 @@ public static void main(String[] args) { survivalDataHashMap.put("Label 1", graph1); - ArrayList graph2 = new ArrayList(); + ArrayList graph2 = new ArrayList<>(); graph2.add(new CensorStatus("A", 1.0, "1")); graph2.add(new CensorStatus("A", 1.0, "1")); graph2.add(new CensorStatus("A", 1.0, "0")); @@ -882,7 +877,7 @@ public static void main(String[] args) { survivalDataHashMap.put("Label 2", graph2); } - ArrayList figureInfo = new ArrayList(); + ArrayList figureInfo = new ArrayList<>(); //DecimalFormat dfe = new DecimalFormat("0.00E0"); //DecimalFormat df = new DecimalFormat("0.00"); @@ -896,7 +891,7 @@ public static void main(String[] args) { application.setSize(500, 400); // window is 500 pixels wide, 400 high application.setVisible(true); - ArrayList titles = new ArrayList(); + ArrayList titles = new ArrayList<>(); titles.add("Line 1"); titles.add("Line 2"); kaplanMeierFigure.setSurvivalData(titles, survivalDataHashMap, true); diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/NumbersAtRiskPanel.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/NumbersAtRiskPanel.java index 9bc6d0572a..2433e0f976 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/NumbersAtRiskPanel.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/NumbersAtRiskPanel.java @@ -69,7 +69,7 @@ private void paintTable(Graphics g) { g2.setStroke(kmfi.kmStroke); SurvFitInfo sfi = kmf.getSurvivalFitInfo(); - LinkedHashMap sfiHashMap = new LinkedHashMap(); + LinkedHashMap sfiHashMap; if(sfi.isWeighted()){ sfiHashMap = sfi.getUnweightedStrataInfoHashMap(); }else{ @@ -94,7 +94,7 @@ private void paintTable(Graphics g) { ArrayList xaxisTimeValues = kmf.getxAxisTimeValues(); ArrayList xAxisTimeCoordinates = kmf.getxAxisTimeCoordinates(); - ArrayList labels = new ArrayList(sfiHashMap.keySet()); + ArrayList labels = new ArrayList<>(sfiHashMap.keySet()); Collections.sort(labels); for (String group : labels) { @@ -113,7 +113,7 @@ private void paintTable(Graphics g) { Double time = xaxisTimeValues.get(i); int xvalue = xAxisTimeCoordinates.get(i); Double value = si.getNearestAtRisk(time); - String nrisk = ""; + String nrisk; if(value == null){ nrisk = ""; }else{ diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/SurvFitKM.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/SurvFitKM.java index f315eaaf0a..91e11e3b29 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/SurvFitKM.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/figure/SurvFitKM.java @@ -29,6 +29,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; +import java.util.Map; /** * Ported from survfitKM.S When combining multiple entries with same time not @@ -54,7 +55,7 @@ public enum Method { /** * */ - fh2; + fh2 } /** @@ -69,7 +70,7 @@ public enum Error { /** * */ - tsiatis; + tsiatis } /** @@ -92,7 +93,7 @@ public enum ConfType { /** * */ - none; + none } /** @@ -111,7 +112,7 @@ public enum ConfLower { /** * */ - modified; + modified } /** @@ -122,17 +123,17 @@ public enum ConfLower { * @throws Exception */ public SurvFitInfo process(LinkedHashMap> survivalData, boolean useWeights) throws Exception { - ArrayList survivalInfoList = new ArrayList(); + ArrayList survivalInfoList = new ArrayList<>(); int i = 0; - for (String strata : survivalData.keySet()) { - ArrayList csList = survivalData.get(strata); + for (Map.Entry> entry : survivalData.entrySet()) { + ArrayList csList = entry.getValue(); for (CensorStatus cs : csList) { SurvivalInfo si = new SurvivalInfo(cs.time, Integer.parseInt(cs.censored)); si.setOrder(i); i++; si.setWeight(cs.weight); - si.addUnknownDataTypeVariable("STRATA", strata); - si.addUnknownDataTypeVariable("VALUE", cs.value + ""); + si.addUnknownDataTypeVariable("STRATA", entry.getKey()); + si.addUnknownDataTypeVariable("VALUE", String.valueOf(cs.value)); survivalInfoList.add(si); } } @@ -154,7 +155,7 @@ public SurvFitInfo process(LinkedHashMap> surviv */ public SurvFitInfo process(String datafile, String timeColumn, String statusColumn, String weightColumn, String variableColumn, boolean useWeights) throws Exception { WorkSheet worksheet = WorkSheet.readCSV(datafile, '\t'); - ArrayList survivalInfoList = new ArrayList(); + ArrayList survivalInfoList = new ArrayList<>(); int i = 1; for (String row : worksheet.getRows()) { @@ -223,8 +224,8 @@ public LinkedHashMap processStrataInfo(String variable, Arr int n = dataT.size(); - LinkedHashMap levels = new LinkedHashMap(); - LinkedHashMap> strataHashMap = new LinkedHashMap>(); + LinkedHashMap levels = new LinkedHashMap<>(); + LinkedHashMap> strataHashMap = new LinkedHashMap<>(); for (int i = 0; i < n; i++) { SurvivalInfo si = dataT.get(i); @@ -235,24 +236,20 @@ public LinkedHashMap processStrataInfo(String variable, Arr } count++; levels.put(value, count); - ArrayList strataList = strataHashMap.get(value); - if (strataList == null) { - strataList = new ArrayList(); - strataHashMap.put(value, strataList); - } + ArrayList strataList = strataHashMap.computeIfAbsent(value, k -> new ArrayList<>()); strataList.add(si); } //int nstrat = levels.size(); - LinkedHashMap strataInfoHashMap = new LinkedHashMap(); + LinkedHashMap strataInfoHashMap = new LinkedHashMap<>(); - for (String strata : strataHashMap.keySet()) { + for (Map.Entry> entry : strataHashMap.entrySet()) { - ArrayList strataList = strataHashMap.get(strata); + ArrayList strataList = entry.getValue(); StrataInfo strataInfo = new StrataInfo(); - strataInfoHashMap.put(strata, strataInfo); + strataInfoHashMap.put(entry.getKey(), strataInfo); Double previousTime = null; @@ -379,8 +376,8 @@ public LinkedHashMap processStrataInfo(String variable, Arr } - ArrayList events = new ArrayList(); - ArrayList nrisk = new ArrayList(); + ArrayList events = new ArrayList<>(); + ArrayList nrisk = new ArrayList<>(); for (StrataInfo strataInfo : strataInfoHashMap.values()) { boolean firsttime = true; for (int j = 0; j < strataInfo.getNevent().size(); j++) { @@ -395,19 +392,19 @@ public LinkedHashMap processStrataInfo(String variable, Arr } } - ArrayList zz = new ArrayList(); + ArrayList zz = new ArrayList<>(); for (int i = 0; i < events.size(); i++) { if (events.get(i)) { zz.add(i + 1); } } zz.add(events.size() + 1); - ArrayList diffzz = new ArrayList(); + ArrayList diffzz = new ArrayList<>(); for (int i = 0; i < zz.size() - 1; i++) { diffzz.add(zz.get(i + 1) - zz.get(i)); } //System.out.println(diffzz); - ArrayList nlag = new ArrayList(); + ArrayList nlag = new ArrayList<>(); for (int j = 0; j < nrisk.size(); j++) { int count = diffzz.get(j); for (int c = 0; c < count; c++) { @@ -542,12 +539,12 @@ public static void main(String[] args) { application.setSize(500, 400); // window is 500 pixels wide, 400 high application.setVisible(true); - ArrayList titles = new ArrayList(); + ArrayList titles = new ArrayList<>(); titles.add("Line 1"); titles.add("line 2"); kaplanMeierFigure.setSurvivalData(titles, si, null); - ArrayList figureInfo = new ArrayList(); + ArrayList figureInfo = new ArrayList<>(); // figureInfo.add("HR=2.1 95% CI(1.8-2.5)"); // figureInfo.add("p-value=.001"); kaplanMeierFigure.setFigureLineInfo(figureInfo); diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/metadata/ClinicalMetaDataOutcome.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/metadata/ClinicalMetaDataOutcome.java index b75cc2d3ad..3b1ca8fe15 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/metadata/ClinicalMetaDataOutcome.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/metadata/ClinicalMetaDataOutcome.java @@ -66,7 +66,7 @@ static public void process(WorkSheet worksheet, String sensorMapColumn, LinkedHa public static void main(String[] args) { try { - LinkedHashMap censorMap = new LinkedHashMap(); + LinkedHashMap censorMap = new LinkedHashMap<>(); censorMap.put("a", "0"); censorMap.put("d", "1"); censorMap.put("d-d.s.", "1"); @@ -74,7 +74,7 @@ public static void main(String[] args) { String timeColumn = "TIME"; String sensorMapColumn = "last_follow_up_status"; // "survstat3"; double timeScale = 1.0; - ArrayList metaDataInfoList = new ArrayList(); + ArrayList metaDataInfoList = new ArrayList<>(); metaDataInfoList.add(new MetaDataInfo("age_at_diagnosis", true, new MeanQuantizer())); metaDataInfoList.add(new MetaDataInfo("size", true, new MeanQuantizer())); metaDataInfoList.add(new MetaDataInfo("lymph_nodes_positive", true, new MeanQuantizer())); diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/metadata/DiscreteQuantizerInterface.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/metadata/DiscreteQuantizerInterface.java index 5c80054a72..b902150400 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/metadata/DiscreteQuantizerInterface.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/metadata/DiscreteQuantizerInterface.java @@ -33,6 +33,6 @@ public interface DiscreteQuantizerInterface { * @param worksheet * @param column */ - public void process(WorkSheet worksheet, String column); + void process(WorkSheet worksheet, String column); } diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/metadata/MeanQuantizer.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/metadata/MeanQuantizer.java index 964a365cdc..7a0a55aff4 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/metadata/MeanQuantizer.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/metadata/MeanQuantizer.java @@ -39,15 +39,15 @@ public void process(WorkSheet worksheet, String column) { DescriptiveStatistics ds = new DescriptiveStatistics(); for (String row : worksheet.getRows()) { try { - Double d = Double.parseDouble(worksheet.getCell(row, column)); + double d = Double.parseDouble(worksheet.getCell(row, column)); ds.addValue(d); } catch (Exception e) { } } - Double mean = ds.getMean(); + double mean = ds.getMean(); for (String row : worksheet.getRows()) { try { - Double d = Double.parseDouble(worksheet.getCell(row, column)); + double d = Double.parseDouble(worksheet.getCell(row, column)); if (d < mean) { worksheet.addCell(row, column, "L"); } else { diff --git a/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/metadata/MetaDataInfo.java b/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/metadata/MetaDataInfo.java index 26bcef3081..25bd425632 100644 --- a/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/metadata/MetaDataInfo.java +++ b/biojava-survival/src/main/java/org/biojava/nbio/survival/kaplanmeier/metadata/MetaDataInfo.java @@ -33,7 +33,7 @@ public class MetaDataInfo { /** * */ - public String column = ""; + public final String column; /** * */ @@ -42,7 +42,7 @@ public class MetaDataInfo { * */ public DiscreteQuantizerInterface discreteQuantizer = null; - ArrayList discreteValues = new ArrayList(); + ArrayList discreteValues = new ArrayList<>(); /** * diff --git a/biojava-ws/pom.xml b/biojava-ws/pom.xml index 8df54334cf..2c2b895319 100644 --- a/biojava-ws/pom.xml +++ b/biojava-ws/pom.xml @@ -56,15 +56,7 @@ - - org.apache.maven.plugins - maven-jar-plugin - - - demo/** - - - + diff --git a/biojava-ws/src/main/java/demo/HmmerDemo.java b/biojava-ws/src/main/java/demo/HmmerDemo.java index 689d62ec92..d3a7374928 100644 --- a/biojava-ws/src/main/java/demo/HmmerDemo.java +++ b/biojava-ws/src/main/java/demo/HmmerDemo.java @@ -85,8 +85,8 @@ public static void main(String[] args) throws Exception { */ private static ProteinSequence getUniprot(String uniProtID) throws Exception { - AminoAcidCompoundSet set = AminoAcidCompoundSet.getAminoAcidCompoundSet(); - UniprotProxySequenceReader uniprotSequence = new UniprotProxySequenceReader(uniProtID,set); + AminoAcidCompoundSet set = AminoAcidCompoundSet.aminoAcidCompoundSet; + UniprotProxySequenceReader uniprotSequence = new UniprotProxySequenceReader<>(uniProtID, set); ProteinSequence seq = new ProteinSequence(uniprotSequence); diff --git a/biojava-ws/src/main/java/demo/NCBIQBlastServiceDemo.java b/biojava-ws/src/main/java/demo/NCBIQBlastServiceDemo.java index 1b3c5a1c9a..32b1ef13e4 100644 --- a/biojava-ws/src/main/java/demo/NCBIQBlastServiceDemo.java +++ b/biojava-ws/src/main/java/demo/NCBIQBlastServiceDemo.java @@ -41,7 +41,7 @@ public class NCBIQBlastServiceDemo { private static final String SEQUENCE = "MKWVTFISLLFLFSSAYSRGVFRRDAHKSEVAHRFKDLGEENFKALVLIAFAQYLQQCPFEDHVKLVNEVTEFAKTCVADESAENCDKS"; public static void main(String[] args) { - NCBIQBlastService service = null; + NCBIQBlastService service; if (args.length == 1) { service = new NCBIQBlastService(args[0]); } else { diff --git a/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/RemotePairwiseAlignmentOutputProperties.java b/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/RemotePairwiseAlignmentOutputProperties.java index d8ca2d2b4b..9e465782c6 100644 --- a/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/RemotePairwiseAlignmentOutputProperties.java +++ b/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/RemotePairwiseAlignmentOutputProperties.java @@ -37,16 +37,15 @@ public interface RemotePairwiseAlignmentOutputProperties extends Serializable{ /** * */ - public static final long serialVersionUID = 1L; + long serialVersionUID = 1L; /** * Method that returns the value associated with the key given in parameter. * * @param key :a String with the required key for this map. * @return a String with the value associated with this key - * @throws Exception if key is not in the map of output options. */ - public String getOutputOption(String key) throws Exception; + String getOutputOption(String key); /** @@ -55,12 +54,12 @@ public interface RemotePairwiseAlignmentOutputProperties extends Serializable{ * @param key :the key use to designate the value to be stored * @param val :the actual value matched to key */ - public void setOutputOption(String key,String val); + void setOutputOption(String key, String val); /** * Method to get all keys to the information stored in this object. * * @return a Set with all keys held in this instance of the object */ - public Set getOutputOptions(); + Set getOutputOptions(); } diff --git a/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/RemotePairwiseAlignmentProperties.java b/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/RemotePairwiseAlignmentProperties.java index 83ac02a612..a8f489fde8 100644 --- a/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/RemotePairwiseAlignmentProperties.java +++ b/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/RemotePairwiseAlignmentProperties.java @@ -39,16 +39,15 @@ */ public interface RemotePairwiseAlignmentProperties extends Serializable{ - public static final long serialVersionUID = 1L; + long serialVersionUID = 1L; /** * Method that returns the value associated with the key given in parameter. * * @param key :a String with the required key for this map. * @return a String with the value associated with this key - * @throws Exception if key is not in the map of output options. */ - public String getAlignmentOption(String key) throws Exception; + String getAlignmentOption(String key); /** * Method to set the value for a specific alignment parameter using a key to store in a map. @@ -56,12 +55,12 @@ public interface RemotePairwiseAlignmentProperties extends Serializable{ * @param key :the key use to designate the value to be stored * @param val :the actual value matched to key */ - public void setAlignementOption(String key,String val); + void setAlignementOption(String key, String val); /** * Method to get all keys to the information stored in this object. * * @return a Set with all keys held in this instance of the object */ - public Set getAlignmentOptions(); + Set getAlignmentOptions(); } diff --git a/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/RemotePairwiseAlignmentService.java b/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/RemotePairwiseAlignmentService.java index 3df4f39f01..d39f85422f 100644 --- a/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/RemotePairwiseAlignmentService.java +++ b/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/RemotePairwiseAlignmentService.java @@ -41,7 +41,7 @@ public interface RemotePairwiseAlignmentService { * * @throws Exception */ - public String sendAlignmentRequest(Sequence seq, RemotePairwiseAlignmentProperties rpa) throws Exception; + String sendAlignmentRequest(Sequence seq, RemotePairwiseAlignmentProperties rpa) throws Exception; /** * Doing the actual analysis on the instantiated service using specified parameters on the string representation @@ -49,7 +49,7 @@ public interface RemotePairwiseAlignmentService { * * @throws Exception */ - public String sendAlignmentRequest(String str, RemotePairwiseAlignmentProperties rpa) throws Exception; + String sendAlignmentRequest(String str, RemotePairwiseAlignmentProperties rpa) throws Exception; /** * Simple method to check if the specified request has been completed by the service used. @@ -59,7 +59,7 @@ public interface RemotePairwiseAlignmentService { * @return a boolean value telling if this requestID has been completed or not. * @throws Exception if the ID does not exist. */ - public boolean isReady(String id,long present) throws Exception; + boolean isReady(String id, long present) throws Exception; /** * Getting the actual alignment results from this instantiated service for a given ID with specific @@ -70,5 +70,5 @@ public interface RemotePairwiseAlignmentService { * @return : an InputStream with the actual alignment results * @throws Exception */ - public InputStream getAlignmentResults(String rid,RemotePairwiseAlignmentOutputProperties out) throws Exception; + InputStream getAlignmentResults(String rid, RemotePairwiseAlignmentOutputProperties out) throws Exception; } diff --git a/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/qblast/MapToStringTransformer.java b/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/qblast/MapToStringTransformer.java index 3fc154d009..bf59d06944 100644 --- a/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/qblast/MapToStringTransformer.java +++ b/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/qblast/MapToStringTransformer.java @@ -83,12 +83,13 @@ public MapToStringTransformer(String mappingSequence, String separatorSequence, */ public String transform(Map map) { StringBuilder sb = new StringBuilder(); - for (Object key : map.keySet()) { - sb.append(getSeparatorSequence()); + for (Map.Entry entry : map.entrySet()) { + Object key = entry.getKey(); + sb.append(getSeparatorSequence()); String keyString = key != null ? key.toString() : getNullValue(); sb.append(keyString); sb.append(getMappingSequence()); - String valueString = map.get(key) != null ? map.get(key).toString() : getNullValue(); + String valueString = entry.getValue() != null ? entry.getValue().toString() : getNullValue(); sb.append(valueString); } return sb.substring(1); diff --git a/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/qblast/NCBIQBlastAlignmentProperties.java b/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/qblast/NCBIQBlastAlignmentProperties.java index 3d9ad05377..225386cc50 100644 --- a/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/qblast/NCBIQBlastAlignmentProperties.java +++ b/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/qblast/NCBIQBlastAlignmentProperties.java @@ -45,7 +45,7 @@ public class NCBIQBlastAlignmentProperties implements RemotePairwiseAlignmentProperties { private static final long serialVersionUID = 7158270364392309841L; - private Map param = new HashMap(); + private final Map param = new HashMap<>(); /** * This method forwards to {@link #getAlignmentOption(BlastAlignmentParameterEnum)}. Consider using it instead. @@ -69,7 +69,7 @@ public void setAlignementOption(String key, String val) { */ @Override public Set getAlignmentOptions() { - Set result = new HashSet(); + Set result = new HashSet<>(); for (BlastAlignmentParameterEnum parameter : param.keySet()) { result.add(parameter.name()); } @@ -302,7 +302,9 @@ public void setBlastMatrix(BlastMatrixEnum matrix) { setBlastGapCosts(9, 1); break; case PAM70: - setBlastGapCosts(10, 1); + case BLOSUM80: + case BLOSUM90: + setBlastGapCosts(10, 1); break; case PAM250: setBlastGapCosts(14, 2); @@ -313,13 +315,8 @@ public void setBlastMatrix(BlastMatrixEnum matrix) { case BLOSUM50: setBlastGapCosts(13, 2); break; - case BLOSUM80: - case BLOSUM90: - setBlastGapCosts(10, 1); - break; - case BLOSUM62: - break; - default: + case BLOSUM62: + default: break; } } diff --git a/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/qblast/NCBIQBlastOutputProperties.java b/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/qblast/NCBIQBlastOutputProperties.java index 8efc91908b..70fefd5899 100644 --- a/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/qblast/NCBIQBlastOutputProperties.java +++ b/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/qblast/NCBIQBlastOutputProperties.java @@ -41,7 +41,7 @@ public class NCBIQBlastOutputProperties implements RemotePairwiseAlignmentOutputProperties { private static final long serialVersionUID = -9202060390925345163L; - private Map param = new HashMap(); + private final Map param = new HashMap<>(); /** * This constructor builds the parameters for the output of the GET command sent to the QBlast service with default @@ -96,7 +96,7 @@ public void setOutputOption(BlastOutputParameterEnum key, String value) { */ @Override public Set getOutputOptions() { - Set result = new HashSet(); + Set result = new HashSet<>(); for (BlastOutputParameterEnum parameter : param.keySet()) { result.add(parameter.name()); } diff --git a/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/qblast/NCBIQBlastService.java b/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/qblast/NCBIQBlastService.java index c63a4b7eb9..10f4c3bf5c 100644 --- a/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/qblast/NCBIQBlastService.java +++ b/biojava-ws/src/main/java/org/biojava/nbio/ws/alignment/qblast/NCBIQBlastService.java @@ -72,7 +72,7 @@ public class NCBIQBlastService implements RemotePairwiseAlignmentService { private String email = DEFAULT_EMAIL; private String tool = DEFAULT_TOOL; - private Map jobs = new HashMap(); + private final Map jobs = new HashMap<>(); /** Constructs a service object that targets the public NCBI BLAST network * service. @@ -164,7 +164,7 @@ public String sendAlignmentRequest(int gid, RemotePairwiseAlignmentProperties rp */ @Override public String sendAlignmentRequest(String query, RemotePairwiseAlignmentProperties alignmentProperties) throws Exception { - Map params = new HashMap(); + Map params = new HashMap<>(); for (String key : alignmentProperties.getAlignmentOptions()) { params.put(key, alignmentProperties.getAlignmentOption(key)); } @@ -318,7 +318,7 @@ public boolean isReady(String id, long present) throws Exception { */ @Override public InputStream getAlignmentResults(String id, RemotePairwiseAlignmentOutputProperties outputProperties) throws Exception { - Map params = new HashMap(); + Map params = new HashMap<>(); for (String key : outputProperties.getOutputOptions()) { params.put(key, outputProperties.getOutputOption(key)); } diff --git a/biojava-ws/src/main/java/org/biojava/nbio/ws/hmmer/HmmerDomain.java b/biojava-ws/src/main/java/org/biojava/nbio/ws/hmmer/HmmerDomain.java index d9b8e3de89..6935568168 100644 --- a/biojava-ws/src/main/java/org/biojava/nbio/ws/hmmer/HmmerDomain.java +++ b/biojava-ws/src/main/java/org/biojava/nbio/ws/hmmer/HmmerDomain.java @@ -129,10 +129,7 @@ public int compareTo(HmmerDomain o) { return (this.getSqFrom().compareTo(o.getSqFrom())); } private boolean emptyDomain(HmmerDomain o) { - - if ( o.getSqFrom() == null) - return true; - return false; + return o.getSqFrom() == null; } /* diff --git a/biojava-ws/src/main/java/org/biojava/nbio/ws/hmmer/HmmerResult.java b/biojava-ws/src/main/java/org/biojava/nbio/ws/hmmer/HmmerResult.java index 3304e78d4f..0e9be75a82 100644 --- a/biojava-ws/src/main/java/org/biojava/nbio/ws/hmmer/HmmerResult.java +++ b/biojava-ws/src/main/java/org/biojava/nbio/ws/hmmer/HmmerResult.java @@ -23,175 +23,187 @@ import java.io.Serializable; import java.util.SortedSet; -/** The results of a Hmmer search for a single sequence +/** + * The results of a Hmmer search for a single sequence * * @author Andreas Prlic * @since 3.0.3 */ -public class HmmerResult implements Comparable, Serializable{ - - /** - * - */ - private static final long serialVersionUID = -6016026193090737943L; - - String desc ; - Float score; - Float evalue; - Double pvalue; - String acc; - Integer dcl; - String name; - Integer ndom; - Integer nreported; - - SortedSetdomains; - - public SortedSet getDomains() { - return domains; - } - public void setDomains(SortedSet domains) { - this.domains = domains; - } - public String getDesc() { - return desc; - } - public void setDesc(String desc) { - this.desc = desc; - } - public Float getScore() { - return score; - } - public void setScore(Float score) { - this.score = score; - } - public Float getEvalue() { - return evalue; - } - public void setEvalue(Float evalue) { - this.evalue = evalue; - } - public Double getPvalue() { - return pvalue; - } - public void setPvalue(Double pvalue) { - this.pvalue = pvalue; - } - public String getAcc() { - return acc; - } - public void setAcc(String acc) { - this.acc = acc; - } - public Integer getDcl() { - return dcl; - } - public void setDcl(Integer dcl) { - this.dcl = dcl; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public Integer getNdom() { - return ndom; - } - public void setNdom(Integer ndom) { - this.ndom = ndom; - } - public Integer getNreported() { - return nreported; - } - public void setNreported(Integer nreported) { - this.nreported = nreported; - } - @Override - public String toString() { - return "HmmerResult [acc=" + acc + ", desc=" + desc + ", score=" + score + ", evalue=" - + evalue + ", pvalue=" + pvalue + ", dcl=" - + dcl + ", name=" + name + ", ndom=" + ndom + ", nreported=" - + nreported + ", domains=" + domains + "]"; - } - - - @Override - public int compareTo(HmmerResult o) { - // sort by the start position of the first domain - - if ( emptyDomains(this) && emptyDomains(o)){ - return 0; - } - - if ( ! emptyDomains(this) && emptyDomains(o)) - return -1; - - if ( emptyDomains(this) && (! emptyDomains(o))) - return 1; - - // ok when we are here, both domains are not empty - - HmmerDomain me = this.getDomains().first(); - HmmerDomain other = o.getDomains().first(); - - //System.out.println(" domains: " + me.getHmmAcc() + " " + other.getHmmAcc()+ " " + me.getSqFrom().compareTo(other.getSqFrom())); - - return(me.getSqFrom().compareTo(other.getSqFrom())); - } - private boolean emptyDomains(HmmerResult o) { - if ( o.getDomains() == null || o.getDomains().size() == 0) - return true; - return false; - } - - - /** Get the overlap between two HmmerResult objects - * - * @param other - * @return 0 if no overlap, otherwise the length of the overlap - */ - public int getOverlapLength(HmmerResult other){ - - int overlap = 0; - for ( HmmerDomain d1 : getDomains()){ - for (HmmerDomain d2 : other.getDomains()){ - overlap += getOverlap(d1, d2); - } - } - return overlap; - - } - - private int getOverlap(HmmerDomain one, HmmerDomain other){ - int xs = one.getSqFrom(); - int ys = one.getSqTo(); - int as = other.getSqFrom(); - int bs = other.getSqTo(); - - int overlap = 0; - //1: - - if ((( xs< as) && ( as, Serializable { + + /** + * + */ + private static final long serialVersionUID = -6016026193090737943L; + + String desc; + Float score; + Float evalue; + Double pvalue; + String acc; + Integer dcl; + String name; + Integer ndom; + Integer nreported; + + SortedSet domains; + + public SortedSet getDomains() { + return domains; + } + + public void setDomains(SortedSet domains) { + this.domains = domains; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public Float getScore() { + return score; + } + + public void setScore(Float score) { + this.score = score; + } + + public Float getEvalue() { + return evalue; + } + + public void setEvalue(Float evalue) { + this.evalue = evalue; + } + + public Double getPvalue() { + return pvalue; + } + + public void setPvalue(Double pvalue) { + this.pvalue = pvalue; + } + + public String getAcc() { + return acc; + } + + public void setAcc(String acc) { + this.acc = acc; + } + + public Integer getDcl() { + return dcl; + } + + public void setDcl(Integer dcl) { + this.dcl = dcl; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getNdom() { + return ndom; + } + + public void setNdom(Integer ndom) { + this.ndom = ndom; + } + + public Integer getNreported() { + return nreported; + } + + public void setNreported(Integer nreported) { + this.nreported = nreported; + } + + @Override + public String toString() { + return "HmmerResult [acc=" + acc + ", desc=" + desc + ", score=" + score + ", evalue=" + + evalue + ", pvalue=" + pvalue + ", dcl=" + + dcl + ", name=" + name + ", ndom=" + ndom + ", nreported=" + + nreported + ", domains=" + domains + "]"; + } + + + @Override + public int compareTo(HmmerResult o) { + + if (this == o) return 0; + // sort by the start position of the first domain + + boolean eThis = emptyDomains(this); + boolean eThat = emptyDomains(o); + if (eThis && eThat) + return 0; + + if (!eThis && eThat) + return -1; + + if (eThis && !eThat) + return 1; + + // ok when we are here, both domains are not empty + + //System.out.println(" domains: " + me.getHmmAcc() + " " + other.getHmmAcc()+ " " + me.getSqFrom().compareTo(other.getSqFrom())); + + return this.getDomains().first().getSqFrom().compareTo(o.getDomains().first().getSqFrom()); + } + + private boolean emptyDomains(HmmerResult o) { + SortedSet d = o.getDomains(); + return d == null || d.size() == 0; + } + + + /** + * Get the overlap between two HmmerResult objects + * + * @param other + * @return 0 if no overlap, otherwise the length of the overlap + */ + public int getOverlapLength(HmmerResult other) { + + int overlap = 0; + for (HmmerDomain d1 : getDomains()) { + for (HmmerDomain d2 : other.getDomains()) { + overlap += getOverlap(d1, d2); + } + } + return overlap; + + } + + private int getOverlap(HmmerDomain one, HmmerDomain other) { + int xs = one.getSqFrom(); + int ys = one.getSqTo(); + int as = other.getSqFrom(); + int bs = other.getSqTo(); + + if (((xs < as) && (as < ys)) || ((xs < bs) && (bs <= ys)) || (as < xs && ys < bs)) { + + //2: + + if (xs < as) { + return ys < bs ? ys - as : bs - as; + } else { + return ys < bs ? ys - xs : bs - xs; + } + + } + + return 0; + } } diff --git a/biojava-ws/src/main/java/org/biojava/nbio/ws/hmmer/HmmerScan.java b/biojava-ws/src/main/java/org/biojava/nbio/ws/hmmer/HmmerScan.java index 854995d39e..60e96253c8 100644 --- a/biojava-ws/src/main/java/org/biojava/nbio/ws/hmmer/HmmerScan.java +++ b/biojava-ws/src/main/java/org/biojava/nbio/ws/hmmer/HmmerScan.java @@ -32,6 +32,6 @@ */ public interface HmmerScan { - public SortedSet scan(ProteinSequence sequence) throws IOException; + SortedSet scan(ProteinSequence sequence) throws IOException; } diff --git a/biojava-ws/src/main/java/org/biojava/nbio/ws/hmmer/RemoteHmmerScan.java b/biojava-ws/src/main/java/org/biojava/nbio/ws/hmmer/RemoteHmmerScan.java index 2083db63aa..5d4e1ab2c3 100644 --- a/biojava-ws/src/main/java/org/biojava/nbio/ws/hmmer/RemoteHmmerScan.java +++ b/biojava-ws/src/main/java/org/biojava/nbio/ws/hmmer/RemoteHmmerScan.java @@ -26,7 +26,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.*; +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.SortedSet; @@ -53,9 +56,7 @@ public RemoteHmmerScan(){ @Override public SortedSet scan(ProteinSequence sequence) throws IOException { - URL url = new URL(HMMER_SERVICE); - - return scan(sequence, url); + return scan(sequence, new URL(HMMER_SERVICE)); } @@ -69,7 +70,7 @@ public SortedSet scan(ProteinSequence sequence) throws IOException */ public SortedSet scan(ProteinSequence sequence, URL serviceLocation) throws IOException{ - StringBuffer postContent = new StringBuffer(); + StringBuilder postContent = new StringBuilder(); postContent.append("hmmdb=pfam"); @@ -94,8 +95,7 @@ public SortedSet scan(ProteinSequence sequence, URL serviceLocation connection.setRequestProperty("Accept","application/json"); - connection.setRequestProperty("Content-Length", "" + - Integer.toString(postContent.toString().getBytes().length)); + connection.setRequestProperty("Content-Length", String.valueOf(postContent.toString().getBytes().length)); //Send request DataOutputStream wr = new DataOutputStream ( @@ -125,7 +125,7 @@ public SortedSet scan(ProteinSequence sequence, URL serviceLocation String inputLine; - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); while ((inputLine = in.readLine()) != null) { result.append(inputLine); } @@ -134,7 +134,7 @@ public SortedSet scan(ProteinSequence sequence, URL serviceLocation // process the response and build up a container for the data. - SortedSet results = new TreeSet(); + SortedSet results = new TreeSet<>(); try { JSONObject json = JSONObject.fromObject(result.toString()); @@ -149,7 +149,7 @@ public SortedSet scan(ProteinSequence sequence, URL serviceLocation HmmerResult hmmResult = new HmmerResult(); Object dclO = hit.get("dcl"); - Integer dcl = -1; + int dcl = -1; if ( dclO instanceof Long){ Long dclL = (Long) dclO; dcl = dclL.intValue(); @@ -170,7 +170,7 @@ public SortedSet scan(ProteinSequence sequence, URL serviceLocation JSONArray hmmdomains = hit.getJSONArray("domains"); - SortedSet domains = new TreeSet(); + SortedSet domains = new TreeSet<>(); for ( int j= 0 ; j < hmmdomains.size() ; j++){ JSONObject d = hmmdomains.getJSONObject(j); Integer is_included = getInteger(d.get("is_included")); diff --git a/biojava-ws/src/test/java/org/biojava/nbio/ws/hmmer/TestRemoteHmmerScan.java b/biojava-ws/src/test/java/org/biojava/nbio/ws/hmmer/TestRemoteHmmerScan.java index a5b493809b..0076052f5c 100644 --- a/biojava-ws/src/test/java/org/biojava/nbio/ws/hmmer/TestRemoteHmmerScan.java +++ b/biojava-ws/src/test/java/org/biojava/nbio/ws/hmmer/TestRemoteHmmerScan.java @@ -20,11 +20,12 @@ */ package org.biojava.nbio.ws.hmmer; -import java.util.SortedSet; - import org.biojava.nbio.core.sequence.ProteinSequence; import org.junit.Ignore; import org.junit.Test; + +import java.util.SortedSet; + import static org.junit.Assert.*; public class TestRemoteHmmerScan { @@ -57,6 +58,7 @@ public void testHmmerWs() throws Exception { for (HmmerResult hmmerResult : results) { if (hmmerResult.getName().equals("HTH_5")) { gotSh2Domain = true; + break; } } diff --git a/pom.xml b/pom.xml index 9ff4c461ee..a3b33e121d 100644 --- a/pom.xml +++ b/pom.xml @@ -39,10 +39,10 @@ UTF-8 UTF-8 - 512M + 1024M 1.0.9 - 1.7.25 - 2.6.2 + 2.0.0-alpha1 + 2.13.1 scm:git:git://github.com/biojava/biojava.git @@ -164,7 +164,7 @@ maven-compiler-plugin - 3.8.0 + 3.8.1 ${jdk.version} ${jdk.version} @@ -180,11 +180,11 @@ maven-scm-plugin - 1.10.0 + 1.11.2 maven-source-plugin - 3.0.1 + 3.2.1 maven-failsafe-plugin @@ -239,7 +239,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.0 + 3.2.2 maven-assembly-plugin @@ -313,7 +313,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.0.0-M3 + 3.0.0-M4 org.apache.maven.plugins @@ -368,8 +368,8 @@ maven-surefire-plugin -Xmx1500M - false - 1 + + @@ -455,6 +455,20 @@ + + maven-dependency-plugin + + + install + + copy-dependencies + + + ${project.build.directory}/lib + + + + @@ -474,7 +488,7 @@ junit junit - 4.12 + 4.13 test @@ -513,17 +527,17 @@ javax.xml.bind jaxb-api - 2.3.0 + 2.4.0-b180830.0359 com.sun.xml.bind jaxb-core - 2.3.0 + 2.3.0.1 com.sun.xml.bind jaxb-impl - 2.3.0 + 2.3.3-b02 javax.activation @@ -549,7 +563,7 @@ maven-project-info-reports-plugin - 2.9 + 3.0.0 @@ -573,12 +587,12 @@ org.apache.maven.plugins maven-checkstyle-plugin - 2.17 + 3.0.0 org.apache.maven.plugins maven-jxr-plugin - 2.5 + 3.0.0 @@ -600,7 +614,7 @@ org.apache.maven.plugins maven-jarsigner-plugin - 1.4 + 3.0.0 sign @@ -645,6 +659,15 @@ + + org.apache.maven.plugins + maven-jar-plugin + + + demo/** + + + org.apache.maven.plugins maven-gpg-plugin @@ -658,28 +681,28 @@ - - + + + - biojava-core + biojava-aa-prop biojava-alignment - biojava-structure - biojava-structure-gui + biojava-core biojava-genome + biojava-integrationtest biojava-modfinder - biojava-ws + biojava-ontology biojava-protein-disorder - biojava-aa-prop + biojava-structure-gui + biojava-structure biojava-survival - biojava-ontology - - biojava-integrationtest + biojava-ws 2000