cubevis 0.5.19__py3-none-any.whl → 0.5.21__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of cubevis might be problematic. Click here for more details.

@@ -0,0 +1,1498 @@
1
+ ########################################################################
2
+ #
3
+ # Copyright (C) 2022,2023,2024,2025
4
+ # Associated Universities, Inc. Washington DC, USA.
5
+ #
6
+ # This script is free software; you can redistribute it and/or modify it
7
+ # under the terms of the GNU Library General Public License as published by
8
+ # the Free Software Foundation; either version 2 of the License, or (at your
9
+ # option) any later version.
10
+ #
11
+ # This library is distributed in the hope that it will be useful, but WITHOUT
12
+ # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
+ # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
14
+ # License for more details.
15
+ #
16
+ # You should have received a copy of the GNU Library General Public License
17
+ # along with this library; if not, write to the Free Software Foundation,
18
+ # Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
19
+ #
20
+ # Correspondence concerning AIPS++ should be adressed as follows:
21
+ # Internet email: casa-feedback@nrao.edu.
22
+ # Postal address: AIPS++ Project Office
23
+ # National Radio Astronomy Observatory
24
+ # 520 Edgemont Road
25
+ # Charlottesville, VA 22903-2475 USA
26
+ #
27
+ ########################################################################
28
+ '''implementation of the ``InteractiveCleanUI`` application for interactive control
29
+ of tclean'''
30
+
31
+ ###
32
+ ### Useful for debugging
33
+ ###
34
+ ###from cubevis.bokeh.state import initialize_bokeh
35
+ ###initialize_bokeh( bokehjs_subst=".../bokeh-3.2.2.js" )
36
+ ###
37
+
38
+ from pprint import pprint
39
+
40
+ import os
41
+ import sys
42
+ import copy
43
+ import asyncio
44
+ import shutil
45
+ import websockets
46
+ from os.path import basename, abspath, exists, join
47
+ from uuid import uuid4
48
+ from html import escape as html_escape
49
+ from contextlib import asynccontextmanager
50
+ from bokeh.models import Button, TextInput, Checkbox, Div, LinearAxis, CustomJS, Spacer, Span, HoverTool, DataRange1d, Step, InlineStyleSheet
51
+ from bokeh.events import ModelEvent, MouseEnter
52
+ from bokeh.models import TabPanel, Tabs
53
+ from bokeh.plotting import ColumnDataSource, figure, show
54
+ from bokeh.layouts import column, row, layout
55
+ from bokeh.io import reset_output as reset_bokeh_output, output_notebook
56
+ from bokeh.models.dom import HTML
57
+
58
+ from bokeh.models.ui.tooltips import Tooltip
59
+ from cubevis.bokeh.models import TipButton, Tip, EvTextInput
60
+ from cubevis.utils import resource_manager, reset_resource_manager, is_interactive_jupyter, find_pkg, load_pkg
61
+ from cubevis.utils import ContextMgrChain as CMC
62
+
63
+ # pylint: disable=no-name-in-module
64
+ from casatasks.private.imagerhelpers.imager_return_dict import ImagingDict
65
+
66
+ from casatasks.private.imagerhelpers.input_parameters import ImagerParameters
67
+ # pylint: enable=no-name-in-module
68
+
69
+ from cubevis.utils import find_ws_address, convert_masks
70
+ from cubevis.toolbox import CubeMask, AppContext
71
+ from cubevis.bokeh.utils import svg_icon
72
+ from cubevis.bokeh.sources import DataPipe
73
+ from cubevis.utils import DocEnum
74
+ from cubevis import exe
75
+
76
+ from ._interactiveclean_wrappers import SharedWidgets
77
+
78
+ USE_MULTIPLE_GCLEAN_HACK=False
79
+
80
+ class InteractiveCleanUI:
81
+ '''InteractiveCleanUI(...) implements interactive clean using Bokeh
82
+ '''
83
+ def __stop( self, _=None ):
84
+ self.__result_future.set_result(self.__retrieve_result( ))
85
+
86
+ def _abort_handler( self, err ):
87
+ self._error_result = err
88
+ self.__stop( )
89
+
90
+ def __reset( self ):
91
+ if self.__pipes_initialized:
92
+ self._pipe = { 'control': None }
93
+ self._clean = { 'converge': { 'state': { } }, 'last-success': None }
94
+ reset_bokeh_output( )
95
+ reset_resource_manager( )
96
+
97
+ ###
98
+ ### reset asyncio result future
99
+ ###
100
+ self.__result_future = None
101
+
102
+ ###
103
+ ### used by data pipe (websocket) initialization function
104
+ ###
105
+ self.__pipes_initialized = False
106
+
107
+ ###
108
+ ### error or exception result
109
+ ###
110
+ self._error_result = None
111
+
112
+ ###
113
+ ### iclean results
114
+ ###
115
+ self.__result = None
116
+ self.__result_from_gui = None
117
+
118
+ '''
119
+ _gen_port_fwd_cmd()
120
+
121
+ Create an SSH port-forwarding command to create the tunnels necessary for remote connection.
122
+ NOTE: This assumes that the same remote ports are also available locally - which may
123
+ NOT always be true.
124
+ '''
125
+ def _gen_port_fwd_cmd(self):
126
+ hostname = os.uname()[1]
127
+
128
+ ###
129
+ ### need to add extra cube ports here for multifield imaging
130
+ ###
131
+ ports = [ self._pipe['control'].address[1], self._clean['converge']['pipe'].address[1] ]
132
+
133
+ for imid, imdetails in self._clean_targets.items( ):
134
+ ports.append( imdetails['gui']['cube']._pipe['image'].address[1] )
135
+ ports.append( imdetails['gui']['cube']._pipe['control'].address[1] )
136
+
137
+ # Also forward http port if serving webpage
138
+ if not self._is_notebook:
139
+ ports.append(self._http_port)
140
+
141
+ cmd = 'ssh'
142
+ for port in ports:
143
+ cmd += (' -L ' + str(port) + ':localhost:' + str(port))
144
+
145
+ cmd += ' ' + str(hostname)
146
+ return cmd
147
+
148
+ def _residual_path( self, gclean, imid ):
149
+ if self._clean['gclean_paths'] is None:
150
+ raise RuntimeError( f'''gclean paths are not available for {imid}''' )
151
+ for p in self._clean['gclean_paths']:
152
+ if p['name'] == imid:
153
+ return f"{p['imagepath']}/{p['residualname']}"
154
+ raise RuntimeError( f'''gclean residual path not found for {imid}''' )
155
+
156
+ def _mask_path( self, gclean, imid ):
157
+ if self._clean['gclean_paths'] is None:
158
+ raise RuntimeError( f'''gclean paths are not available for {imid}''' )
159
+ for p in self._clean['gclean_paths']:
160
+ if p['name'] == imid:
161
+ return f"{p['imagepath']}/{p['maskname']}"
162
+ raise RuntimeError( f'''gclean mask path not found for {imid}''' )
163
+
164
+ def __init__( self, gclean, user_args ):
165
+
166
+ ###
167
+ ### With Bokeh 3.2.2, the spectrum and convergence plots extend beyond the edge of the
168
+ ### browser window (requiring scrolling) if a width is not specified. It could be that
169
+ ### this should be computed from the width of the tabbed control area at the right of
170
+ ### the image display.
171
+ ###
172
+ self._conv_spect_plot_width = 450
173
+ ###
174
+ ### Create application context (which includes a temporary directory).
175
+ ### This sets the title of the plot.
176
+ ###
177
+ self._app_state = AppContext( 'Interactive Clean' )
178
+
179
+ ###
180
+ ### Whether or not the Interactive Clean session is running remotely
181
+ ###
182
+ #self._is_remote = remote
183
+ self._is_remote = False
184
+
185
+ ###
186
+ ### whether or not the session is being run from a jupyter notebook or script
187
+ ###
188
+ self._is_notebook = is_interactive_jupyter()
189
+
190
+ ##
191
+ ## the http port for serving GUI in webpage if not running in script
192
+ ##
193
+ self._http_port = None
194
+
195
+ ###
196
+ ### the asyncio future that is used to transmit the result from interactive clean
197
+ ###
198
+ self.__result_future = None
199
+
200
+ ###
201
+ ### This is used to tell whether the websockets have been initialized, but also to
202
+ ### indicate if __call__ is being called multiple times to allow for resetting Bokeh
203
+ ###
204
+ self.__pipes_initialized = False
205
+
206
+ ###
207
+ ### State required to manage iteration control
208
+ ###
209
+ self._control = { 'iteration': { } }
210
+
211
+ ###
212
+ ### color specs
213
+ ###
214
+ self._converge_color = { 'residual': 'black',
215
+ 'flux': 'forestgreen' }
216
+
217
+ ###
218
+ ### widgets shared across image tabs (multifield imaging)
219
+ ###
220
+ self._cube_palette = None
221
+ self._image_bitmask_controls = None
222
+
223
+ ###
224
+ ### String which indicates the changes applied to the mask to indicte when
225
+ ### the mask has changed... however, THIS IS NO LONGER USED
226
+ ### It could be removed, but it adds minor overhead and would be
227
+ ### DIFFICULT to add back in the future
228
+ ###
229
+ self._last_mask_breadcrumbs = ''
230
+
231
+ ###
232
+ ### Set up dictionary of javascript code snippets
233
+ ###
234
+ self._initialize_javascript( )
235
+
236
+ self._pipe = { 'control': None }
237
+ self._clean = { 'converge': { 'state': { } }, 'last-success': None }
238
+
239
+ ###
240
+ ### create clean interface -- final version will have only one gclean object
241
+ ###
242
+ self._init_values = { "deconvolver": user_args['deconvolver'], ### used by _residual_path( )
243
+ "cycleniter": user_args['cycleniter'], ### used by _setup( )
244
+ "threshold": user_args['threshold'], ### used by _setup( )
245
+ "cyclefactor": user_args['cyclefactor'], ### used by _setup( )
246
+ "gain": user_args['gain'], ### used by _setup( )
247
+ "nsigma": user_args['nsigma'], ### used by _setup( )
248
+ "convergence_state": { 'convergence': {}, ### shares state between
249
+ 'cyclethreshold': {} } } ### __init__( ) and _setup( )
250
+
251
+ self._clean['gclean'] = gclean
252
+
253
+ self._clean['gclean_paths'] = { prod['name']: prod for prod in self._clean['gclean'].image_products( ) }
254
+ self._clean['imid'] = [ name for name,prod in self._clean['gclean_paths'].items( ) ]
255
+ self._clean_targets = { id: { } for id in self._clean['imid'] }
256
+ self._clean['gclean_rest'] = [ ]
257
+ self._initial_clean_params = { }
258
+
259
+ imagename = self._clean['imid'][0]
260
+
261
+ # Create folder for the generated html webpage - needs its own folder to not name conflict (must be 'index.html')
262
+ webpage_dirname = imagename + '_webpage'
263
+ ### Directory is created when an HTTP server is running
264
+ ### (MAX)
265
+ # if not os.path.isdir(webpage_dirname):
266
+ # os.makedirs(webpage_dirname)
267
+ self._webpage_path = os.path.abspath(webpage_dirname)
268
+
269
+ for imid, imdetails in self._clean_targets.items( ):
270
+ self._clean['imid'].append(imid)
271
+
272
+ ###
273
+ ### Residual path...
274
+ ###
275
+ if 'path' not in imdetails: imdetails['path'] = { }
276
+ output_dir = self._clean['gclean_paths'][imid]['imagepath']
277
+ imdetails['path']['residual'] = join( output_dir, self._clean['gclean_paths'][imid]['residualname'] )
278
+ imdetails['path']['mask'] = join( output_dir, self._clean['gclean_paths'][imid]['maskname'] )
279
+
280
+ for idx, (imid, imdetails) in enumerate(self._clean_targets.items( )):
281
+ imdetails['gui'] = { }
282
+
283
+ imdetails['gui'] = { 'params': { 'iteration': { }, 'automask': { } },
284
+ 'image': { },
285
+ 'image-adjust': { } }
286
+
287
+ ###
288
+ ### Only the first image should initialize the initial convergence state
289
+ ###
290
+ imdetails['gui']['cube'] = CubeMask( imdetails['path']['residual'], mask=imdetails['path']['mask'], abort=self._abort_handler,
291
+ init_script=CustomJS( args=dict( initial_convergence_state=self._init_values["convergence_state"],
292
+ name=imid ),
293
+ code='''document._casa_convergence_data = initial_convergence_state''' )
294
+ if idx == 0 else None )
295
+
296
+ ###
297
+ ### Auto Masking Parameters
298
+ ###
299
+ imdetails['params'] = { }
300
+ imdetails['params']['am'] = { }
301
+ imdetails['params']['am']['usemask'] = user_args['usemask']
302
+ imdetails['params']['am']['noisethreshold'] = user_args['noisethreshold']
303
+ imdetails['params']['am']['sidelobethreshold'] = user_args['sidelobethreshold']
304
+ imdetails['params']['am']['lownoisethreshold'] = user_args['lownoisethreshold']
305
+ imdetails['params']['am']['minbeamfrac'] = user_args['minbeamfrac']
306
+ imdetails['params']['am']['negativethreshold'] = user_args['negativethreshold']
307
+ imdetails['params']['am']['dogrowprune'] = user_args['dogrowprune']
308
+ imdetails['params']['am']['fastnoise'] = user_args['fastnoise']
309
+
310
+ def _init_pipes( self ):
311
+ if not self.__pipes_initialized:
312
+ self.__pipes_initialized = True
313
+ self._pipe['control'] = DataPipe( address=find_ws_address( ), abort=self._abort_handler )
314
+ ###
315
+ ### One pipe for updating the convergence plots.
316
+ ###
317
+ self._clean['converge'] = { 'state': None }
318
+ self._clean['converge']['pipe'] = DataPipe( address=find_ws_address( ), abort=self._abort_handler )
319
+ self._clean['converge']['id'] = str(uuid4( ))
320
+
321
+
322
+
323
+ # Get port for serving HTTP server if running in script
324
+ self._http_port = find_ws_address("")[1]
325
+ for imid, imdetails in self._clean_targets.items( ):
326
+ imdetails['gui']['cube']._init_pipes( )
327
+
328
+ def _create_convergence_gui( self, imdetails, orient='horizontal', sizing_mode='stretch_width', **kw ):
329
+ TOOLTIPS='''<div>
330
+ <div>
331
+ <span style="font-weight: bold;">@type</span>
332
+ <span>@values</span>
333
+ </div>
334
+ <div>
335
+ <span style="font-weight: bold; font-size: 10px">cycle threshold</span>
336
+ <span>@cyclethreshold</span>
337
+ </div>
338
+ <div>
339
+ <span style="font-weight: bold; font-size: 10px">stop</span>
340
+ <span>@stopDesc</span>
341
+ </div>
342
+ </div>'''
343
+
344
+ hover = HoverTool( tooltips=TOOLTIPS )
345
+ imdetails['gui']['convergence'] = figure( sizing_mode=sizing_mode, y_axis_location="right",
346
+ tools=[ hover ], toolbar_location=None, **kw )
347
+
348
+ if orient == 'vertical':
349
+ imdetails['gui']['convergence'].yaxis.axis_label='Iteration (cycle threshold dotted red)'
350
+ imdetails['gui']['convergence'].xaxis.axis_label='Peak Residual'
351
+ imdetails['gui']['convergence'].extra_x_ranges = { 'residual_range': DataRange1d( follow='end' ),
352
+ 'flux_range': DataRange1d( follow='end' ) }
353
+
354
+ imdetails['gui']['convergence'].step( 'values', 'iterations', source=imdetails['converge-data']['cyclethreshold'],
355
+ line_color='red', x_range_name='residual_range', line_dash='dotted', line_width=2 )
356
+ imdetails['gui']['convergence'].line( 'values', 'iterations', source=imdetails['converge-data']['residual'],
357
+ line_color=self._converge_color['residual'], x_range_name='residual_range' )
358
+ imdetails['gui']['convergence'].scatter( 'values', 'iterations', source=imdetails['converge-data']['residual'],
359
+ color=self._converge_color['residual'], x_range_name='residual_range',size=10 )
360
+ imdetails['gui']['convergence'].line( 'values', 'iterations', source=imdetails['converge-data']['flux'],
361
+ line_color=self._converge_color['flux'], x_range_name='flux_range' )
362
+ imdetails['gui']['convergence'].scatter( 'values', 'iterations', source=imdetails['converge-data']['flux'],
363
+ color=self._converge_color['flux'], x_range_name='flux_range', size=10 )
364
+
365
+ imdetails['gui']['convergence'].add_layout( LinearAxis( x_range_name='flux_range', axis_label='Total Flux',
366
+ axis_line_color=self._converge_color['flux'],
367
+ major_label_text_color=self._converge_color['flux'],
368
+ axis_label_text_color=self._converge_color['flux'],
369
+ major_tick_line_color=self._converge_color['flux'],
370
+ minor_tick_line_color=self._converge_color['flux'] ), 'above')
371
+
372
+ else:
373
+ imdetails['gui']['convergence'].xaxis.axis_label='Iteration (cycle threshold dotted red)'
374
+ imdetails['gui']['convergence'].yaxis.axis_label='Peak Residual'
375
+ imdetails['gui']['convergence'].extra_y_ranges = { 'residual_range': DataRange1d( follow='end' ),
376
+ 'flux_range': DataRange1d( follow='end' ) }
377
+
378
+ imdetails['gui']['convergence'].step( 'iterations', 'values', source=imdetails['converge-data']['cyclethreshold'],
379
+ line_color='red', y_range_name='residual_range', line_dash='dotted', line_width=2 )
380
+ imdetails['gui']['convergence'].line( 'iterations', 'values', source=imdetails['converge-data']['residual'],
381
+ line_color=self._converge_color['residual'], y_range_name='residual_range' )
382
+ imdetails['gui']['convergence'].scatter( 'iterations', 'values', source=imdetails['converge-data']['residual'],
383
+ color=self._converge_color['residual'], y_range_name='residual_range',size=10 )
384
+ imdetails['gui']['convergence'].line( 'iterations', 'values', source=imdetails['converge-data']['flux'],
385
+ line_color=self._converge_color['flux'], y_range_name='flux_range' )
386
+ imdetails['gui']['convergence'].scatter( 'iterations', 'values', source=imdetails['converge-data']['flux'],
387
+ color=self._converge_color['flux'], y_range_name='flux_range', size=10 )
388
+
389
+ imdetails['gui']['convergence'].add_layout( LinearAxis( y_range_name='flux_range', axis_label='Total Flux',
390
+ axis_line_color=self._converge_color['flux'],
391
+ major_label_text_color=self._converge_color['flux'],
392
+ axis_label_text_color=self._converge_color['flux'],
393
+ major_tick_line_color=self._converge_color['flux'],
394
+ minor_tick_line_color=self._converge_color['flux'] ), 'right')
395
+
396
+
397
+ def _launch_gui( self ):
398
+ '''create and show GUI
399
+ '''
400
+ ###
401
+ ### Will contain the top level GUI
402
+ ###
403
+ self._fig = { }
404
+
405
+ ###
406
+ ### Python-side handler for events from the interactive clean control buttons
407
+ ###
408
+ async def clean_handler( msg, self=self ):
409
+ if msg['action'] == 'next' or msg['action'] == 'finish':
410
+
411
+ if 'mask' in msg['value']:
412
+ ###
413
+ ### >>HERE>> breadcrumbs must be specific to the field they are related to...
414
+ ###
415
+ if 'breadcrumbs' in msg['value'] and msg['value']['breadcrumbs'] is not None and msg['value']['breadcrumbs'] != self._last_mask_breadcrumbs:
416
+ self._last_mask_breadcrumbs = msg['value']['breadcrumbs']
417
+ mask_dir = "%s.mask" % self._imagename
418
+ shutil.rmtree(mask_dir)
419
+ new_mask = imdetails['gui']['cube'].jsmask_to_raw(msg['value']['mask'])
420
+ self._mask_history.append(new_mask)
421
+
422
+ msg['value']['mask'] = convert_masks(masks=new_mask, coord='pixel', cdesc=imdetails['gui']['cube'].coorddesc())
423
+
424
+ else:
425
+ ##### seemingly the mask path used to be spliced in?
426
+ #msg['value']['mask'] = self._mask_path
427
+ pass
428
+ else:
429
+ ##### seemingly the mask path used to be spliced in?
430
+ #msg['value']['mask'] = self._mask_path
431
+ pass
432
+
433
+ ###
434
+ ### In the final implementation, there will only be one gclean object...
435
+ ###
436
+ convergence_state={ 'convergence': {}, 'cyclethreshold': {} }
437
+ err,errmsg = self._clean['gclean'].update( dict( **msg['value']['iteration'],
438
+ **msg['value']['automask'] ) )
439
+
440
+ iteration_limit = int(msg['value']['iteration']['niter'])
441
+ stopdesc, stopcode, majordone, majorleft, iterleft, self._convergence_data = await self._clean['gclean'].__anext__( )
442
+
443
+ clean_cmds = self._clean['gclean']._log( )
444
+
445
+ for key, value in self._convergence_data.items( ):
446
+
447
+ if len(value['chan']) == 0 or stopcode[0] == -1:
448
+ ### stopcode[0] == -1 indicates an error condition within gclean
449
+ return dict( result='error', stopcode=stopcode, cmd=clean_cmds,
450
+ convergence=None, majordone=majordone,
451
+ majorleft=majorleft, iterleft=iterleft, stopdesc=stopdesc )
452
+
453
+ convergence_state['convergence'][key] = value['chan']
454
+ convergence_state['cyclethreshold'][key] = value['major']['cyclethreshold']
455
+
456
+ ### stopcode[0] != 0 indicates that some stopping criteria has been reached
457
+ ### this will also catch errors as well as convergence
458
+ ### (so 'converged' isn't quite right...)
459
+ self._clean['last-success'] = dict( result='converged' if stopcode[0] else 'update', stopcode=stopcode, cmd=clean_cmds,
460
+ convergence=convergence_state['convergence'],
461
+ iterdone=iteration_limit - iterleft, iterleft=iterleft,
462
+ majordone=majordone, majorleft=majorleft, cyclethreshold=convergence_state['cyclethreshold'], stopdesc=stopdesc )
463
+ return self._clean['last-success']
464
+
465
+ elif msg['action'] == 'stop':
466
+ self.__stop( )
467
+ return dict( result='stopped', update=dict( ) )
468
+ elif msg['action'] == 'status':
469
+ return dict( result="ok", update=dict( ) )
470
+ else:
471
+ print( "got something else: '%s'" % msg['action'] )
472
+
473
+ ###
474
+ ### set up websockets which will be used for control and convergence updates
475
+ ###
476
+ self._init_pipes( )
477
+
478
+ ###
479
+ ### Setup id that will be used for messages from each button
480
+ ###
481
+ self._clean_ids = { }
482
+ for btn in "continue", 'finish', 'stop':
483
+ self._clean_ids[btn] = str(uuid4( ))
484
+ #print("%s: %s" % ( btn, self._clean_ids[btn] ) )
485
+ self._pipe['control'].register( self._clean_ids[btn], clean_handler )
486
+
487
+
488
+ ###
489
+ ### There is one set of tclean controls for all images/outlier/etc. because
490
+ ### in the final version gclean will handle the iterations for all fields...
491
+ ###
492
+ cwidth = 64
493
+ cheight = 40
494
+ self._control['iteration'] = { }
495
+ self._control['iteration']['continue'] = TipButton( max_width=cwidth, max_height=cheight, name='continue',
496
+ icon=svg_icon(icon_name="iclean-continue", size=18),
497
+ tooltip=Tooltip( content=HTML( '''Stop after <b>one major cycle</b> or when any stopping criteria is met.''' ), position='left') )
498
+ self._control['iteration']['finish'] = TipButton( max_width=cwidth, max_height=cheight, name='finish',
499
+ icon=svg_icon(icon_name="iclean-finish", size=18),
500
+ tooltip=Tooltip( content=HTML( '''<b>Continue</b> until some stopping criteria is met.''' ), position='left') )
501
+ self._control['iteration']['stop'] = TipButton( button_type="danger", max_width=cwidth, max_height=cheight, name='stop',
502
+ icon=svg_icon(icon_name="iclean-stop", size=18),
503
+ tooltip=Tooltip( content=HTML( '''<p>Clicking a <font color="red">red</font> stop button will cause this tab to close and control will return to Python.<p>Clicking an <font color="orange">orange</font> stop button will cause <tt>tclean</tt> to stop after the current major cycle.''' ), position='left' ) )
504
+
505
+ ###
506
+ ### The single SHARED help button will be supplied by the first CubeMask...
507
+ ###
508
+ help_button = None
509
+ ###
510
+ ### First status line will be reused...
511
+ ###
512
+ status_line = None
513
+
514
+ ###
515
+ ### Manage the widgets which are shared between tabs...
516
+ ###
517
+ icw = SharedWidgets( )
518
+ toolbars = [ ]
519
+ for imid, imdetails in self._clean_targets.items( ):
520
+ imdetails['gui']['stats'] = imdetails['gui']['cube'].statistics( )
521
+ imdetails['image-channels'] = imdetails['gui']['cube'].shape( )[3]
522
+
523
+ status_line = imdetails['gui']['stopcode'] = imdetails['gui']['cube'].status_text( "<p>initial residual image</p>" if imdetails['image-channels'] > 1 else "<p>initial <b>single-channel</b> residual image</p>", width=230, reuse=status_line )
524
+
525
+ ###
526
+ ### Retrieve convergence information
527
+ ###
528
+ def convergence_handler( msg, self=self, imid=imid ):
529
+ if msg['action'] == 'retrieve':
530
+ return { 'result': self._clean['last-success'] }
531
+ else:
532
+ return { 'result': None, 'error': 'unrecognized action' }
533
+
534
+ self._clean['converge']['pipe'].register( self._clean['converge']['id'], convergence_handler )
535
+
536
+ ###
537
+ ### Data source that will be used for updating the convergence plot
538
+ ###
539
+ stokes = 0
540
+ convergence = imdetails['converge']['chan'][0][stokes]
541
+ imdetails['converge-data'] = { }
542
+ imdetails['converge-data']['flux'] = ColumnDataSource( data=dict( values=convergence['modelFlux'], iterations=convergence['iterations'],
543
+ cyclethreshold=convergence['cycleThresh'],
544
+ stopDesc=list( map( ImagingDict.get_summaryminor_stopdesc, convergence['stopCode'] ) ),
545
+ type=['flux'] * len(convergence['iterations']) ) )
546
+ imdetails['converge-data']['residual'] = ColumnDataSource( data=dict( values=convergence['peakRes'], iterations=convergence['iterations'],
547
+ cyclethreshold=convergence['cycleThresh'],
548
+ stopDesc=list( map( ImagingDict.get_summaryminor_stopdesc, convergence['stopCode'] ) ),
549
+ type=['residual'] * len(convergence['iterations'])) )
550
+ imdetails['converge-data']['cyclethreshold'] = ColumnDataSource( data=dict( values=convergence['cycleThresh'], iterations=convergence['iterations'] ) )
551
+
552
+
553
+ ###
554
+ ### help page for cube interactions
555
+ ###
556
+ if help_button is None:
557
+ help_button = imdetails['gui']['cube'].help( rows=[ '<tr><td><i><b>red</b> stop button</i></td><td>clicking the stop button (when red) will close the dialog and control to python</td></tr>',
558
+ '<tr><td><i><b>orange</b> stop button</i></td><td>clicking the stop button (when orange) will return control to the GUI after the currently executing tclean run completes</td></tr>' ], position='right' )
559
+
560
+ self._create_convergence_gui( imdetails, orient='horizontal', sizing_mode='stretch_height', width=self._conv_spect_plot_width )
561
+
562
+ imdetails['gui']['params']['iteration']['nmajor'] = icw.nmajor( title='nmajor', value="%s" % self._initial_clean_params['nmajor'], width=90 )
563
+ imdetails['gui']['params']['iteration']['niter'] = icw.niter( title='niter', value="%s" % self._initial_clean_params['niter'], width=90 )
564
+ imdetails['gui']['params']['iteration']['cycleniter'] = icw.cycleniter( title="cycleniter", value="%s" % self._initial_clean_params['cycleniter'], width=90 )
565
+ imdetails['gui']['params']['iteration']['threshold'] = icw.threshold( title="threshold", value="%s" % self._initial_clean_params['threshold'], width=90 )
566
+ imdetails['gui']['params']['iteration']['cyclefactor'] = icw.cyclefactor( value="%s" % self._initial_clean_params['cyclefactor'], title="cyclefactor", width=90 )
567
+ imdetails['gui']['params']['iteration']['gain'] = icw.gain( title='gain', value="%s" % self._initial_clean_params['gain'], width=90 )
568
+ imdetails['gui']['params']['iteration']['nsigma'] = icw.nsigma( title='nsigma', value="%s" % self._initial_clean_params['nsigma'], width=90 )
569
+
570
+ if imdetails['params']['am']['usemask'] == 'auto-multithresh':
571
+ ###
572
+ ### Currently automasking tab is only available when the user selects 'auto-multithresh'
573
+ ###
574
+ imdetails['gui']['params']['automask']['active'] = True
575
+ imdetails['gui']['params']['automask']['noisethreshold'] = icw.noisethreshold( title='noisethreshold', value="%s" % imdetails['params']['am']['noisethreshold'], margin=( 5, 25, 5, 5 ), width=90 )
576
+ imdetails['gui']['params']['automask']['sidelobethreshold'] = icw.sidelobethreshold( title='sidelobethreshold', value="%s" % imdetails['params']['am']['sidelobethreshold'], margin=( 5, 25, 5, 5 ), width=90 )
577
+ imdetails['gui']['params']['automask']['lownoisethreshold'] = icw.lownoisethreshold( title='lownoisethreshold', value="%s" % imdetails['params']['am']['lownoisethreshold'], margin=( 5, 25, 5, 5 ), width=90 )
578
+ imdetails['gui']['params']['automask']['minbeamfrac'] = icw.minbeamfrac( title='minbeamfrac', value="%s" % imdetails['params']['am']['minbeamfrac'], width=90 )
579
+ imdetails['gui']['params']['automask']['negativethreshold'] = icw.negativethreshold( title='negativethreshold', value="%s" % imdetails['params']['am']['negativethreshold'], margin=( 5, 25, 5, 5 ), width=90 )
580
+ imdetails['gui']['params']['automask']['dogrowprune'] = icw.dogrowprune( label='dogrowprune', active=imdetails['params']['am']['dogrowprune'], margin=( 15, 25, 5, 5 ) )
581
+ imdetails['gui']['params']['automask']['fastnoise'] = icw.fastnoise( label='fastnoise', active=imdetails['params']['am']['fastnoise'], margin=( 15, 25, 5, 5 ) )
582
+
583
+
584
+ imdetails['gui']['image']['src'] = imdetails['gui']['cube'].js_obj( )
585
+ imdetails['gui']['image']['fig'] = imdetails['gui']['cube'].image( grid=False, height_policy='max', width_policy='max',
586
+ channelcb=CustomJS( args=dict( img_state={ 'src': imdetails['gui']['image']['src'],
587
+ 'flux': imdetails['converge-data']['flux'],
588
+ 'residual': imdetails['converge-data']['residual'],
589
+ 'cyclethreshold': imdetails['converge-data']['cyclethreshold'] },
590
+ imid=imid,
591
+ ctrl={ 'converge': self._clean['converge'] },
592
+ stopdescmap=ImagingDict.get_summaryminor_stopdesc( ) ),
593
+ code=self._js['update-converge'] +
594
+ '''update_convergence_single( img_state, document._casa_convergence_data.convergence[imid] )''' ) )
595
+
596
+ ###
597
+ ### collect toolbars for syncing selection
598
+ ###
599
+ toolbars.append(imdetails['gui']['image']['fig'].toolbar)
600
+
601
+ ###
602
+ ### spectrum plot must be disabled during iteration due to "tap to change channel" functionality
603
+ ###
604
+ if imdetails['image-channels'] > 1:
605
+ imdetails['gui']['spectrum'] = imdetails['gui']['cube'].spectrum( orient='vertical', sizing_mode='stretch_height', width=self._conv_spect_plot_width )
606
+ imdetails['gui']['slider'] = imdetails['gui']['cube'].slider( show_value=False, title='', margin=(14,5,5,5), sizing_mode="scale_width" )
607
+ imdetails['gui']['goto'] = imdetails['gui']['cube'].goto( )
608
+ else:
609
+ imdetails['gui']['spectrum'] = None
610
+ imdetails['gui']['slider'] = None
611
+ imdetails['gui']['goto'] = None
612
+
613
+ imdetails['gui']['channel-ctrl'] = imdetails['gui']['cube'].channel_ctrl( )
614
+
615
+ imdetails['gui']['cursor-pixel-text'] = imdetails['gui']['cube'].pixel_tracking_text( margin=(-3, 5, 3, 30) )
616
+
617
+ self._image_bitmask_controls = imdetails['gui']['cube'].bitmask_ctrl( reuse=self._image_bitmask_controls, button_type='light' )
618
+
619
+ if imdetails['params']['am']['usemask'] == 'auto-multithresh':
620
+ imdetails['gui']['auto-masking-panel'] = [ TabPanel( child=column( row( Tip( imdetails['gui']['params']['automask']['noisethreshold'],
621
+ tooltip=Tooltip( content=HTML( 'sets the signal-to-noise threshold above which significant emission is masked during the initial round of mask creation' ),
622
+ position='bottom' ) ),
623
+ Tip( imdetails['gui']['params']['automask']['sidelobethreshold'],
624
+ tooltip=Tooltip( content=HTML( 'sets a threshold based on the sidelobe level above which significant emission is masked during the initial round of mask creation' ),
625
+ position='bottom' ) ),
626
+ Tip( imdetails['gui']['params']['automask']['minbeamfrac'],
627
+ tooltip=Tooltip( content=HTML( 'sets the minimum size a region must be to be retained in the mask' ),
628
+ position='bottom' ) ) ),
629
+ row( Tip( imdetails['gui']['params']['automask']['lownoisethreshold'],
630
+ tooltip=Tooltip( content=HTML( 'sets the threshold into which the initial mask (which is determined by either noisethreshold or sidelobethreshold) is expanded in order to include low signal-to-noise regions in the mask' ),
631
+ position='bottom' ) ),
632
+ Tip( imdetails['gui']['params']['automask']['negativethreshold'],
633
+ tooltip=Tooltip( content=HTML( 'sets the signal-to-noise threshold for absorption features to be masked' ),
634
+ position='bottom' ) ) ),
635
+ row( Tip( imdetails['gui']['params']['automask']['dogrowprune'],
636
+ tooltip=Tooltip( content=HTML( 'allows you to turn off the pruning of the low signal-to-noise mask, which speeds up masking for images and cubes with complex low signal-to-noise emission' ),
637
+ position='bottom' ) ),
638
+ Tip( imdetails['gui']['params']['automask']['fastnoise'],
639
+ tooltip=Tooltip( content=HTML( 'When set to True, a simpler but faster noise calucation is used' ),
640
+ position='bottom' ) ) ) ),
641
+ title='Automask' ) ]
642
+ else:
643
+ imdetails['gui']['auto-masking-panel'] = [ ]
644
+
645
+
646
+ ###
647
+ ### synchronize toolbar selections among figures
648
+ ###
649
+ if toolbars:
650
+ for tb in toolbars:
651
+ tb.js_on_change( 'active_changed',
652
+ ###
653
+ ### toolbars must filter out 'tb' to avoid circular references
654
+ ###
655
+ CustomJS( args=dict(toolbars=[t for t in toolbars if t.id != tb.id]),
656
+ code='''casalib.map( (gest,tool) => {
657
+ if ( tool.active ) {
658
+ // a tool which belongs to the toolbar that signaled a change
659
+ // is active for this gesture...
660
+ toolbars.forEach( (other_tb) => {
661
+ let new_active = other_tb.gestures[gest].tools.find(
662
+ (t) => t.name == tool.active.name )
663
+ if ( ! other_tb.gestures[gest].active ) {
664
+ if ( new_active ) {
665
+ other_tb.gestures[gest].active = new_active
666
+ new_active.active = true
667
+ }
668
+ } else if ( other_tb.gestures[gest].active.name != tool.active.name ) {
669
+ if ( new_active ) {
670
+ other_tb.gestures[gest].active.active = false
671
+ new_active.active = true
672
+ other_tb.gestures[gest].active = new_active
673
+ }
674
+ }
675
+ } )
676
+ } else {
677
+ // a tool which belongs to the toolbar that signaled a change
678
+ // is NOT active for this gesture...
679
+ toolbars.forEach( (other_tb) => {
680
+ if ( other_tb.gestures[gest] && other_tb.gestures[gest].active ) {
681
+ other_tb.gestures[gest].active.active = false
682
+ other_tb.gestures[gest].active = null
683
+ }
684
+ } )
685
+ }
686
+ }, cb_obj.gestures )''' ) )
687
+
688
+ ###
689
+ ### button to display the tclean log -- in the final implmentation, outliers and other multifield imaging should be handled by gclean
690
+ ###
691
+ self._log_button = TipButton( max_width=help_button.width, max_height=help_button.height, name='log',
692
+ icon=svg_icon(icon_name="bp-application-sm", size=25),
693
+ tooltip=Tooltip( content=HTML('''click here to see the <pre>tclean</pre> execution log'''), position="right" ),
694
+ margin=(-1, 0, -10, 0), button_type='light',
695
+ stylesheets=[ InlineStyleSheet( css='''.bk-btn { border: 0px solid #ccc; padding: 0 var(--padding-vertical) var(--padding-horizontal); margin-top: 3px; }''' ) ] )
696
+
697
+ self._control['iteration']['cb'] = CustomJS( args=dict( images_state={ k: { 'status': v['gui']['stopcode'],
698
+ 'automask': v['gui']['params']['automask'],
699
+ 'iteration': v['gui']['params']['iteration'],
700
+ 'img': v['gui']['image']['fig'],
701
+ 'src': v['gui']['cube'].js_obj( ),
702
+ 'spectrum': v['gui']['spectrum'],
703
+ 'src': v['gui']['image']['src'],
704
+ 'flux': v['converge-data']['flux'],
705
+ 'cyclethreshold': v['converge-data']['cyclethreshold'],
706
+ 'residual': v['converge-data']['residual'],
707
+ 'navi': { 'slider': v['gui']['slider'],
708
+ 'goto': v['gui']['goto'],
709
+ ## it doesn't seem like pixel tracking must be disabled
710
+ ##'tracking': v['gui']['cursor-pixel-text'],
711
+ 'stokes': v['gui']['channel-ctrl'][1] } }
712
+ for k,v in self._clean_targets.items( ) },
713
+ ctrl={ 'converge': self._clean['converge'] },
714
+ clean_ctrl=self._control['iteration'],
715
+ state=dict( mode='interactive', stopped=False, awaiting_stop=False, mask="" ),
716
+ ctrl_pipe=self._pipe['control'],
717
+ ids=self._clean_ids,
718
+ logbutton=self._log_button,
719
+ stopdescmap=ImagingDict.get_summaryminor_stopdesc( )
720
+ ),
721
+ code=self._js['update-converge'] + self._js['clean-refresh'] + self._js['clean-disable'] +
722
+ self._js['clean-enable'] + self._js['clean-status-update'] +
723
+ self._js['iter-gui-update'] + self._js['clean-wait'] +
724
+ '''function invalid_niter( s ) {
725
+ let v = parseInt( s )
726
+ if ( v > 0 ) return ''
727
+ if ( v == 0 ) return 'niter is zero'
728
+ if ( v < 0 ) return 'niter cannot be negative'
729
+ if ( isNaN(v) ) return 'niter must be an integer'
730
+ }
731
+ const itobj = Object.entries(images_state)[0][1].iteration
732
+ if ( ! state.stopped && cb_obj.origin.name == 'finish' ) {
733
+ let invalid = invalid_niter(itobj.niter.value)
734
+ if ( invalid ) update_status( invalid )
735
+ else {
736
+ state.mode = 'continuous'
737
+ update_status( 'Running multiple iterations' )
738
+ disable( false )
739
+ clean_ctrl.stop.button_type = "warning"
740
+ const thevalue = get_update_dictionary( )
741
+ ctrl_pipe.send( ids[cb_obj.origin.name],
742
+ { action: 'finish',
743
+ value: thevalue },
744
+ update_gui )
745
+ }
746
+ }
747
+ if ( ! state.stopped && state.mode === 'interactive' &&
748
+ cb_obj.origin.name === 'continue' ) {
749
+ let invalid = invalid_niter(itobj.niter.value)
750
+ if ( invalid ) update_status( invalid )
751
+ else {
752
+ update_status( 'Running one set of deconvolution iterations' )
753
+ disable( true )
754
+ // only send message for button that was pressed
755
+ // it's unclear whether 'this.origin.' or 'cb_obj.origin.' should be used
756
+ // (or even if 'XXX.origin.' is public)...
757
+ ctrl_pipe.send( ids[cb_obj.origin.name],
758
+ { action: 'next',
759
+ value: get_update_dictionary( ) },
760
+ update_gui )
761
+ }
762
+ }
763
+ if ( state.mode === 'interactive' && cb_obj.origin.name === 'stop' ) {
764
+ if ( confirm( "Are you sure you want to end this interactive clean session and close the GUI?" ) ) {
765
+ disable( true )
766
+ //ctrl_pipe.send( ids[cb_obj.origin.name],
767
+ // { action: 'stop',
768
+ // value: { } },
769
+ // update_gui )
770
+ document._casa_window_closed = true
771
+ /*** this will close the tab >>>>---------+ ***/
772
+ /*** | ***/
773
+ /*** vvvvv----------------------------+ ***/
774
+ document._cube_done( Object.entries(images_state).reduce((acc,[k,v]) => ({ ...acc, [k]: v.src.masks( ) }),{ } ) )
775
+ }
776
+ } else if ( state.mode === 'continuous' &&
777
+ cb_obj.origin.name === 'stop' &&
778
+ ! state.awaiting_stop ) {
779
+ disable( true )
780
+ state.awaiting_stop = true
781
+ ctrl_pipe.send( ids[cb_obj.origin.name],
782
+ { action: 'status',
783
+ value: { } },
784
+ wait_for_tclean_stop )
785
+ }''' )
786
+
787
+
788
+ self._control['iteration']['continue'].js_on_click( self._control['iteration']['cb'] )
789
+ self._control['iteration']['finish'].js_on_click( self._control['iteration']['cb'] )
790
+ self._control['iteration']['stop'].js_on_click( self._control['iteration']['cb'] )
791
+
792
+ self._log_button.js_on_click( CustomJS( args=dict( logbutton=self._log_button ),
793
+ code='''function format_log( elem ) {
794
+ return `<html>
795
+ <head>
796
+ <style type="text/css">
797
+ body {
798
+ counter-reset: section;
799
+ }
800
+ p:not([no-num]):before {
801
+ font-weight: bold;
802
+ counter-increment: section;
803
+ content: "" counter(section) ": ";
804
+ }
805
+ </style>
806
+ </head>
807
+ <body>
808
+ <h1>Interactive Clean History</h1>
809
+ ` + elem.map((x) => x.startsWith('#') ? `<p no-num>${x}</p>` : `<p>${x}</p>`).join('\\n') + '</body>\\n</html>'
810
+ }
811
+ let b = cb_obj.origin
812
+ if ( ! b._window || b._window.closed ) {
813
+ b._window = window.open("about:blank","Interactive Clean Log")
814
+ b._window.document.write(format_log(b._log))
815
+ b._window.document.close( )
816
+ }''' ) )
817
+
818
+ ###
819
+ ### Setup script that will be called when the user closes the
820
+ ### browser tab that is running interactive clean
821
+ ###
822
+ initial_log = self._clean['gclean']._log( )
823
+
824
+ self._pipe['control'].init_script=CustomJS( args=dict( ctrl_pipe=self._pipe['control'],
825
+ ids=self._clean_ids,
826
+ logbutton=self._log_button,
827
+ log=initial_log,
828
+ initial_image=list(self._clean_targets.items( ))[0][0]
829
+ ),
830
+ code=self._js['initialize'] +
831
+ '''if ( ! logbutton._log ) {
832
+ /*** store log list with log button for access in other callbacks ***/
833
+ logbutton._log = log
834
+ }''' )
835
+
836
+ tab_panels = list( map( self._create_image_panel, self._clean_targets.items( ) ) )
837
+
838
+ for imid, imdetails in self._clean_targets.items( ):
839
+ imdetails['gui']['cube'].connect( )
840
+
841
+ image_tabs = Tabs( tabs=tab_panels, tabs_location='below', height_policy='max', width_policy='max' )
842
+
843
+ self._fig['layout'] = column(
844
+ row( help_button,
845
+ self._log_button,
846
+ Spacer( height=self._control['iteration']['stop'].height, sizing_mode="scale_width" ),
847
+ Div( text="<div><b>status:</b></div>" ),
848
+ status_line,
849
+ self._control['iteration']['stop'], self._control['iteration']['continue'], self._control['iteration']['finish'], sizing_mode="scale_width" ),
850
+ row( image_tabs, height_policy='max', width_policy='max' ),
851
+ height_policy='max', width_policy='max' )
852
+
853
+ ###
854
+ ### Keep track of which image is currently active in document._casa_image_name (which is
855
+ ### initialized in self._js['initialize']). Also, update the current control sub-tab
856
+ ### when the field main-tab is changed. An attempt to manage this all within the
857
+ ### control sub-tabs using a reference to self._image_control_tab_groups from
858
+ ### each control sub-tab failed with:
859
+ ###
860
+ ### bokeh.core.serialization.SerializationError: circular reference
861
+ ###
862
+ image_tabs.js_on_change( 'active', CustomJS( args=dict( names=[ t[0] for t in self._clean_targets.items( ) ],
863
+ itergroups=self._image_control_tab_groups ),
864
+ code='''if ( ! hasprop(document,'_casa_last_control_tab') ) {
865
+ document._casa_last_control_tab = 0
866
+ }
867
+ document._casa_image_name = names[cb_obj.active]
868
+ itergroups[document._casa_image_name].active = document._casa_last_control_tab''' ) )
869
+
870
+ # Change display type depending on runtime environment
871
+ if self._is_notebook:
872
+ output_notebook()
873
+ else:
874
+ ### Directory is created when an HTTP server is running
875
+ ### (MAX)
876
+ ### output_file(self._imagename+'_webpage/index.html')
877
+ pass
878
+
879
+ show(self._fig['layout'])
880
+
881
+ def _create_colormap_adjust( self, imdetails ):
882
+ palette = imdetails['gui']['cube'].palette( reuse=self._cube_palette )
883
+ return column( row( Div(text="<div><b>Colormap:</b></div>",margin=(5,2,5,25)), palette ),
884
+ imdetails['gui']['cube'].colormap_adjust( ), sizing_mode='stretch_both' )
885
+
886
+
887
+ def _create_control_image_tab( self, imid, imdetails ):
888
+ result = Tabs( tabs=[ TabPanel(child=column( row( Tip( imdetails['gui']['params']['iteration']['nmajor'],
889
+ tooltip=Tooltip( content=HTML( 'maximum number of major cycles to run before stopping'),
890
+ position='bottom' ) ),
891
+ Tip( imdetails['gui']['params']['iteration']['niter'],
892
+ tooltip=Tooltip( content=HTML( 'number of clean iterations to run' ),
893
+ position='bottom' ) ),
894
+ Tip( imdetails['gui']['params']['iteration']['threshold'],
895
+ tooltip=Tooltip( content=HTML( 'stopping threshold' ),
896
+ position='bottom' ) ) ),
897
+ row( Tip( imdetails['gui']['params']['iteration']['nsigma'],
898
+ tooltip=Tooltip( content=HTML( 'multiplicative factor for rms-based threshold stopping'),
899
+ position='bottom' ) ),
900
+ Tip( imdetails['gui']['params']['iteration']['gain'],
901
+ tooltip=Tooltip( content=HTML( 'fraction of the source flux to subtract out of the residual image'),
902
+ position='bottom' ) ) ),
903
+ row( Tip( imdetails['gui']['params']['iteration']['cycleniter'],
904
+ tooltip=Tooltip( content=HTML( 'maximum number of <b>minor-cycle</b> iterations' ),
905
+ position='bottom' ) ),
906
+ Tip( imdetails['gui']['params']['iteration']['cyclefactor'],
907
+ tooltip=Tooltip( content=HTML( 'scaling on PSF sidelobe level to compute the minor-cycle stopping threshold' ),
908
+ position='bottom_left' ) ), background="lightgray" ),
909
+ imdetails['gui']['convergence'], sizing_mode='stretch_height' ),
910
+ title='Iteration' ) ] +
911
+ ( [ TabPanel( child=imdetails['gui']['spectrum'],
912
+ title='Spectrum' ) ] if imdetails['image-channels'] > 1 else [ ] ) +
913
+ [ TabPanel( child=self._create_colormap_adjust(imdetails),
914
+ title='Colormap' ),
915
+ TabPanel( child=column( *imdetails['gui']['stats'] ),
916
+ title='Statistics' ) ] + imdetails['gui']['auto-masking-panel'],
917
+ width=500, sizing_mode='stretch_height', tabs_location='below' )
918
+
919
+ if not hasattr(self,'_image_control_tab_groups'):
920
+ self._image_control_tab_groups = { }
921
+
922
+ self._image_control_tab_groups[imid] = result
923
+ result.js_on_change( 'active', CustomJS( args=dict( ),
924
+ code='''document._casa_last_control_tab = cb_obj.active''' ) )
925
+ return result
926
+
927
+ def _create_image_panel( self, imagetuple ):
928
+ imid, imdetails = imagetuple
929
+
930
+
931
+
932
+ return TabPanel( child=column( row( *imdetails['gui']['channel-ctrl'], imdetails['gui']['cube'].coord_ctrl( ),
933
+ *self._image_bitmask_controls,
934
+ #Spacer( height=5, height_policy="fixed", sizing_mode="scale_width" ),
935
+ imdetails['gui']['cursor-pixel-text'],
936
+ row( Spacer( sizing_mode='stretch_width' ),
937
+ imdetails['gui']['cube'].tapedeck( size='20px' ) if imdetails['image-channels'] > 1 else Div( ),
938
+ Spacer( height=5, width=350 ), width_policy='max' ),
939
+ width_policy='max' ),
940
+ row( imdetails['gui']['image']['fig'],
941
+ column( row( imdetails['gui']['goto'],
942
+ imdetails['gui']['slider'],
943
+ width_policy='max' ) if imdetails['image-channels'] > 1 else Div( ),
944
+ self._create_control_image_tab(imid, imdetails), height_policy='max' ),
945
+ height_policy='max', width_policy='max' ),
946
+ height_policy='max', width_policy='max' ), title=imid )
947
+
948
+ def __call__( self, setting, exec_context, id=None ):
949
+ '''Display GUI and process events until the user stops the application.
950
+
951
+ Example:
952
+ Create ``iclean`` object and display::
953
+
954
+ print( "Result: %s" %
955
+ iclean( vis='refim_point_withline.ms', imagename='test', imsize=512,
956
+ cell='12.0arcsec', specmode='cube',
957
+ interpolation='nearest', ... )( ) )
958
+ '''
959
+
960
+ self._setup()
961
+
962
+ # If Interactive Clean is being run remotely, print helper info for port tunneling
963
+ if self._is_remote:
964
+ # Tunnel ports for Jupyter kernel connection
965
+ print("\nImportant: Copy the following line and run in your local terminal to establish port forwarding.\
966
+ You may need to change the last argument to align with your ssh config.\n")
967
+ print(self._gen_port_fwd_cmd())
968
+
969
+ # TODO: Include?
970
+ # VSCode will auto-forward ports that appear in well-formatted addresses.
971
+ # Printing this line will cause VSCode to autoforward the ports
972
+ # print("Cmd: " + str(repr(self.auto_fwd_ports_vscode())))
973
+ input("\nPress enter when port forwarding is setup...")
974
+
975
+ ###
976
+ ### cubevis.exe subpkg supports adding a stop condition to allow for interrupt,
977
+ ### but it is not needed for synchronous execution
978
+ ###
979
+ self._exec = { 'stop-condition': None }
980
+ #self._exec['stop-condition'], self._exec['id'] = exec_context.create_stop_condition(id)
981
+
982
+ return exe.Task( self._task_server )
983
+ # , stop_condition=self._exec['stop-condition'] )
984
+
985
+ async def _task_server( self ):
986
+ """Wrapper for your serve() context manager"""
987
+
988
+ @asynccontextmanager
989
+ async def serve_func( ):
990
+ '''This function is intended for developers who would like to embed interactive
991
+ clean as a part of a larger GUI. This embedded use of interactive clean is not
992
+ currently supported and would require the addition of parameters to this function
993
+ as well as changes to the interactive clean implementation. However, this function
994
+ does expose the ``asyncio.Future`` that is used to signal completion of the
995
+ interactive cleaning operation, and it provides the coroutines which must be
996
+ managed by asyncio to make the interactive clean GUI responsive.
997
+
998
+ Example:
999
+ Create ``iclean`` object, process events and retrieve result::
1000
+
1001
+ ic = iclean( vis='refim_point_withline.ms', imagename='test', imsize=512,
1002
+ cell='12.0arcsec', specmode='cube', interpolation='nearest', ... )
1003
+ async def process_events( ):
1004
+ async with ic.serve( ) as state:
1005
+ await state[0]
1006
+
1007
+ asyncio.run(process_events( ))
1008
+ print( "Result:", ic.result( ) )
1009
+
1010
+ Returns
1011
+ -------
1012
+ (asyncio.Future, dictionary of coroutines)
1013
+ '''
1014
+ def start_http_server():
1015
+ import http.server
1016
+ import socketserver
1017
+ PORT = self._http_port
1018
+ DIRECTORY=self._webpage_path
1019
+
1020
+ class Handler(http.server.SimpleHTTPRequestHandler):
1021
+ def __init__(self, *args, **kwargs):
1022
+ super().__init__(*args, directory=DIRECTORY, **kwargs)
1023
+
1024
+ with socketserver.TCPServer(("", PORT), Handler) as httpd:
1025
+ print("\nServing Interactive Clean webpage from local directory: ", DIRECTORY)
1026
+ print("Use Control-C to stop Interactive clean.\n")
1027
+ print("Copy and paste one of the below URLs into your browser (Chrome or Firefox) to view:")
1028
+ print("http://localhost:"+str(PORT))
1029
+ print("http://127.0.0.1:"+str(PORT))
1030
+
1031
+ httpd.serve_forever()
1032
+
1033
+ self._launch_gui( )
1034
+
1035
+ async with CMC( *( [ ctx for img in self._clean_targets.keys( ) for ctx in
1036
+ [
1037
+ self._clean_targets[img]['gui']['cube'].serve(self.__stop),
1038
+ ]
1039
+ ] + [ websockets.serve( self._pipe['control'].process_messages,
1040
+ self._pipe['control'].address[0],
1041
+ self._pipe['control'].address[1] ),
1042
+ websockets.serve( self._clean['converge']['pipe'].process_messages,
1043
+ self._clean['converge']['pipe'].address[0],
1044
+ self._clean['converge']['pipe'].address[1] ) ]
1045
+ ) ):
1046
+ self.__result_future = asyncio.Future( )
1047
+ yield self.__result_future
1048
+
1049
+ async with serve_func( ) as result_future:
1050
+ if self._exec['stop-condition'] is None:
1051
+ await result_future
1052
+ return self.result( )
1053
+ else:
1054
+ raise RuntimeError( 'internal error: no stop condition expected' )
1055
+
1056
+ ###
1057
+ ### If stop conditions were used, a mechanism to check the stop
1058
+ ### condition would be required...
1059
+ ###
1060
+ #if isinstance(self._exec['stop-condition'], asyncio.Event):
1061
+ # done, pending = await asyncio.wait(
1062
+ # [ result_future, asyncio.create_task(stop_condition.wait()) ],
1063
+ # return_when=asyncio.FIRST_COMPLETED
1064
+ # )
1065
+ # # Cancel pending tasks
1066
+ # for task in pending:
1067
+ # task.cancel()
1068
+ # try:
1069
+ # await task
1070
+ # except asyncio.CancelledError:
1071
+ # pass
1072
+ #
1073
+ # if result_future in done:
1074
+ # return result_future.result()
1075
+ # else:
1076
+ # return "Stopped by signal"
1077
+ #else:
1078
+ # raise RuntimeError( f"unexpected stop condition type: {type(self._exec['stop-condition'])}" )
1079
+
1080
+ def _setup( self ):
1081
+ self.__reset( )
1082
+
1083
+ def initialize_tclean( gclean ):
1084
+
1085
+ stopdesc, stopcode, majordone, majorleft, iterleft, all_converge = next(gclean)
1086
+
1087
+ for imid, converge in all_converge.items( ):
1088
+ #######################################################################################################
1089
+ ### gclean seems to return its internal state making it succeptable to modification... so we'll at ###
1090
+ ### least start out with unique dictionaries. ###
1091
+ #######################################################################################################
1092
+ converge = copy.deepcopy(converge)
1093
+
1094
+ imdetails = self._clean_targets[imid]
1095
+ imdetails['converge'] = converge
1096
+
1097
+ if imdetails['converge'] is None or len(imdetails['converge'].keys()) == 0 or \
1098
+ imdetails['converge']['major'] is None or imdetails['converge']['chan'] is None:
1099
+ ###
1100
+ ### gclean should provide argument checking (https://github.com/casangi/casagui/issues/33)
1101
+ ### but currently gclean can be initialized with bad arguments and it is not known until
1102
+ ### the initial calls to tclean/deconvolve
1103
+ ###
1104
+ raise RuntimeError(f'''gclean failure "%s" not returned: {imdetails["converge"]}''' % ('major' if imdetails['converge']['major'] is None else 'chan'))
1105
+
1106
+ self._clean['cmds'].extend(self._clean['gclean']._log( ))
1107
+
1108
+ self._initial_clean_params['nmajor'] = majorleft
1109
+ self._initial_clean_params['niter'] = iterleft
1110
+ self._initial_clean_params['cycleniter'] = self._init_values["cycleniter"]
1111
+ self._initial_clean_params['threshold'] = self._init_values["threshold"]
1112
+ self._initial_clean_params['cyclefactor'] = self._init_values["cyclefactor"]
1113
+ self._initial_clean_params['gain'] = self._init_values["gain"]
1114
+ self._initial_clean_params['nsigma'] = self._init_values["nsigma"]
1115
+
1116
+ self._init_values["convergence_state"]['convergence'][imid] = imdetails['converge']['chan']
1117
+ self._init_values["convergence_state"]['cyclethreshold'][imid] = imdetails['converge']['major']['cyclethreshold']
1118
+
1119
+ return (stopdesc, stopcode, majordone, majorleft, iterleft)
1120
+
1121
+
1122
+ self._clean['cmds'] = []
1123
+
1124
+ stopdesc, stopcode, majordone, majorleft, iterleft = initialize_tclean(self._clean['gclean'])
1125
+
1126
+
1127
+ self._clean['last-success'] = dict( result='converged' if stopcode[0] else 'update', stopcode=stopcode, cmd=self._clean['cmds'],
1128
+ convergence=self._init_values["convergence_state"]['convergence'],
1129
+ iterdone=0, iterleft=iterleft,
1130
+ majordone=majordone, majorleft=majorleft,
1131
+ cyclethreshold=self._init_values["convergence_state"]['cyclethreshold'],
1132
+ stopdesc=stopdesc )
1133
+
1134
+ ### Must occur AFTER initial "next" call to gclean(s)
1135
+ self._init_pipes()
1136
+
1137
+ def __retrieve_result( self ):
1138
+ '''If InteractiveCleanUI had a return value, it would be filled in as part of the
1139
+ GUI dialog between Python and JavaScript and this function would return it'''
1140
+ if isinstance(self._error_result,Exception):
1141
+ raise self._error_result
1142
+ elif self._error_result is not None:
1143
+ return self._error_result
1144
+ return { k: v['converge'] for k,v in self._clean_targets.items( ) }
1145
+
1146
+ def result( self ):
1147
+ '''If InteractiveCleanUI had a return value, it would be filled in as part of the
1148
+ GUI dialog between Python and JavaScript and this function would return it'''
1149
+ if self.__result_future is None:
1150
+ raise RuntimeError( 'no interactive clean result is available' )
1151
+
1152
+ if self.__result is None:
1153
+ ### restore returns full return dictionary
1154
+ self.__result_from_gui = self.__result_future.result( )
1155
+ self.__result = self._clean['gclean'].restore( )
1156
+
1157
+ return self.__result
1158
+
1159
+ def masks( self ):
1160
+ '''Retrieves the masks which were used with interactive clean.
1161
+
1162
+ Returns
1163
+ -------
1164
+ The standard ``cubevis`` cube region dictionary which contains two elements
1165
+ ``masks`` and ``polys``.
1166
+
1167
+ The value of the ``masks`` element is a dictionary that is indexed by
1168
+ tuples of ``(stokes,chan)`` and the value of each element is a list
1169
+ whose elements describe the polygons drawn on the channel represented
1170
+ by ``(stokes,chan)``. Each polygon description in this list has a
1171
+ polygon index (``p``) and a x/y translation (``d``).
1172
+
1173
+ The value of the ``polys`` element is a dictionary that is indexed by
1174
+ polygon indexes. The value of each polygon index is a dictionary containing
1175
+ ``type`` (whose value is either ``'rect'`` or ``'poly``) and ``geometry``
1176
+ (whose value is a dictionary containing ``'xs'`` and ``'ys'`` (which are
1177
+ the x and y coordinates that define the polygon).
1178
+
1179
+ This can be converted to other formats with ``cubevis.utils.convert_masks``.
1180
+ '''
1181
+ return copy.deepcopy(self._mask_history) ## don't allow users to change history
1182
+
1183
+ def history( self ):
1184
+ '''Retrieves the commands used during the interactive clean session.
1185
+
1186
+ Returns
1187
+ -------
1188
+ list[str] tclean calls made during the interactive clean session.
1189
+ '''
1190
+ return self._clean['gclean']._log( True )
1191
+
1192
+ def _initialize_javascript( self ):
1193
+ self._js = { ### initialize state
1194
+ ### --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
1195
+ ### -- document is used storing state --
1196
+ ### --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
1197
+ 'initialize': '''if ( ! document._casa_initialized ) {
1198
+ document._casa_image_name = initial_image
1199
+ document._casa_initialized = true
1200
+ document._casa_window_closed = false
1201
+ window.addEventListener( 'beforeunload',
1202
+ function (e) {
1203
+ // if the window is already closed this message is never
1204
+ // delivered (unless interactive clean is called again then
1205
+ // the event shows up in the newly created control pipe
1206
+ if ( document._casa_window_closed == false ) {
1207
+ ctrl_pipe.send( ids['stop'],
1208
+ { action: 'stop', value: { } },
1209
+ undefined ) } } )
1210
+ }''',
1211
+
1212
+ ### --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
1213
+ ### -- flux_src._convergence_data is used to store the complete --
1214
+ ### -- --
1215
+ ### -- The "Insert here ..." code seems to be called when when the stokes plane is changed --
1216
+ ### -- but there have been no tclean iterations yet... --
1217
+ ### --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
1218
+ 'update-converge': '''function update_convergence_single( target, data ) {
1219
+ const pos = target.src.cur_chan
1220
+ const imdata = data.get(pos[1]).get(pos[0])
1221
+ // chan----------------^^^^^^ ^^^^^^----stokes
1222
+ const iterations = imdata.iterations
1223
+ const peakRes = imdata.peakRes
1224
+ const cyclethreshold = imdata.cycleThresh
1225
+ const modelFlux = imdata.modelFlux
1226
+ const stopCode = imdata.stopCode
1227
+ const stopDesc = imdata.stopCode.map( code => stopdescmap.has(code) ? stopdescmap.get(code): "" )
1228
+ target.residual.data = { iterations, cyclethreshold, stopDesc, values: peakRes, type: Array(iterations.length).fill('residual') }
1229
+ target.flux.data = { iterations, cyclethreshold, stopDesc, values: modelFlux, type: Array(iterations.length).fill('flux') }
1230
+ target.cyclethreshold.data = { iterations, values: cyclethreshold }
1231
+ }
1232
+
1233
+ function update_convergence( recurse=false ) {
1234
+ let convdata
1235
+ if ( hasprop(document,'_casa_convergence_data') ) {
1236
+ convdata = document._casa_convergence_data
1237
+ } else {
1238
+ if ( ! recurse ) {
1239
+ ctrl.converge.pipe.send( ctrl.converge.id, { action: 'retrieve' },
1240
+ (msg) => { if ( hasprop( msg.result, 'convergence' ) ) {
1241
+ document._casa_convergence_data = { convergence: msg.result.convergence,
1242
+ cyclethreshold: msg.result.cyclethreshold }
1243
+ update_convergence(true)
1244
+ } } )
1245
+ } else { console.log( 'INTERNAL ERROR: fetching convergence data failed' ) }
1246
+ return
1247
+ }
1248
+
1249
+ Object.entries(images_state).map(
1250
+ ([k,v],i) => { update_convergence_single(v,convdata.convergence[k]) } )
1251
+ }''',
1252
+
1253
+ 'clean-refresh': '''function refresh( clean_msg ) {
1254
+ const itobj = Object.entries(images_state)[0][1].iteration
1255
+ let stokes = 0 // later we will receive the polarity
1256
+ // from some widget mechanism...
1257
+ if ( clean_msg !== undefined ) {
1258
+ if ( 'iterleft' in clean_msg ) {
1259
+ itobj.niter.value = '' + clean_msg['iterleft']
1260
+ } else if ( clean_msg !== undefined && 'iterdone' in clean_msg ) {
1261
+ const remaining = parseInt(itobj.niter.value) - parseInt(clean_msg['iterdone'])
1262
+ itobj.niter.value = '' + (remaining < 0 ? 0 : remaining)
1263
+ }
1264
+
1265
+ if ( 'majorleft' in clean_msg ) {
1266
+ itobj.nmajor.value = '' + clean_msg['majorleft']
1267
+ } else if ( 'majordone' in clean_msg ) {
1268
+ const nm = parseInt(itobj.nmajor.value)
1269
+ if ( nm != -1 ) {
1270
+ const remaining = nm - parseInt(clean_msg['majordone'])
1271
+ itobj.nmajor.value = '' + (remaining < 0 ? 0 : remaining)
1272
+ } else itobj.nmajor.value = '' + nm // nmajor == -1 implies do not consider nmajor in stop decision
1273
+ }
1274
+
1275
+ if ( hasprop(clean_msg,'convergence') && clean_msg.convergence != null ) {
1276
+ document._casa_convergence_data = { convergence: clean_msg.convergence,
1277
+ cyclethreshold: clean_msg.cyclethreshold }
1278
+ }
1279
+ }
1280
+
1281
+ // All images must be updated... without this no images are updated
1282
+ casalib.map( (im,state) => state.src.refresh( msg => {
1283
+ if ( 'stats' in msg ) state.src.update_statistics( msg.stats )
1284
+ } ), images_state )
1285
+ // Update convergence plot...
1286
+ update_convergence( )
1287
+ }''',
1288
+
1289
+ ###
1290
+ ### enabling/disabling tools in imdetails['gui']['image']['fig'].toolbar.tools does not seem to not work
1291
+ ### imdetails['gui']['image']['fig'].toolbar.tools.tool_name (e.g. "Box Select", "Lasso Select")
1292
+ ###
1293
+ ### By design, images_state[*].automask.*/images_state[*].iteration.* are singletons which only need
1294
+ ### to be disabled once...
1295
+ ###
1296
+ 'clean-disable': '''function disable( with_stop ) {
1297
+ const amobj = Object.entries(images_state)[0][1].automask
1298
+ Object.entries(amobj).map(
1299
+ ([k,v],i) => { if ( hasprop(v,'disabled') ) v.disabled = true } )
1300
+ const itobj = Object.entries(images_state)[0][1].iteration
1301
+ Object.entries(itobj).map(
1302
+ ([k,v],i) => { if ( hasprop(v,'disabled') ) v.disabled = true } )
1303
+ Object.entries(images_state).map(
1304
+ ([k,v],i) => {
1305
+ v.img.disabled = true
1306
+ if ( v.spectrum ) v.spectrum.disabled = true
1307
+ v.src.disable_masking( )
1308
+ v.src.disable_pixel_update( )
1309
+ Object.entries(v.navi).map(
1310
+ ([k1,v1],i1) => { if ( hasprop(v1,'disabled') ) v1.disabled = true }
1311
+ )
1312
+ }
1313
+ )
1314
+ clean_ctrl.continue.disabled = true
1315
+ clean_ctrl.finish.disabled = true
1316
+ clean_ctrl.stop.disabled = with_stop
1317
+ }''',
1318
+
1319
+ 'clean-enable': '''function enable( only_stop ) {
1320
+ const amobj = Object.entries(images_state)[0][1].automask
1321
+ Object.entries(amobj).map(
1322
+ ([k,v],i) => { if ( hasprop(v,'disabled') ) v.disabled = false } )
1323
+ const itobj = Object.entries(images_state)[0][1].iteration
1324
+ Object.entries(itobj).map(
1325
+ ([k,v],i) => { if ( hasprop(v,'disabled') ) v.disabled = false } )
1326
+ Object.entries(images_state).map(
1327
+ ([k,v],i) => {
1328
+ v.img.disabled = false
1329
+ if ( v.spectrum ) v.spectrum.disabled = false
1330
+ v.src.enable_masking( )
1331
+ v.src.enable_pixel_update( )
1332
+ Object.entries(v.navi).map(
1333
+ ([k1,v1],i) => { if ( hasprop(v1,'disabled') ) v1.disabled = false } )
1334
+ } )
1335
+
1336
+ clean_ctrl.stop.disabled = false
1337
+ if ( ! only_stop ) {
1338
+ clean_ctrl.continue.disabled = false
1339
+ clean_ctrl.finish.disabled = false
1340
+ }
1341
+ }''',
1342
+
1343
+
1344
+ 'clean-status-update': '''function update_status( status ) {
1345
+ const stopstr = [ 'Zero stop code',
1346
+ 'Iteration limit hit',
1347
+ 'Force stop',
1348
+ 'No change in peak residual across two major cycles',
1349
+ 'Peak residual increased by 3x from last major cycle',
1350
+ 'Peak residual increased by 3x from the minimum',
1351
+ 'Zero mask found',
1352
+ 'No mask found',
1353
+ 'N-sigma or other valid exit criterion',
1354
+ 'Stopping criteria encountered',
1355
+ 'Unrecognized stop code' ]
1356
+ if ( typeof status === 'number' ) {
1357
+ images_state[document._casa_image_name]['status'].text =
1358
+ '<p>' +
1359
+ stopstr[ status < 0 || status >= stopstr.length ?
1360
+ stopstr.length - 1 : status ] +
1361
+ '</p>'
1362
+ } else {
1363
+ images_state[document._casa_image_name]['status'].text = `<p>${status}</p>`
1364
+ }
1365
+ }''',
1366
+
1367
+ 'iter-gui-update': '''function get_update_dictionary( ) {
1368
+ //const amste = images_state[document._casa_image_name]['automask']
1369
+ //const clste = images_state[document._casa_image_name]['iteration']
1370
+ // Assumption is that there is ONE set of iteration and automask updates
1371
+ // for ALL imaging fields...
1372
+ const amobj = Object.entries(images_state)[0][1].automask
1373
+ const automask = amobj.active ?
1374
+ Object.entries(amobj).reduce(
1375
+ (acc,[k1,v1]) => { if ( hasprop(v1,'value') ) acc[k1] = v1.value; return acc },
1376
+ { dogrowprune: amobj.dogrowprune.active,
1377
+ fastnoise: amobj.fastnoise.active,
1378
+ active: true }
1379
+ ) : { }
1380
+ const itobj = Object.entries(images_state)[0][1].iteration
1381
+ const iteration = Object.entries(itobj).reduce(
1382
+ (acc,[k1,v1]) => { if ( hasprop(v1,'value') ) acc[k1] = v1.value; return acc },
1383
+ { }
1384
+ )
1385
+
1386
+ const masks = Object.entries(images_state).reduce( (acc,[k,v]) => { acc[k] = v.src.masks( ); return acc }, { } )
1387
+ const breadcrumbs = Object.entries(images_state).reduce( (acc,[k,v]) => { acc[k] = v.src.breadcrumbs( ); return acc }, { } )
1388
+ return { iteration, automask, masks, breadcrumbs, current_image: document._casa_image_name }
1389
+ }
1390
+ function update_log( log_lines ) {
1391
+ let b = logbutton
1392
+ b._log = b._log.concat( log_lines )
1393
+ if ( b._window && ! b._window.closed ) {
1394
+ for ( const line of log_lines ) {
1395
+ const p = b._window.document.createElement('p')
1396
+ p.appendChild( b._window.document.createTextNode(line) )
1397
+ b._window.document.body.appendChild(p)
1398
+ }
1399
+ }
1400
+ }
1401
+ function update_gui( msg ) {
1402
+ const itobj = Object.entries(images_state)[0][1].iteration
1403
+ if ( msg.result === 'error' ) {
1404
+ // ************************************************************************************
1405
+ // ******** error occurs and is signaled by _gclean, e.g. exception in gclean ********
1406
+ // ************************************************************************************
1407
+ state.mode = 'interactive'
1408
+ clean_ctrl.stop.button_type = "danger"
1409
+ enable(false)
1410
+ state.stopped = false
1411
+ update_status( msg.stopdesc ? msg.stopdesc : 'An internal error has occurred' )
1412
+ if ( 'cmd' in msg ) {
1413
+ update_log( msg.cmd )
1414
+ }
1415
+ } else if ( msg.result === 'no-action' ) {
1416
+ update_status( msg.stopdesc ? msg.stopdesc : 'nothing done' )
1417
+ enable( false )
1418
+ if ( 'cmd' in msg ) {
1419
+ update_log( msg.cmd )
1420
+ }
1421
+ } else if ( msg.result == 'converged' ) {
1422
+ state.mode = 'interactive'
1423
+ clean_ctrl.stop.button_type = "danger"
1424
+ enable(false)
1425
+ state.stopped = false
1426
+ update_status( msg.stopdesc ? msg.stopdesc : 'stopping criteria reached' )
1427
+ if ( 'cmd' in msg ) {
1428
+ update_log( msg.cmd )
1429
+ }
1430
+ refresh( msg )
1431
+ } else if ( msg.result === 'update' ) {
1432
+ if ( 'cmd' in msg ) {
1433
+ update_log( msg.cmd )
1434
+ }
1435
+ refresh( msg )
1436
+ // stopcode[0] == 1: iteration limit hit
1437
+ // stopcode[0] == 9: major cycle limit hit
1438
+ // *******************************************************************************************
1439
+ // ******** perhaps the user should not be locked into exiting after the limit is hit ********
1440
+ // *******************************************************************************************
1441
+ //state.stopped = state.stopped || (msg.stopcode[0] > 1 && msg.stopcode[0] < 9) || msg.stopcode[0] == 0
1442
+ state.stopped = false
1443
+ if ( state.mode === 'interactive' && ! state.awaiting_stop ) {
1444
+ clean_ctrl.stop.button_type = "danger"
1445
+ update_status( msg.stopdesc ? msg.stopdesc : 'stopcode' in msg ? msg.stopcode[0] : -1 )
1446
+ if ( ! state.stopped ) {
1447
+ enable( false )
1448
+ } else {
1449
+ disable( false )
1450
+ }
1451
+ } else if ( state.mode === 'continuous' && ! state.awaiting_stop ) {
1452
+ if ( ! state.stopped && itobj.niter.value > 0 && (itobj.nmajor.value > 0 || itobj.nmajor.value == -1) ) {
1453
+ // *******************************************************************************************
1454
+ // ******** 'niter.value > 0 so continue with one more iteration ********
1455
+ // ******** 'nmajor.value' == -1 implies do not consider nmajor in stop consideration ********
1456
+ // *******************************************************************************************
1457
+ ctrl_pipe.send( ids[cb_obj.origin.name],
1458
+ { action: 'finish',
1459
+ value: get_update_dictionary( ) },
1460
+ update_gui )
1461
+ } else if ( ! state.stopped ) {
1462
+ // *******************************************************************************************
1463
+ // ******** 'niter.value <= 0 so iteration should stop ********
1464
+ // *******************************************************************************************
1465
+ state.mode = 'interactive'
1466
+ clean_ctrl.stop.button_type = "danger"
1467
+ enable(false)
1468
+ state.stopped = false
1469
+ update_status( msg.stopdesc ? msg.stopdesc : 'stopping criteria reached' )
1470
+ } else {
1471
+ state.mode = 'interactive'
1472
+ clean_ctrl.stop.button_type = "danger"
1473
+ enable(false)
1474
+ state.stopped = false
1475
+ update_status( msg.stopdesc ? msg.stopdesc : 'stopcode' in msg ? msg.stopcode[0] : -1 )
1476
+ }
1477
+ }
1478
+ } else if ( msg.result === 'error' ) {
1479
+ img_src.drop_breadcrumb('E')
1480
+ if ( 'cmd' in msg ) {
1481
+ update_log( msg.cmd )
1482
+ }
1483
+ state.mode = 'interactive'
1484
+ clean_ctrl.stop.button_type = "danger"
1485
+ state.stopped = false
1486
+ update_status( 'stopcode' in msg ? msg.stopcode[0] : -1 )
1487
+ enable( false )
1488
+ }
1489
+ }''',
1490
+
1491
+ 'clean-wait': '''function wait_for_tclean_stop( msg ) {
1492
+ state.mode = 'interactive'
1493
+ clean_ctrl.stop.button_type = "danger"
1494
+ enable( false )
1495
+ state.awaiting_stop = false
1496
+ update_status( 'user requested stop' )
1497
+ }''',
1498
+ }