1 package jalview.ws.jws2;
3 import static java.lang.String.format;
5 import java.util.Hashtable;
8 import jalview.analysis.SeqsetUtils;
9 import jalview.bin.Cache;
10 import jalview.commands.RemoveGapsCommand;
11 import jalview.datamodel.Alignment;
12 import jalview.datamodel.AlignmentAnnotation;
13 import jalview.datamodel.AlignmentI;
14 import jalview.datamodel.AlignmentView;
15 import jalview.datamodel.HiddenColumns;
16 import jalview.datamodel.SequenceI;
17 import jalview.gui.AlignFrame;
18 import jalview.gui.Desktop;
19 import jalview.gui.WebserviceInfo;
20 import jalview.io.JnetAnnotationMaker;
21 import jalview.util.MessageManager;
22 import jalview.ws.AWSThread;
23 import jalview.ws.AWsJob;
24 import jalview.ws.JobStateSummary;
25 import jalview.ws.WSClientI;
26 import jalview.ws.api.CancellableI;
27 import jalview.ws.api.JPredServiceI;
28 import jalview.ws.gui.WsJob;
29 import jalview.ws.gui.WsJob.JobState;
32 public class JPredThread extends AWSThread implements WSClientI
35 private static class JPredJob extends WsJob
37 private final Hashtable<?, ?> sequenceInfo;
38 private final List<SequenceI> msf;
39 private final int[] delMap;
40 private AlignmentI alignment = null;
41 private HiddenColumns hiddenCols = null;
43 private JPredJob(Hashtable<?, ?> sequenceInfo, SequenceI[] msf, int[] delMap)
45 this.sequenceInfo = sequenceInfo;
46 this.msf = List.of(msf);
51 public boolean hasValidInput()
57 public boolean hasResults()
59 return (isSubjobComplete() && alignment != null);
62 public boolean isMSA()
64 return msf.size() > 1;
69 private JPredServiceI server;
71 private Hashtable<?, ?> sequenceInfo;
72 private SequenceI[] msf;
75 public JPredThread(WebserviceInfo wsInfo, String title,
76 JPredServiceI server, Hashtable<?, ?> sequenceInfo,
77 SequenceI[] msf, int[] delMap, AlignmentView view, AlignFrame frame,
80 super(frame, wsInfo, view, wsURL);
83 this.sequenceInfo = sequenceInfo;
86 JPredJob job = new JPredJob(sequenceInfo, msf, delMap);
87 this.jobs = new JPredJob[] { job };
91 public boolean isCancellable()
93 return server instanceof CancellableI;
97 public boolean canMergeResults()
103 public void cancelJob()
105 // TODO Auto-generated method stub
110 public void pollJob(AWsJob job_) throws Exception
112 var job = (JPredJob) job_;
113 server.updateStatus(job);
114 server.updateJobProgress(job);
118 public void StartJob(AWsJob job_)
120 if (!(job_ instanceof JPredJob))
121 throw new RuntimeException("Invalid job type");
122 var job = (JPredJob) job_;
123 if (job.isSubmitted())
130 var jobHandle = server.predict(job.msf, job.isMSA());
131 if (jobHandle != null)
132 job.setJobHandle(jobHandle);
134 catch (Throwable th) {
135 if (!server.handleSubmitError(th, job, wsInfo)) {
139 if (job.getJobId() != null) {
140 job.setSubmitted(true);
141 job.setSubjobComplete(false);
145 throw new Exception(MessageManager.formatMessage(
146 "exception.web_service_returned_null_try_later",
153 // For unexpected errors
154 System.err.println(WebServiceName
155 + "Client: Failed to submit the sequences for alignment (probably a server side problem)\n"
156 + "When contacting Server:" + WsUrl + "\n");
157 th.printStackTrace(System.err);
158 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
159 wsInfo.setStatus(job.getJobnum(),
160 WebserviceInfo.STATE_STOPPED_SERVERERROR);
165 if (!job.isSubmitted())
167 job.setAllowedServerExceptions(0);
168 wsInfo.appendProgressText(job.getJobnum(), MessageManager.getString(
169 "info.failed_to_submit_sequences_for_alignment"));
175 public void parseResult()
177 long progbar = (long) (Math.random() * ~(1L << 63));
178 wsInfo.setProgressBar(
179 MessageManager.getString("status.collecting_job_results"), progbar);
181 var finalState = new JobStateSummary();
184 for (int i = 0; i < jobs.length; i++) {
185 final var job = (JPredJob) jobs[i];
186 finalState.updateJobPanelState(wsInfo, OutputHeader, job);
187 if (job.isFinished()) {
189 server.updateJobProgress(job);
191 catch (Exception e) {
192 Cache.log.warn(format(
193 "Exception when retrieving remaining Job progress data " +
194 "for job %s on server %s", job.getJobId(), WsUrl));
197 // removed the waiting loop
198 Cache.log.debug(format("Job Execution file for job: %s " +
199 "on server %s%n%s", job.getJobId(), WsUrl, job.getStatus()));
201 prepareJobResult(job);
203 catch (Exception e) {
204 if (!server.handleCollectionException(e, job, wsInfo)) {
205 Cache.log.error("Could not get alignment for job.", e);
206 job.setState(JobState.SERVERERROR);
210 finalState.updateJobPanelState(wsInfo, OutputHeader, job);
211 if (job.isSubmitted() && job.isSubjobComplete() && job.hasResults()) {
216 catch (Exception e) {
218 "Unexpected exception when processing results for " + title, e);
219 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
222 wsInfo.showResultsNewFrame.addActionListener(
223 (evt) -> displayResults(true));
224 wsInfo.mergeResults.addActionListener(
225 (evt) -> displayResults(false));
226 wsInfo.setResultsReady();
229 wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
230 wsInfo.appendInfoText("No jobs ran.");
231 wsInfo.setFinishedNoResults();
233 updateGlobalStatus(finalState);
234 wsInfo.removeProgressBar(progbar);
237 static final int msaIndex = 0;
239 private void prepareJobResult(JPredJob job) throws Exception
241 HiddenColumns hiddenCols = null;
243 AlignmentI alignment;
244 var prediction = server.getPrediction(job.getJobHandle());
245 var preds = prediction.getSeqsAsArray();
247 if (job.msf.size() > 1)
249 if (job.delMap != null)
251 Object[] alandcolsel = input
252 .getAlignmentAndHiddenColumns(getGapChar());
253 alignment = new Alignment((SequenceI[]) alandcolsel[0]);
254 hiddenCols = (HiddenColumns) alandcolsel[1];
258 alignment = server.getAlignment(job.getJobHandle());
259 var seqs = new SequenceI[alignment.getHeight()];
260 for (int i = 0; i < alignment.getHeight(); i++)
262 seqs[i] = alignment.getSequenceAt(i);
264 if (!SeqsetUtils.deuniquify(sequenceInfo, seqs))
266 throw (new Exception(MessageManager.getString(
267 "exception.couldnt_recover_sequence_properties_for_alignment")));
271 if (currentView.getDataset() != null)
273 alignment.setDataset(currentView.getDataset());
277 alignment.setDataset(null);
279 JnetAnnotationMaker.add_annotation(prediction, alignment, firstSeq, false,
284 alignment = new Alignment(preds);
285 firstSeq = prediction.getQuerySeqPosition();
286 if (job.delMap != null)
288 Object[] alanndcolsel = input.getAlignmentAndHiddenColumns(getGapChar());
289 SequenceI[] seqs = (SequenceI[]) alanndcolsel[0];
290 new RemoveGapsCommand(MessageManager.getString("label.remove_gaps"),
291 new SequenceI[] {seqs[msaIndex]}, currentView);
292 SequenceI profileSeq = alignment.getSequenceAt(firstSeq);
293 profileSeq.setSequence(seqs[msaIndex].getSequenceAsString());
295 if (!SeqsetUtils.SeqCharacterUnhash(
296 alignment.getSequenceAt(firstSeq), sequenceInfo))
298 throw new Exception(MessageManager.getString(
299 "exception.couldnt_recover_sequence_props_for_jnet_query"));
301 alignment.setDataset(currentView.getDataset());
302 JnetAnnotationMaker.add_annotation(prediction, alignment, firstSeq, true,
304 SequenceI profileSeq = alignment.getSequenceAt(0);
305 alignToProfileSeq(alignment, profileSeq);
306 if (job.delMap != null)
308 hiddenCols = alignment.propagateInsertions(profileSeq, input);
312 for (var annot : alignment.getAlignmentAnnotation())
314 if (annot.sequenceRef != null)
316 replaceAnnotationOnAlignmentWith(annot, annot.label,
317 "jalview.ws.JPred", annot.sequenceRef);
320 job.alignment = alignment;
321 job.hiddenCols = hiddenCols;
324 private static void replaceAnnotationOnAlignmentWith(
325 AlignmentAnnotation newAnnot, String typeName, String calcId,
328 SequenceI dsseq = aSeq.getDatasetSequence();
329 while (dsseq.getDatasetSequence() != null)
331 dsseq = dsseq.getDatasetSequence();
333 // look for same annotation on dataset and lift this one over
334 List<AlignmentAnnotation> dsan = dsseq.getAlignmentAnnotations(calcId,
336 if (dsan != null && dsan.size() > 0)
338 for (AlignmentAnnotation dssan : dsan)
340 dsseq.removeAlignmentAnnotation(dssan);
343 AlignmentAnnotation dssan = new AlignmentAnnotation(newAnnot);
344 dsseq.addAlignmentAnnotation(dssan);
345 dssan.adjustForAlignment();
348 private static void alignToProfileSeq(AlignmentI al, SequenceI profileseq)
350 char gc = al.getGapCharacter();
351 int[] gapMap = profileseq.gapMap();
352 // insert gaps into profile
353 for (int lp = 0, r = 0; r < gapMap.length; r++)
355 if (gapMap[r] - lp > 1)
357 StringBuffer sb = new StringBuffer();
358 for (int s = 0, ns = gapMap[r] - lp; s < ns; s++)
362 for (int s = 1, ns = al.getHeight(); s < ns; s++)
364 String sq = al.getSequenceAt(s).getSequenceAsString();
365 int diff = gapMap[r] - sq.length();
370 while ((diff = gapMap[r] - sq.length()) > 0)
372 sq = sq + ((diff >= sb.length()) ? sb.toString()
373 : sb.substring(0, diff));
375 al.getSequenceAt(s).setSequence(sq);
379 al.getSequenceAt(s).setSequence(sq.substring(0, gapMap[r])
380 + sb.toString() + sq.substring(gapMap[r]));
388 private void displayResults(boolean newWindow)
390 if (jobs == null || jobs.length == 0)
394 var job = (JPredJob) jobs[0];
395 if (job.hasResults() && newWindow)
397 job.alignment.setSeqrep(job.alignment.getSequenceAt(0));
398 AlignFrame frame = new AlignFrame(job.alignment, job.hiddenCols,
399 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
400 Desktop.addInternalFrame(frame, title, AlignFrame.DEFAULT_WIDTH,
401 AlignFrame.DEFAULT_HEIGHT);