Changeset 226


Ignore:
Timestamp:
01/19/05 18:24:16 (19 years ago)
Author:
mar637
Message:

added rcParams to support rc style default parameters, read from .asaprc

Location:
trunk/python
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • trunk/python/__init__.py

    r210 r226  
    33
    44"""
    5 #import _asap
    6 #from asaplot import ASAPlot
     5import os,sys
     6
     7def validate_bool(b):
     8    'Convert b to a boolean or raise'
     9    bl = b.lower()
     10    if bl in ('f', 'no', 'false', '0', 0): return False
     11    elif bl in ('t', 'yes', 'true', '1', 1): return True
     12    else:
     13        raise ValueError('Could not convert "%s" to boolean' % b)
     14
     15def validate_int(s):
     16    'convert s to int or raise'
     17    try: return int(s)
     18    except ValueError:
     19        raise ValueError('Could not convert "%s" to int' % s)
     20
     21def asap_fname():
     22    """
     23    Return the path to the rc file
     24
     25    Search order:
     26
     27     * current working dir
     28     * environ var ASAPRC
     29     * HOME/.matplotlibrc
     30     
     31    """
     32
     33    fname = os.path.join( os.getcwd(), '.asaprc')
     34    if os.path.exists(fname): return fname
     35
     36    if os.environ.has_key('ASAPRC'):
     37        path =  os.environ['ASAPRC']
     38        if os.path.exists(path):
     39            fname = os.path.join(path, '.asaprc')
     40            if os.path.exists(fname):
     41                return fname
     42
     43    if os.environ.has_key('HOME'):
     44        home =  os.environ['HOME']
     45        fname = os.path.join(home, '.asaprc')
     46        if os.path.exists(fname):
     47            return fname
     48    return None
     49       
     50
     51defaultParams = {
     52    # general
     53    'verbose'             : [True, validate_bool],
     54    'useplotter'          : [True, validate_bool],
     55
     56    # plotting
     57    'plotter.stacking'    : ['p', str],
     58    'plotter.panelling'   : ['s', str],
     59
     60    # scantable
     61    'scantable.save'      : ['ASAP', str],
     62    'scantable.autoaverage'      : [True, validate_bool],
     63    'scantable.freqframe' : ['LSRK', str],  #default frequency frame
     64    'scantable.allaxes'   : [True, validate_bool],  # apply action to all axes
     65    'scantable.plotter'   : [True, validate_bool], # use internal plotter
     66
     67    # math
     68    'math.insitu'         : [False, validate_bool],
     69
     70    # fitter
     71    'fitter.polyorder'    : [0, validate_int],
     72    'fitter.ncomponents'  : [1, validate_int]
     73    }
     74
     75def rc_params():
     76    'Return the default params updated from the values in the rc file'
     77   
     78    fname = asap_fname()
     79   
     80    if fname is None or not os.path.exists(fname):
     81        message = 'could not find rc file; returning defaults'
     82        ret =  dict([ (key, tup[0]) for key, tup in defaultParams.items()])
     83        #print message
     84        return ret
     85       
     86    cnt = 0
     87    for line in file(fname):
     88        cnt +=1
     89        line = line.strip()
     90        if not len(line): continue
     91        if line.startswith('#'): continue
     92        tup = line.split(':',1)
     93        if len(tup) !=2:
     94            print ('Illegal line #%d\n\t%s\n\tin file "%s"' % (cnt, line, fname))
     95            continue
     96       
     97        key, val = tup
     98        key = key.strip()
     99        if not defaultParams.has_key(key):
     100            print ('Bad key "%s" on line %d in %s' % (key, cnt, fname))
     101            continue
     102       
     103        default, converter =  defaultParams[key]
     104
     105        ind = val.find('#')
     106        if ind>=0: val = val[:ind]   # ignore trailing comments
     107        val = val.strip()
     108        try: cval = converter(val)   # try to convert to proper type or raise
     109        except Exception, msg:
     110            print ('Bad val "%s" on line #%d\n\t"%s"\n\tin file "%s"\n\t%s' % (val, cnt, line, fname, msg))
     111            continue
     112        else:
     113            # Alles Klar, update dict
     114            defaultParams[key][0] = cval
     115
     116    # strip the conveter funcs and return
     117    ret =  dict([ (key, tup[0]) for key, tup in defaultParams.items()])
     118    verbose.report('loaded rc file %s'%fname)
     119
     120    return ret
     121
     122
     123# this is the instance used by the asap classes
     124rcParams = rc_params()
     125
     126rcParamsDefault = dict(rcParams.items()) # a copy
     127
     128def rc(group, **kwargs):
     129    """
     130    Set the current rc params.  Group is the grouping for the rc, eg
     131    for lines.linewidth the group is 'lines', for axes.facecolor, the
     132    group is 'axes', and so on.  kwargs is a list of attribute
     133    name/value pairs, eg
     134
     135      rc('lines', linewidth=2, color='r')
     136
     137    sets the current rc params and is equivalent to
     138   
     139      rcParams['lines.linewidth'] = 2
     140      rcParams['lines.color'] = 'r'
     141
     142
     143    Note you can use python's kwargs dictionary facility to store
     144    dictionaries of default parameters.  Eg, you can customize the
     145    font rc as follows
     146
     147      font = {'family' : 'monospace',
     148              'weight' : 'bold',
     149              'size'   : 'larger',
     150             }
     151
     152      rc('font', **font)  # pass in the font dict as kwargs
     153
     154    This enables you to easily switch between several configurations.
     155    Use rcdefaults to restore the default rc params after changes.
     156    """
     157
     158    aliases = {
     159        }
     160   
     161    for k,v in kwargs.items():
     162        name = aliases.get(k) or k
     163        key = '%s.%s' % (group, name)
     164        if not rcParams.has_key(key):
     165            raise KeyError('Unrecognized key "%s" for group "%s" and name "%s"' % (key, group, name))
     166       
     167        rcParams[key] = v
     168
     169
     170def rcdefaults():
     171    """
     172    Restore the default rc params - the ones that were created at
     173    asap load time
     174    """
     175    rcParams.update(rcParamsDefault)
     176
    7177from asapfitter import *
    8178from asapreader import reader
    9179from asapmath import *
    10180from scantable import *
    11 print "Initialising plotter..."
    12 from asapplotter import *
    13 plotter = asapplotter()
     181if rcParams['useplotter']:
     182    print "Initialising plotter..."
     183    from asapplotter import *
     184    plotter = asapplotter()
    14185#from numarray ones,zeros
    15186
  • trunk/python/asaplot.py

    r202 r226  
    77import Tkinter as Tk
    88
    9 print "Importing matplotlib with TkAgg backend."
     9#print "Importing matplotlib with TkAgg backend."
    1010import matplotlib
    1111matplotlib.use("TkAgg")
  • trunk/python/asapplotter.py

    r203 r226  
    11from asap.asaplot import ASAPlot
     2from asap import rcParams
    23
    34class asapplotter:
     5    """
     6    The ASAP plotter.
     7    By default the plotter is set up to plot polarisations
     8    'colour stacked' and scantables across panels.
     9    The defaul plotter is called 'plotter'.
     10    Note:
     11        Currenly it only plots 'spectra' not Tsys or
     12        other variables.
     13    """
    414    def __init__(self):
    5         """
    6         The ASAP plotter.
    7         By default the plotter is set up to plot polarisations
    8         'colour stacked' and scantables across panels.
    9         The defaul plotter is called 'plotter'.
    10         Note:
    11             Currenly it only plots 'spectra' not Tsys or
    12             other variables.
    13        
    14         """
    1515        self._plotter = ASAPlot()
    1616
     
    3333                       self._sdict]
    3434        self._panels = 's'
    35         self._stacking = 'p'
     35        self._stacking = rcParams['plotter.stacking']
    3636        self._autoplot = False
    3737        self._minmax = None
    3838        self._data = None
    3939        self._lmap = []
     40        self._title = None
    4041
    4142    def _translate(self, name):
     
    9798                y = None
    9899                m = None
    99                 tlab = scan._getsourcename(i)
     100                if not self._title:
     101                    tlab = scan._getsourcename(i)                   
     102                else:
     103                    if len(self._title) == n:
     104                        tlab = self._title[i]
     105                    else:
     106                        tlab = scan._getsourcename(i)                   
    100107                x,xlab = scan.get_abcissa(i)
    101108                y = scan.getspectrum(i)
    102109                ylab = 'Flux ('+scan.get_fluxunit()+')'
    103110                m = scan.getmask(i)
    104                 if len(self._lmap) > 0:
     111                if self._lmap and len(self._lmap) > 0:
    105112                    llab = self._lmap[j]
    106113                else:
     
    138145                y = None
    139146                m = None
    140                 tlab = scan._getsourcename()
     147                tlab = self._title
     148                if not self._title:
     149                    tlab = scan._getsourcename()
    141150                x,xlab = scan.get_abcissa()
    142151                y = scan.getspectrum()
     
    194203                m = scan.getmask(k)
    195204                if colmode == 's' or colmode == 't':
    196                     tlab = self._ldict.get(self._panels)+' '+str(i)
     205                    if not self._title:
     206                        tlab = self._ldict.get(self._panels)+' '+str(i)
     207                    else:
     208                        if len(self.title) == n:
     209                            tlab = self._title[i]
     210                        else:
     211                            tlab = self._ldict.get(self._panels)+' '+str(i)
    197212                    llab = scan._getsourcename(k)
    198213                else:
    199                     tlab = scan._getsourcename(k)
    200                     if len(self._lmap) > 0:
     214                    if self._title and len(self._title) > 0:
     215                        tlab = self._title[k]
     216                    else:
     217                        tlab = scan._getsourcename(k)
     218                    if self._lmap and len(self._lmap) > 0:
    201219                        llab = self._lmap[j]
    202220                    else:
     
    214232
    215233
    216     def set_mode(self, stacking='pol', panelling='scan'):
     234    def set_mode(self, stacking=None, panelling=None):
    217235        """
    218236        Parameters:
     
    231249        if not self.set_panels(panelling):
    232250            print "Invalid mode"
     251            return
    233252        if not self.set_stacking(stacking):
    234253            print "Invalid mode"
    235         return
    236 
    237     def set_panels(self, what='scan'):       
     254            return
     255        if self._data: self.plot()
     256        return
     257
     258    def set_panels(self, what=None):       
     259        if not what:
     260             what = rcParams['plotter.panelling']
    238261        md = self._translate(what)
    239262        if md:
    240             self._panels = md       
     263            self._panels = md
     264            self._title = None
    241265            return True
    242266        return False
    243267
    244     def set_stacking(self, what='pol'):       
     268    def set_stacking(self, what=None): 
     269        if not what:
     270             what = rcParams['plotter.stacking']       
    245271        md = self._translate(what)
    246272        if md:
    247273            self._stacking = md
     274            self._lmap = None
    248275            return True
    249276        return False
     
    261288        if start is None and end is None:
    262289            self._minmax = None
    263             if self._data is not None:
    264                 self.plot()
     290            if self._data: self.plot()
    265291        else:
    266292            self._minmax = [start,end]
    267             if self._data is not None:
    268                 self.plot()
     293            if self._data: self.plot()
    269294        return
    270295   
    271     def set_legend_map(self,mp=[]):
     296    def set_legend_map(self, mp=[]):
    272297        """
    273298        Specify a mapping for the legend instead of using the default
     
    286311        """
    287312        self._lmap = mp
    288        
     313        if self._data: self.plot()
     314        return
     315
     316    def set_title(self, title=None):
     317        self._title = title
     318        if self._data: self.plot()
     319        return
     320
    289321if __name__ == '__main__':
    290322    plotter = asapplotter()
  • trunk/python/scantable.py

    r200 r226  
    11from asap._asap import sdtable
     2from asap import rcParams
    23from numarray import ones,zeros
    34import sys
     
    2122                         scantable
    2223        """
    23         self._vb = True
     24        self._vb = rcParams['verbose']
    2425        self._p = None
    2526        from os import stat as st
     
    2829            sdtable.__init__(self, filename)           
    2930        else:
    30             mode = st(filename)[stat.ST_MODE]
     31            try:
     32                mode = st(filename)[stat.ST_MODE]
     33            except OSError:
     34                print "File not found"
     35                return
    3136            if stat.S_ISDIR(mode):
    3237                # crude check if asap table
     
    3540                else:
    3641                    print 'The given file is not a valid asap table'
    37             else:           
     42                    return
     43            else:
     44                autoav = rcParams['scantable.autoaverage']
     45
    3846                from asap._asap import sdreader
    3947                r = sdreader(filename)
     
    4149                r.read([-1])
    4250                tbl = r.getdata()
    43                
    44                 from asap._asap import average
    45                 tmp = tuple([tbl])
    46                 print 'Auto averging integrations...'
    47                 tbl2 = average(tmp,(),True,'none')
    48                 sdtable.__init__(self,tbl2)
    49                 del r,tbl
    50 
    51     def save(self, name="", format='ASAP'):
     51                if autoav:
     52                    from asap._asap import average
     53                    tmp = tuple([tbl])
     54                    print 'Auto averaging integrations...'
     55                    tbl2 = average(tmp,(),True,'none')
     56                    sdtable.__init__(self,tbl2)
     57                    del r,tbl
     58                else:
     59                    sdtable.__init__(self,tbl)
     60
     61    def save(self, name="", format=None):
    5262        """
    5363        Store the scantable on disk. This can be a asap file or SDFITS/MS2.
     
    6070                                       'FITS' (saves each row as a FITS Image)
    6171                                       'ASCII' (saves as ascii text file)
    62                                        'MS2' (saves as an aips++ MeasurementSet V2)
     72                                       'MS2' (saves as an aips++
     73                                              MeasurementSet V2)
    6374        Example:
    6475            scan.save('myscan.asap')
    6576            scan.save('myscan.sdfits','SDFITS')
    6677        """
     78        if format is None: format = rcParams['scantable.save']
    6779        if format == 'ASAP':
    6880            self._save(name)
     
    7284            w.write(self, name)
    7385        return
    74 
    75     def _verbose(self, *args):
    76         """
    77         Set the verbose level True or False, to indicate if output
    78         should be printed as well as returned.
    79         """
    80         if len(args) == 0:
    81             return self._vb
    82         elif type(args[0]) is bool:
    83             self._vb = args[0]
    84             return
    8586
    8687    def copy(self):
     
    166167            print " Cursor selection"
    167168            print "--------------------------------------------------"
    168             out = 'Beam=%d IF=%d Pol=%d '% (i,j,k)
     169            out = 'Beam=%d IF=%d Pol=%d ' % (i,j,k)
    169170            print out
    170171        return i,j,k
    171172
    172     def stats(self, stat='stddev', mask=None, all=True):
     173    def stats(self, stat='stddev', mask=None, all=None):
    173174        """
    174175        Determine the specified statistic of the current beam/if/pol
     
    180181            mask:    an optional mask specifying where the statistic
    181182                     should be determined.
    182             all:     optional flag to show all (default) or a selected
    183                      spectrum of Beam/IF/Pol
     183            all:     optional flag to show all (default or .asaprc) or a
     184                     cursor selected spectrum of Beam/IF/Pol
    184185
    185186        Example:
     
    188189            scan.stats(stat='mean', mask=m)
    189190        """
     191        if all is None: all = rcParams['scantable.allaxes']
    190192        from asap._asap import stats as _stats
    191193        if mask == None:
     
    210212                            out += '= %3.3f\n' % (statval[l])
    211213                out += "--------------------------------------------------\n"
    212 
    213214            if self._vb:
    214215                print "--------------------------------------------------"
     
    232233                out += '= %3.3f\n' % (statval[l])
    233234                out +=  "--------------------------------------------------\n"
     235
    234236            if self._vb:
    235237                print "--------------------------------------------------"
     
    239241            return statval
    240242
    241     def stddev(self,mask=None, all=True):
     243    def stddev(self,mask=None, all=None):
    242244        """
    243245        Determine the standard deviation of the current beam/if/pol
     
    247249            mask:    an optional mask specifying where the standard
    248250                     deviation should be determined.
    249             all:     optional flag to show all or a selected
    250                      spectrum of Beam/IF/Pol
     251            all:     optional flag to show all or a cursor selected
     252                     spectrum of Beam/IF/Pol. Default is all or taken
     253                     from .asaprc
    251254
    252255        Example:
     
    255258            scan.stddev(mask=m)
    256259        """
     260        if all is None: all = rcParams['scantable.allaxes']
    257261        return self.stats(stat='stddev',mask=mask, all=all);
    258262
    259     def get_tsys(self, all=True):
     263    def get_tsys(self, all=None):
    260264        """
    261265        Return the System temperatures.
     
    268272            a list of Tsys values.
    269273        """
     274        if all is None: all = rcParams['scantable.allaxes']
    270275        if all:
    271276            out = ''
     
    287292                            out += '= %3.3f\n' % (ts[l])
    288293                out+= "--------------------------------------------------\n"
    289 
    290294            if self._vb:
    291295                print "--------------------------------------------------"
     
    308312                out += '= %3.3f\n' % (ts[l])
    309313                out += "--------------------------------------------------\n"
    310 
    311314            if self._vb:
    312315                print "--------------------------------------------------"
     
    345348        if self._p: self.plot()
    346349
    347     def set_freqframe(self, frame='LSRK'):
     350    def set_freqframe(self, frame=None):
    348351        """
    349352        Set the frame type of the Spectral Axis.
     
    353356            scan.set_freqframe('BARY')
    354357        """
     358        if not frame: frame = rcParams['scantable.freqframe']
    355359        valid = ['REST','TOPO','LSRD','LSRK','BARY', \
    356360                   'GEO','GALACTO','LGROUP','CMB']
     
    379383        selected Beam/IF/Pol
    380384        Parameters:
    381             none
     385            rowno:    an optional row number in the scantable. Default is the
     386                      first row, i.e. rowno=0
    382387        Returns:
    383388            The abcissa values and it's format string.
     
    501506            self._p.set_panels(rows=npan)
    502507        xlab,ylab,tlab = None,None,None
    503         vb = self._verbose()
    504         self._verbose(False)
    505         sel = self.get_selection()
     508        self._vb = False
     509        sel = self.get_selection()       
    506510        for i in range(npan):
    507             self._p.subplot(i)
     511            if npan > 1:
     512                self._p.subplot(i)
    508513            for j in range(validcol[col]):
    509514                x = None
     
    540545        self._p.release()
    541546        self.set_selection(sel[0],sel[1],sel[2])
    542         self._verbose(vb)
     547        self._vb = rcParams['verbose']
    543548        return
Note: See TracChangeset for help on using the changeset viewer.