2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.ws.jws2;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.Iterator;
26 import java.util.List;
29 import compbio.data.msa.SequenceAnnotation;
30 import compbio.data.sequence.FastaSequence;
31 import compbio.data.sequence.Score;
32 import compbio.data.sequence.ScoreManager;
33 import compbio.metadata.Argument;
34 import compbio.metadata.ChunkHolder;
35 import compbio.metadata.JobStatus;
36 import compbio.metadata.JobSubmissionException;
37 import compbio.metadata.Option;
38 import compbio.metadata.ResultNotAvailableException;
39 import compbio.metadata.WrongParameterException;
40 import jalview.analysis.AlignSeq;
41 import jalview.analysis.SeqsetUtils;
42 import jalview.api.AlignViewportI;
43 import jalview.api.AlignmentViewPanel;
44 import jalview.datamodel.AlignmentAnnotation;
45 import jalview.datamodel.AlignmentI;
46 import jalview.datamodel.AnnotatedCollectionI;
47 import jalview.datamodel.Annotation;
48 import jalview.datamodel.SequenceI;
49 import jalview.gui.AlignFrame;
50 import jalview.gui.IProgressIndicator;
51 import jalview.workers.AlignCalcWorker;
52 import jalview.ws.jws2.dm.JabaWsParamSet;
53 import jalview.ws.jws2.jabaws2.Jws2Instance;
54 import jalview.ws.params.WsParamSetI;
56 public abstract class JabawsCalcWorker extends AlignCalcWorker
59 protected Jws2Instance service;
60 @SuppressWarnings("unchecked")
61 protected SequenceAnnotation aaservice;
62 protected ScoreManager scoremanager;
63 protected WsParamSetI preset;
64 protected List<Argument> arguments;
65 protected IProgressIndicator guiProgress;
67 public JabawsCalcWorker(AlignViewportI alignViewport,
68 AlignmentViewPanel alignPanel)
70 super(alignViewport, alignPanel);
73 public JabawsCalcWorker(Jws2Instance service, AlignFrame alignFrame,
74 WsParamSetI preset, List<Argument> paramset)
76 this(alignFrame.getCurrentView(), alignFrame.alignPanel);
77 this.guiProgress = alignFrame;
79 this.arguments = paramset;
80 this.service = service;
81 aaservice = (SequenceAnnotation) service.service;
85 public WsParamSetI getPreset()
90 public List<Argument> getArguments()
96 * reconfigure and restart the AAConClient. This method will spawn a new
97 * thread that will wait until any current jobs are finished, modify the
98 * parameters and restart the conservation calculation with the new values.
101 * @param newarguments
103 public void updateParameters(final WsParamSetI newpreset, final List<Argument> newarguments)
106 arguments = newarguments;
107 calcMan.startWorker(this);
110 public List<Option> getJabaArguments()
112 List<Option> newargs = new ArrayList<Option>();
113 if (preset != null && preset instanceof JabaWsParamSet)
115 newargs.addAll(((JabaWsParamSet) preset).getjabaArguments());
117 if (arguments != null && arguments.size() > 0)
119 for (Argument rg : arguments)
121 if (Option.class.isAssignableFrom(rg.getClass()))
123 newargs.add((Option) rg);
133 if (aaservice == null)
137 long progressId = -1;
139 int serverErrorsLeft = 3;
141 String rslt = "JOB NOT DEFINED";
142 StringBuffer msg = new StringBuffer();
149 List<compbio.data.sequence.FastaSequence> seqs = getInputSequences(alignViewport
150 .getAlignment(), bySequence ? alignViewport.getSelectionGroup() : null);
154 calcMan.workerComplete(this);
158 AlignmentAnnotation[] aa = alignViewport.getAlignment()
159 .getAlignmentAnnotation();
160 if (guiProgress != null)
162 guiProgress.setProgressBar("JABA " + getServiceActionText(),
163 progressId = System.currentTimeMillis());
165 if (preset == null && arguments == null)
167 rslt = aaservice.analize(seqs);
173 rslt = aaservice.customAnalize(seqs, getJabaArguments());
174 } catch (WrongParameterException x)
176 throw new JobSubmissionException(
177 "Invalid parameter set. Check Jalview implementation.", x);
181 boolean finished = false;
185 JobStatus status = aaservice.getJobStatus(rslt);
186 if (status.equals(JobStatus.FINISHED))
190 if (calcMan.isPending(this) && this instanceof AAConClient)
193 // cancel this job and yield to the new job
196 if (aaservice.cancelJob(rslt))
198 System.err.println("Cancelled AACon job: " + rslt);
202 System.err.println("FAILED TO CANCEL AACon job: " + rslt);
205 } catch (Exception x)
213 ChunkHolder stats = null;
217 boolean retry = false;
222 stats = aaservice.pullExecStatistics(rslt, rpos);
223 } catch (Exception x)
226 if (x.getMessage().contains(
227 "Position in a file could not be negative!"))
229 // squash index out of bounds exception- seems to happen for
230 // disorder predictors which don't (apparently) produce any
231 // progress information and JABA server throws an exception
232 // because progress length is -1.
237 if (--serverErrorsLeft > 0)
243 } catch (InterruptedException q)
257 System.out.print(stats.getChunk());
259 rpos = stats.getNextPosition();
261 } while (stats != null && rpos > cpos);
263 if (!finished && status.equals(JobStatus.FAILED))
268 } catch (InterruptedException x)
274 if (serverErrorsLeft > 0)
279 } catch (InterruptedException x)
283 scoremanager = aaservice.getAnnotation(rslt);
284 if (scoremanager != null)
286 jalview.bin.Cache.log
287 .debug("Updating result annotation from Job " + rslt
288 + " at " + service.getUri());
289 updateResultAnnotation(true);
290 ap.adjustAnnotationHeight();
295 catch (JobSubmissionException x)
298 System.err.println("submission error with " + getServiceActionText()
301 calcMan.workerCannotRun(this);
302 } catch (ResultNotAvailableException x)
304 System.err.println("collection error:\nJob ID: " + rslt);
306 calcMan.workerCannotRun(this);
308 } catch (OutOfMemoryError error)
310 calcMan.workerCannotRun(this);
313 // hconsensus = null;
314 ap.raiseOOMWarning(getServiceActionText(), error);
315 } catch (Exception x)
317 calcMan.workerCannotRun(this);
320 // hconsensus = null;
322 .println("Blacklisting worker due to unexpected exception:");
327 calcMan.workerComplete(this);
330 calcMan.workerComplete(this);
331 if (guiProgress != null && progressId != -1)
333 guiProgress.setProgressBar("", progressId);
335 ap.paintAlignment(true);
337 if (msg.length() > 0)
339 // TODO: stash message somewhere in annotation or alignment view.
340 // code below shows result in a text box popup
342 * jalview.gui.CutAndPasteTransfer cap = new
343 * jalview.gui.CutAndPasteTransfer(); cap.setText(msg.toString());
344 * jalview.gui.Desktop.addInternalFrame(cap,
345 * "Job Status for "+getServiceActionText(), 600, 400);
353 public void updateAnnotation()
355 updateResultAnnotation(false);
358 public abstract void updateResultAnnotation(boolean immediate);
360 public abstract String getServiceActionText();
362 protected boolean submitGaps = true;
363 protected boolean alignedSeqs = true;
364 protected boolean nucleotidesAllowed = false;
365 protected boolean proteinAllowed = false;
367 * record sequences for mapping result back to afterwards
369 protected boolean bySequence = false;
370 protected Map<String, SequenceI> seqNames;
371 protected boolean[] gapMap;
375 public List<FastaSequence> getInputSequences(AlignmentI alignment, AnnotatedCollectionI inputSeqs)
377 if (alignment == null || alignment.getWidth() <= 0
378 || alignment.getSequences() == null
379 || alignment.isNucleotide() ? !nucleotidesAllowed
384 if (inputSeqs==null || inputSeqs.getWidth()<=0 || inputSeqs.getSequences()==null || inputSeqs.getSequences().size()<1)
386 inputSeqs = alignment;
389 List<compbio.data.sequence.FastaSequence> seqs = new ArrayList<compbio.data.sequence.FastaSequence>();
395 seqNames = new HashMap<String, SequenceI>();
397 gapMap = new boolean[0];
398 start=inputSeqs.getStartRes();
399 end=inputSeqs.getEndRes();
402 for (SequenceI sq : ((List<SequenceI>) inputSeqs.getSequences()))
404 if (bySequence ? sq.findPosition(end+1) -sq.findPosition(start+1) > minlen - 1 : sq.getEnd() - sq.getStart() > minlen - 1)
406 String newname = SeqsetUtils.unique_name(seqs.size() + 1);
407 // make new input sequence with or without gaps
408 if (seqNames != null)
410 seqNames.put(newname, sq);
415 seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
416 sq.getSequenceAsString()));
417 if (gapMap == null || gapMap.length < seq.getSequence().length())
419 boolean[] tg = gapMap;
420 gapMap = new boolean[seq.getLength()];
421 System.arraycopy(tg, 0, gapMap, 0, tg.length);
422 for (int p = tg.length; p < gapMap.length; p++)
424 gapMap[p] = false; // init as a gap
427 for (int apos : sq.gapMap())
429 gapMap[apos] = true; // aligned.
434 seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
435 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
436 sq.getSequenceAsString(start,end+1))));
438 if (seq.getSequence().length() > ln)
440 ln = seq.getSequence().length();
444 if (alignedSeqs && submitGaps)
447 for (int i = 0; i < gapMap.length; i++)
454 // try real hard to return something submittable
455 // TODO: some of AAcon measures need a minimum of two or three amino
456 // acids at each position, and AAcon doesn't gracefully degrade.
457 for (int p = 0; p < seqs.size(); p++)
459 FastaSequence sq = seqs.get(p);
460 int l = sq.getSequence().length();
461 // strip gapped columns
462 char[] padded = new char[realw], orig = sq.getSequence()
464 for (int i = 0, pp = 0; i < realw; pp++)
468 if (orig.length > pp)
470 padded[i++] = orig[pp];
478 seqs.set(p, new compbio.data.sequence.FastaSequence(sq.getId(),
479 new String(padded)));
486 * notify manager that we have started, and wait for a free calculation slot
488 * @return true if slot is obtained and work still valid, false if another
489 * thread has done our work for us.
493 calcMan.notifyStart(this);
494 ap.paintAlignment(false);
495 while (!calcMan.notifyWorking(this))
497 if (calcMan.isWorking(this))
505 ap.paintAlignment(false);
509 } catch (Exception ex)
511 ex.printStackTrace();
514 if (alignViewport.isClosed())
522 protected void createAnnotationRowsForScores(List<AlignmentAnnotation> ourAnnot, String calcId,
523 int alWidth, Score scr)
525 // simple annotation row
526 AlignmentAnnotation annotation = alignViewport.getAlignment()
527 .findOrCreateAnnotation(scr.getMethod(), calcId, true, null,
529 if (alWidth == gapMap.length) // scr.getScores().size())
531 constructAnnotationFromScore(annotation, 0, alWidth, scr);
532 ourAnnot.add(annotation);
536 protected AlignmentAnnotation createAnnotationRowsForScores(List<AlignmentAnnotation> ourAnnot, String typeName,
537 String calcId, SequenceI dseq, int base, Score scr)
539 System.out.println("Creating annotation on dseq:" + dseq.getStart()
540 + " base is " + base + " and length=" + dseq.getLength()
541 + " == " + scr.getScores().size());
542 // AlignmentAnnotation annotation = new AlignmentAnnotation(
543 // scr.getMethod(), typeName, new Annotation[]
544 // {}, 0, -1, AlignmentAnnotation.LINE_GRAPH);
545 // annotation.setCalcId(calcId);
546 AlignmentAnnotation annotation = alignViewport.getAlignment()
547 .findOrCreateAnnotation(typeName, calcId, false, dseq, null);
548 constructAnnotationFromScore(annotation, 0, dseq.getLength(), scr);
549 annotation.createSequenceMapping(dseq, base, false);
550 annotation.adjustForAlignment();
551 dseq.addAlignmentAnnotation(annotation);
552 ourAnnot.add(annotation);
556 private void constructAnnotationFromScore(AlignmentAnnotation annotation, int base,
557 int alWidth, Score scr)
559 Annotation[] elm = new Annotation[alWidth];
560 Iterator<Float> vals = scr.getScores().iterator();
561 float m = 0f, x = 0f;
562 for (int i = 0; vals.hasNext(); i++)
564 float val = vals.next().floatValue();
582 // if we're at a gapped column then skip to next ungapped position
583 if (gapMap != null && gapMap.length > 0)
587 elm[i++] = new Annotation("", "", ' ', Float.NaN);
590 elm[i] = new Annotation("", "" + val, ' ', val);
593 annotation.annotations = elm;
594 annotation.belowAlignment = true;
600 annotation.graphMax = x;
601 annotation.graphMin = m;
602 annotation.validateRangeAndDisplay();
605 protected void updateOurAnnots(List<AlignmentAnnotation> ourAnnot)
607 List<AlignmentAnnotation> our = ourAnnots;
608 ourAnnots = ourAnnot;
609 AlignmentI alignment = alignViewport.getAlignment();
614 for (AlignmentAnnotation an : our)
616 if (!ourAnnots.contains(an))
618 // remove the old annotation
619 alignment.deleteAnnotation(an);
625 ap.adjustAnnotationHeight();