// jalview.bin.Console.outPrintln(elapsed);
}
-
public static final ProfilesI calculateSS(List<SequenceI> list, int start,
int end)
{
return calculateSS(list, start, end, false);
}
-
+
public static final ProfilesI calculateSS(List<SequenceI> sequences,
int start, int end, boolean profile)
{
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++)
"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();
}
}
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)
{
// 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.
}
return description;
}
-
+
static String getSSTooltip(ProfileI profile, float pid,
boolean showSequenceLogo, boolean ignoreGaps, int dp)
{
{
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;
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;
int[] aseq1;
int[] aseq2;
-
+
/*
* matches in alignment
*/
- int match=-1;
+ int match = -1;
public String astr1 = "";
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;
GAP_OPEN_COST = opencost;
GAP_EXTEND_COST = extcost;
}
+
public AlignSeq(SequenceI s1, SequenceI s2, String type)
{
seqInit(s1, s1.getSequenceAsString(), s2, s2.getSequenceAsString(),
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;
}
/**
}
/**
- * returns the overall score of the alignment
- *
- * @return
- */
+ * returns the overall score of the alignment
+ *
+ * @return
+ */
public float getAlignmentScore()
{
return alignmentScore;
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;
}
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);
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];
{
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
int trace;
maxscore = score[i][j] / 10f;
- //prepare trailing gaps
+ // prepare trailing gaps
while ((i < seq1.length - 1) || (j < seq2.length - 1))
{
i++;
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--;
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("-");
}
}
{
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),
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;
}
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();
}
/**
- * 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<Character, Integer> seq1ResCount = new HashMap<Character, Integer>();
HashMap<Character, Integer> seq2ResCount = new HashMap<Character, Integer>();
- // 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;
}
/**
- * 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
}
}
/**
- * 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()
{
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;
+ }
}
}
{
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
}
}
}
-
-
- public static boolean isSSAnnotationPresent( Map<SequenceI, List<AlignmentAnnotation>> annotations) {
-
+
+ public static boolean isSSAnnotationPresent(
+ Map<SequenceI, List<AlignmentAnnotation>> 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;
}
}
return true;
}
-
-
- public static List<String> getSecondaryStructureSources(AlignmentAnnotation[] annotations) {
-
- List<String> ssSources = new ArrayList<>();
- Set<String> 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<String> getSecondaryStructureSources(
+ AlignmentAnnotation[] annotations)
+ {
+
+ List<String> ssSources = new ArrayList<>();
+ Set<String> 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<String> extractSSSourceInAlignmentAnnotation(AlignmentAnnotation[] annotations) {
-
+
+ public static List<String> extractSSSourceInAlignmentAnnotation(
+ AlignmentAnnotation[] annotations)
+ {
+
List<String> ssSources = new ArrayList<>();
- Set<String> addedSources = new HashSet<>(); // to keep track of added sources
+ Set<String> 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<PDBEntry> 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<PDBEntry> 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;
-
+
}
-
+
}
public class ConnectivityException extends RuntimeException
{
private String sequence;
+
private int connection;
+
private byte dim;
public ConnectivityException(String sequence, int connection, byte dim)
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;
}
else
{
- //allFeatures = sf.getAllFeatures(null);
+ // allFeatures = sf.getAllFeatures(null);
allFeatures = sf.getAllFeatures();
}
// so we can check we are advancing when debugging
/**
* Performs Principal Component Analysis on given sequences
- * @AUTHOR MorellThomas
+ *
+ * @AUTHOR MorellThomas
*/
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;
}
* DOCUMENT ME!
* @param mm
* DOCUMENT ME!
- * @param factor ~ is 1
+ * @param factor
+ * ~ is 1
*
* @return DOCUMENT ME!
*/
}
/**
- * 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
*/
/**
* 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
{
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);
/**
* 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)
{
{
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++)
{
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);
// 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;
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<int[]> estimatedPositions = new ArrayList<int[]>();
-
- // 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<int[]> estimatedPositions = new ArrayList<int[]>();
+
+ // 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<Double, Integer> 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<Double, Integer> 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<Double, Integer> 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<Double, Integer> 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)
{
}
/**
- * 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++)
{
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];
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();
}
/**
- * 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)
{
return this.alpha;
}
-
+
public int getIteration()
{
return this.iteration;
}
/**
- * 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)
{
}
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);
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];
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));
}
/**
- * 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)
{
}
/**
- * 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;
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;
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);
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++;
}
}
/**
- * 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);
return similarities;
}
-
+
}
public boolean isProtein()
{
return true;
- }
+ }
@Override
public String toString()
private final ScoreMatrix PAM250;
private final ScoreMatrix DNA;
-
+
private final ScoreMatrix SECONDARYSTRUCTURE;
private static ScoreModels instance;
* <li>PAM250</li>
* <li>PID</li>
* <li>DNA</li>
- * <li>Sequence Feature Similarity</li> *
+ * <li>Sequence Feature Similarity</li> *
* <li>Secondary Structure Similarity</li>
* </ul>
*/
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());
}
public void registerScoreModel(ScoreModelI sm)
{
- if(sm.getName().equals("SECONDARYSTRUCTURE")) {
+ if (sm.getName().equals("SECONDARYSTRUCTURE"))
+ {
return;
}
ScoreModelI sm2 = models.get(sm.getName());
{
return PAM250;
}
-
+
public ScoreMatrix getSecondaryStructureMatrix()
{
return SECONDARYSTRUCTURE;
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)
{
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.
* <p>
- * 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<String, HashSet<String>> ssAlignmentAnnotationForSequences
- = new HashMap<String,HashSet<String>>();
-
+ Map<String, HashSet<String>> ssAlignmentAnnotationForSequences = new HashMap<String, HashSet<String>>();
+
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:
* 2. Sequences whose secondary structure annotations are not added to
* the annotation track
*/
- Set<SeqCigar> seqsWithUndefinedSS
- = findSeqsWithUndefinedSS(seqs, ssAlignmentAnnotationForSequences);
+ Set<SeqCigar> seqsWithUndefinedSS = findSeqsWithUndefinedSS(seqs,
+ ssAlignmentAnnotationForSequences);
/*
* scan each column, compute and add to each similarity[i, j]
*/
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<SeqCigar> seqsWithoutGapAtCol = findSeqsWithoutGapAtColumn(seqs, cpos);
+ Set<SeqCigar> seqsWithoutGapAtCol = findSeqsWithoutGapAtColumn(seqs,
+ cpos);
/*
* calculate similarity score for each secondary structure annotation on i'th and j'th
*/
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;
}
}
* 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<SeqCigar> findSeqsWithoutGapAtColumn(
- SeqCigar[] seqs, int columnPosition)
+ private Set<SeqCigar> findSeqsWithoutGapAtColumn(SeqCigar[] seqs,
+ int columnPosition)
{
Set<SeqCigar> seqsWithoutGapAtCol = new HashSet<>();
for (SeqCigar seq : seqs)
{
/*
* 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<SeqCigar> findSeqsWithUndefinedSS(SeqCigar[] seqs,
- Map<String, HashSet<String>> ssAlignmentAnnotationForSequences) {
- Set<SeqCigar> seqsWithUndefinedSS = new HashSet<>();
- for (SeqCigar seq : seqs) {
- if (isSSUndefinedOrNotAdded(seq, ssAlignmentAnnotationForSequences)) {
- seqsWithUndefinedSS.add(seq);
- }
+ Map<String, HashSet<String>> ssAlignmentAnnotationForSequences)
+ {
+ Set<SeqCigar> 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<String, HashSet<String>> ssAlignmentAnnotationForSequences) {
- for (String label : Constants.SECONDARY_STRUCTURE_LABELS.keySet()) {
- AlignmentAnnotation[] annotations = seq.getRefSeq().getAnnotation(label);
- if (annotations != null) {
- for (AlignmentAnnotation annotation : annotations) {
- HashSet<String> 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<String, HashSet<String>> ssAlignmentAnnotationForSequences)
+ {
+ for (String label : Constants.SECONDARY_STRUCTURE_LABELS.keySet())
+ {
+ AlignmentAnnotation[] annotations = seq.getRefSeq()
+ .getAnnotation(label);
+ if (annotations != null)
+ {
+ for (AlignmentAnnotation annotation : annotations)
+ {
+ HashSet<String> 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()
{
@Override
public boolean isDNA()
{
- return false;
+ return false;
}
@Override
{
return false;
}
-
+
@Override
public boolean isSecondaryStructure()
{
private boolean includeGaps;
private boolean denominateByShortestLength;
-
+
private String secondaryStructureSource;
/**
/**
* 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);
boolean isValidCharWidth();
boolean isShowConsensusHistogram();
-
+
boolean isShowSSConsensusHistogram();
boolean isShowSequenceLogo();
-
+
boolean isShowSequenceSSLogo();
boolean isNormaliseSequenceLogo();
* @return
*/
AlignmentAnnotation getAlignmentConsensusAnnotation();
-
- AlignmentAnnotation getAlignmentSecondaryStructureConsensusAnnotation();
+ AlignmentAnnotation getAlignmentSecondaryStructureConsensusAnnotation();
/**
* get the container for alignment gap annotation
* @param hconsensus
*/
void setSequenceConsensusHash(ProfilesI hconsensus);
-
+
void setSequenceSSConsensusHash(ProfilesI hSSConsensus);
-
/**
* Set the cDNA complement consensus for the viewport
* @return
*/
Iterator<int[]> getViewAsVisibleContigs(boolean selectedRegionOnly);
+
/**
* notify all concerned that the alignment data has changed and derived data
* needs to be recalculated
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
*/
// 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
* @return
*/
boolean denominateByShortestLength();
-
+
String getSecondaryStructureSource();
void setSecondaryStructureSource(String secondaryStructureSource);
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);
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
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];
{
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;
}
alseq[gapstart + gp] = gc;
}
- for (int sqp = 0,insp=0; sqp<alseq.length; sqp++)
+ for (int sqp = 0, insp = 0; sqp < alseq.length; sqp++)
{
if (sqp < range.length && !Comparison.isGap(range[sqp]))
{
// Technically we should return false, since view has not changed
return false;
}
-
+
@Override
public boolean justify_Region(boolean left)
{
public void setProviderCategory(String providerCategory)
{
- setProperty(PROVIDERCATEGORY, providerCategory);
+ setProperty(PROVIDERCATEGORY, providerCategory);
}
-
+
public String getProviderCategory()
{
return (String) getProperty(PROVIDERCATEGORY);
{
return _hasProperty(PROVIDERCATEGORY);
}
-
+
}
* an object holding counts of symbols in the profile
*/
private ResidueCount counts;
-
+
private SecondaryStructureCount ssCounts;
/*
* the highest count for any residue in the profile
*/
private int maxCount;
+
private int maxSSCount;
-
/*
* the residue (e.g. K) or residues (e.g. KQW) with the
* highest count in the profile
*/
private String modalResidue;
-
+
private String modalSS;
/**
this.maxCount = max;
this.modalResidue = modalRes;
}
-
+
public Profile(String modalSS, int ssCount, int gaps, int maxSSCount)
{
this.height = ssCount;
{
this.counts = residueCounts;
}
-
+
@Override
public void setSSCounts(SecondaryStructureCount secondaryStructureCount)
{
}
return pid;
}
-
+
@Override
public float getSSPercentageIdentity(boolean ignoreGaps)
{
{
return counts;
}
-
+
@Override
public SecondaryStructureCount getSSCounts()
{
{
return maxCount;
}
-
+
@Override
public int getMaxSSCount()
{
{
return modalResidue;
}
-
+
@Override
public String getModalSS()
{
* @param residueCounts
*/
public abstract void setCounts(ResidueCount residueCounts);
- public abstract void setSSCounts(SecondaryStructureCount secondaryStructureCount);
-
+
+ public abstract void setSSCounts(
+ SecondaryStructureCount secondaryStructureCount);
/**
* Returns the percentage identity of the profile, i.e. the highest proportion
* @return
*/
public abstract float getPercentageIdentity(boolean ignoreGaps);
-
+
public abstract float getSSPercentageIdentity(boolean ignoreGaps);
/**
* @return
*/
public abstract int getMaxCount();
+
public abstract int getMaxSSCount();
/**
* @return
*/
public abstract String getModalResidue();
+
public abstract String getModalSS();
/**
* @return
*/
public abstract int getNonGapped();
+
SecondaryStructureCount getSSCounts();
}
\ No newline at end of file
*/
private static final String SS_SYMBOLS = "HEC";
-
static final int GAP_COUNT = 0;
/*
*/
public SecondaryStructureCount()
{
- //isSS = true;
+ // isSS = true;
int charsToCount = SS_SYMBOLS.length();
counts = new short[charsToCount + 1];
}
{
if (intCounts[i] == count)
{
- modal.append(
- SS_SYMBOLS.charAt(i - 1));
+ modal.append(SS_SYMBOLS.charAt(i - 1));
}
}
}
{
if (counts[i] == count)
{
- modal.append(
- SS_SYMBOLS.charAt(i - 1));
+ modal.append(SS_SYMBOLS.charAt(i - 1));
}
}
}
* consensus calculation property
*/
private boolean showSequenceLogo = false;
-
private boolean showSequenceSSLogo = false;
private boolean hidecols = false;
AlignmentAnnotation consensus = null;
-
AlignmentAnnotation ssConsensus = null;
AlignmentAnnotation conservation = null;
private boolean showConsensusHistogram;
-
+
private boolean showSSConsensusHistogram;
private AnnotatedCollectionI context;
cs.setConsensus(cnsns);
upd = true;
}
-
-
+
ProfilesI ssCnsns = AAFrequency.calculateSS(sequences, startRes,
endRes + 1, showSequenceLogo);
if (ssConsensus != null)
cs.setSsConsensus(ssCnsns);
upd = true;
}
-
if ((conservation != null)
|| (cs != null && cs.conservationApplied()))
// for
// ignoreGapsInConsensusCalculation);
}
-
+
public ProfilesI ssConsensusData = null;
-
+
private void _updateSSConsensusRow(ProfilesI ssCnsns, long nseq)
{
if (ssConsensus == null)
: endRes + 1)
: endRes + 1;
ssConsensus.annotations = null;
- ssConsensus.annotations = new Annotation[aWidth]; // should be alignment width
+ ssConsensus.annotations = new Annotation[aWidth]; // should be alignment
+ // width
- AAFrequency.completeSSConsensus(ssConsensus, ssCnsns, startRes, endRes + 1,
- ignoreGapsInConsensus, showSequenceLogo, nseq); // TODO: setting
- // container
+ AAFrequency.completeSSConsensus(ssConsensus, ssCnsns, startRes,
+ endRes + 1, ignoreGapsInConsensus, showSequenceLogo, nseq); // TODO:
+ // setting
+ // container
// for
// ignoreGapsInConsensusCalculation);
}
}
return consensus;
}
-
+
public AlignmentAnnotation getSSConsensus()
{
// TODO get or calculate and get consensus annotation row for this group
}
this.showSequenceLogo = showSequenceLogo;
}
-
-
+
public void setshowSequenceSSLogo(boolean showSequenceSSLogo)
{
// TODO: decouple calculation from settings update
- if (this.showSequenceSSLogo != showSequenceSSLogo && ssConsensus != null)
+ if (this.showSequenceSSLogo != showSequenceSSLogo
+ && ssConsensus != null)
{
this.showSequenceSSLogo = showSequenceSSLogo;
recalcConservation();
}
this.showConsensusHistogram = showConsHist;
}
-
+
public void setShowSSConsensusHistogram(boolean showSSConsHist)
{
}
else
{
- new Thread(new Runnable() {
+ new Thread(new Runnable()
+ {
@Override
public void run()
{
- JInternalFrame frame = new JInternalFrame();
- frame.setFrameIcon(null);
- frame.setContentPane(new PairwiseAlignPanel(viewport));
- Desktop.addInternalFrame(frame,
- MessageManager.getString("action.pairwise_alignment"), 600,
- 500);
+ JInternalFrame frame = new JInternalFrame();
+ frame.setFrameIcon(null);
+ frame.setContentPane(new PairwiseAlignPanel(viewport));
+ Desktop.addInternalFrame(frame,
+ MessageManager.getString("action.pairwise_alignment"),
+ 600, 500);
}
}).start();
-
+
}
}
viewport.setShowUnconserved(showNonconservedMenuItem.getState());
alignPanel.paintAlignment(false, false);
}
-
+
@Override
- protected void updateShowSSRadioButtons(JMenu showSS, ButtonGroup ssButtonGroup){
-
+ protected void updateShowSSRadioButtons(JMenu showSS,
+ ButtonGroup ssButtonGroup)
+ {
+
List<String> ssSources = new ArrayList<String>();
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<AlignCalcWorkerI> 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<AlignCalcWorkerI> 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<AbstractButton> 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)
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());
}
}
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);
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
{
while (!isRepainting())
{
- try {
+ try
+ {
Thread.sleep(2);
} catch (Exception q)
- {}
+ {
+ }
}
try
{
}
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
ButtonGroup calcTypes = new ButtonGroup();
calcTypes.add(pca);
- if (!Platform.isJS()) {
+ if (!Platform.isJS())
+ {
// FIXME JAL-4443
calcTypes.add(pasimap);
}
*
* @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<ScoreModelI> getApplicableScoreModels(
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))
/**
* set font size of the textarea
+ *
* @param size
*/
public void setFont(Font font)
{
textarea.setFont(font);
}
-
+
/**
* DOCUMENT ME!
*/
{
}
}
-
+
/**
- * show menu for changing the font
- * @param e
- */
+ * show menu for changing the font
+ *
+ * @param e
+ */
@Override
public void fontSizeMenu_actionPerformed(ActionEvent e)
{
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;
}
/**
* Creates a new FontChooser for a CutAndPasteTransfer
+ *
* @param cap
- */
+ */
public FontChooser(CutAndPasteTransfer cap)
{
oldFont = new Font("Monospaced", Font.PLAIN, 12);
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
{
return cap != null;
}
+
/**
* DOCUMENT ME!
*/
*/
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()
{
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));
}
/**
- * 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()
{
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);
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));
}
}
/**
- * 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()
}
/**
- * 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
}
/**
- * 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()
}
}
- public void makePaSiMapImage(ImageMaker.TYPE type) throws Exception
+ public void makePaSiMapImage(ImageMaker.TYPE type) throws Exception
{
int width = getRotatableCanvas().getWidth();
int height = getRotatableCanvas().getHeight();
{
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);
public void updateProgressBar(int lengthOfTask, int progress)
{
JProgressBar pBar = progressBar.getProgressBar(progId);
- if (pBar==null)
+ if (pBar == null)
{
return;
}
}
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)
}
/**
- * 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
private float[][] scores;
- private float[][] alignmentScores; // scores used by PaSiMap
+ private float[][] alignmentScores; // scores used by PaSiMap
private int GAP_OPEN_COST;
private String alignmentOutput;
private boolean quiet;
-
+
private boolean discardAlignments;
private boolean endGaps;
private int total;
private int progress;
-
+
private SequenceGroup selection;
+
/**
* input sequences
*/
- private SequenceI[] seqs=null;
+ private SequenceI[] seqs = null;
private ScoreMatrix scoreMatrix;
*
* @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
* @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;
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<SequenceI>();
String[] seqStrings;
- seqs=null;
+ seqs = null;
if (selection != null)
{
seqs = av.getAlignment().getSequencesArray();
}
}
-
+
String type = (av.getAlignment().isNucleotide()) ? AlignSeq.DNA
: AlignSeq.PEP;
float[][] alignmentScores = new float[seqs.length][seqs.length];
double totscore = 0D;
int count = seqs.length;
-
+
boolean first = true;
progress = 0;
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;
}
sb.append(DASHES);
}
first = false;
- if (!discardAlignments) {
+ if (!discardAlignments)
+ {
as.printAlignment(System.out);
}
scores[i][j] = as.getMaxScore() / as.getASeq1().length;
this.scores = scores;
this.alignmentScores = alignmentScores;
- if (count > 2 && !quiet)
+ if (count > 2 && !quiet)
{
printScoreMatrix(seqs, scores, totscore);
}
{
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;
}
}
{
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<AlignCalcWorkerI> workers = ap.alignFrame.getViewport().getCalcManager()
- .getRegisteredWorkersOfClass(SecondaryStructureConsensusThread.class);
- if (!workers.isEmpty()) {
-
- ap.alignFrame.getViewport().getCalcManager().startWorker(workers.remove(0));
-
- }
-
+
+ private void restartSSConsensusWorker()
+ {
+
+ List<AlignCalcWorkerI> 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)
{
public JProgressBar getProgressBar(long id)
{
Container progBar = progressBars.get(id);
- if (progBar==null || progBar.getComponentCount()==0)
+ if (progBar == null || progBar.getComponentCount() == 0)
{
return null;
}
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;
}
}
// //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);
+ }
}
/**
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);
// 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
{
mouseY = yPos;
// findWidths();
}
- repaint();
+ repaint();
}
@Override
{
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))
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()
{
* @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(
ssm = ap.getStructureSelectionManager();
StructureSelectionManager.doConfigureStructurePrefs(ssm);
}
-
+
PDBEntry fileEntry = new AssociatePdbFileWithSeq().associatePdbWithSeq(
sFilename, DataSourceType.FILE, seq, prompt, Desktop.instance,
tft, paeFilename, doXferSettings);
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);
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,
protected JMenuItem gatherViews = new JMenuItem();
protected JMenuItem expandViews = new JMenuItem();
-
+
protected JCheckBoxMenuItem threeDStructure = new JCheckBoxMenuItem();
protected JCheckBoxMenuItem jPred = new JCheckBoxMenuItem();
protected JCheckBoxMenuItem showGroupConservation = new JCheckBoxMenuItem();
- protected JCheckBoxMenuItem showConsensusHistogram = new JCheckBoxMenuItem();
+ protected JCheckBoxMenuItem showConsensusHistogram = new JCheckBoxMenuItem();
protected JCheckBoxMenuItem showSSConsensusHistogram = new JCheckBoxMenuItem();
showConsensusHistogram_actionPerformed(e);
}
- });
+ });
showSSConsensusHistogram.setText(
MessageManager.getString("label.show_ssconsensus_histogram"));
showSSConsensusHistogram.addActionListener(new ActionListener()
};
addMenuActionAndAccelerator(keyStroke, copyHighlighted, al);
copyHighlighted.addActionListener(al);
-
-
ButtonGroup ssButtonGroup = new ButtonGroup();
final JRadioButtonMenuItem showAll = new JRadioButtonMenuItem(
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"));
// TODO Auto-generated method stub
}
-
+
protected void showSSConsensusHistogram_actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
protected void showSS_actionPerformed(String ssSourceSelection)
{
// TODO Auto-generated method stub
-
+
}
}
@Override
public void actionPerformed(ActionEvent e)
{
- fontSizeMenu_actionPerformed(e);
+ fontSizeMenu_actionPerformed(e);
}
});
copyItem.setText(MessageManager.getString("action.copy"));
/**
* shows a menu for changing the font
+ *
* @param e
*/
public void fontSizeMenu_actionPerformed(ActionEvent e)
zCombobox.addItem("dim " + i);
}
}
+
public GPCAPanel(int dim)
{
try
zCombobox.addItem("dim " + i);
}
}
+
public GPaSiMapPanel(int dim)
{
try
}
});
JMenuItem outputAlignment = new JMenuItem();
- outputAlignment.setText(
- MessageManager.getString("label.output_alignment"));
+ outputAlignment
+ .setText(MessageManager.getString("label.output_alignment"));
outputAlignment.addActionListener(new ActionListener()
{
@Override
protected JCheckBox conservation = new JCheckBox();
- protected JCheckBox identity = new JCheckBox();
+ protected JCheckBox identity = new JCheckBox();
protected JCheckBox ssConsensus = new JCheckBox();
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++;
}
*/
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]);
- }
+ }
}
}
}
}
/**
- * returns the matrix as a double[][] array
- *
- * @return
- */
+ * returns the matrix as a double[][] array
+ *
+ * @return
+ */
@Override
public double[][] asArray()
{
/**
* Add d to all entries of this matrix
*
- * @param d ~ value to add
+ * @param d
+ * ~ value to add
*/
@Override
public void add(double d)
}
/**
- * 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
*/
{
if (row != null)
{
- mean[i++] = MiscMath.mean(row);
+ mean[i++] = MiscMath.mean(row);
}
}
return mean;
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()
{
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()
{
{
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()
{
{
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)
{
}
/**
- * calculates the Frobenius norm of this matrix
- *
- * @return
- */
+ * calculates the Frobenius norm of this matrix
+ *
+ * @return
+ */
@Override
public double norm()
{
{
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()
{
{
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++)
double sum = 0;
for (int j = 0; j < row.length; j++)
{
- sum += row[j] * v[j];
+ sum += row[j] * v[j];
}
result[i] = sum;
}
}
/**
- * 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);
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();
/**
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);
/**
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();
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();
}
/**
* 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("[ ");
}
/**
- * 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];
}
}
/**
- * 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];
}
/**
- * 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);
}
}
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);
}
}
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);
}
}
return result;
}
+
public static double[] elementwiseMultiply(double[] a, double b)
{
double[] result = new double[a.length];
}
/**
- * 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);
}
}
/**
- * 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);
}
}
return result;
}
+
public static double[] elementwiseAdd(double[] a, double b)
{
double[] result = new double[a.length];
}
/**
- * 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;
{
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;
}
/**
- * 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;
{
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;
{
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)
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
*
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
}
/**
- * 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();
Console.error("Error saving PaSiMap: " + t.getMessage());
}
}
+
/**
* Stores values from a matrix into an XML element, including (if present) the
* D or E vectors
viewport.getResidueShading()
.setConsensus(viewport.getSequenceConsensusHash());
viewport.getResidueShading()
- .setSsConsensus(viewport.getSequenceSSConsensusHash());
+ .setSsConsensus(viewport.getSequenceSSConsensusHash());
if (safeBoolean(view.isConservationSelected()) && cs != null)
{
viewport.getResidueShading()
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
*
viewer.isIncludeGappedColumns(), viewer.isMatchGaps(),
viewer.isIncludeGaps(),
viewer.isDenominateByShortestLength());
- */
+ */
/*
* create the panel (without computing the PaSiMAp)
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());
private HiddenColumns hiddenColumns;
private ProfilesI hconsensus;
-
+
private ProfilesI hSSconsensus;
private Hashtable<String, Object>[] complementConsensus;
}
}
}
-
- 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"))
* {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)
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);
}
* the consensus data for each column
*/
private ProfilesI consensus;
-
+
/*
* the consensus data for each column
*/
private ProfilesI ssConsensus;
-
public ProfilesI getSsConsensus()
{
public void setConsensus(ProfilesI cons)
{
consensus = cons;
-
+
}
/**
return colour;
}
-
+
@Override
public Color findSSColour(char symbol, int position, SequenceI seq)
{
/*
* 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
{
public abstract void setConsensus(ProfilesI cons);
-
+
public abstract void setSsConsensus(ProfilesI cons);
public abstract boolean conservationApplied();
{
return false;
}
+
public String toRuleRep()
{
makeColours();
- HashMap<String, String> cols=new HashMap();
- for (String res:ResidueProperties.aa) {
+ HashMap<String, String> 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();
}
public static final int[] nucleotideIndex;
public static final int[] purinepyrimidineIndex;
-
+
public static final int[] secondaryStructureIndex;
public static final Map<String, Integer> aa3Hash = new HashMap<>();
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;
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
*/
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<String, String> 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
+ }
}
}
protected AlignmentAnnotation consensus;
-
+
protected AlignmentAnnotation secondaryStructureConsensus;
protected AlignmentAnnotation complementConsensus;
protected AlignmentAnnotation quality;
protected AlignmentAnnotation[] groupConsensus;
-
+
protected AlignmentAnnotation[] groupSSConsensus;
protected AlignmentAnnotation[] groupConservation;
* 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
{
this.hconsensus = hconsensus;
}
-
+
@Override
public void setSequenceSSConsensusHash(ProfilesI hSSConsensus)
{
this.hSSConsensus = hSSConsensus;
}
-
+
@Override
public void setComplementConsensusHash(
Hashtable<String, Object>[] hconsensus)
{
return hconsensus;
}
-
+
@Override
public ProfilesI getSequenceSSConsensusHash()
{
return consensus;
}
-
@Override
public AlignmentAnnotation getAlignmentSecondaryStructureConsensusAnnotation()
{
return secondaryStructureConsensus;
}
-
@Override
public AlignmentAnnotation getAlignmentGapAnnotation()
}
}
}
-
-
-
/**
* trigger update of consensus annotation
{
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));
}
}
* should consensus profile be rendered by default
*/
protected boolean showSequenceLogo = false;
-
+
protected boolean showSequenceSSLogo = false;
/**
* should consensus histograms be rendered by default
*/
protected boolean showConsensusHistogram = true;
-
+
protected boolean showSSConsensusHistogram = true;
public void setShowSSConsensusHistogram(boolean showSSConsensusHistogram)
{
return showSequenceLogo;
}
-
+
@Override
public boolean isShowSequenceSSLogo()
{
}
this.showSequenceLogo = showSequenceLogo;
}
-
+
public void setShowSequenceSSLogo(boolean showSequenceSSLogo)
{
if (showSequenceSSLogo != this.showSequenceSSLogo)
// 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;
}
{
return this.showConsensusHistogram;
}
-
+
@Override
public boolean isShowSSConsensusHistogram()
{
protected boolean showQuality = true;
- protected boolean showConsensus = true;
+ protected boolean showConsensus = true;
protected boolean showSSConsensus = false;
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();
}
}
-
/**
* If this is a protein alignment and there are mappings to cDNA, adds the
* cDNA consensus annotation and returns true, else returns false.
alignment.addAnnotation(aa);
}
}
-
+
private void initSSConsensus(AlignmentAnnotation aa)
{
aa.hasText = true;
+ ((ignoreGapsInConsensusCalculation) ? " without gaps" : ""));
return sq;
}
-
+
public SequenceI getSSConsensusSeq()
{
if (secondaryStructureConsensus == null)
* @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;
}
/**
- * 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)
{
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++)
{
/**
* 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
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);
*/
protected AlignmentAnnotation getSSConsensusAnnotation()
{
- return alignViewport.getAlignmentSecondaryStructureConsensusAnnotation();
+ return alignViewport
+ .getAlignmentSecondaryStructureConsensusAnnotation();
}
/**
* @param hconsensus
* the computed consensus data
*/
- protected void deriveSSConsensus(AlignmentAnnotation ssConsensusAnnotation,
- ProfilesI hSSConsensus)
+ protected void deriveSSConsensus(
+ AlignmentAnnotation ssConsensusAnnotation, ProfilesI hSSConsensus)
{
long nseq = getSequences().length;
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);
}
}
{
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" })
&& al.getAlignmentAnnotation().length == 2);
}
-
- @Test(groups = "Functional", dataProvider = "SecondaryStructureAnnotations")
- public void testSecondaryStructurePresentAndSources(AlignmentAnnotation[] annotations, boolean expectedSSPresent, ArrayList<String> 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<String> ssSources1 = new ArrayList<>(Arrays.asList("3D Structures"));
- List<String> ssSources2 = new ArrayList<>(Arrays.asList("JPred"));
- List<String> ssSources3 = new ArrayList<>(Arrays.asList("3D Structures", "JPred"));
- List<String> 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<String> 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<SequenceI, List<AlignmentAnnotation>> 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<SequenceI, List<AlignmentAnnotation>> annotations1 = new HashMap<>();
- SequenceI seq1 = new Sequence("Seq1", "ASD---ASD---ASD", 37, 45);
- List<AlignmentAnnotation> annotationsList1 = new ArrayList<>();
- annotationsList1.add(new AlignmentAnnotation("Secondary Structure", "Secondary Structure", new Annotation[]{}));
- annotations1.put(seq1, annotationsList1); // Annotation present secondary structure for seq1
-
- Map<SequenceI, List<AlignmentAnnotation>> annotations2 = new HashMap<>();
- SequenceI seq2 = new Sequence("Seq2", "ASD---ASD------", 37, 42);
- List<AlignmentAnnotation> 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<SequenceI, List<AlignmentAnnotation>> annotations3 = new HashMap<>();
- // Empty annotation map
-
- Map<SequenceI, List<AlignmentAnnotation>> annotations4 = new HashMap<>();
- SequenceI seq4 = new Sequence("Seq4", "ASD---ASD---AS-", 37, 44);
- List<AlignmentAnnotation> 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<String> actualSSSource = AlignmentUtils.extractSSSourceInAlignmentAnnotation(annotations);
- Assert.assertEquals(actualSSSource, expectedSSSource);
- }
-
- @DataProvider(name = "SSSourceFromAnnotationDescription")
- public static Object[][] provideSSSourceFromAnnotationDescription() {
- Map<SequenceI, List<AlignmentAnnotation>> annotations1 = new HashMap<>();
- SequenceI seq1 = new Sequence("Seq1", "ASD---ASD---ASD", 37, 45);
- List<AlignmentAnnotation> annotationsList1 = new ArrayList<>();
- annotationsList1.add(new AlignmentAnnotation("jnetpred", "JPred Output", new Annotation[]{}));
- annotations1.put(seq1, annotationsList1); // Annotation present from JPred for seq1
-
- Map<SequenceI, List<AlignmentAnnotation>> annotations2 = new HashMap<>();
- SequenceI seq2 = new Sequence("Seq2", "ASD---ASD------", 37, 42);
- List<AlignmentAnnotation> 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<SequenceI, List<AlignmentAnnotation>> annotations3 = new HashMap<>();
- // Empty annotation map
-
- Map<SequenceI, List<AlignmentAnnotation>> annotations4 = new HashMap<>();
- SequenceI seq4 = new Sequence("Seq4", "ASD---ASD---AS-", 37, 44);
- List<AlignmentAnnotation> 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<SequenceI, List<AlignmentAnnotation>> annotations5 = new HashMap<>();
- SequenceI seq5 = new Sequence("Seq5", "ASD---ASD---AS-", 37, 44);
- List<AlignmentAnnotation> 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<String> ssSources1 = new ArrayList<>(
+ Arrays.asList("3D Structures"));
+ List<String> ssSources2 = new ArrayList<>(Arrays.asList("JPred"));
+ List<String> ssSources3 = new ArrayList<>(
+ Arrays.asList("3D Structures", "JPred"));
+ List<String> 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<SequenceI, List<AlignmentAnnotation>> annotations,
+ boolean expectedPresence)
+ {
+ boolean actualPresence = AlignmentUtils
+ .isSSAnnotationPresent(annotations);
+ Assert.assertEquals(actualPresence, expectedPresence);
+ }
+
+ @DataProvider(name = "SSAnnotationPresence")
+ public static Object[][] provideSSAnnotationPresence()
+ {
+ Map<SequenceI, List<AlignmentAnnotation>> annotations1 = new HashMap<>();
+ SequenceI seq1 = new Sequence("Seq1", "ASD---ASD---ASD", 37, 45);
+ List<AlignmentAnnotation> annotationsList1 = new ArrayList<>();
+ annotationsList1.add(new AlignmentAnnotation("Secondary Structure",
+ "Secondary Structure", new Annotation[] {}));
+ annotations1.put(seq1, annotationsList1); // Annotation present secondary
+ // structure for seq1
+
+ Map<SequenceI, List<AlignmentAnnotation>> annotations2 = new HashMap<>();
+ SequenceI seq2 = new Sequence("Seq2", "ASD---ASD------", 37, 42);
+ List<AlignmentAnnotation> 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<SequenceI, List<AlignmentAnnotation>> annotations3 = new HashMap<>();
+ // Empty annotation map
+
+ Map<SequenceI, List<AlignmentAnnotation>> annotations4 = new HashMap<>();
+ SequenceI seq4 = new Sequence("Seq4", "ASD---ASD---AS-", 37, 44);
+ List<AlignmentAnnotation> 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<String> actualSSSource = AlignmentUtils
+ .extractSSSourceInAlignmentAnnotation(annotations);
+ Assert.assertEquals(actualSSSource, expectedSSSource);
+ }
+
+ @DataProvider(name = "SSSourceFromAnnotationDescription")
+ public static Object[][] provideSSSourceFromAnnotationDescription()
+ {
+ Map<SequenceI, List<AlignmentAnnotation>> annotations1 = new HashMap<>();
+ SequenceI seq1 = new Sequence("Seq1", "ASD---ASD---ASD", 37, 45);
+ List<AlignmentAnnotation> annotationsList1 = new ArrayList<>();
+ annotationsList1.add(new AlignmentAnnotation("jnetpred", "JPred Output",
+ new Annotation[] {}));
+ annotations1.put(seq1, annotationsList1); // Annotation present from JPred
+ // for seq1
+
+ Map<SequenceI, List<AlignmentAnnotation>> annotations2 = new HashMap<>();
+ SequenceI seq2 = new Sequence("Seq2", "ASD---ASD------", 37, 42);
+ List<AlignmentAnnotation> 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<SequenceI, List<AlignmentAnnotation>> annotations3 = new HashMap<>();
+ // Empty annotation map
+
+ Map<SequenceI, List<AlignmentAnnotation>> annotations4 = new HashMap<>();
+ SequenceI seq4 = new Sequence("Seq4", "ASD---ASD---AS-", 37, 44);
+ List<AlignmentAnnotation> 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<SequenceI, List<AlignmentAnnotation>> annotations5 = new HashMap<>();
+ SequenceI seq5 = new Sequence("Seq5", "ASD---ASD---AS-", 37, 44);
+ List<AlignmentAnnotation> 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" } };
+ }
}
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);
// This class tests methods in Class SecondaryStructureDistanceModel
public class SecondaryStructureDistanceModelTest
{
-
+
/**
* Verify computed distances of sequences with gap
*/
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)
* 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
*/
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)
* 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
*/
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)
* 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);
}
-
-
/**
* <pre>
* Set up
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
* 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
* 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
* 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
* 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;
}
-
/**
* <pre>
*/
protected AlignFrame setupAlignmentViewWithGap()
{
-
+
SequenceI s1 = new Sequence("s1", "FR S");
SequenceI s2 = new Sequence("s2", "FSJL");
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(
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);
}
-
}
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
* 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<SequenceI> sqs = Arrays.asList( seq1, seq2, seq3 );
+ List<SequenceI> 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());
+
}
}
*/
package jalview.gui;
-
import java.awt.Color;
import java.io.File;
import java.util.Iterator;
+ "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
@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);
}
}
}
* peptide models for PCA
*/
List<ScoreModelI> 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");
/*
* 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");
/*
* 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);
}
}
}
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))
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,
SecondaryStructureCount secondaryStructureCount)
{
// TODO Auto-generated method stub
-
+
}
@Override
// viewport
// assertEquals(cs.findColour('C', 0, al.getSequenceAt(0)), clustalPink);
}
+
@Test
public void testDocString()
{
/**
* these need to be maintained as jalview's source base grows
+ *
* @return
*/
@DataProvider(name = "patternsAndMinNumFiles")