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;
23 import jalview.analysis.AlignSeq;
24 import jalview.bin.Cache;
25 import jalview.datamodel.Alignment;
26 import jalview.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.AlignmentView;
28 import jalview.datamodel.ColumnSelection;
29 import jalview.datamodel.SequenceI;
30 import jalview.gui.AlignFrame;
31 import jalview.gui.Desktop;
32 import jalview.gui.WebserviceInfo;
33 import jalview.io.FormatAdapter;
34 import jalview.util.Comparison;
35 import jalview.util.MessageManager;
36 import jalview.ws.AWsJob;
37 import jalview.ws.JobStateSummary;
38 import jalview.ws.WSClientI;
40 import java.util.Hashtable;
41 import java.util.List;
43 import vamsas.objects.simple.JpredResult;
45 class JPredThread extends JWS1Thread implements WSClientI
47 // TODO: put mapping between JPredJob input and input data here -
48 // JNetAnnotation adding is done after result parsing.
49 class JPredJob extends WSJob
51 // TODO: make JPredJob deal only with what was sent to and received from a
53 int[] predMap = null; // mapping from sequence(i) to the original
55 // sequence(predMap[i]) being predicted on
57 vamsas.objects.simple.Sequence sequence;
59 vamsas.objects.simple.Msfalignment msa;
61 java.util.Hashtable SequenceInfo = null;
63 int msaIndex = 0; // the position of the original sequence in the array of
65 // Sequences in the input object that this job holds a
70 * @return true if getResultSet will return a valid alignment and prediction
73 public boolean hasResults()
75 if (subjobComplete && result != null && result.isFinished()
76 && ((JpredResult) result).getPredfile() != null
77 && ((JpredResult) result).getAligfile() != null)
84 public boolean hasValidInput()
95 * @return null or Object[] { annotated alignment for this prediction,
96 * ColumnSelection for this prediction} or null if no results
100 public Object[] getResultSet() throws Exception
102 if (result == null || !result.isFinished())
107 ColumnSelection alcsel = null;
108 int FirstSeq = -1; // the position of the query sequence in Alignment al
110 JpredResult result = (JpredResult) this.result;
112 jalview.bin.Cache.log.debug("Parsing output from JNet job.");
113 // JPredFile prediction = new JPredFile("C:/JalviewX/files/jpred.txt",
115 jalview.io.JPredFile prediction = new jalview.io.JPredFile(
116 result.getPredfile(), "Paste");
117 SequenceI[] preds = prediction.getSeqsAsArray();
118 jalview.bin.Cache.log.debug("Got prediction profile.");
120 if ((this.msa != null) && (result.getAligfile() != null))
122 jalview.bin.Cache.log.debug("Getting associated alignment.");
123 // we ignore the returned alignment if we only predicted on a single
125 String format = new jalview.io.IdentifyFile().Identify(
126 result.getAligfile(), "Paste");
128 if (jalview.io.FormatAdapter.isValidFormat(format))
133 Object[] alandcolsel = input
134 .getAlignmentAndColumnSelection(getGapChar());
135 sqs = (SequenceI[]) alandcolsel[0];
136 al = new Alignment(sqs);
137 alcsel = (ColumnSelection) alandcolsel[1];
141 al = new FormatAdapter().readFile(result.getAligfile(),
143 sqs = new SequenceI[al.getHeight()];
145 for (int i = 0, j = al.getHeight(); i < j; i++)
147 sqs[i] = al.getSequenceAt(i);
149 if (!jalview.analysis.SeqsetUtils.deuniquify(
152 throw (new Exception(MessageManager.getString("exception.couldnt_recover_sequence_properties_for_alignment")));
156 if (currentView.getDataset() != null)
158 al.setDataset(currentView.getDataset());
165 jalview.io.JnetAnnotationMaker.add_annotation(prediction, al,
166 FirstSeq, false, predMap);
171 throw (new Exception(MessageManager.formatMessage("exception.unknown_format_for_file", new String[]{format,result.getAligfile()})));
176 al = new Alignment(preds);
177 FirstSeq = prediction.getQuerySeqPosition();
180 char gc = getGapChar();
181 SequenceI[] sqs = (SequenceI[]) input
182 .getAlignmentAndColumnSelection(gc)[0];
183 if (this.msaIndex >= sqs.length)
185 throw new Error(MessageManager.getString("error.implementation_error_invalid_msa_index_for_job"));
189 // Uses RemoveGapsCommand
191 new jalview.commands.RemoveGapsCommand(MessageManager.getString("label.remove_gaps"),
193 { sqs[msaIndex] }, currentView);
195 SequenceI profileseq = al.getSequenceAt(FirstSeq);
196 profileseq.setSequence(sqs[msaIndex].getSequenceAsString());
199 if (!jalview.analysis.SeqsetUtils.SeqCharacterUnhash(
200 al.getSequenceAt(FirstSeq), SequenceInfo))
202 throw (new Exception(MessageManager.getString("exception.couldnt_recover_sequence_props_for_jnet_query")));
206 if (currentView.getDataset() != null)
208 al.setDataset(currentView.getDataset());
215 jalview.io.JnetAnnotationMaker.add_annotation(prediction, al,
216 FirstSeq, true, predMap);
217 SequenceI profileseq = al.getSequenceAt(0); // this includes any gaps.
218 alignToProfileSeq(al, profileseq);
221 // Adjust input view for gaps
222 // propagate insertions into profile
223 alcsel = ColumnSelection.propagateInsertions(profileseq, al,
228 // transfer to dataset
229 for (AlignmentAnnotation alant : al.getAlignmentAnnotation())
231 if (alant.sequenceRef != null)
233 replaceAnnotationOnAlignmentWith(alant, alant.label,
234 "jalview.jws1.Jpred", alant.sequenceRef);
238 { al, alcsel }; // , FirstSeq, noMsa};
242 * copied from JabawsCalcWorker
249 protected void replaceAnnotationOnAlignmentWith(
250 AlignmentAnnotation newAnnot, String typeName, String calcId,
253 SequenceI dsseq = aSeq.getDatasetSequence();
254 while (dsseq.getDatasetSequence() != null)
256 dsseq = dsseq.getDatasetSequence();
258 // look for same annotation on dataset and lift this one over
259 List<AlignmentAnnotation> dsan = dsseq.getAlignmentAnnotations(
261 if (dsan != null && dsan.size() > 0)
263 for (AlignmentAnnotation dssan : dsan)
265 dsseq.removeAlignmentAnnotation(dssan);
268 AlignmentAnnotation dssan = new AlignmentAnnotation(newAnnot);
269 dsseq.addAlignmentAnnotation(dssan);
270 dssan.adjustForAlignment();
274 * Given an alignment where all other sequences except profileseq are
275 * aligned to the ungapped profileseq, insert gaps in the other sequences to
276 * realign them with the residues in profileseq
281 private void alignToProfileSeq(Alignment al, SequenceI profileseq)
283 char gc = al.getGapCharacter();
284 int[] gapMap = profileseq.gapMap();
285 // insert gaps into profile
286 for (int lp = 0, r = 0; r < gapMap.length; r++)
288 if (gapMap[r] - lp > 1)
290 StringBuffer sb = new StringBuffer();
291 for (int s = 0, ns = gapMap[r] - lp; s < ns; s++)
295 for (int s = 1, ns = al.getHeight(); s < ns; s++)
297 String sq = al.getSequenceAt(s).getSequenceAsString();
298 int diff = gapMap[r] - sq.length();
303 while ((diff = gapMap[r] - sq.length()) > 0)
306 + ((diff >= sb.length()) ? sb.toString() : sb
307 .substring(0, diff));
309 al.getSequenceAt(s).setSequence(sq);
313 al.getSequenceAt(s).setSequence(
314 sq.substring(0, gapMap[r]) + sb.toString()
315 + sq.substring(gapMap[r]));
323 public JPredJob(Hashtable SequenceInfo, SequenceI seq, int[] delMap)
326 this.predMap = delMap;
327 String sq = AlignSeq.extractGaps(Comparison.GapChars,
328 seq.getSequenceAsString());
329 if (sq.length() >= 20)
331 this.SequenceInfo = SequenceInfo;
332 sequence = new vamsas.objects.simple.Sequence();
333 sequence.setId(seq.getName());
338 errorMessage = "Sequence is too short to predict with JPred - need at least 20 amino acids.";
342 public JPredJob(Hashtable SequenceInfo, SequenceI[] msf, int[] delMap)
344 this(SequenceInfo, msf[0], delMap);
345 if (sequence != null)
349 msa = new vamsas.objects.simple.Msfalignment();
350 jalview.io.PileUpfile pileup = new jalview.io.PileUpfile();
351 msa.setMsf(pileup.print(msf));
356 String errorMessage = "";
358 public String getValidationMessages()
360 return errorMessage + "\n";
364 ext.vamsas.Jpred server;
368 JPredThread(WebserviceInfo wsinfo, String altitle,
369 ext.vamsas.Jpred server, String wsurl, AlignmentView alview,
372 super(alframe, wsinfo, alview, wsurl);
373 this.altitle = altitle;
374 this.server = server;
377 JPredThread(WebserviceInfo wsinfo, String altitle,
378 ext.vamsas.Jpred server, String wsurl, Hashtable SequenceInfo,
379 SequenceI seq, int[] delMap, AlignmentView alview,
382 this(wsinfo, altitle, server, wsurl, alview, alframe);
383 JPredJob job = new JPredJob(SequenceInfo, seq, delMap);
384 if (job.hasValidInput())
386 OutputHeader = wsInfo.getProgressText();
393 wsInfo.appendProgressText(job.getValidationMessages());
397 JPredThread(WebserviceInfo wsinfo, String altitle,
398 ext.vamsas.Jpred server, Hashtable SequenceInfo, SequenceI[] msf,
399 int[] delMap, AlignmentView alview, AlignFrame alframe,
402 this(wsinfo, altitle, server, wsurl, alview, alframe);
403 JPredJob job = new JPredJob(SequenceInfo, msf, delMap);
404 if (job.hasValidInput())
408 OutputHeader = wsInfo.getProgressText();
413 wsInfo.appendProgressText(job.getValidationMessages());
417 public void StartJob(AWsJob j)
419 if (!(j instanceof JPredJob))
421 throw new Error(MessageManager.formatMessage("error.implementation_error_startjob_called", new String[]{j.getClass().toString()}));
425 JPredJob job = (JPredJob) j;
428 job.setJobId(server.predictOnMsa(job.msa));
430 else if (job.sequence != null)
432 job.setJobId(server.predict(job.sequence)); // debug like : job.jobId =
433 // "/jobs/www-jpred/jp_Yatat29";//
436 if (job.getJobId() != null)
438 if (job.getJobId().startsWith("Broken"))
440 job.result = new JpredResult();
441 job.result.setInvalid(true);
442 job.result.setStatus(MessageManager.formatMessage("label.submission_params", new String[]{job.getJobId().toString()}));
443 throw new Exception(job.getJobId());
447 job.setSubmitted(true);
448 job.setSubjobComplete(false);
449 Cache.log.info(WsUrl + " Job Id '" + job.getJobId() + "'");
454 throw new Exception(MessageManager.getString("exception.server_timeout_try_later"));
456 } catch (Exception e)
458 // kill the whole job.
459 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
460 if (e.getMessage().indexOf("Exception") > -1)
462 wsInfo.setStatus(j.getJobnum(),
463 WebserviceInfo.STATE_STOPPED_SERVERERROR);
464 wsInfo.setProgressText(
466 "Failed to submit the prediction. (Just close the window)\n"
467 + "It is most likely that there is a problem with the server.\n");
469 .println("JPredWS Client: Failed to submit the prediction. Quite possibly because of a server error - see below)\n"
470 + e.getMessage() + "\n");
472 jalview.bin.Cache.log.warn("Server Exception", e);
476 wsInfo.setStatus(j.getJobnum(), WebserviceInfo.STATE_STOPPED_ERROR);
477 // JBPNote - this could be a popup informing the user of the problem.
478 wsInfo.appendProgressText(j.getJobnum(), MessageManager.formatMessage("info.failed_to_submit_prediction", new String[]{e.getMessage(),wsInfo.getProgressText()}));
480 jalview.bin.Cache.log.debug(
481 "Failed Submission of job " + j.getJobnum(), e);
484 j.setAllowedServerExceptions(-1);
485 j.setSubjobComplete(true);
489 public void parseResult()
491 int results = 0; // number of result sets received
492 JobStateSummary finalState = new JobStateSummary();
495 for (int j = 0; j < jobs.length; j++)
497 finalState.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
498 if (jobs[j].isSubmitted() && jobs[j].isSubjobComplete()
499 && jobs[j].hasResults())
504 } catch (Exception ex)
507 Cache.log.error("Unexpected exception when processing results for "
509 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
513 wsInfo.showResultsNewFrame
514 .addActionListener(new java.awt.event.ActionListener()
516 public void actionPerformed(java.awt.event.ActionEvent evt)
518 displayResults(true);
522 .addActionListener(new java.awt.event.ActionListener()
524 public void actionPerformed(java.awt.event.ActionEvent evt)
526 displayResults(false);
529 wsInfo.setResultsReady();
533 wsInfo.setStatus(wsInfo.STATE_STOPPED_ERROR);
534 wsInfo.appendInfoText("No jobs ran.");
535 wsInfo.setFinishedNoResults();
539 void displayResults(boolean newWindow)
541 // TODO: cope with multiple subjobs.
546 for (int jn = 0; jn < jobs.length; jn++)
548 Object[] jobres = null;
549 JPredJob j = (JPredJob) jobs[jn];
553 // hack - we only deal with all single seuqence predictions or all
554 // profile predictions
555 msa = (j.msa != null) ? true : msa;
558 jalview.bin.Cache.log.debug("Parsing output of job " + jn);
559 jobres = j.getResultSet();
560 jalview.bin.Cache.log.debug("Finished parsing output.");
561 if (jobs.length == 1)
567 // do merge with other job results
568 throw new Error(MessageManager.getString("error.multiple_jnet_subjob_merge_not_implemented"));
570 } catch (Exception e)
572 jalview.bin.Cache.log.error(
573 "JNet Client: JPred Annotation Parse Error", e);
574 wsInfo.setStatus(j.getJobnum(),
575 WebserviceInfo.STATE_STOPPED_ERROR);
576 wsInfo.appendProgressText(j.getJobnum(), MessageManager.formatMessage("info.invalid_jnet_job_result_data", new String[]{OutputHeader.toString(),j.result.getStatus(), e.getMessage() }));
577 j.result.setBroken(true);
591 af = new AlignFrame((Alignment) res[0],
592 (ColumnSelection) res[1], AlignFrame.DEFAULT_WIDTH,
593 AlignFrame.DEFAULT_HEIGHT);
597 af = new AlignFrame((Alignment) res[0],
598 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
604 * java.lang.Object[] alandcolsel =
605 * input.getAlignmentAndColumnSelection
606 * (alignFrame.getViewport().getGapCharacter()); if
607 * (((SequenceI[])alandcolsel[0])[0].getLength()!=res.getWidth()) {
608 * if (msa) { throw new Error("Implementation Error! ColumnSelection
609 * from input alignment will not map to result alignment!"); } } if
610 * (!msa) { // update hidden regions to account for loss of gaps in
611 * profile. - if any // gapMap returns insert list, interpreted as
612 * delete list by pruneDeletions //((ColumnSelection)
613 * alandcolsel[1]).pruneDeletions(ShiftList.parseMap(((SequenceI[])
614 * alandcolsel[0])[0].gapMap())); }
617 af = new AlignFrame((Alignment) res[0],
618 (ColumnSelection) res[1], AlignFrame.DEFAULT_WIDTH,
619 AlignFrame.DEFAULT_HEIGHT);
621 Desktop.addInternalFrame(af, altitle, AlignFrame.DEFAULT_WIDTH,
622 AlignFrame.DEFAULT_HEIGHT);
626 Cache.log.info("Append results onto existing alignment.");
632 public void pollJob(AWsJob job) throws Exception
634 ((JPredJob) job).result = server.getresult(job.getJobId());
637 public boolean isCancellable()
642 public void cancelJob()
644 throw new Error(MessageManager.getString("error.implementation_error"));
647 public boolean canMergeResults()