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;
25 import jalview.analysis.*;
27 import jalview.datamodel.*;
30 import jalview.util.*;
31 import jalview.ws.AWsJob;
32 import jalview.ws.JobStateSummary;
33 import jalview.ws.WSClientI;
34 import vamsas.objects.simple.JpredResult;
36 class JPredThread extends JWS1Thread implements WSClientI
38 // TODO: put mapping between JPredJob input and input data here -
39 // JNetAnnotation adding is done after result parsing.
40 class JPredJob extends WSJob
42 // TODO: make JPredJob deal only with what was sent to and received from a
44 int[] predMap = null; // mapping from sequence(i) to the original
46 // sequence(predMap[i]) being predicted on
48 vamsas.objects.simple.Sequence sequence;
50 vamsas.objects.simple.Msfalignment msa;
52 java.util.Hashtable SequenceInfo = null;
54 int msaIndex = 0; // the position of the original sequence in the array of
56 // Sequences in the input object that this job holds a
61 * @return true if getResultSet will return a valid alignment and prediction
64 public boolean hasResults()
66 if (subjobComplete && result != null && result.isFinished()
67 && ((JpredResult) result).getPredfile() != null
68 && ((JpredResult) result).getAligfile() != null)
75 public boolean hasValidInput()
86 * @return null or Object[] { annotated alignment for this prediction,
87 * ColumnSelection for this prediction} or null if no results
91 public Object[] getResultSet() throws Exception
93 if (result == null || !result.isFinished())
98 ColumnSelection alcsel = null;
99 int FirstSeq = -1; // the position of the query sequence in Alignment al
101 JpredResult result = (JpredResult) this.result;
103 jalview.bin.Cache.log.debug("Parsing output from JNet job.");
104 // JPredFile prediction = new JPredFile("C:/JalviewX/files/jpred.txt",
106 jalview.io.JPredFile prediction = new jalview.io.JPredFile(
107 result.getPredfile(), "Paste");
108 SequenceI[] preds = prediction.getSeqsAsArray();
109 jalview.bin.Cache.log.debug("Got prediction profile.");
111 if ((this.msa != null) && (result.getAligfile() != null))
113 jalview.bin.Cache.log.debug("Getting associated alignment.");
114 // we ignore the returned alignment if we only predicted on a single
116 String format = new jalview.io.IdentifyFile().Identify(
117 result.getAligfile(), "Paste");
119 if (jalview.io.FormatAdapter.isValidFormat(format))
124 Object[] alandcolsel = input
125 .getAlignmentAndColumnSelection(getGapChar());
126 sqs = (SequenceI[]) alandcolsel[0];
127 al = new Alignment(sqs);
128 alcsel = (ColumnSelection) alandcolsel[1];
132 al = new FormatAdapter().readFile(result.getAligfile(),
134 sqs = new SequenceI[al.getHeight()];
136 for (int i = 0, j = al.getHeight(); i < j; i++)
138 sqs[i] = al.getSequenceAt(i);
140 if (!jalview.analysis.SeqsetUtils.deuniquify(
141 (Hashtable) SequenceInfo, sqs))
143 throw (new Exception(MessageManager.getString("exception.couldnt_recover_sequence_properties_for_alignment")));
149 jalview.io.JnetAnnotationMaker.add_annotation(prediction, al,
150 FirstSeq, false, predMap);
155 throw (new Exception(MessageManager.formatMessage("exception.unknown_format_for_file", new String[]{format,result.getAligfile()})));
160 al = new Alignment(preds);
161 FirstSeq = prediction.getQuerySeqPosition();
164 char gc = getGapChar();
165 SequenceI[] sqs = (SequenceI[]) ((java.lang.Object[]) input
166 .getAlignmentAndColumnSelection(gc))[0];
167 if (this.msaIndex >= sqs.length)
169 throw new Error(MessageManager.getString("error.implementation_error_invalid_msa_index_for_job"));
173 // Uses RemoveGapsCommand
175 new jalview.commands.RemoveGapsCommand(MessageManager.getString("label.remove_gaps"),
177 { sqs[msaIndex] }, currentView);
179 SequenceI profileseq = al.getSequenceAt(FirstSeq);
180 profileseq.setSequence(sqs[msaIndex].getSequenceAsString());
183 if (!jalview.analysis.SeqsetUtils.SeqCharacterUnhash(
184 al.getSequenceAt(FirstSeq), SequenceInfo))
186 throw (new Exception(MessageManager.getString("exception.couldnt_recover_sequence_props_for_jnet_query")));
191 jalview.io.JnetAnnotationMaker.add_annotation(prediction, al,
192 FirstSeq, true, predMap);
193 SequenceI profileseq = al.getSequenceAt(0); // this includes any gaps.
194 alignToProfileSeq(al, profileseq);
197 // Adjust input view for gaps
198 // propagate insertions into profile
199 alcsel = ColumnSelection.propagateInsertions(profileseq, al,
205 { al, alcsel }; // , FirstSeq, noMsa};
209 * Given an alignment where all other sequences except profileseq are
210 * aligned to the ungapped profileseq, insert gaps in the other sequences to
211 * realign them with the residues in profileseq
216 private void alignToProfileSeq(Alignment al, SequenceI profileseq)
218 char gc = al.getGapCharacter();
219 int[] gapMap = profileseq.gapMap();
220 // insert gaps into profile
221 for (int lp = 0, r = 0; r < gapMap.length; r++)
223 if (gapMap[r] - lp > 1)
225 StringBuffer sb = new StringBuffer();
226 for (int s = 0, ns = gapMap[r] - lp; s < ns; s++)
230 for (int s = 1, ns = al.getHeight(); s < ns; s++)
232 String sq = al.getSequenceAt(s).getSequenceAsString();
233 int diff = gapMap[r] - sq.length();
238 while ((diff = gapMap[r] - sq.length()) > 0)
241 + ((diff >= sb.length()) ? sb.toString() : sb
242 .substring(0, diff));
244 al.getSequenceAt(s).setSequence(sq);
248 al.getSequenceAt(s).setSequence(
249 sq.substring(0, gapMap[r]) + sb.toString()
250 + sq.substring(gapMap[r]));
258 public JPredJob(Hashtable SequenceInfo, SequenceI seq, int[] delMap)
261 this.predMap = delMap;
262 String sq = AlignSeq.extractGaps(Comparison.GapChars,
263 seq.getSequenceAsString());
264 if (sq.length() >= 20)
266 this.SequenceInfo = SequenceInfo;
267 sequence = new vamsas.objects.simple.Sequence();
268 sequence.setId(seq.getName());
273 errorMessage = "Sequence is too short to predict with JPred - need at least 20 amino acids.";
277 public JPredJob(Hashtable SequenceInfo, SequenceI[] msf, int[] delMap)
279 this(SequenceInfo, msf[0], delMap);
280 if (sequence != null)
284 msa = new vamsas.objects.simple.Msfalignment();
285 jalview.io.PileUpfile pileup = new jalview.io.PileUpfile();
286 msa.setMsf(pileup.print(msf));
291 String errorMessage = "";
293 public String getValidationMessages()
295 return errorMessage + "\n";
299 ext.vamsas.Jpred server;
303 JPredThread(WebserviceInfo wsinfo, String altitle,
304 ext.vamsas.Jpred server, String wsurl, AlignmentView alview,
307 super(alframe, wsinfo, alview, wsurl);
308 this.altitle = altitle;
309 this.server = server;
312 JPredThread(WebserviceInfo wsinfo, String altitle,
313 ext.vamsas.Jpred server, String wsurl, Hashtable SequenceInfo,
314 SequenceI seq, int[] delMap, AlignmentView alview,
317 this(wsinfo, altitle, server, wsurl, alview, alframe);
318 JPredJob job = new JPredJob(SequenceInfo, seq, delMap);
319 if (job.hasValidInput())
321 OutputHeader = wsInfo.getProgressText();
328 wsInfo.appendProgressText(job.getValidationMessages());
332 JPredThread(WebserviceInfo wsinfo, String altitle,
333 ext.vamsas.Jpred server, Hashtable SequenceInfo, SequenceI[] msf,
334 int[] delMap, AlignmentView alview, AlignFrame alframe,
337 this(wsinfo, altitle, server, wsurl, alview, alframe);
338 JPredJob job = new JPredJob(SequenceInfo, msf, delMap);
339 if (job.hasValidInput())
343 OutputHeader = wsInfo.getProgressText();
348 wsInfo.appendProgressText(job.getValidationMessages());
352 public void StartJob(AWsJob j)
354 if (!(j instanceof JPredJob))
356 throw new Error(MessageManager.formatMessage("error.implementation_error_startjob_called", new String[]{j.getClass().toString()}));
360 JPredJob job = (JPredJob) j;
363 job.setJobId(server.predictOnMsa(job.msa));
365 else if (job.sequence != null)
367 job.setJobId(server.predict(job.sequence)); // debug like : job.jobId =
368 // "/jobs/www-jpred/jp_Yatat29";//
371 if (job.getJobId() != null)
373 if (job.getJobId().startsWith("Broken"))
375 job.result = (vamsas.objects.simple.Result) new JpredResult();
376 job.result.setInvalid(true);
377 job.result.setStatus(MessageManager.formatMessage("label.submission_params", new String[]{job.getJobId().toString()}));
378 throw new Exception(job.getJobId());
382 job.setSubmitted(true);
383 job.setSubjobComplete(false);
384 Cache.log.info(WsUrl + " Job Id '" + job.getJobId() + "'");
389 throw new Exception(MessageManager.getString("exception.server_timeout_try_later"));
391 } catch (Exception e)
393 // kill the whole job.
394 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
395 if (e.getMessage().indexOf("Exception") > -1)
397 wsInfo.setStatus(j.getJobnum(),
398 WebserviceInfo.STATE_STOPPED_SERVERERROR);
399 wsInfo.setProgressText(
401 "Failed to submit the prediction. (Just close the window)\n"
402 + "It is most likely that there is a problem with the server.\n");
404 .println("JPredWS Client: Failed to submit the prediction. Quite possibly because of a server error - see below)\n"
405 + e.getMessage() + "\n");
407 jalview.bin.Cache.log.warn("Server Exception", e);
411 wsInfo.setStatus(j.getJobnum(), WebserviceInfo.STATE_STOPPED_ERROR);
412 // JBPNote - this could be a popup informing the user of the problem.
413 wsInfo.appendProgressText(j.getJobnum(), MessageManager.formatMessage("info.failed_to_submit_prediction", new String[]{e.getMessage(),wsInfo.getProgressText()}));
415 jalview.bin.Cache.log.debug(
416 "Failed Submission of job " + j.getJobnum(), e);
419 j.setAllowedServerExceptions(-1);
420 j.setSubjobComplete(true);
424 public void parseResult()
426 int results = 0; // number of result sets received
427 JobStateSummary finalState = new JobStateSummary();
430 for (int j = 0; j < jobs.length; j++)
432 finalState.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
433 if (jobs[j].isSubmitted() && jobs[j].isSubjobComplete()
434 && jobs[j].hasResults())
439 } catch (Exception ex)
442 Cache.log.error("Unexpected exception when processing results for "
444 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
448 wsInfo.showResultsNewFrame
449 .addActionListener(new java.awt.event.ActionListener()
451 public void actionPerformed(java.awt.event.ActionEvent evt)
453 displayResults(true);
457 .addActionListener(new java.awt.event.ActionListener()
459 public void actionPerformed(java.awt.event.ActionEvent evt)
461 displayResults(false);
464 wsInfo.setResultsReady();
468 wsInfo.setStatus(wsInfo.STATE_STOPPED_ERROR);
469 wsInfo.appendInfoText("No jobs ran.");
470 wsInfo.setFinishedNoResults();
474 void displayResults(boolean newWindow)
476 // TODO: cope with multiple subjobs.
481 for (int jn = 0; jn < jobs.length; jn++)
483 Object[] jobres = null;
484 JPredJob j = (JPredJob) jobs[jn];
488 // hack - we only deal with all single seuqence predictions or all
489 // profile predictions
490 msa = (j.msa != null) ? true : msa;
493 jalview.bin.Cache.log.debug("Parsing output of job " + jn);
494 jobres = j.getResultSet();
495 jalview.bin.Cache.log.debug("Finished parsing output.");
496 if (jobs.length == 1)
502 // do merge with other job results
503 throw new Error(MessageManager.getString("error.multiple_jnet_subjob_merge_not_implemented"));
505 } catch (Exception e)
507 jalview.bin.Cache.log.error(
508 "JNet Client: JPred Annotation Parse Error", e);
509 wsInfo.setStatus(j.getJobnum(),
510 WebserviceInfo.STATE_STOPPED_ERROR);
511 wsInfo.appendProgressText(j.getJobnum(), MessageManager.formatMessage("info.invalid_jnet_job_result_data", new String[]{OutputHeader.toString(),j.result.getStatus(), e.getMessage() }));
512 j.result.setBroken(true);
526 af = new AlignFrame((Alignment) res[0],
527 (ColumnSelection) res[1], AlignFrame.DEFAULT_WIDTH,
528 AlignFrame.DEFAULT_HEIGHT);
532 af = new AlignFrame((Alignment) res[0],
533 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
539 * java.lang.Object[] alandcolsel =
540 * input.getAlignmentAndColumnSelection
541 * (alignFrame.getViewport().getGapCharacter()); if
542 * (((SequenceI[])alandcolsel[0])[0].getLength()!=res.getWidth()) {
543 * if (msa) { throw new Error("Implementation Error! ColumnSelection
544 * from input alignment will not map to result alignment!"); } } if
545 * (!msa) { // update hidden regions to account for loss of gaps in
546 * profile. - if any // gapMap returns insert list, interpreted as
547 * delete list by pruneDeletions //((ColumnSelection)
548 * alandcolsel[1]).pruneDeletions(ShiftList.parseMap(((SequenceI[])
549 * alandcolsel[0])[0].gapMap())); }
552 af = new AlignFrame((Alignment) res[0],
553 (ColumnSelection) res[1], AlignFrame.DEFAULT_WIDTH,
554 AlignFrame.DEFAULT_HEIGHT);
556 Desktop.addInternalFrame(af, altitle, AlignFrame.DEFAULT_WIDTH,
557 AlignFrame.DEFAULT_HEIGHT);
561 Cache.log.info("Append results onto existing alignment.");
567 public void pollJob(AWsJob job) throws Exception
569 ((JPredJob) job).result = server.getresult(job.getJobId());
572 public boolean isCancellable()
577 public void cancelJob()
579 throw new Error(MessageManager.getString("error.implementation_error"));
582 public boolean canMergeResults()