##################### generated by xml-casa (v2) from h_export_calstate.xml #########
##################### 6ed8a366d50e0af757fb7a4b68580313 ##############################
from __future__ import absolute_import
from casashell.private.stack_manip import find_local as __sf__
from casashell.private.stack_manip import find_frame as _find_frame
from casatools.typecheck import validator as _pc
from casatools.coercetype import coerce as _coerce
from pipeline.h.cli import h_export_calstate as _h_export_calstate_t
from collections import OrderedDict
import numpy
import sys
import os
import shutil
[docs]def static_var(varname, value):
def decorate(func):
setattr(func, varname, value)
return func
return decorate
class _h_export_calstate:
"""
h_export_calstate ---- Save the pipeline calibration state to disk
h_export_calstate saves the current pipeline calibration state to disk
in the form of a set of equivalent applycal calls.
If filename is not given, h_export_calstate saves the calibration state to
disk with a filename based on the pipeline context creation time, using the
extension '.calstate'
One of two calibration states can be exported: either the active calibration
state (those calibrations currently applied on-the-fly but scheduled for
permanent application to the MeasurementSet in a subsequent hif_applycal
call) or the applied calibration state (calibrations that were previously
applied to the MeasurementSet using hif_applycal). The default is to export
the active calibration state.
Issues
If run several times in one pipeline session does the automatic export
file naming scheme, overwrite previous versions?
--------- parameter descriptions ---------------------------------------------
filename Name for saved calibration state
state The calibration state to export
--------- examples -----------------------------------------------------------
Example
1. Save the calibration state.
h_export_calstate()
2. Save the active calibration state with a custom filename
h_export_calstate(filename='afterbandpass.calstate')
3. Save the applied calibration state with a custom filename
h_export_calstate(filename='applied.calstate', state='applied')
"""
_info_group_ = """pipeline"""
_info_desc_ = """Save the pipeline calibration state to disk"""
__schema = {'filename': {'type': 'cStr', 'coerce': _coerce.to_str}, 'state': {'type': 'cStr', 'coerce': _coerce.to_str, 'allowed': [ 'active', 'applied' ]}}
def __init__(self):
self.__stdout = None
self.__stderr = None
self.__root_frame_ = None
def __globals_(self):
if self.__root_frame_ is None:
self.__root_frame_ = _find_frame( )
assert self.__root_frame_ is not None, "could not find CASAshell global frame"
return self.__root_frame_
def __to_string_(self,value):
if type(value) is str:
return "'%s'" % value
else:
return str(value)
def __validate_(self,doc,schema):
return _pc.validate(doc,schema)
def __do_inp_output(self,param_prefix,description_str,formatting_chars):
out = self.__stdout or sys.stdout
description = description_str.split( )
prefix_width = 23 + 8 + 4
output = [ ]
addon = ''
first_addon = True
while len(description) > 0:
## starting a new line.....................................................................
if len(output) == 0:
## for first line add parameter information............................................
if len(param_prefix)-formatting_chars > prefix_width - 1:
output.append(param_prefix)
continue
addon = param_prefix + ' #'
first_addon = True
addon_formatting = formatting_chars
else:
## for subsequent lines space over prefix width........................................
addon = (' ' * prefix_width) + '#'
first_addon = False
addon_formatting = 0
## if first word of description puts us over the screen width, bail........................
if len(addon + description[0]) - addon_formatting + 1 > self.term_width:
## if we're doing the first line make sure it's output.................................
if first_addon: output.append(addon)
break
while len(description) > 0:
## if the next description word puts us over break for the next line...................
if len(addon + description[0]) - addon_formatting + 1 > self.term_width: break
addon = addon + ' ' + description[0]
description.pop(0)
output.append(addon)
out.write('\n'.join(output) + '\n')
#--------- return nonsubparam values ----------------------------------------------
def __filename_dflt( self, glb ):
return ''
def __filename( self, glb ):
if 'filename' in glb: return glb['filename']
return ''
def __state_dflt( self, glb ):
return 'active'
def __state( self, glb ):
if 'state' in glb: return glb['state']
return 'active'
#--------- return inp/go default --------------------------------------------------
#--------- return subparam values -------------------------------------------------
#--------- subparam inp output ----------------------------------------------------
def __filename_inp(self):
description = 'Name for saved calibration state'
value = self.__filename( self.__globals_( ) )
(pre,post) = ('','') if self.__validate_({'filename': value},{'filename': self.__schema['filename']}) else ('\x1B[91m','\x1B[0m')
self.__do_inp_output('%-8.8s = %s%-23s%s' % ('filename',pre,self.__to_string_(value),post),description,0+len(pre)+len(post))
def __state_inp(self):
description = 'The calibration state to export'
value = self.__state( self.__globals_( ) )
(pre,post) = ('','') if self.__validate_({'state': value},{'state': self.__schema['state']}) else ('\x1B[91m','\x1B[0m')
self.__do_inp_output('%-8.8s = %s%-23s%s' % ('state',pre,self.__to_string_(value),post),description,0+len(pre)+len(post))
#--------- global default implementation-------------------------------------------
@static_var('state', __sf__('casa_inp_go_state'))
def set_global_defaults(self):
self.set_global_defaults.state['last'] = self
glb = self.__globals_( )
if 'filename' in glb: del glb['filename']
if 'state' in glb: del glb['state']
#--------- inp function -----------------------------------------------------------
def inp(self):
print("# h_export_calstate -- %s" % self._info_desc_)
self.term_width, self.term_height = shutil.get_terminal_size(fallback=(80, 24))
self.__filename_inp( )
self.__state_inp( )
#--------- tget function ----------------------------------------------------------
@static_var('state', __sf__('casa_inp_go_state'))
def tget(self,file=None):
from casashell.private.stack_manip import find_frame
from runpy import run_path
filename = None
if file is None:
if os.path.isfile("h_export_calstate.last"):
filename = "h_export_calstate.last"
elif isinstance(file, str):
if os.path.isfile(file):
filename = file
if filename is not None:
glob = find_frame( )
newglob = run_path( filename, init_globals={ } )
for i in newglob:
glob[i] = newglob[i]
self.tget.state['last'] = self
else:
print("could not find last file, setting defaults instead...")
self.set_global_defaults( )
def __call__( self, filename=None, state=None ):
def noobj(s):
if s.startswith('<') and s.endswith('>'):
return "None"
else:
return s
_prefile = os.path.realpath('h_export_calstate.pre')
_postfile = os.path.realpath('h_export_calstate.last')
_return_result_ = None
_arguments = [filename,state]
_invocation_parameters = OrderedDict( )
if any(map(lambda x: x is not None,_arguments)):
# invoke python style
# set the non sub-parameters that are not None
local_global = { }
if filename is not None: local_global['filename'] = filename
if state is not None: local_global['state'] = state
# the invocation parameters for the non-subparameters can now be set - this picks up those defaults
_invocation_parameters['filename'] = self.__filename( local_global )
_invocation_parameters['state'] = self.__state( local_global )
# the sub-parameters can then be set. Use the supplied value if not None, else the function, which gets the appropriate default
else:
# invoke with inp/go semantics
_invocation_parameters['filename'] = self.__filename( self.__globals_( ) )
_invocation_parameters['state'] = self.__state( self.__globals_( ) )
try:
with open(_prefile,'w') as _f:
for _i in _invocation_parameters:
_f.write("%-8s = %s\n" % (_i,noobj(repr(_invocation_parameters[_i]))))
_f.write("#h_export_calstate( ")
count = 0
for _i in _invocation_parameters:
_f.write("%s=%s" % (_i,noobj(repr(_invocation_parameters[_i]))))
count += 1
if count < len(_invocation_parameters): _f.write(",")
_f.write(" )\n")
except: pass
try:
_return_result_ = _h_export_calstate_t( _invocation_parameters['filename'],_invocation_parameters['state'] )
except Exception as e:
from traceback import format_exc
from casatasks import casalog
casalog.origin('h_export_calstate')
casalog.post("Exception Reported: Error in h_export_calstate: %s" % str(e),'SEVERE')
casalog.post(format_exc( ))
_return_result_ = False
try:
os.rename(_prefile,_postfile)
except: pass
return _return_result_
h_export_calstate = _h_export_calstate( )