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.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.AlignmentI;
28 import jalview.datamodel.AlignmentView;
29 import jalview.datamodel.ColumnSelection;
30 import jalview.datamodel.SequenceI;
31 import jalview.gui.AlignFrame;
32 import jalview.gui.Desktop;
33 import jalview.gui.WebserviceInfo;
34 import jalview.io.FormatAdapter;
35 import jalview.util.Comparison;
36 import jalview.util.MessageManager;
37 import jalview.ws.AWsJob;
38 import jalview.ws.JobStateSummary;
39 import jalview.ws.WSClientI;
41 import java.util.Hashtable;
42 import java.util.List;
44 import vamsas.objects.simple.JpredResult;
46 class JPredThread extends JWS1Thread implements WSClientI
48 // TODO: put mapping between JPredJob input and input data here -
49 // JNetAnnotation adding is done after result parsing.
50 class JPredJob extends WSJob
52 // TODO: make JPredJob deal only with what was sent to and received from a
54 int[] predMap = null; // mapping from sequence(i) to the original
56 // sequence(predMap[i]) being predicted on
58 vamsas.objects.simple.Sequence sequence;
60 vamsas.objects.simple.Msfalignment msa;
62 java.util.Hashtable SequenceInfo = null;
64 int msaIndex = 0; // the position of the original sequence in the array of
66 // Sequences in the input object that this job holds a
71 * @return true if getResultSet will return a valid alignment and prediction
74 public boolean hasResults()
76 if (subjobComplete && result != null && result.isFinished()
77 && ((JpredResult) result).getPredfile() != null
78 && ((JpredResult) result).getAligfile() != null)
85 public boolean hasValidInput()
96 * @return null or Object[] { annotated alignment for this prediction,
97 * ColumnSelection for this prediction} or null if no results
101 public Object[] getResultSet() throws Exception
103 if (result == null || !result.isFinished())
107 AlignmentI al = null;
108 ColumnSelection alcsel = null;
109 int FirstSeq = -1; // the position of the query sequence in Alignment al
111 JpredResult result = (JpredResult) this.result;
113 jalview.bin.Cache.log.debug("Parsing output from JNet job.");
114 // JPredFile prediction = new JPredFile("C:/JalviewX/files/jpred.txt",
116 jalview.io.JPredFile prediction = new jalview.io.JPredFile(
117 result.getPredfile(), "Paste");
118 SequenceI[] preds = prediction.getSeqsAsArray();
119 jalview.bin.Cache.log.debug("Got prediction profile.");
121 if ((this.msa != null) && (result.getAligfile() != null))
123 jalview.bin.Cache.log.debug("Getting associated alignment.");
124 // we ignore the returned alignment if we only predicted on a single
126 String format = new jalview.io.IdentifyFile().Identify(
127 result.getAligfile(), "Paste");
129 if (jalview.io.FormatAdapter.isValidFormat(format))
134 Object[] alandcolsel = input
135 .getAlignmentAndColumnSelection(getGapChar());
136 sqs = (SequenceI[]) alandcolsel[0];
137 al = new Alignment(sqs);
138 alcsel = (ColumnSelection) alandcolsel[1];
142 al = new FormatAdapter().readFile(result.getAligfile(),
144 sqs = new SequenceI[al.getHeight()];
146 for (int i = 0, j = al.getHeight(); i < j; i++)
148 sqs[i] = al.getSequenceAt(i);
150 if (!jalview.analysis.SeqsetUtils.deuniquify(
153 throw (new Exception(MessageManager.getString("exception.couldnt_recover_sequence_properties_for_alignment")));
157 if (currentView.getDataset() != null)
159 al.setDataset(currentView.getDataset());
166 jalview.io.JnetAnnotationMaker.add_annotation(prediction, al,
167 FirstSeq, false, predMap);
172 throw (new Exception(MessageManager.formatMessage("exception.unknown_format_for_file", new String[]{format,result.getAligfile()})));
177 al = new Alignment(preds);
178 FirstSeq = prediction.getQuerySeqPosition();
181 char gc = getGapChar();
182 SequenceI[] sqs = (SequenceI[]) input
183 .getAlignmentAndColumnSelection(gc)[0];
184 if (this.msaIndex >= sqs.length)
186 throw new Error(MessageManager.getString("error.implementation_error_invalid_msa_index_for_job"));
190 // Uses RemoveGapsCommand
192 new jalview.commands.RemoveGapsCommand(MessageManager.getString("label.remove_gaps"),
194 { sqs[msaIndex] }, currentView);
196 SequenceI profileseq = al.getSequenceAt(FirstSeq);
197 profileseq.setSequence(sqs[msaIndex].getSequenceAsString());
200 if (!jalview.analysis.SeqsetUtils.SeqCharacterUnhash(
201 al.getSequenceAt(FirstSeq), SequenceInfo))
203 throw (new Exception(MessageManager.getString("exception.couldnt_recover_sequence_props_for_jnet_query")));
207 if (currentView.getDataset() != null)
209 al.setDataset(currentView.getDataset());
216 jalview.io.JnetAnnotationMaker.add_annotation(prediction, al,
217 FirstSeq, true, predMap);
218 SequenceI profileseq = al.getSequenceAt(0); // this includes any gaps.
219 alignToProfileSeq(al, profileseq);
222 // Adjust input view for gaps
223 // propagate insertions into profile
224 alcsel = ColumnSelection.propagateInsertions(profileseq, al,
229 // transfer to dataset
230 for (AlignmentAnnotation alant : al.getAlignmentAnnotation())
232 if (alant.sequenceRef != null)
234 replaceAnnotationOnAlignmentWith(alant, alant.label,
235 "jalview.jws1.Jpred" + (this.msa == null ? "" : "MSA"),
240 { al, alcsel }; // , FirstSeq, noMsa};
244 * copied from JabawsCalcWorker
251 protected void replaceAnnotationOnAlignmentWith(
252 AlignmentAnnotation newAnnot, String typeName, String calcId,
255 SequenceI dsseq = aSeq.getDatasetSequence();
256 while (dsseq.getDatasetSequence() != null)
258 dsseq = dsseq.getDatasetSequence();
260 // look for same annotation on dataset and lift this one over
261 List<AlignmentAnnotation> dsan = dsseq.getAlignmentAnnotations(
263 if (dsan != null && dsan.size() > 0)
265 for (AlignmentAnnotation dssan : dsan)
267 dsseq.removeAlignmentAnnotation(dssan);
270 AlignmentAnnotation dssan = new AlignmentAnnotation(newAnnot);
271 dsseq.addAlignmentAnnotation(dssan);
272 dssan.adjustForAlignment();
276 * Given an alignment where all other sequences except profileseq are
277 * aligned to the ungapped profileseq, insert gaps in the other sequences to
278 * realign them with the residues in profileseq
283 private void alignToProfileSeq(AlignmentI al, SequenceI profileseq)
285 char gc = al.getGapCharacter();
286 int[] gapMap = profileseq.gapMap();
287 // insert gaps into profile
288 for (int lp = 0, r = 0; r < gapMap.length; r++)
290 if (gapMap[r] - lp > 1)
292 StringBuffer sb = new StringBuffer();
293 for (int s = 0, ns = gapMap[r] - lp; s < ns; s++)
297 for (int s = 1, ns = al.getHeight(); s < ns; s++)
299 String sq = al.getSequenceAt(s).getSequenceAsString();
300 int diff = gapMap[r] - sq.length();
305 while ((diff = gapMap[r] - sq.length()) > 0)
308 + ((diff >= sb.length()) ? sb.toString() : sb
309 .substring(0, diff));
311 al.getSequenceAt(s).setSequence(sq);
315 al.getSequenceAt(s).setSequence(
316 sq.substring(0, gapMap[r]) + sb.toString()
317 + sq.substring(gapMap[r]));
325 public JPredJob(Hashtable SequenceInfo, SequenceI seq, int[] delMap)
328 this.predMap = delMap;
329 String sq = AlignSeq.extractGaps(Comparison.GapChars,
330 seq.getSequenceAsString());
331 if (sq.length() >= 20)
333 this.SequenceInfo = SequenceInfo;
334 sequence = new vamsas.objects.simple.Sequence();
335 sequence.setId(seq.getName());
340 errorMessage = "Sequence is too short to predict with JPred - need at least 20 amino acids.";
344 public JPredJob(Hashtable SequenceInfo, SequenceI[] msf, int[] delMap)
346 this(SequenceInfo, msf[0], delMap);
347 if (sequence != null)
351 msa = new vamsas.objects.simple.Msfalignment();
352 jalview.io.PileUpfile pileup = new jalview.io.PileUpfile();
353 msa.setMsf(pileup.print(msf));
358 String errorMessage = "";
360 public String getValidationMessages()
362 return errorMessage + "\n";
366 ext.vamsas.Jpred server;
370 JPredThread(WebserviceInfo wsinfo, String altitle,
371 ext.vamsas.Jpred server, String wsurl, AlignmentView alview,
374 super(alframe, wsinfo, alview, wsurl);
375 this.altitle = altitle;
376 this.server = server;
379 JPredThread(WebserviceInfo wsinfo, String altitle,
380 ext.vamsas.Jpred server, String wsurl, Hashtable SequenceInfo,
381 SequenceI seq, int[] delMap, AlignmentView alview,
384 this(wsinfo, altitle, server, wsurl, alview, alframe);
385 JPredJob job = new JPredJob(SequenceInfo, seq, delMap);
386 if (job.hasValidInput())
388 OutputHeader = wsInfo.getProgressText();
395 wsInfo.appendProgressText(job.getValidationMessages());
399 JPredThread(WebserviceInfo wsinfo, String altitle,
400 ext.vamsas.Jpred server, Hashtable SequenceInfo, SequenceI[] msf,
401 int[] delMap, AlignmentView alview, AlignFrame alframe,
404 this(wsinfo, altitle, server, wsurl, alview, alframe);
405 JPredJob job = new JPredJob(SequenceInfo, msf, delMap);
406 if (job.hasValidInput())
410 OutputHeader = wsInfo.getProgressText();
415 wsInfo.appendProgressText(job.getValidationMessages());
419 public void StartJob(AWsJob j)
421 if (!(j instanceof JPredJob))
423 throw new Error(MessageManager.formatMessage("error.implementation_error_startjob_called", new String[]{j.getClass().toString()}));
427 JPredJob job = (JPredJob) j;
430 job.setJobId(server.predictOnMsa(job.msa));
432 else if (job.sequence != null)
434 job.setJobId(server.predict(job.sequence)); // debug like : job.jobId =
435 // "/jobs/www-jpred/jp_Yatat29";//
438 if (job.getJobId() != null)
440 if (job.getJobId().startsWith("Broken"))
442 job.result = new JpredResult();
443 job.result.setInvalid(true);
444 job.result.setStatus(MessageManager.formatMessage("label.submission_params", new String[]{job.getJobId().toString()}));
445 throw new Exception(job.getJobId());
449 job.setSubmitted(true);
450 job.setSubjobComplete(false);
451 Cache.log.info(WsUrl + " Job Id '" + job.getJobId() + "'");
456 throw new Exception(MessageManager.getString("exception.server_timeout_try_later"));
458 } catch (Exception e)
460 // kill the whole job.
461 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
462 if (e.getMessage().indexOf("Exception") > -1)
464 wsInfo.setStatus(j.getJobnum(),
465 WebserviceInfo.STATE_STOPPED_SERVERERROR);
466 wsInfo.setProgressText(
468 "Failed to submit the prediction. (Just close the window)\n"
469 + "It is most likely that there is a problem with the server.\n");
471 .println("JPredWS Client: Failed to submit the prediction. Quite possibly because of a server error - see below)\n"
472 + e.getMessage() + "\n");
474 jalview.bin.Cache.log.warn("Server Exception", e);
478 wsInfo.setStatus(j.getJobnum(), WebserviceInfo.STATE_STOPPED_ERROR);
479 // JBPNote - this could be a popup informing the user of the problem.
480 wsInfo.appendProgressText(j.getJobnum(), MessageManager.formatMessage("info.failed_to_submit_prediction", new String[]{e.getMessage(),wsInfo.getProgressText()}));
482 jalview.bin.Cache.log.debug(
483 "Failed Submission of job " + j.getJobnum(), e);
486 j.setAllowedServerExceptions(-1);
487 j.setSubjobComplete(true);
491 public void parseResult()
493 int results = 0; // number of result sets received
494 JobStateSummary finalState = new JobStateSummary();
497 for (int j = 0; j < jobs.length; j++)
499 finalState.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
500 if (jobs[j].isSubmitted() && jobs[j].isSubjobComplete()
501 && jobs[j].hasResults())
506 } catch (Exception ex)
509 Cache.log.error("Unexpected exception when processing results for "
511 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
515 wsInfo.showResultsNewFrame
516 .addActionListener(new java.awt.event.ActionListener()
518 public void actionPerformed(java.awt.event.ActionEvent evt)
520 displayResults(true);
524 .addActionListener(new java.awt.event.ActionListener()
526 public void actionPerformed(java.awt.event.ActionEvent evt)
528 displayResults(false);
531 wsInfo.setResultsReady();
535 wsInfo.setStatus(wsInfo.STATE_STOPPED_ERROR);
536 wsInfo.appendInfoText("No jobs ran.");
537 wsInfo.setFinishedNoResults();
541 void displayResults(boolean newWindow)
543 // TODO: cope with multiple subjobs.
548 for (int jn = 0; jn < jobs.length; jn++)
550 Object[] jobres = null;
551 JPredJob j = (JPredJob) jobs[jn];
555 // hack - we only deal with all single seuqence predictions or all
556 // profile predictions
557 msa = (j.msa != null) ? true : msa;
560 jalview.bin.Cache.log.debug("Parsing output of job " + jn);
561 jobres = j.getResultSet();
562 jalview.bin.Cache.log.debug("Finished parsing output.");
563 if (jobs.length == 1)
569 // do merge with other job results
570 throw new Error(MessageManager.getString("error.multiple_jnet_subjob_merge_not_implemented"));
572 } catch (Exception e)
574 jalview.bin.Cache.log.error(
575 "JNet Client: JPred Annotation Parse Error", e);
576 wsInfo.setStatus(j.getJobnum(),
577 WebserviceInfo.STATE_STOPPED_ERROR);
578 wsInfo.appendProgressText(j.getJobnum(), MessageManager.formatMessage("info.invalid_jnet_job_result_data", new String[]{OutputHeader.toString(),j.result.getStatus(), e.getMessage() }));
579 j.result.setBroken(true);
593 af = new AlignFrame((Alignment) res[0],
594 (ColumnSelection) res[1], AlignFrame.DEFAULT_WIDTH,
595 AlignFrame.DEFAULT_HEIGHT);
599 af = new AlignFrame((Alignment) res[0],
600 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
606 * java.lang.Object[] alandcolsel =
607 * input.getAlignmentAndColumnSelection
608 * (alignFrame.getViewport().getGapCharacter()); if
609 * (((SequenceI[])alandcolsel[0])[0].getLength()!=res.getWidth()) {
610 * if (msa) { throw new Error("Implementation Error! ColumnSelection
611 * from input alignment will not map to result alignment!"); } } if
612 * (!msa) { // update hidden regions to account for loss of gaps in
613 * profile. - if any // gapMap returns insert list, interpreted as
614 * delete list by pruneDeletions //((ColumnSelection)
615 * alandcolsel[1]).pruneDeletions(ShiftList.parseMap(((SequenceI[])
616 * alandcolsel[0])[0].gapMap())); }
619 af = new AlignFrame((Alignment) res[0],
620 (ColumnSelection) res[1], AlignFrame.DEFAULT_WIDTH,
621 AlignFrame.DEFAULT_HEIGHT);
623 Desktop.addInternalFrame(af, altitle, AlignFrame.DEFAULT_WIDTH,
624 AlignFrame.DEFAULT_HEIGHT);
628 Cache.log.info("Append results onto existing alignment.");
634 public void pollJob(AWsJob job) throws Exception
636 ((JPredJob) job).result = server.getresult(job.getJobId());
639 public boolean isCancellable()
644 public void cancelJob()
646 throw new Error(MessageManager.getString("error.implementation_error"));
649 public boolean canMergeResults()