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" + (this.msa == null ? "" : "MSA"),
239 { al, alcsel }; // , FirstSeq, noMsa};
243 * copied from JabawsCalcWorker
250 protected void replaceAnnotationOnAlignmentWith(
251 AlignmentAnnotation newAnnot, String typeName, String calcId,
254 SequenceI dsseq = aSeq.getDatasetSequence();
255 while (dsseq.getDatasetSequence() != null)
257 dsseq = dsseq.getDatasetSequence();
259 // look for same annotation on dataset and lift this one over
260 List<AlignmentAnnotation> dsan = dsseq.getAlignmentAnnotations(
262 if (dsan != null && dsan.size() > 0)
264 for (AlignmentAnnotation dssan : dsan)
266 dsseq.removeAlignmentAnnotation(dssan);
269 AlignmentAnnotation dssan = new AlignmentAnnotation(newAnnot);
270 dsseq.addAlignmentAnnotation(dssan);
271 dssan.adjustForAlignment();
275 * Given an alignment where all other sequences except profileseq are
276 * aligned to the ungapped profileseq, insert gaps in the other sequences to
277 * realign them with the residues in profileseq
282 private void alignToProfileSeq(Alignment al, SequenceI profileseq)
284 char gc = al.getGapCharacter();
285 int[] gapMap = profileseq.gapMap();
286 // insert gaps into profile
287 for (int lp = 0, r = 0; r < gapMap.length; r++)
289 if (gapMap[r] - lp > 1)
291 StringBuffer sb = new StringBuffer();
292 for (int s = 0, ns = gapMap[r] - lp; s < ns; s++)
296 for (int s = 1, ns = al.getHeight(); s < ns; s++)
298 String sq = al.getSequenceAt(s).getSequenceAsString();
299 int diff = gapMap[r] - sq.length();
304 while ((diff = gapMap[r] - sq.length()) > 0)
307 + ((diff >= sb.length()) ? sb.toString() : sb
308 .substring(0, diff));
310 al.getSequenceAt(s).setSequence(sq);
314 al.getSequenceAt(s).setSequence(
315 sq.substring(0, gapMap[r]) + sb.toString()
316 + sq.substring(gapMap[r]));
324 public JPredJob(Hashtable SequenceInfo, SequenceI seq, int[] delMap)
327 this.predMap = delMap;
328 String sq = AlignSeq.extractGaps(Comparison.GapChars,
329 seq.getSequenceAsString());
330 if (sq.length() >= 20)
332 this.SequenceInfo = SequenceInfo;
333 sequence = new vamsas.objects.simple.Sequence();
334 sequence.setId(seq.getName());
339 errorMessage = "Sequence is too short to predict with JPred - need at least 20 amino acids.";
343 public JPredJob(Hashtable SequenceInfo, SequenceI[] msf, int[] delMap)
345 this(SequenceInfo, msf[0], delMap);
346 if (sequence != null)
350 msa = new vamsas.objects.simple.Msfalignment();
351 jalview.io.PileUpfile pileup = new jalview.io.PileUpfile();
352 msa.setMsf(pileup.print(msf));
357 String errorMessage = "";
359 public String getValidationMessages()
361 return errorMessage + "\n";
365 ext.vamsas.Jpred server;
369 JPredThread(WebserviceInfo wsinfo, String altitle,
370 ext.vamsas.Jpred server, String wsurl, AlignmentView alview,
373 super(alframe, wsinfo, alview, wsurl);
374 this.altitle = altitle;
375 this.server = server;
378 JPredThread(WebserviceInfo wsinfo, String altitle,
379 ext.vamsas.Jpred server, String wsurl, Hashtable SequenceInfo,
380 SequenceI seq, int[] delMap, AlignmentView alview,
383 this(wsinfo, altitle, server, wsurl, alview, alframe);
384 JPredJob job = new JPredJob(SequenceInfo, seq, delMap);
385 if (job.hasValidInput())
387 OutputHeader = wsInfo.getProgressText();
394 wsInfo.appendProgressText(job.getValidationMessages());
398 JPredThread(WebserviceInfo wsinfo, String altitle,
399 ext.vamsas.Jpred server, Hashtable SequenceInfo, SequenceI[] msf,
400 int[] delMap, AlignmentView alview, AlignFrame alframe,
403 this(wsinfo, altitle, server, wsurl, alview, alframe);
404 JPredJob job = new JPredJob(SequenceInfo, msf, delMap);
405 if (job.hasValidInput())
409 OutputHeader = wsInfo.getProgressText();
414 wsInfo.appendProgressText(job.getValidationMessages());
418 public void StartJob(AWsJob j)
420 if (!(j instanceof JPredJob))
422 throw new Error(MessageManager.formatMessage("error.implementation_error_startjob_called", new String[]{j.getClass().toString()}));
426 JPredJob job = (JPredJob) j;
429 job.setJobId(server.predictOnMsa(job.msa));
431 else if (job.sequence != null)
433 job.setJobId(server.predict(job.sequence)); // debug like : job.jobId =
434 // "/jobs/www-jpred/jp_Yatat29";//
437 if (job.getJobId() != null)
439 if (job.getJobId().startsWith("Broken"))
441 job.result = new JpredResult();
442 job.result.setInvalid(true);
443 job.result.setStatus(MessageManager.formatMessage("label.submission_params", new String[]{job.getJobId().toString()}));
444 throw new Exception(job.getJobId());
448 job.setSubmitted(true);
449 job.setSubjobComplete(false);
450 Cache.log.info(WsUrl + " Job Id '" + job.getJobId() + "'");
455 throw new Exception(MessageManager.getString("exception.server_timeout_try_later"));
457 } catch (Exception e)
459 // kill the whole job.
460 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
461 if (e.getMessage().indexOf("Exception") > -1)
463 wsInfo.setStatus(j.getJobnum(),
464 WebserviceInfo.STATE_STOPPED_SERVERERROR);
465 wsInfo.setProgressText(
467 "Failed to submit the prediction. (Just close the window)\n"
468 + "It is most likely that there is a problem with the server.\n");
470 .println("JPredWS Client: Failed to submit the prediction. Quite possibly because of a server error - see below)\n"
471 + e.getMessage() + "\n");
473 jalview.bin.Cache.log.warn("Server Exception", e);
477 wsInfo.setStatus(j.getJobnum(), WebserviceInfo.STATE_STOPPED_ERROR);
478 // JBPNote - this could be a popup informing the user of the problem.
479 wsInfo.appendProgressText(j.getJobnum(), MessageManager.formatMessage("info.failed_to_submit_prediction", new String[]{e.getMessage(),wsInfo.getProgressText()}));
481 jalview.bin.Cache.log.debug(
482 "Failed Submission of job " + j.getJobnum(), e);
485 j.setAllowedServerExceptions(-1);
486 j.setSubjobComplete(true);
490 public void parseResult()
492 int results = 0; // number of result sets received
493 JobStateSummary finalState = new JobStateSummary();
496 for (int j = 0; j < jobs.length; j++)
498 finalState.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
499 if (jobs[j].isSubmitted() && jobs[j].isSubjobComplete()
500 && jobs[j].hasResults())
505 } catch (Exception ex)
508 Cache.log.error("Unexpected exception when processing results for "
510 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
514 wsInfo.showResultsNewFrame
515 .addActionListener(new java.awt.event.ActionListener()
517 public void actionPerformed(java.awt.event.ActionEvent evt)
519 displayResults(true);
523 .addActionListener(new java.awt.event.ActionListener()
525 public void actionPerformed(java.awt.event.ActionEvent evt)
527 displayResults(false);
530 wsInfo.setResultsReady();
534 wsInfo.setStatus(wsInfo.STATE_STOPPED_ERROR);
535 wsInfo.appendInfoText("No jobs ran.");
536 wsInfo.setFinishedNoResults();
540 void displayResults(boolean newWindow)
542 // TODO: cope with multiple subjobs.
547 for (int jn = 0; jn < jobs.length; jn++)
549 Object[] jobres = null;
550 JPredJob j = (JPredJob) jobs[jn];
554 // hack - we only deal with all single seuqence predictions or all
555 // profile predictions
556 msa = (j.msa != null) ? true : msa;
559 jalview.bin.Cache.log.debug("Parsing output of job " + jn);
560 jobres = j.getResultSet();
561 jalview.bin.Cache.log.debug("Finished parsing output.");
562 if (jobs.length == 1)
568 // do merge with other job results
569 throw new Error(MessageManager.getString("error.multiple_jnet_subjob_merge_not_implemented"));
571 } catch (Exception e)
573 jalview.bin.Cache.log.error(
574 "JNet Client: JPred Annotation Parse Error", e);
575 wsInfo.setStatus(j.getJobnum(),
576 WebserviceInfo.STATE_STOPPED_ERROR);
577 wsInfo.appendProgressText(j.getJobnum(), MessageManager.formatMessage("info.invalid_jnet_job_result_data", new String[]{OutputHeader.toString(),j.result.getStatus(), e.getMessage() }));
578 j.result.setBroken(true);
592 af = new AlignFrame((Alignment) res[0],
593 (ColumnSelection) res[1], AlignFrame.DEFAULT_WIDTH,
594 AlignFrame.DEFAULT_HEIGHT);
598 af = new AlignFrame((Alignment) res[0],
599 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
605 * java.lang.Object[] alandcolsel =
606 * input.getAlignmentAndColumnSelection
607 * (alignFrame.getViewport().getGapCharacter()); if
608 * (((SequenceI[])alandcolsel[0])[0].getLength()!=res.getWidth()) {
609 * if (msa) { throw new Error("Implementation Error! ColumnSelection
610 * from input alignment will not map to result alignment!"); } } if
611 * (!msa) { // update hidden regions to account for loss of gaps in
612 * profile. - if any // gapMap returns insert list, interpreted as
613 * delete list by pruneDeletions //((ColumnSelection)
614 * alandcolsel[1]).pruneDeletions(ShiftList.parseMap(((SequenceI[])
615 * alandcolsel[0])[0].gapMap())); }
618 af = new AlignFrame((Alignment) res[0],
619 (ColumnSelection) res[1], AlignFrame.DEFAULT_WIDTH,
620 AlignFrame.DEFAULT_HEIGHT);
622 Desktop.addInternalFrame(af, altitle, AlignFrame.DEFAULT_WIDTH,
623 AlignFrame.DEFAULT_HEIGHT);
627 Cache.log.info("Append results onto existing alignment.");
633 public void pollJob(AWsJob job) throws Exception
635 ((JPredJob) job).result = server.getresult(job.getJobId());
638 public boolean isCancellable()
643 public void cancelJob()
645 throw new Error(MessageManager.getString("error.implementation_error"));
648 public boolean canMergeResults()