2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.0b1)
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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
17 * The Jalview Authors are detailed in the 'AUTHORS' file.
19 package jalview.ws.jws1;
23 import jalview.analysis.*;
25 import jalview.datamodel.*;
28 import jalview.util.*;
29 import jalview.ws.AWsJob;
30 import jalview.ws.JobStateSummary;
31 import jalview.ws.WSClientI;
32 import vamsas.objects.simple.JpredResult;
34 class JPredThread extends JWS1Thread implements WSClientI
36 // TODO: put mapping between JPredJob input and input data here -
37 // JNetAnnotation adding is done after result parsing.
38 class JPredJob extends WSJob
40 // TODO: make JPredJob deal only with what was sent to and received from a
42 int[] predMap = null; // mapping from sequence(i) to the original
44 // sequence(predMap[i]) being predicted on
46 vamsas.objects.simple.Sequence sequence;
48 vamsas.objects.simple.Msfalignment msa;
50 java.util.Hashtable SequenceInfo = null;
52 int msaIndex = 0; // the position of the original sequence in the array of
54 // Sequences in the input object that this job holds a
59 * @return true if getResultSet will return a valid alignment and prediction
62 public boolean hasResults()
64 if (subjobComplete && result != null && result.isFinished()
65 && ((JpredResult) result).getPredfile() != null
66 && ((JpredResult) result).getAligfile() != null)
73 public boolean hasValidInput()
84 * @return null or Object[] { annotated alignment for this prediction,
85 * ColumnSelection for this prediction} or null if no results
89 public Object[] getResultSet() throws Exception
91 if (result == null || !result.isFinished())
96 ColumnSelection alcsel = null;
97 int FirstSeq = -1; // the position of the query sequence in Alignment al
99 JpredResult result = (JpredResult) this.result;
101 jalview.bin.Cache.log.debug("Parsing output from JNet job.");
102 // JPredFile prediction = new JPredFile("C:/JalviewX/files/jpred.txt",
104 jalview.io.JPredFile prediction = new jalview.io.JPredFile(
105 result.getPredfile(), "Paste");
106 SequenceI[] preds = prediction.getSeqsAsArray();
107 jalview.bin.Cache.log.debug("Got prediction profile.");
109 if ((this.msa != null) && (result.getAligfile() != null))
111 jalview.bin.Cache.log.debug("Getting associated alignment.");
112 // we ignore the returned alignment if we only predicted on a single
114 String format = new jalview.io.IdentifyFile().Identify(
115 result.getAligfile(), "Paste");
117 if (jalview.io.FormatAdapter.isValidFormat(format))
122 Object[] alandcolsel = input
123 .getAlignmentAndColumnSelection(getGapChar());
124 sqs = (SequenceI[]) alandcolsel[0];
125 al = new Alignment(sqs);
126 alcsel = (ColumnSelection) alandcolsel[1];
130 al = new FormatAdapter().readFile(result.getAligfile(),
132 sqs = new SequenceI[al.getHeight()];
134 for (int i = 0, j = al.getHeight(); i < j; i++)
136 sqs[i] = al.getSequenceAt(i);
138 if (!jalview.analysis.SeqsetUtils.deuniquify(
139 (Hashtable) SequenceInfo, sqs))
141 throw (new Exception(
142 "Couldn't recover sequence properties for alignment."));
148 jalview.io.JnetAnnotationMaker.add_annotation(prediction, al,
149 FirstSeq, false, predMap);
154 throw (new Exception("Unknown format " + format
155 + " for file : \n" + 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)
170 "Implementation Error! Invalid msaIndex for JPredJob on parent MSA input object!");
174 // Uses RemoveGapsCommand
176 new jalview.commands.RemoveGapsCommand("Remove Gaps",
178 { sqs[msaIndex] }, currentView);
180 SequenceI profileseq = al.getSequenceAt(FirstSeq);
181 profileseq.setSequence(sqs[msaIndex].getSequenceAsString());
184 if (!jalview.analysis.SeqsetUtils.SeqCharacterUnhash(
185 al.getSequenceAt(FirstSeq), SequenceInfo))
187 throw (new Exception(
188 "Couldn't recover sequence properties for JNet Query sequence!"));
193 jalview.io.JnetAnnotationMaker.add_annotation(prediction, al,
194 FirstSeq, true, predMap);
195 SequenceI profileseq = al.getSequenceAt(0); // this includes any gaps.
196 alignToProfileSeq(al, profileseq);
199 // Adjust input view for gaps
200 // propagate insertions into profile
201 alcsel = ColumnSelection.propagateInsertions(profileseq, al,
207 { al, alcsel }; // , FirstSeq, noMsa};
211 * Given an alignment where all other sequences except profileseq are
212 * aligned to the ungapped profileseq, insert gaps in the other sequences to
213 * realign them with the residues in profileseq
218 private void alignToProfileSeq(Alignment al, SequenceI profileseq)
220 char gc = al.getGapCharacter();
221 int[] gapMap = profileseq.gapMap();
222 // insert gaps into profile
223 for (int lp = 0, r = 0; r < gapMap.length; r++)
225 if (gapMap[r] - lp > 1)
227 StringBuffer sb = new StringBuffer();
228 for (int s = 0, ns = gapMap[r] - lp; s < ns; s++)
232 for (int s = 1, ns = al.getHeight(); s < ns; s++)
234 String sq = al.getSequenceAt(s).getSequenceAsString();
235 int diff = gapMap[r] - sq.length();
240 while ((diff = gapMap[r] - sq.length()) > 0)
243 + ((diff >= sb.length()) ? sb.toString() : sb
244 .substring(0, diff));
246 al.getSequenceAt(s).setSequence(sq);
250 al.getSequenceAt(s).setSequence(
251 sq.substring(0, gapMap[r]) + sb.toString()
252 + sq.substring(gapMap[r]));
260 public JPredJob(Hashtable SequenceInfo, SequenceI seq, int[] delMap)
263 this.predMap = delMap;
264 String sq = AlignSeq.extractGaps(Comparison.GapChars,
265 seq.getSequenceAsString());
266 if (sq.length() >= 20)
268 this.SequenceInfo = SequenceInfo;
269 sequence = new vamsas.objects.simple.Sequence();
270 sequence.setId(seq.getName());
275 errorMessage = "Sequence is too short to predict with JPred - need at least 20 amino acids.";
279 public JPredJob(Hashtable SequenceInfo, SequenceI[] msf, int[] delMap)
281 this(SequenceInfo, msf[0], delMap);
282 if (sequence != null)
286 msa = new vamsas.objects.simple.Msfalignment();
287 jalview.io.PileUpfile pileup = new jalview.io.PileUpfile();
288 msa.setMsf(pileup.print(msf));
293 String errorMessage = "";
295 public String getValidationMessages()
297 return errorMessage + "\n";
301 ext.vamsas.Jpred server;
305 JPredThread(WebserviceInfo wsinfo, String altitle,
306 ext.vamsas.Jpred server, String wsurl, AlignmentView alview,
309 super(alframe, wsinfo, alview, wsurl);
310 this.altitle = altitle;
311 this.server = server;
314 JPredThread(WebserviceInfo wsinfo, String altitle,
315 ext.vamsas.Jpred server, String wsurl, Hashtable SequenceInfo,
316 SequenceI seq, int[] delMap, AlignmentView alview,
319 this(wsinfo, altitle, server, wsurl, alview, alframe);
320 JPredJob job = new JPredJob(SequenceInfo, seq, delMap);
321 if (job.hasValidInput())
323 OutputHeader = wsInfo.getProgressText();
330 wsInfo.appendProgressText(job.getValidationMessages());
334 JPredThread(WebserviceInfo wsinfo, String altitle,
335 ext.vamsas.Jpred server, Hashtable SequenceInfo, SequenceI[] msf,
336 int[] delMap, AlignmentView alview, AlignFrame alframe,
339 this(wsinfo, altitle, server, wsurl, alview, alframe);
340 JPredJob job = new JPredJob(SequenceInfo, msf, delMap);
341 if (job.hasValidInput())
345 OutputHeader = wsInfo.getProgressText();
350 wsInfo.appendProgressText(job.getValidationMessages());
354 public void StartJob(AWsJob j)
356 if (!(j instanceof JPredJob))
359 "Implementation error - StartJob(JpredJob) called on "
364 JPredJob job = (JPredJob) j;
367 job.setJobId(server.predictOnMsa(job.msa));
369 else if (job.sequence != null)
371 job.setJobId(server.predict(job.sequence)); // debug like : job.jobId =
372 // "/jobs/www-jpred/jp_Yatat29";//
375 if (job.getJobId() != null)
377 if (job.getJobId().startsWith("Broken"))
379 job.result = (vamsas.objects.simple.Result) new JpredResult();
380 job.result.setInvalid(true);
381 job.result.setStatus("Submission " + job.getJobId());
382 throw new Exception(job.getJobId());
386 job.setSubmitted(true);
387 job.setSubjobComplete(false);
388 Cache.log.info(WsUrl + " Job Id '" + job.getJobId() + "'");
393 throw new Exception("Server timed out - try again later\n");
395 } catch (Exception e)
397 // kill the whole job.
398 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
399 if (e.getMessage().indexOf("Exception") > -1)
401 wsInfo.setStatus(j.getJobnum(),
402 WebserviceInfo.STATE_STOPPED_SERVERERROR);
403 wsInfo.setProgressText(
405 "Failed to submit the prediction. (Just close the window)\n"
406 + "It is most likely that there is a problem with the server.\n");
408 .println("JPredWS Client: Failed to submit the prediction. Quite possibly because of a server error - see below)\n"
409 + e.getMessage() + "\n");
411 jalview.bin.Cache.log.warn("Server Exception", e);
415 wsInfo.setStatus(j.getJobnum(), WebserviceInfo.STATE_STOPPED_ERROR);
416 // JBPNote - this could be a popup informing the user of the problem.
417 wsInfo.appendProgressText(j.getJobnum(),
418 "Failed to submit the prediction:\n" + e.getMessage()
419 + wsInfo.getProgressText());
421 jalview.bin.Cache.log.debug(
422 "Failed Submission of job " + j.getJobnum(), e);
425 j.setAllowedServerExceptions(-1);
426 j.setSubjobComplete(true);
430 public void parseResult()
432 int results = 0; // number of result sets received
433 JobStateSummary finalState = new JobStateSummary();
436 for (int j = 0; j < jobs.length; j++)
438 finalState.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
439 if (jobs[j].isSubmitted() && jobs[j].isSubjobComplete()
440 && jobs[j].hasResults())
445 } catch (Exception ex)
448 Cache.log.error("Unexpected exception when processing results for "
450 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
454 wsInfo.showResultsNewFrame
455 .addActionListener(new java.awt.event.ActionListener()
457 public void actionPerformed(java.awt.event.ActionEvent evt)
459 displayResults(true);
463 .addActionListener(new java.awt.event.ActionListener()
465 public void actionPerformed(java.awt.event.ActionEvent evt)
467 displayResults(false);
470 wsInfo.setResultsReady();
474 wsInfo.setStatus(wsInfo.STATE_STOPPED_ERROR);
475 wsInfo.appendInfoText("No jobs ran.");
476 wsInfo.setFinishedNoResults();
480 void displayResults(boolean newWindow)
482 // TODO: cope with multiple subjobs.
487 for (int jn = 0; jn < jobs.length; jn++)
489 Object[] jobres = null;
490 JPredJob j = (JPredJob) jobs[jn];
494 // hack - we only deal with all single seuqence predictions or all
495 // profile predictions
496 msa = (j.msa != null) ? true : msa;
499 jalview.bin.Cache.log.debug("Parsing output of job " + jn);
500 jobres = j.getResultSet();
501 jalview.bin.Cache.log.debug("Finished parsing output.");
502 if (jobs.length == 1)
508 // do merge with other job results
510 "Multiple JNet subjob merging not yet implemented.");
512 } catch (Exception e)
514 jalview.bin.Cache.log.error(
515 "JNet Client: JPred Annotation Parse Error", e);
516 wsInfo.setStatus(j.getJobnum(),
517 WebserviceInfo.STATE_STOPPED_ERROR);
518 wsInfo.appendProgressText(j.getJobnum(), OutputHeader + "\n"
519 + j.result.getStatus()
520 + "\nInvalid JNet job result data!\n" + e.getMessage());
521 j.result.setBroken(true);
535 af = new AlignFrame((Alignment) res[0],
536 (ColumnSelection) res[1], AlignFrame.DEFAULT_WIDTH,
537 AlignFrame.DEFAULT_HEIGHT);
541 af = new AlignFrame((Alignment) res[0],
542 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
548 * java.lang.Object[] alandcolsel =
549 * input.getAlignmentAndColumnSelection
550 * (alignFrame.getViewport().getGapCharacter()); if
551 * (((SequenceI[])alandcolsel[0])[0].getLength()!=res.getWidth()) {
552 * if (msa) { throw new Error("Implementation Error! ColumnSelection
553 * from input alignment will not map to result alignment!"); } } if
554 * (!msa) { // update hidden regions to account for loss of gaps in
555 * profile. - if any // gapMap returns insert list, interpreted as
556 * delete list by pruneDeletions //((ColumnSelection)
557 * alandcolsel[1]).pruneDeletions(ShiftList.parseMap(((SequenceI[])
558 * alandcolsel[0])[0].gapMap())); }
561 af = new AlignFrame((Alignment) res[0],
562 (ColumnSelection) res[1], AlignFrame.DEFAULT_WIDTH,
563 AlignFrame.DEFAULT_HEIGHT);
565 Desktop.addInternalFrame(af, altitle, AlignFrame.DEFAULT_WIDTH,
566 AlignFrame.DEFAULT_HEIGHT);
570 Cache.log.info("Append results onto existing alignment.");
576 public void pollJob(AWsJob job) throws Exception
578 ((JPredJob) job).result = server.getresult(job.getJobId());
581 public boolean isCancellable()
586 public void cancelJob()
588 throw new Error("Implementation error!");
591 public boolean canMergeResults()