cubevis 0.5.2__py3-none-any.whl → 0.5.10__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.
@@ -0,0 +1,1498 @@
1
+ ########################################################################
2
+ #
3
+ #TASK XML> tclean -argfilter=interactive,fullsummary -argfilter:initParams=vis,imagename
4
+ # Copyright (C) 2022,2023,2024
5
+ # Associated Universities, Inc. Washington DC, USA.
6
+ #
7
+ # This script is free software; you can redistribute it and/or modify it
8
+ # under the terms of the GNU Library General Public License as published by
9
+ # the Free Software Foundation; either version 2 of the License, or (at your
10
+ # option) any later version.
11
+ #
12
+ # This library is distributed in the hope that it will be useful, but WITHOUT
13
+ # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14
+ # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
15
+ # License for more details.
16
+ #
17
+ # You should have received a copy of the GNU Library General Public License
18
+ # along with this library; if not, write to the Free Software Foundation,
19
+ # Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
20
+ #
21
+ # Correspondence concerning AIPS++ should be adressed as follows:
22
+ # Internet email: casa-feedback@nrao.edu.
23
+ # Postal address: AIPS++ Project Office
24
+ # National Radio Astronomy Observatory
25
+ # 520 Edgemont Road
26
+ # Charlottesville, VA 22903-2475 USA
27
+ #
28
+ ########################################################################
29
+ '''implementation of the ``InteractiveClean`` application for interactive control
30
+ of tclean'''
31
+
32
+ ###
33
+ ### Useful for debugging
34
+ ###
35
+ ###from cubevis.bokeh.state import initialize_bokeh
36
+ ###initialize_bokeh( bokehjs_subst=".../bokeh-3.2.2.js" )
37
+ ###
38
+ import os
39
+ import copy
40
+ import asyncio
41
+ import shutil
42
+ import websockets
43
+ from os.path import basename, abspath, exists
44
+ from uuid import uuid4
45
+ from html import escape as html_escape
46
+ from contextlib import asynccontextmanager
47
+ from bokeh.models import Button, TextInput, Checkbox, Div, LinearAxis, CustomJS, Spacer, Span, HoverTool, DataRange1d, Step, InlineStyleSheet
48
+ from bokeh.events import ModelEvent, MouseEnter
49
+ from bokeh.models import TabPanel, Tabs
50
+ from bokeh.plotting import ColumnDataSource, figure, show
51
+ from bokeh.layouts import column, row, layout
52
+ from bokeh.io import reset_output as reset_bokeh_output, output_notebook
53
+ from bokeh.models.dom import HTML
54
+
55
+ from bokeh.models.ui.tooltips import Tooltip
56
+ from cubevis.bokeh.models import TipButton, Tip, EvTextInput
57
+ from cubevis.utils import resource_manager, reset_resource_manager, is_notebook, find_pkg, load_pkg
58
+ from cubevis.utils import ContextMgrChain as CMC
59
+
60
+ # pylint: disable=no-name-in-module
61
+ from casatasks.private.imagerhelpers.imager_return_dict import ImagingDict
62
+
63
+ from casatasks.private.imagerhelpers.input_parameters import ImagerParameters
64
+ # pylint: enable=no-name-in-module
65
+
66
+ from cubevis.utils import find_ws_address, convert_masks
67
+ from cubevis.toolbox import CubeMask, AppContext
68
+ from cubevis.bokeh.utils import svg_icon
69
+ from cubevis.bokeh.sources import DataPipe
70
+ from cubevis.utils import DocEnum
71
+
72
+ from ._interactiveclean_wrappers import SharedWidgets
73
+
74
+ USE_MULTIPLE_GCLEAN_HACK=False
75
+
76
+ class InteractiveClean:
77
+ '''InteractiveClean(...) implements interactive clean using Bokeh
78
+ {{docstring}}
79
+ '''
80
+ def __stop( self, _=None ):
81
+ self.__result_future.set_result(self.__retrieve_result( ))
82
+
83
+ def _abort_handler( self, err ):
84
+ self._error_result = err
85
+ self.__stop( )
86
+
87
+ def __reset( self ):
88
+ if self.__pipes_initialized:
89
+ self._pipe = { 'control': None }
90
+ self._clean = { 'converge': { 'state': { } }, 'last-success': None }
91
+ reset_bokeh_output( )
92
+ reset_resource_manager( )
93
+
94
+ ###
95
+ ### reset asyncio result future
96
+ ###
97
+ self.__result_future = None
98
+
99
+ ###
100
+ ### used by data pipe (websocket) initialization function
101
+ ###
102
+ self.__pipes_initialized = False
103
+
104
+ ###
105
+ ### error or exception result
106
+ ###
107
+ self._error_result = None
108
+
109
+ '''
110
+ _gen_port_fwd_cmd()
111
+
112
+ Create an SSH port-forwarding command to create the tunnels necessary for remote connection.
113
+ NOTE: This assumes that the same remote ports are also available locally - which may
114
+ NOT always be true.
115
+ '''
116
+ def _gen_port_fwd_cmd(self):
117
+ hostname = os.uname()[1]
118
+
119
+ ###
120
+ ### need to add extra cube ports here for multifield imaging
121
+ ###
122
+ ports = [ self._pipe['control'].address[1], self._clean['converge']['pipe'].address[1] ]
123
+
124
+ for imid, imdetails in self._clean_targets.items( ):
125
+ ports.append( imdetails['gui']['cube']._pipe['image'].address[1] )
126
+ ports.append( imdetails['gui']['cube']._pipe['control'].address[1] )
127
+
128
+ # Also forward http port if serving webpage
129
+ if not self._is_notebook:
130
+ ports.append(self._http_port)
131
+
132
+ cmd = 'ssh'
133
+ for port in ports:
134
+ cmd += (' -L ' + str(port) + ':localhost:' + str(port))
135
+
136
+ cmd += ' ' + str(hostname)
137
+ return cmd
138
+
139
+ def _residual_path( self, gclean, imid ):
140
+ if self._clean['gclean_paths'] is None:
141
+ raise RuntimeError( f'''gclean paths are not available for {imid}''' )
142
+ for p in self._clean['gclean_paths']:
143
+ if p['name'] == imid:
144
+ return f"{p['imagepath']}/{p['residualname']}"
145
+ raise RuntimeError( f'''gclean residual path not found for {imid}''' )
146
+
147
+ def _mask_path( self, gclean, imid ):
148
+ if self._clean['gclean_paths'] is None:
149
+ raise RuntimeError( f'''gclean paths are not available for {imid}''' )
150
+ for p in self._clean['gclean_paths']:
151
+ if p['name'] == imid:
152
+ return f"{p['imagepath']}/{p['maskname']}"
153
+ raise RuntimeError( f'''gclean mask path not found for {imid}''' )
154
+
155
+ def __init__( self, vis, imagename{{# initParams}}, {{name}}={{default}}{{/ initParams}}, iclean_backend="PROD" ):
156
+
157
+ ###
158
+ ### iclean_backend can be used to select alternate backends for interactive clean. This could be used
159
+ ### to enable a backend with extended features or it could be used to select a stub backend designed
160
+ ### for testing
161
+ ###
162
+ mod_specs = None
163
+ self._gclean_module = None
164
+ if iclean_backend == 'PROD':
165
+ mod_specs = find_pkg( "casatasks.private.imagerhelpers._gclean" )
166
+ else:
167
+ mod_specs = find_pkg( f"_gclean_{iclean_backend}" )
168
+
169
+ if mod_specs:
170
+ self._gclean_module = load_pkg(mod_specs[0])
171
+ else:
172
+ raise ImportError(f"Could not locate {iclean_backend} kind of iclean backend")
173
+
174
+ ###
175
+ ### With Bokeh 3.2.2, the spectrum and convergence plots extend beyond the edge of the
176
+ ### browser window (requiring scrolling) if a width is not specified. It could be that
177
+ ### this should be computed from the width of the tabbed control area at the right of
178
+ ### the image display.
179
+ ###
180
+ self._conv_spect_plot_width = 450
181
+ ###
182
+ ### Create application context (which includes a temporary directory).
183
+ ### This sets the title of the plot.
184
+ ###
185
+ self._app_state = AppContext( 'Interactive Clean' )
186
+
187
+ ###
188
+ ### Whether or not the Interactive Clean session is running remotely
189
+ ###
190
+ #self._is_remote = remote
191
+ self._is_remote = False
192
+
193
+ ###
194
+ ### whether or not the session is being run from a jupyter notebook or script
195
+ ###
196
+ self._is_notebook = is_notebook()
197
+
198
+ ##
199
+ ## the http port for serving GUI in webpage if not running in script
200
+ ##
201
+ self._http_port = None
202
+
203
+ ###
204
+ ### the asyncio future that is used to transmit the result from interactive clean
205
+ ###
206
+ self.__result_future = None
207
+
208
+ ###
209
+ ### This is used to tell whether the websockets have been initialized, but also to
210
+ ### indicate if __call__ is being called multiple times to allow for resetting Bokeh
211
+ ###
212
+ self.__pipes_initialized = False
213
+
214
+ ###
215
+ ### State required to manage iteration control
216
+ ###
217
+ self._control = { 'iteration': { } }
218
+
219
+ ###
220
+ ### color specs
221
+ ###
222
+ self._converge_color = { 'residual': 'black',
223
+ 'flux': 'forestgreen' }
224
+
225
+ ###
226
+ ### widgets shared across image tabs (multifield imaging)
227
+ ###
228
+ self._cube_palette = None
229
+ self._image_bitmask_controls = None
230
+
231
+ ###
232
+ ### String which indicates the changes applied to the mask to indicte when
233
+ ### the mask has changed... however, THIS IS NO LONGER USED
234
+ ### It could be removed, but it adds minor overhead and would be
235
+ ### DIFFICULT to add back in the future
236
+ ###
237
+ self._last_mask_breadcrumbs = ''
238
+
239
+ ###
240
+ ### Set up dictionary of javascript code snippets
241
+ ###
242
+ self._initialize_javascript( )
243
+
244
+ # Create folder for the generated html webpage - needs its own folder to not name conflict (must be 'index.html')
245
+ webpage_dirname = imagename + '_webpage'
246
+ ### Directory is created when an HTTP server is running
247
+ ### (MAX)
248
+ # if not os.path.isdir(webpage_dirname):
249
+ # os.makedirs(webpage_dirname)
250
+ self._webpage_path = os.path.abspath(webpage_dirname)
251
+
252
+ self._pipe = { 'control': None }
253
+ self._clean = { 'converge': { 'state': { } }, 'last-success': None }
254
+
255
+ self._clean_targets = { imagename: { 'args': {{forwDict}} } }
256
+ self._initial_clean_params = { }
257
+
258
+ self._parameters = ImagerParameters( **{ k:v for k,v in self._clean_targets[imagename]['args'].items( )
259
+ if k in ImagerParameters.__init__.__code__.co_varnames[1:] } )
260
+
261
+ ###
262
+ ### For 6.6.5, outliers are not yet completely implemented so the
263
+ ### 'outlierfile' parameter may not be present.
264
+ ###
265
+ if 'outlierfile' in locals( ) and outlierfile and exists(outlierfile):
266
+ outliers, err = self._parameters.parseOutlierFile(outlierfile)
267
+ if err: raise RuntimeError( f'''outlierfile error: {err}''' )
268
+ for image in outliers:
269
+ if 'impars' in image and 'imagename' in image['impars']:
270
+ name = image['impars']['imagename']
271
+ self._clean_targets[name] = { }
272
+ args = {{forwDict}}
273
+ args['outlierfile'] = '' ### >>HERE>> outlierfile TEMPORARILY handled in _interactiveclean.py
274
+ for _,arg_mods in image.items( ):
275
+ for k,v in arg_mods.items( ):
276
+ if k in args:
277
+ args[k] = v
278
+ self._clean_targets[name]['args'] = args
279
+
280
+ ###
281
+ ### create clean interface -- final version will have only one gclean object
282
+ ###
283
+ self._init_values = { "deconvolver": deconvolver, ### used by _residual_path( )
284
+ "cycleniter": cycleniter, ### used by _setup( )
285
+ "threshold": threshold, ### used by _setup( )
286
+ "cyclefactor": cyclefactor, ### used by _setup( )
287
+ "gain": gain, ### used by _setup( )
288
+ "nsigma": nsigma, ### used by _setup( )
289
+ "convergence_state": { 'convergence': {}, ### shares state between
290
+ 'cyclethreshold': {} } } ### __init__( ) and _setup( )
291
+
292
+ self._clean['gclean'] = None
293
+ self._clean['gclean_paths'] = None
294
+ self._clean['imid'] = [ ]
295
+ self._clean['gclean_rest'] = [ ]
296
+ for imid, imdetails in self._clean_targets.items( ):
297
+ self._clean['imid'].append(imid)
298
+
299
+ ###
300
+ ### Residual path...
301
+ ###
302
+ if 'path' not in imdetails: imdetails['path'] = { }
303
+ if self._clean['gclean'] is None:
304
+
305
+ self._clean['gclean'] = self._gclean_module.gclean( **imdetails['args'] )
306
+ self._clean['gclean_paths'] = self._clean['gclean'].image_products( )
307
+
308
+ imdetails['path']['residual'] = self._residual_path(self._clean['gclean'],imid)
309
+ imdetails['path']['mask'] = self._mask_path(self._clean['gclean'],imid)
310
+
311
+ else:
312
+
313
+ imdetails['path']['residual'] = self._residual_path(self._clean['gclean'],imid)
314
+ imdetails['path']['mask'] = self._mask_path(self._clean['gclean'],imid)
315
+
316
+ for idx, (imid, imdetails) in enumerate(self._clean_targets.items( )):
317
+ imdetails['gui'] = { }
318
+
319
+ imdetails['gui'] = { 'params': { 'iteration': { }, 'automask': { } },
320
+ 'image': { },
321
+ 'image-adjust': { } }
322
+
323
+ ###
324
+ ### Only the first image should initialize the initial convergence state
325
+ ###
326
+ imdetails['gui']['cube'] = CubeMask( imdetails['path']['residual'], mask=imdetails['path']['mask'], abort=self._abort_handler,
327
+ init_script=CustomJS( args=dict( initial_convergence_state=self._init_values["convergence_state"],
328
+ name=imid ),
329
+ code='''document._casa_convergence_data = initial_convergence_state''' )
330
+ if idx == 0 else None )
331
+
332
+ ###
333
+ ### Auto Masking Parameters
334
+ ###
335
+ imdetails['params'] = { }
336
+ imdetails['params']['am'] = { }
337
+ imdetails['params']['am']['usemask'] = usemask
338
+ imdetails['params']['am']['noisethreshold'] = noisethreshold
339
+ imdetails['params']['am']['sidelobethreshold'] = sidelobethreshold
340
+ imdetails['params']['am']['lownoisethreshold'] = lownoisethreshold
341
+ imdetails['params']['am']['minbeamfrac'] = minbeamfrac
342
+ imdetails['params']['am']['negativethreshold'] = negativethreshold
343
+ imdetails['params']['am']['dogrowprune'] = dogrowprune
344
+ imdetails['params']['am']['fastnoise'] = fastnoise
345
+
346
+ def _init_pipes( self ):
347
+ if not self.__pipes_initialized:
348
+ self.__pipes_initialized = True
349
+ self._pipe['control'] = DataPipe( address=find_ws_address( ), abort=self._abort_handler )
350
+ ###
351
+ ### One pipe for updating the convergence plots.
352
+ ###
353
+ self._clean['converge'] = { 'state': None }
354
+ self._clean['converge']['pipe'] = DataPipe( address=find_ws_address( ), abort=self._abort_handler )
355
+ self._clean['converge']['id'] = str(uuid4( ))
356
+
357
+
358
+
359
+ # Get port for serving HTTP server if running in script
360
+ self._http_port = find_ws_address("")[1]
361
+ for imid, imdetails in self._clean_targets.items( ):
362
+ imdetails['gui']['cube']._init_pipes( )
363
+
364
+ def _create_convergence_gui( self, imdetails, orient='horizontal', sizing_mode='stretch_width', **kw ):
365
+ TOOLTIPS='''<div>
366
+ <div>
367
+ <span style="font-weight: bold;">@type</span>
368
+ <span>@values</span>
369
+ </div>
370
+ <div>
371
+ <span style="font-weight: bold; font-size: 10px">cycle threshold</span>
372
+ <span>@cyclethreshold</span>
373
+ </div>
374
+ <div>
375
+ <span style="font-weight: bold; font-size: 10px">stop</span>
376
+ <span>@stopDesc</span>
377
+ </div>
378
+ </div>'''
379
+
380
+ hover = HoverTool( tooltips=TOOLTIPS )
381
+ imdetails['gui']['convergence'] = figure( sizing_mode=sizing_mode, y_axis_location="right",
382
+ tools=[ hover ], toolbar_location=None, **kw )
383
+
384
+ if orient == 'vertical':
385
+ imdetails['gui']['convergence'].yaxis.axis_label='Iteration (cycle threshold dotted red)'
386
+ imdetails['gui']['convergence'].xaxis.axis_label='Peak Residual'
387
+ imdetails['gui']['convergence'].extra_x_ranges = { 'residual_range': DataRange1d( follow='end' ),
388
+ 'flux_range': DataRange1d( follow='end' ) }
389
+
390
+ imdetails['gui']['convergence'].step( 'values', 'iterations', source=imdetails['converge-data']['cyclethreshold'],
391
+ line_color='red', x_range_name='residual_range', line_dash='dotted', line_width=2 )
392
+ imdetails['gui']['convergence'].line( 'values', 'iterations', source=imdetails['converge-data']['residual'],
393
+ line_color=self._converge_color['residual'], x_range_name='residual_range' )
394
+ imdetails['gui']['convergence'].scatter( 'values', 'iterations', source=imdetails['converge-data']['residual'],
395
+ color=self._converge_color['residual'], x_range_name='residual_range',size=10 )
396
+ imdetails['gui']['convergence'].line( 'values', 'iterations', source=imdetails['converge-data']['flux'],
397
+ line_color=self._converge_color['flux'], x_range_name='flux_range' )
398
+ imdetails['gui']['convergence'].scatter( 'values', 'iterations', source=imdetails['converge-data']['flux'],
399
+ color=self._converge_color['flux'], x_range_name='flux_range', size=10 )
400
+
401
+ imdetails['gui']['convergence'].add_layout( LinearAxis( x_range_name='flux_range', axis_label='Total Flux',
402
+ axis_line_color=self._converge_color['flux'],
403
+ major_label_text_color=self._converge_color['flux'],
404
+ axis_label_text_color=self._converge_color['flux'],
405
+ major_tick_line_color=self._converge_color['flux'],
406
+ minor_tick_line_color=self._converge_color['flux'] ), 'above')
407
+
408
+ else:
409
+ imdetails['gui']['convergence'].xaxis.axis_label='Iteration (cycle threshold dotted red)'
410
+ imdetails['gui']['convergence'].yaxis.axis_label='Peak Residual'
411
+ imdetails['gui']['convergence'].extra_y_ranges = { 'residual_range': DataRange1d( follow='end' ),
412
+ 'flux_range': DataRange1d( follow='end' ) }
413
+
414
+ imdetails['gui']['convergence'].step( 'iterations', 'values', source=imdetails['converge-data']['cyclethreshold'],
415
+ line_color='red', y_range_name='residual_range', line_dash='dotted', line_width=2 )
416
+ imdetails['gui']['convergence'].line( 'iterations', 'values', source=imdetails['converge-data']['residual'],
417
+ line_color=self._converge_color['residual'], y_range_name='residual_range' )
418
+ imdetails['gui']['convergence'].scatter( 'iterations', 'values', source=imdetails['converge-data']['residual'],
419
+ color=self._converge_color['residual'], y_range_name='residual_range',size=10 )
420
+ imdetails['gui']['convergence'].line( 'iterations', 'values', source=imdetails['converge-data']['flux'],
421
+ line_color=self._converge_color['flux'], y_range_name='flux_range' )
422
+ imdetails['gui']['convergence'].scatter( 'iterations', 'values', source=imdetails['converge-data']['flux'],
423
+ color=self._converge_color['flux'], y_range_name='flux_range', size=10 )
424
+
425
+ imdetails['gui']['convergence'].add_layout( LinearAxis( y_range_name='flux_range', axis_label='Total Flux',
426
+ axis_line_color=self._converge_color['flux'],
427
+ major_label_text_color=self._converge_color['flux'],
428
+ axis_label_text_color=self._converge_color['flux'],
429
+ major_tick_line_color=self._converge_color['flux'],
430
+ minor_tick_line_color=self._converge_color['flux'] ), 'right')
431
+
432
+
433
+ def _launch_gui( self ):
434
+ '''create and show GUI
435
+ '''
436
+ ###
437
+ ### Will contain the top level GUI
438
+ ###
439
+ self._fig = { }
440
+
441
+ ###
442
+ ### Python-side handler for events from the interactive clean control buttons
443
+ ###
444
+ async def clean_handler( msg, self=self ):
445
+ if msg['action'] == 'next' or msg['action'] == 'finish':
446
+
447
+ if 'mask' in msg['value']:
448
+ ###
449
+ ### >>HERE>> breadcrumbs must be specific to the field they are related to...
450
+ ###
451
+ if 'breadcrumbs' in msg['value'] and msg['value']['breadcrumbs'] is not None and msg['value']['breadcrumbs'] != self._last_mask_breadcrumbs:
452
+ self._last_mask_breadcrumbs = msg['value']['breadcrumbs']
453
+ mask_dir = "%s.mask" % self._imagename
454
+ shutil.rmtree(mask_dir)
455
+ new_mask = imdetails['gui']['cube'].jsmask_to_raw(msg['value']['mask'])
456
+ self._mask_history.append(new_mask)
457
+
458
+ msg['value']['mask'] = convert_masks(masks=new_mask, coord='pixel', cdesc=imdetails['gui']['cube'].coorddesc())
459
+
460
+ else:
461
+ ##### seemingly the mask path used to be spliced in?
462
+ #msg['value']['mask'] = self._mask_path
463
+ pass
464
+ else:
465
+ ##### seemingly the mask path used to be spliced in?
466
+ #msg['value']['mask'] = self._mask_path
467
+ pass
468
+
469
+ ###
470
+ ### In the final implementation, there will only be one gclean object...
471
+ ###
472
+ convergence_state={ 'convergence': {}, 'cyclethreshold': {} }
473
+ err,errmsg = self._clean['gclean'].update( dict( **msg['value']['iteration'],
474
+ **msg['value']['automask'] ) )
475
+
476
+ iteration_limit = int(msg['value']['iteration']['niter'])
477
+ stopdesc, stopcode, majordone, majorleft, iterleft, self._convergence_data = await self._clean['gclean'].__anext__( )
478
+
479
+ clean_cmds = self._clean['gclean'].cmds( )
480
+
481
+ for key, value in self._convergence_data.items( ):
482
+
483
+ if len(value['chan']) == 0 or stopcode[0] == -1:
484
+ ### stopcode[0] == -1 indicates an error condition within gclean
485
+ return dict( result='error', stopcode=stopcode, cmd=clean_cmds,
486
+ convergence=None, majordone=majordone,
487
+ majorleft=majorleft, iterleft=iterleft, stopdesc=stopdesc )
488
+
489
+ convergence_state['convergence'][key] = value['chan']
490
+ convergence_state['cyclethreshold'][key] = value['major']['cyclethreshold']
491
+
492
+ ### stopcode[0] != 0 indicates that some stopping criteria has been reached
493
+ ### this will also catch errors as well as convergence
494
+ ### (so 'converged' isn't quite right...)
495
+ self._clean['last-success'] = dict( result='converged' if stopcode[0] else 'update', stopcode=stopcode, cmd=clean_cmds,
496
+ convergence=convergence_state['convergence'],
497
+ iterdone=iteration_limit - iterleft, iterleft=iterleft,
498
+ majordone=majordone, majorleft=majorleft, cyclethreshold=convergence_state['cyclethreshold'], stopdesc=stopdesc )
499
+ return self._clean['last-success']
500
+
501
+ elif msg['action'] == 'stop':
502
+ self.__stop( )
503
+ return dict( result='stopped', update=dict( ) )
504
+ elif msg['action'] == 'status':
505
+ return dict( result="ok", update=dict( ) )
506
+ else:
507
+ print( "got something else: '%s'" % msg['action'] )
508
+
509
+ ###
510
+ ### set up websockets which will be used for control and convergence updates
511
+ ###
512
+ self._init_pipes( )
513
+
514
+ ###
515
+ ### Setup id that will be used for messages from each button
516
+ ###
517
+ self._clean_ids = { }
518
+ for btn in "continue", 'finish', 'stop':
519
+ self._clean_ids[btn] = str(uuid4( ))
520
+ #print("%s: %s" % ( btn, self._clean_ids[btn] ) )
521
+ self._pipe['control'].register( self._clean_ids[btn], clean_handler )
522
+
523
+
524
+ ###
525
+ ### There is one set of tclean controls for all images/outlier/etc. because
526
+ ### in the final version gclean will handle the iterations for all fields...
527
+ ###
528
+ cwidth = 64
529
+ cheight = 40
530
+ self._control['iteration'] = { }
531
+ self._control['iteration']['continue'] = TipButton( max_width=cwidth, max_height=cheight, name='continue',
532
+ icon=svg_icon(icon_name="iclean-continue", size=18),
533
+ tooltip=Tooltip( content=HTML( '''Stop after <b>one major cycle</b> or when any stopping criteria is met.''' ), position='left') )
534
+ self._control['iteration']['finish'] = TipButton( max_width=cwidth, max_height=cheight, name='finish',
535
+ icon=svg_icon(icon_name="iclean-finish", size=18),
536
+ tooltip=Tooltip( content=HTML( '''<b>Continue</b> until some stopping criteria is met.''' ), position='left') )
537
+ self._control['iteration']['stop'] = TipButton( button_type="danger", max_width=cwidth, max_height=cheight, name='stop',
538
+ icon=svg_icon(icon_name="iclean-stop", size=18),
539
+ 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' ) )
540
+
541
+ ###
542
+ ### The single SHARED help button will be supplied by the first CubeMask...
543
+ ###
544
+ help_button = None
545
+ ###
546
+ ### First status line will be reused...
547
+ ###
548
+ status_line = None
549
+
550
+ ###
551
+ ### Manage the widgets which are shared between tabs...
552
+ ###
553
+ icw = SharedWidgets( )
554
+ toolbars = [ ]
555
+ for imid, imdetails in self._clean_targets.items( ):
556
+ imdetails['gui']['stats'] = imdetails['gui']['cube'].statistics( )
557
+ imdetails['image-channels'] = imdetails['gui']['cube'].shape( )[3]
558
+
559
+ 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 )
560
+
561
+ ###
562
+ ### Retrieve convergence information
563
+ ###
564
+ def convergence_handler( msg, self=self, imid=imid ):
565
+ if msg['action'] == 'retrieve':
566
+ return { 'result': self._clean['last-success'] }
567
+ else:
568
+ return { 'result': None, 'error': 'unrecognized action' }
569
+
570
+ self._clean['converge']['pipe'].register( self._clean['converge']['id'], convergence_handler )
571
+
572
+ ###
573
+ ### Data source that will be used for updating the convergence plot
574
+ ###
575
+ stokes = 0
576
+ convergence = imdetails['converge']['chan'][0][stokes]
577
+ imdetails['converge-data'] = { }
578
+ imdetails['converge-data']['flux'] = ColumnDataSource( data=dict( values=convergence['modelFlux'], iterations=convergence['iterations'],
579
+ cyclethreshold=convergence['cycleThresh'],
580
+ stopDesc=list( map( ImagingDict.get_summaryminor_stopdesc, convergence['stopCode'] ) ),
581
+ type=['flux'] * len(convergence['iterations']) ) )
582
+ imdetails['converge-data']['residual'] = ColumnDataSource( data=dict( values=convergence['peakRes'], iterations=convergence['iterations'],
583
+ cyclethreshold=convergence['cycleThresh'],
584
+ stopDesc=list( map( ImagingDict.get_summaryminor_stopdesc, convergence['stopCode'] ) ),
585
+ type=['residual'] * len(convergence['iterations'])) )
586
+ imdetails['converge-data']['cyclethreshold'] = ColumnDataSource( data=dict( values=convergence['cycleThresh'], iterations=convergence['iterations'] ) )
587
+
588
+
589
+ ###
590
+ ### help page for cube interactions
591
+ ###
592
+ if help_button is None:
593
+ 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>',
594
+ '<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' )
595
+
596
+ self._create_convergence_gui( imdetails, orient='horizontal', sizing_mode='stretch_height', width=self._conv_spect_plot_width )
597
+
598
+ imdetails['gui']['params']['iteration']['nmajor'] = icw.nmajor( title='nmajor', value="%s" % self._initial_clean_params['nmajor'], width=90 )
599
+ imdetails['gui']['params']['iteration']['niter'] = icw.niter( title='niter', value="%s" % self._initial_clean_params['niter'], width=90 )
600
+ imdetails['gui']['params']['iteration']['cycleniter'] = icw.cycleniter( title="cycleniter", value="%s" % self._initial_clean_params['cycleniter'], width=90 )
601
+ imdetails['gui']['params']['iteration']['threshold'] = icw.threshold( title="threshold", value="%s" % self._initial_clean_params['threshold'], width=90 )
602
+ imdetails['gui']['params']['iteration']['cyclefactor'] = icw.cyclefactor( value="%s" % self._initial_clean_params['cyclefactor'], title="cyclefactor", width=90 )
603
+ imdetails['gui']['params']['iteration']['gain'] = icw.gain( title='gain', value="%s" % self._initial_clean_params['gain'], width=90 )
604
+ imdetails['gui']['params']['iteration']['nsigma'] = icw.nsigma( title='nsigma', value="%s" % self._initial_clean_params['nsigma'], width=90 )
605
+
606
+ if imdetails['params']['am']['usemask'] == 'auto-multithresh':
607
+ ###
608
+ ### Currently automasking tab is only available when the user selects 'auto-multithresh'
609
+ ###
610
+ imdetails['gui']['params']['automask']['active'] = True
611
+ imdetails['gui']['params']['automask']['noisethreshold'] = icw.noisethreshold( title='noisethreshold', value="%s" % imdetails['params']['am']['noisethreshold'], margin=( 5, 25, 5, 5 ), width=90 )
612
+ imdetails['gui']['params']['automask']['sidelobethreshold'] = icw.sidelobethreshold( title='sidelobethreshold', value="%s" % imdetails['params']['am']['sidelobethreshold'], margin=( 5, 25, 5, 5 ), width=90 )
613
+ imdetails['gui']['params']['automask']['lownoisethreshold'] = icw.lownoisethreshold( title='lownoisethreshold', value="%s" % imdetails['params']['am']['lownoisethreshold'], margin=( 5, 25, 5, 5 ), width=90 )
614
+ imdetails['gui']['params']['automask']['minbeamfrac'] = icw.minbeamfrac( title='minbeamfrac', value="%s" % imdetails['params']['am']['minbeamfrac'], width=90 )
615
+ imdetails['gui']['params']['automask']['negativethreshold'] = icw.negativethreshold( title='negativethreshold', value="%s" % imdetails['params']['am']['negativethreshold'], margin=( 5, 25, 5, 5 ), width=90 )
616
+ imdetails['gui']['params']['automask']['dogrowprune'] = icw.dogrowprune( label='dogrowprune', active=imdetails['params']['am']['dogrowprune'], margin=( 15, 25, 5, 5 ) )
617
+ imdetails['gui']['params']['automask']['fastnoise'] = icw.fastnoise( label='fastnoise', active=imdetails['params']['am']['fastnoise'], margin=( 15, 25, 5, 5 ) )
618
+
619
+
620
+ imdetails['gui']['image']['src'] = imdetails['gui']['cube'].js_obj( )
621
+ imdetails['gui']['image']['fig'] = imdetails['gui']['cube'].image( grid=False, height_policy='max', width_policy='max',
622
+ channelcb=CustomJS( args=dict( img_state={ 'src': imdetails['gui']['image']['src'],
623
+ 'flux': imdetails['converge-data']['flux'],
624
+ 'residual': imdetails['converge-data']['residual'],
625
+ 'cyclethreshold': imdetails['converge-data']['cyclethreshold'] },
626
+ imid=imid,
627
+ ctrl={ 'converge': self._clean['converge'] },
628
+ stopdescmap=ImagingDict.get_summaryminor_stopdesc( ) ),
629
+ code=self._js['update-converge'] +
630
+ '''update_convergence_single( img_state, document._casa_convergence_data.convergence[imid] )''' ) )
631
+
632
+ ###
633
+ ### collect toolbars for syncing selection
634
+ ###
635
+ toolbars.append(imdetails['gui']['image']['fig'].toolbar)
636
+
637
+ ###
638
+ ### spectrum plot must be disabled during iteration due to "tap to change channel" functionality
639
+ ###
640
+ if imdetails['image-channels'] > 1:
641
+ imdetails['gui']['spectrum'] = imdetails['gui']['cube'].spectrum( orient='vertical', sizing_mode='stretch_height', width=self._conv_spect_plot_width )
642
+ imdetails['gui']['slider'] = imdetails['gui']['cube'].slider( show_value=False, title='', margin=(14,5,5,5), sizing_mode="scale_width" )
643
+ imdetails['gui']['goto'] = imdetails['gui']['cube'].goto( )
644
+ else:
645
+ imdetails['gui']['spectrum'] = None
646
+ imdetails['gui']['slider'] = None
647
+ imdetails['gui']['goto'] = None
648
+
649
+ imdetails['gui']['channel-ctrl'] = imdetails['gui']['cube'].channel_ctrl( )
650
+
651
+ imdetails['gui']['cursor-pixel-text'] = imdetails['gui']['cube'].pixel_tracking_text( margin=(-3, 5, 3, 30) )
652
+
653
+ self._image_bitmask_controls = imdetails['gui']['cube'].bitmask_ctrl( reuse=self._image_bitmask_controls, button_type='light' )
654
+
655
+ if imdetails['params']['am']['usemask'] == 'auto-multithresh':
656
+ imdetails['gui']['auto-masking-panel'] = [ TabPanel( child=column( row( Tip( imdetails['gui']['params']['automask']['noisethreshold'],
657
+ tooltip=Tooltip( content=HTML( 'sets the signal-to-noise threshold above which significant emission is masked during the initial round of mask creation' ),
658
+ position='bottom' ) ),
659
+ Tip( imdetails['gui']['params']['automask']['sidelobethreshold'],
660
+ 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' ),
661
+ position='bottom' ) ),
662
+ Tip( imdetails['gui']['params']['automask']['minbeamfrac'],
663
+ tooltip=Tooltip( content=HTML( 'sets the minimum size a region must be to be retained in the mask' ),
664
+ position='bottom' ) ) ),
665
+ row( Tip( imdetails['gui']['params']['automask']['lownoisethreshold'],
666
+ 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' ),
667
+ position='bottom' ) ),
668
+ Tip( imdetails['gui']['params']['automask']['negativethreshold'],
669
+ tooltip=Tooltip( content=HTML( 'sets the signal-to-noise threshold for absorption features to be masked' ),
670
+ position='bottom' ) ) ),
671
+ row( Tip( imdetails['gui']['params']['automask']['dogrowprune'],
672
+ 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' ),
673
+ position='bottom' ) ),
674
+ Tip( imdetails['gui']['params']['automask']['fastnoise'],
675
+ tooltip=Tooltip( content=HTML( 'When set to True, a simpler but faster noise calucation is used' ),
676
+ position='bottom' ) ) ) ),
677
+ title='Automask' ) ]
678
+ else:
679
+ imdetails['gui']['auto-masking-panel'] = [ ]
680
+
681
+
682
+ ###
683
+ ### synchronize toolbar selections among figures
684
+ ###
685
+ if toolbars:
686
+ for tb in toolbars:
687
+ tb.js_on_change( 'active_changed',
688
+ ###
689
+ ### toolbars must filter out 'tb' to avoid circular references
690
+ ###
691
+ CustomJS( args=dict(toolbars=[t for t in toolbars if t.id != tb.id]),
692
+ code='''casalib.map( (gest,tool) => {
693
+ if ( tool.active ) {
694
+ // a tool which belongs to the toolbar that signaled a change
695
+ // is active for this gesture...
696
+ toolbars.forEach( (other_tb) => {
697
+ let new_active = other_tb.gestures[gest].tools.find(
698
+ (t) => t.name == tool.active.name )
699
+ if ( ! other_tb.gestures[gest].active ) {
700
+ if ( new_active ) {
701
+ other_tb.gestures[gest].active = new_active
702
+ new_active.active = true
703
+ }
704
+ } else if ( other_tb.gestures[gest].active.name != tool.active.name ) {
705
+ if ( new_active ) {
706
+ other_tb.gestures[gest].active.active = false
707
+ new_active.active = true
708
+ other_tb.gestures[gest].active = new_active
709
+ }
710
+ }
711
+ } )
712
+ } else {
713
+ // a tool which belongs to the toolbar that signaled a change
714
+ // is NOT active for this gesture...
715
+ toolbars.forEach( (other_tb) => {
716
+ if ( other_tb.gestures[gest] && other_tb.gestures[gest].active ) {
717
+ other_tb.gestures[gest].active.active = false
718
+ other_tb.gestures[gest].active = null
719
+ }
720
+ } )
721
+ }
722
+ }, cb_obj.gestures )''' ) )
723
+
724
+ ###
725
+ ### button to display the tclean log -- in the final implmentation, outliers and other multifield imaging should be handled by gclean
726
+ ###
727
+ self._log_button = TipButton( max_width=help_button.width, max_height=help_button.height, name='log',
728
+ icon=svg_icon(icon_name="bp-application-sm", size=25),
729
+ tooltip=Tooltip( content=HTML('''click here to see the <pre>tclean</pre> execution log'''), position="right" ),
730
+ margin=(-1, 0, -10, 0), button_type='light',
731
+ stylesheets=[ InlineStyleSheet( css='''.bk-btn { border: 0px solid #ccc; padding: 0 var(--padding-vertical) var(--padding-horizontal); margin-top: 3px; }''' ) ] )
732
+
733
+ self._control['iteration']['cb'] = CustomJS( args=dict( images_state={ k: { 'status': v['gui']['stopcode'],
734
+ 'automask': v['gui']['params']['automask'],
735
+ 'iteration': v['gui']['params']['iteration'],
736
+ 'img': v['gui']['image']['fig'],
737
+ 'src': v['gui']['cube'].js_obj( ),
738
+ 'spectrum': v['gui']['spectrum'],
739
+ 'src': v['gui']['image']['src'],
740
+ 'flux': v['converge-data']['flux'],
741
+ 'cyclethreshold': v['converge-data']['cyclethreshold'],
742
+ 'residual': v['converge-data']['residual'],
743
+ 'navi': { 'slider': v['gui']['slider'],
744
+ 'goto': v['gui']['goto'],
745
+ ## it doesn't seem like pixel tracking must be disabled
746
+ ##'tracking': v['gui']['cursor-pixel-text'],
747
+ 'stokes': v['gui']['channel-ctrl'][1] } }
748
+ for k,v in self._clean_targets.items( ) },
749
+ ctrl={ 'converge': self._clean['converge'] },
750
+ clean_ctrl=self._control['iteration'],
751
+ state=dict( mode='interactive', stopped=False, awaiting_stop=False, mask="" ),
752
+ ctrl_pipe=self._pipe['control'],
753
+ ids=self._clean_ids,
754
+ logbutton=self._log_button,
755
+ stopdescmap=ImagingDict.get_summaryminor_stopdesc( )
756
+ ),
757
+ code=self._js['update-converge'] + self._js['clean-refresh'] + self._js['clean-disable'] +
758
+ self._js['clean-enable'] + self._js['clean-status-update'] +
759
+ self._js['iter-gui-update'] + self._js['clean-wait'] +
760
+ '''function invalid_niter( s ) {
761
+ let v = parseInt( s )
762
+ if ( v > 0 ) return ''
763
+ if ( v == 0 ) return 'niter is zero'
764
+ if ( v < 0 ) return 'niter cannot be negative'
765
+ if ( isNaN(v) ) return 'niter must be an integer'
766
+ }
767
+ const itobj = Object.entries(images_state)[0][1].iteration
768
+ if ( ! state.stopped && cb_obj.origin.name == 'finish' ) {
769
+ let invalid = invalid_niter(itobj.niter.value)
770
+ if ( invalid ) update_status( invalid )
771
+ else {
772
+ state.mode = 'continuous'
773
+ update_status( 'Running multiple iterations' )
774
+ disable( false )
775
+ clean_ctrl.stop.button_type = "warning"
776
+ const thevalue = get_update_dictionary( )
777
+ ctrl_pipe.send( ids[cb_obj.origin.name],
778
+ { action: 'finish',
779
+ value: thevalue },
780
+ update_gui )
781
+ }
782
+ }
783
+ if ( ! state.stopped && state.mode === 'interactive' &&
784
+ cb_obj.origin.name === 'continue' ) {
785
+ let invalid = invalid_niter(itobj.niter.value)
786
+ if ( invalid ) update_status( invalid )
787
+ else {
788
+ update_status( 'Running one set of deconvolution iterations' )
789
+ disable( true )
790
+ // only send message for button that was pressed
791
+ // it's unclear whether 'this.origin.' or 'cb_obj.origin.' should be used
792
+ // (or even if 'XXX.origin.' is public)...
793
+ ctrl_pipe.send( ids[cb_obj.origin.name],
794
+ { action: 'next',
795
+ value: get_update_dictionary( ) },
796
+ update_gui )
797
+ }
798
+ }
799
+ if ( state.mode === 'interactive' && cb_obj.origin.name === 'stop' ) {
800
+ if ( confirm( "Are you sure you want to end this interactive clean session and close the GUI?" ) ) {
801
+ disable( true )
802
+ //ctrl_pipe.send( ids[cb_obj.origin.name],
803
+ // { action: 'stop',
804
+ // value: { } },
805
+ // update_gui )
806
+ document._casa_window_closed = true
807
+ /*** this will close the tab >>>>---------+ ***/
808
+ /*** | ***/
809
+ /*** vvvvv----------------------------+ ***/
810
+ document._cube_done( Object.entries(images_state).reduce((acc,[k,v]) => ({ ...acc, [k]: v.src.masks( ) }),{ } ) )
811
+ }
812
+ } else if ( state.mode === 'continuous' &&
813
+ cb_obj.origin.name === 'stop' &&
814
+ ! state.awaiting_stop ) {
815
+ disable( true )
816
+ state.awaiting_stop = true
817
+ ctrl_pipe.send( ids[cb_obj.origin.name],
818
+ { action: 'status',
819
+ value: { } },
820
+ wait_for_tclean_stop )
821
+ }''' )
822
+
823
+
824
+ self._control['iteration']['continue'].js_on_click( self._control['iteration']['cb'] )
825
+ self._control['iteration']['finish'].js_on_click( self._control['iteration']['cb'] )
826
+ self._control['iteration']['stop'].js_on_click( self._control['iteration']['cb'] )
827
+
828
+ self._log_button.js_on_click( CustomJS( args=dict( logbutton=self._log_button ),
829
+ code='''function format_log( elem ) {
830
+ return `<html>
831
+ <head>
832
+ <style type="text/css">
833
+ body {
834
+ counter-reset: section;
835
+ }
836
+ p:before {
837
+ font-weight: bold;
838
+ counter-increment: section;
839
+ content: "" counter(section) ": ";
840
+ }
841
+ </style>
842
+ </head>
843
+ <body>
844
+ <h1>Interactive Clean History</h1>
845
+ ` + elem.map((x) => `<p>${x}</p>`).join('\\n') + '</body>\\n</html>'
846
+ }
847
+ let b = cb_obj.origin
848
+ if ( ! b._window || b._window.closed ) {
849
+ b._window = window.open("about:blank","Interactive Clean Log")
850
+ b._window.document.write(format_log(b._log))
851
+ b._window.document.close( )
852
+ }''' ) )
853
+
854
+ ###
855
+ ### Setup script that will be called when the user closes the
856
+ ### browser tab that is running interactive clean
857
+ ###
858
+ initial_log = self._clean['gclean'].cmds( )
859
+
860
+ self._pipe['control'].init_script=CustomJS( args=dict( ctrl_pipe=self._pipe['control'],
861
+ ids=self._clean_ids,
862
+ logbutton=self._log_button,
863
+ log=initial_log,
864
+ initial_image=list(self._clean_targets.items( ))[0][0]
865
+ ),
866
+ code=self._js['initialize'] +
867
+ '''if ( ! logbutton._log ) {
868
+ /*** store log list with log button for access in other callbacks ***/
869
+ logbutton._log = log
870
+ }''' )
871
+
872
+ tab_panels = list( map( self._create_image_panel, self._clean_targets.items( ) ) )
873
+
874
+ for imid, imdetails in self._clean_targets.items( ):
875
+ imdetails['gui']['cube'].connect( )
876
+
877
+ image_tabs = Tabs( tabs=tab_panels, tabs_location='below', height_policy='max', width_policy='max' )
878
+
879
+ self._fig['layout'] = column(
880
+ row( help_button,
881
+ self._log_button,
882
+ Spacer( height=self._control['iteration']['stop'].height, sizing_mode="scale_width" ),
883
+ Div( text="<div><b>status:</b></div>" ),
884
+ status_line,
885
+ self._control['iteration']['stop'], self._control['iteration']['continue'], self._control['iteration']['finish'], sizing_mode="scale_width" ),
886
+ row( image_tabs, height_policy='max', width_policy='max' ),
887
+ height_policy='max', width_policy='max' )
888
+
889
+ ###
890
+ ### Keep track of which image is currently active in document._casa_image_name (which is
891
+ ### initialized in self._js['initialize']). Also, update the current control sub-tab
892
+ ### when the field main-tab is changed. An attempt to manage this all within the
893
+ ### control sub-tabs using a reference to self._image_control_tab_groups from
894
+ ### each control sub-tab failed with:
895
+ ###
896
+ ### bokeh.core.serialization.SerializationError: circular reference
897
+ ###
898
+ image_tabs.js_on_change( 'active', CustomJS( args=dict( names=[ t[0] for t in self._clean_targets.items( ) ],
899
+ itergroups=self._image_control_tab_groups ),
900
+ code='''if ( ! hasprop(document,'_casa_last_control_tab') ) {
901
+ document._casa_last_control_tab = 0
902
+ }
903
+ document._casa_image_name = names[cb_obj.active]
904
+ itergroups[document._casa_image_name].active = document._casa_last_control_tab''' ) )
905
+
906
+ # Change display type depending on runtime environment
907
+ if self._is_notebook:
908
+ output_notebook()
909
+ else:
910
+ ### Directory is created when an HTTP server is running
911
+ ### (MAX)
912
+ ### output_file(self._imagename+'_webpage/index.html')
913
+ pass
914
+
915
+ show(self._fig['layout'])
916
+
917
+ def _create_colormap_adjust( self, imdetails ):
918
+ palette = imdetails['gui']['cube'].palette( reuse=self._cube_palette )
919
+ return column( row( Div(text="<div><b>Colormap:</b></div>",margin=(5,2,5,25)), palette ),
920
+ imdetails['gui']['cube'].colormap_adjust( ), sizing_mode='stretch_both' )
921
+
922
+
923
+ def _create_control_image_tab( self, imid, imdetails ):
924
+ result = Tabs( tabs=[ TabPanel(child=column( row( Tip( imdetails['gui']['params']['iteration']['nmajor'],
925
+ tooltip=Tooltip( content=HTML( 'maximum number of major cycles to run before stopping'),
926
+ position='bottom' ) ),
927
+ Tip( imdetails['gui']['params']['iteration']['niter'],
928
+ tooltip=Tooltip( content=HTML( 'number of clean iterations to run' ),
929
+ position='bottom' ) ),
930
+ Tip( imdetails['gui']['params']['iteration']['threshold'],
931
+ tooltip=Tooltip( content=HTML( 'stopping threshold' ),
932
+ position='bottom' ) ) ),
933
+ row( Tip( imdetails['gui']['params']['iteration']['nsigma'],
934
+ tooltip=Tooltip( content=HTML( 'multiplicative factor for rms-based threshold stopping'),
935
+ position='bottom' ) ),
936
+ Tip( imdetails['gui']['params']['iteration']['gain'],
937
+ tooltip=Tooltip( content=HTML( 'fraction of the source flux to subtract out of the residual image'),
938
+ position='bottom' ) ) ),
939
+ row( Tip( imdetails['gui']['params']['iteration']['cycleniter'],
940
+ tooltip=Tooltip( content=HTML( 'maximum number of <b>minor-cycle</b> iterations' ),
941
+ position='bottom' ) ),
942
+ Tip( imdetails['gui']['params']['iteration']['cyclefactor'],
943
+ tooltip=Tooltip( content=HTML( 'scaling on PSF sidelobe level to compute the minor-cycle stopping threshold' ),
944
+ position='bottom_left' ) ), background="lightgray" ),
945
+ imdetails['gui']['convergence'], sizing_mode='stretch_height' ),
946
+ title='Iteration' ) ] +
947
+ ( [ TabPanel( child=imdetails['gui']['spectrum'],
948
+ title='Spectrum' ) ] if imdetails['image-channels'] > 1 else [ ] ) +
949
+ [ TabPanel( child=self._create_colormap_adjust(imdetails),
950
+ title='Colormap' ),
951
+ TabPanel( child=column( *imdetails['gui']['stats'] ),
952
+ title='Statistics' ) ] + imdetails['gui']['auto-masking-panel'],
953
+ width=500, sizing_mode='stretch_height', tabs_location='below' )
954
+
955
+ if not hasattr(self,'_image_control_tab_groups'):
956
+ self._image_control_tab_groups = { }
957
+
958
+ self._image_control_tab_groups[imid] = result
959
+ result.js_on_change( 'active', CustomJS( args=dict( ),
960
+ code='''document._casa_last_control_tab = cb_obj.active''' ) )
961
+ return result
962
+
963
+ def _create_image_panel( self, imagetuple ):
964
+ imid, imdetails = imagetuple
965
+
966
+
967
+
968
+ return TabPanel( child=column( row( *imdetails['gui']['channel-ctrl'], imdetails['gui']['cube'].coord_ctrl( ),
969
+ *self._image_bitmask_controls,
970
+ #Spacer( height=5, height_policy="fixed", sizing_mode="scale_width" ),
971
+ imdetails['gui']['cursor-pixel-text'],
972
+ row( Spacer( sizing_mode='stretch_width' ),
973
+ imdetails['gui']['cube'].tapedeck( size='20px' ) if imdetails['image-channels'] > 1 else Div( ),
974
+ Spacer( height=5, width=350 ), width_policy='max' ),
975
+ width_policy='max' ),
976
+ row( imdetails['gui']['image']['fig'],
977
+ column( row( imdetails['gui']['goto'],
978
+ imdetails['gui']['slider'],
979
+ width_policy='max' ) if imdetails['image-channels'] > 1 else Div( ),
980
+ self._create_control_image_tab(imid, imdetails), height_policy='max' ),
981
+ height_policy='max', width_policy='max' ),
982
+ height_policy='max', width_policy='max' ), title=imid )
983
+
984
+ def __call__( self ):
985
+ '''Display GUI and process events until the user stops the application.
986
+
987
+ Example:
988
+ Create ``iclean`` object and display::
989
+
990
+ print( "Result: %s" %
991
+ iclean( vis='refim_point_withline.ms', imagename='test', imsize=512,
992
+ cell='12.0arcsec', specmode='cube',
993
+ interpolation='nearest', ... )( ) )
994
+ '''
995
+
996
+ self._setup()
997
+
998
+ # If Interactive Clean is being run remotely, print helper info for port tunneling
999
+ if self._is_remote:
1000
+ # Tunnel ports for Jupyter kernel connection
1001
+ print("\nImportant: Copy the following line and run in your local terminal to establish port forwarding.\
1002
+ You may need to change the last argument to align with your ssh config.\n")
1003
+ print(self._gen_port_fwd_cmd())
1004
+
1005
+ # TODO: Include?
1006
+ # VSCode will auto-forward ports that appear in well-formatted addresses.
1007
+ # Printing this line will cause VSCode to autoforward the ports
1008
+ # print("Cmd: " + str(repr(self.auto_fwd_ports_vscode())))
1009
+ input("\nPress enter when port forwarding is setup...")
1010
+
1011
+ async def _run_( ):
1012
+ async with self.serve( ) as s:
1013
+ await s
1014
+
1015
+ if self._is_notebook:
1016
+ ic_task = asyncio.create_task(_run_())
1017
+ else:
1018
+ asyncio.run(_run_( ))
1019
+ return self.result( )
1020
+
1021
+ def _setup( self ):
1022
+ self.__reset( )
1023
+
1024
+ def initialize_tclean( gclean ):
1025
+
1026
+ stopdesc, stopcode, majordone, majorleft, iterleft, all_converge = next(gclean)
1027
+
1028
+ for imid, converge in all_converge.items( ):
1029
+ #######################################################################################################
1030
+ ### gclean seems to return its internal state making it succeptable to modification... so we'll at ###
1031
+ ### least start out with unique dictionaries. ###
1032
+ #######################################################################################################
1033
+ converge = copy.deepcopy(converge)
1034
+
1035
+ imdetails = self._clean_targets[imid]
1036
+ imdetails['converge'] = converge
1037
+
1038
+ if imdetails['converge'] is None or len(imdetails['converge'].keys()) == 0 or \
1039
+ imdetails['converge']['major'] is None or imdetails['converge']['chan'] is None:
1040
+ ###
1041
+ ### gclean should provide argument checking (https://github.com/casangi/casagui/issues/33)
1042
+ ### but currently gclean can be initialized with bad arguments and it is not known until
1043
+ ### the initial calls to tclean/deconvolve
1044
+ ###
1045
+ raise RuntimeError(f'''gclean failure "%s" not returned: {imdetails["converge"]}''' % ('major' if imdetails['converge']['major'] is None else 'chan'))
1046
+
1047
+ self._clean['cmds'].extend(self._clean['gclean'].cmds( ))
1048
+
1049
+ self._initial_clean_params['nmajor'] = majorleft
1050
+ self._initial_clean_params['niter'] = iterleft
1051
+ self._initial_clean_params['cycleniter'] = self._init_values["cycleniter"]
1052
+ self._initial_clean_params['threshold'] = self._init_values["threshold"]
1053
+ self._initial_clean_params['cyclefactor'] = self._init_values["cyclefactor"]
1054
+ self._initial_clean_params['gain'] = self._init_values["gain"]
1055
+ self._initial_clean_params['nsigma'] = self._init_values["nsigma"]
1056
+
1057
+ self._init_values["convergence_state"]['convergence'][imid] = imdetails['converge']['chan']
1058
+ self._init_values["convergence_state"]['cyclethreshold'][imid] = imdetails['converge']['major']['cyclethreshold']
1059
+
1060
+ return (stopdesc, stopcode, majordone, majorleft, iterleft)
1061
+
1062
+
1063
+ self._clean['cmds'] = []
1064
+
1065
+ stopdesc, stopcode, majordone, majorleft, iterleft = initialize_tclean(self._clean['gclean'])
1066
+
1067
+
1068
+ self._clean['last-success'] = dict( result='converged' if stopcode[0] else 'update', stopcode=stopcode, cmd=self._clean['cmds'],
1069
+ convergence=self._init_values["convergence_state"]['convergence'],
1070
+ iterdone=0, iterleft=iterleft,
1071
+ majordone=majordone, majorleft=majorleft,
1072
+ cyclethreshold=self._init_values["convergence_state"]['cyclethreshold'],
1073
+ stopdesc=stopdesc )
1074
+
1075
+ ### Must occur AFTER initial "next" call to gclean(s)
1076
+ self._init_pipes()
1077
+
1078
+ @asynccontextmanager
1079
+ async def serve( self ):
1080
+ '''This function is intended for developers who would like to embed interactive
1081
+ clean as a part of a larger GUI. This embedded use of interactive clean is not
1082
+ currently supported and would require the addition of parameters to this function
1083
+ as well as changes to the interactive clean implementation. However, this function
1084
+ does expose the ``asyncio.Future`` that is used to signal completion of the
1085
+ interactive cleaning operation, and it provides the coroutines which must be
1086
+ managed by asyncio to make the interactive clean GUI responsive.
1087
+
1088
+ Example:
1089
+ Create ``iclean`` object, process events and retrieve result::
1090
+
1091
+ ic = iclean( vis='refim_point_withline.ms', imagename='test', imsize=512,
1092
+ cell='12.0arcsec', specmode='cube', interpolation='nearest', ... )
1093
+ async def process_events( ):
1094
+ async with ic.serve( ) as state:
1095
+ await state[0]
1096
+
1097
+ asyncio.run(process_events( ))
1098
+ print( "Result:", ic.result( ) )
1099
+
1100
+
1101
+ Returns
1102
+ -------
1103
+ (asyncio.Future, dictionary of coroutines)
1104
+ '''
1105
+ def start_http_server():
1106
+ import http.server
1107
+ import socketserver
1108
+ PORT = self._http_port
1109
+ DIRECTORY=self._webpage_path
1110
+
1111
+ class Handler(http.server.SimpleHTTPRequestHandler):
1112
+ def __init__(self, *args, **kwargs):
1113
+ super().__init__(*args, directory=DIRECTORY, **kwargs)
1114
+
1115
+ with socketserver.TCPServer(("", PORT), Handler) as httpd:
1116
+ print("\nServing Interactive Clean webpage from local directory: ", DIRECTORY)
1117
+ print("Use Control-C to stop Interactive clean.\n")
1118
+ print("Copy and paste one of the below URLs into your browser (Chrome or Firefox) to view:")
1119
+ print("http://localhost:"+str(PORT))
1120
+ print("http://127.0.0.1:"+str(PORT))
1121
+
1122
+ httpd.serve_forever()
1123
+
1124
+ self._launch_gui( )
1125
+
1126
+ async with CMC( *( [ ctx for img in self._clean_targets.keys( ) for ctx in
1127
+ [
1128
+ self._clean_targets[img]['gui']['cube'].serve(self.__stop),
1129
+ ]
1130
+ ] + [ websockets.serve( self._pipe['control'].process_messages,
1131
+ self._pipe['control'].address[0],
1132
+ self._pipe['control'].address[1] ),
1133
+ websockets.serve( self._clean['converge']['pipe'].process_messages,
1134
+ self._clean['converge']['pipe'].address[0],
1135
+ self._clean['converge']['pipe'].address[1] ) ]
1136
+ ) ):
1137
+ self.__result_future = asyncio.Future( )
1138
+ yield self.__result_future
1139
+
1140
+ def __retrieve_result( self ):
1141
+ '''If InteractiveClean had a return value, it would be filled in as part of the
1142
+ GUI dialog between Python and JavaScript and this function would return it'''
1143
+ if isinstance(self._error_result,Exception):
1144
+ raise self._error_result
1145
+ elif self._error_result is not None:
1146
+ return self._error_result
1147
+ return { k: v['converge'] for k,v in self._clean_targets.items( ) }
1148
+
1149
+ def result( self ):
1150
+ '''If InteractiveClean had a return value, it would be filled in as part of the
1151
+ GUI dialog between Python and JavaScript and this function would return it'''
1152
+ if self.__result_future is None:
1153
+ raise RuntimeError( 'no interactive clean result is available' )
1154
+
1155
+ self._clean['gclean'].restore( )
1156
+
1157
+ return self.__result_future.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.cmds( 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
+ }