2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ 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 jalview.analysis.AlignSeq;
24 import jalview.analysis.SeqsetUtils;
25 import jalview.api.AlignViewportI;
26 import jalview.api.AlignmentViewPanel;
27 import jalview.datamodel.AlignmentAnnotation;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.AnnotatedCollectionI;
30 import jalview.datamodel.SequenceI;
31 import jalview.gui.AlignFrame;
32 import jalview.gui.IProgressIndicator;
33 import jalview.gui.IProgressIndicatorHandler;
34 import jalview.schemes.ResidueProperties;
35 import jalview.workers.AlignCalcWorker;
36 import jalview.ws.jws2.dm.AAConSettings;
37 import jalview.ws.jws2.dm.JabaWsParamSet;
38 import jalview.ws.jws2.jabaws2.Jws2Instance;
39 import jalview.ws.params.ArgumentI;
40 import jalview.ws.params.WsParamSetI;
42 import java.util.ArrayList;
43 import java.util.HashMap;
44 import java.util.List;
47 import compbio.data.sequence.FastaSequence;
48 import compbio.metadata.ChunkHolder;
49 import compbio.metadata.JobStatus;
50 import compbio.metadata.JobSubmissionException;
51 import compbio.metadata.Option;
52 import compbio.metadata.ResultNotAvailableException;
54 public abstract class AbstractJabaCalcWorker extends AlignCalcWorker
57 protected Jws2Instance service;
59 protected WsParamSetI preset;
61 protected List<ArgumentI> arguments;
63 protected IProgressIndicator guiProgress;
65 protected boolean submitGaps = true;
68 * by default, we filter out non-standard residues before submission
70 protected boolean filterNonStandardResidues = true;
73 * Recover any existing parameters for this service
75 protected void initViewportParams()
77 if (getCalcId() != null)
79 ((jalview.gui.AlignViewport) alignViewport).setCalcIdSettingsFor(
81 new AAConSettings(true, service, this.preset, arguments),
88 * @return null or a string used to recover all annotation generated by this
91 public abstract String getCalcId();
93 public WsParamSetI getPreset()
98 public List<ArgumentI> getArguments()
104 * reconfigure and restart the AAConClient. This method will spawn a new
105 * thread that will wait until any current jobs are finished, modify the
106 * parameters and restart the conservation calculation with the new values.
109 * @param newarguments
111 public void updateParameters(final WsParamSetI newpreset,
112 final List<ArgumentI> newarguments)
115 arguments = newarguments;
116 calcMan.startWorker(this);
117 initViewportParams();
120 public List<Option> getJabaArguments()
122 List<Option> newargs = new ArrayList<>();
123 if (preset != null && preset instanceof JabaWsParamSet)
125 newargs.addAll(((JabaWsParamSet) preset).getjabaArguments());
127 if (arguments != null && arguments.size() > 0)
129 for (Object rg : JabaParamStore.getJabafromJwsArgs(arguments))
131 if (Option.class.isAssignableFrom(rg.getClass()))
133 newargs.add((Option) rg);
140 protected boolean alignedSeqs = true;
142 protected boolean nucleotidesAllowed = false;
144 protected boolean proteinAllowed = false;
147 * record sequences for mapping result back to afterwards
149 protected boolean bySequence = false;
151 protected Map<String, SequenceI> seqNames;
153 protected boolean[] gapMap;
161 public AbstractJabaCalcWorker(AlignViewportI alignViewport,
162 AlignmentViewPanel alignPanel)
164 super(alignViewport, alignPanel);
167 public AbstractJabaCalcWorker(Jws2Instance service, AlignFrame alignFrame,
168 WsParamSetI preset, List<ArgumentI> paramset)
170 this(alignFrame.getCurrentView(), alignFrame.alignPanel);
171 this.guiProgress = alignFrame;
172 this.preset = preset;
173 this.arguments = paramset;
174 this.service = service;
179 * @return true if the submission thread should attempt to submit data
181 abstract boolean hasService();
183 volatile String rslt = "JOB NOT DEFINED";
192 long progressId = -1;
194 int serverErrorsLeft = 3;
196 StringBuffer msg = new StringBuffer();
203 List<compbio.data.sequence.FastaSequence> seqs = getInputSequences(
204 alignViewport.getAlignment(),
205 bySequence ? alignViewport.getSelectionGroup() : null);
207 if (seqs == null || !checkValidInputSeqs(true, seqs))
209 calcMan.workerComplete(this);
213 AlignmentAnnotation[] aa = alignViewport.getAlignment()
214 .getAlignmentAnnotation();
215 if (guiProgress != null)
217 guiProgress.setProgressBar("JABA " + getServiceActionText(),
218 progressId = System.currentTimeMillis());
220 rslt = submitToService(seqs);
221 if (guiProgress != null)
223 guiProgress.registerHandler(progressId,
224 new IProgressIndicatorHandler()
228 public boolean cancelActivity(long id)
235 public boolean canCancel()
241 boolean finished = false;
245 JobStatus status = getJobStatus(rslt);
246 if (status.equals(JobStatus.FINISHED))
250 if (calcMan.isPending(this) && isInteractiveUpdate())
253 // cancel this job and yield to the new job
258 System.err.println("Cancelled AACon job: " + rslt);
262 System.err.println("FAILED TO CANCEL AACon job: " + rslt);
265 } catch (Exception x)
269 rslt = "CANCELLED JOB";
273 ChunkHolder stats = null;
277 boolean retry = false;
282 stats = pullExecStatistics(rslt, rpos);
283 } catch (Exception x)
286 if (x.getMessage().contains(
287 "Position in a file could not be negative!"))
289 // squash index out of bounds exception- seems to happen for
290 // disorder predictors which don't (apparently) produce any
291 // progress information and JABA server throws an exception
292 // because progress length is -1.
297 if (--serverErrorsLeft > 0)
303 } catch (InterruptedException q)
317 System.out.print(stats.getChunk());
319 rpos = stats.getNextPosition();
321 } while (stats != null && rpos > cpos);
323 if (!finished && status.equals(JobStatus.FAILED))
328 } catch (InterruptedException x)
334 if (serverErrorsLeft > 0)
339 } catch (InterruptedException x)
342 if (collectAnnotationResultsFor(rslt))
344 jalview.bin.Cache.log.debug("Updating result annotation from Job "
345 + rslt + " at " + service.getUri());
346 updateResultAnnotation(true);
347 ap.adjustAnnotationHeight();
352 catch (JobSubmissionException x)
356 "submission error with " + getServiceActionText() + " :");
358 calcMan.disableWorker(this);
359 } catch (ResultNotAvailableException x)
361 System.err.println("collection error:\nJob ID: " + rslt);
363 calcMan.disableWorker(this);
365 } catch (OutOfMemoryError error)
367 calcMan.disableWorker(this);
370 // hconsensus = null;
371 ap.raiseOOMWarning(getServiceActionText(), error);
372 } catch (Exception x)
374 calcMan.disableWorker(this);
377 // hconsensus = null;
379 .println("Blacklisting worker due to unexpected exception:");
384 calcMan.workerComplete(this);
387 calcMan.workerComplete(this);
388 if (guiProgress != null && progressId != -1)
390 guiProgress.setProgressBar("", progressId);
392 // TODO: may not need to paintAlignment again !
393 ap.paintAlignment(false, false);
395 if (msg.length() > 0)
397 // TODO: stash message somewhere in annotation or alignment view.
398 // code below shows result in a text box popup
400 * jalview.gui.CutAndPasteTransfer cap = new
401 * jalview.gui.CutAndPasteTransfer(); cap.setText(msg.toString());
402 * jalview.gui.Desktop.addInternalFrame(cap,
403 * "Job Status for "+getServiceActionText(), 600, 400);
411 * validate input for dynamic/non-dynamic update context
415 * @return true if input is valid
417 abstract boolean checkValidInputSeqs(boolean dynamic,
418 List<FastaSequence> seqs);
420 abstract String submitToService(
421 List<compbio.data.sequence.FastaSequence> seqs)
422 throws JobSubmissionException;
424 abstract boolean cancelJob(String rslt) throws Exception;
426 abstract JobStatus getJobStatus(String rslt) throws Exception;
428 abstract ChunkHolder pullExecStatistics(String rslt, long rpos);
430 abstract boolean collectAnnotationResultsFor(String rslt)
431 throws ResultNotAvailableException;
433 public void cancelCurrentJob()
440 System.err.println("Cancelled job " + id);
444 System.err.println("Job " + id + " couldn't be cancelled.");
446 } catch (Exception q)
453 * Interactive updating. Analysis calculations that work on the currently
454 * displayed alignment data should cancel existing jobs when the input data
457 * @return true if a running job should be cancelled because new input data is
458 * available for analysis
460 abstract boolean isInteractiveUpdate();
462 public List<FastaSequence> getInputSequences(AlignmentI alignment,
463 AnnotatedCollectionI inputSeqs)
465 if (alignment == null || alignment.getWidth() <= 0
466 || alignment.getSequences() == null || alignment.isNucleotide()
467 ? !nucleotidesAllowed
472 if (inputSeqs == null || inputSeqs.getWidth() <= 0
473 || inputSeqs.getSequences() == null
474 || inputSeqs.getSequences().size() < 1)
476 inputSeqs = alignment;
479 List<compbio.data.sequence.FastaSequence> seqs = new ArrayList<>();
485 seqNames = new HashMap<>();
487 gapMap = new boolean[0];
488 start = inputSeqs.getStartRes();
489 end = inputSeqs.getEndRes();
491 for (SequenceI sq : (inputSeqs.getSequences()))
494 ? sq.findPosition(end + 1)
495 - sq.findPosition(start + 1) > minlen - 1
496 : sq.getEnd() - sq.getStart() > minlen - 1)
498 String newname = SeqsetUtils.unique_name(seqs.size() + 1);
499 // make new input sequence with or without gaps
500 if (seqNames != null)
502 seqNames.put(newname, sq);
507 seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
508 sq.getSequenceAsString()));
509 if (gapMap == null || gapMap.length < seq.getSequence().length())
511 boolean[] tg = gapMap;
512 gapMap = new boolean[seq.getLength()];
513 System.arraycopy(tg, 0, gapMap, 0, tg.length);
514 for (int p = tg.length; p < gapMap.length; p++)
516 gapMap[p] = false; // init as a gap
519 for (int apos : sq.gapMap())
521 char sqc = sq.getCharAt(apos);
522 if (!filterNonStandardResidues
523 || (sq.isProtein() ? ResidueProperties.aaIndex[sqc] < 20
524 : ResidueProperties.nucleotideIndex[sqc] < 5))
526 gapMap[apos] = true; // aligned and real amino acid residue
533 seqs.add(seq = new compbio.data.sequence.FastaSequence(newname,
534 AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
535 sq.getSequenceAsString(start, end + 1))));
537 if (seq.getSequence().length() > ln)
539 ln = seq.getSequence().length();
543 if (alignedSeqs && submitGaps)
546 for (int i = 0; i < gapMap.length; i++)
553 // try real hard to return something submittable
554 // TODO: some of AAcon measures need a minimum of two or three amino
555 // acids at each position, and AAcon doesn't gracefully degrade.
556 for (int p = 0; p < seqs.size(); p++)
558 FastaSequence sq = seqs.get(p);
559 int l = sq.getSequence().length();
560 // strip gapped columns
561 char[] padded = new char[realw],
562 orig = sq.getSequence().toCharArray();
563 for (int i = 0, pp = 0; i < realw; pp++)
567 if (orig.length > pp)
569 padded[i++] = orig[pp];
577 seqs.set(p, new compbio.data.sequence.FastaSequence(sq.getId(),
578 new String(padded)));
585 public void updateAnnotation()
587 updateResultAnnotation(false);
590 public abstract void updateResultAnnotation(boolean immediate);
592 public abstract String getServiceActionText();
595 * notify manager that we have started, and wait for a free calculation slot
597 * @return true if slot is obtained and work still valid, false if another
598 * thread has done our work for us.
600 protected boolean checkDone()
602 calcMan.notifyStart(this);
603 ap.paintAlignment(false, false);
604 while (!calcMan.notifyWorking(this))
606 if (calcMan.isWorking(this))
614 ap.paintAlignment(false, false);
618 } catch (Exception ex)
620 ex.printStackTrace();
623 if (alignViewport.isClosed())
631 protected void updateOurAnnots(List<AlignmentAnnotation> ourAnnot)
633 List<AlignmentAnnotation> our = ourAnnots;
634 ourAnnots = ourAnnot;
635 AlignmentI alignment = alignViewport.getAlignment();
640 for (AlignmentAnnotation an : our)
642 if (!ourAnnots.contains(an))
644 // remove the old annotation
645 alignment.deleteAnnotation(an);
651 ap.adjustAnnotationHeight();