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.jws1;
25 import jalview.analysis.*;
27 import jalview.datamodel.*;
30 import jalview.util.*;
31 import jalview.ws.AWsJob;
32 import jalview.ws.JobStateSummary;
33 import jalview.ws.WSClientI;
34 import vamsas.objects.simple.JpredResult;
36 class JPredThread extends JWS1Thread implements WSClientI
38 // TODO: put mapping between JPredJob input and input data here -
39 // JNetAnnotation adding is done after result parsing.
40 class JPredJob extends WSJob
42 // TODO: make JPredJob deal only with what was sent to and received from a
44 int[] predMap = null; // mapping from sequence(i) to the original
46 // sequence(predMap[i]) being predicted on
48 vamsas.objects.simple.Sequence sequence;
50 vamsas.objects.simple.Msfalignment msa;
52 java.util.Hashtable SequenceInfo = null;
54 int msaIndex = 0; // the position of the original sequence in the array of
56 // Sequences in the input object that this job holds a
61 * @return true if getResultSet will return a valid alignment and prediction
64 public boolean hasResults()
66 if (subjobComplete && result != null && result.isFinished()
67 && ((JpredResult) result).getPredfile() != null
68 && ((JpredResult) result).getAligfile() != null)
75 public boolean hasValidInput()
86 * @return null or Object[] { annotated alignment for this prediction,
87 * ColumnSelection for this prediction} or null if no results
91 public Object[] getResultSet() throws Exception
93 if (result == null || !result.isFinished())
98 ColumnSelection alcsel = null;
99 int FirstSeq = -1; // the position of the query sequence in Alignment al
101 JpredResult result = (JpredResult) this.result;
103 jalview.bin.Cache.log.debug("Parsing output from JNet job.");
104 // JPredFile prediction = new JPredFile("C:/JalviewX/files/jpred.txt",
106 jalview.io.JPredFile prediction = new jalview.io.JPredFile(
107 result.getPredfile(), "Paste");
108 SequenceI[] preds = prediction.getSeqsAsArray();
109 jalview.bin.Cache.log.debug("Got prediction profile.");
111 if ((this.msa != null) && (result.getAligfile() != null))
113 jalview.bin.Cache.log.debug("Getting associated alignment.");
114 // we ignore the returned alignment if we only predicted on a single
116 String format = new jalview.io.IdentifyFile().Identify(
117 result.getAligfile(), "Paste");
119 if (jalview.io.FormatAdapter.isValidFormat(format))
124 Object[] alandcolsel = input
125 .getAlignmentAndColumnSelection(getGapChar());
126 sqs = (SequenceI[]) alandcolsel[0];
127 al = new Alignment(sqs);
128 alcsel = (ColumnSelection) alandcolsel[1];
132 al = new FormatAdapter().readFile(result.getAligfile(),
134 sqs = new SequenceI[al.getHeight()];
136 for (int i = 0, j = al.getHeight(); i < j; i++)
138 sqs[i] = al.getSequenceAt(i);
140 if (!jalview.analysis.SeqsetUtils.deuniquify(
141 (Hashtable) SequenceInfo, sqs))
143 throw (new Exception(MessageManager.getString("exception.couldnt_recover_sequence_properties_for_alignment")));
147 if (currentView.getDataset() != null)
149 al.setDataset(currentView.getDataset());
156 jalview.io.JnetAnnotationMaker.add_annotation(prediction, al,
157 FirstSeq, false, predMap);
162 throw (new Exception(MessageManager.formatMessage("exception.unknown_format_for_file", new String[]{format,result.getAligfile()})));
167 al = new Alignment(preds);
168 FirstSeq = prediction.getQuerySeqPosition();
171 char gc = getGapChar();
172 SequenceI[] sqs = (SequenceI[]) ((java.lang.Object[]) input
173 .getAlignmentAndColumnSelection(gc))[0];
174 if (this.msaIndex >= sqs.length)
176 throw new Error(MessageManager.getString("error.implementation_error_invalid_msa_index_for_job"));
180 // Uses RemoveGapsCommand
182 new jalview.commands.RemoveGapsCommand(MessageManager.getString("label.remove_gaps"),
184 { sqs[msaIndex] }, currentView);
186 SequenceI profileseq = al.getSequenceAt(FirstSeq);
187 profileseq.setSequence(sqs[msaIndex].getSequenceAsString());
190 if (!jalview.analysis.SeqsetUtils.SeqCharacterUnhash(
191 al.getSequenceAt(FirstSeq), SequenceInfo))
193 throw (new Exception(MessageManager.getString("exception.couldnt_recover_sequence_props_for_jnet_query")));
197 if (currentView.getDataset() != null)
199 al.setDataset(currentView.getDataset());
206 jalview.io.JnetAnnotationMaker.add_annotation(prediction, al,
207 FirstSeq, true, predMap);
208 SequenceI profileseq = al.getSequenceAt(0); // this includes any gaps.
209 alignToProfileSeq(al, profileseq);
212 // Adjust input view for gaps
213 // propagate insertions into profile
214 alcsel = ColumnSelection.propagateInsertions(profileseq, al,
219 // transfer to dataset
220 for (AlignmentAnnotation alant : al.getAlignmentAnnotation())
222 if (alant.sequenceRef != null)
224 replaceAnnotationOnAlignmentWith(alant, alant.label,
225 "jalview.jws1.Jpred", alant.sequenceRef);
229 { al, alcsel }; // , FirstSeq, noMsa};
233 * copied from JabawsCalcWorker
240 protected void replaceAnnotationOnAlignmentWith(
241 AlignmentAnnotation newAnnot, String typeName, String calcId,
244 SequenceI dsseq = aSeq.getDatasetSequence();
245 while (dsseq.getDatasetSequence() != null)
247 dsseq = dsseq.getDatasetSequence();
249 // look for same annotation on dataset and lift this one over
250 List<AlignmentAnnotation> dsan = dsseq.getAlignmentAnnotations(
252 if (dsan != null && dsan.size() > 0)
254 for (AlignmentAnnotation dssan : dsan)
256 dsseq.removeAlignmentAnnotation(dssan);
259 AlignmentAnnotation dssan = new AlignmentAnnotation(newAnnot);
260 dsseq.addAlignmentAnnotation(dssan);
261 dssan.adjustForAlignment();
265 * Given an alignment where all other sequences except profileseq are
266 * aligned to the ungapped profileseq, insert gaps in the other sequences to
267 * realign them with the residues in profileseq
272 private void alignToProfileSeq(Alignment al, SequenceI profileseq)
274 char gc = al.getGapCharacter();
275 int[] gapMap = profileseq.gapMap();
276 // insert gaps into profile
277 for (int lp = 0, r = 0; r < gapMap.length; r++)
279 if (gapMap[r] - lp > 1)
281 StringBuffer sb = new StringBuffer();
282 for (int s = 0, ns = gapMap[r] - lp; s < ns; s++)
286 for (int s = 1, ns = al.getHeight(); s < ns; s++)
288 String sq = al.getSequenceAt(s).getSequenceAsString();
289 int diff = gapMap[r] - sq.length();
294 while ((diff = gapMap[r] - sq.length()) > 0)
297 + ((diff >= sb.length()) ? sb.toString() : sb
298 .substring(0, diff));
300 al.getSequenceAt(s).setSequence(sq);
304 al.getSequenceAt(s).setSequence(
305 sq.substring(0, gapMap[r]) + sb.toString()
306 + sq.substring(gapMap[r]));
314 public JPredJob(Hashtable SequenceInfo, SequenceI seq, int[] delMap)
317 this.predMap = delMap;
318 String sq = AlignSeq.extractGaps(Comparison.GapChars,
319 seq.getSequenceAsString());
320 if (sq.length() >= 20)
322 this.SequenceInfo = SequenceInfo;
323 sequence = new vamsas.objects.simple.Sequence();
324 sequence.setId(seq.getName());
329 errorMessage = "Sequence is too short to predict with JPred - need at least 20 amino acids.";
333 public JPredJob(Hashtable SequenceInfo, SequenceI[] msf, int[] delMap)
335 this(SequenceInfo, msf[0], delMap);
336 if (sequence != null)
340 msa = new vamsas.objects.simple.Msfalignment();
341 jalview.io.PileUpfile pileup = new jalview.io.PileUpfile();
342 msa.setMsf(pileup.print(msf));
347 String errorMessage = "";
349 public String getValidationMessages()
351 return errorMessage + "\n";
355 ext.vamsas.Jpred server;
359 JPredThread(WebserviceInfo wsinfo, String altitle,
360 ext.vamsas.Jpred server, String wsurl, AlignmentView alview,
363 super(alframe, wsinfo, alview, wsurl);
364 this.altitle = altitle;
365 this.server = server;
368 JPredThread(WebserviceInfo wsinfo, String altitle,
369 ext.vamsas.Jpred server, String wsurl, Hashtable SequenceInfo,
370 SequenceI seq, int[] delMap, AlignmentView alview,
373 this(wsinfo, altitle, server, wsurl, alview, alframe);
374 JPredJob job = new JPredJob(SequenceInfo, seq, delMap);
375 if (job.hasValidInput())
377 OutputHeader = wsInfo.getProgressText();
384 wsInfo.appendProgressText(job.getValidationMessages());
388 JPredThread(WebserviceInfo wsinfo, String altitle,
389 ext.vamsas.Jpred server, Hashtable SequenceInfo, SequenceI[] msf,
390 int[] delMap, AlignmentView alview, AlignFrame alframe,
393 this(wsinfo, altitle, server, wsurl, alview, alframe);
394 JPredJob job = new JPredJob(SequenceInfo, msf, delMap);
395 if (job.hasValidInput())
399 OutputHeader = wsInfo.getProgressText();
404 wsInfo.appendProgressText(job.getValidationMessages());
408 public void StartJob(AWsJob j)
410 if (!(j instanceof JPredJob))
412 throw new Error(MessageManager.formatMessage("error.implementation_error_startjob_called", new String[]{j.getClass().toString()}));
416 JPredJob job = (JPredJob) j;
419 job.setJobId(server.predictOnMsa(job.msa));
421 else if (job.sequence != null)
423 job.setJobId(server.predict(job.sequence)); // debug like : job.jobId =
424 // "/jobs/www-jpred/jp_Yatat29";//
427 if (job.getJobId() != null)
429 if (job.getJobId().startsWith("Broken"))
431 job.result = (vamsas.objects.simple.Result) new JpredResult();
432 job.result.setInvalid(true);
433 job.result.setStatus(MessageManager.formatMessage("label.submission_params", new String[]{job.getJobId().toString()}));
434 throw new Exception(job.getJobId());
438 job.setSubmitted(true);
439 job.setSubjobComplete(false);
440 Cache.log.info(WsUrl + " Job Id '" + job.getJobId() + "'");
445 throw new Exception(MessageManager.getString("exception.server_timeout_try_later"));
447 } catch (Exception e)
449 // kill the whole job.
450 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
451 if (e.getMessage().indexOf("Exception") > -1)
453 wsInfo.setStatus(j.getJobnum(),
454 WebserviceInfo.STATE_STOPPED_SERVERERROR);
455 wsInfo.setProgressText(
457 "Failed to submit the prediction. (Just close the window)\n"
458 + "It is most likely that there is a problem with the server.\n");
460 .println("JPredWS Client: Failed to submit the prediction. Quite possibly because of a server error - see below)\n"
461 + e.getMessage() + "\n");
463 jalview.bin.Cache.log.warn("Server Exception", e);
467 wsInfo.setStatus(j.getJobnum(), WebserviceInfo.STATE_STOPPED_ERROR);
468 // JBPNote - this could be a popup informing the user of the problem.
469 wsInfo.appendProgressText(j.getJobnum(), MessageManager.formatMessage("info.failed_to_submit_prediction", new String[]{e.getMessage(),wsInfo.getProgressText()}));
471 jalview.bin.Cache.log.debug(
472 "Failed Submission of job " + j.getJobnum(), e);
475 j.setAllowedServerExceptions(-1);
476 j.setSubjobComplete(true);
480 public void parseResult()
482 int results = 0; // number of result sets received
483 JobStateSummary finalState = new JobStateSummary();
486 for (int j = 0; j < jobs.length; j++)
488 finalState.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
489 if (jobs[j].isSubmitted() && jobs[j].isSubjobComplete()
490 && jobs[j].hasResults())
495 } catch (Exception ex)
498 Cache.log.error("Unexpected exception when processing results for "
500 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
504 wsInfo.showResultsNewFrame
505 .addActionListener(new java.awt.event.ActionListener()
507 public void actionPerformed(java.awt.event.ActionEvent evt)
509 displayResults(true);
513 .addActionListener(new java.awt.event.ActionListener()
515 public void actionPerformed(java.awt.event.ActionEvent evt)
517 displayResults(false);
520 wsInfo.setResultsReady();
524 wsInfo.setStatus(wsInfo.STATE_STOPPED_ERROR);
525 wsInfo.appendInfoText("No jobs ran.");
526 wsInfo.setFinishedNoResults();
530 void displayResults(boolean newWindow)
532 // TODO: cope with multiple subjobs.
537 for (int jn = 0; jn < jobs.length; jn++)
539 Object[] jobres = null;
540 JPredJob j = (JPredJob) jobs[jn];
544 // hack - we only deal with all single seuqence predictions or all
545 // profile predictions
546 msa = (j.msa != null) ? true : msa;
549 jalview.bin.Cache.log.debug("Parsing output of job " + jn);
550 jobres = j.getResultSet();
551 jalview.bin.Cache.log.debug("Finished parsing output.");
552 if (jobs.length == 1)
558 // do merge with other job results
559 throw new Error(MessageManager.getString("error.multiple_jnet_subjob_merge_not_implemented"));
561 } catch (Exception e)
563 jalview.bin.Cache.log.error(
564 "JNet Client: JPred Annotation Parse Error", e);
565 wsInfo.setStatus(j.getJobnum(),
566 WebserviceInfo.STATE_STOPPED_ERROR);
567 wsInfo.appendProgressText(j.getJobnum(), MessageManager.formatMessage("info.invalid_jnet_job_result_data", new String[]{OutputHeader.toString(),j.result.getStatus(), e.getMessage() }));
568 j.result.setBroken(true);
582 af = new AlignFrame((Alignment) res[0],
583 (ColumnSelection) res[1], AlignFrame.DEFAULT_WIDTH,
584 AlignFrame.DEFAULT_HEIGHT);
588 af = new AlignFrame((Alignment) res[0],
589 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
595 * java.lang.Object[] alandcolsel =
596 * input.getAlignmentAndColumnSelection
597 * (alignFrame.getViewport().getGapCharacter()); if
598 * (((SequenceI[])alandcolsel[0])[0].getLength()!=res.getWidth()) {
599 * if (msa) { throw new Error("Implementation Error! ColumnSelection
600 * from input alignment will not map to result alignment!"); } } if
601 * (!msa) { // update hidden regions to account for loss of gaps in
602 * profile. - if any // gapMap returns insert list, interpreted as
603 * delete list by pruneDeletions //((ColumnSelection)
604 * alandcolsel[1]).pruneDeletions(ShiftList.parseMap(((SequenceI[])
605 * alandcolsel[0])[0].gapMap())); }
608 af = new AlignFrame((Alignment) res[0],
609 (ColumnSelection) res[1], AlignFrame.DEFAULT_WIDTH,
610 AlignFrame.DEFAULT_HEIGHT);
612 Desktop.addInternalFrame(af, altitle, AlignFrame.DEFAULT_WIDTH,
613 AlignFrame.DEFAULT_HEIGHT);
617 Cache.log.info("Append results onto existing alignment.");
623 public void pollJob(AWsJob job) throws Exception
625 ((JPredJob) job).result = server.getresult(job.getJobId());
628 public boolean isCancellable()
633 public void cancelJob()
635 throw new Error(MessageManager.getString("error.implementation_error"));
638 public boolean canMergeResults()