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.commands.RemoveGapsCommand;
27 import jalview.datamodel.Alignment;
28 import jalview.datamodel.AlignmentAnnotation;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.AlignmentView;
31 import jalview.datamodel.ColumnSelection;
32 import jalview.datamodel.SequenceI;
33 import jalview.gui.AlignFrame;
34 import jalview.gui.Desktop;
35 import jalview.gui.WebserviceInfo;
36 import jalview.io.FormatAdapter;
37 import jalview.io.IdentifyFile;
38 import jalview.io.JPredFile;
39 import jalview.io.JnetAnnotationMaker;
40 import jalview.io.PileUpfile;
41 import jalview.util.Comparison;
42 import jalview.util.MessageManager;
43 import jalview.ws.AWsJob;
44 import jalview.ws.JobStateSummary;
45 import jalview.ws.WSClientI;
47 import java.util.Hashtable;
48 import java.util.List;
50 import vamsas.objects.simple.JpredResult;
51 import vamsas.objects.simple.Msfalignment;
53 class JPredThread extends JWS1Thread implements WSClientI
55 // TODO: put mapping between JPredJob input and input data here -
56 // JNetAnnotation adding is done after result parsing.
57 class JPredJob extends WSJob
59 // TODO: make JPredJob deal only with what was sent to and received from a
61 int[] predMap = null; // mapping from sequence(i) to the original
63 // sequence(predMap[i]) being predicted on
65 vamsas.objects.simple.Sequence sequence;
67 vamsas.objects.simple.Msfalignment msa;
69 java.util.Hashtable SequenceInfo = null;
71 int msaIndex = 0; // the position of the original sequence in the array of
73 // Sequences in the input object that this job holds a
78 * @return true if getResultSet will return a valid alignment and prediction
81 public boolean hasResults()
83 if (subjobComplete && result != null && result.isFinished()
84 && ((JpredResult) result).getPredfile() != null
85 && ((JpredResult) result).getAligfile() != null)
92 public boolean hasValidInput()
103 * @return null or Object[] { annotated alignment for this prediction,
104 * ColumnSelection for this prediction} or null if no results
108 public Object[] getResultSet() throws Exception
110 if (result == null || !result.isFinished())
114 AlignmentI al = null;
115 ColumnSelection alcsel = null;
116 int FirstSeq = -1; // the position of the query sequence in Alignment al
118 JpredResult result = (JpredResult) this.result;
120 Cache.log.debug("Parsing output from JNet job.");
121 // JPredFile prediction = new JPredFile("C:/JalviewX/files/jpred.txt",
123 JPredFile prediction = new JPredFile(result.getPredfile(), "Paste");
124 SequenceI[] preds = prediction.getSeqsAsArray();
125 Cache.log.debug("Got prediction profile.");
127 if ((this.msa != null) && (result.getAligfile() != null))
129 Cache.log.debug("Getting associated alignment.");
130 // we ignore the returned alignment if we only predicted on a single
132 String format = new IdentifyFile().Identify(result.getAligfile(),
135 if (FormatAdapter.isValidFormat(format))
140 Object[] alandcolsel = input
141 .getAlignmentAndColumnSelection(getGapChar());
142 sqs = (SequenceI[]) alandcolsel[0];
143 al = new Alignment(sqs);
144 alcsel = (ColumnSelection) alandcolsel[1];
148 al = new FormatAdapter().readFile(result.getAligfile(),
150 sqs = new SequenceI[al.getHeight()];
152 for (int i = 0, j = al.getHeight(); i < j; i++)
154 sqs[i] = al.getSequenceAt(i);
156 if (!SeqsetUtils.deuniquify(SequenceInfo, sqs))
158 throw (new Exception(MessageManager.getString("exception.couldnt_recover_sequence_properties_for_alignment")));
162 if (currentView.getDataset() != null)
164 al.setDataset(currentView.getDataset());
171 JnetAnnotationMaker.add_annotation(prediction, al, FirstSeq,
177 throw (new Exception(MessageManager.formatMessage("exception.unknown_format_for_file", new String[]{format,result.getAligfile()})));
182 al = new Alignment(preds);
183 FirstSeq = prediction.getQuerySeqPosition();
186 char gc = getGapChar();
187 SequenceI[] sqs = (SequenceI[]) input
188 .getAlignmentAndColumnSelection(gc)[0];
189 if (this.msaIndex >= sqs.length)
191 throw new Error(MessageManager.getString("error.implementation_error_invalid_msa_index_for_job"));
195 // Uses RemoveGapsCommand
197 new RemoveGapsCommand(
198 MessageManager.getString("label.remove_gaps"),
200 { sqs[msaIndex] }, currentView);
202 SequenceI profileseq = al.getSequenceAt(FirstSeq);
203 profileseq.setSequence(sqs[msaIndex].getSequenceAsString());
206 if (!SeqsetUtils.SeqCharacterUnhash(
207 al.getSequenceAt(FirstSeq), SequenceInfo))
209 throw (new Exception(MessageManager.getString("exception.couldnt_recover_sequence_props_for_jnet_query")));
213 if (currentView.getDataset() != null)
215 al.setDataset(currentView.getDataset());
222 JnetAnnotationMaker.add_annotation(prediction, al,
223 FirstSeq, true, predMap);
224 SequenceI profileseq = al.getSequenceAt(0); // this includes any gaps.
225 alignToProfileSeq(al, profileseq);
228 // Adjust input view for gaps
229 // propagate insertions into profile
230 alcsel = ColumnSelection.propagateInsertions(profileseq, al,
235 // transfer to dataset
236 for (AlignmentAnnotation alant : al.getAlignmentAnnotation())
238 if (alant.sequenceRef != null)
240 replaceAnnotationOnAlignmentWith(alant, alant.label,
241 "jalview.jws1.Jpred" + (this.msa == null ? "" : "MSA"),
246 { al, alcsel }; // , FirstSeq, noMsa};
250 * copied from JabawsCalcWorker
257 protected void replaceAnnotationOnAlignmentWith(
258 AlignmentAnnotation newAnnot, String typeName, String calcId,
261 SequenceI dsseq = aSeq.getDatasetSequence();
262 while (dsseq.getDatasetSequence() != null)
264 dsseq = dsseq.getDatasetSequence();
266 // look for same annotation on dataset and lift this one over
267 List<AlignmentAnnotation> dsan = dsseq.getAlignmentAnnotations(
269 if (dsan != null && dsan.size() > 0)
271 for (AlignmentAnnotation dssan : dsan)
273 dsseq.removeAlignmentAnnotation(dssan);
276 AlignmentAnnotation dssan = new AlignmentAnnotation(newAnnot);
277 dsseq.addAlignmentAnnotation(dssan);
278 dssan.adjustForAlignment();
282 * Given an alignment where all other sequences except profileseq are
283 * aligned to the ungapped profileseq, insert gaps in the other sequences to
284 * realign them with the residues in profileseq
289 private void alignToProfileSeq(AlignmentI al, SequenceI profileseq)
291 char gc = al.getGapCharacter();
292 int[] gapMap = profileseq.gapMap();
293 // insert gaps into profile
294 for (int lp = 0, r = 0; r < gapMap.length; r++)
296 if (gapMap[r] - lp > 1)
298 StringBuffer sb = new StringBuffer();
299 for (int s = 0, ns = gapMap[r] - lp; s < ns; s++)
303 for (int s = 1, ns = al.getHeight(); s < ns; s++)
305 String sq = al.getSequenceAt(s).getSequenceAsString();
306 int diff = gapMap[r] - sq.length();
311 while ((diff = gapMap[r] - sq.length()) > 0)
314 + ((diff >= sb.length()) ? sb.toString() : sb
315 .substring(0, diff));
317 al.getSequenceAt(s).setSequence(sq);
321 al.getSequenceAt(s).setSequence(
322 sq.substring(0, gapMap[r]) + sb.toString()
323 + sq.substring(gapMap[r]));
331 public JPredJob(Hashtable SequenceInfo, SequenceI seq, int[] delMap)
334 this.predMap = delMap;
335 String sq = AlignSeq.extractGaps(Comparison.GapChars,
336 seq.getSequenceAsString());
337 if (sq.length() >= 20)
339 this.SequenceInfo = SequenceInfo;
340 sequence = new vamsas.objects.simple.Sequence();
341 sequence.setId(seq.getName());
346 errorMessage = "Sequence is too short to predict with JPred - need at least 20 amino acids.";
350 public JPredJob(Hashtable SequenceInfo, SequenceI[] msf, int[] delMap)
352 this(SequenceInfo, msf[0], delMap);
353 if (sequence != null)
357 msa = new Msfalignment();
358 PileUpfile pileup = new PileUpfile();
359 msa.setMsf(pileup.print(msf));
364 String errorMessage = "";
366 public String getValidationMessages()
368 return errorMessage + "\n";
372 ext.vamsas.Jpred server;
376 JPredThread(WebserviceInfo wsinfo, String altitle,
377 ext.vamsas.Jpred server, String wsurl, AlignmentView alview,
380 super(alframe, wsinfo, alview, wsurl);
381 this.altitle = altitle;
382 this.server = server;
385 JPredThread(WebserviceInfo wsinfo, String altitle,
386 ext.vamsas.Jpred server, String wsurl, Hashtable SequenceInfo,
387 SequenceI seq, int[] delMap, AlignmentView alview,
390 this(wsinfo, altitle, server, wsurl, alview, alframe);
391 JPredJob job = new JPredJob(SequenceInfo, seq, delMap);
392 if (job.hasValidInput())
394 OutputHeader = wsInfo.getProgressText();
401 wsInfo.appendProgressText(job.getValidationMessages());
405 JPredThread(WebserviceInfo wsinfo, String altitle,
406 ext.vamsas.Jpred server, Hashtable SequenceInfo, SequenceI[] msf,
407 int[] delMap, AlignmentView alview, AlignFrame alframe,
410 this(wsinfo, altitle, server, wsurl, alview, alframe);
411 JPredJob job = new JPredJob(SequenceInfo, msf, delMap);
412 if (job.hasValidInput())
416 OutputHeader = wsInfo.getProgressText();
421 wsInfo.appendProgressText(job.getValidationMessages());
425 public void StartJob(AWsJob j)
427 if (!(j instanceof JPredJob))
429 throw new Error(MessageManager.formatMessage("error.implementation_error_startjob_called", new String[]{j.getClass().toString()}));
433 JPredJob job = (JPredJob) j;
436 job.setJobId(server.predictOnMsa(job.msa));
438 else if (job.sequence != null)
440 job.setJobId(server.predict(job.sequence)); // debug like : job.jobId =
441 // "/jobs/www-jpred/jp_Yatat29";//
444 if (job.getJobId() != null)
446 if (job.getJobId().startsWith("Broken"))
448 job.result = new JpredResult();
449 job.result.setInvalid(true);
450 job.result.setStatus(MessageManager.formatMessage("label.submission_params", new String[]{job.getJobId().toString()}));
451 throw new Exception(job.getJobId());
455 job.setSubmitted(true);
456 job.setSubjobComplete(false);
457 Cache.log.info(WsUrl + " Job Id '" + job.getJobId() + "'");
462 throw new Exception(MessageManager.getString("exception.server_timeout_try_later"));
464 } catch (Exception e)
466 // kill the whole job.
467 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
468 if (e.getMessage().indexOf("Exception") > -1)
470 wsInfo.setStatus(j.getJobnum(),
471 WebserviceInfo.STATE_STOPPED_SERVERERROR);
472 wsInfo.setProgressText(
474 "Failed to submit the prediction. (Just close the window)\n"
475 + "It is most likely that there is a problem with the server.\n");
477 .println("JPredWS Client: Failed to submit the prediction. Quite possibly because of a server error - see below)\n"
478 + e.getMessage() + "\n");
480 Cache.log.warn("Server Exception", e);
484 wsInfo.setStatus(j.getJobnum(), WebserviceInfo.STATE_STOPPED_ERROR);
485 // JBPNote - this could be a popup informing the user of the problem.
486 wsInfo.appendProgressText(j.getJobnum(), MessageManager.formatMessage("info.failed_to_submit_prediction", new String[]{e.getMessage(),wsInfo.getProgressText()}));
489 "Failed Submission of job " + j.getJobnum(), e);
492 j.setAllowedServerExceptions(-1);
493 j.setSubjobComplete(true);
497 public void parseResult()
499 int results = 0; // number of result sets received
500 JobStateSummary finalState = new JobStateSummary();
503 for (int j = 0; j < jobs.length; j++)
505 finalState.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
506 if (jobs[j].isSubmitted() && jobs[j].isSubjobComplete()
507 && jobs[j].hasResults())
512 } catch (Exception ex)
515 Cache.log.error("Unexpected exception when processing results for "
517 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
521 wsInfo.showResultsNewFrame
522 .addActionListener(new java.awt.event.ActionListener()
524 public void actionPerformed(java.awt.event.ActionEvent evt)
526 displayResults(true);
530 .addActionListener(new java.awt.event.ActionListener()
532 public void actionPerformed(java.awt.event.ActionEvent evt)
534 displayResults(false);
537 wsInfo.setResultsReady();
541 wsInfo.setStatus(wsInfo.STATE_STOPPED_ERROR);
542 wsInfo.appendInfoText("No jobs ran.");
543 wsInfo.setFinishedNoResults();
547 void displayResults(boolean newWindow)
549 // TODO: cope with multiple subjobs.
554 for (int jn = 0; jn < jobs.length; jn++)
556 Object[] jobres = null;
557 JPredJob j = (JPredJob) jobs[jn];
561 // hack - we only deal with all single seuqence predictions or all
562 // profile predictions
563 msa = (j.msa != null) ? true : msa;
566 Cache.log.debug("Parsing output of job " + jn);
567 jobres = j.getResultSet();
568 Cache.log.debug("Finished parsing output.");
569 if (jobs.length == 1)
575 // do merge with other job results
576 throw new Error(MessageManager.getString("error.multiple_jnet_subjob_merge_not_implemented"));
578 } catch (Exception e)
581 "JNet Client: JPred Annotation Parse Error", e);
582 wsInfo.setStatus(j.getJobnum(),
583 WebserviceInfo.STATE_STOPPED_ERROR);
584 wsInfo.appendProgressText(j.getJobnum(), MessageManager.formatMessage("info.invalid_jnet_job_result_data", new String[]{OutputHeader.toString(),j.result.getStatus(), e.getMessage() }));
585 j.result.setBroken(true);
599 af = new AlignFrame((Alignment) res[0],
600 (ColumnSelection) res[1], AlignFrame.DEFAULT_WIDTH,
601 AlignFrame.DEFAULT_HEIGHT);
605 af = new AlignFrame((Alignment) res[0],
606 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
612 * java.lang.Object[] alandcolsel =
613 * input.getAlignmentAndColumnSelection
614 * (alignFrame.getViewport().getGapCharacter()); if
615 * (((SequenceI[])alandcolsel[0])[0].getLength()!=res.getWidth()) {
616 * if (msa) { throw new Error("Implementation Error! ColumnSelection
617 * from input alignment will not map to result alignment!"); } } if
618 * (!msa) { // update hidden regions to account for loss of gaps in
619 * profile. - if any // gapMap returns insert list, interpreted as
620 * delete list by pruneDeletions //((ColumnSelection)
621 * alandcolsel[1]).pruneDeletions(ShiftList.parseMap(((SequenceI[])
622 * alandcolsel[0])[0].gapMap())); }
625 af = new AlignFrame((Alignment) res[0],
626 (ColumnSelection) res[1], AlignFrame.DEFAULT_WIDTH,
627 AlignFrame.DEFAULT_HEIGHT);
629 Desktop.addInternalFrame(af, altitle, AlignFrame.DEFAULT_WIDTH,
630 AlignFrame.DEFAULT_HEIGHT);
634 Cache.log.info("Append results onto existing alignment.");
640 public void pollJob(AWsJob job) throws Exception
642 ((JPredJob) job).result = server.getresult(job.getJobId());
645 public boolean isCancellable()
650 public void cancelJob()
652 throw new Error(MessageManager.getString("error.implementation_error"));
655 public boolean canMergeResults()