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.analysis.SeqsetUtils;
25 import jalview.bin.Cache;
26 import jalview.datamodel.Alignment;
27 import jalview.datamodel.AlignmentAnnotation;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.AlignmentView;
30 import jalview.datamodel.ColumnSelection;
31 import jalview.datamodel.HiddenColumns;
32 import jalview.datamodel.SequenceI;
33 import jalview.gui.AlignFrame;
34 import jalview.gui.Desktop;
35 import jalview.gui.WebserviceInfo;
36 import jalview.io.DataSourceType;
37 import jalview.io.FileFormatI;
38 import jalview.io.FormatAdapter;
39 import jalview.io.IdentifyFile;
40 import jalview.io.JPredFile;
41 import jalview.io.JnetAnnotationMaker;
42 import jalview.io.PileUpfile;
43 import jalview.util.Comparison;
44 import jalview.util.MessageManager;
45 import jalview.ws.AWsJob;
46 import jalview.ws.JobStateSummary;
47 import jalview.ws.WSClientI;
49 import java.util.Hashtable;
50 import java.util.List;
52 import vamsas.objects.simple.JpredResult;
54 class JPredThread extends JWS1Thread implements WSClientI
56 // TODO: put mapping between JPredJob input and input data here -
57 // JNetAnnotation adding is done after result parsing.
58 class JPredJob extends WSJob
60 // TODO: make JPredJob deal only with what was sent to and received from a
62 int[] predMap = null; // mapping from sequence(i) to the original
64 // sequence(predMap[i]) being predicted on
66 vamsas.objects.simple.Sequence sequence;
68 vamsas.objects.simple.Msfalignment msa;
70 java.util.Hashtable SequenceInfo = null;
72 int msaIndex = 0; // the position of the original sequence in the array of
74 // Sequences in the input object that this job holds a
79 * @return true if getResultSet will return a valid alignment and prediction
83 public boolean hasResults()
85 if (subjobComplete && result != null && result.isFinished()
86 && ((JpredResult) result).getPredfile() != null
87 && ((JpredResult) result).getAligfile() != null)
95 public boolean hasValidInput()
106 * @return null or Object[] { annotated alignment for this prediction,
107 * ColumnSelection for this prediction} or null if no results
111 public Object[] getResultSet() throws Exception
113 if (result == null || !result.isFinished())
117 AlignmentI al = null;
118 ColumnSelection alcsel = null;
119 int FirstSeq = -1; // the position of the query sequence in Alignment al
121 JpredResult result = (JpredResult) this.result;
123 Cache.log.debug("Parsing output from JNet job.");
124 // JPredFile prediction = new JPredFile("C:/JalviewX/files/jpred.txt",
126 JPredFile prediction = new JPredFile(
127 result.getPredfile(), DataSourceType.PASTE);
128 SequenceI[] preds = prediction.getSeqsAsArray();
129 Cache.log.debug("Got prediction profile.");
131 if ((this.msa != null) && (result.getAligfile() != null))
133 Cache.log.debug("Getting associated alignment.");
134 // we ignore the returned alignment if we only predicted on a single
136 FileFormatI format = new IdentifyFile().identify(
137 result.getAligfile(), DataSourceType.PASTE);
144 Object[] alandcolsel = input
145 .getAlignmentAndHiddenColumns(getGapChar());
146 sqs = (SequenceI[]) alandcolsel[0];
147 al = new Alignment(sqs);
148 alcsel = (ColumnSelection) alandcolsel[1];
152 al = new FormatAdapter().readFile(result.getAligfile(),
153 DataSourceType.PASTE, format);
154 sqs = new SequenceI[al.getHeight()];
156 for (int i = 0, j = al.getHeight(); i < j; i++)
158 sqs[i] = al.getSequenceAt(i);
160 if (!SeqsetUtils.deuniquify(SequenceInfo, sqs))
162 throw (new Exception(
164 .getString("exception.couldnt_recover_sequence_properties_for_alignment")));
168 if (currentView.getDataset() != null)
170 al.setDataset(currentView.getDataset());
177 JnetAnnotationMaker.add_annotation(prediction, al,
178 FirstSeq, false, predMap);
183 throw (new Exception(MessageManager.formatMessage(
184 "exception.unknown_format_for_file", new String[] { "",
185 result.getAligfile() })));
190 al = new Alignment(preds);
191 FirstSeq = prediction.getQuerySeqPosition();
194 char gc = getGapChar();
195 SequenceI[] sqs = (SequenceI[]) input
196 .getAlignmentAndHiddenColumns(gc)[0];
197 if (this.msaIndex >= sqs.length)
201 .getString("error.implementation_error_invalid_msa_index_for_job"));
205 // Uses RemoveGapsCommand
207 new jalview.commands.RemoveGapsCommand(
208 MessageManager.getString("label.remove_gaps"),
209 new SequenceI[] { sqs[msaIndex] }, currentView);
211 SequenceI profileseq = al.getSequenceAt(FirstSeq);
212 profileseq.setSequence(sqs[msaIndex].getSequenceAsString());
215 if (!jalview.analysis.SeqsetUtils.SeqCharacterUnhash(
216 al.getSequenceAt(FirstSeq), SequenceInfo))
218 throw (new Exception(
220 .getString("exception.couldnt_recover_sequence_props_for_jnet_query")));
224 if (currentView.getDataset() != null)
226 al.setDataset(currentView.getDataset());
233 jalview.io.JnetAnnotationMaker.add_annotation(prediction, al,
234 FirstSeq, true, predMap);
235 SequenceI profileseq = al.getSequenceAt(0); // this includes any gaps.
236 alignToProfileSeq(al, profileseq);
239 // Adjust input view for gaps
240 // propagate insertions into profile
241 alcsel = ColumnSelection.propagateInsertions(profileseq, al,
246 // transfer to dataset
247 for (AlignmentAnnotation alant : al.getAlignmentAnnotation())
249 if (alant.sequenceRef != null)
251 replaceAnnotationOnAlignmentWith(alant, alant.label,
252 "jalview.jws1.Jpred" + (this.msa == null ? "" : "MSA"),
256 return new Object[] { al, alcsel }; // , FirstSeq, noMsa};
260 * copied from JabawsCalcWorker
267 protected void replaceAnnotationOnAlignmentWith(
268 AlignmentAnnotation newAnnot, String typeName, String calcId,
271 SequenceI dsseq = aSeq.getDatasetSequence();
272 while (dsseq.getDatasetSequence() != null)
274 dsseq = dsseq.getDatasetSequence();
276 // look for same annotation on dataset and lift this one over
277 List<AlignmentAnnotation> dsan = dsseq.getAlignmentAnnotations(
279 if (dsan != null && dsan.size() > 0)
281 for (AlignmentAnnotation dssan : dsan)
283 dsseq.removeAlignmentAnnotation(dssan);
286 AlignmentAnnotation dssan = new AlignmentAnnotation(newAnnot);
287 dsseq.addAlignmentAnnotation(dssan);
288 dssan.adjustForAlignment();
292 * Given an alignment where all other sequences except profileseq are
293 * aligned to the ungapped profileseq, insert gaps in the other sequences to
294 * realign them with the residues in profileseq
299 private void alignToProfileSeq(AlignmentI al, SequenceI profileseq)
301 char gc = al.getGapCharacter();
302 int[] gapMap = profileseq.gapMap();
303 // insert gaps into profile
304 for (int lp = 0, r = 0; r < gapMap.length; r++)
306 if (gapMap[r] - lp > 1)
308 StringBuffer sb = new StringBuffer();
309 for (int s = 0, ns = gapMap[r] - lp; s < ns; s++)
313 for (int s = 1, ns = al.getHeight(); s < ns; s++)
315 String sq = al.getSequenceAt(s).getSequenceAsString();
316 int diff = gapMap[r] - sq.length();
321 while ((diff = gapMap[r] - sq.length()) > 0)
324 + ((diff >= sb.length()) ? sb.toString() : sb
325 .substring(0, diff));
327 al.getSequenceAt(s).setSequence(sq);
331 al.getSequenceAt(s).setSequence(
332 sq.substring(0, gapMap[r]) + sb.toString()
333 + sq.substring(gapMap[r]));
341 public JPredJob(Hashtable SequenceInfo, SequenceI seq, int[] delMap)
344 this.predMap = delMap;
345 String sq = AlignSeq.extractGaps(Comparison.GapChars,
346 seq.getSequenceAsString());
347 if (sq.length() >= 20)
349 this.SequenceInfo = SequenceInfo;
350 sequence = new vamsas.objects.simple.Sequence();
351 sequence.setId(seq.getName());
356 errorMessage = "Sequence is too short to predict with JPred - need at least 20 amino acids.";
360 public JPredJob(Hashtable SequenceInfo, SequenceI[] msf, int[] delMap)
362 this(SequenceInfo, msf[0], delMap);
363 if (sequence != null)
367 msa = new vamsas.objects.simple.Msfalignment();
368 PileUpfile pileup = new PileUpfile();
369 msa.setMsf(pileup.print(msf, true));
374 String errorMessage = "";
376 public String getValidationMessages()
378 return errorMessage + "\n";
382 ext.vamsas.Jpred server;
386 JPredThread(WebserviceInfo wsinfo, String altitle,
387 ext.vamsas.Jpred server, String wsurl, AlignmentView alview,
390 super(alframe, wsinfo, alview, wsurl);
391 this.altitle = altitle;
392 this.server = server;
395 JPredThread(WebserviceInfo wsinfo, String altitle,
396 ext.vamsas.Jpred server, String wsurl, Hashtable SequenceInfo,
397 SequenceI seq, int[] delMap, AlignmentView alview,
400 this(wsinfo, altitle, server, wsurl, alview, alframe);
401 JPredJob job = new JPredJob(SequenceInfo, seq, delMap);
402 if (job.hasValidInput())
404 OutputHeader = wsInfo.getProgressText();
405 jobs = new WSJob[] { job };
410 wsInfo.appendProgressText(job.getValidationMessages());
414 JPredThread(WebserviceInfo wsinfo, String altitle,
415 ext.vamsas.Jpred server, Hashtable SequenceInfo, SequenceI[] msf,
416 int[] delMap, AlignmentView alview, AlignFrame alframe,
419 this(wsinfo, altitle, server, wsurl, alview, alframe);
420 JPredJob job = new JPredJob(SequenceInfo, msf, delMap);
421 if (job.hasValidInput())
423 jobs = new WSJob[] { job };
424 OutputHeader = wsInfo.getProgressText();
429 wsInfo.appendProgressText(job.getValidationMessages());
434 public void StartJob(AWsJob j)
436 if (!(j instanceof JPredJob))
438 throw new Error(MessageManager.formatMessage(
439 "error.implementation_error_startjob_called",
440 new String[] { j.getClass().toString() }));
444 JPredJob job = (JPredJob) j;
447 job.setJobId(server.predictOnMsa(job.msa));
449 else if (job.sequence != null)
451 job.setJobId(server.predict(job.sequence)); // debug like : job.jobId =
452 // "/jobs/www-jpred/jp_Yatat29";//
455 if (job.getJobId() != null)
457 if (job.getJobId().startsWith("Broken"))
459 job.result = new JpredResult();
460 job.result.setInvalid(true);
461 job.result.setStatus(MessageManager.formatMessage(
462 "label.submission_params", new String[] { job.getJobId()
464 throw new Exception(job.getJobId());
468 job.setSubmitted(true);
469 job.setSubjobComplete(false);
470 Cache.log.info(WsUrl + " Job Id '" + job.getJobId() + "'");
477 .getString("exception.server_timeout_try_later"));
479 } catch (Exception e)
481 // kill the whole job.
482 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
483 if (e.getMessage().indexOf("Exception") > -1)
485 wsInfo.setStatus(j.getJobnum(),
486 WebserviceInfo.STATE_STOPPED_SERVERERROR);
487 wsInfo.setProgressText(
489 "Failed to submit the prediction. (Just close the window)\n"
490 + "It is most likely that there is a problem with the server.\n");
492 .println("JPredWS Client: Failed to submit the prediction. Quite possibly because of a server error - see below)\n"
493 + e.getMessage() + "\n");
495 jalview.bin.Cache.log.warn("Server Exception", e);
499 wsInfo.setStatus(j.getJobnum(), WebserviceInfo.STATE_STOPPED_ERROR);
500 // JBPNote - this could be a popup informing the user of the problem.
501 wsInfo.appendProgressText(j.getJobnum(), MessageManager
503 "info.failed_to_submit_prediction",
504 new String[] { e.getMessage(),
505 wsInfo.getProgressText() }));
507 jalview.bin.Cache.log.debug(
508 "Failed Submission of job " + j.getJobnum(), e);
511 j.setAllowedServerExceptions(-1);
512 j.setSubjobComplete(true);
517 public void parseResult()
519 int results = 0; // number of result sets received
520 JobStateSummary finalState = new JobStateSummary();
523 for (int j = 0; j < jobs.length; j++)
525 finalState.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
526 if (jobs[j].isSubmitted() && jobs[j].isSubjobComplete()
527 && jobs[j].hasResults())
532 } catch (Exception ex)
535 Cache.log.error("Unexpected exception when processing results for "
537 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
541 wsInfo.showResultsNewFrame
542 .addActionListener(new java.awt.event.ActionListener()
545 public void actionPerformed(java.awt.event.ActionEvent evt)
547 displayResults(true);
551 .addActionListener(new java.awt.event.ActionListener()
554 public void actionPerformed(java.awt.event.ActionEvent evt)
556 displayResults(false);
559 wsInfo.setResultsReady();
563 wsInfo.setStatus(wsInfo.STATE_STOPPED_ERROR);
564 wsInfo.appendInfoText("No jobs ran.");
565 wsInfo.setFinishedNoResults();
569 void displayResults(boolean newWindow)
571 // TODO: cope with multiple subjobs.
576 for (int jn = 0; jn < jobs.length; jn++)
578 Object[] jobres = null;
579 JPredJob j = (JPredJob) jobs[jn];
583 // hack - we only deal with all single seuqence predictions or all
584 // profile predictions
585 msa = (j.msa != null) ? true : msa;
588 jalview.bin.Cache.log.debug("Parsing output of job " + jn);
589 jobres = j.getResultSet();
590 jalview.bin.Cache.log.debug("Finished parsing output.");
591 if (jobs.length == 1)
597 // do merge with other job results
600 .getString("error.multiple_jnet_subjob_merge_not_implemented"));
602 } catch (Exception e)
604 jalview.bin.Cache.log.error(
605 "JNet Client: JPred Annotation Parse Error", e);
606 wsInfo.setStatus(j.getJobnum(),
607 WebserviceInfo.STATE_STOPPED_ERROR);
608 wsInfo.appendProgressText(j.getJobnum(), MessageManager
609 .formatMessage("info.invalid_jnet_job_result_data",
610 new String[] { OutputHeader.toString(),
611 j.result.getStatus(), e.getMessage() }));
612 j.result.setBroken(true);
622 ((AlignmentI) res[0]).setSeqrep(((AlignmentI) res[0])
628 af = new AlignFrame((Alignment) res[0],
629 (HiddenColumns) res[1], AlignFrame.DEFAULT_WIDTH,
630 AlignFrame.DEFAULT_HEIGHT);
634 af = new AlignFrame((Alignment) res[0],
635 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
641 * java.lang.Object[] alandcolsel =
642 * input.getAlignmentAndColumnSelection
643 * (alignFrame.getViewport().getGapCharacter()); if
644 * (((SequenceI[])alandcolsel[0])[0].getLength()!=res.getWidth()) {
645 * if (msa) { throw new Error("Implementation Error! ColumnSelection
646 * from input alignment will not map to result alignment!"); } } if
647 * (!msa) { // update hidden regions to account for loss of gaps in
648 * profile. - if any // gapMap returns insert list, interpreted as
649 * delete list by pruneDeletions //((ColumnSelection)
650 * alandcolsel[1]).pruneDeletions(ShiftList.parseMap(((SequenceI[])
651 * alandcolsel[0])[0].gapMap())); }
654 af = new AlignFrame((Alignment) res[0],
655 (HiddenColumns) res[1],
656 AlignFrame.DEFAULT_WIDTH,
657 AlignFrame.DEFAULT_HEIGHT);
659 Desktop.addInternalFrame(af, altitle, AlignFrame.DEFAULT_WIDTH,
660 AlignFrame.DEFAULT_HEIGHT);
664 Cache.log.info("Append results onto existing alignment.");
671 public void pollJob(AWsJob job) throws Exception
673 ((JPredJob) job).result = server.getresult(job.getJobId());
677 public boolean isCancellable()
683 public void cancelJob()
685 throw new Error(MessageManager.getString("error.implementation_error"));
689 public boolean canMergeResults()