From 8261f257af8a4a9509a6bb8054b0016dfeae4a55 Mon Sep 17 00:00:00 2001 From: Jim Procter Date: Mon, 5 Aug 2024 16:14:37 +0100 Subject: [PATCH] JAL-1551 gradle spotlessApply and doc tweaks --- src/jalview/analysis/AAFrequency.java | 151 +-- src/jalview/analysis/AlignSeq.java | 231 +++-- src/jalview/analysis/AlignmentUtils.java | 331 ++++--- src/jalview/analysis/ConnectivityException.java | 8 +- src/jalview/analysis/Finder.java | 2 +- src/jalview/analysis/PaSiMap.java | 44 +- src/jalview/analysis/ccAnalysis.java | 1017 +++++++++++--------- .../analysis/scoremodels/DistanceScoreModel.java | 2 +- .../analysis/scoremodels/FeatureDistanceModel.java | 2 +- src/jalview/analysis/scoremodels/ScoreModels.java | 14 +- .../SecondaryStructureDistanceModel.java | 302 +++--- .../analysis/scoremodels/SimilarityParams.java | 2 +- src/jalview/api/AlignViewControllerI.java | 4 +- src/jalview/api/AlignViewportI.java | 14 +- src/jalview/api/analysis/ScoreModelI.java | 9 +- src/jalview/api/analysis/SimilarityParamsI.java | 2 +- src/jalview/appletgui/AlignFrame.java | 4 +- src/jalview/bin/Cache.java | 9 +- src/jalview/bin/JalviewLite.java | 4 +- .../commands/JustifyLeftOrRightCommand.java | 6 +- src/jalview/controller/AlignViewController.java | 2 +- src/jalview/datamodel/PDBEntry.java | 6 +- src/jalview/datamodel/Profile.java | 18 +- src/jalview/datamodel/ProfileI.java | 10 +- src/jalview/datamodel/SecondaryStructureCount.java | 9 +- src/jalview/datamodel/SequenceGroup.java | 32 +- src/jalview/gui/AlignFrame.java | 216 +++-- src/jalview/gui/AlignViewport.java | 6 +- src/jalview/gui/AppJmol.java | 18 +- src/jalview/gui/CalculationChooser.java | 11 +- src/jalview/gui/CutAndPasteTransfer.java | 12 +- src/jalview/gui/Desktop.java | 4 +- src/jalview/gui/FontChooser.java | 6 +- src/jalview/gui/PaSiMapPanel.java | 80 +- src/jalview/gui/PairwiseAlignPanel.java | 73 +- src/jalview/gui/PopupMenu.java | 36 +- src/jalview/gui/ProgressBar.java | 2 +- src/jalview/gui/RotatableCanvas.java | 50 +- src/jalview/gui/StructureChooser.java | 14 +- .../ThreeDBStructureChooserQuerySource.java | 5 +- src/jalview/jbgui/GAlignFrame.java | 32 +- src/jalview/jbgui/GCutAndPasteTransfer.java | 3 +- src/jalview/jbgui/GPCAPanel.java | 1 + src/jalview/jbgui/GPaSiMapPanel.java | 5 +- src/jalview/jbgui/GPreferences.java | 2 +- src/jalview/math/Matrix.java | 250 ++--- src/jalview/math/MatrixI.java | 173 ++-- src/jalview/math/MiscMath.java | 275 +++--- src/jalview/project/Jalview2XML.java | 19 +- src/jalview/renderer/AnnotationRenderer.java | 25 +- src/jalview/renderer/ResidueShader.java | 17 +- src/jalview/renderer/ResidueShaderI.java | 2 +- src/jalview/schemes/ClustalxColourScheme.java | 60 +- src/jalview/schemes/ResidueProperties.java | 18 +- src/jalview/util/Constants.java | 27 +- src/jalview/viewmodel/AlignmentViewport.java | 53 +- src/jalview/viewmodel/PaSiMapModel.java | 32 +- .../workers/SecondaryStructureConsensusThread.java | 7 +- test/jalview/analysis/AlignSeqTest.java | 16 +- test/jalview/analysis/AlignmentUtilsTests.java | 333 ++++--- .../analysis/scoremodels/ScoreModelsTest.java | 2 +- .../SecondaryStructureDistanceModelTest.java | 266 ++--- test/jalview/commands/EditCommandTest.java | 49 +- test/jalview/gui/AssociatePDBFileTest.java | 25 +- test/jalview/gui/CalculationChooserTest.java | 42 +- test/jalview/project/Jalview2xmlTests.java | 10 +- test/jalview/renderer/ResidueShaderTest.java | 2 +- test/jalview/schemes/ClustalxColourSchemeTest.java | 1 + test/jalview/util/FileUtilsTest.java | 1 + 69 files changed, 2504 insertions(+), 2012 deletions(-) diff --git a/src/jalview/analysis/AAFrequency.java b/src/jalview/analysis/AAFrequency.java index 707110a..0fa80b3 100755 --- a/src/jalview/analysis/AAFrequency.java +++ b/src/jalview/analysis/AAFrequency.java @@ -194,13 +194,12 @@ public class AAFrequency // jalview.bin.Console.outPrintln(elapsed); } - public static final ProfilesI calculateSS(List list, int start, int end) { return calculateSS(list, start, end, false); } - + public static final ProfilesI calculateSS(List sequences, int start, int end, boolean profile) { @@ -227,20 +226,20 @@ public class AAFrequency return reply; } } - + public static final ProfilesI calculateSS(final SequenceI[] sequences, int width, int start, int end, boolean saveFullProfile) { int seqCount = sequences.length; - + ProfileI[] result = new ProfileI[width]; for (int column = start; column < end; column++) { - + int ssCount = 0; - + SecondaryStructureCount ssCounts = new SecondaryStructureCount(); for (int row = 0; row < seqCount; row++) @@ -251,26 +250,31 @@ public class AAFrequency "WARNING: Consensus skipping null sequence - possible race condition."); continue; } - + char c = sequences[row].getCharAt(column); - AlignmentAnnotation aa = AlignmentUtils.getDisplayedAlignmentAnnotation(sequences[row]); - if(aa!=null) { + AlignmentAnnotation aa = AlignmentUtils + .getDisplayedAlignmentAnnotation(sequences[row]); + if (aa != null) + { ssCount++; } - - if (sequences[row].getLength() > column && !Comparison.isGap(c) && aa !=null) + + if (sequences[row].getLength() > column && !Comparison.isGap(c) + && aa != null) { - + int seqPosition = sequences[row].findPosition(column); - - char ss = AlignmentUtils.findSSAnnotationForGivenSeqposition( - aa, seqPosition); - if(ss == '*') { + + char ss = AlignmentUtils.findSSAnnotationForGivenSeqposition(aa, + seqPosition); + if (ss == '*') + { continue; - } - ssCounts.add(ss); + } + ssCounts.add(ss); } - else if(Comparison.isGap(c) && aa!=null) { + else if (Comparison.isGap(c) && aa != null) + { ssCounts.addGap(); } } @@ -278,8 +282,7 @@ public class AAFrequency int maxSSCount = ssCounts.getModalCount(); String maxSS = ssCounts.getSSForCount(maxSSCount); int gapCount = ssCounts.getGapCount(); - ProfileI profile = new Profile(maxSS, ssCount, gapCount, - maxSSCount); + ProfileI profile = new Profile(maxSS, ssCount, gapCount, maxSSCount); if (saveFullProfile) { @@ -387,58 +390,57 @@ public class AAFrequency // long elapsed = System.currentTimeMillis() - now; // jalview.bin.Console.outPrintln(-elapsed); } - - - public static void completeSSConsensus(AlignmentAnnotation ssConsensus, - ProfilesI profiles, int startCol, int endCol, boolean ignoreGaps, - boolean showSequenceLogo, long nseq) - { - // long now = System.currentTimeMillis(); - if (ssConsensus == null || ssConsensus.annotations == null - || ssConsensus.annotations.length < endCol) - { - /* + + public static void completeSSConsensus(AlignmentAnnotation ssConsensus, + ProfilesI profiles, int startCol, int endCol, boolean ignoreGaps, + boolean showSequenceLogo, long nseq) + { + // long now = System.currentTimeMillis(); + if (ssConsensus == null || ssConsensus.annotations == null + || ssConsensus.annotations.length < endCol) + { + /* * called with a bad alignment annotation row * wait for it to be initialised properly */ - return; - } - - for (int i = startCol; i < endCol; i++) - { - ProfileI profile = profiles.get(i); - if (profile == null) - { - /* + return; + } + + for (int i = startCol; i < endCol; i++) + { + ProfileI profile = profiles.get(i); + if (profile == null) + { + /* * happens if sequences calculated over were * shorter than alignment width */ - ssConsensus.annotations[i] = null; - return; - } - - final int dp = getPercentageDp(nseq); - - float value = profile.getSSPercentageIdentity(ignoreGaps); - - String description = getSSTooltip(profile, value, showSequenceLogo, - ignoreGaps, dp); - - String modalSS = profile.getModalSS(); - if ("".equals(modalSS)) - { - modalSS = "-"; - } - else if (modalSS.length() > 1) - { - modalSS = "+"; - } - ssConsensus.annotations[i] = new Annotation(modalSS, description, - ' ', value); - } - // long elapsed = System.currentTimeMillis() - now; - // jalview.bin.Console.outPrintln(-elapsed); - } + ssConsensus.annotations[i] = null; + return; + } + + final int dp = getPercentageDp(nseq); + + float value = profile.getSSPercentageIdentity(ignoreGaps); + + String description = getSSTooltip(profile, value, showSequenceLogo, + ignoreGaps, dp); + + String modalSS = profile.getModalSS(); + if ("".equals(modalSS)) + { + modalSS = "-"; + } + else if (modalSS.length() > 1) + { + modalSS = "+"; + } + ssConsensus.annotations[i] = new Annotation(modalSS, description, ' ', + value); + } + // long elapsed = System.currentTimeMillis() - now; + // jalview.bin.Console.outPrintln(-elapsed); + } /** * Derive the gap count annotation row. @@ -544,7 +546,7 @@ public class AAFrequency } return description; } - + static String getSSTooltip(ProfileI profile, float pid, boolean showSequenceLogo, boolean ignoreGaps, int dp) { @@ -600,27 +602,28 @@ public class AAFrequency { char[] symbols; int[] values; - + if (profile.getCounts() != null) { ResidueCount counts = profile.getCounts(); SymbolCounts symbolCounts = counts.getSymbolCounts(); symbols = symbolCounts.symbols; values = symbolCounts.values; - + } - else if(profile.getSSCounts() != null) + else if (profile.getSSCounts() != null) { SecondaryStructureCount counts = profile.getSSCounts(); // to do - SecondaryStructureCount.SymbolCounts symbolCounts = counts.getSymbolCounts(); + SecondaryStructureCount.SymbolCounts symbolCounts = counts + .getSymbolCounts(); symbols = symbolCounts.symbols; values = symbolCounts.values; } - else { + else + { return null; } - QuickSort.sort(values, symbols); int totalPercentage = 0; diff --git a/src/jalview/analysis/AlignSeq.java b/src/jalview/analysis/AlignSeq.java index e806d2b..1a12681 100755 --- a/src/jalview/analysis/AlignSeq.java +++ b/src/jalview/analysis/AlignSeq.java @@ -58,10 +58,10 @@ public class AlignSeq private static final int DEFAULT_OPENCOST = 120; private static final int DEFAULT_EXTENDCOST = 20; - - private int GAP_OPEN_COST=DEFAULT_OPENCOST; - private int GAP_EXTEND_COST=DEFAULT_EXTENDCOST; + private int GAP_OPEN_COST = DEFAULT_OPENCOST; + + private int GAP_EXTEND_COST = DEFAULT_EXTENDCOST; private static final int GAP_INDEX = -1; @@ -100,11 +100,11 @@ public class AlignSeq int[] aseq1; int[] aseq2; - + /* * matches in alignment */ - int match=-1; + int match = -1; public String astr1 = ""; @@ -129,9 +129,9 @@ public class AlignSeq public float maxscore; - public float meanScore; //needed for PaSiMap + public float meanScore; // needed for PaSiMap - public int hypotheticMaxScore; // needed for PaSiMap + public int hypotheticMaxScore; // needed for PaSiMap int prev = 0; @@ -156,6 +156,7 @@ public class AlignSeq GAP_OPEN_COST = opencost; GAP_EXTEND_COST = extcost; } + public AlignSeq(SequenceI s1, SequenceI s2, String type) { seqInit(s1, s1.getSequenceAsString(), s2, s2.getSequenceAsString(), @@ -182,18 +183,18 @@ public class AlignSeq public AlignSeq(SequenceI s1, SequenceI s2, String type, int opencost, int extcost) { - this(s1,s2,type); - GAP_OPEN_COST=opencost; - GAP_EXTEND_COST=extcost; + this(s1, s2, type); + GAP_OPEN_COST = opencost; + GAP_EXTEND_COST = extcost; } public AlignSeq(SequenceI s12, String string1, SequenceI s22, String string2, String type2, int defaultOpencost, int defaultExtendcost) { - this(s12,string1,s22,string2,type2); - GAP_OPEN_COST=defaultOpencost; - GAP_EXTEND_COST=defaultExtendcost; + this(s12, string1, s22, string2, type2); + GAP_OPEN_COST = defaultOpencost; + GAP_EXTEND_COST = defaultExtendcost; } /** @@ -207,10 +208,10 @@ public class AlignSeq } /** - * returns the overall score of the alignment - * - * @return - */ + * returns the overall score of the alignment + * + * @return + */ public float getAlignmentScore() { return alignmentScore; @@ -333,27 +334,31 @@ public class AlignSeq s2.getDatasetSequence() == null ? s2 : s2.getDatasetSequence()); return alSeq2; } + /** * fraction of seq2 matched in the alignment + * * @return NaN or [0..1] */ public double getS2Coverage() { - if (match>=0) + if (match >= 0) { - return ((double)match)/((double)s2.getEnd()-s2.getStart()+1); + return ((double) match) / ((double) s2.getEnd() - s2.getStart() + 1); } return Double.NaN; } + /** * fraction of seq1 matched in the alignment + * * @return NaN or [0..1] */ public double getS1Coverage() { - if (match>=0) + if (match >= 0) { - return ((double)match)/((double)s1.getEnd()-s1.getStart()+1); + return ((double) match) / ((double) s1.getEnd() - s1.getStart() + 1); } return Double.NaN; } @@ -375,13 +380,14 @@ public class AlignSeq public void seqInit(SequenceI s1, String string1, SequenceI s2, String string2, String type) { - seqInit(s1,string1,s2,string2,type,GAP_OPEN_COST,GAP_EXTEND_COST); + seqInit(s1, string1, s2, string2, type, GAP_OPEN_COST, GAP_EXTEND_COST); } + public void seqInit(SequenceI s1, String string1, SequenceI s2, - String string2, String type, int opening,int extension) + String string2, String type, int opening, int extension) { - GAP_OPEN_COST=opening; - GAP_EXTEND_COST=extension; + GAP_OPEN_COST = opening; + GAP_EXTEND_COST = extension; this.s1 = s1; this.s2 = s2; setDefaultParams(type); @@ -473,13 +479,12 @@ public class AlignSeq aseq1 = new int[seq1.length + seq2.length]; aseq2 = new int[seq1.length + seq2.length]; - match=0; + match = 0; StringBuilder sb1 = new StringBuilder(aseq1.length); StringBuilder sb2 = new StringBuilder(aseq2.length); count = (seq1.length + seq2.length) - 1; - while (i > 0 && j > 0) { aseq1[count] = seq1[i]; @@ -523,12 +528,12 @@ public class AlignSeq { aseq2[count] = seq2[j]; sb2.append(s2str.charAt(j)); - if (aseq1[count]!=GAP_INDEX) { + if (aseq1[count] != GAP_INDEX) + { match++; } } - /* * we built the character strings backwards, so now * reverse them to convert to sequence strings @@ -570,7 +575,7 @@ public class AlignSeq int trace; maxscore = score[i][j] / 10f; - //prepare trailing gaps + // prepare trailing gaps while ((i < seq1.length - 1) || (j < seq2.length - 1)) { i++; @@ -587,20 +592,22 @@ public class AlignSeq count = (seq1.length + seq2.length) - 1; - //get trailing gaps + // get trailing gaps while ((i >= seq1.length) || (j >= seq2.length)) { if (i >= seq1.length) { - aseq1[count] = GAP_INDEX; - sb1.append("-"); - aseq2[count] = seq2[j]; - sb2.append(s2str.charAt(j)); - } else if (j >= seq2.length) { - aseq1[count] = seq1[i]; - sb1.append(s1str.charAt(i)); - aseq2[count] = GAP_INDEX; - sb2.append("-"); + aseq1[count] = GAP_INDEX; + sb1.append("-"); + aseq2[count] = seq2[j]; + sb2.append(s2str.charAt(j)); + } + else if (j >= seq2.length) + { + aseq1[count] = seq1[i]; + sb1.append(s1str.charAt(i)); + aseq2[count] = GAP_INDEX; + sb2.append("-"); } i--; j--; @@ -644,18 +651,20 @@ public class AlignSeq aseq2[count] = seq2[j]; sb2.append(s2str.charAt(j)); - //get initial gaps + // get initial gaps while (j > 0 || i > 0) { if (j > 0) { - j--; - sb1.append("-"); - sb2.append(s2str.charAt(j)); - } else if (i > 0) { - i--; - sb1.append(s1str.charAt(i)); - sb2.append("-"); + j--; + sb1.append("-"); + sb2.append(s2str.charAt(j)); + } + else if (i > 0) + { + i--; + sb1.append(s1str.charAt(i)); + sb2.append("-"); } } @@ -853,7 +862,7 @@ public class AlignSeq { int n = seq1.length; int m = seq2.length; - final int GAP_EX_COST=GAP_EXTEND_COST; + final int GAP_EX_COST = GAP_EXTEND_COST; final int GAP_OP_COST = GAP_OPEN_COST; // top left hand element score[0][0] = scoreMatrix.getPairwiseScore(s1str.charAt(0), @@ -871,8 +880,7 @@ public class AlignSeq float pairwiseScore = scoreMatrix.getPairwiseScore(s1str.charAt(0), s2str.charAt(j)); - score[0][j] = max(pairwiseScore * 10, -GAP_OP_COST, - -GAP_EX_COST); + score[0][j] = max(pairwiseScore * 10, -GAP_OP_COST, -GAP_EX_COST); traceback[0][j] = 1; } @@ -1076,13 +1084,15 @@ public class AlignSeq public static AlignSeq doGlobalNWAlignment(SequenceI s1, SequenceI s2, String type) { - return doGlobalNWAlignment(s1, s2, type, DEFAULT_OPENCOST,DEFAULT_EXTENDCOST); + return doGlobalNWAlignment(s1, s2, type, DEFAULT_OPENCOST, + DEFAULT_EXTENDCOST); } + public static AlignSeq doGlobalNWAlignment(SequenceI s1, SequenceI s2, - String type, int opencost,int extcost) + String type, int opencost, int extcost) { - - AlignSeq as = new AlignSeq(s1, s2, type,opencost,extcost); + + AlignSeq as = new AlignSeq(s1, s2, type, opencost, extcost); as.calcScoreMatrix(); as.traceAlignment(); @@ -1359,42 +1369,45 @@ public class AlignSeq } /** - * calculate the mean score of the alignment - * mean score is equal to the score of an alignmenet of two sequences with randomly shuffled AA sequence composited of the same AA as the two original sequences - * - */ + * calculate the mean score of the alignment mean score is equal to the score + * of an alignmenet of two sequences with randomly shuffled AA sequence + * composited of the same AA as the two original sequences + * + */ public void meanScore() { - int length = indelfreeAstr1.length(); //both have the same length - //create HashMap for counting residues in each sequence + int length = indelfreeAstr1.length(); // both have the same length + // create HashMap for counting residues in each sequence HashMap seq1ResCount = new HashMap(); HashMap seq2ResCount = new HashMap(); - // for both sequences (String indelfreeAstr1 or 2) create a key for the residue and add 1 each time its encountered - for (char residue: indelfreeAstr1.toCharArray()) + // for both sequences (String indelfreeAstr1 or 2) create a key for the + // residue and add 1 each time its encountered + for (char residue : indelfreeAstr1.toCharArray()) { seq1ResCount.putIfAbsent(residue, 0); seq1ResCount.replace(residue, seq1ResCount.get(residue) + 1); } - for (char residue: indelfreeAstr2.toCharArray()) + for (char residue : indelfreeAstr2.toCharArray()) { seq2ResCount.putIfAbsent(residue, 0); seq2ResCount.replace(residue, seq2ResCount.get(residue) + 1); } - // meanscore = for each residue pair get the number of appearance and add (countA * countB * pairwiseScore(AB)) + // meanscore = for each residue pair get the number of appearance and add + // (countA * countB * pairwiseScore(AB)) // divide the meanscore by the sequence length afterwards float _meanscore = 0; for (char resA : seq1ResCount.keySet()) { for (char resB : seq2ResCount.keySet()) { - int countA = seq1ResCount.get(resA); - int countB = seq2ResCount.get(resB); + int countA = seq1ResCount.get(resA); + int countB = seq2ResCount.get(resB); float scoreAB = scoreMatrix.getPairwiseScore(resA, resB); - _meanscore += countA * countB * scoreAB; + _meanscore += countA * countB * scoreAB; } } _meanscore /= length; @@ -1407,21 +1420,23 @@ public class AlignSeq } /** - * calculate the hypothetic max score using the self-alignment of the sequences - */ + * calculate the hypothetic max score using the self-alignment of the + * sequences + */ public void hypotheticMaxScore() { int _hmsA = 0; int _hmsB = 0; - for (char residue: indelfreeAstr1.toCharArray()) + for (char residue : indelfreeAstr1.toCharArray()) { _hmsA += scoreMatrix.getPairwiseScore(residue, residue); } - for (char residue: indelfreeAstr2.toCharArray()) + for (char residue : indelfreeAstr2.toCharArray()) { _hmsB += scoreMatrix.getPairwiseScore(residue, residue); } - this.hypotheticMaxScore = (_hmsA < _hmsB) ? _hmsA : _hmsB; // take the lower self alignment + this.hypotheticMaxScore = (_hmsA < _hmsB) ? _hmsA : _hmsB; // take the lower + // self alignment } @@ -1431,27 +1446,30 @@ public class AlignSeq } /** - * create strings based of astr1 and astr2 but without gaps - */ + * create strings based of astr1 and astr2 but without gaps + */ public void getIndelfreeAstr() { - int n = astr1.length(); // both have the same length + int n = astr1.length(); // both have the same length for (int i = 0; i < n; i++) { - if (Character.isLetter(astr1.charAt(i)) && Character.isLetter(astr2.charAt(i))) // if both sequences dont have a gap -> add to indelfreeAstr + if (Character.isLetter(astr1.charAt(i)) + && Character.isLetter(astr2.charAt(i))) // if both sequences dont + // have a gap -> add to + // indelfreeAstr { - this.indelfreeAstr1 += astr1.charAt(i); - this.indelfreeAstr2 += astr2.charAt(i); + this.indelfreeAstr1 += astr1.charAt(i); + this.indelfreeAstr2 += astr2.charAt(i); } } } /** - * calculates the overall score of the alignment - * preprescore = sum of all scores - all penalties - * if preprescore < 1 ~ alignmentScore = Float.NaN > - * alignmentScore = ((preprescore - meanScore) / (hypotheticMaxScore - meanScore)) * coverage - */ + * calculates the overall score of the alignment preprescore = sum of all + * scores - all penalties if preprescore < 1 ~ alignmentScore = Float.NaN > + * alignmentScore = ((preprescore - meanScore) / (hypotheticMaxScore - + * meanScore)) * coverage + */ public void scoreAlignment() { @@ -1475,36 +1493,51 @@ public class AlignSeq char char2 = indelfreeAstr2.charAt(i); boolean aIsLetter = Character.isLetter(char1); boolean bIsLetter = Character.isLetter(char2); - if (aIsLetter && bIsLetter) // if pair -> get score + if (aIsLetter && bIsLetter) // if pair -> get score { score += scoreMatrix.getPairwiseScore(char1, char2); - } else if (!aIsLetter && !bIsLetter) { // both are gap -> skip - } else if ((!aIsLetter && aGapOpen) || (!bIsLetter && bGapOpen)) { // one side gapopen -> score - gap_extend - score -= GAP_EXTEND_COST; - } else { // no gap open -> score - gap_open - score -= GAP_OPEN_COST; + } + else if (!aIsLetter && !bIsLetter) + { // both are gap -> skip + } + else if ((!aIsLetter && aGapOpen) || (!bIsLetter && bGapOpen)) + { // one side gapopen -> score - gap_extend + score -= GAP_EXTEND_COST; + } + else + { // no gap open -> score - gap_open + score -= GAP_OPEN_COST; } // adjust GapOpen status in both sequences aGapOpen = (!aIsLetter) ? true : false; bGapOpen = (!bIsLetter) ? true : false; } - float preprescore = score; // if this score < 1 --> alignment score = Float.NaN - score = (score - this.meanScore) / (this.hypotheticMaxScore - this.meanScore); - int[] _max = MiscMath.findMax(new int[]{astr1.replace("-","").length(), astr2.replace("-","").length()}); // {index of max, max} - float coverage = (float) n / (float) _max[1]; // indelfreeAstr length / longest sequence length - float prescore = score; // only debug + float preprescore = score; // if this score < 1 --> alignment score = + // Float.NaN + score = (score - this.meanScore) + / (this.hypotheticMaxScore - this.meanScore); + int[] _max = MiscMath + .findMax(new int[] + { astr1.replace("-", "").length(), + astr2.replace("-", "").length() }); // {index of max, max} + float coverage = (float) n / (float) _max[1]; // indelfreeAstr length / + // longest sequence length + float prescore = score; // only debug score *= coverage; - //System.out.println(String.format("prepre-score: %f, pre-score: %f, longlength: %d\nscore: %1.16f, mean: %f, max: %d", preprescore, prescore, _max[1], score, this.meanScore, this.hypotheticMaxScore)); + // System.out.println(String.format("prepre-score: %f, pre-score: %f, + // longlength: %d\nscore: %1.16f, mean: %f, max: %d", preprescore, prescore, + // _max[1], score, this.meanScore, this.hypotheticMaxScore)); float minScore = 0f; this.alignmentScore = (score <= minScore) ? Float.NaN : score; } public void setScoreMatrix(ScoreMatrix sm) { - if (sm != null) { - scoreMatrix = sm; - } + if (sm != null) + { + scoreMatrix = sm; + } } } diff --git a/src/jalview/analysis/AlignmentUtils.java b/src/jalview/analysis/AlignmentUtils.java index 7d0ccdb..ba74f67 100644 --- a/src/jalview/analysis/AlignmentUtils.java +++ b/src/jalview/analysis/AlignmentUtils.java @@ -83,7 +83,7 @@ public class AlignmentUtils { private static final int CODON_LENGTH = 3; - private static final String SEQUENCE_VARIANT = "sequence_variant:"; + private static final String SEQUENCE_VARIANT = "sequence_variant:"; /* * the 'id' attribute is provided for variant features fetched from @@ -1541,13 +1541,15 @@ public class AlignmentUtils } } } - - - public static boolean isSSAnnotationPresent( Map> annotations) { - + + public static boolean isSSAnnotationPresent( + Map> annotations) + { + for (SequenceI seq : annotations.keySet()) { - if(isSecondaryStructurePresent(annotations.get(seq).toArray(new AlignmentAnnotation[0]))) + if (isSecondaryStructurePresent( + annotations.get(seq).toArray(new AlignmentAnnotation[0]))) { return true; } @@ -2852,195 +2854,234 @@ public class AlignmentUtils } return true; } - - - public static List getSecondaryStructureSources(AlignmentAnnotation[] annotations) { - - List ssSources = new ArrayList<>(); - Set addedLabels = new HashSet<>(); // to keep track of added labels - - for (AlignmentAnnotation annotation : annotations) { - String label = annotation.label; - if (Constants.SECONDARY_STRUCTURE_LABELS.containsKey(label) && !addedLabels.contains(label)) { - ssSources.add(Constants.SECONDARY_STRUCTURE_LABELS.get(label)); - addedLabels.add(label); // Add the label to the set - } + + public static List getSecondaryStructureSources( + AlignmentAnnotation[] annotations) + { + + List ssSources = new ArrayList<>(); + Set addedLabels = new HashSet<>(); // to keep track of added labels + + for (AlignmentAnnotation annotation : annotations) + { + String label = annotation.label; + if (Constants.SECONDARY_STRUCTURE_LABELS.containsKey(label) + && !addedLabels.contains(label)) + { + ssSources.add(Constants.SECONDARY_STRUCTURE_LABELS.get(label)); + addedLabels.add(label); // Add the label to the set } + } - return ssSources; + return ssSources; } - - public static boolean isSecondaryStructurePresent(AlignmentAnnotation[] annotations) + + public static boolean isSecondaryStructurePresent( + AlignmentAnnotation[] annotations) { boolean ssPresent = false; - + for (AlignmentAnnotation aa : annotations) { - if(ssPresent) { + if (ssPresent) + { break; - } + } - if (Constants.SECONDARY_STRUCTURE_LABELS.containsKey(aa.label)) { - ssPresent = true; - break; + if (Constants.SECONDARY_STRUCTURE_LABELS.containsKey(aa.label)) + { + ssPresent = true; + break; } } - + return ssPresent; - + } - - public static Color getSecondaryStructureAnnotationColour(char symbol){ - - if (symbol== Constants.COIL) { + + public static Color getSecondaryStructureAnnotationColour(char symbol) + { + + if (symbol == Constants.COIL) + { return Color.gray; } - if (symbol== Constants.SHEET) { + if (symbol == Constants.SHEET) + { return Color.green; } - if (symbol== Constants.HELIX) { + if (symbol == Constants.HELIX) + { return Color.red; } - + return Color.gray; } - public static char findSSAnnotationForGivenSeqposition(AlignmentAnnotation aa, - int seqPosition) + public static char findSSAnnotationForGivenSeqposition( + AlignmentAnnotation aa, int seqPosition) { - char ss = '*'; - - if (aa != null) { - if (aa.getAnnotationForPosition(seqPosition) != null) { + char ss = '*'; + + if (aa != null) + { + if (aa.getAnnotationForPosition(seqPosition) != null) + { Annotation a = aa.getAnnotationForPosition(seqPosition); ss = a.secondaryStructure; - - //There is no representation for coil and it can be either ' ' or null. - if (ss == ' ' || ss == '-') { - ss = Constants.COIL; + + // There is no representation for coil and it can be either ' ' or null. + if (ss == ' ' || ss == '-') + { + ss = Constants.COIL; } } - else { + else + { ss = Constants.COIL; - } + } } - - return ss; + + return ss; } - - - public static List extractSSSourceInAlignmentAnnotation(AlignmentAnnotation[] annotations) { - + + public static List extractSSSourceInAlignmentAnnotation( + AlignmentAnnotation[] annotations) + { + List ssSources = new ArrayList<>(); - Set addedSources = new HashSet<>(); // to keep track of added sources + Set addedSources = new HashSet<>(); // to keep track of added + // sources + + for (AlignmentAnnotation aa : annotations) + { - - for (AlignmentAnnotation aa: annotations) { - String ssSource = extractSSSourceFromAnnotationDescription(aa); - - if (ssSource!= null && !addedSources.contains(ssSource)) { - ssSources.add(ssSource); - addedSources.add(ssSource); + + if (ssSource != null && !addedSources.contains(ssSource)) + { + ssSources.add(ssSource); + addedSources.add(ssSource); } - - } + + } Collections.sort(ssSources); - + return ssSources; - + } - - public static String extractSSSourceFromAnnotationDescription(AlignmentAnnotation aa) { - - - for (String label : Constants.SECONDARY_STRUCTURE_LABELS.keySet()) { - - if (label.equals(aa.label)) { - - //For JPred - if(aa.label.equals(Constants.SS_ANNOTATION_FROM_JPRED_LABEL)){ - + + public static String extractSSSourceFromAnnotationDescription( + AlignmentAnnotation aa) + { + + for (String label : Constants.SECONDARY_STRUCTURE_LABELS.keySet()) + { + + if (label.equals(aa.label)) + { + + // For JPred + if (aa.label.equals(Constants.SS_ANNOTATION_FROM_JPRED_LABEL)) + { + return (Constants.SECONDARY_STRUCTURE_LABELS.get(aa.label)); - - } - - //For input with secondary structure - if(aa.label.equals(Constants.SS_ANNOTATION_LABEL) - && aa.description.equals(Constants.SS_ANNOTATION_LABEL)){ - + + } + + // For input with secondary structure + if (aa.label.equals(Constants.SS_ANNOTATION_LABEL) + && aa.description.equals(Constants.SS_ANNOTATION_LABEL)) + { + return (Constants.SECONDARY_STRUCTURE_LABELS.get(aa.label)); - - } - - //For other sources - if(aa.sequenceRef==null) { + + } + + // For other sources + if (aa.sequenceRef == null) + { return null; } - else if(aa.sequenceRef.getDatasetSequence()==null) { + else if (aa.sequenceRef.getDatasetSequence() == null) + { return null; } - Vector pdbEntries = aa.sequenceRef.getDatasetSequence().getAllPDBEntries(); - - for (PDBEntry entry : pdbEntries){ - - String entryProvider = entry.getProvider(); - if(entryProvider == null) { - entryProvider = "PDB"; - } - - // Trim the string from first occurrence of colon - String entryID = entry.getId(); - int index = entryID.indexOf(':'); - - // Check if colon exists - if (index != -1) { - - // Trim the string from first occurrence of colon - entryID = entryID.substring(0, index); - - } - - if(entryProvider == "PDB" && aa.description.toLowerCase().contains - ("secondary structure for " + entryID.toLowerCase())){ - - return entryProvider; - - } - - else if (entryProvider != "PDB" && aa.description.toLowerCase().contains(entryID.toLowerCase())){ - - return entryProvider; - - } - + Vector pdbEntries = aa.sequenceRef.getDatasetSequence() + .getAllPDBEntries(); + + for (PDBEntry entry : pdbEntries) + { + + String entryProvider = entry.getProvider(); + if (entryProvider == null) + { + entryProvider = "PDB"; + } + + // Trim the string from first occurrence of colon + String entryID = entry.getId(); + int index = entryID.indexOf(':'); + + // Check if colon exists + if (index != -1) + { + + // Trim the string from first occurrence of colon + entryID = entryID.substring(0, index); + + } + + if (entryProvider == "PDB" && aa.description.toLowerCase() + .contains("secondary structure for " + + entryID.toLowerCase())) + { + + return entryProvider; + + } + + else if (entryProvider != "PDB" && aa.description.toLowerCase() + .contains(entryID.toLowerCase())) + { + + return entryProvider; + } - - } + + } + } - + } + return null; - + } - - //to do set priority for labels - public static AlignmentAnnotation getDisplayedAlignmentAnnotation(SequenceI seq){ - - for(String ssLabel : Constants.SECONDARY_STRUCTURE_LABELS.keySet()) { - - AlignmentAnnotation[] aa = seq.getAnnotation(ssLabel); - if(aa!=null) { - - for (AlignmentAnnotation annot: aa) { - if(annot.visible) { - return annot; + + // to do set priority for labels + public static AlignmentAnnotation getDisplayedAlignmentAnnotation( + SequenceI seq) + { + + for (String ssLabel : Constants.SECONDARY_STRUCTURE_LABELS.keySet()) + { + + AlignmentAnnotation[] aa = seq.getAnnotation(ssLabel); + if (aa != null) + { + + for (AlignmentAnnotation annot : aa) + { + if (annot.visible) + { + return annot; + } } } - } } - + return null; - + } - + } diff --git a/src/jalview/analysis/ConnectivityException.java b/src/jalview/analysis/ConnectivityException.java index 9915f2a..5f371c8 100644 --- a/src/jalview/analysis/ConnectivityException.java +++ b/src/jalview/analysis/ConnectivityException.java @@ -23,7 +23,9 @@ package jalview.analysis; public class ConnectivityException extends RuntimeException { private String sequence; + private int connection; + private byte dim; public ConnectivityException(String sequence, int connection, byte dim) @@ -31,9 +33,11 @@ public class ConnectivityException extends RuntimeException this("Insufficient number of connections", sequence, connection, dim); } - public ConnectivityException(String message, String sequence, int connection, byte dim) + public ConnectivityException(String message, String sequence, + int connection, byte dim) { - super(String.format("%s for %s (%d, should be %d or more)", message, sequence, connection, dim)); + super(String.format("%s for %s (%d, should be %d or more)", message, + sequence, connection, dim)); this.sequence = sequence; this.connection = connection; this.dim = dim; diff --git a/src/jalview/analysis/Finder.java b/src/jalview/analysis/Finder.java index c84c69a..32d4cf3 100644 --- a/src/jalview/analysis/Finder.java +++ b/src/jalview/analysis/Finder.java @@ -606,7 +606,7 @@ public class Finder implements FinderI } else { - //allFeatures = sf.getAllFeatures(null); + // allFeatures = sf.getAllFeatures(null); allFeatures = sf.getAllFeatures(); } // so we can check we are advancing when debugging diff --git a/src/jalview/analysis/PaSiMap.java b/src/jalview/analysis/PaSiMap.java index 48ec899..5be8c7b 100755 --- a/src/jalview/analysis/PaSiMap.java +++ b/src/jalview/analysis/PaSiMap.java @@ -38,7 +38,8 @@ import java.util.Hashtable; /** * Performs Principal Component Analysis on given sequences - * @AUTHOR MorellThomas + * + * @AUTHOR MorellThomas */ public class PaSiMap implements Runnable { @@ -72,14 +73,17 @@ public class PaSiMap implements Runnable * @param sm * @param options */ - public PaSiMap(AlignmentViewport sequences, ScoreModelI sm, PairwiseAlignPanel pap) + public PaSiMap(AlignmentViewport sequences, ScoreModelI sm, + PairwiseAlignPanel pap) { this.seqs = sequences; - if (sm!=null && sm instanceof ScoreMatrix) + if (sm != null && sm instanceof ScoreMatrix) { this.scoreMatrix = ((ScoreMatrix) sm); - } else { + } + else + { this.scoreMatrix = null; } @@ -108,7 +112,8 @@ public class PaSiMap implements Runnable * DOCUMENT ME! * @param mm * DOCUMENT ME! - * @param factor ~ is 1 + * @param factor + * ~ is 1 * * @return DOCUMENT ME! */ @@ -164,8 +169,8 @@ public class PaSiMap implements Runnable } /** - * Answers a formatted text report of the PaSiMap calculation results (matrices - * and eigenvalues) suitable for display + * Answers a formatted text report of the PaSiMap calculation results + * (matrices and eigenvalues) suitable for display * * @return */ @@ -197,13 +202,25 @@ public class PaSiMap implements Runnable /** * Performs the PaSiMap calculation * - * creates a new gui/PairwiseAlignPanel with the input sequences (AlignmentViewport) - * uses analysis/AlignSeq to creatue the pairwise alignments and calculate the AlignmentScores (float for each pair) + * creates a new gui/PairwiseAlignPanel with the input sequences + * (AlignmentViewport) + * + * uses analysis/AlignSeq to creatue the pairwise alignments and calculate the + * AlignmentScores (float for each pair) + * * gets all float[][] scores from the gui/PairwiseAlignPanel - * checks the connections for each sequence with AlignmentViewport seqs.calculateConnectivity(float[][] scores, int dim) (from analysis/Connectivity) -- throws an Exception if insufficient + * + * checks the connections for each sequence with AlignmentViewport + * seqs.calculateConnectivity(float[][] scores, int dim) (from + * analysis/Connectivity) -- throws an Exception if insufficient + * * creates a math/MatrixI pairwiseScores of the float[][] scores - * copys the scores and fills the diagonal to create a symmetric matrix using math/Matrix.fillDiagonal() + * + * copys the scores and fills the diagonal to create a symmetric matrix using + * math/Matrix.fillDiagonal() + * * performs the analysis/ccAnalysis with the symmetric matrix + * * gets the eigenmatrix and the eigenvalues using math/Matrix.tqli() */ @Override @@ -211,9 +228,10 @@ public class PaSiMap implements Runnable { try { - //alignment = new PairwiseAlignPanel(seqs, true, 100, 5); + // alignment = new PairwiseAlignPanel(seqs, true, 100, 5); alignment.calculate(scoreMatrix); - float[][] scores = alignment.getAlignmentScores(); //bigger index first -- eg scores[14][13] + float[][] scores = alignment.getAlignmentScores(); // bigger index first + // -- eg scores[14][13] SequenceI[] iseqs = alignment.getInputSequences(); Connectivity.getConnectivity(iseqs, scores, dim); diff --git a/src/jalview/analysis/ccAnalysis.java b/src/jalview/analysis/ccAnalysis.java index b8ed4e2..62e1913 100755 --- a/src/jalview/analysis/ccAnalysis.java +++ b/src/jalview/analysis/ccAnalysis.java @@ -55,11 +55,11 @@ import org.apache.commons.math3.linear.SingularValueDecomposition; /** * A class to model rectangular matrices of double values and operations on them */ -public class ccAnalysis +public class ccAnalysis { - private byte dim = 0; //dimensions + private byte dim = 0; // dimensions - private MatrixI scoresOld; //input scores + private MatrixI scoresOld; // input scores public ccAnalysis(MatrixI scores, byte dim) { @@ -68,29 +68,33 @@ public class ccAnalysis { for (int j = 0; j < scores.width(); j++) { - if (!Double.isNaN(scores.getValue(i,j))) - { - scores.setValue(i, j, (double) Math.round(scores.getValue(i,j) * (int) 10000) / 10000); - } + if (!Double.isNaN(scores.getValue(i, j))) + { + scores.setValue(i, j, + (double) Math.round(scores.getValue(i, j) * (int) 10000) + / 10000); + } } } this.scoresOld = scores; this.dim = dim; } - /** - * Initialise a distrust-score for each hypothesis (h) of hSigns - * distrust = conHypNum - proHypNum - * - * @param hSigns ~ hypothesis signs (+/-) for each sequence - * @param scores ~ input score matrix - * - * @return distrustScores - */ + /** + * Initialise a distrust-score for each hypothesis (h) of hSigns distrust = + * conHypNum - proHypNum + * + * @param hSigns + * ~ hypothesis signs (+/-) for each sequence + * @param scores + * ~ input score matrix + * + * @return distrustScores + */ private int[] initialiseDistrusts(byte[] hSigns, MatrixI scores) { int[] distrustScores = new int[scores.width()]; - + // loop over symmetric matrix for (int i = 0; i < scores.width(); i++) { @@ -100,34 +104,43 @@ public class ccAnalysis for (int j = 0; j < scores.width(); j++) { - double cell = scores.getRow(i)[j]; // value at [i][j] in scores - byte hBSign = hSigns[j]; - if (!Double.isNaN(cell)) - { - byte cellSign = (byte) Math.signum(cell); //check if sign of matrix value fits hyptohesis - if (cellSign == hASign * hBSign) - { - proHypNum++; - } else { - conHypNum++; - } - } + double cell = scores.getRow(i)[j]; // value at [i][j] in scores + byte hBSign = hSigns[j]; + if (!Double.isNaN(cell)) + { + byte cellSign = (byte) Math.signum(cell); // check if sign of matrix + // value fits hyptohesis + if (cellSign == hASign * hBSign) + { + proHypNum++; + } + else + { + conHypNum++; + } + } } - distrustScores[i] = conHypNum - proHypNum; //create distrust score for each sequence + distrustScores[i] = conHypNum - proHypNum; // create distrust score for + // each sequence } return distrustScores; } /** - * Optemise hypothesis concerning the sign of the hypothetical value for each hSigns by interpreting the pairwise correlation coefficients as scalar products - * - * @param hSigns ~ hypothesis signs (+/-) - * @param distrustScores - * @param scores ~ input score matrix - * - * @return hSigns - */ - private byte[] optimiseHypothesis(byte[] hSigns, int[] distrustScores, MatrixI scores) + * Optimise hypothesis concerning the sign of the hypothetical value for each + * hSigns by interpreting the pairwise correlation coefficients as scalar + * products + * + * @param hSigns + * ~ hypothesis signs (+/-) + * @param distrustScores + * @param scores + * ~ input score matrix + * + * @return hSigns + */ + private byte[] optimiseHypothesis(byte[] hSigns, int[] distrustScores, + MatrixI scores) { // get maximum distrust score int[] maxes = MiscMath.findMax(distrustScores); @@ -137,7 +150,7 @@ public class ccAnalysis // if hypothesis is not optimal yet if (maxDistrust > 0) { - //toggle sign for hI with maximum distrust + // toggle sign for hI with maximum distrust hSigns[maxDistrustIndex] *= -1; // update distrust at same position distrustScores[maxDistrustIndex] *= -1; @@ -146,300 +159,327 @@ public class ccAnalysis byte hASign = hSigns[maxDistrustIndex]; for (int NOTmaxDistrustIndex = 0; NOTmaxDistrustIndex < distrustScores.length; NOTmaxDistrustIndex++) { - if (NOTmaxDistrustIndex != maxDistrustIndex) - { - byte hBSign = hSigns[NOTmaxDistrustIndex]; - double cell = scores.getValue(maxDistrustIndex, NOTmaxDistrustIndex); - - // distrust only changed if not NaN - if (!Double.isNaN(cell)) - { - byte cellSign = (byte) Math.signum(cell); - // if sign of cell matches hypothesis decrease distrust by 2 because 1 more value supporting and 1 less contradicting - // else increase by 2 - if (cellSign == hASign * hBSign) - { - distrustScores[NOTmaxDistrustIndex] -= 2; - } else { - distrustScores[NOTmaxDistrustIndex] += 2; - } - } - } + if (NOTmaxDistrustIndex != maxDistrustIndex) + { + byte hBSign = hSigns[NOTmaxDistrustIndex]; + double cell = scores.getValue(maxDistrustIndex, + NOTmaxDistrustIndex); + + // distrust only changed if not NaN + if (!Double.isNaN(cell)) + { + byte cellSign = (byte) Math.signum(cell); + // if sign of cell matches hypothesis decrease distrust by 2 because + // 1 more value supporting and 1 less contradicting + // else increase by 2 + if (cellSign == hASign * hBSign) + { + distrustScores[NOTmaxDistrustIndex] -= 2; + } + else + { + distrustScores[NOTmaxDistrustIndex] += 2; + } + } + } } - //further optimisation necessary + // further optimisation necessary return optimiseHypothesis(hSigns, distrustScores, scores); - } else { + } + else + { return hSigns; } } - /** - * takes the a symmetric MatrixI as input scores which may contain Double.NaN - * approximate the missing values using hypothesis optimisation - * - * runs analysis - * - * @param scores ~ score matrix - * - * @return - */ - public MatrixI run () throws Exception + /** + * takes the a symmetric MatrixI as input scores which may contain Double.NaN + * approximate the missing values using hypothesis optimisation + * + * runs analysis + * + * @param scores + * ~ score matrix + * + * @return + */ + public MatrixI run() throws Exception { - //initialse eigenMatrix and repMatrix + // initialse eigenMatrix and repMatrix MatrixI eigenMatrix = scoresOld.copy(); MatrixI repMatrix = scoresOld.copy(); try { - /* - * Calculate correction factor for 2nd and higher eigenvalue(s). - * This correction is NOT needed for the 1st eigenvalue, because the - * unknown (=NaN) values of the matrix are approximated by presuming - * 1-dimensional vectors as the basis of the matrix interpretation as dot - * products. - */ - - System.out.println("Input correlation matrix:"); - eigenMatrix.print(System.out, "%1.4f "); - - int matrixWidth = eigenMatrix.width(); // square matrix, so width == height - int matrixElementsTotal = (int) Math.pow(matrixWidth, 2); //total number of elemts - - float correctionFactor = (float) (matrixElementsTotal - eigenMatrix.countNaN()) / (float) matrixElementsTotal; - - /* - * Calculate hypothetical value (1-dimensional vector) h_i for each - * dataset by interpreting the given correlation coefficients as scalar - * products. - */ - - /* - * Memory for current hypothesis concerning sign of each h_i. - * List of signs for all h_i in the encoding: + /* + * Calculate correction factor for 2nd and higher eigenvalue(s). + * This correction is NOT needed for the 1st eigenvalue, because the + * unknown (=NaN) values of the matrix are approximated by presuming + * 1-dimensional vectors as the basis of the matrix interpretation as dot + * products. + */ + + System.out.println("Input correlation matrix:"); + eigenMatrix.print(System.out, "%1.4f "); + + int matrixWidth = eigenMatrix.width(); // square matrix, so width == + // height + int matrixElementsTotal = (int) Math.pow(matrixWidth, 2); // total number + // of elemts + + float correctionFactor = (float) (matrixElementsTotal + - eigenMatrix.countNaN()) / (float) matrixElementsTotal; + + /* + * Calculate hypothetical value (1-dimensional vector) h_i for each + * dataset by interpreting the given correlation coefficients as scalar + * products. + */ + + /* + * Memory for current hypothesis concerning sign of each h_i. + * List of signs for all h_i in the encoding: * * 1: positive * * 0: zero * * -1: negative - * Initial hypothesis: all signs are positive. - */ - byte[] hSigns = new byte[matrixWidth]; - Arrays.fill(hSigns, (byte) 1); - - //Estimate signs for each h_i by refining hypothesis on signs. - hSigns = optimiseHypothesis(hSigns, initialiseDistrusts(hSigns, eigenMatrix), eigenMatrix); - - - //Estimate absolute values for each h_i by determining sqrt of mean of - //non-NaN absolute values for every row. - double[] hAbs = MiscMath.sqrt(eigenMatrix.absolute().meanRow()); - - //Combine estimated signs with absolute values in obtain total value for - //each h_i. - double[] hValues = MiscMath.elementwiseMultiply(hSigns, hAbs); - - /*Complement symmetric matrix by using the scalar products of estimated - *values of h_i to replace NaN-cells. - *Matrix positions that have estimated values - *(only for diagonal and upper off-diagonal values, due to the symmetry - *the positions of the lower-diagonal values can be inferred). - List of tuples (row_idx, column_idx).*/ - - ArrayList estimatedPositions = new ArrayList(); - - // for off-diagonal cells - for (int rowIndex = 0; rowIndex < matrixWidth - 1; rowIndex++) - { - for (int columnIndex = rowIndex + 1; columnIndex < matrixWidth; columnIndex++) + * Initial hypothesis: all signs are positive. + */ + byte[] hSigns = new byte[matrixWidth]; + Arrays.fill(hSigns, (byte) 1); + + // Estimate signs for each h_i by refining hypothesis on signs. + hSigns = optimiseHypothesis(hSigns, + initialiseDistrusts(hSigns, eigenMatrix), eigenMatrix); + + // Estimate absolute values for each h_i by determining sqrt of mean of + // non-NaN absolute values for every row. + double[] hAbs = MiscMath.sqrt(eigenMatrix.absolute().meanRow()); + + // Combine estimated signs with absolute values in obtain total value for + // each h_i. + double[] hValues = MiscMath.elementwiseMultiply(hSigns, hAbs); + + /*Complement symmetric matrix by using the scalar products of estimated + *values of h_i to replace NaN-cells. + *Matrix positions that have estimated values + *(only for diagonal and upper off-diagonal values, due to the symmetry + *the positions of the lower-diagonal values can be inferred). + List of tuples (row_idx, column_idx).*/ + + ArrayList estimatedPositions = new ArrayList(); + + // for off-diagonal cells + for (int rowIndex = 0; rowIndex < matrixWidth - 1; rowIndex++) { - double cell = eigenMatrix.getValue(rowIndex, columnIndex); - if (Double.isNaN(cell)) - { - //calculate scalar product as new cell value - cell = hValues[rowIndex] * hValues[columnIndex]; - //fill in new value in cell and symmetric partner - eigenMatrix.setValue(rowIndex, columnIndex, cell); - eigenMatrix.setValue(columnIndex, rowIndex, cell); - //save positions of estimated values - estimatedPositions.add(new int[]{rowIndex, columnIndex}); - } + for (int columnIndex = rowIndex + + 1; columnIndex < matrixWidth; columnIndex++) + { + double cell = eigenMatrix.getValue(rowIndex, columnIndex); + if (Double.isNaN(cell)) + { + // calculate scalar product as new cell value + cell = hValues[rowIndex] * hValues[columnIndex]; + // fill in new value in cell and symmetric partner + eigenMatrix.setValue(rowIndex, columnIndex, cell); + eigenMatrix.setValue(columnIndex, rowIndex, cell); + // save positions of estimated values + estimatedPositions.add(new int[] { rowIndex, columnIndex }); + } + } } - } - // for diagonal cells - for (int diagonalIndex = 0; diagonalIndex < matrixWidth; diagonalIndex++) + // for diagonal cells + for (int diagonalIndex = 0; diagonalIndex < matrixWidth; diagonalIndex++) { double cell = Math.pow(hValues[diagonalIndex], 2); - eigenMatrix.setValue(diagonalIndex, diagonalIndex, cell); - estimatedPositions.add(new int[]{diagonalIndex, diagonalIndex}); + eigenMatrix.setValue(diagonalIndex, diagonalIndex, cell); + estimatedPositions.add(new int[] { diagonalIndex, diagonalIndex }); } - /*Refine total values of each h_i: - *Initialise h_values of the hypothetical non-existant previous iteration - *with the correct format but with impossible values. - Needed for exit condition of otherwise endless loop.*/ - System.out.print("initial values: [ "); - for (double h : hValues) - { - System.out.print(String.format("%1.4f, ", h)); - } - System.out.println(" ]"); - - - double[] hValuesOld = new double[matrixWidth]; - - int iterationCount = 0; - - // FIXME JAL-4443 - spliterators could be coded out or patched with j2s annotation - // repeat unitl values of h do not significantly change anymore - while (true) - { - for (int hIndex = 0; hIndex < matrixWidth; hIndex++) - { - double newH = Arrays.stream(MiscMath.elementwiseMultiply(hValues, eigenMatrix.getRow(hIndex))).sum() / Arrays.stream(MiscMath.elementwiseMultiply(hValues, hValues)).sum(); - hValues[hIndex] = newH; - } - - System.out.print(String.format("iteration %d: [ ", iterationCount)); + /*Refine total values of each h_i: + *Initialise h_values of the hypothetical non-existant previous iteration + *with the correct format but with impossible values. + Needed for exit condition of otherwise endless loop.*/ + System.out.print("initial values: [ "); for (double h : hValues) { - System.out.print(String.format("%1.4f, ", h)); + System.out.print(String.format("%1.4f, ", h)); } System.out.println(" ]"); - //update values of estimated positions - for (int[] pair : estimatedPositions) // pair ~ row, col - { - double newVal = hValues[pair[0]] * hValues[pair[1]]; - eigenMatrix.setValue(pair[0], pair[1], newVal); - eigenMatrix.setValue(pair[1], pair[0], newVal); - } + double[] hValuesOld = new double[matrixWidth]; - iterationCount++; + int iterationCount = 0; - //exit loop as soon as new values are similar to the last iteration - if (MiscMath.allClose(hValues, hValuesOld, 0d, 1e-05d, false)) + // FIXME JAL-4443 - spliterators could be coded out or patched with j2s + // annotation + // repeat unitl values of h do not significantly change anymore + while (true) { - break; + for (int hIndex = 0; hIndex < matrixWidth; hIndex++) + { + double newH = Arrays + .stream(MiscMath.elementwiseMultiply(hValues, + eigenMatrix.getRow(hIndex))) + .sum() + / Arrays.stream( + MiscMath.elementwiseMultiply(hValues, hValues)) + .sum(); + hValues[hIndex] = newH; + } + + System.out.print(String.format("iteration %d: [ ", iterationCount)); + for (double h : hValues) + { + System.out.print(String.format("%1.4f, ", h)); + } + System.out.println(" ]"); + + // update values of estimated positions + for (int[] pair : estimatedPositions) // pair ~ row, col + { + double newVal = hValues[pair[0]] * hValues[pair[1]]; + eigenMatrix.setValue(pair[0], pair[1], newVal); + eigenMatrix.setValue(pair[1], pair[0], newVal); + } + + iterationCount++; + + // exit loop as soon as new values are similar to the last iteration + if (MiscMath.allClose(hValues, hValuesOld, 0d, 1e-05d, false)) + { + break; + } + + // save hValues for comparison in the next iteration + System.arraycopy(hValues, 0, hValuesOld, 0, hValues.length); } - //save hValues for comparison in the next iteration - System.arraycopy(hValues, 0, hValuesOld, 0, hValues.length); - } - - //----------------------------- - //Use complemented symmetric matrix to calculate final representative - //vectors. - - //Eigendecomposition. - eigenMatrix.tred(); - eigenMatrix.tqli(); + // ----------------------------- + // Use complemented symmetric matrix to calculate final representative + // vectors. - System.out.println("eigenmatrix"); - eigenMatrix.print(System.out, "%8.2f"); - System.out.println(); - System.out.println("uncorrected eigenvalues"); - eigenMatrix.printD(System.out, "%2.4f "); - System.out.println(); + // Eigendecomposition. + eigenMatrix.tred(); + eigenMatrix.tqli(); - double[] eigenVals = eigenMatrix.getD(); + System.out.println("eigenmatrix"); + eigenMatrix.print(System.out, "%8.2f"); + System.out.println(); + System.out.println("uncorrected eigenvalues"); + eigenMatrix.printD(System.out, "%2.4f "); + System.out.println(); - TreeMap eigenPairs = new TreeMap<>(Comparator.reverseOrder()); - for (int i = 0; i < eigenVals.length; i++) - { - eigenPairs.put(eigenVals[i], i); - } + double[] eigenVals = eigenMatrix.getD(); - // matrix of representative eigenvectors (each row is a vector) - double[][] _repMatrix = new double[eigenVals.length][dim]; - double[][] _oldMatrix = new double[eigenVals.length][dim]; - double[] correctedEigenValues = new double[dim]; - - int l = 0; - for (Entry pair : eigenPairs.entrySet()) - { - double eigenValue = pair.getKey(); - int column = pair.getValue(); - double[] eigenVector = eigenMatrix.getColumn(column); - //for 2nd and higher eigenvalues - if (l >= 1) + TreeMap eigenPairs = new TreeMap<>( + Comparator.reverseOrder()); + for (int i = 0; i < eigenVals.length; i++) { - eigenValue /= correctionFactor; + eigenPairs.put(eigenVals[i], i); } - correctedEigenValues[l] = eigenValue; - for (int j = 0; j < eigenVector.length; j++) - { - _repMatrix[j][l] = (eigenValue < 0) ? 0.0 : - Math.sqrt(eigenValue) * eigenVector[j]; - double tmpOldScore = scoresOld.getColumn(column)[j]; - _oldMatrix[j][dim - l - 1] = (Double.isNaN(tmpOldScore)) ? 0.0 : tmpOldScore; - } - l++; - if (l >= dim) - { - break; - } - } - System.out.println("correctedEigenValues"); - MiscMath.print(correctedEigenValues, "%2.4f "); - - repMatrix = new Matrix(_repMatrix); - repMatrix.setD(correctedEigenValues); - MatrixI oldMatrix = new Matrix(_oldMatrix); - - MatrixI dotMatrix = repMatrix.postMultiply(repMatrix.transpose()); - - double rmsd = scoresOld.rmsd(dotMatrix); - - System.out.println("iteration, rmsd, maxDiff, rmsdDiff"); - System.out.println(String.format("0, %8.5f, -, -", rmsd)); - // Refine representative vectors by minimising sum-of-squared deviates between dotMatrix and original score matrix - for (int iteration = 1; iteration < 21; iteration++) // arbitrarily set to 20 - { - MatrixI repMatrixOLD = repMatrix.copy(); - MatrixI dotMatrixOLD = dotMatrix.copy(); + // matrix of representative eigenvectors (each row is a vector) + double[][] _repMatrix = new double[eigenVals.length][dim]; + double[][] _oldMatrix = new double[eigenVals.length][dim]; + double[] correctedEigenValues = new double[dim]; - // for all rows/hA in the original matrix - for (int hAIndex = 0; hAIndex < oldMatrix.height(); hAIndex++) + int l = 0; + for (Entry pair : eigenPairs.entrySet()) { - double[] row = oldMatrix.getRow(hAIndex); - double[] hA = repMatrix.getRow(hAIndex); - hAIndex = hAIndex; - //find least-squares-solution fo rdifferences between original scores and representative vectors - double[] hAlsm = leastSquaresOptimisation(repMatrix, scoresOld, hAIndex); - // update repMatrix with new hAlsm - for (int j = 0; j < repMatrix.width(); j++) - { - repMatrix.setValue(hAIndex, j, hAlsm[j]); - } - } - - // dot product of representative vecotrs yields a matrix with values approximating the correlation matrix - dotMatrix = repMatrix.postMultiply(repMatrix.transpose()); - // calculate rmsd between approximation and correlation matrix - rmsd = scoresOld.rmsd(dotMatrix); - - // calculate maximum change of representative vectors of current iteration - MatrixI diff = repMatrix.subtract(repMatrixOLD).absolute(); - double maxDiff = 0.0; - for (int i = 0; i < diff.height(); i++) - { - for (int j = 0; j < diff.width(); j++) - { - maxDiff = (diff.getValue(i, j) > maxDiff) ? diff.getValue(i, j) : maxDiff; - } + double eigenValue = pair.getKey(); + int column = pair.getValue(); + double[] eigenVector = eigenMatrix.getColumn(column); + // for 2nd and higher eigenvalues + if (l >= 1) + { + eigenValue /= correctionFactor; + } + correctedEigenValues[l] = eigenValue; + for (int j = 0; j < eigenVector.length; j++) + { + _repMatrix[j][l] = (eigenValue < 0) ? 0.0 + : -Math.sqrt(eigenValue) * eigenVector[j]; + double tmpOldScore = scoresOld.getColumn(column)[j]; + _oldMatrix[j][dim - l - 1] = (Double.isNaN(tmpOldScore)) ? 0.0 + : tmpOldScore; + } + l++; + if (l >= dim) + { + break; + } } - // calculate rmsd between current and previous estimation - double rmsdDiff = dotMatrix.rmsd(dotMatrixOLD); + System.out.println("correctedEigenValues"); + MiscMath.print(correctedEigenValues, "%2.4f "); + + repMatrix = new Matrix(_repMatrix); + repMatrix.setD(correctedEigenValues); + MatrixI oldMatrix = new Matrix(_oldMatrix); - System.out.println(String.format("%d, %8.5f, %8.5f, %8.5f", iteration, rmsd, maxDiff, rmsdDiff)); + MatrixI dotMatrix = repMatrix.postMultiply(repMatrix.transpose()); - if (!(Math.abs(maxDiff) > 1e-06)) + double rmsd = scoresOld.rmsd(dotMatrix); + + System.out.println("iteration, rmsd, maxDiff, rmsdDiff"); + System.out.println(String.format("0, %8.5f, -, -", rmsd)); + // Refine representative vectors by minimising sum-of-squared deviates + // between dotMatrix and original score matrix + for (int iteration = 1; iteration < 21; iteration++) // arbitrarily set to + // 20 { - repMatrix = repMatrixOLD.copy(); - break; + MatrixI repMatrixOLD = repMatrix.copy(); + MatrixI dotMatrixOLD = dotMatrix.copy(); + + // for all rows/hA in the original matrix + for (int hAIndex = 0; hAIndex < oldMatrix.height(); hAIndex++) + { + double[] row = oldMatrix.getRow(hAIndex); + double[] hA = repMatrix.getRow(hAIndex); + hAIndex = hAIndex; + // find least-squares-solution fo rdifferences between original scores + // and representative vectors + double[] hAlsm = leastSquaresOptimisation(repMatrix, scoresOld, + hAIndex); + // update repMatrix with new hAlsm + for (int j = 0; j < repMatrix.width(); j++) + { + repMatrix.setValue(hAIndex, j, hAlsm[j]); + } + } + + // dot product of representative vecotrs yields a matrix with values + // approximating the correlation matrix + dotMatrix = repMatrix.postMultiply(repMatrix.transpose()); + // calculate rmsd between approximation and correlation matrix + rmsd = scoresOld.rmsd(dotMatrix); + + // calculate maximum change of representative vectors of current + // iteration + MatrixI diff = repMatrix.subtract(repMatrixOLD).absolute(); + double maxDiff = 0.0; + for (int i = 0; i < diff.height(); i++) + { + for (int j = 0; j < diff.width(); j++) + { + maxDiff = (diff.getValue(i, j) > maxDiff) ? diff.getValue(i, j) + : maxDiff; + } + } + + // calculate rmsd between current and previous estimation + double rmsdDiff = dotMatrix.rmsd(dotMatrixOLD); + + System.out.println(String.format("%d, %8.5f, %8.5f, %8.5f", + iteration, rmsd, maxDiff, rmsdDiff)); + + if (!(Math.abs(maxDiff) > 1e-06)) + { + repMatrix = repMatrixOLD.copy(); + break; + } } - } - } catch (Exception q) { @@ -452,35 +492,48 @@ public class ccAnalysis } /** - * Create equations system using information on originally known - * pairwise correlation coefficients (parsed from infile) and the - * representative result vectors - * - * Each equation has the format: - * hA * hA - pairwiseCC = 0 - * with: - * hA: unknown variable - * hB: known representative vector - * pairwiseCC: known pairwise correlation coefficien - * - * The resulting equations system is overdetermined, if there are more - * equations than unknown elements - * - * @param x ~ unknown n-dimensional column-vector - * (needed for generating equations system, NOT to be specified by user). - * @param hAIndex ~ index of currently optimised representative result vector. - * @param h ~ matrix with row-wise listing of representative result vectors. - * @param originalRow ~ matrix-row of originally parsed pairwise correlation coefficients. - * - * @return - */ - private double[] originalToEquasionSystem(double[] hA, MatrixI repMatrix, MatrixI scoresOld, int hAIndex) + * Create equations system using information on originally known pairwise + * correlation coefficients (parsed from infile) and the representative result + * vectors + * + * Each equation has the format: + * + * hA * hA - pairwiseCC = 0 + * + * with: + * + * hA: unknown variable + * + * hB: known representative vector + * + * pairwiseCC: known pairwise correlation coefficien + * + * The resulting equations system is overdetermined, if there are more + * equations than unknown elements + * + * x is the user input. Remaining parameters are needed for generating + * equations system, NOT to be specified by user). + * + * @param x + * ~ unknown n-dimensional column-vector + * @param hAIndex + * ~ index of currently optimised representative result vector. + * @param h + * ~ matrix with row-wise listing of representative result vectors. + * @param originalRow + * ~ matrix-row of originally parsed pairwise correlation + * coefficients. + * + * @return + */ + private double[] originalToEquasionSystem(double[] hA, MatrixI repMatrix, + MatrixI scoresOld, int hAIndex) { double[] originalRow = scoresOld.getRow(hAIndex); int nans = MiscMath.countNaN(originalRow); double[] result = new double[originalRow.length - nans]; - //for all pairwiseCC in originalRow + // for all pairwiseCC in originalRow int resultIndex = 0; for (int hBIndex = 0; hBIndex < originalRow.length; hBIndex++) { @@ -489,40 +542,48 @@ public class ccAnalysis if (!Double.isNaN(pairwiseCC)) { double[] hB = repMatrix.getRow(hBIndex); - result[resultIndex++] = MiscMath.sum(MiscMath.elementwiseMultiply(hA, hB)) - pairwiseCC; - } else { + result[resultIndex++] = MiscMath + .sum(MiscMath.elementwiseMultiply(hA, hB)) - pairwiseCC; + } + else + { } } return result; } /** - * returns the jacobian matrix - * @param repMatrix ~ matrix of representative vectors - * @param hAIndex ~ current row index - * - * @return - */ - private MatrixI approximateDerivative(MatrixI repMatrix, MatrixI scoresOld, int hAIndex) + * returns the jacobian matrix + * + * @param repMatrix + * ~ matrix of representative vectors + * @param hAIndex + * ~ current row index + * + * @return + */ + private MatrixI approximateDerivative(MatrixI repMatrix, + MatrixI scoresOld, int hAIndex) { - //hA = x0 + // hA = x0 double[] hA = repMatrix.getRow(hAIndex); - double[] f0 = originalToEquasionSystem(hA, repMatrix, scoresOld, hAIndex); + double[] f0 = originalToEquasionSystem(hA, repMatrix, scoresOld, + hAIndex); double[] signX0 = new double[hA.length]; double[] xAbs = new double[hA.length]; for (int i = 0; i < hA.length; i++) { signX0[i] = (hA[i] >= 0) ? 1 : -1; xAbs[i] = (Math.abs(hA[i]) >= 1.0) ? Math.abs(hA[i]) : 1.0; - } + } double rstep = Math.pow(Math.ulp(1.0), 0.5); - double[] h = new double [hA.length]; + double[] h = new double[hA.length]; for (int i = 0; i < hA.length; i++) { h[i] = rstep * signX0[i] * xAbs[i]; } - + int m = f0.length; int n = hA.length; double[][] jTransposed = new double[n][m]; @@ -532,11 +593,12 @@ public class ccAnalysis System.arraycopy(hA, 0, x, 0, h.length); x[i] += h[i]; double dx = x[i] - hA[i]; - double[] df = originalToEquasionSystem(x, repMatrix, scoresOld, hAIndex); + double[] df = originalToEquasionSystem(x, repMatrix, scoresOld, + hAIndex); for (int j = 0; j < df.length; j++) { - df[j] -= f0[j]; - jTransposed[i][j] = df[j] / dx; + df[j] -= f0[j]; + jTransposed[i][j] = df[j] / dx; } } MatrixI J = new Matrix(jTransposed).transpose(); @@ -544,31 +606,40 @@ public class ccAnalysis } /** - * norm of regularized (by alpha) least-squares solution minus Delta - * @param alpha - * @param suf - * @param s - * @param Delta - * - * @return - */ - private double[] phiAndDerivative(double alpha, double[] suf, double[] s, double Delta) + * norm of regularized (by alpha) least-squares solution minus Delta + * + * @param alpha + * @param suf + * @param s + * @param Delta + * + * @return + */ + private double[] phiAndDerivative(double alpha, double[] suf, double[] s, + double Delta) { - double[] denom = MiscMath.elementwiseAdd(MiscMath.elementwiseMultiply(s, s), alpha); + double[] denom = MiscMath + .elementwiseAdd(MiscMath.elementwiseMultiply(s, s), alpha); double pNorm = MiscMath.norm(MiscMath.elementwiseDivide(suf, denom)); double phi = pNorm - Delta; // - sum ( suf**2 / denom**3) / pNorm - double phiPrime = - MiscMath.sum(MiscMath.elementwiseDivide(MiscMath.elementwiseMultiply(suf, suf), MiscMath.elementwiseMultiply(MiscMath.elementwiseMultiply(denom, denom), denom))) / pNorm; - return new double[]{phi, phiPrime}; + double phiPrime = -MiscMath.sum(MiscMath.elementwiseDivide( + MiscMath.elementwiseMultiply(suf, suf), + MiscMath.elementwiseMultiply( + MiscMath.elementwiseMultiply(denom, denom), denom))) + / pNorm; + return new double[] { phi, phiPrime }; } /** - * class holding the result of solveLsqTrustRegion - */ + * class holding the result of solveLsqTrustRegion + */ private class TrustRegion { private double[] step; + private double alpha; + private int iteration; public TrustRegion(double[] step, double alpha, int iteration) @@ -587,7 +658,7 @@ public class ccAnalysis { return this.alpha; } - + public int getIteration() { return this.iteration; @@ -595,22 +666,30 @@ public class ccAnalysis } /** - * solve a trust-region problem arising in least-squares optimisation - * @param n ~ number of variables - * @param m ~ number of residuals - * @param uf - * @param s ~ singular values of J - * @param V ~ transpose of VT - * @param Delta ~ radius of a trust region - * @param alpha ~ initial guess for alpha - * - * @return - */ - private TrustRegion solveLsqTrustRegion(int n, int m, double[] uf, double[] s, MatrixI V, double Delta, double alpha) + * solve a trust-region problem arising in least-squares optimisation + * + * @param n + * ~ number of variables + * @param m + * ~ number of residuals + * @param uf + * @param s + * ~ singular values of J + * @param V + * ~ transpose of VT + * @param Delta + * ~ radius of a trust region + * @param alpha + * ~ initial guess for alpha + * + * @return + */ + private TrustRegion solveLsqTrustRegion(int n, int m, double[] uf, + double[] s, MatrixI V, double Delta, double alpha) { double[] suf = MiscMath.elementwiseMultiply(s, uf); - //check if J has full rank and tr Gauss-Newton step + // check if J has full rank and tr Gauss-Newton step boolean fullRank = false; if (m >= n) { @@ -619,7 +698,8 @@ public class ccAnalysis } if (fullRank) { - double[] p = MiscMath.elementwiseMultiply(V.sumProduct(MiscMath.elementwiseDivide(uf, s)), -1); + double[] p = MiscMath.elementwiseMultiply( + V.sumProduct(MiscMath.elementwiseDivide(uf, s)), -1); if (MiscMath.norm(p) <= Delta) { TrustRegion result = new TrustRegion(p, 0.0, 0); @@ -632,15 +712,21 @@ public class ccAnalysis if (fullRank) { double[] phiAndPrime = phiAndDerivative(0.0, suf, s, Delta); - alphaLower = - phiAndPrime[0] / phiAndPrime[1]; + alphaLower = -phiAndPrime[0] / phiAndPrime[1]; } - alpha = (!fullRank && alpha == 0.0) ? alpha = Math.max(0.001 * alphaUpper, Math.pow(alphaLower * alphaUpper, 0.5)) : alpha; + alpha = (!fullRank && alpha == 0.0) + ? alpha = Math.max(0.001 * alphaUpper, + Math.pow(alphaLower * alphaUpper, 0.5)) + : alpha; int iteration = 0; - while (iteration < 10) // 10 is default max_iter + while (iteration < 10) // 10 is default max_iter { - alpha = (alpha < alphaLower || alpha > alphaUpper) ? alpha = Math.max(0.001 * alphaUpper, Math.pow(alphaLower * alphaUpper, 0.5)) : alpha; + alpha = (alpha < alphaLower || alpha > alphaUpper) + ? alpha = Math.max(0.001 * alphaUpper, + Math.pow(alphaLower * alphaUpper, 0.5)) + : alpha; double[] phiAndPrime = phiAndDerivative(alpha, suf, s, Delta); double phi = phiAndPrime[0]; double phiPrime = phiAndPrime[1]; @@ -650,18 +736,20 @@ public class ccAnalysis alphaLower = Math.max(alphaLower, alpha - ratio); alpha -= (phi + Delta) * ratio / Delta; - if (Math.abs(phi) < 0.01 * Delta) // default rtol set to 0.01 + if (Math.abs(phi) < 0.01 * Delta) // default rtol set to 0.01 { - break; + break; } iteration++; } // p = - V.dot( suf / (s**2 + alpha)) - double[] tmp = MiscMath.elementwiseDivide(suf, MiscMath.elementwiseAdd(MiscMath.elementwiseMultiply(s, s), alpha)); + double[] tmp = MiscMath.elementwiseDivide(suf, MiscMath + .elementwiseAdd(MiscMath.elementwiseMultiply(s, s), alpha)); double[] p = MiscMath.elementwiseMultiply(V.sumProduct(tmp), -1); - // Make the norm of p equal to Delta, p is changed only slightly during this. + // Make the norm of p equal to Delta, p is changed only slightly during + // this. // It is done to prevent p lie outside of the trust region p = MiscMath.elementwiseMultiply(p, Delta / MiscMath.norm(p)); @@ -670,15 +758,18 @@ public class ccAnalysis } /** - * compute values of a quadratic function arising in least squares - * function: 0.5 * s.T * (J.T * J + diag) * s + g.T * s - * - * @param J ~ jacobian matrix - * @param g ~ gradient - * @param s ~ steps and rows - * - * @return - */ + * compute values of a quadratic function arising in least squares function: + * 0.5 * s.T * (J.T * J + diag) * s + g.T * s + * + * @param J + * ~ jacobian matrix + * @param g + * ~ gradient + * @param s + * ~ steps and rows + * + * @return + */ private double evaluateQuadratic(MatrixI J, double[] g, double[] s) { @@ -690,50 +781,64 @@ public class ccAnalysis } /** - * update the radius of a trust region based on the cost reduction - * - * @param Delta - * @param actualReduction - * @param predictedReduction - * @param stepNorm - * @param boundHit - * - * @return - */ - private double[] updateTrustRegionRadius(double Delta, double actualReduction, double predictedReduction, double stepNorm, boolean boundHit) + * update the radius of a trust region based on the cost reduction + * + * @param Delta + * @param actualReduction + * @param predictedReduction + * @param stepNorm + * @param boundHit + * + * @return + */ + private double[] updateTrustRegionRadius(double Delta, + double actualReduction, double predictedReduction, + double stepNorm, boolean boundHit) { double ratio = 0; if (predictedReduction > 0) { ratio = actualReduction / predictedReduction; - } else if (predictedReduction == 0 && actualReduction == 0) { + } + else if (predictedReduction == 0 && actualReduction == 0) + { ratio = 1; - } else { + } + else + { ratio = 0; } if (ratio < 0.25) { Delta = 0.25 * stepNorm; - } else if (ratio > 0.75 && boundHit) { + } + else if (ratio > 0.75 && boundHit) + { Delta *= 2.0; } - return new double[]{Delta, ratio}; + return new double[] { Delta, ratio }; } /** - * trust region reflective algorithm - * @param repMatrix ~ Matrix containing representative vectors - * @param scoresOld ~ Matrix containing initial observations - * @param index ~ current row index - * @param J ~ jacobian matrix - * - * @return - */ - private double[] trf(MatrixI repMatrix, MatrixI scoresOld, int index, MatrixI J) + * trust region reflective algorithm + * + * @param repMatrix + * ~ Matrix containing representative vectors + * @param scoresOld + * ~ Matrix containing initial observations + * @param index + * ~ current row index + * @param J + * ~ jacobian matrix + * + * @return + */ + private double[] trf(MatrixI repMatrix, MatrixI scoresOld, int index, + MatrixI J) { - //hA = x0 + // hA = x0 double[] hA = repMatrix.getRow(index); double[] f0 = originalToEquasionSystem(hA, repMatrix, scoresOld, index); int nfev = 1; @@ -743,7 +848,7 @@ public class ccAnalysis double[] g = J.transpose().sumProduct(f0); double Delta = MiscMath.norm(hA); int maxNfev = hA.length * 100; - double alpha = 0.0; // "Levenberg-Marquardt" parameter + double alpha = 0.0; // "Levenberg-Marquardt" parameter double gNorm = 0; boolean terminationStatus = false; @@ -754,11 +859,12 @@ public class ccAnalysis gNorm = MiscMath.norm(g); if (terminationStatus || nfev == maxNfev) { - break; + break; } - SingularValueDecomposition svd = new SingularValueDecomposition(new Array2DRowRealMatrix(J.asArray())); + SingularValueDecomposition svd = new SingularValueDecomposition( + new Array2DRowRealMatrix(J.asArray())); MatrixI U = new Matrix(svd.getU().getData()); - double[] s = svd.getSingularValues(); + double[] s = svd.getSingularValues(); MatrixI V = new Matrix(svd.getV().getData()).transpose(); double[] uf = U.transpose().sumProduct(f0); @@ -767,60 +873,67 @@ public class ccAnalysis double[] fNew = new double[f0.length]; double costNew = 0; double stepHnorm = 0; - + while (actualReduction <= 0 && nfev < maxNfev) { - TrustRegion trustRegion = solveLsqTrustRegion(n, m, uf, s, V, Delta, alpha); - double[] stepH = trustRegion.getStep(); - alpha = trustRegion.getAlpha(); - int nIterations = trustRegion.getIteration(); - double predictedReduction = - (evaluateQuadratic(J, g, stepH)); + TrustRegion trustRegion = solveLsqTrustRegion(n, m, uf, s, V, Delta, + alpha); + double[] stepH = trustRegion.getStep(); + alpha = trustRegion.getAlpha(); + int nIterations = trustRegion.getIteration(); + double predictedReduction = -(evaluateQuadratic(J, g, stepH)); xNew = MiscMath.elementwiseAdd(hA, stepH); - fNew = originalToEquasionSystem(xNew, repMatrix, scoresOld, index); - nfev++; - - stepHnorm = MiscMath.norm(stepH); + fNew = originalToEquasionSystem(xNew, repMatrix, scoresOld, index); + nfev++; - if (MiscMath.countNaN(fNew) > 0) - { - Delta = 0.25 * stepHnorm; - continue; - } + stepHnorm = MiscMath.norm(stepH); - // usual trust-region step quality estimation - costNew = 0.5 * MiscMath.dot(fNew, fNew); - actualReduction = cost - costNew; + if (MiscMath.countNaN(fNew) > 0) + { + Delta = 0.25 * stepHnorm; + continue; + } - double[] updatedTrustRegion = updateTrustRegionRadius(Delta, actualReduction, predictedReduction, stepHnorm, stepHnorm > (0.95 * Delta)); - double DeltaNew = updatedTrustRegion[0]; - double ratio = updatedTrustRegion[1]; + // usual trust-region step quality estimation + costNew = 0.5 * MiscMath.dot(fNew, fNew); + actualReduction = cost - costNew; - // default ftol and xtol = 1e-8 - boolean ftolSatisfied = actualReduction < (1e-8 * cost) && ratio > 0.25; - boolean xtolSatisfied = stepHnorm < (1e-8 * (1e-8 + MiscMath.norm(hA))); - terminationStatus = ftolSatisfied || xtolSatisfied; - if (terminationStatus) - { - break; - } + double[] updatedTrustRegion = updateTrustRegionRadius(Delta, + actualReduction, predictedReduction, stepHnorm, + stepHnorm > (0.95 * Delta)); + double DeltaNew = updatedTrustRegion[0]; + double ratio = updatedTrustRegion[1]; - alpha *= Delta / DeltaNew; - Delta = DeltaNew; + // default ftol and xtol = 1e-8 + boolean ftolSatisfied = actualReduction < (1e-8 * cost) + && ratio > 0.25; + boolean xtolSatisfied = stepHnorm < (1e-8 + * (1e-8 + MiscMath.norm(hA))); + terminationStatus = ftolSatisfied || xtolSatisfied; + if (terminationStatus) + { + break; + } + + alpha *= Delta / DeltaNew; + Delta = DeltaNew; } if (actualReduction > 0) { - hA = xNew; - f0 = fNew; - cost = costNew; + hA = xNew; + f0 = fNew; + cost = costNew; - J = approximateDerivative(repMatrix, scoresOld, index); + J = approximateDerivative(repMatrix, scoresOld, index); g = J.transpose().sumProduct(f0); - } else { + } + else + { stepHnorm = 0; - actualReduction = 0; + actualReduction = 0; } iteration++; } @@ -829,16 +942,20 @@ public class ccAnalysis } /** - * performs the least squares optimisation - * adapted from https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.least_squares.html#scipy.optimize.least_squares - * - * @param repMatrix ~ Matrix containing representative vectors - * @param scoresOld ~ Matrix containing initial observations - * @param index ~ current row index - * - * @return - */ - private double[] leastSquaresOptimisation(MatrixI repMatrix, MatrixI scoresOld, int index) + * performs the least squares optimisation adapted from + * https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.least_squares.html#scipy.optimize.least_squares + * + * @param repMatrix + * ~ Matrix containing representative vectors + * @param scoresOld + * ~ Matrix containing initial observations + * @param index + * ~ current row index + * + * @return + */ + private double[] leastSquaresOptimisation(MatrixI repMatrix, + MatrixI scoresOld, int index) { MatrixI J = approximateDerivative(repMatrix, scoresOld, index); double[] result = trf(repMatrix, scoresOld, index, J); diff --git a/src/jalview/analysis/scoremodels/DistanceScoreModel.java b/src/jalview/analysis/scoremodels/DistanceScoreModel.java index 55510bd..1bdaad6 100644 --- a/src/jalview/analysis/scoremodels/DistanceScoreModel.java +++ b/src/jalview/analysis/scoremodels/DistanceScoreModel.java @@ -57,5 +57,5 @@ public abstract class DistanceScoreModel implements ScoreModelI return similarities; } - + } diff --git a/src/jalview/analysis/scoremodels/FeatureDistanceModel.java b/src/jalview/analysis/scoremodels/FeatureDistanceModel.java index df45a72..bcc0855 100644 --- a/src/jalview/analysis/scoremodels/FeatureDistanceModel.java +++ b/src/jalview/analysis/scoremodels/FeatureDistanceModel.java @@ -235,7 +235,7 @@ public class FeatureDistanceModel extends DistanceScoreModel public boolean isProtein() { return true; - } + } @Override public String toString() diff --git a/src/jalview/analysis/scoremodels/ScoreModels.java b/src/jalview/analysis/scoremodels/ScoreModels.java index f591c8e..490ec00 100644 --- a/src/jalview/analysis/scoremodels/ScoreModels.java +++ b/src/jalview/analysis/scoremodels/ScoreModels.java @@ -40,7 +40,7 @@ public class ScoreModels private final ScoreMatrix PAM250; private final ScoreMatrix DNA; - + private final ScoreMatrix SECONDARYSTRUCTURE; private static ScoreModels instance; @@ -70,7 +70,7 @@ public class ScoreModels *
  • PAM250
  • *
  • PID
  • *
  • DNA
  • - *
  • Sequence Feature Similarity
  • * + *
  • Sequence Feature Similarity
  • * *
  • Secondary Structure Similarity
  • * */ @@ -85,8 +85,9 @@ public class ScoreModels DNA = loadScoreMatrix("scoreModel/dna.scm"); registerScoreModel(new PIDModel()); registerScoreModel(new FeatureDistanceModel()); - SECONDARYSTRUCTURE = loadScoreMatrix("scoreModel/secondarystructure.scm"); - registerScoreModel(new SecondaryStructureDistanceModel()); + SECONDARYSTRUCTURE = loadScoreMatrix( + "scoreModel/secondarystructure.scm"); + registerScoreModel(new SecondaryStructureDistanceModel()); } @@ -146,7 +147,8 @@ public class ScoreModels public void registerScoreModel(ScoreModelI sm) { - if(sm.getName().equals("SECONDARYSTRUCTURE")) { + if (sm.getName().equals("SECONDARYSTRUCTURE")) + { return; } ScoreModelI sm2 = models.get(sm.getName()); @@ -187,7 +189,7 @@ public class ScoreModels { return PAM250; } - + public ScoreMatrix getSecondaryStructureMatrix() { return SECONDARYSTRUCTURE; diff --git a/src/jalview/analysis/scoremodels/SecondaryStructureDistanceModel.java b/src/jalview/analysis/scoremodels/SecondaryStructureDistanceModel.java index 6cce5b4..473abcf 100644 --- a/src/jalview/analysis/scoremodels/SecondaryStructureDistanceModel.java +++ b/src/jalview/analysis/scoremodels/SecondaryStructureDistanceModel.java @@ -47,20 +47,19 @@ public class SecondaryStructureDistanceModel extends DistanceScoreModel private static final String NAME = "Secondary Structure Similarity"; private ScoreMatrix ssRateMatrix; - - private String description; - + + private String description; + FeatureRenderer fr; - - + /** * Constructor */ public SecondaryStructureDistanceModel() { - + } - + @Override public ScoreModelI getInstance(AlignmentViewPanel view) { @@ -87,66 +86,77 @@ public class SecondaryStructureDistanceModel extends DistanceScoreModel fr = view.cloneFeatureRenderer(); return true; } - + /** - * Calculates distance score [i][j] between each pair of protein sequences - * based on their secondary structure annotations (H, E, C). - * The final score is normalised by the number of - * alignment columns processed, providing an average similarity score. + * Calculates distance score [i][j] between each pair of protein sequences + * based on their secondary structure annotations (H, E, C). The final score + * is normalised by the number of alignment columns processed, providing an + * average similarity score. *

    - * The parameters argument can include settings for handling gap-residue aligned - * positions and may determine if the score calculation is based on the longer or shorter - * sequence in each pair. This can be important for handling partial alignments or - * sequences of significantly different lengths. + * The parameters argument can include settings for handling gap-residue + * aligned positions and may determine if the score calculation is based on + * the longer or shorter sequence in each pair. This can be important for + * handling partial alignments or sequences of significantly different + * lengths. * - * @param seqData The aligned sequence data including secondary structure annotations. - * @param params Additional parameters for customising the scoring process, such as gap - * handling and sequence length consideration. + * @param seqData + * The aligned sequence data including secondary structure + * annotations. + * @param params + * Additional parameters for customising the scoring process, such as + * gap handling and sequence length consideration. */ @Override public MatrixI findDistances(AlignmentView seqData, SimilarityParamsI params) - { - + { + SeqCigar[] seqs = seqData.getSequences(); - int noseqs = seqs.length; //no of sequences + int noseqs = seqs.length; // no of sequences int cpwidth = 0; // = seqData.getWidth(); - double[][] similarities = new double[noseqs][noseqs]; //matrix to store similarity score - //secondary structure source parameter selected by the user from the drop down. - String ssSource = params.getSecondaryStructureSource(); + double[][] similarities = new double[noseqs][noseqs]; // matrix to store + // similarity score + // secondary structure source parameter selected by the user from the drop + // down. + String ssSource = params.getSecondaryStructureSource(); ssRateMatrix = ScoreModels.getInstance().getSecondaryStructureMatrix(); - - //defining the default value for secondary structure source as 3d structures - //or JPred if user selected JPred + + // defining the default value for secondary structure source as 3d + // structures + // or JPred if user selected JPred String selectedSSSource = Constants.SS_ANNOTATION_LABEL; - if(ssSource.equals(Constants.SECONDARY_STRUCTURE_LABELS.get(Constants.SS_ANNOTATION_FROM_JPRED_LABEL))) + if (ssSource.equals(Constants.SECONDARY_STRUCTURE_LABELS + .get(Constants.SS_ANNOTATION_FROM_JPRED_LABEL))) { selectedSSSource = Constants.SS_ANNOTATION_FROM_JPRED_LABEL; } - + // need to get real position for view position int[] viscont = seqData.getVisibleContigs(); - + /* * Add secondary structure annotations that are added to the annotation track * to the map */ - Map> ssAlignmentAnnotationForSequences - = new HashMap>(); - + Map> ssAlignmentAnnotationForSequences = new HashMap>(); + AlignmentAnnotation[] alignAnnotList = fr.getViewport().getAlignment() - .getAlignmentAnnotation(); - - if(alignAnnotList.length > 0) { - for (AlignmentAnnotation aa: alignAnnotList) { - if (selectedSSSource.equals(aa.label)) { - ssAlignmentAnnotationForSequences.computeIfAbsent( - aa.sequenceRef.getName(), k -> new HashSet<>()) - .add(aa.description); - } - } + .getAlignmentAnnotation(); + + if (alignAnnotList.length > 0) + { + for (AlignmentAnnotation aa : alignAnnotList) + { + if (selectedSSSource.equals(aa.label)) + { + ssAlignmentAnnotationForSequences + .computeIfAbsent(aa.sequenceRef.getName(), + k -> new HashSet<>()) + .add(aa.description); + } + } } - + /* * Get the set of sequences which are not considered for the calculation. * Following sequences are added: @@ -155,8 +165,8 @@ public class SecondaryStructureDistanceModel extends DistanceScoreModel * 2. Sequences whose secondary structure annotations are not added to * the annotation track */ - Set seqsWithUndefinedSS - = findSeqsWithUndefinedSS(seqs, ssAlignmentAnnotationForSequences); + Set seqsWithUndefinedSS = findSeqsWithUndefinedSS(seqs, + ssAlignmentAnnotationForSequences); /* * scan each column, compute and add to each similarity[i, j] @@ -165,15 +175,16 @@ public class SecondaryStructureDistanceModel extends DistanceScoreModel */ for (int vc = 0; vc < viscont.length; vc += 2) { - //Iterates for each column position - for (int cpos = viscont[vc]; cpos <= viscont[vc + 1]; cpos++) + // Iterates for each column position + for (int cpos = viscont[vc]; cpos <= viscont[vc + 1]; cpos++) { - cpwidth++; //used to normalise the similarity score + cpwidth++; // used to normalise the similarity score /* * get set of sequences without gap in the current column */ - Set seqsWithoutGapAtCol = findSeqsWithoutGapAtColumn(seqs, cpos); + Set seqsWithoutGapAtCol = findSeqsWithoutGapAtColumn(seqs, + cpos); /* * calculate similarity score for each secondary structure annotation on i'th and j'th @@ -182,62 +193,68 @@ public class SecondaryStructureDistanceModel extends DistanceScoreModel */ for (int i = 0; i < (noseqs - 1); i++) { - //Iterates for each sequences + // Iterates for each sequences for (int j = i + 1; j < noseqs; j++) { SeqCigar sc1 = seqs[i]; SeqCigar sc2 = seqs[j]; - - //check if ss is defined + // check if ss is defined boolean undefinedSS1 = seqsWithUndefinedSS.contains(sc1); boolean undefinedSS2 = seqsWithUndefinedSS.contains(sc2); // Set similarity to max score if both SS are not defined - if (undefinedSS1 && undefinedSS2) { - similarities[i][j] += ssRateMatrix.getMaximumScore(); - continue; - } - + if (undefinedSS1 && undefinedSS2) + { + similarities[i][j] += ssRateMatrix.getMaximumScore(); + continue; + } + // Set similarity to minimum score if either one SS is not defined - else if(undefinedSS1 || undefinedSS2) { - similarities[i][j] += ssRateMatrix.getMinimumScore(); - continue; + else if (undefinedSS1 || undefinedSS2) + { + similarities[i][j] += ssRateMatrix.getMinimumScore(); + continue; } - - //check if the sequence contains gap in the current column + + // check if the sequence contains gap in the current column boolean gap1 = !seqsWithoutGapAtCol.contains(sc1); - boolean gap2 = !seqsWithoutGapAtCol.contains(sc2); - - //Variable to store secondary structure at the current column + boolean gap2 = !seqsWithoutGapAtCol.contains(sc2); + + // Variable to store secondary structure at the current column char ss1 = '*'; char ss2 = '*'; - - //secondary structure is fetched only if the current column is not - //gap for the sequence - if(!gap1 && !undefinedSS1) { - //fetch the position in sequence for the column and finds the - //corresponding secondary structure annotation - //TO DO - consider based on priority and displayed + + // secondary structure is fetched only if the current column is not + // gap for the sequence + if (!gap1 && !undefinedSS1) + { + // fetch the position in sequence for the column and finds the + // corresponding secondary structure annotation + // TO DO - consider based on priority and displayed int seqPosition = seqs[i].findPosition(cpos); - AlignmentAnnotation[] aa = seqs[i].getRefSeq().getAnnotation(selectedSSSource); - if(aa!=null) - ss1 = - AlignmentUtils.findSSAnnotationForGivenSeqposition(aa[0], seqPosition); + AlignmentAnnotation[] aa = seqs[i].getRefSeq() + .getAnnotation(selectedSSSource); + if (aa != null) + ss1 = AlignmentUtils.findSSAnnotationForGivenSeqposition( + aa[0], seqPosition); } - - if(!gap2 && !undefinedSS2) { + + if (!gap2 && !undefinedSS2) + { int seqPosition = seqs[j].findPosition(cpos); - AlignmentAnnotation[] aa = seqs[j].getRefSeq().getAnnotation(selectedSSSource); - if(aa!=null) - ss2 = - AlignmentUtils.findSSAnnotationForGivenSeqposition(aa[0], seqPosition); - } + AlignmentAnnotation[] aa = seqs[j].getRefSeq() + .getAnnotation(selectedSSSource); + if (aa != null) + ss2 = AlignmentUtils.findSSAnnotationForGivenSeqposition( + aa[0], seqPosition); + } if ((!gap1 && !gap2) || params.includeGaps()) { // Calculate similarity score based on the substitution matrix - double similarityScore = ssRateMatrix.getPairwiseScore(ss1, ss2); + double similarityScore = ssRateMatrix.getPairwiseScore(ss1, + ss2); similarities[i][j] += similarityScore; } } @@ -251,30 +268,30 @@ public class SecondaryStructureDistanceModel extends DistanceScoreModel * and fill in the bottom half of the matrix */ // TODO JAL-2424 cpwidth may be out by 1 - affects scores but not tree shape - + for (int i = 0; i < noseqs; i++) { for (int j = i + 1; j < noseqs; j++) - { + { similarities[i][j] /= cpwidth; similarities[j][i] = similarities[i][j]; } } return ssRateMatrix.similarityToDistance(new Matrix(similarities)); - + } /** - * Builds and returns a set containing sequences (SeqCigar) which do not - * have a gap at the given column position. + * Builds and returns a set containing sequences (SeqCigar) which do not have + * a gap at the given column position. * * @param seqs * @param columnPosition * (0..) * @return */ - private Set findSeqsWithoutGapAtColumn( - SeqCigar[] seqs, int columnPosition) + private Set findSeqsWithoutGapAtColumn(SeqCigar[] seqs, + int columnPosition) { Set seqsWithoutGapAtCol = new HashSet<>(); for (SeqCigar seq : seqs) @@ -284,73 +301,78 @@ public class SecondaryStructureDistanceModel extends DistanceScoreModel { /* * position is not a gap - */ + */ seqsWithoutGapAtCol.add(seq); } } return seqsWithoutGapAtCol; } - /** - * Builds and returns a set containing sequences (SeqCigar) which - * are not considered for the similarity calculation. - * Following sequences are added: - * 1. Sequences without a defined secondary structure from the selected - * source. - * 2. Sequences whose secondary structure annotations are not added to + * Builds and returns a set containing sequences (SeqCigar) which are not + * considered for the similarity calculation. Following sequences are added: + * 1. Sequences without a defined secondary structure from the selected + * source. 2. Sequences whose secondary structure annotations are not added to * the annotation track + * * @param seqs - * @param ssAlignmentAnnotationForSequences + * @param ssAlignmentAnnotationForSequences * @return */ private Set findSeqsWithUndefinedSS(SeqCigar[] seqs, - Map> ssAlignmentAnnotationForSequences) { - Set seqsWithUndefinedSS = new HashSet<>(); - for (SeqCigar seq : seqs) { - if (isSSUndefinedOrNotAdded(seq, ssAlignmentAnnotationForSequences)) { - seqsWithUndefinedSS.add(seq); - } + Map> ssAlignmentAnnotationForSequences) + { + Set seqsWithUndefinedSS = new HashSet<>(); + for (SeqCigar seq : seqs) + { + if (isSSUndefinedOrNotAdded(seq, ssAlignmentAnnotationForSequences)) + { + seqsWithUndefinedSS.add(seq); } - return seqsWithUndefinedSS; + } + return seqsWithUndefinedSS; } - - + /** - * Returns true if a sequence (SeqCigar) should not be - * considered for the similarity calculation. - * Following conditions are checked: - * 1. Sequence without a defined secondary structure from the selected - * source. - * 2. Sequences whose secondary structure annotations are not added to - * the annotation track + * Returns true if a sequence (SeqCigar) should not be considered for the + * similarity calculation. Following conditions are checked: 1. Sequence + * without a defined secondary structure from the selected source. 2. + * Sequences whose secondary structure annotations are not added to the + * annotation track + * * @param seq * @param ssAlignmentAnnotationForSequences * @return */ - private boolean isSSUndefinedOrNotAdded(SeqCigar seq, - Map> ssAlignmentAnnotationForSequences) { - for (String label : Constants.SECONDARY_STRUCTURE_LABELS.keySet()) { - AlignmentAnnotation[] annotations = seq.getRefSeq().getAnnotation(label); - if (annotations != null) { - for (AlignmentAnnotation annotation : annotations) { - HashSet descriptionSet = ssAlignmentAnnotationForSequences - .get(annotation.sequenceRef.getName()); - if (descriptionSet != null) - { - if (descriptionSet.contains(annotation.description)) { - // Secondary structure annotation is present and - //added to the track, no need to add seq - return false; - } - } - } + private boolean isSSUndefinedOrNotAdded(SeqCigar seq, + Map> ssAlignmentAnnotationForSequences) + { + for (String label : Constants.SECONDARY_STRUCTURE_LABELS.keySet()) + { + AlignmentAnnotation[] annotations = seq.getRefSeq() + .getAnnotation(label); + if (annotations != null) + { + for (AlignmentAnnotation annotation : annotations) + { + HashSet descriptionSet = ssAlignmentAnnotationForSequences + .get(annotation.sequenceRef.getName()); + if (descriptionSet != null) + { + if (descriptionSet.contains(annotation.description)) + { + // Secondary structure annotation is present and + // added to the track, no need to add seq + return false; + } } + } } - // Either annotations are undefined or not added to the track - return true; + } + // Either annotations are undefined or not added to the track + return true; } - + @Override public String getName() { @@ -366,7 +388,7 @@ public class SecondaryStructureDistanceModel extends DistanceScoreModel @Override public boolean isDNA() { - return false; + return false; } @Override @@ -374,7 +396,7 @@ public class SecondaryStructureDistanceModel extends DistanceScoreModel { return false; } - + @Override public boolean isSecondaryStructure() { diff --git a/src/jalview/analysis/scoremodels/SimilarityParams.java b/src/jalview/analysis/scoremodels/SimilarityParams.java index 2a25fa8..40a4636 100644 --- a/src/jalview/analysis/scoremodels/SimilarityParams.java +++ b/src/jalview/analysis/scoremodels/SimilarityParams.java @@ -103,7 +103,7 @@ public class SimilarityParams implements SimilarityParamsI private boolean includeGaps; private boolean denominateByShortestLength; - + private String secondaryStructureSource; /** diff --git a/src/jalview/api/AlignViewControllerI.java b/src/jalview/api/AlignViewControllerI.java index 25e4873..098024c 100644 --- a/src/jalview/api/AlignViewControllerI.java +++ b/src/jalview/api/AlignViewControllerI.java @@ -121,7 +121,9 @@ public interface AlignViewControllerI /** * Justify alignment or currently selected region left or right - * @param left - true - means justify left + * + * @param left + * - true - means justify left * @return */ boolean justify_Region(boolean left); diff --git a/src/jalview/api/AlignViewportI.java b/src/jalview/api/AlignViewportI.java index 9624f83..ef4a192 100644 --- a/src/jalview/api/AlignViewportI.java +++ b/src/jalview/api/AlignViewportI.java @@ -85,11 +85,11 @@ public interface AlignViewportI extends ViewStyleI boolean isValidCharWidth(); boolean isShowConsensusHistogram(); - + boolean isShowSSConsensusHistogram(); boolean isShowSequenceLogo(); - + boolean isShowSequenceSSLogo(); boolean isNormaliseSequenceLogo(); @@ -133,9 +133,8 @@ public interface AlignViewportI extends ViewStyleI * @return */ AlignmentAnnotation getAlignmentConsensusAnnotation(); - - AlignmentAnnotation getAlignmentSecondaryStructureConsensusAnnotation(); + AlignmentAnnotation getAlignmentSecondaryStructureConsensusAnnotation(); /** * get the container for alignment gap annotation @@ -182,9 +181,8 @@ public interface AlignViewportI extends ViewStyleI * @param hconsensus */ void setSequenceConsensusHash(ProfilesI hconsensus); - + void setSequenceSSConsensusHash(ProfilesI hSSConsensus); - /** * Set the cDNA complement consensus for the viewport @@ -575,6 +573,7 @@ public interface AlignViewportI extends ViewStyleI * @return */ Iterator getViewAsVisibleContigs(boolean selectedRegionOnly); + /** * notify all concerned that the alignment data has changed and derived data * needs to be recalculated @@ -582,7 +581,8 @@ public interface AlignViewportI extends ViewStyleI public void notifyAlignmentChanged(); /** - * retrieve a matrix associated with the view's alignment's annotation + * retrieve a matrix associated with the view's alignment's annotation + * * @param alignmentAnnotation * @return contact matrix or NULL */ diff --git a/src/jalview/api/analysis/ScoreModelI.java b/src/jalview/api/analysis/ScoreModelI.java index a243c0c..ce415c2 100644 --- a/src/jalview/api/analysis/ScoreModelI.java +++ b/src/jalview/api/analysis/ScoreModelI.java @@ -62,21 +62,18 @@ public interface ScoreModelI // TODO getName, isDNA, isProtein can be static methods in Java 8 - default public boolean isSecondaryStructure() { return false; } /** - * Answers false by default - * Answers true if the data has secondary structure (so should be - * shown in menus in that context) + * Answers false by default Answers true if the data has secondary structure + * (so should be shown in menus in that context) * * @return */ - - + /** * Returns a distance score for the given sequence regions, that is, a matrix * whose value [i][j] is the distance of sequence i from sequence j by some diff --git a/src/jalview/api/analysis/SimilarityParamsI.java b/src/jalview/api/analysis/SimilarityParamsI.java index 43f2866..2558515 100644 --- a/src/jalview/api/analysis/SimilarityParamsI.java +++ b/src/jalview/api/analysis/SimilarityParamsI.java @@ -60,7 +60,7 @@ public interface SimilarityParamsI * @return */ boolean denominateByShortestLength(); - + String getSecondaryStructureSource(); void setSecondaryStructureSource(String secondaryStructureSource); diff --git a/src/jalview/appletgui/AlignFrame.java b/src/jalview/appletgui/AlignFrame.java index 55a5364..b77ee85 100644 --- a/src/jalview/appletgui/AlignFrame.java +++ b/src/jalview/appletgui/AlignFrame.java @@ -3432,8 +3432,8 @@ public class AlignFrame extends EmbmenuFrame implements ActionListener, Menu autoAnnMenu = new Menu( MessageManager.getString("label.autocalculated_annotation")); - Menu selectSS = new Menu( - MessageManager.getString("label.select_secondary_structure_source")); + Menu selectSS = new Menu(MessageManager + .getString("label.select_secondary_structure_source")); showGroupConsensus.addItemListener(this); showGroupConservation.addItemListener(this); showConsensusHistogram.addItemListener(this); diff --git a/src/jalview/bin/Cache.java b/src/jalview/bin/Cache.java index 681394f..6a82e7d 100755 --- a/src/jalview/bin/Cache.java +++ b/src/jalview/bin/Cache.java @@ -1500,11 +1500,10 @@ public class Cache if (customProxySet && // we have a username but no password for the scheme being // requested - (protocol.equalsIgnoreCase("http") - && (httpUser != null - && httpUser.length() > 0 - && (httpPassword == null - || httpPassword.length == 0))) + (protocol.equalsIgnoreCase("http") + && (httpUser != null && httpUser.length() > 0 + && (httpPassword == null + || httpPassword.length == 0))) || (protocol.equalsIgnoreCase("https") && (httpsUser != null && httpsUser.length() > 0 diff --git a/src/jalview/bin/JalviewLite.java b/src/jalview/bin/JalviewLite.java index 7e1296e..2e2dd49 100644 --- a/src/jalview/bin/JalviewLite.java +++ b/src/jalview/bin/JalviewLite.java @@ -2251,8 +2251,8 @@ public class JalviewLite extends Applet PDBEntry[] pdb = new PDBEntry[pdbs.size()]; String[][] chains = new String[pdbs.size()][]; String[] protocols = new String[pdbs.size()]; - for (int pdbsi = 0, - pdbsiSize = pdbs.size(); pdbsi < pdbsiSize; pdbsi++) + for (int pdbsi = 0, pdbsiSize = pdbs + .size(); pdbsi < pdbsiSize; pdbsi++) { Object[] o = (Object[]) pdbs.elementAt(pdbsi); pdb[pdbsi] = (PDBEntry) o[0]; diff --git a/src/jalview/commands/JustifyLeftOrRightCommand.java b/src/jalview/commands/JustifyLeftOrRightCommand.java index 2559662..c1eb655 100644 --- a/src/jalview/commands/JustifyLeftOrRightCommand.java +++ b/src/jalview/commands/JustifyLeftOrRightCommand.java @@ -58,8 +58,8 @@ public class JustifyLeftOrRightCommand extends EditCommand { continue; } - char[] range = seq.getSequence(from, to+1); - if (range==null || range.length==0) + char[] range = seq.getSequence(from, to + 1); + if (range == null || range.length == 0) { continue; } @@ -78,7 +78,7 @@ public class JustifyLeftOrRightCommand extends EditCommand alseq[gapstart + gp] = gc; } - for (int sqp = 0,insp=0; sqp ssSources = new ArrayList(); AlignmentAnnotation[] anns = alignPanel.getAlignment() .getAlignmentAnnotation(); - + ssSources = AlignmentUtils.extractSSSourceInAlignmentAnnotation(anns); - + // Get the currently selected radio button - String selectedButtonModelName = getSelectedRadioButtonDisplayString(ssButtonGroup); - boolean selectedButtonModel = false; - + String selectedButtonModelName = getSelectedRadioButtonDisplayString( + ssButtonGroup); + boolean selectedButtonModel = false; + // Clear existing radio buttons showSS.removeAll(); JRadioButtonMenuItem radioButtonAllSS = new JRadioButtonMenuItem("All"); - radioButtonAllSS.addActionListener(new ActionListener() { + radioButtonAllSS.addActionListener(new ActionListener() + { @Override - public void actionPerformed(ActionEvent e) { - showSS_actionPerformed("All"); + public void actionPerformed(ActionEvent e) + { + showSS_actionPerformed("All"); } }); ssButtonGroup.add(radioButtonAllSS); showSS.add(radioButtonAllSS); - - JRadioButtonMenuItem radioButtonNoneSS = new JRadioButtonMenuItem("None"); - radioButtonNoneSS.addActionListener(new ActionListener() { + + JRadioButtonMenuItem radioButtonNoneSS = new JRadioButtonMenuItem( + "None"); + radioButtonNoneSS.addActionListener(new ActionListener() + { @Override - public void actionPerformed(ActionEvent e) { - showSS_actionPerformed("None"); + public void actionPerformed(ActionEvent e) + { + showSS_actionPerformed("None"); } }); ssButtonGroup.add(radioButtonNoneSS); showSS.add(radioButtonNoneSS); showSS.addSeparator(); - for(String ssSource : ssSources) { - - JRadioButtonMenuItem radioButton = new JRadioButtonMenuItem(ssSource); - radioButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - showSS_actionPerformed(ssSource); - } - }); - ssButtonGroup.add(radioButton); - showSS.add(radioButton); - - // Check if this radio button's name matches the selected radio button's name - if (ssSource.equals(selectedButtonModelName)) { - radioButton.setSelected(true); // Select this radio button - selectedButtonModel = true; + for (String ssSource : ssSources) + { + + JRadioButtonMenuItem radioButton = new JRadioButtonMenuItem(ssSource); + radioButton.addActionListener(new ActionListener() + { + @Override + public void actionPerformed(ActionEvent e) + { + showSS_actionPerformed(ssSource); } - - } + }); + ssButtonGroup.add(radioButton); + showSS.add(radioButton); + + // Check if this radio button's name matches the selected radio button's + // name + if (ssSource.equals(selectedButtonModelName)) + { + radioButton.setSelected(true); // Select this radio button + selectedButtonModel = true; + } - if (selectedButtonModelName == "None") { - // If no radio button was previously selected, select "All" - ssButtonGroup.setSelected(radioButtonNoneSS.getModel(), true); - selectedButtonModel = true; - } - if (!selectedButtonModel) { - // If no radio button was previously selected, select "All" - ssButtonGroup.setSelected(radioButtonAllSS.getModel(), true); - } + } + + if (selectedButtonModelName == "None") + { + // If no radio button was previously selected, select "All" + ssButtonGroup.setSelected(radioButtonNoneSS.getModel(), true); + selectedButtonModel = true; + } + if (!selectedButtonModel) + { + // If no radio button was previously selected, select "All" + ssButtonGroup.setSelected(radioButtonAllSS.getModel(), true); + } } - + @Override - protected void showSS_actionPerformed(String ssSourceSelection){ - + protected void showSS_actionPerformed(String ssSourceSelection) + { AlignmentAnnotation[] annotations = alignPanel.getAlignment() .getAlignmentAnnotation(); - - for (AlignmentAnnotation aa: annotations) { - - for (String label : Constants.SECONDARY_STRUCTURE_LABELS.keySet()) { - - if (label.equals(aa.label)) { - + + for (AlignmentAnnotation aa : annotations) + { + + for (String label : Constants.SECONDARY_STRUCTURE_LABELS.keySet()) + { + + if (label.equals(aa.label)) + { + aa.visible = false; - - if(ssSourceSelection == "All") { + + if (ssSourceSelection == "All") + { aa.visible = true; } - - else { - String ssSource = AlignmentUtils.extractSSSourceFromAnnotationDescription(aa); - if(ssSource.equals(ssSourceSelection)) { + + else + { + String ssSource = AlignmentUtils + .extractSSSourceFromAnnotationDescription(aa); + if (ssSource.equals(ssSourceSelection)) + { aa.visible = true; } - - + } } } - + } - - - List workers = viewport.getCalcManager() - .getRegisteredWorkersOfClass(SecondaryStructureConsensusThread.class); - if (!workers.isEmpty()) { - - viewport.getCalcManager().startWorker(workers.remove(0)); - } - - PaintRefresher.Refresh(this, viewport.getSequenceSetId()); - alignPanel.updateAnnotation(); - alignPanel.paintAlignment(true, true); - - - + List workers = viewport.getCalcManager() + .getRegisteredWorkersOfClass( + SecondaryStructureConsensusThread.class); + if (!workers.isEmpty()) + { + + viewport.getCalcManager().startWorker(workers.remove(0)); + + } + + PaintRefresher.Refresh(this, viewport.getSequenceSetId()); + alignPanel.updateAnnotation(); + alignPanel.paintAlignment(true, true); + } - - protected String getSelectedRadioButtonDisplayString(ButtonGroup ssButtonGroup) { + + protected String getSelectedRadioButtonDisplayString( + ButtonGroup ssButtonGroup) + { Enumeration buttons = ssButtonGroup.getElements(); - while (buttons.hasMoreElements()) { - AbstractButton button = buttons.nextElement(); - if (button.isSelected()) { - return button.getText(); - } + while (buttons.hasMoreElements()) + { + AbstractButton button = buttons.nextElement(); + if (button.isSelected()) + { + return button.getText(); + } } return null; // No radio button is selected -} + } /* * (non-Javadoc) @@ -5862,11 +5887,12 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener, viewport.setShowConsensusHistogram(showConsensusHistogram.getState()); alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState()); } - + @Override protected void showSSConsensusHistogram_actionPerformed(ActionEvent e) { - viewport.setShowSSConsensusHistogram(showSSConsensusHistogram.getState()); + viewport.setShowSSConsensusHistogram( + showSSConsensusHistogram.getState()); alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState()); } diff --git a/src/jalview/gui/AlignViewport.java b/src/jalview/gui/AlignViewport.java index 4e1fcab..f55a10f 100644 --- a/src/jalview/gui/AlignViewport.java +++ b/src/jalview/gui/AlignViewport.java @@ -281,14 +281,14 @@ public class AlignViewport extends AlignmentViewport } showConsensusHistogram = Cache.getDefault("SHOW_CONSENSUS_HISTOGRAM", true); - showSSConsensusHistogram = Cache.getDefault("SHOW_SSCONSENSUS_HISTOGRAM", - true); + showSSConsensusHistogram = Cache + .getDefault("SHOW_SSCONSENSUS_HISTOGRAM", true); showSequenceLogo = Cache.getDefault("SHOW_CONSENSUS_LOGO", true); normaliseSequenceLogo = Cache.getDefault("NORMALISE_CONSENSUS_LOGO", false); showGroupConsensus = Cache.getDefault("SHOW_GROUP_CONSENSUS", false); showConsensus = Cache.getDefault("SHOW_IDENTITY", true); - + showSSConsensus = Cache.getDefault("SHOW_SS_CONSENSUS", false); showOccupancy = Cache.getDefault(Preferences.SHOW_OCCUPANCY, true); diff --git a/src/jalview/gui/AppJmol.java b/src/jalview/gui/AppJmol.java index 4d0de1b..d37c9c0 100644 --- a/src/jalview/gui/AppJmol.java +++ b/src/jalview/gui/AppJmol.java @@ -423,12 +423,13 @@ public class AppJmol extends StructureViewerBase public boolean isRepainting() { - if (renderPanel!=null && renderPanel.isVisible()) + if (renderPanel != null && renderPanel.isVisible()) { return renderPanel.repainting; } return false; } + /** * Outputs the Jmol viewer image as an image file, after prompting the user to * choose a file and (for EPS) choice of Text or Lineart character rendering @@ -441,10 +442,12 @@ public class AppJmol extends StructureViewerBase { while (!isRepainting()) { - try { + try + { Thread.sleep(2); } catch (Exception q) - {} + { + } } try { @@ -642,17 +645,18 @@ public class AppJmol extends StructureViewerBase } else { - repainting=true; + repainting = true; synchronized (jmb) { jmb.jmolViewer.renderScreenImage(g, currentSize.width, currentSize.height); - + } - repainting=false; + repainting = false; } } - volatile boolean repainting=false; + + volatile boolean repainting = false; } @Override diff --git a/src/jalview/gui/CalculationChooser.java b/src/jalview/gui/CalculationChooser.java index 4d5823a..711cac8 100644 --- a/src/jalview/gui/CalculationChooser.java +++ b/src/jalview/gui/CalculationChooser.java @@ -282,7 +282,8 @@ public class CalculationChooser extends JPanel ButtonGroup calcTypes = new ButtonGroup(); calcTypes.add(pca); - if (!Platform.isJS()) { + if (!Platform.isJS()) + { // FIXME JAL-4443 calcTypes.add(pasimap); } @@ -643,8 +644,10 @@ public class CalculationChooser extends JPanel * * @param nucleotide * @param forPca - * @param ssPresent - include secondary structure similarity model - * @param forPasimap - limit to ScoreMatrix based models - allows use of AlignSeq + * @param ssPresent + * - include secondary structure similarity model + * @param forPasimap + * - limit to ScoreMatrix based models - allows use of AlignSeq * @return */ protected static List getApplicableScoreModels( @@ -656,7 +659,7 @@ public class CalculationChooser extends JPanel ScoreModels scoreModels = ScoreModels.getInstance(); for (ScoreModelI sm : scoreModels.getModels()) { - if ((!forPasimap || sm instanceof ScoreMatrix) + if ((!forPasimap || sm instanceof ScoreMatrix) && (!nucleotide && sm.isProtein() || nucleotide && sm.isDNA() || sm.isSecondaryStructure() && ssPresent)) diff --git a/src/jalview/gui/CutAndPasteTransfer.java b/src/jalview/gui/CutAndPasteTransfer.java index 299af6b..10aa229 100644 --- a/src/jalview/gui/CutAndPasteTransfer.java +++ b/src/jalview/gui/CutAndPasteTransfer.java @@ -94,13 +94,14 @@ public class CutAndPasteTransfer extends GCutAndPasteTransfer /** * set font size of the textarea + * * @param size */ public void setFont(Font font) { textarea.setFont(font); } - + /** * DOCUMENT ME! */ @@ -217,11 +218,12 @@ public class CutAndPasteTransfer extends GCutAndPasteTransfer { } } - + /** - * show menu for changing the font - * @param e - */ + * show menu for changing the font + * + * @param e + */ @Override public void fontSizeMenu_actionPerformed(ActionEvent e) { diff --git a/src/jalview/gui/Desktop.java b/src/jalview/gui/Desktop.java index c144268..9c542a3 100644 --- a/src/jalview/gui/Desktop.java +++ b/src/jalview/gui/Desktop.java @@ -2945,11 +2945,11 @@ public class Desktop extends jalview.jbgui.GDesktop if (progressBars.get(Long.valueOf(id)) == null) return null; - + for (Component c : progressBars.get(Long.valueOf(id)).getComponents()) { if (c.getClass() == JProgressBar.class) - return (JProgressBar) c; + return (JProgressBar) c; } return null; } diff --git a/src/jalview/gui/FontChooser.java b/src/jalview/gui/FontChooser.java index 853d4aa..1ec4881 100755 --- a/src/jalview/gui/FontChooser.java +++ b/src/jalview/gui/FontChooser.java @@ -113,8 +113,9 @@ public class FontChooser extends GFontChooser /** * Creates a new FontChooser for a CutAndPasteTransfer + * * @param cap - */ + */ public FontChooser(CutAndPasteTransfer cap) { oldFont = new Font("Monospaced", Font.PLAIN, 12); @@ -131,7 +132,7 @@ public class FontChooser extends GFontChooser if (!isCapFont()) { smoothFont.setSelected(ap.av.antiAlias); - + /* * Enable 'scale protein as cDNA' in a SplitFrame view. The selection is * stored in the ViewStyle of both dna and protein Viewport. Also enable @@ -289,6 +290,7 @@ public class FontChooser extends GFontChooser { return cap != null; } + /** * DOCUMENT ME! */ diff --git a/src/jalview/gui/PaSiMapPanel.java b/src/jalview/gui/PaSiMapPanel.java index 702c4f4..7926efc 100644 --- a/src/jalview/gui/PaSiMapPanel.java +++ b/src/jalview/gui/PaSiMapPanel.java @@ -101,12 +101,12 @@ public class PaSiMapPanel extends GPaSiMapPanel */ public PaSiMapPanel(AlignmentPanel alignPanel, String modelName) { - super(8); // dim = 8 + super(8); // dim = 8 this.av = alignPanel.av; this.ap = alignPanel; boolean nucleotide = av.getAlignment().isNucleotide(); - //progressBar = new ProgressBar(statusPanel, statusBar); + // progressBar = new ProgressBar(statusPanel, statusBar); addInternalFrameListener(new InternalFrameAdapter() { @@ -131,8 +131,7 @@ public class PaSiMapPanel extends GPaSiMapPanel ScoreModelI scoreModel = ScoreModels.getInstance() .getScoreModel(modelName, ap); - setPasimapModel( - new PaSiMapModel(av, seqs, nucleotide, scoreModel)); + setPasimapModel(new PaSiMapModel(av, seqs, nucleotide, scoreModel)); PaintRefresher.Register(this, av.getSequenceSetId()); setRotatableCanvas(new RotatableCanvas(alignPanel)); @@ -143,8 +142,8 @@ public class PaSiMapPanel extends GPaSiMapPanel } /** - * Ensure references to potentially very large objects (the PaSiMap matrices) are - * nulled when the frame is closed + * Ensure references to potentially very large objects (the PaSiMap matrices) + * are nulled when the frame is closed */ protected void close_actionPerformed() { @@ -193,29 +192,31 @@ public class PaSiMapPanel extends GPaSiMapPanel progressBar.setProgressBar(message, progId); try { - SequenceGroup selGroup=av.getSelectionGroup(); - - if (selGroup==null) + SequenceGroup selGroup = av.getSelectionGroup(); + + if (selGroup == null) { selGroup = new SequenceGroup(av.getAlignment().getSequences()); selGroup.setStartRes(0); - selGroup.setEndRes(av.getAlignment().getWidth()-1); + selGroup.setEndRes(av.getAlignment().getWidth() - 1); } - - if (selGroup.getSize()>MAX_PASIMAP_SEQ) + + if (selGroup.getSize() > MAX_PASIMAP_SEQ) { - int start = selGroup.getStartRes(),end=selGroup.getEndRes(); - selGroup = new SequenceGroup(selGroup.getSequences().subList(0, MAX_PASIMAP_SEQ)); - selGroup.setStartRes(start); - selGroup.setEndRes(end); - Console.warn("Truncated input sequences for PASIMAP analysis to "+MAX_PASIMAP_SEQ); + int start = selGroup.getStartRes(), end = selGroup.getEndRes(); + selGroup = new SequenceGroup( + selGroup.getSequences().subList(0, MAX_PASIMAP_SEQ)); + selGroup.setStartRes(start); + selGroup.setEndRes(end); + Console.warn("Truncated input sequences for PASIMAP analysis to " + + MAX_PASIMAP_SEQ); } - + PairwiseAlignPanel pap = new PairwiseAlignPanel(av, selGroup, true, GAP_OPEN_COST, GAP_EXTEND_COST, false, null); pap.setDiscardAlignments(true); pap.setQuiet(true); - + System.out.println(pap != null); setPairwiseAlignPanel(pap); getPasimapModel().calculate(pap); @@ -241,9 +242,9 @@ public class PaSiMapPanel extends GPaSiMapPanel repaint(); if (getParent() == null) { - Desktop.addInternalFrame( - this, MessageManager.formatMessage("label.calc_title", - "PaSiMap", ap.alignFrame.getTitle()), + Desktop.addInternalFrame(this, + MessageManager.formatMessage("label.calc_title", "PaSiMap", + ap.alignFrame.getTitle()), 475, 450); this.setMinimumSize(new Dimension(MIN_WIDTH, MIN_HEIGHT)); } @@ -251,8 +252,8 @@ public class PaSiMapPanel extends GPaSiMapPanel } /** - * Updates the PaSiMap display after a change of component to use for x, y or z - * axis + * Updates the PaSiMap display after a change of component to use for x, y or + * z axis */ @Override protected void doDimensionChange() @@ -270,8 +271,8 @@ public class PaSiMapPanel extends GPaSiMapPanel } /** - * Sets the selected checkbox item index for PaSiMap dimension (1, 2, 3...) for - * the given axis (X/Y/Z) + * Sets the selected checkbox item index for PaSiMap dimension (1, 2, 3...) + * for the given axis (X/Y/Z) * * @param index * @param axis @@ -323,8 +324,8 @@ public class PaSiMapPanel extends GPaSiMapPanel } /** - * If available, shows the data which formed the inputs for the PaSiMap as a new - * alignment + * If available, shows the data which formed the inputs for the PaSiMap as a + * new alignment */ @Override public void originalSeqData_actionPerformed() @@ -452,7 +453,7 @@ public class PaSiMapPanel extends GPaSiMapPanel } } - public void makePaSiMapImage(ImageMaker.TYPE type) throws Exception + public void makePaSiMapImage(ImageMaker.TYPE type) throws Exception { int width = getRotatableCanvas().getWidth(); int height = getRotatableCanvas().getHeight(); @@ -612,7 +613,8 @@ public class PaSiMapPanel extends GPaSiMapPanel { cap.setText(getPasimapModel().getAlignmentOutput()); Desktop.addInternalFrame(cap, MessageManager.formatMessage( - "label.pairwise_alignment_for_params", new String[] { this.getTitle() }), 500, 500); + "label.pairwise_alignment_for_params", new String[] + { this.getTitle() }), 500, 500); } catch (OutOfMemoryError oom) { new OOMWarning("exporting pairwise alignments", oom); @@ -680,7 +682,7 @@ public class PaSiMapPanel extends GPaSiMapPanel public void updateProgressBar(int lengthOfTask, int progress) { JProgressBar pBar = progressBar.getProgressBar(progId); - if (pBar==null) + if (pBar == null) { return; } @@ -692,22 +694,24 @@ public class PaSiMapPanel extends GPaSiMapPanel } updateProgressBar(progress); } + public void updateProgressBar(int progress) { JProgressBar pBar = progressBar.getProgressBar(progId); - - if (pBar==null) + + if (pBar == null) { return; } - + pBar.setValue(progress); pBar.repaint(); } /** - * adds a listener for a pairwise alignment panel's progress - * TODO: generalise for anything that can report progress ? + * adds a listener for a pairwise alignment panel's progress TODO: generalise + * for anything that can report progress ? + * * @param pap */ public void setPairwiseAlignPanel(PairwiseAlignPanel pap) @@ -794,8 +798,8 @@ public class PaSiMapPanel extends GPaSiMapPanel } /** - * Answers the selected checkbox item index for PaSiMap dimension for the X, Y or - * Z axis of the display + * Answers the selected checkbox item index for PaSiMap dimension for the X, Y + * or Z axis of the display * * @param axis * @return diff --git a/src/jalview/gui/PairwiseAlignPanel.java b/src/jalview/gui/PairwiseAlignPanel.java index 3e8fb02..77ec0f5 100755 --- a/src/jalview/gui/PairwiseAlignPanel.java +++ b/src/jalview/gui/PairwiseAlignPanel.java @@ -47,7 +47,7 @@ public class PairwiseAlignPanel extends GPairwiseAlignPanel private float[][] scores; - private float[][] alignmentScores; // scores used by PaSiMap + private float[][] alignmentScores; // scores used by PaSiMap private int GAP_OPEN_COST; @@ -60,7 +60,7 @@ public class PairwiseAlignPanel extends GPairwiseAlignPanel private String alignmentOutput; private boolean quiet; - + private boolean discardAlignments; private boolean endGaps; @@ -73,12 +73,13 @@ public class PairwiseAlignPanel extends GPairwiseAlignPanel private int total; private int progress; - + private SequenceGroup selection; + /** * input sequences */ - private SequenceI[] seqs=null; + private SequenceI[] seqs = null; private ScoreMatrix scoreMatrix; @@ -87,23 +88,31 @@ public class PairwiseAlignPanel extends GPairwiseAlignPanel * * @param viewport * contains selected sequences to align - * @param endGaps ~ toggle gaps and the beginning and end of sequences + * @param endGaps + * ~ toggle gaps and the beginning and end of sequences */ public PairwiseAlignPanel(AlignmentViewport viewport) { - this(viewport, null, false, 120, 20, true, null); // default penalties used in AlignSeq + this(viewport, null, false, 120, 20, true, null); // default penalties used + // in AlignSeq } + public PairwiseAlignPanel(AlignmentViewport viewport, ScoreMatrix params) { - this(viewport, null, false, 120, 20, true,params); // default penalties used in AlignSeq + this(viewport, null, false, 120, 20, true, params); // default penalties + // used in AlignSeq } - public PairwiseAlignPanel(AlignmentViewport viewport, boolean endGaps, int gapOpenCost, int gapExtendCost) + + public PairwiseAlignPanel(AlignmentViewport viewport, boolean endGaps, + int gapOpenCost, int gapExtendCost) { this(viewport, null, endGaps, gapOpenCost, gapExtendCost, true, null); } /** - * Create a new pairwise alignpanel with specified parameters and score model, and optionally start the calculation + * Create a new pairwise alignpanel with specified parameters and score model, + * and optionally start the calculation + * * @param viewport * @param selection * @param endGaps @@ -112,8 +121,9 @@ public class PairwiseAlignPanel extends GPairwiseAlignPanel * @param run * @param scoreMatrix */ - public PairwiseAlignPanel(AlignmentViewport viewport, SequenceGroup selection, boolean endGaps, - int gapOpenCost, int gapExtendCost, boolean run, ScoreMatrix scoreMatrix) + public PairwiseAlignPanel(AlignmentViewport viewport, + SequenceGroup selection, boolean endGaps, int gapOpenCost, + int gapExtendCost, boolean run, ScoreMatrix scoreMatrix) { super(); this.av = viewport; @@ -123,23 +133,25 @@ public class PairwiseAlignPanel extends GPairwiseAlignPanel this.selection = selection; this.total = MiscMath.combinations(av.getAlignment().getHeight(), 2); this.scoreMatrix = scoreMatrix; - if (run) { + if (run) + { calculate(); } } - + public void calculate() { calculate(scoreMatrix); } - public void calculate (ScoreMatrix sm) + + public void calculate(ScoreMatrix sm) { StringBuilder sb = new StringBuilder(1024); sequences = new Vector(); String[] seqStrings; - seqs=null; + seqs = null; if (selection != null) { @@ -169,7 +181,7 @@ public class PairwiseAlignPanel extends GPairwiseAlignPanel seqs = av.getAlignment().getSequencesArray(); } } - + String type = (av.getAlignment().isNucleotide()) ? AlignSeq.DNA : AlignSeq.PEP; @@ -177,7 +189,7 @@ public class PairwiseAlignPanel extends GPairwiseAlignPanel float[][] alignmentScores = new float[seqs.length][seqs.length]; double totscore = 0D; int count = seqs.length; - + boolean first = true; progress = 0; @@ -192,11 +204,12 @@ public class PairwiseAlignPanel extends GPairwiseAlignPanel AlignSeq as = new AlignSeq(seqs[i], seqStrings[i], seqs[j], seqStrings[j], type, GAP_OPEN_COST, GAP_EXTEND_COST); - if (sm != null) { - as.setScoreMatrix(sm); - } + if (sm != null) + { + as.setScoreMatrix(sm); + } - if (as.s1str.length() == 0 || as.s2str.length() == 0) + if (as.s1str.length() == 0 || as.s2str.length() == 0) { continue; } @@ -219,7 +232,8 @@ public class PairwiseAlignPanel extends GPairwiseAlignPanel sb.append(DASHES); } first = false; - if (!discardAlignments) { + if (!discardAlignments) + { as.printAlignment(System.out); } scores[i][j] = as.getMaxScore() / as.getASeq1().length; @@ -243,7 +257,7 @@ public class PairwiseAlignPanel extends GPairwiseAlignPanel this.scores = scores; this.alignmentScores = alignmentScores; - if (count > 2 && !quiet) + if (count > 2 && !quiet) { printScoreMatrix(seqs, scores, totscore); } @@ -344,24 +358,29 @@ public class PairwiseAlignPanel extends GPairwiseAlignPanel { return progress; } + public SequenceI[] getInputSequences() { return seqs; } + /** - * Set to true to suppress output of progress to Console.stdout or GUI - * @param quiet + * Set to true to suppress output of progress to Console.stdout or GUI + * + * @param quiet */ public void setQuiet(boolean quiet) { - this.quiet=quiet; + this.quiet = quiet; } + /** * set this if you are only interested in final alignment scores + * * @param discard */ public void setDiscardAlignments(boolean discard) { - discardAlignments=discard; + discardAlignments = discard; } } diff --git a/src/jalview/gui/PopupMenu.java b/src/jalview/gui/PopupMenu.java index 09cd9a0..f4dd579 100644 --- a/src/jalview/gui/PopupMenu.java +++ b/src/jalview/gui/PopupMenu.java @@ -1764,28 +1764,30 @@ public class PopupMenu extends JPopupMenu implements ColourChangeListener { final AlignmentI alignment = this.ap.getAlignment(); AlignmentUtils.addReferenceAnnotations(candidates, alignment, null); - - if(AlignmentUtils.isSSAnnotationPresent(candidates)) { + + if (AlignmentUtils.isSSAnnotationPresent(candidates)) + { restartSSConsensusWorker(); } - + refresh(); } - - - private void restartSSConsensusWorker() { - - List workers = ap.alignFrame.getViewport().getCalcManager() - .getRegisteredWorkersOfClass(SecondaryStructureConsensusThread.class); - if (!workers.isEmpty()) { - - ap.alignFrame.getViewport().getCalcManager().startWorker(workers.remove(0)); - - } - + + private void restartSSConsensusWorker() + { + + List workers = ap.alignFrame.getViewport() + .getCalcManager().getRegisteredWorkersOfClass( + SecondaryStructureConsensusThread.class); + if (!workers.isEmpty()) + { + + ap.alignFrame.getViewport().getCalcManager() + .startWorker(workers.remove(0)); + + } + } - - protected void makeReferenceSeq_actionPerformed(ActionEvent actionEvent) { diff --git a/src/jalview/gui/ProgressBar.java b/src/jalview/gui/ProgressBar.java index 73cd496..9d2cb2c 100644 --- a/src/jalview/gui/ProgressBar.java +++ b/src/jalview/gui/ProgressBar.java @@ -274,7 +274,7 @@ public class ProgressBar implements IProgressIndicator public JProgressBar getProgressBar(long id) { Container progBar = progressBars.get(id); - if (progBar==null || progBar.getComponentCount()==0) + if (progBar == null || progBar.getComponentCount() == 0) { return null; } diff --git a/src/jalview/gui/RotatableCanvas.java b/src/jalview/gui/RotatableCanvas.java index 5261b23..03d8d87 100755 --- a/src/jalview/gui/RotatableCanvas.java +++ b/src/jalview/gui/RotatableCanvas.java @@ -119,10 +119,13 @@ public class RotatableCanvas extends JPanel private Point[] axisEndPoints; // fields for 'select rectangle' (JAL-1124) - int rectx1; - int recty1; - int rectx2; - int recty2; + int rectx1; + + int recty1; + + int rectx2; + + int recty2; AlignmentViewport av; @@ -405,11 +408,12 @@ public class RotatableCanvas extends JPanel } } // //Now the rectangle - if (rectx2 != -1 && recty2 != -1) { - g.setColor(Color.white); - - g.drawRect(rectx1,recty1,rectx2-rectx1,recty2-recty1); - } + if (rectx2 != -1 && recty2 != -1) + { + g.setColor(Color.white); + + g.drawRect(rectx1, recty1, rectx2 - rectx1, recty2 - recty1); + } } /** @@ -566,10 +570,10 @@ public class RotatableCanvas extends JPanel mouseX = x; mouseY = y; - rectx1 = x; - recty1 = y; - rectx2 = -1; - recty2 = -1; + rectx1 = x; + recty1 = y; + rectx2 = -1; + recty2 = -1; SequenceI found = findSequenceAtPoint(x, y); @@ -634,12 +638,12 @@ public class RotatableCanvas extends JPanel // Check if this is a rectangle drawing drag if ((evt.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0) { - rectx2 = evt.getX(); - recty2 = evt.getY(); - if ((rectx2 != -1) && (recty2 != -1)) - { - rectSelect(rectx1, recty1, rectx2, recty2); - } + rectx2 = evt.getX(); + recty2 = evt.getY(); + if ((rectx2 != -1) && (recty2 != -1)) + { + rectSelect(rectx1, recty1, rectx2, recty2); + } } else { @@ -649,7 +653,7 @@ public class RotatableCanvas extends JPanel mouseY = yPos; // findWidths(); } - repaint(); + repaint(); } @Override @@ -753,12 +757,10 @@ public class RotatableCanvas extends JPanel { SequencePoint sp = sequencePoints.get(i); int tmp1 = (int) (((sp.coord.x - centre[0]) * getScaleFactor()) - * (getWidth() / 3.15) - + (getWidth() / 2.0)); + * (getWidth() / 3.15) + (getWidth() / 2.0)); float pre1 = ((sp.coord.x - centre[0]) * getScaleFactor()); int tmp2 = (int) (((sp.coord.y - centre[1]) * getScaleFactor()) - * (getHeight() / 1.70) - + (getHeight() / 2.0)); + * (getHeight() / 1.70) + (getHeight() / 2.0)); float pre2 = ((sp.coord.y - centre[1]) * getScaleFactor()); if ((tmp1 > x1) && (tmp1 < x2) && (tmp2 > y1) && (tmp2 < y2)) diff --git a/src/jalview/gui/StructureChooser.java b/src/jalview/gui/StructureChooser.java index 9658a92..ce043fe 100644 --- a/src/jalview/gui/StructureChooser.java +++ b/src/jalview/gui/StructureChooser.java @@ -1347,8 +1347,9 @@ public class StructureChooser extends GStructureChooser String pdbFilename = selectedPdbFileName; // TODO - tidy up this ugly hack so we call launchStructureViewer too StructureChooser.openStructureFileForSequence(ssm, sc, ap, - selectedSequence, true, pdbFilename, tft, paeFilename,false, - true,false,getTargetedStructureViewer(ssm).getViewerType()); + selectedSequence, true, pdbFilename, tft, paeFilename, + false, true, false, + getTargetedStructureViewer(ssm).getViewerType()); } SwingUtilities.invokeLater(new Runnable() { @@ -1820,7 +1821,9 @@ public class StructureChooser extends GStructureChooser * @param forceHeadless * @param showRefAnnotations * @param doXferSettings - * @param viewerType - when not null means the viewer will be opened, providing forceHeadless/headless is not true + * @param viewerType + * - when not null means the viewer will be opened, providing + * forceHeadless/headless is not true * @return */ public static StructureViewer openStructureFileForSequence( @@ -1845,7 +1848,7 @@ public class StructureChooser extends GStructureChooser ssm = ap.getStructureSelectionManager(); StructureSelectionManager.doConfigureStructurePrefs(ssm); } - + PDBEntry fileEntry = new AssociatePdbFileWithSeq().associatePdbWithSeq( sFilename, DataSourceType.FILE, seq, prompt, Desktop.instance, tft, paeFilename, doXferSettings); @@ -1863,7 +1866,8 @@ public class StructureChooser extends GStructureChooser sc.mainFrame.dispose(); - // TODO should honor preferences - only show reference annotation that is requested - JAL-4415 JAL-3124 + // TODO should honor preferences - only show reference annotation that is + // requested - JAL-4415 JAL-3124 if (showRefAnnotations) { showReferenceAnnotationsForSequence(ap.alignFrame, seq); diff --git a/src/jalview/gui/structurechooser/ThreeDBStructureChooserQuerySource.java b/src/jalview/gui/structurechooser/ThreeDBStructureChooserQuerySource.java index 333f995..2bd5a91 100644 --- a/src/jalview/gui/structurechooser/ThreeDBStructureChooserQuerySource.java +++ b/src/jalview/gui/structurechooser/ThreeDBStructureChooserQuerySource.java @@ -426,8 +426,9 @@ public class ThreeDBStructureChooserQuerySource String modelPage = humanUrl < 1 ? null : (String) restable.getValueAt(row, humanUrl); - String modelCategory = idx_mcat < 1 ? null :(String) restable.getValueAt(row,idx_mcat); - + String modelCategory = idx_mcat < 1 ? null + : (String) restable.getValueAt(row, idx_mcat); + String strucFormat = restable.getValueAt(row, modelformat).toString(); SequenceI selectedSeq = (SequenceI) restable.getValueAt(row, diff --git a/src/jalview/jbgui/GAlignFrame.java b/src/jalview/jbgui/GAlignFrame.java index 2a79908..687c22b 100755 --- a/src/jalview/jbgui/GAlignFrame.java +++ b/src/jalview/jbgui/GAlignFrame.java @@ -198,7 +198,7 @@ public class GAlignFrame extends JInternalFrame protected JMenuItem gatherViews = new JMenuItem(); protected JMenuItem expandViews = new JMenuItem(); - + protected JCheckBoxMenuItem threeDStructure = new JCheckBoxMenuItem(); protected JCheckBoxMenuItem jPred = new JCheckBoxMenuItem(); @@ -207,7 +207,7 @@ public class GAlignFrame extends JInternalFrame protected JCheckBoxMenuItem showGroupConservation = new JCheckBoxMenuItem(); - protected JCheckBoxMenuItem showConsensusHistogram = new JCheckBoxMenuItem(); + protected JCheckBoxMenuItem showConsensusHistogram = new JCheckBoxMenuItem(); protected JCheckBoxMenuItem showSSConsensusHistogram = new JCheckBoxMenuItem(); @@ -889,7 +889,7 @@ public class GAlignFrame extends JInternalFrame showConsensusHistogram_actionPerformed(e); } - }); + }); showSSConsensusHistogram.setText( MessageManager.getString("label.show_ssconsensus_histogram")); showSSConsensusHistogram.addActionListener(new ActionListener() @@ -1807,8 +1807,6 @@ public class GAlignFrame extends JInternalFrame }; addMenuActionAndAccelerator(keyStroke, copyHighlighted, al); copyHighlighted.addActionListener(al); - - ButtonGroup ssButtonGroup = new ButtonGroup(); final JRadioButtonMenuItem showAll = new JRadioButtonMenuItem( @@ -1850,18 +1848,22 @@ public class GAlignFrame extends JInternalFrame MessageManager.getString("label.autocalculated_annotation")); JMenu showSS = new JMenu( - MessageManager.getString("label.show_secondary_structure")); - - showSS.addMouseListener(new MouseAdapter() { - + MessageManager.getString("label.show_secondary_structure")); + + showSS.addMouseListener(new MouseAdapter() + { + @Override - public void mouseEntered(MouseEvent e) { + public void mouseEntered(MouseEvent e) + { + + updateShowSSRadioButtons(showSS, ssButtonGroup); // Update radio buttons + // every time the menu + // is clicked - updateShowSSRadioButtons(showSS, ssButtonGroup); // Update radio buttons every time the menu is clicked - } }); - + JMenu exportImageMenu = new JMenu( MessageManager.getString("label.export_image")); JMenu fileMenu = new JMenu(MessageManager.getString("action.file")); @@ -2304,7 +2306,7 @@ public class GAlignFrame extends JInternalFrame // TODO Auto-generated method stub } - + protected void showSSConsensusHistogram_actionPerformed(ActionEvent e) { // TODO Auto-generated method stub @@ -2887,6 +2889,6 @@ public class GAlignFrame extends JInternalFrame protected void showSS_actionPerformed(String ssSourceSelection) { // TODO Auto-generated method stub - + } } diff --git a/src/jalview/jbgui/GCutAndPasteTransfer.java b/src/jalview/jbgui/GCutAndPasteTransfer.java index 5daea78..106ad7c 100755 --- a/src/jalview/jbgui/GCutAndPasteTransfer.java +++ b/src/jalview/jbgui/GCutAndPasteTransfer.java @@ -198,7 +198,7 @@ public class GCutAndPasteTransfer extends JInternalFrame @Override public void actionPerformed(ActionEvent e) { - fontSizeMenu_actionPerformed(e); + fontSizeMenu_actionPerformed(e); } }); copyItem.setText(MessageManager.getString("action.copy")); @@ -256,6 +256,7 @@ public class GCutAndPasteTransfer extends JInternalFrame /** * shows a menu for changing the font + * * @param e */ public void fontSizeMenu_actionPerformed(ActionEvent e) diff --git a/src/jalview/jbgui/GPCAPanel.java b/src/jalview/jbgui/GPCAPanel.java index ec5b209..65394ed 100755 --- a/src/jalview/jbgui/GPCAPanel.java +++ b/src/jalview/jbgui/GPCAPanel.java @@ -85,6 +85,7 @@ public class GPCAPanel extends JInternalFrame zCombobox.addItem("dim " + i); } } + public GPCAPanel(int dim) { try diff --git a/src/jalview/jbgui/GPaSiMapPanel.java b/src/jalview/jbgui/GPaSiMapPanel.java index 369a005..3c7fb5a 100755 --- a/src/jalview/jbgui/GPaSiMapPanel.java +++ b/src/jalview/jbgui/GPaSiMapPanel.java @@ -85,6 +85,7 @@ public class GPaSiMapPanel extends JInternalFrame zCombobox.addItem("dim " + i); } } + public GPaSiMapPanel(int dim) { try @@ -223,8 +224,8 @@ public class GPaSiMapPanel extends JInternalFrame } }); JMenuItem outputAlignment = new JMenuItem(); - outputAlignment.setText( - MessageManager.getString("label.output_alignment")); + outputAlignment + .setText(MessageManager.getString("label.output_alignment")); outputAlignment.addActionListener(new ActionListener() { @Override diff --git a/src/jalview/jbgui/GPreferences.java b/src/jalview/jbgui/GPreferences.java index e574327..c644e3c 100755 --- a/src/jalview/jbgui/GPreferences.java +++ b/src/jalview/jbgui/GPreferences.java @@ -160,7 +160,7 @@ public class GPreferences extends JPanel protected JCheckBox conservation = new JCheckBox(); - protected JCheckBox identity = new JCheckBox(); + protected JCheckBox identity = new JCheckBox(); protected JCheckBox ssConsensus = new JCheckBox(); diff --git a/src/jalview/math/Matrix.java b/src/jalview/math/Matrix.java index 7ae4b94..f767444 100755 --- a/src/jalview/math/Matrix.java +++ b/src/jalview/math/Matrix.java @@ -123,12 +123,12 @@ public class Matrix implements MatrixI if (row != null) { value[i] = new double[row.length]; - int j = 0; - for (float oldValue : row) - { - value[i][j] = oldValue; - j++; - } + int j = 0; + for (float oldValue : row) + { + value[i][j] = oldValue; + j++; + } } i++; } @@ -191,10 +191,11 @@ public class Matrix implements MatrixI */ for (int k = 0; k < in.width(); k++) { - if (!Double.isNaN(in.getValue(i,k)) && !Double.isNaN(this.value[k][j])) - { + if (!Double.isNaN(in.getValue(i, k)) + && !Double.isNaN(this.value[k][j])) + { tmp[i][j] += (in.getValue(i, k) * this.value[k][j]); - } + } } } } @@ -833,10 +834,10 @@ public class Matrix implements MatrixI } /** - * returns the matrix as a double[][] array - * - * @return - */ + * returns the matrix as a double[][] array + * + * @return + */ @Override public double[][] asArray() { @@ -1018,7 +1019,8 @@ public class Matrix implements MatrixI /** * Add d to all entries of this matrix * - * @param d ~ value to add + * @param d + * ~ value to add */ @Override public void add(double d) @@ -1086,7 +1088,7 @@ public class Matrix implements MatrixI } /** - * Returns a copy in which every value in the matrix is its absolute + * Returns a copy in which every value in the matrix is its absolute * * @return */ @@ -1122,7 +1124,7 @@ public class Matrix implements MatrixI { if (row != null) { - mean[i++] = MiscMath.mean(row); + mean[i++] = MiscMath.mean(row); } } return mean; @@ -1142,17 +1144,17 @@ public class Matrix implements MatrixI double[] column = getColumn(j); if (column != null) { - mean[j] = MiscMath.mean(column); + mean[j] = MiscMath.mean(column); } } return mean; } /** - * return a flattened matrix containing the sum of each column - * - * @return - */ + * return a flattened matrix containing the sum of each column + * + * @return + */ @Override public double[] sumCol() { @@ -1162,17 +1164,17 @@ public class Matrix implements MatrixI double[] column = getColumn(j); if (column != null) { - sum[j] = MiscMath.sum(column); + sum[j] = MiscMath.sum(column); } - } + } return sum; } /** - * returns the mean value of the complete matrix - * - * @return - */ + * returns the mean value of the complete matrix + * + * @return + */ @Override public double mean() { @@ -1182,47 +1184,51 @@ public class Matrix implements MatrixI { for (double col : row) { - if (!Double.isNaN(col)) - { - sum += col; - } else { - nanCount++; - } + if (!Double.isNaN(col)) + { + sum += col; + } + else + { + nanCount++; + } } } return sum / (double) (this.rows * this.cols - nanCount); } /** - * fills up a diagonal matrix with its transposed copy - * !other side should be filled with 0 - * !keeps Double.NaN found in either side - * - * TODO check on which side it was diagonal and only do calculations for the other side - */ + * fills up a diagonal matrix with its transposed copy !other side should be + * filled with 0 !keeps Double.NaN found in either side + * + * TODO check on which side it was diagonal and only do calculations for the + * other side + */ @Override public void fillDiagonal() { int n = this.rows; int m = this.cols; - MatrixI copy = this.transpose(); // goes through each element in the matrix and - for (int i = 0; i < n; i++) // adds the value in the transposed copy to the original value + MatrixI copy = this.transpose(); // goes through each element in the matrix + // and + for (int i = 0; i < n; i++) // adds the value in the transposed copy to the + // original value { for (int j = 0; j < m; j++) { - if (i != j) - { - this.addValue(i, j, copy.getValue(i,j)); - } + if (i != j) + { + this.addValue(i, j, copy.getValue(i, j)); + } } } } /** - * counts the number of Double.NaN in the matrix - * - * @return - */ + * counts the number of Double.NaN in the matrix + * + * @return + */ @Override public int countNaN() { @@ -1231,117 +1237,139 @@ public class Matrix implements MatrixI { for (int j = 0; j < this.cols; j++) { - if (Double.isNaN(this.getValue(i,j))) - { - NaN++; - } + if (Double.isNaN(this.getValue(i, j))) + { + NaN++; + } } } return NaN; } /** - * performs an element-wise addition of this matrix by another matrix ~ this - m - * @param m ~ other matrix - * - * @return - */ + * performs an element-wise addition of this matrix by another matrix ~ this - + * m + * + * @param m + * ~ other matrix + * + * @return + */ @Override public MatrixI add(MatrixI m) { if (m.width() != cols || m.height() != rows) { - throw new IllegalArgumentException("Can't add a " + m.height() + "x" + m.width() + " to a " + this.rows + "x" + this.cols + " matrix"); + throw new IllegalArgumentException( + "Can't add a " + m.height() + "x" + m.width() + " to a " + + this.rows + "x" + this.cols + " matrix"); } double[][] tmp = new double[this.rows][this.cols]; for (int i = 0; i < this.rows; i++) { for (int j = 0; j < this.cols; j++) { - tmp[i][j] = this.getValue(i,j) + m.getValue(i,j); + tmp[i][j] = this.getValue(i, j) + m.getValue(i, j); } } return new Matrix(tmp); } /** - * performs an element-wise subtraction of this matrix by another matrix ~ this - m - * @param m ~ other matrix - * - * @return - */ + * performs an element-wise subtraction of this matrix by another matrix ~ + * this - m + * + * @param m + * ~ other matrix + * + * @return + */ @Override public MatrixI subtract(MatrixI m) { if (m.width() != cols || m.height() != rows) { - throw new IllegalArgumentException("Can't subtract a " + m.height() + "x" + m.width() + " from a " + this.rows + "x" + this.cols + " matrix"); + throw new IllegalArgumentException("Can't subtract a " + m.height() + + "x" + m.width() + " from a " + this.rows + "x" + this.cols + + " matrix"); } double[][] tmp = new double[this.rows][this.cols]; for (int i = 0; i < this.rows; i++) { for (int j = 0; j < this.cols; j++) { - tmp[i][j] = this.getValue(i,j) - m.getValue(i,j); + tmp[i][j] = this.getValue(i, j) - m.getValue(i, j); } } return new Matrix(tmp); } /** - * performs an element-wise multiplication of this matrix by another matrix ~ this * m - * @param m ~ other matrix - * - * @return - */ + * performs an element-wise multiplication of this matrix by another matrix ~ + * this * m + * + * @param m + * ~ other matrix + * + * @return + */ @Override public MatrixI elementwiseMultiply(MatrixI m) { if (m.width() != cols || m.height() != rows) { - throw new IllegalArgumentException("Can't multiply a " + this.rows + "x" + this.cols + " by a " + m.height() + "x" + m.width() + " matrix"); + throw new IllegalArgumentException( + "Can't multiply a " + this.rows + "x" + this.cols + " by a " + + m.height() + "x" + m.width() + " matrix"); } double[][] tmp = new double[this.rows][this.cols]; for (int i = 0; i < this.rows; i++) { for (int j = 0; j < this.cols; j++) { - tmp[i][j] = this.getValue(i, j) * m.getValue(i,j); + tmp[i][j] = this.getValue(i, j) * m.getValue(i, j); } } return new Matrix(tmp); } /** - * performs an element-wise division of this matrix by another matrix ~ this / m - * @param m ~ other matrix - * - * @return - */ + * performs an element-wise division of this matrix by another matrix ~ this / + * m + * + * @param m + * ~ other matrix + * + * @return + */ @Override public MatrixI elementwiseDivide(MatrixI m) { if (m.width() != cols || m.height() != rows) { - throw new IllegalArgumentException("Can't divide a " + this.rows + "x" + this.cols + " by a " + m.height() + "x" + m.width() + " matrix"); + throw new IllegalArgumentException( + "Can't divide a " + this.rows + "x" + this.cols + " by a " + + m.height() + "x" + m.width() + " matrix"); } double[][] tmp = new double[this.rows][this.cols]; for (int i = 0; i < this.rows; i++) { for (int j = 0; j < this.cols; j++) { - tmp[i][j] = this.getValue(i, j) / m.getValue(i,j); + tmp[i][j] = this.getValue(i, j) / m.getValue(i, j); } } return new Matrix(tmp); } /** - * calculate the root-mean-square for tow matrices - * @param m ~ other matrix - * - * @return - */ + * calculate the root-mean-square for tow matrices + * + * @param m + * ~ other matrix + * + * @return + */ @Override public double rmsd(MatrixI m) { @@ -1351,10 +1379,10 @@ public class Matrix implements MatrixI } /** - * calculates the Frobenius norm of this matrix - * - * @return - */ + * calculates the Frobenius norm of this matrix + * + * @return + */ @Override public double norm() { @@ -1363,17 +1391,17 @@ public class Matrix implements MatrixI { for (double val : row) { - result += Math.pow(val, 2); + result += Math.pow(val, 2); } } return Math.sqrt(result); } /** - * returns the sum of all values in this matrix - * - * @return - */ + * returns the sum of all values in this matrix + * + * @return + */ @Override public double sum() { @@ -1382,24 +1410,28 @@ public class Matrix implements MatrixI { for (double val : row) { - sum += (Double.isNaN(val)) ? 0.0 : val; + sum += (Double.isNaN(val)) ? 0.0 : val; } } return sum; } /** - * returns the sum-product of this matrix with vector v - * @param v ~ vector - * - * @return - */ + * returns the sum-product of this matrix with vector v + * + * @param v + * ~ vector + * + * @return + */ @Override public double[] sumProduct(double[] v) { if (v.length != cols) { - throw new IllegalArgumentException("Vector and matrix do not have the same dimension! (" + v.length + " != " + cols + ")"); + throw new IllegalArgumentException( + "Vector and matrix do not have the same dimension! (" + + v.length + " != " + cols + ")"); } double[] result = new double[rows]; for (int i = 0; i < rows; i++) @@ -1408,7 +1440,7 @@ public class Matrix implements MatrixI double sum = 0; for (int j = 0; j < row.length; j++) { - sum += row[j] * v[j]; + sum += row[j] * v[j]; } result[i] = sum; } @@ -1416,20 +1448,20 @@ public class Matrix implements MatrixI } /** - * mirrors columns of the matrix - * - * @return - */ + * mirrors columns of the matrix + * + * @return + */ @Override public MatrixI mirrorCol() { double[][] result = new double[rows][cols]; for (int i = 0; i < rows; i++) { - int k = cols - 1; // reverse col + int k = cols - 1; // reverse col for (int j = 0; j < cols; j++) { - result[i][k--] = this.getValue(i,j); + result[i][k--] = this.getValue(i, j); } } MatrixI resultMatrix = new Matrix(result); diff --git a/src/jalview/math/MatrixI.java b/src/jalview/math/MatrixI.java index 7faac73..b932b33 100644 --- a/src/jalview/math/MatrixI.java +++ b/src/jalview/math/MatrixI.java @@ -61,10 +61,10 @@ public interface MatrixI void setValue(int i, int j, double d); /** - * Returns the matrix as a double[][] array - * - * @return - */ + * Returns the matrix as a double[][] array + * + * @return + */ double[][] asArray(); /** @@ -175,10 +175,11 @@ public interface MatrixI void multiply(double d); /** - * Add d to all entries of this matrix - * - * @param d ~ value to add - */ + * Add d to all entries of this matrix + * + * @param d + * ~ value to add + */ void add(double d); /** @@ -193,7 +194,7 @@ public interface MatrixI boolean equals(MatrixI m2, double delta); /** - * Returns a copy in which every value in the matrix is its absolute + * Returns a copy in which every value in the matrix is its absolute */ MatrixI absolute(); @@ -208,110 +209,122 @@ public interface MatrixI double[] meanCol(); /** - * Returns a flattened matrix containing the sum of each column - * - * @return - */ + * Returns a flattened matrix containing the sum of each column + * + * @return + */ double[] sumCol(); /** - * returns the mean value of the complete matrix - */ + * returns the mean value of the complete matrix + */ double mean(); /** - * fills up a diagonal matrix with its transposed copy - * !other side should be filled with either 0 or Double.NaN - */ + * fills up a diagonal matrix with its transposed copy !other side should be + * filled with either 0 or Double.NaN + */ void fillDiagonal(); /** - * counts the number of Double.NaN in the matrix - * - * @return - */ + * counts the number of Double.NaN in the matrix + * + * @return + */ int countNaN(); /** - * performs an element-wise addition of this matrix by another matrix - * !matrices have to be the same size - * @param m ~ other matrix - * - * @return - * @throws IllegalArgumentException - * if this and m do not have the same dimensions - */ + * performs an element-wise addition of this matrix by another matrix + * !matrices have to be the same size + * + * @param m + * ~ other matrix + * + * @return + * @throws IllegalArgumentException + * if this and m do not have the same dimensions + */ MatrixI add(MatrixI m); /** - * performs an element-wise subtraction of this matrix by another matrix - * !matrices have to be the same size - * @param m ~ other matrix - * - * @return - * @throws IllegalArgumentException - * if this and m do not have the same dimensions - */ + * performs an element-wise subtraction of this matrix by another matrix + * !matrices have to be the same size + * + * @param m + * ~ other matrix + * + * @return + * @throws IllegalArgumentException + * if this and m do not have the same dimensions + */ MatrixI subtract(MatrixI m); - + /** - * performs an element-wise multiplication of this matrix by another matrix ~ this * m - * !matrices have to be the same size - * @param m ~ other matrix - * - * @return - * @throws IllegalArgumentException - * if this and m do not have the same dimensions - */ + * performs an element-wise multiplication of this matrix by another matrix ~ + * this * m !matrices have to be the same size + * + * @param m + * ~ other matrix + * + * @return + * @throws IllegalArgumentException + * if this and m do not have the same dimensions + */ MatrixI elementwiseMultiply(MatrixI m); /** - * performs an element-wise division of this matrix by another matrix ~ this / m - * !matrices have to be the same size - * @param m ~ other matrix - * - * @return - * @throws IllegalArgumentException - * if this and m do not have the same dimensions - */ + * performs an element-wise division of this matrix by another matrix ~ this / + * m !matrices have to be the same size + * + * @param m + * ~ other matrix + * + * @return + * @throws IllegalArgumentException + * if this and m do not have the same dimensions + */ MatrixI elementwiseDivide(MatrixI m); /** - * calculates the root-mean-square for two matrices - * @param m ~ other matrix - * - * @return - */ + * calculates the root-mean-square for two matrices + * + * @param m + * ~ other matrix + * + * @return + */ double rmsd(MatrixI m); /** - * calculates the Frobenius norm of this matrix - * - * @return - */ + * calculates the Frobenius norm of this matrix + * + * @return + */ double norm(); - + /** - * returns the sum of all values in this matrix - * - * @return - */ + * returns the sum of all values in this matrix + * + * @return + */ double sum(); /** - * returns the sum-product of this matrix with vector v - * @param v ~ vector - * - * @return - * @throws IllegalArgumentException - * if this.cols and v do not have the same length - */ + * returns the sum-product of this matrix with vector v + * + * @param v + * ~ vector + * + * @return + * @throws IllegalArgumentException + * if this.cols and v do not have the same length + */ double[] sumProduct(double[] v); /** - * mirrors the columns of this matrix - * - * @return - */ + * mirrors the columns of this matrix + * + * @return + */ MatrixI mirrorCol(); } diff --git a/src/jalview/math/MiscMath.java b/src/jalview/math/MiscMath.java index b5218d5..eee7ef8 100755 --- a/src/jalview/math/MiscMath.java +++ b/src/jalview/math/MiscMath.java @@ -27,14 +27,17 @@ import java.util.Arrays; /** * A collection of miscellaneous mathematical operations + * * @AUTHOR MorellThomas */ public class MiscMath { /** - * prints an array - * @param m ~ array - */ + * prints an array + * + * @param m + * ~ array + */ public static void print(double[] m, String format) { System.out.print("[ "); @@ -46,39 +49,43 @@ public class MiscMath } /** - * calculates the mean of an array - * - * @param m ~ array - * @return - */ + * calculates the mean of an array + * + * @param m + * ~ array + * @return + */ public static double mean(double[] m) { double sum = 0; int nanCount = 0; for (int i = 0; i < m.length; i++) { - if (!Double.isNaN(m[i])) // ignore NaN values in the array + if (!Double.isNaN(m[i])) // ignore NaN values in the array { sum += m[i]; - } else { - nanCount++; + } + else + { + nanCount++; } } return sum / (double) (m.length - nanCount); } /** - * calculates the sum of an array - * - * @param m ~ array - * @return - */ + * calculates the sum of an array + * + * @param m + * ~ array + * @return + */ public static double sum(double[] m) { double sum = 0; for (int i = 0; i < m.length; i++) { - if (!Double.isNaN(m[i])) // ignore NaN values in the array + if (!Double.isNaN(m[i])) // ignore NaN values in the array { sum += m[i]; } @@ -87,14 +94,14 @@ public class MiscMath } /** - * calculates the square root of each element in an array - * - * @param m ~ array - * - * @return - * TODO - * make general with function passed -> apply function to each element - */ + * calculates the square root of each element in an array + * + * @param m + * ~ array + * + * @return TODO make general with function passed -> apply function to each + * element + */ public static double[] sqrt(double[] m) { double[] sqrts = new double[m.length]; @@ -106,16 +113,20 @@ public class MiscMath } /** - * calculate element wise multiplication of two arrays with the same length - * - * @param a ~ array - * @param b ~ array - * - * @return - */ - public static double[] elementwiseMultiply(byte[] a, double[] b) throws RuntimeException + * calculate element wise multiplication of two arrays with the same length + * + * @param a + * ~ array + * @param b + * ~ array + * + * @return + */ + public static double[] elementwiseMultiply(byte[] a, double[] b) + throws RuntimeException { - if (a.length != b.length) // throw exception if the arrays do not have the same length + if (a.length != b.length) // throw exception if the arrays do not have the + // same length { throw new SameLengthException(a.length, b.length); } @@ -126,9 +137,12 @@ public class MiscMath } return result; } - public static double[] elementwiseMultiply(double[] a, double[] b) throws RuntimeException + + public static double[] elementwiseMultiply(double[] a, double[] b) + throws RuntimeException { - if (a.length != b.length) // throw exception if the arrays do not have the same length + if (a.length != b.length) // throw exception if the arrays do not have the + // same length { throw new SameLengthException(a.length, b.length); } @@ -139,9 +153,12 @@ public class MiscMath } return result; } - public static byte[] elementwiseMultiply(byte[] a, byte[] b) throws RuntimeException + + public static byte[] elementwiseMultiply(byte[] a, byte[] b) + throws RuntimeException { - if (a.length != b.length) // throw exception if the arrays do not have the same length + if (a.length != b.length) // throw exception if the arrays do not have the + // same length { throw new SameLengthException(a.length, b.length); } @@ -152,6 +169,7 @@ public class MiscMath } return result; } + public static double[] elementwiseMultiply(double[] a, double b) { double[] result = new double[a.length]; @@ -163,16 +181,20 @@ public class MiscMath } /** - * calculate element wise division of two arrays ~ a / b - * - * @param a ~ array - * @param b ~ array - * - * @return - */ - public static double[] elementwiseDivide(double[] a, double[] b) throws RuntimeException + * calculate element wise division of two arrays ~ a / b + * + * @param a + * ~ array + * @param b + * ~ array + * + * @return + */ + public static double[] elementwiseDivide(double[] a, double[] b) + throws RuntimeException { - if (a.length != b.length) // throw exception if the arrays do not have the same length + if (a.length != b.length) // throw exception if the arrays do not have the + // same length { throw new SameLengthException(a.length, b.length); } @@ -185,16 +207,20 @@ public class MiscMath } /** - * calculate element wise addition of two arrays - * - * @param a ~ array - * @param b ~ array - * - * @return - */ - public static double[] elementwiseAdd(double[] a, double[] b) throws RuntimeException + * calculate element wise addition of two arrays + * + * @param a + * ~ array + * @param b + * ~ array + * + * @return + */ + public static double[] elementwiseAdd(double[] a, double[] b) + throws RuntimeException { - if (a.length != b.length) // throw exception if the arrays do not have the same length + if (a.length != b.length) // throw exception if the arrays do not have the + // same length { throw new SameLengthException(a.length, b.length); } @@ -206,6 +232,7 @@ public class MiscMath } return result; } + public static double[] elementwiseAdd(double[] a, double b) { double[] result = new double[a.length]; @@ -217,41 +244,59 @@ public class MiscMath } /** - * returns true if two arrays are element wise within a tolerance - * - * @param a ~ array - * @param b ~ array - * @param rtol ~ relative tolerance - * @param atol ~ absolute tolerance - * @param equalNAN ~ whether NaN at the same position return true - * - * @return - */ - public static boolean allClose(double[] a, double[] b, double rtol, double atol, boolean equalNAN) + * returns true if two arrays are element wise within a tolerance + * + * @param a + * ~ array + * @param b + * ~ array + * @param rtol + * ~ relative tolerance + * @param atol + * ~ absolute tolerance + * @param equalNAN + * ~ whether NaN at the same position return true + * + * @return + */ + public static boolean allClose(double[] a, double[] b, double rtol, + double atol, boolean equalNAN) { boolean areEqual = true; for (int i = 0; i < a.length; i++) { - if (equalNAN && (Double.isNaN(a[i]) && Double.isNaN(b[i]))) // if equalNAN == true -> skip the NaN pair + if (equalNAN && (Double.isNaN(a[i]) && Double.isNaN(b[i]))) // if equalNAN + // == true -> + // skip the + // NaN pair { - continue; + continue; } - if (Math.abs(a[i] - b[i]) > (atol + rtol * Math.abs(b[i]))) // check for the similarity condition -> if not met -> break and return false + if (Math.abs(a[i] - b[i]) > (atol + rtol * Math.abs(b[i]))) // check for + // the + // similarity + // condition + // -> if not + // met -> + // break and + // return + // false { - areEqual = false; - break; + areEqual = false; + break; } } return areEqual; } /** - * returns the index of the maximum and the maximum value of an array - * - * @param a ~ array - * - * @return - */ + * returns the index of the maximum and the maximum value of an array + * + * @param a + * ~ array + * + * @return + */ public static int[] findMax(int[] a) { int max = 0; @@ -260,25 +305,30 @@ public class MiscMath { if (a[i] > max) { - max = a[i]; - maxIndex = i; + max = a[i]; + maxIndex = i; } } - return new int[]{maxIndex, max}; + return new int[] { maxIndex, max }; } /** - * returns the dot product of two arrays - * @param a ~ array a - * @param b ~ array b - * - * @return - */ + * returns the dot product of two arrays + * + * @param a + * ~ array a + * @param b + * ~ array b + * + * @return + */ public static double dot(double[] a, double[] b) { if (a.length != b.length) { - throw new IllegalArgumentException(String.format("Vectors do not have the same length (%d, %d)!", a.length, b.length)); + throw new IllegalArgumentException( + String.format("Vectors do not have the same length (%d, %d)!", + a.length, b.length)); } double aibi = 0; @@ -290,11 +340,13 @@ public class MiscMath } /** - * returns the euklidian norm of the vector - * @param v ~ vector - * - * @return - */ + * returns the euklidian norm of the vector + * + * @param v + * ~ vector + * + * @return + */ public static double norm(double[] v) { double result = 0; @@ -302,15 +354,17 @@ public class MiscMath { result += Math.pow(i, 2); } - return Math.sqrt(result); + return Math.sqrt(result); } /** - * returns the number of NaN in the vector - * @param v ~ vector - * - * @return - */ + * returns the number of NaN in the vector + * + * @param v + * ~ vector + * + * @return + */ public static int countNaN(double[] v) { int cnt = 0; @@ -318,20 +372,21 @@ public class MiscMath { if (Double.isNaN(i)) { - cnt++; + cnt++; } } return cnt; } /** - * recursively calculates the permutations of total n items with r items per combination - * according to n!/(n-r)! by only multiplying the relevant terms - * @param n - * @param r - * - * @return permutations - */ + * recursively calculates the permutations of total n items with r items per + * combination according to n!/(n-r)! by only multiplying the relevant terms + * + * @param n + * @param r + * + * @return permutations + */ public static long permutations(int n, int r) { if (n < r) @@ -340,13 +395,14 @@ public class MiscMath long result = 1l; for (int i = 0; i < r; i++) { - result *= (n-i); + result *= (n - i); } return result; } /** * calculate all unique combinations of n elements into r sized groups + * * @param n * @param r * @@ -357,13 +413,14 @@ public class MiscMath int result = 1; for (int i = 0; i < r; i++) { - result *= (n-1); + result *= (n - 1); } return (int) (result / MiscMath.factorial(r)); } /** * calculate the factorial of n (n >= 0) + * * @param n * * @return diff --git a/src/jalview/project/Jalview2XML.java b/src/jalview/project/Jalview2XML.java index 93faea1..e2a5508 100644 --- a/src/jalview/project/Jalview2XML.java +++ b/src/jalview/project/Jalview2XML.java @@ -1989,13 +1989,14 @@ public class Jalview2XML } /** - * Writes PaSiMap viewer attributes and computed values to an XML model object and - * adds it to the JalviewModel. Any exceptions are reported by logging. + * Writes PaSiMap viewer attributes and computed values to an XML model object + * and adds it to the JalviewModel. Any exceptions are reported by logging. * uses the functions from PCA */ protected void savePaSiMap(PaSiMapPanel panel, JalviewModel object) { - // TODO: this should be merged with above savePCAPanel - otherwise it is essentially redundant code + // TODO: this should be merged with above savePCAPanel - otherwise it is + // essentially redundant code try { PcaViewer viewer = new PcaViewer(); @@ -2085,6 +2086,7 @@ public class Jalview2XML Console.error("Error saving PaSiMap: " + t.getMessage()); } } + /** * Stores values from a matrix into an XML element, including (if present) the * D or E vectors @@ -5417,7 +5419,7 @@ public class Jalview2XML viewport.getResidueShading() .setConsensus(viewport.getSequenceConsensusHash()); viewport.getResidueShading() - .setSsConsensus(viewport.getSequenceSSConsensusHash()); + .setSsConsensus(viewport.getSequenceSSConsensusHash()); if (safeBoolean(view.isConservationSelected()) && cs != null) { viewport.getResidueShading() @@ -6707,9 +6709,9 @@ public class Jalview2XML private boolean isPasimap(PcaViewer viewer) { - return viewer.getTitle().toLowerCase(Locale.ROOT) - .startsWith("pasimap"); + return viewer.getTitle().toLowerCase(Locale.ROOT).startsWith("pasimap"); } + /** * Loads any saved PaSiMAp viewers using the function from PCA * @@ -6733,7 +6735,7 @@ public class Jalview2XML viewer.isIncludeGappedColumns(), viewer.isMatchGaps(), viewer.isIncludeGaps(), viewer.isDenominateByShortestLength()); - */ + */ /* * create the panel (without computing the PaSiMAp) @@ -6760,7 +6762,8 @@ public class Jalview2XML PaSiMap pasimap = new PaSiMap(null, scoreModel, null); PcaDataType pasimapData = viewer.getPcaData(); - MatrixI pairwise = loadDoubleMatrix(pasimapData.getPairwiseMatrix()); + MatrixI pairwise = loadDoubleMatrix( + pasimapData.getPairwiseMatrix()); pasimap.setPairwiseScores(pairwise); MatrixI result = loadDoubleMatrix(pasimapData.getEigenMatrix()); diff --git a/src/jalview/renderer/AnnotationRenderer.java b/src/jalview/renderer/AnnotationRenderer.java index 4e9f669..9e9329a 100644 --- a/src/jalview/renderer/AnnotationRenderer.java +++ b/src/jalview/renderer/AnnotationRenderer.java @@ -90,7 +90,7 @@ public class AnnotationRenderer private HiddenColumns hiddenColumns; private ProfilesI hconsensus; - + private ProfilesI hSSconsensus; private Hashtable[] complementConsensus; @@ -431,15 +431,15 @@ public class AnnotationRenderer } } } - - else if(aa.autoCalculated && aa.label.startsWith(MessageManager.getString("label.ssconsensus_label"))) + + else if (aa.autoCalculated && aa.label.startsWith( + MessageManager.getString("label.ssconsensus_label"))) { - return AAFrequency.extractProfile( - hSSconsensus.get(column), + return AAFrequency.extractProfile(hSSconsensus.get(column), av_ignoreGapsConsensus); - + } - + else { if (aa.autoCalculated && aa.label.startsWith("StrucConsensus")) @@ -1536,8 +1536,6 @@ public class AnnotationRenderer * {profile type, #values, total count, char1, pct1, char2, pct2...} */ int profl[] = getProfileFor(_aa, column); - - // just try to draw the logo if profl is not null if (profl != null && profl[2] != 0) @@ -1619,12 +1617,15 @@ public class AnnotationRenderer colour = profcolour.findColour(codonTranslation.charAt(0), column, null); } - if(_aa.label == MessageManager.getString("label.ssconsensus_label")) { - colour = AlignmentUtils.getSecondaryStructureAnnotationColour(dc[0]); + if (_aa.label == MessageManager + .getString("label.ssconsensus_label")) + { + colour = AlignmentUtils + .getSecondaryStructureAnnotationColour(dc[0]); } else { - + colour = profcolour.findColour(dc[0], column, null); } diff --git a/src/jalview/renderer/ResidueShader.java b/src/jalview/renderer/ResidueShader.java index b914c65..b9f3ee1 100644 --- a/src/jalview/renderer/ResidueShader.java +++ b/src/jalview/renderer/ResidueShader.java @@ -61,12 +61,11 @@ public class ResidueShader implements ResidueShaderI * the consensus data for each column */ private ProfilesI consensus; - + /* * the consensus data for each column */ private ProfilesI ssConsensus; - public ProfilesI getSsConsensus() { @@ -154,7 +153,7 @@ public class ResidueShader implements ResidueShaderI public void setConsensus(ProfilesI cons) { consensus = cons; - + } /** @@ -279,7 +278,7 @@ public class ResidueShader implements ResidueShaderI return colour; } - + @Override public Color findSSColour(char symbol, int position, SequenceI seq) { @@ -291,13 +290,13 @@ public class ResidueShader implements ResidueShaderI /* * get 'base' colour */ - ProfileI profile = ssConsensus == null ? null : ssConsensus.get(position); - String modalSS = profile == null ? null - : profile.getModalSS(); + ProfileI profile = ssConsensus == null ? null + : ssConsensus.get(position); + String modalSS = profile == null ? null : profile.getModalSS(); float pid = profile == null ? 0f : profile.getSSPercentageIdentity(ignoreGaps); - Color colour = colourScheme.findColour(symbol, position, seq, - modalSS, pid); + Color colour = colourScheme.findColour(symbol, position, seq, modalSS, + pid); /* * apply PID threshold and consensus fading if in force diff --git a/src/jalview/renderer/ResidueShaderI.java b/src/jalview/renderer/ResidueShaderI.java index 0412d21..30c87a9 100644 --- a/src/jalview/renderer/ResidueShaderI.java +++ b/src/jalview/renderer/ResidueShaderI.java @@ -34,7 +34,7 @@ public interface ResidueShaderI { public abstract void setConsensus(ProfilesI cons); - + public abstract void setSsConsensus(ProfilesI cons); public abstract boolean conservationApplied(); diff --git a/src/jalview/schemes/ClustalxColourScheme.java b/src/jalview/schemes/ClustalxColourScheme.java index 04097a8..8e64f8f 100755 --- a/src/jalview/schemes/ClustalxColourScheme.java +++ b/src/jalview/schemes/ClustalxColourScheme.java @@ -364,62 +364,72 @@ public class ClustalxColourScheme extends ResidueColourScheme { return false; } + public String toRuleRep() { makeColours(); - HashMap cols=new HashMap(); - for (String res:ResidueProperties.aa) { + HashMap cols = new HashMap(); + for (String res : ResidueProperties.aa) + { StringBuilder sb = new StringBuilder(); - - int rnum=ResidueProperties.aaIndex[res.charAt(0)]; - if (rnum<0 || rnum>=residueColour.length) + + int rnum = ResidueProperties.aaIndex[res.charAt(0)]; + if (rnum < 0 || rnum >= residueColour.length) { continue; } - + ConsensusColour cc = residueColour[rnum]; - if (cc==null) + if (cc == null) { continue; } - //sb.append("Residue "+res+" ("+rnum+")"); - //sb.append("\t"); + // sb.append("Residue "+res+" ("+rnum+")"); + // sb.append("\t"); sb.append(cc.c.toString()); - double f=0; + double f = 0; sb.append("\t"); - for (Consensus cons: cc.cons) { - if (cons.threshold==0 || f!=cons.threshold) + for (Consensus cons : cc.cons) + { + if (cons.threshold == 0 || f != cons.threshold) { - if (f!=0) + if (f != 0) { - sb.append("}, {"); - } else { - sb.append("{"); + sb.append("}, {"); + } + else + { + sb.append("{"); } - sb.append(cons.threshold); - sb.append(","); - f=cons.threshold; - } else { + sb.append(cons.threshold); + sb.append(","); + f = cons.threshold; + } + else + { sb.append(","); } sb.append(cons.maskstr); } sb.append("}"); - String clxrep=sb.toString(); + String clxrep = sb.toString(); String xres = cols.get(clxrep); - if (xres==null) { xres = "";} - xres+=res; + if (xres == null) + { + xres = ""; + } + xres += res; cols.put(clxrep, xres); } StringBuilder sb = new StringBuilder(); - for (String clxrep:cols.keySet()) + for (String clxrep : cols.keySet()) { sb.append(cols.get(clxrep)); sb.append("\t"); sb.append(clxrep); sb.append("\n"); - + } return sb.toString(); } diff --git a/src/jalview/schemes/ResidueProperties.java b/src/jalview/schemes/ResidueProperties.java index 2fcb95f..9d83069 100755 --- a/src/jalview/schemes/ResidueProperties.java +++ b/src/jalview/schemes/ResidueProperties.java @@ -41,7 +41,7 @@ public class ResidueProperties public static final int[] nucleotideIndex; public static final int[] purinepyrimidineIndex; - + public static final int[] secondaryStructureIndex; public static final Map aa3Hash = new HashMap<>(); @@ -197,13 +197,13 @@ public class ResidueProperties purinepyrimidineIndex['N'] = 2; purinepyrimidineIndex['n'] = 2; } - + static { secondaryStructureIndex = new int[255]; for (int i = 0; i < 255; i++) { - secondaryStructureIndex[i] = 3; + secondaryStructureIndex[i] = 3; } secondaryStructureIndex['H'] = 0; @@ -398,12 +398,12 @@ public class ResidueProperties Color.white, // all other nucleotides Color.white // Gap }; - - //Secondary structure - public static final Color[] secondarystructure = { Color.red, // H - Color.green, // E - Color.gray // C - }; + + // Secondary structure + public static final Color[] secondarystructure = { Color.red, // H + Color.green, // E + Color.gray // C + }; // Zappo public static final Color[] zappo = { Color.pink, // A diff --git a/src/jalview/util/Constants.java b/src/jalview/util/Constants.java index bced9c8..1321fb0 100644 --- a/src/jalview/util/Constants.java +++ b/src/jalview/util/Constants.java @@ -28,22 +28,25 @@ import java.util.Map; */ public class Constants { - - //character used to represent secondary structures + + // character used to represent secondary structures public static final char HELIX = 'H'; + public static final char SHEET = 'E'; + public static final char COIL = 'C'; - //label in secondary structure annotation data model from 3d structures + // label in secondary structure annotation data model from 3d structures public static final String SS_ANNOTATION_LABEL = "Secondary Structure"; - - //label in secondary structure annotation data model from JPred - public static final String SS_ANNOTATION_FROM_JPRED_LABEL = "jnetpred"; - + + // label in secondary structure annotation data model from JPred + public static final String SS_ANNOTATION_FROM_JPRED_LABEL = "jnetpred"; + public static final Map SECONDARY_STRUCTURE_LABELS = new HashMap<>(); - static { - SECONDARY_STRUCTURE_LABELS.put(SS_ANNOTATION_LABEL, "3D Structures"); - SECONDARY_STRUCTURE_LABELS.put(SS_ANNOTATION_FROM_JPRED_LABEL, "JPred"); - // Add other secondary structure labels here if needed - } + static + { + SECONDARY_STRUCTURE_LABELS.put(SS_ANNOTATION_LABEL, "3D Structures"); + SECONDARY_STRUCTURE_LABELS.put(SS_ANNOTATION_FROM_JPRED_LABEL, "JPred"); + // Add other secondary structure labels here if needed + } } diff --git a/src/jalview/viewmodel/AlignmentViewport.java b/src/jalview/viewmodel/AlignmentViewport.java index d26f023..ce4473b 100644 --- a/src/jalview/viewmodel/AlignmentViewport.java +++ b/src/jalview/viewmodel/AlignmentViewport.java @@ -699,7 +699,7 @@ public abstract class AlignmentViewport } protected AlignmentAnnotation consensus; - + protected AlignmentAnnotation secondaryStructureConsensus; protected AlignmentAnnotation complementConsensus; @@ -713,7 +713,7 @@ public abstract class AlignmentViewport protected AlignmentAnnotation quality; protected AlignmentAnnotation[] groupConsensus; - + protected AlignmentAnnotation[] groupSSConsensus; protected AlignmentAnnotation[] groupConservation; @@ -722,10 +722,8 @@ public abstract class AlignmentViewport * results of alignment consensus analysis for visible portion of view */ protected ProfilesI hconsensus = null; - + protected ProfilesI hSSConsensus = null; - - /** * results of cDNA complement consensus visible portion of view @@ -763,13 +761,13 @@ public abstract class AlignmentViewport { this.hconsensus = hconsensus; } - + @Override public void setSequenceSSConsensusHash(ProfilesI hSSConsensus) { this.hSSConsensus = hSSConsensus; } - + @Override public void setComplementConsensusHash( Hashtable[] hconsensus) @@ -782,7 +780,7 @@ public abstract class AlignmentViewport { return hconsensus; } - + @Override public ProfilesI getSequenceSSConsensusHash() { @@ -827,13 +825,11 @@ public abstract class AlignmentViewport return consensus; } - @Override public AlignmentAnnotation getAlignmentSecondaryStructureConsensusAnnotation() { return secondaryStructureConsensus; } - @Override public AlignmentAnnotation getAlignmentGapAnnotation() @@ -926,9 +922,6 @@ public abstract class AlignmentViewport } } } - - - /** * trigger update of consensus annotation @@ -940,10 +933,11 @@ public abstract class AlignmentViewport { return; } - if (calculator - .getRegisteredWorkersOfClass(SecondaryStructureConsensusThread.class) == null) + if (calculator.getRegisteredWorkersOfClass( + SecondaryStructureConsensusThread.class) == null) { - calculator.registerWorker(new SecondaryStructureConsensusThread(this, ap)); + calculator.registerWorker( + new SecondaryStructureConsensusThread(this, ap)); } } @@ -1056,7 +1050,7 @@ public abstract class AlignmentViewport * should consensus profile be rendered by default */ protected boolean showSequenceLogo = false; - + protected boolean showSequenceSSLogo = false; /** @@ -1068,7 +1062,7 @@ public abstract class AlignmentViewport * should consensus histograms be rendered by default */ protected boolean showConsensusHistogram = true; - + protected boolean showSSConsensusHistogram = true; public void setShowSSConsensusHistogram(boolean showSSConsensusHistogram) @@ -1084,7 +1078,7 @@ public abstract class AlignmentViewport { return showSequenceLogo; } - + @Override public boolean isShowSequenceSSLogo() { @@ -1108,7 +1102,7 @@ public abstract class AlignmentViewport } this.showSequenceLogo = showSequenceLogo; } - + public void setShowSequenceSSLogo(boolean showSequenceSSLogo) { if (showSequenceSSLogo != this.showSequenceSSLogo) @@ -1116,7 +1110,8 @@ public abstract class AlignmentViewport // TODO: decouple settings setting from calculation when refactoring // annotation update method from alignframe to viewport this.showSequenceSSLogo = showSequenceSSLogo; - calculator.updateAnnotationFor(SecondaryStructureConsensusThread.class); + calculator + .updateAnnotationFor(SecondaryStructureConsensusThread.class); } this.showSequenceSSLogo = showSequenceSSLogo; } @@ -1174,7 +1169,7 @@ public abstract class AlignmentViewport { return this.showConsensusHistogram; } - + @Override public boolean isShowSSConsensusHistogram() { @@ -1404,7 +1399,7 @@ public abstract class AlignmentViewport protected boolean showQuality = true; - protected boolean showConsensus = true; + protected boolean showConsensus = true; protected boolean showSSConsensus = false; @@ -2049,11 +2044,12 @@ public abstract class AlignmentViewport consensus = new AlignmentAnnotation("Consensus", MessageManager.getString("label.consensus_descr"), new Annotation[1], 0f, 100f, AlignmentAnnotation.BAR_GRAPH); - - secondaryStructureConsensus = new AlignmentAnnotation(MessageManager.getString("label.ssconsensus_label"), + + secondaryStructureConsensus = new AlignmentAnnotation( + MessageManager.getString("label.ssconsensus_label"), MessageManager.getString("label.ssconsensus_descr"), new Annotation[1], 0f, 100f, AlignmentAnnotation.BAR_GRAPH); - + initConsensus(consensus); initSSConsensus(secondaryStructureConsensus); initGapCounts(); @@ -2061,7 +2057,6 @@ public abstract class AlignmentViewport } } - /** * If this is a protein alignment and there are mappings to cDNA, adds the * cDNA consensus annotation and returns true, else returns false. @@ -2112,7 +2107,7 @@ public abstract class AlignmentViewport alignment.addAnnotation(aa); } } - + private void initSSConsensus(AlignmentAnnotation aa) { aa.hasText = true; @@ -3114,7 +3109,7 @@ public abstract class AlignmentViewport + ((ignoreGapsInConsensusCalculation) ? " without gaps" : "")); return sq; } - + public SequenceI getSSConsensusSeq() { if (secondaryStructureConsensus == null) diff --git a/src/jalview/viewmodel/PaSiMapModel.java b/src/jalview/viewmodel/PaSiMapModel.java index a0e5174..8568af4 100644 --- a/src/jalview/viewmodel/PaSiMapModel.java +++ b/src/jalview/viewmodel/PaSiMapModel.java @@ -69,8 +69,8 @@ public class PaSiMapModel * @param modelName * @param params */ - public PaSiMapModel(AlignmentViewport seqData, SequenceI[] sqs, boolean nuc, - ScoreModelI modelName) + public PaSiMapModel(AlignmentViewport seqData, SequenceI[] sqs, + boolean nuc, ScoreModelI modelName) { inputData = seqData; seqs = sqs; @@ -79,8 +79,8 @@ public class PaSiMapModel } /** - * Performs the PaSiMap calculation (in the same thread) and extracts result data - * needed for visualisation by PaSiMapPanel + * Performs the PaSiMap calculation (in the same thread) and extracts result + * data needed for visualisation by PaSiMapPanel */ public void calculate(PairwiseAlignPanel pap) { @@ -100,7 +100,8 @@ public class PaSiMapModel top = width; points = new Vector<>(); - Point[] scores = pasimap.getComponents(width - 1, width - 2, width - 3, 1); + Point[] scores = pasimap.getComponents(width - 1, width - 2, width - 3, + 1); for (int i = 0; i < height; i++) { @@ -142,8 +143,9 @@ public class PaSiMapModel /** * Updates the 3D coordinates for the list of points to the given dimensions. * Principal dimension is getTop(). Next greatest eigenvector is getTop()-1. - * Note - pasimap.getComponents starts counting the spectrum from rank-2 to zero, - * rather than rank-1, so getComponents(dimN ...) == updateRcView(dimN+1 ..) + * Note - pasimap.getComponents starts counting the spectrum from rank-2 to + * zero, rather than rank-1, so getComponents(dimN ...) == updateRcView(dimN+1 + * ..) * * @param dim1 * @param dim2 @@ -207,13 +209,15 @@ public class PaSiMapModel csv.append("\"" + seqs[s].getName() + "\""); if (!transformed) { - double[] fl = pasimap.component(s); - for (int d = fl.length - 1; d >= 0; d--) - { - csv.append(","); - csv.append(fl[d]); - } - } else { + double[] fl = pasimap.component(s); + for (int d = fl.length - 1; d >= 0; d--) + { + csv.append(","); + csv.append(fl[d]); + } + } + else + { Point p = points.get(s).coord; csv.append(",").append(p.x); csv.append(",").append(p.y); diff --git a/src/jalview/workers/SecondaryStructureConsensusThread.java b/src/jalview/workers/SecondaryStructureConsensusThread.java index 04cefe5..945d99b 100644 --- a/src/jalview/workers/SecondaryStructureConsensusThread.java +++ b/src/jalview/workers/SecondaryStructureConsensusThread.java @@ -169,7 +169,8 @@ public class SecondaryStructureConsensusThread extends AlignCalcWorker */ protected AlignmentAnnotation getSSConsensusAnnotation() { - return alignViewport.getAlignmentSecondaryStructureConsensusAnnotation(); + return alignViewport + .getAlignmentSecondaryStructureConsensusAnnotation(); } /** @@ -217,8 +218,8 @@ public class SecondaryStructureConsensusThread extends AlignCalcWorker * @param hconsensus * the computed consensus data */ - protected void deriveSSConsensus(AlignmentAnnotation ssConsensusAnnotation, - ProfilesI hSSConsensus) + protected void deriveSSConsensus( + AlignmentAnnotation ssConsensusAnnotation, ProfilesI hSSConsensus) { long nseq = getSequences().length; diff --git a/test/jalview/analysis/AlignSeqTest.java b/test/jalview/analysis/AlignSeqTest.java index 03bdd0b..1f94601 100644 --- a/test/jalview/analysis/AlignSeqTest.java +++ b/test/jalview/analysis/AlignSeqTest.java @@ -76,16 +76,18 @@ public class AlignSeqTest String s = "aArRnNzZxX *.-?"; assertArrayEquals(expected, as.indexEncode(s)); } - @Test(groups= {"Functional"}) + + @Test(groups = { "Functional" }) public void testGlobalAlignment() { - String seq1="CAGCTAGCG",seq2="CCATACGA"; - Sequence sq1=new Sequence("s1",seq1),sq2=new Sequence("s2",seq2); + String seq1 = "CAGCTAGCG", seq2 = "CCATACGA"; + Sequence sq1 = new Sequence("s1", seq1), sq2 = new Sequence("s2", seq2); // AlignSeq doesn't report the unaligned regions at either end of sequences - //String alseq1="-CAGCTAGCG-",alseq2="CCA--TA-CGA"; + // String alseq1="-CAGCTAGCG-",alseq2="CCA--TA-CGA"; // so we check we have the aligned segment correct only - String alseq1="CAGCTAGCG",alseq2="CA--TA-CG"; - AlignSeq as = AlignSeq.doGlobalNWAlignment(sq1,sq2,AlignSeq.DNA); - assertEquals(as.getAStr1()+"\n"+as.getAStr2(),alseq1+"\n"+alseq2); + String alseq1 = "CAGCTAGCG", alseq2 = "CA--TA-CG"; + AlignSeq as = AlignSeq.doGlobalNWAlignment(sq1, sq2, AlignSeq.DNA); + assertEquals(as.getAStr1() + "\n" + as.getAStr2(), + alseq1 + "\n" + alseq2); } } diff --git a/test/jalview/analysis/AlignmentUtilsTests.java b/test/jalview/analysis/AlignmentUtilsTests.java index d5639fa..67b9ad8 100644 --- a/test/jalview/analysis/AlignmentUtilsTests.java +++ b/test/jalview/analysis/AlignmentUtilsTests.java @@ -83,25 +83,29 @@ public class AlignmentUtilsTests { JvOptionPane.setInteractiveMode(false); JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION); - - AlignmentAnnotation ann1 = new AlignmentAnnotation("Secondary Structure", "Secondary Structure", - new Annotation[] {}); - AlignmentAnnotation ann2 = new AlignmentAnnotation("jnetpred", "jnetpred", + + AlignmentAnnotation ann1 = new AlignmentAnnotation( + "Secondary Structure", "Secondary Structure", new Annotation[] {}); + AlignmentAnnotation ann2 = new AlignmentAnnotation("jnetpred", + "jnetpred", new Annotation[] {}); AlignmentAnnotation ann3 = new AlignmentAnnotation("Temp", "Temp", new Annotation[] {}); AlignmentAnnotation ann4 = new AlignmentAnnotation("Temp", "Temp", new Annotation[] {}); - - AlignmentAnnotation[] anns1 = new AlignmentAnnotation[] {ann1, ann3, ann4}; - AlignmentAnnotation[] anns2 = new AlignmentAnnotation[] {ann2, ann3, ann4}; - - AlignmentAnnotation[] anns3 = new AlignmentAnnotation[] {ann3, ann4}; - + AlignmentAnnotation[] anns1 = new AlignmentAnnotation[] { ann1, ann3, + ann4 }; + + AlignmentAnnotation[] anns2 = new AlignmentAnnotation[] { ann2, ann3, + ann4 }; + + AlignmentAnnotation[] anns3 = new AlignmentAnnotation[] { ann3, ann4 }; + AlignmentAnnotation[] anns4 = new AlignmentAnnotation[0]; - - AlignmentAnnotation[] anns5 = new AlignmentAnnotation[] {ann1, ann2, ann3, ann4}; + + AlignmentAnnotation[] anns5 = new AlignmentAnnotation[] { ann1, ann2, + ann3, ann4 }; } @Test(groups = { "Functional" }) @@ -2775,140 +2779,181 @@ public class AlignmentUtilsTests && al.getAlignmentAnnotation().length == 2); } - - @Test(groups = "Functional", dataProvider = "SecondaryStructureAnnotations") - public void testSecondaryStructurePresentAndSources(AlignmentAnnotation[] annotations, boolean expectedSSPresent, ArrayList expectedSSSources) { - Assert.assertEquals(expectedSSPresent, AlignmentUtils.isSecondaryStructurePresent(annotations)); - Assert.assertEquals(expectedSSSources, AlignmentUtils.getSecondaryStructureSources(annotations)); - } - @DataProvider(name = "SecondaryStructureAnnotations") - public static Object[][] provideSecondaryStructureAnnotations() { - AlignmentAnnotation ann1 = new AlignmentAnnotation("Secondary Structure", "Secondary Structure", new Annotation[]{}); - AlignmentAnnotation ann2 = new AlignmentAnnotation("jnetpred", "jnetpred", new Annotation[]{}); - AlignmentAnnotation ann3 = new AlignmentAnnotation("Temp", "Temp", new Annotation[]{}); - AlignmentAnnotation ann4 = new AlignmentAnnotation("Temp", "Temp", new Annotation[]{}); - - List ssSources1 = new ArrayList<>(Arrays.asList("3D Structures")); - List ssSources2 = new ArrayList<>(Arrays.asList("JPred")); - List ssSources3 = new ArrayList<>(Arrays.asList("3D Structures", "JPred")); - List ssSources4 = new ArrayList<>(); - - return new Object[][]{ - {new AlignmentAnnotation[]{ann1, ann3, ann4}, true, ssSources1}, - {new AlignmentAnnotation[]{ann2, ann3, ann4}, true, ssSources2}, - {new AlignmentAnnotation[]{ann3, ann4}, false, ssSources4}, - {new AlignmentAnnotation[]{}, false, ssSources4}, - {new AlignmentAnnotation[]{ann1, ann2, ann3, ann4}, true, ssSources3} - }; - } - - @Test(dataProvider = "SecondaryStructureAnnotationColours") - public void testSecondaryStructureAnnotationColour(char symbol, Color expectedColor) { - Color actualColor = AlignmentUtils.getSecondaryStructureAnnotationColour(symbol); - Assert.assertEquals(actualColor, expectedColor); - } + @Test( + groups = "Functional", + dataProvider = "SecondaryStructureAnnotations") + public void testSecondaryStructurePresentAndSources( + AlignmentAnnotation[] annotations, boolean expectedSSPresent, + ArrayList expectedSSSources) + { + Assert.assertEquals(expectedSSPresent, + AlignmentUtils.isSecondaryStructurePresent(annotations)); + Assert.assertEquals(expectedSSSources, + AlignmentUtils.getSecondaryStructureSources(annotations)); + } - @DataProvider(name = "SecondaryStructureAnnotationColours") - public static Object[][] provideSecondaryStructureAnnotationColours() { - return new Object[][]{ - {'C', Color.gray}, - {'E', Color.green}, - {'H', Color.red}, - {'-', Color.gray} - }; - } - - @Test(dataProvider = "SSAnnotationPresence") - public void testIsSSAnnotationPresent(Map> annotations, boolean expectedPresence) { - boolean actualPresence = AlignmentUtils.isSSAnnotationPresent(annotations); - Assert.assertEquals(actualPresence, expectedPresence); - } + @DataProvider(name = "SecondaryStructureAnnotations") + public static Object[][] provideSecondaryStructureAnnotations() + { + AlignmentAnnotation ann1 = new AlignmentAnnotation( + "Secondary Structure", "Secondary Structure", + new Annotation[] {}); + AlignmentAnnotation ann2 = new AlignmentAnnotation("jnetpred", + "jnetpred", new Annotation[] {}); + AlignmentAnnotation ann3 = new AlignmentAnnotation("Temp", "Temp", + new Annotation[] {}); + AlignmentAnnotation ann4 = new AlignmentAnnotation("Temp", "Temp", + new Annotation[] {}); - @DataProvider(name = "SSAnnotationPresence") - public static Object[][] provideSSAnnotationPresence() { - Map> annotations1 = new HashMap<>(); - SequenceI seq1 = new Sequence("Seq1", "ASD---ASD---ASD", 37, 45); - List annotationsList1 = new ArrayList<>(); - annotationsList1.add(new AlignmentAnnotation("Secondary Structure", "Secondary Structure", new Annotation[]{})); - annotations1.put(seq1, annotationsList1); // Annotation present secondary structure for seq1 - - Map> annotations2 = new HashMap<>(); - SequenceI seq2 = new Sequence("Seq2", "ASD---ASD------", 37, 42); - List annotationsList2 = new ArrayList<>(); - annotationsList2.add(new AlignmentAnnotation("Other Annotation", "Other Annotation", new Annotation[]{})); - annotations2.put(seq2, annotationsList2); // Annotation not related to any of secondary structure for seq2 - - Map> annotations3 = new HashMap<>(); - // Empty annotation map - - Map> annotations4 = new HashMap<>(); - SequenceI seq4 = new Sequence("Seq4", "ASD---ASD---AS-", 37, 44); - List annotationsList4 = new ArrayList<>(); - annotationsList4.add(new AlignmentAnnotation("jnetpred", "jnetpred", new Annotation[]{})); - annotations4.put(seq4, annotationsList4); // Annotation present from JPred for seq4 - - - return new Object[][]{ - {annotations1, true}, // Annotations present secondary structure present - {annotations2, false}, // No annotations related to any of the secondary structure present - {annotations3, false}, // Empty annotation map - {annotations4, true}, // Annotations present from JPred secondary structure present - }; - } - - @Test - public void testGetSSSourceFromAnnotationDescription(AlignmentAnnotation[] annotations, String expectedSSSource) { - List actualSSSource = AlignmentUtils.extractSSSourceInAlignmentAnnotation(annotations); - Assert.assertEquals(actualSSSource, expectedSSSource); - } - - @DataProvider(name = "SSSourceFromAnnotationDescription") - public static Object[][] provideSSSourceFromAnnotationDescription() { - Map> annotations1 = new HashMap<>(); - SequenceI seq1 = new Sequence("Seq1", "ASD---ASD---ASD", 37, 45); - List annotationsList1 = new ArrayList<>(); - annotationsList1.add(new AlignmentAnnotation("jnetpred", "JPred Output", new Annotation[]{})); - annotations1.put(seq1, annotationsList1); // Annotation present from JPred for seq1 - - Map> annotations2 = new HashMap<>(); - SequenceI seq2 = new Sequence("Seq2", "ASD---ASD------", 37, 42); - List annotationsList2 = new ArrayList<>(); - annotationsList2.add(new AlignmentAnnotation("Secondary Structure", - "Secondary Structure for af-q43517-f1A", new Annotation[]{})); - annotations2.put(seq2, annotationsList2); // Annotation present secondary structure from Alphafold for seq2 - - Map> annotations3 = new HashMap<>(); - // Empty annotation map - - Map> annotations4 = new HashMap<>(); - SequenceI seq4 = new Sequence("Seq4", "ASD---ASD---AS-", 37, 44); - List annotationsList4 = new ArrayList<>(); - annotationsList4.add(new AlignmentAnnotation("Secondary Structure", - "Secondary Structure for 4zhpA", new Annotation[]{})); - annotations4.put(seq4, annotationsList4); // Annotation present secondary structure from pdb for seq4 - - Map> annotations5 = new HashMap<>(); - SequenceI seq5 = new Sequence("Seq5", "ASD---ASD---AS-", 37, 44); - List annotationsList5 = new ArrayList<>(); - annotationsList5.add(new AlignmentAnnotation("Secondary Structure", - "Secondary Structure for p09911_54-147__3a7wzn.1.p3502557454997462030P", - new Annotation[]{})); - annotations5.put(seq5, annotationsList5); // Annotation present secondary structure from Swiss model for seq5 - - - //JPred Output - JPred - //Secondary Structure for af-q43517-f1A - Alphafold - //Secondary Structure for 4zhpA - Experimental - //Secondary Structure for p09911_54-147__3a7wzn.1.p3502557454997462030P - Swiss Model - - return new Object[][]{ - {annotations1, "JPred"}, - {annotations2, "Alphafold"}, - {annotations3, null}, - {annotations4, "PDB"}, - {annotations5, "Swiss Model"} - }; - } + List ssSources1 = new ArrayList<>( + Arrays.asList("3D Structures")); + List ssSources2 = new ArrayList<>(Arrays.asList("JPred")); + List ssSources3 = new ArrayList<>( + Arrays.asList("3D Structures", "JPred")); + List ssSources4 = new ArrayList<>(); + + return new Object[][] { + { new AlignmentAnnotation[] + { ann1, ann3, ann4 }, true, ssSources1 }, + { new AlignmentAnnotation[] + { ann2, ann3, ann4 }, true, ssSources2 }, + { new AlignmentAnnotation[] + { ann3, ann4 }, false, ssSources4 }, + { new AlignmentAnnotation[] {}, false, ssSources4 }, + { new AlignmentAnnotation[] + { ann1, ann2, ann3, ann4 }, true, ssSources3 } }; + } + + @Test(dataProvider = "SecondaryStructureAnnotationColours") + public void testSecondaryStructureAnnotationColour(char symbol, + Color expectedColor) + { + Color actualColor = AlignmentUtils + .getSecondaryStructureAnnotationColour(symbol); + Assert.assertEquals(actualColor, expectedColor); + } + + @DataProvider(name = "SecondaryStructureAnnotationColours") + public static Object[][] provideSecondaryStructureAnnotationColours() + { + return new Object[][] { { 'C', Color.gray }, { 'E', Color.green }, + { 'H', Color.red }, + { '-', Color.gray } }; + } + + @Test(dataProvider = "SSAnnotationPresence") + public void testIsSSAnnotationPresent( + Map> annotations, + boolean expectedPresence) + { + boolean actualPresence = AlignmentUtils + .isSSAnnotationPresent(annotations); + Assert.assertEquals(actualPresence, expectedPresence); + } + + @DataProvider(name = "SSAnnotationPresence") + public static Object[][] provideSSAnnotationPresence() + { + Map> annotations1 = new HashMap<>(); + SequenceI seq1 = new Sequence("Seq1", "ASD---ASD---ASD", 37, 45); + List annotationsList1 = new ArrayList<>(); + annotationsList1.add(new AlignmentAnnotation("Secondary Structure", + "Secondary Structure", new Annotation[] {})); + annotations1.put(seq1, annotationsList1); // Annotation present secondary + // structure for seq1 + + Map> annotations2 = new HashMap<>(); + SequenceI seq2 = new Sequence("Seq2", "ASD---ASD------", 37, 42); + List annotationsList2 = new ArrayList<>(); + annotationsList2.add(new AlignmentAnnotation("Other Annotation", + "Other Annotation", new Annotation[] {})); + annotations2.put(seq2, annotationsList2); // Annotation not related to any + // of secondary structure for seq2 + + Map> annotations3 = new HashMap<>(); + // Empty annotation map + + Map> annotations4 = new HashMap<>(); + SequenceI seq4 = new Sequence("Seq4", "ASD---ASD---AS-", 37, 44); + List annotationsList4 = new ArrayList<>(); + annotationsList4.add(new AlignmentAnnotation("jnetpred", "jnetpred", + new Annotation[] {})); + annotations4.put(seq4, annotationsList4); // Annotation present from JPred + // for seq4 + + return new Object[][] { { annotations1, true }, // Annotations present + // secondary structure + // present + { annotations2, false }, // No annotations related to any of the + // secondary structure present + { annotations3, false }, // Empty annotation map + { annotations4, true }, // Annotations present from JPred secondary + // structure present + }; + } + + @Test + public void testGetSSSourceFromAnnotationDescription( + AlignmentAnnotation[] annotations, String expectedSSSource) + { + List actualSSSource = AlignmentUtils + .extractSSSourceInAlignmentAnnotation(annotations); + Assert.assertEquals(actualSSSource, expectedSSSource); + } + + @DataProvider(name = "SSSourceFromAnnotationDescription") + public static Object[][] provideSSSourceFromAnnotationDescription() + { + Map> annotations1 = new HashMap<>(); + SequenceI seq1 = new Sequence("Seq1", "ASD---ASD---ASD", 37, 45); + List annotationsList1 = new ArrayList<>(); + annotationsList1.add(new AlignmentAnnotation("jnetpred", "JPred Output", + new Annotation[] {})); + annotations1.put(seq1, annotationsList1); // Annotation present from JPred + // for seq1 + + Map> annotations2 = new HashMap<>(); + SequenceI seq2 = new Sequence("Seq2", "ASD---ASD------", 37, 42); + List annotationsList2 = new ArrayList<>(); + annotationsList2.add(new AlignmentAnnotation("Secondary Structure", + "Secondary Structure for af-q43517-f1A", new Annotation[] {})); + annotations2.put(seq2, annotationsList2); // Annotation present secondary + // structure from Alphafold for + // seq2 + + Map> annotations3 = new HashMap<>(); + // Empty annotation map + + Map> annotations4 = new HashMap<>(); + SequenceI seq4 = new Sequence("Seq4", "ASD---ASD---AS-", 37, 44); + List annotationsList4 = new ArrayList<>(); + annotationsList4.add(new AlignmentAnnotation("Secondary Structure", + "Secondary Structure for 4zhpA", new Annotation[] {})); + annotations4.put(seq4, annotationsList4); // Annotation present secondary + // structure from pdb for seq4 + + Map> annotations5 = new HashMap<>(); + SequenceI seq5 = new Sequence("Seq5", "ASD---ASD---AS-", 37, 44); + List annotationsList5 = new ArrayList<>(); + annotationsList5.add(new AlignmentAnnotation("Secondary Structure", + "Secondary Structure for p09911_54-147__3a7wzn.1.p3502557454997462030P", + new Annotation[] {})); + annotations5.put(seq5, annotationsList5); // Annotation present secondary + // structure from Swiss model for + // seq5 + + // JPred Output - JPred + // Secondary Structure for af-q43517-f1A - Alphafold + // Secondary Structure for 4zhpA - Experimental + // Secondary Structure for p09911_54-147__3a7wzn.1.p3502557454997462030P - + // Swiss Model + + return new Object[][] { { annotations1, "JPred" }, + { annotations2, "Alphafold" }, + { annotations3, null }, + { annotations4, "PDB" }, + { annotations5, "Swiss Model" } }; + } } diff --git a/test/jalview/analysis/scoremodels/ScoreModelsTest.java b/test/jalview/analysis/scoremodels/ScoreModelsTest.java index d0a8047..f82a18a 100644 --- a/test/jalview/analysis/scoremodels/ScoreModelsTest.java +++ b/test/jalview/analysis/scoremodels/ScoreModelsTest.java @@ -83,7 +83,7 @@ public class ScoreModelsTest assertFalse(sm instanceof PairwiseScoreModelI); assertTrue(sm instanceof DistanceScoreModel); assertEquals(sm.getName(), "Sequence Feature Similarity"); - + sm = models.next(); assertFalse(sm instanceof SimilarityScoreModel); assertFalse(sm instanceof PairwiseScoreModelI); diff --git a/test/jalview/analysis/scoremodels/SecondaryStructureDistanceModelTest.java b/test/jalview/analysis/scoremodels/SecondaryStructureDistanceModelTest.java index f32be37..03dcdc7 100644 --- a/test/jalview/analysis/scoremodels/SecondaryStructureDistanceModelTest.java +++ b/test/jalview/analysis/scoremodels/SecondaryStructureDistanceModelTest.java @@ -48,7 +48,7 @@ import org.testng.annotations.Test; // This class tests methods in Class SecondaryStructureDistanceModel public class SecondaryStructureDistanceModelTest { - + /** * Verify computed distances of sequences with gap */ @@ -62,7 +62,7 @@ public class SecondaryStructureDistanceModelTest ScoreModelI sm = new SecondaryStructureDistanceModel(); sm = ScoreModels.getInstance().getScoreModel(sm.getName(), af.alignPanel); - + /* * feature distance model always normalises by region width * gap-gap is always included (but scores zero) @@ -73,27 +73,28 @@ public class SecondaryStructureDistanceModelTest * include gaps * score = 0 + 0 + 1 + 0 = 1/4 */ - SimilarityParamsI params = new SimilarityParams(false, true, true, true); + SimilarityParamsI params = new SimilarityParams(false, true, true, + true); params.setSecondaryStructureSource("3D Structures"); MatrixI distances = sm.findDistances(view, params); assertEquals(distances.getValue(0, 0), 1d); assertEquals(distances.getValue(1, 1), 1d); - assertEquals(distances.getValue(0, 1), 0d); + assertEquals(distances.getValue(0, 1), 0d); assertEquals(distances.getValue(1, 0), 0d); - + /* * exclude gaps * score = 0 + 0 + 0 + 0 = 0/4 */ - - SimilarityParamsI params2 = new SimilarityParams(false, true, false, true); + + SimilarityParamsI params2 = new SimilarityParams(false, true, false, + true); params2.setSecondaryStructureSource("3D Structures"); MatrixI distances2 = sm.findDistances(view, params2); - assertEquals(distances2.getValue(0, 1), 0d); + assertEquals(distances2.getValue(0, 1), 0d); assertEquals(distances2.getValue(1, 0), 0d); } - - + /** * Verify computed distances of sequences with gap */ @@ -107,7 +108,7 @@ public class SecondaryStructureDistanceModelTest ScoreModelI sm = new SecondaryStructureDistanceModel(); sm = ScoreModels.getInstance().getScoreModel(sm.getName(), af.alignPanel); - + /* * feature distance model always normalises by region width * gap-gap is always included (but scores zero) @@ -118,27 +119,28 @@ public class SecondaryStructureDistanceModelTest * include gaps * score = 0 + 0 + 2 + 2 = 2/4 */ - SimilarityParamsI params = new SimilarityParams(false, true, true, true); + SimilarityParamsI params = new SimilarityParams(false, true, true, + true); params.setSecondaryStructureSource("3D Structures"); MatrixI distances = sm.findDistances(view, params); assertEquals(distances.getValue(0, 0), 1d); assertEquals(distances.getValue(1, 1), 1d); - assertEquals(distances.getValue(0, 1), 0d); + assertEquals(distances.getValue(0, 1), 0d); assertEquals(distances.getValue(1, 0), 0d); - + /* * exclude gaps * score = 0 + 0 + 2 + 2 = 2/4 */ - - SimilarityParamsI params2 = new SimilarityParams(false, true, false, true); + + SimilarityParamsI params2 = new SimilarityParams(false, true, false, + true); params2.setSecondaryStructureSource("3D Structures"); MatrixI distances2 = sm.findDistances(view, params2); - assertEquals(distances2.getValue(0, 1), 0d); + assertEquals(distances2.getValue(0, 1), 0d); assertEquals(distances2.getValue(1, 0), 0d); } - /** * Verify computed distances of sequences with gap */ @@ -152,7 +154,7 @@ public class SecondaryStructureDistanceModelTest ScoreModelI sm = new SecondaryStructureDistanceModel(); sm = ScoreModels.getInstance().getScoreModel(sm.getName(), af.alignPanel); - + /* * feature distance model always normalises by region width * gap-gap is always included (but scores zero) @@ -163,28 +165,28 @@ public class SecondaryStructureDistanceModelTest * include gaps * score = 0 + 0 + 2 + 2 = 2/4 */ - SimilarityParamsI params = new SimilarityParams(false, true, true, true); + SimilarityParamsI params = new SimilarityParams(false, true, true, + true); params.setSecondaryStructureSource("3D Structures"); MatrixI distances = sm.findDistances(view, params); assertEquals(distances.getValue(0, 0), 1d); assertEquals(distances.getValue(1, 1), 1d); - assertEquals(distances.getValue(0, 1), 0d); + assertEquals(distances.getValue(0, 1), 0d); assertEquals(distances.getValue(1, 0), 0d); - + /* * exclude gaps * score = 0 + 0 + 2 + 2 = 2/4 */ - - SimilarityParamsI params2 = new SimilarityParams(false, true, false, true); + + SimilarityParamsI params2 = new SimilarityParams(false, true, false, + true); params2.setSecondaryStructureSource("3D Structures"); MatrixI distances2 = sm.findDistances(view, params2); - assertEquals(distances2.getValue(0, 1), 0d); + assertEquals(distances2.getValue(0, 1), 0d); assertEquals(distances2.getValue(1, 0), 0d); } - - /** *

        * Set up
    @@ -214,18 +216,17 @@ public class SecondaryStructureDistanceModelTest
                 new SequenceFeature("metal", null, 1, 4, 0f, null));
         s2.addSequenceFeature(
                 new SequenceFeature("Pfam", null, 1, 4, 0f, null));
    -    
    -    
    +
         /*
          * Set up secondary structure annotations
          */
    -    Annotation ssE = new Annotation("","",'E',0);
    -    Annotation ssH = new Annotation("","",'H',0);
    -    Annotation ssC = new Annotation(".","",' ',0);
    -    
    +    Annotation ssE = new Annotation("", "", 'E', 0);
    +    Annotation ssH = new Annotation("", "", 'H', 0);
    +    Annotation ssC = new Annotation(".", "", ' ', 0);
    +
         Annotation[] anns1;
         Annotation[] anns2;
    -    
    +
         /* All secondary structure annotations are similar for each column
          * Set up
         *   column      1 2 3 4 
    @@ -235,13 +236,14 @@ public class SecondaryStructureDistanceModelTest
         *        seq s2 F S J L
         *        	 ss E H S E
         */
    -    if(similar == "All Similar") {
    -    
    -    	anns1 = new Annotation[] { ssE, ssH, ssC, ssE};
    -    	anns2 = new Annotation[] { ssE, ssH, ssC, ssE};
    -    
    +    if (similar == "All Similar")
    +    {
    +
    +      anns1 = new Annotation[] { ssE, ssH, ssC, ssE };
    +      anns2 = new Annotation[] { ssE, ssH, ssC, ssE };
    +
         }
    -    
    +
         /* All secondary structure annotations are dissimilar for each column
          * Set up
          *   column      1 2 3 4 
    @@ -251,13 +253,14 @@ public class SecondaryStructureDistanceModelTest
          *        seq s2 F S J L
          *        	  ss H E E C
          */
    -    else if(similar == "Not Similar") {
    -        
    -    	anns1 = new Annotation[] { ssE, ssE, ssC, ssE};
    -    	anns2 = new Annotation[] { ssH, ssH, ssE, ssC};
    -    
    +    else if (similar == "Not Similar")
    +    {
    +
    +      anns1 = new Annotation[] { ssE, ssE, ssC, ssE };
    +      anns2 = new Annotation[] { ssH, ssH, ssE, ssC };
    +
         }
    -    
    +
         /* All secondary structure annotations are dissimilar for each column
          * Set up
          *   column      1 2 3 4 
    @@ -267,13 +270,14 @@ public class SecondaryStructureDistanceModelTest
          *        seq s2 F S J L
          *            ss H E E C
          */
    -    else if(similar == "With Coil") {
    -        
    -      anns1 = new Annotation[] { ssE, ssE, null, ssE};
    -      anns2 = new Annotation[] { ssH, ssH, ssE, null};
    -    
    +    else if (similar == "With Coil")
    +    {
    +
    +      anns1 = new Annotation[] { ssE, ssE, null, ssE };
    +      anns2 = new Annotation[] { ssH, ssH, ssE, null };
    +
         }
    -    
    +
         /*  Set up
          *   column      1 2 3 4 
          *        seq s1 F R K S
    @@ -282,28 +286,27 @@ public class SecondaryStructureDistanceModelTest
          *        seq s2 F S J L
          *        	  ss H E E C
          */
    -    else {
    -    	
    -    	anns1 = new Annotation[] { ssH, ssE, ssC, ssE};
    -    	anns2 = new Annotation[] { ssH, ssE, ssE, ssC};
    +    else
    +    {
    +
    +      anns1 = new Annotation[] { ssH, ssE, ssC, ssE };
    +      anns2 = new Annotation[] { ssH, ssE, ssE, ssC };
         }
    -    
    -    
    -    AlignmentAnnotation ann1 = new AlignmentAnnotation("Secondary Structure",
    -            "Secondary Structure", anns1);
    -    AlignmentAnnotation ann2 = new AlignmentAnnotation("Secondary Structure",
    -            "Secondary Structure", anns2);
    -    
    +
    +    AlignmentAnnotation ann1 = new AlignmentAnnotation(
    +            "Secondary Structure", "Secondary Structure", anns1);
    +    AlignmentAnnotation ann2 = new AlignmentAnnotation(
    +            "Secondary Structure", "Secondary Structure", anns2);
    +
         s1.addAlignmentAnnotation(ann1);
    -    s2.addAlignmentAnnotation(ann2);    
    -    
    +    s2.addAlignmentAnnotation(ann2);
    +
         AlignmentI al = new Alignment(new SequenceI[] { s1, s2 });
         AlignFrame af = new AlignFrame(al, 300, 300);
         af.setShowSeqFeatures(true);
         af.getFeatureRenderer().findAllFeatures(true);
         return af;
       }
    -  
     
       /**
        * 
    @@ -320,7 +323,7 @@ public class SecondaryStructureDistanceModelTest
        */
       protected AlignFrame setupAlignmentViewWithGap()
       {
    -    
    +
         SequenceI s1 = new Sequence("s1", "FR S");
         SequenceI s2 = new Sequence("s2", "FSJL");
     
    @@ -334,39 +337,39 @@ public class SecondaryStructureDistanceModelTest
                 new SequenceFeature("metal", null, 1, 4, 0f, null));
         s2.addSequenceFeature(
                 new SequenceFeature("Pfam", null, 1, 4, 0f, null));
    -    
    -    
    -    Annotation ssE = new Annotation("","",'E',0);
    -    Annotation ssH = new Annotation("","",'H',0);
    -    Annotation ssC = new Annotation(".","",' ',0);
    -    
    +
    +    Annotation ssE = new Annotation("", "", 'E', 0);
    +    Annotation ssH = new Annotation("", "", 'H', 0);
    +    Annotation ssC = new Annotation(".", "", ' ', 0);
    +
         Annotation[] anns1;
         Annotation[] anns2;
    -    	
    -    anns1 = new Annotation[] { ssH, ssE, ssC};
    -    anns2 = new Annotation[] { ssH, ssE, ssE, ssC};    
    -    
    -    AlignmentAnnotation ann1 = new AlignmentAnnotation("Secondary Structure",
    -            "Secondary Structure", anns1);
    -    AlignmentAnnotation ann2 = new AlignmentAnnotation("Secondary Structure",
    -            "Secondary Structure", anns2);
    -    
    +
    +    anns1 = new Annotation[] { ssH, ssE, ssC };
    +    anns2 = new Annotation[] { ssH, ssE, ssE, ssC };
    +
    +    AlignmentAnnotation ann1 = new AlignmentAnnotation(
    +            "Secondary Structure", "Secondary Structure", anns1);
    +    AlignmentAnnotation ann2 = new AlignmentAnnotation(
    +            "Secondary Structure", "Secondary Structure", anns2);
    +
         s1.addAlignmentAnnotation(ann1);
    -    s2.addAlignmentAnnotation(ann2);    
    -        
    +    s2.addAlignmentAnnotation(ann2);
    +
         AlignmentI al = new Alignment(new SequenceI[] { s1, s2 });
         AlignFrame af = new AlignFrame(al, 300, 300);
         af.setShowSeqFeatures(true);
         af.getFeatureRenderer().findAllFeatures(true);
    -    
    +
         return af;
       }
    -  
    -  protected AlignFrame setupAlignmentViewWithoutSS(String type) {
    -    
    +
    +  protected AlignFrame setupAlignmentViewWithoutSS(String type)
    +  {
    +
         SequenceI s1 = new Sequence("s1", "FR S");
         SequenceI s2 = new Sequence("s2", "FSJL");
    -    
    +
         s1.addSequenceFeature(
                 new SequenceFeature("chain", null, 1, 3, 0f, null));
         s1.addSequenceFeature(
    @@ -377,60 +380,61 @@ public class SecondaryStructureDistanceModelTest
                 new SequenceFeature("metal", null, 1, 4, 0f, null));
         s2.addSequenceFeature(
                 new SequenceFeature("Pfam", null, 1, 4, 0f, null));
    -    
    -    if(!type.equals("both")) {    
    -      Annotation ssE = new Annotation("","",'E',0);
    -      Annotation ssH = new Annotation("","",'H',0);
    -      Annotation ssC = new Annotation(".","",' ',0);
    -      
    +
    +    if (!type.equals("both"))
    +    {
    +      Annotation ssE = new Annotation("", "", 'E', 0);
    +      Annotation ssH = new Annotation("", "", 'H', 0);
    +      Annotation ssC = new Annotation(".", "", ' ', 0);
    +
           Annotation[] anns1;
    -        
    -      anns1 = new Annotation[] { ssH, ssE, ssC};
    -          
    -      AlignmentAnnotation ann1 = new AlignmentAnnotation("Secondary Structure",
    -              "Secondary Structure", anns1);    
    -  
    -      s1.addAlignmentAnnotation(ann1);    
    +
    +      anns1 = new Annotation[] { ssH, ssE, ssC };
    +
    +      AlignmentAnnotation ann1 = new AlignmentAnnotation(
    +              "Secondary Structure", "Secondary Structure", anns1);
    +
    +      s1.addAlignmentAnnotation(ann1);
         }
    -    
    +
         AlignmentI al = new Alignment(new SequenceI[] { s1, s2 });
         AlignFrame af = new AlignFrame(al, 300, 300);
         af.setShowSeqFeatures(true);
         af.getFeatureRenderer().findAllFeatures(true);
         return af;
       }
    -  
    -  
    +
       @DataProvider(name = "testData")
    -  public Object[][] testData() {
    -      return new Object[][] {
    -              {"All Similar", 1d, 1d, 0d, 0d / 4},
    -              {"Partially Similar", 1d, 1d, 0d, 0d},
    -              {"Not Similar", 1d, 1d, 0d, 0d},
    -              {"With Coil", 1d, 1d, 0d, 0d},
    -      };
    +  public Object[][] testData()
    +  {
    +    return new Object[][] { { "All Similar", 1d, 1d, 0d, 0d / 4 },
    +        { "Partially Similar", 1d, 1d, 0d, 0d },
    +        { "Not Similar", 1d, 1d, 0d, 0d },
    +        { "With Coil", 1d, 1d, 0d, 0d }, };
       }
     
       @Test(dataProvider = "testData")
    -  public void testFindDistances(String scenario, double expectedValue00, double expectedValue11,
    -                                 double expectedValue01, double expectedValue10) {
    -      AlignFrame af = setupAlignmentView(scenario);
    -      AlignViewport viewport = af.getViewport();
    -      AlignmentView view = viewport.getAlignmentView(false);
    -
    -      ScoreModelI sm = new SecondaryStructureDistanceModel();
    -      sm = ScoreModels.getInstance().getScoreModel(sm.getName(),
    -              af.alignPanel);
    -
    -      SimilarityParamsI params = new SimilarityParams(false, true, true, true);
    -      params.setSecondaryStructureSource("3D Structures");
    -      MatrixI distances = sm.findDistances(view, params);
    -
    -      assertEquals(distances.getValue(0, 0), expectedValue00);
    -      assertEquals(distances.getValue(1, 1), expectedValue11);
    -      assertEquals(distances.getValue(0, 1), expectedValue01);
    -      assertEquals(distances.getValue(1, 0), expectedValue10);
    +  public void testFindDistances(String scenario, double expectedValue00,
    +          double expectedValue11, double expectedValue01,
    +          double expectedValue10)
    +  {
    +    AlignFrame af = setupAlignmentView(scenario);
    +    AlignViewport viewport = af.getViewport();
    +    AlignmentView view = viewport.getAlignmentView(false);
    +
    +    ScoreModelI sm = new SecondaryStructureDistanceModel();
    +    sm = ScoreModels.getInstance().getScoreModel(sm.getName(),
    +            af.alignPanel);
    +
    +    SimilarityParamsI params = new SimilarityParams(false, true, true,
    +            true);
    +    params.setSecondaryStructureSource("3D Structures");
    +    MatrixI distances = sm.findDistances(view, params);
    +
    +    assertEquals(distances.getValue(0, 0), expectedValue00);
    +    assertEquals(distances.getValue(1, 1), expectedValue11);
    +    assertEquals(distances.getValue(0, 1), expectedValue01);
    +    assertEquals(distances.getValue(1, 0), expectedValue10);
       }
     
    -  
     }
    diff --git a/test/jalview/commands/EditCommandTest.java b/test/jalview/commands/EditCommandTest.java
    index 1255c58..2e36111 100644
    --- a/test/jalview/commands/EditCommandTest.java
    +++ b/test/jalview/commands/EditCommandTest.java
    @@ -1182,12 +1182,14 @@ public class EditCommandTest
         assertEquals(10, sf.getBegin());
         assertEquals(11, sf.getEnd());
       }
    +
       private SequenceI mkDs(SequenceI as)
       {
         SequenceI ds = as.createDatasetSequence();
         ds.setSequence(ds.getSequenceAsString().toUpperCase(Locale.ROOT));
         return ds;
       }
    +
       /**
        * Test that mimics 'remove all gapped columns' action. This generates a
        * series Delete Gap edits that each act on all sequences that share a gapped
    @@ -1210,35 +1212,38 @@ public class EditCommandTest
          * and check we are preserving data - if the calls below fail, something has broken the Jalview dataset derivation process
          */
         assertEquals("ABCDEF", seq1.getDatasetSequence().getSequenceAsString());
    -    assertEquals(original1,seq1.getSequenceAsString());
    -    SequenceI seq2 = new Sequence("sq2",original2);
    +    assertEquals(original1, seq1.getSequenceAsString());
    +    SequenceI seq2 = new Sequence("sq2", original2);
         SequenceI ds2 = mkDs(seq2);
         SequenceI seq3 = new Sequence("sq3", original3);
         SequenceI ds3 = mkDs(seq3);
    -    List sqs = Arrays.asList( seq1, seq2, seq3 );
    +    List sqs = Arrays.asList(seq1, seq2, seq3);
         Alignment al = new Alignment(sqs.toArray(new SequenceI[0]));
    -    EditCommand lefj = new JustifyLeftOrRightCommand("Left J", true, sqs, 1, 7, al);
    +    EditCommand lefj = new JustifyLeftOrRightCommand("Left J", true, sqs, 1,
    +            7, al);
         String exp = "-ABcD---EF";
         // check without case conservation
    -    assertEquals(exp.toUpperCase(Locale.ROOT),seq1.getSequenceAsString().toUpperCase(Locale.ROOT));
    +    assertEquals(exp.toUpperCase(Locale.ROOT),
    +            seq1.getSequenceAsString().toUpperCase(Locale.ROOT));
         // check case
    -    assertEquals(exp,seq1.getSequenceAsString());
    +    assertEquals(exp, seq1.getSequenceAsString());
         // and other seqs
    -    assertEquals("-GHiJ---",seq2.getSequenceAsString());
    -    assertEquals("-MNoP---Q",seq3.getSequenceAsString());
    -    lefj.undoCommand(new AlignmentI[] { al});
    -    assertEquals(original3,seq3.getSequenceAsString());
    -    assertEquals(original1,seq1.getSequenceAsString());
    -    assertEquals(original2,seq2.getSequenceAsString());
    -    
    -    EditCommand righj = new JustifyLeftOrRightCommand("Right J", false, sqs, 2, 7, al);
    -    assertEquals("----ABcDEF",seq1.getSequenceAsString());
    -    assertEquals("-G---HiJ",seq2.getSequenceAsString());
    -    assertEquals("-M---NoPQ",seq3.getSequenceAsString());
    -    righj.undoCommand(new AlignmentI[] { al});
    -    assertEquals(original3,seq3.getSequenceAsString());
    -    assertEquals(original1,seq1.getSequenceAsString());
    -    assertEquals(original2,seq2.getSequenceAsString());
    -        
    +    assertEquals("-GHiJ---", seq2.getSequenceAsString());
    +    assertEquals("-MNoP---Q", seq3.getSequenceAsString());
    +    lefj.undoCommand(new AlignmentI[] { al });
    +    assertEquals(original3, seq3.getSequenceAsString());
    +    assertEquals(original1, seq1.getSequenceAsString());
    +    assertEquals(original2, seq2.getSequenceAsString());
    +
    +    EditCommand righj = new JustifyLeftOrRightCommand("Right J", false, sqs,
    +            2, 7, al);
    +    assertEquals("----ABcDEF", seq1.getSequenceAsString());
    +    assertEquals("-G---HiJ", seq2.getSequenceAsString());
    +    assertEquals("-M---NoPQ", seq3.getSequenceAsString());
    +    righj.undoCommand(new AlignmentI[] { al });
    +    assertEquals(original3, seq3.getSequenceAsString());
    +    assertEquals(original1, seq1.getSequenceAsString());
    +    assertEquals(original2, seq2.getSequenceAsString());
    +
       }
     }
    diff --git a/test/jalview/gui/AssociatePDBFileTest.java b/test/jalview/gui/AssociatePDBFileTest.java
    index 0e6791b..c1b5b6e 100644
    --- a/test/jalview/gui/AssociatePDBFileTest.java
    +++ b/test/jalview/gui/AssociatePDBFileTest.java
    @@ -20,7 +20,6 @@
      */
     package jalview.gui;
     
    -
     import java.awt.Color;
     import java.io.File;
     import java.util.Iterator;
    @@ -92,18 +91,14 @@ public class AssociatePDBFileTest
                 + "KVRLYSIASSAIGDFGDSKTVSLCVKRLIYTNDAGEIVKGVCSNFLCDLQPGDNVQITGPVGKEMLMPKDPN\n"
                 + "ATIIMLATGTGIAPFRSFLWKMFFEKHDDYKFNGLGWLFLGVPTSSSLLYKEEFGKMKERAPENFRVDYAVS\n"
                 + "REQTNAAGERMYIQTRMAEYKEELWELLKKDNTYVYMCGLKGMEKGIDDIMVSLAEKDGIDWFDYKKQLKRG\n"
    -            + "DQWNVEVY\n"
    -            + ">1GAQ|B/1-98\n"
    +            + "DQWNVEVY\n" + ">1GAQ|B/1-98\n"
                 + "ATYNVKLITPEGEVELQVPDDVYILDQAEEDGIDLPYSCRAGSCSSCAGKVVSGSVDQSDQSYLDDGQIADG\n"
    -            + "WVLTCHAYPTSDVVIETHKEEELTGA\n"
    -            + ">1GAQ|C/19-314\n"
    +            + "WVLTCHAYPTSDVVIETHKEEELTGA\n" + ">1GAQ|C/19-314\n"
                 + "ESKKQEEGVVTNLYKPKEPYVGRCLLNTKITGDDAPGETWHMVFSTEGKIPYREGQSIGVIADGVDKNGKPH\n"
                 + "KVRLYSIASSAIGDFGDSKTVSLCVKRLIYTNDAGEIVKGVCSNFLCDLQPGDNVQITGPVGKEMLMPKDPN\n"
                 + "ATIIMLATGTGIAPFRSFLWKMFFEKHDDYKFNGLGWLFLGVPTSSSLLYKEEFGKMKERAPENFRVDYAVS\n"
                 + "REQTNAAGERMYIQTRMAEYKEELWELLKKDNTYVYMCGLKGMEKGIDDIMVSLAEKDGIDWFDYKKQLKRG\n"
    -            + "DQWNVEVY\n"
    -            ,
    -            DataSourceType.PASTE);
    +            + "DQWNVEVY\n", DataSourceType.PASTE);
     
         /*
          * wait for Consensus thread to complete
    @@ -128,15 +123,15 @@ public class AssociatePDBFileTest
       @Test(groups = "Functional")
       public void testAssociatePDBFile()
       {
    -    String assoc_file="examples/1gaq.txt";
    -    for (SequenceI toassoc:af.getViewport().getAlignment().getSequences())
    +    String assoc_file = "examples/1gaq.txt";
    +    for (SequenceI toassoc : af.getViewport().getAlignment().getSequences())
         {
    -      PDBEntry pe = new AssociatePdbFileWithSeq()
    -              .associatePdbWithSeq(assoc_file,
    -                      DataSourceType.FILE, toassoc, false,
    -                      Desktop.instance);
    +      PDBEntry pe = new AssociatePdbFileWithSeq().associatePdbWithSeq(
    +              assoc_file, DataSourceType.FILE, toassoc, false,
    +              Desktop.instance);
           Assert.assertNotNull(pe);
    -      Assert.assertNotEquals(toassoc.getDatasetSequence().getAnnotation().length,0);
    +      Assert.assertNotEquals(
    +              toassoc.getDatasetSequence().getAnnotation().length, 0);
         }
       }
     }
    diff --git a/test/jalview/gui/CalculationChooserTest.java b/test/jalview/gui/CalculationChooserTest.java
    index ac02c03..e6316f3 100644
    --- a/test/jalview/gui/CalculationChooserTest.java
    +++ b/test/jalview/gui/CalculationChooserTest.java
    @@ -55,29 +55,33 @@ public class CalculationChooserTest
          * peptide models for PCA
          */
         List filtered = CalculationChooser
    -            .getApplicableScoreModels(false, true, true,false);
    +            .getApplicableScoreModels(false, true, true, false);
         assertEquals(filtered.size(), 5);
         assertSame(filtered.get(0), blosum62);
         assertSame(filtered.get(1), pam250);
         assertEquals(filtered.get(2).getName(), "PID");
         assertEquals(filtered.get(3).getName(), "Sequence Feature Similarity");
    -    assertEquals(filtered.get(4).getName(), "Secondary Structure Similarity");
    +    assertEquals(filtered.get(4).getName(),
    +            "Secondary Structure Similarity");
     
         /*
          * peptide models for Tree are the same
          */
    -    filtered = CalculationChooser.getApplicableScoreModels(false, false, true,false);
    +    filtered = CalculationChooser.getApplicableScoreModels(false, false,
    +            true, false);
         assertEquals(filtered.size(), 5);
         assertSame(filtered.get(0), blosum62);
         assertSame(filtered.get(1), pam250);
         assertEquals(filtered.get(2).getName(), "PID");
         assertEquals(filtered.get(3).getName(), "Sequence Feature Similarity");
    -    assertEquals(filtered.get(4).getName(), "Secondary Structure Similarity");
    +    assertEquals(filtered.get(4).getName(),
    +            "Secondary Structure Similarity");
     
         /*
          * nucleotide models for PCA
          */
    -    filtered = CalculationChooser.getApplicableScoreModels(true, true, false,false);
    +    filtered = CalculationChooser.getApplicableScoreModels(true, true,
    +            false, false);
         assertEquals(filtered.size(), 3);
         assertSame(filtered.get(0), dna);
         assertEquals(filtered.get(1).getName(), "PID");
    @@ -86,7 +90,8 @@ public class CalculationChooserTest
         /*
          * nucleotide models for Tree are the same
          */
    -    filtered = CalculationChooser.getApplicableScoreModels(true, false, false,false);
    +    filtered = CalculationChooser.getApplicableScoreModels(true, false,
    +            false, false);
         assertEquals(filtered.size(), 3);
         assertSame(filtered.get(0), dna);
         assertEquals(filtered.get(1).getName(), "PID");
    @@ -101,30 +106,37 @@ public class CalculationChooserTest
         /*
          * nucleotide models for Tree are unchanged
          */
    -    filtered = CalculationChooser.getApplicableScoreModels(true, false, true,false);
    +    filtered = CalculationChooser.getApplicableScoreModels(true, false,
    +            true, false);
         assertEquals(filtered.size(), 4);
         assertSame(filtered.get(0), dna);
         assertEquals(filtered.get(1).getName(), "PID");
         assertEquals(filtered.get(2).getName(), "Sequence Feature Similarity");
    -    assertEquals(filtered.get(3).getName(), "Secondary Structure Similarity");
    +    assertEquals(filtered.get(3).getName(),
    +            "Secondary Structure Similarity");
     
         /*
          * nucleotide models for PCA add BLOSUM62 as last option
          */
    -    filtered = CalculationChooser.getApplicableScoreModels(true, true, false,false);
    +    filtered = CalculationChooser.getApplicableScoreModels(true, true,
    +            false, false);
         assertEquals(filtered.size(), 4);
         assertSame(filtered.get(0), dna);
         assertEquals(filtered.get(1).getName(), "PID");
         assertEquals(filtered.get(2).getName(), "Sequence Feature Similarity");
         assertSame(filtered.get(3), blosum62);
    -    
    -    filtered = CalculationChooser.getApplicableScoreModels(true, true, false,true);
    +
    +    filtered = CalculationChooser.getApplicableScoreModels(true, true,
    +            false, true);
         assertEquals(filtered.size(), 1); // DNA matrix for DNA pasimap
    -    for (int i=0; i<=8;i++)
    +    for (int i = 0; i <= 8; i++)
         {
    -      boolean isDna = (i & 1) != 0,isPca = (i & 2) != 0,isSS = (i & 4) != 0;
    -     
    -      assertEquals(CalculationChooser.getApplicableScoreModels(isDna,isPca,isSS,true).size(), (isDna) ? 1: 2);
    +      boolean isDna = (i & 1) != 0, isPca = (i & 2) != 0,
    +              isSS = (i & 4) != 0;
    +
    +      assertEquals(CalculationChooser
    +              .getApplicableScoreModels(isDna, isPca, isSS, true).size(),
    +              (isDna) ? 1 : 2);
         }
       }
     }
    diff --git a/test/jalview/project/Jalview2xmlTests.java b/test/jalview/project/Jalview2xmlTests.java
    index 8b2fa74..ca90d8a 100644
    --- a/test/jalview/project/Jalview2xmlTests.java
    +++ b/test/jalview/project/Jalview2xmlTests.java
    @@ -250,9 +250,8 @@ public class Jalview2xmlTests extends Jalview2xmlBase
     
         boolean diffseqcols = false, diffgseqcols = false;
         SequenceI[] sqs = af.getViewport().getAlignment().getSequencesArray();
    -    for (int p = 0,
    -            pSize = af.getViewport().getAlignment().getWidth(); p < pSize
    -                    && (!diffseqcols || !diffgseqcols); p++)
    +    for (int p = 0, pSize = af.getViewport().getAlignment()
    +            .getWidth(); p < pSize && (!diffseqcols || !diffgseqcols); p++)
         {
           if (_rcs.findColour(sqs[0].getCharAt(p), p, sqs[0], null, 0f) != _rcs
                   .findColour(sqs[5].getCharAt(p), p, sqs[5], null, 0f))
    @@ -271,9 +270,8 @@ public class Jalview2xmlTests extends Jalview2xmlBase
         assertTrue(__rcs.isSeqAssociated(),
                 "Group Annotation colourscheme wasn't sequence associated");
     
    -    for (int p = 0,
    -            pSize = af.getViewport().getAlignment().getWidth(); p < pSize
    -                    && (!diffseqcols || !diffgseqcols); p++)
    +    for (int p = 0, pSize = af.getViewport().getAlignment()
    +            .getWidth(); p < pSize && (!diffseqcols || !diffgseqcols); p++)
         {
           if (_rgcs.findColour(sqs[1].getCharAt(p), p, sqs[1], null,
                   0f) != _rgcs.findColour(sqs[2].getCharAt(p), p, sqs[2], null,
    diff --git a/test/jalview/renderer/ResidueShaderTest.java b/test/jalview/renderer/ResidueShaderTest.java
    index 081272a..528abed 100644
    --- a/test/jalview/renderer/ResidueShaderTest.java
    +++ b/test/jalview/renderer/ResidueShaderTest.java
    @@ -345,7 +345,7 @@ public class ResidueShaderTest
                       SecondaryStructureCount secondaryStructureCount)
               {
                 // TODO Auto-generated method stub
    -            
    +
               }
     
               @Override
    diff --git a/test/jalview/schemes/ClustalxColourSchemeTest.java b/test/jalview/schemes/ClustalxColourSchemeTest.java
    index d476d6e..983f94c 100644
    --- a/test/jalview/schemes/ClustalxColourSchemeTest.java
    +++ b/test/jalview/schemes/ClustalxColourSchemeTest.java
    @@ -151,6 +151,7 @@ public class ClustalxColourSchemeTest
         // viewport
         // assertEquals(cs.findColour('C', 0, al.getSequenceAt(0)), clustalPink);
       }
    +
       @Test
       public void testDocString()
       {
    diff --git a/test/jalview/util/FileUtilsTest.java b/test/jalview/util/FileUtilsTest.java
    index acc754f..62dc73e 100644
    --- a/test/jalview/util/FileUtilsTest.java
    +++ b/test/jalview/util/FileUtilsTest.java
    @@ -79,6 +79,7 @@ public class FileUtilsTest
     
       /**
        * these need to be maintained as jalview's source base grows
    +   * 
        * @return
        */
       @DataProvider(name = "patternsAndMinNumFiles")
    -- 
    1.7.10.2