Changeset 1826


Ignore:
Timestamp:
08/03/10 11:41:13 (14 years ago)
Author:
Malte Marquarding
Message:

Tidy up of imports (now imported from asap.). Also fixed some whitespace/tab issues

Location:
trunk/python
Files:
15 edited

Legend:

Unmodified
Added
Removed
  • trunk/python/asapfit.py

    r1232 r1826  
    11from _asap import fitentry
    2 from asap import rcParams
     2from asap.parameters import rcParams
    33
    44class asapfit(fitentry):
  • trunk/python/asapfitter.py

    r1819 r1826  
    11import _asap
    2 from asap import rcParams
    3 from asap import print_log, print_log_dec
    4 from asap import _n_bools
    5 from asap import mask_and
    6 from asap import asaplog
     2from asap.parameters import rcParams
     3from asap.logging import asaplog, print_log, print_log_dec
     4from asap.utils import _n_bools, mask_and
     5
    76
    87class fitter:
     
    697696            scan = self.data
    698697        rows = xrange(scan.nrow())
    699         # Save parameters of baseline fits as a class attribute. 
     698        # Save parameters of baseline fits as a class attribute.
    700699        # NOTICE: This does not reflect changes in scantable!
    701700        if len(rows) > 0: self.blpars=[]
  • trunk/python/asaplinefind.py

    r1644 r1826  
    7171                                       in the noise box (default)
    7272                              'median' median of deviations in the noise box
    73                              
     73
    7474        Note:  For bad baselines threshold should be increased,
    7575               and avg_limit decreased (or even switched off completely by
  • trunk/python/asaplot.py

    r1819 r1826  
    1313    """
    1414    def __init__(self, rows=1, cols=0, title='', size=None, buffering=False):
    15         """
    16         Create a new instance of the ASAPlot plotting class.
     15        """
     16        Create a new instance of the ASAPlot plotting class.
    1717
    18         If rows < 1 then a separate call to set_panels() is required to define
    19         the panel layout; refer to the doctext for set_panels().
    20         """
     18        If rows < 1 then a separate call to set_panels() is required to define
     19        the panel layout; refer to the doctext for set_panels().
     20        """
    2121        v = vars()
    2222        del v['self']
  • trunk/python/asaplotbase.py

    r1819 r1826  
    55import sys
    66from re import match
    7 
    87import matplotlib
    98
     
    1211from numpy import sqrt
    1312from matplotlib import rc, rcParams
    14 from asap import rcParams as asaprcParams
    1513from matplotlib.ticker import OldScalarFormatter
     14
     15from asap.parameters import rcParams as asaprcParams
     16from asap.logging import asaplog
    1617
    1718# API change in mpl >= 0.98
     
    2122    from matplotlib.transforms import blend_xy_sep_transform as blended_transform_factory
    2223
    23 from asap import asaplog
    24 
    25 if int(matplotlib.__version__.split(".")[1]) < 87:
     24if int(matplotlib.__version__.split(".")[1]) < 99:
    2625    #print "Warning: matplotlib version < 0.87. This might cause errors. Please upgrade."
    27     asaplog.push( "matplotlib version < 0.87. This might cause errors. Please upgrade." )
     26    asaplog.push( "matplotlib version < 0.99. This might cause errors. Please upgrade." )
    2827    print_log( 'WARN' )
    2928
     
    316315            self.figmgr.toolbar.draw_rubberband(event, event.x, event.y,
    317316                                                self.rect['x'], self.rect['y'])
    318            
     317
    319318        def region_disable(event):
    320319            self.register('motion_notify', None)
     
    655654                                                cols, i+1)
    656655                        if asaprcParams['plotter.axesformatting'] != 'mpl':
    657                            
     656
    658657                            self.subplots[i]['axes'].xaxis.set_major_formatter(OldScalarFormatter())
    659658                    else:
  • trunk/python/asaplotgui.py

    r1819 r1826  
    1717
    1818    def __init__(self, rows=1, cols=0, title='', size=None, buffering=False):
    19         """
    20         Create a new instance of the ASAPlot plotting class.
     19        """
     20        Create a new instance of the ASAPlot plotting class.
    2121
    22         If rows < 1 then a separate call to set_panels() is required to define
    23         the panel layout; refer to the doctext for set_panels().
    24         """
     22        If rows < 1 then a separate call to set_panels() is required to define
     23        the panel layout; refer to the doctext for set_panels().
     24        """
    2525        v = vars()
    2626        del v['self']
     
    4949
    5050    def map(self):
    51         """
    52         Reveal the ASAPlot graphics window and bring it to the top of the
    53         window stack.
    54         """
    55         self.window.wm_deiconify()
    56         self.window.lift()
     51        """
     52        Reveal the ASAPlot graphics window and bring it to the top of the
     53        window stack.
     54        """
     55        self.window.wm_deiconify()
     56        self.window.lift()
    5757
    5858    def quit(self):
    59         """
    60         Destroy the ASAPlot graphics window.
    61         """
    62         self.window.destroy()
     59        """
     60        Destroy the ASAPlot graphics window.
     61        """
     62        self.window.destroy()
    6363
    6464    def show(self, hardrefresh=True):
    65         """
    66         Show graphics dependent on the current buffering state.
    67         """
    68         if not self.buffering:
     65        """
     66        Show graphics dependent on the current buffering state.
     67        """
     68        if not self.buffering:
    6969            if hardrefresh:
    7070                asaplotbase.show(self)
    71             self.window.wm_deiconify()
    72             self.canvas.show()
     71            self.window.wm_deiconify()
     72            self.canvas.show()
    7373
    7474    def terminate(self):
    75         """
    76         Clear the figure.
    77         """
    78         self.window.destroy()
     75        """
     76        Clear the figure.
     77        """
     78        self.window.destroy()
    7979
    8080    def unmap(self):
    81         """
    82         Hide the ASAPlot graphics window.
    83         """
    84         self.window.wm_withdraw()
     81        """
     82        Hide the ASAPlot graphics window.
     83        """
     84        self.window.wm_withdraw()
  • trunk/python/asapmath.py

    r1819 r1826  
    11from asap.scantable import scantable
    2 from asap import rcParams
    3 from asap import print_log, print_log_dec
    4 from asap import selector
    5 from asap import asaplog
     2from asap.paramaters import rcParams
     3from asap.logging import asaplog, print_log, print_log_dec
     4from asap.selector import selector
    65from asap import asaplotgui
    76
     
    937936    """
    938937    Calibrate data.
    939    
     938
    940939    Parameters:
    941940        scantab:       scantable
    942941        scannos:       list of scan number
    943942        calmode:       calibration mode
    944         verify:        verify calibration     
     943        verify:        verify calibration
    945944    """
    946945    antname = scantab.get_antennaname()
     
    979978        scal = scantab.copy()
    980979
    981     return scal 
     980    return scal
    982981
    983982def apexcal( scantab, scannos=[], calmode='none', verify=False ):
     
    990989        calmode:       calibration mode
    991990
    992         verify:        verify calibration     
     991        verify:        verify calibration
    993992    """
    994993    from asap._asap import stmath
     
    10081007        calmode:       calibration mode
    10091008
    1010         verify:        verify calibration     
     1009        verify:        verify calibration
    10111010    """
    10121011    from asap._asap import stmath
     
    10201019    Split Measurement set by antenna name, save data as a scantables,
    10211020    and return a list of filename.
    1022     Notice this method can only be available from CASA. 
     1021    Notice this method can only be available from CASA.
    10231022    Prameter
    1024        filename:    the name of Measurement set to be read. 
     1023       filename:    the name of Measurement set to be read.
    10251024       outprefix:   the prefix of output scantable name.
    10261025                    the names of output scantable will be
     
    10301029                    The default False is to return with warning
    10311030                    without writing the output. USE WITH CARE.
    1032                    
     1031
    10331032    """
    10341033    # Import the table toolkit from CASA
     
    10711070        if not os.path.isdir(filename) \
    10721071               or not os.path.exists(filename+'/ANTENNA') \
    1073                or not os.path.exists(filename+'/table.f1'): 
     1072               or not os.path.exists(filename+'/table.f1'):
    10741073            s = "File '%s' is not a Measurement set." % (filename)
    10751074            if rcParams['verbose']:
     
    11191118    value:   float list operand
    11201119    mode:    operation mode (ADD, SUB, MUL, DIV)
    1121     tsys:    if True, operate tsys as well 
     1120    tsys:    if True, operate tsys as well
    11221121    """
    11231122    nrow = scan.nrow()
     
    11341133        from asap._asap import stmath
    11351134        stm = stmath()
    1136         # insitu must be True 
     1135        # insitu must be True
    11371136        stm._setinsitu( True )
    11381137        s = scan.copy()
     
    11501149        del stm
    11511150    return s
    1152 
    1153            
    1154            
  • trunk/python/asapreader.py

    r1819 r1826  
    11from asap._asap import stfiller
    2 from asap import print_log, print_log_dec
     2from asap.logging import print_log, print_log_dec
    33
    44class reader(stfiller):
  • trunk/python/casatoolbar.py

    r1819 r1826  
    1010
    1111    ### select the nearest spectrum in pick radius
    12     ###    and display spectral value on the toolbar. 
     12    ###    and display spectral value on the toolbar.
    1313    def _select_spectrum(self,event):
    1414        # Do not fire event when in zooming/panning mode
    1515        mode = self.figmgr.toolbar.mode
    16         if not mode =='':
    17                 return
    18         # When selected point is out of panels
     16        if not mode == '':
     17            return
     18            # When selected point is out of panels
    1919        if event.inaxes == None:
    20                 return
     20            return
    2121        # If not left button
    2222        if event.button != 1:
    23                 return
     23            return
    2424
    2525        xclick=event.xdata
     
    2727        dist2=1000.
    2828        pickline=None
    29         # If the pannel has picable objects
    30         pflag=False
     29        # If the pannel has picable objects
     30        pflag=False
    3131        for lin in event.inaxes.lines:
    32                 if not lin.pickable(): continue
    33                 pflag=True
    34                 flag,pind = lin.contains(event)
    35                 if not flag: continue
    36                 # Get nearest point
    37                 inds = pind['ind']
    38                 xlin = lin.get_xdata()
    39                 ylin = lin.get_ydata()
    40                 for i in inds:
    41                         d2=(xlin[i]-xclick)**2+(ylin[i]-yclick)**2
    42                         if dist2 >= d2:
    43                                 dist2 = d2
    44                                 pickline = lin
    45         # No pickcable line in the pannel
    46         if not pflag: return
    47         # Pickable but too far from mouse position
    48         elif pickline is None:
    49                 picked='No line selected.'
    50                 self.figmgr.toolbar.set_message(picked)
    51                 return
     32            if not lin.pickable():
     33                continue
     34            pflag=True
     35            flag,pind = lin.contains(event)
     36            if not flag:
     37                continue
     38            # Get nearest point
     39            inds = pind['ind']
     40            xlin = lin.get_xdata()
     41            ylin = lin.get_ydata()
     42            for i in inds:
     43                d2=(xlin[i]-xclick)**2+(ylin[i]-yclick)**2
     44                if dist2 >= d2:
     45                    dist2 = d2
     46                    pickline = lin
     47        # No pickcable line in the pannel
     48        if not pflag:
     49            return
     50        # Pickable but too far from mouse position
     51        elif pickline is None:
     52            picked='No line selected.'
     53            self.figmgr.toolbar.set_message(picked)
     54            return
    5255        del pind, inds, xlin, ylin
    53         # Spectra are Picked
     56        # Spectra are Picked
    5457        theplot = self.plotter._plotter
    55         thetoolbar = self.figmgr.toolbar
    56         thecanvas = self.figmgr.canvas
    57         # Disconnect the default motion notify event
    58         # Notice! the other buttons are also diabled!!!
    59         thecanvas.mpl_disconnect(thetoolbar._idDrag)
     58        thetoolbar = self.figmgr.toolbar
     59        thecanvas = self.figmgr.canvas
     60        # Disconnect the default motion notify event
     61        # Notice! the other buttons are also diabled!!!
     62        thecanvas.mpl_disconnect(thetoolbar._idDrag)
    6063        # Get picked spectrum
    6164        xdata = pickline.get_xdata()
     
    6467        titp=event.inaxes.title.get_text()
    6568        panel0=event.inaxes
    66         picked="Selected: '"+titl+"' in panel '"+titp+"'."
    67         thetoolbar.set_message(picked)
    68         # Generate a navigation window
     69        picked="Selected: '"+titl+"' in panel '"+titp+"'."
     70        thetoolbar.set_message(picked)
     71        # Generate a navigation window
    6972        #naviwin=Navigationwindow(titp,titl)
    7073        #------------------------------------------------------#
    7174        # Show spectrum data at mouse position
    7275        def spec_data(event):
    73                 # Getting spectrum data of neiboring point
    74                 xclick=event.xdata
    75                 if event.inaxes != panel0:
    76                         return
    77                 ipoint=len(xdata)-1
    78                 for i in range(len(xdata)-1):
    79                         xl=xclick-xdata[i]
    80                         xr=xclick-xdata[i+1]
    81                         if xl*xr <= 0.:
    82                                 ipoint = i
    83                                 break
    84                 # Output spectral value on the navigation window
    85                 posi='[ %s, %s ]:  x = %.2f   value = %.2f'\
    86                       %(titl,titp,xdata[ipoint],ydata[ipoint])
    87                 #naviwin.posi.set(posi)
    88                 thetoolbar.set_message(posi)
     76            # Getting spectrum data of neiboring point
     77            xclick=event.xdata
     78            if event.inaxes != panel0:
     79                return
     80            ipoint=len(xdata)-1
     81            for i in range(len(xdata)-1):
     82                xl=xclick-xdata[i]
     83                xr=xclick-xdata[i+1]
     84                if xl*xr <= 0.:
     85                    ipoint = i
     86                    break
     87            # Output spectral value on the navigation window
     88            posi='[ %s, %s ]:  x = %.2f   value = %.2f'\
     89                  %(titl,titp,xdata[ipoint],ydata[ipoint])
     90            #naviwin.posi.set(posi)
     91            thetoolbar.set_message(posi)
    8992        #------------------------------------------------------#
    9093        # Disconnect from mouse events
    9194        def discon(event):
    92                 #naviwin.window.destroy()
    93                 theplot.register('motion_notify',None)
    94                 # Re-activate the default motion_notify_event
    95                 thetoolbar._idDrag=thecanvas.mpl_connect('motion_notify_event', thetoolbar.mouse_move)
    96                 theplot.register('button_release',None)
    97                 return
     95            #naviwin.window.destroy()
     96            theplot.register('motion_notify',None)
     97            # Re-activate the default motion_notify_event
     98            thetoolbar._idDrag=thecanvas.mpl_connect('motion_notify_event',
     99                                                     thetoolbar.mouse_move)
     100            theplot.register('button_release',None)
     101            return
    98102        #------------------------------------------------------#
    99103        # Show data value along with mouse movement
    100         theplot.register('motion_notify',spec_data)
     104        theplot.register('motion_notify',spec_data)
    101105        # Finish events when mouse button is released
    102106        theplot.register('button_release',discon)
    103107
    104108
    105     ### Calculate statistics of the selected area. 
     109    ### Calculate statistics of the selected area.
    106110    def _single_mask(self,event):
    107111        # Do not fire event when in zooming/panning mode
    108         if not self.figmgr.toolbar.mode == '': return
     112        if not self.figmgr.toolbar.mode == '':
     113            return
    109114        # When selected point is out of panels
    110115        if event.inaxes == None:
    111                 return
    112         if event.button ==1: baseinv=True
    113         elif event.button == 3: baseinv=False
    114         else: return
    115 
    116         def _calc_stats():
    117                 msk=mymask.get_mask()
    118                 mymask.scan.stats(stat='max',mask=msk)
    119                 mymask.scan.stats(stat='min',mask=msk)
    120                 mymask.scan.stats(stat='sum',mask=msk)
    121                 mymask.scan.stats(stat='mean',mask=msk)
    122                 mymask.scan.stats(stat='median',mask=msk)
    123                 mymask.scan.stats(stat='rms',mask=msk)
    124                 mymask.scan.stats(stat='stddev',mask=msk)
    125 
    126         # Interactive mask definition
     116            return
     117        if event.button ==1:
     118            baseinv=True
     119        elif event.button == 3:
     120            baseinv=False
     121        else:
     122            return
     123
     124        def _calc_stats():
     125            msk=mymask.get_mask()
     126            mymask.scan.stats(stat='max',mask=msk)
     127            mymask.scan.stats(stat='min',mask=msk)
     128            mymask.scan.stats(stat='sum',mask=msk)
     129            mymask.scan.stats(stat='mean',mask=msk)
     130            mymask.scan.stats(stat='median',mask=msk)
     131            mymask.scan.stats(stat='rms',mask=msk)
     132            mymask.scan.stats(stat='stddev',mask=msk)
     133
     134        # Interactive mask definition
    127135        from asap.interactivemask import interactivemask
    128         mymask=interactivemask(plotter=self.plotter,scan=self.plotter._data)
    129         # Create initial mask
    130         mymask.set_basemask(invert=baseinv)
    131         # Inherit event
    132         mymask.set_startevent(event)
    133         # Set callback func
    134         mymask.set_callback(_calc_stats)
    135         # Selected mask
    136         mymask.select_mask(once=True,showmask=False)
     136        mymask=interactivemask(plotter=self.plotter,scan=self.plotter._data)
     137        # Create initial mask
     138        mymask.set_basemask(invert=baseinv)
     139        # Inherit event
     140        mymask.set_startevent(event)
     141        # Set callback func
     142        mymask.set_callback(_calc_stats)
     143        # Selected mask
     144        mymask.select_mask(once=True,showmask=False)
    137145
    138146#####################################
     
    140148#####################################
    141149### TkAgg
    142 if matplotlib.get_backend() == 'TkAgg': import Tkinter as Tk
     150if matplotlib.get_backend() == 'TkAgg':
     151    import Tkinter as Tk
     152
    143153class CustomToolbarTkAgg(CustomToolbarCommon, Tk.Frame):
    144154    def __init__(self,parent):
    145155        from asap.asapplotter import asapplotter
    146         if not isinstance(parent,asapplotter): return False
    147         if not parent._plotter: return False
     156        if not isinstance(parent,asapplotter):
     157            return False
     158        if not parent._plotter:
     159            return False
    148160        self._p=parent._plotter
    149161        self.figmgr=self._p.figmgr
     
    172184
    173185    def _NewButton(self, master, text, command, side=Tk.LEFT):
    174         if(os.uname()[0] == 'Darwin'):
     186        if os.uname()[0] == 'Darwin':
    175187            b = Tk.Button(master=master, text=text, command=command)
    176188        else:
    177             b = Tk.Button(master=master, text=text, padx=2, pady=2, command=command)
     189            b = Tk.Button(master=master, text=text, padx=2, pady=2,
     190                          command=command)
    178191        b.pack(side=side)
    179192        return b
    180        
     193
    181194    def spec_show(self):
    182195        if not self.figmgr.toolbar.mode == '' or not self.button: return
     
    212225        self.button=True
    213226        self.spec_show()
    214        
     227
    215228    def disable_button(self):
    216229        if not self.button: return
    217         self.bStat.config(relief='raised',state=Tk.DISABLED)
    218         self.bSpec.config(relief='raised',state=Tk.DISABLED)
     230        self.bStat.config(relief='raised', state=Tk.DISABLED)
     231        self.bSpec.config(relief='raised', state=Tk.DISABLED)
    219232        self.button=False
    220233        self.mode=''
  • trunk/python/interactivemask.py

    r1819 r1826  
    1 from asap import rcParams
    2 from asap import _n_bools, mask_and, mask_or
     1from asap.parameters import rcParams
     2from asap.utils import _n_bools, mask_and, mask_or
    33from asap.scantable import scantable
    44
     
    1515           my_mask.finish_selection(callback=func)
    1616           mask=my_mask.get_mask()
    17            
    18         Modify mask region by selecting a region on a plot with mouse. 
     17
     18        Modify mask region by selecting a region on a plot with mouse.
    1919        """
    2020
     
    2222                """
    2323                Create a interactive masking object.
    24                 Either or both 'plotter' or/and 'scan' should be defined. 
     24                Either or both 'plotter' or/and 'scan' should be defined.
    2525
    2626                Parameters:
     
    6363                self.ydataold=None
    6464                self._polygons=[]
    65        
     65
    6666
    6767        def set_basemask(self,masklist=[],invert=False):
    6868                """
    6969                Set initial channel mask.
    70                
     70
    7171                Parameters:
    7272                    masklist:  [[min, max], [min2, max2], ...]
    73                                A list of pairs of start/end points (inclusive) 
     73                               A list of pairs of start/end points (inclusive)
    7474                               specifying the regions to be masked
    7575                    invert:    optional argument. If specified as True,
     
    7777                               specified are excluded
    7878                You can reset the mask selection by running this method with
    79                 the default parameters. 
     79                the default parameters.
    8080                """
    8181                # Verify input parameters
     
    9797                """
    9898                Inherit an event from the parent function.
    99                
     99
    100100                Parameters:
    101101                    event: 'button_press_event' object to be inherited to
    102                            start interactive region selection . 
     102                           start interactive region selection .
    103103                """
    104104                from matplotlib.backend_bases import MouseEvent
    105                 if isinstance(event,MouseEvent) and event.name=='button_press_event': 
     105                if isinstance(event,MouseEvent) and event.name=='button_press_event':
    106106                        self.event=event
    107107                else:
    108108                        msg="Invalid event."
    109                         raise TypeError(msg)   
     109                        raise TypeError(msg)
    110110
    111111        def set_callback(self,callback):
    112112                """
    113                 Set callback function to run when finish_selection() is executed. 
     113                Set callback function to run when finish_selection() is executed.
    114114                    callback: The post processing function to run after
    115115                              the mask selections are completed.
     
    123123                Do interactive mask selection.
    124124                Modify masks interactively by adding/deleting regions with
    125                 mouse drawing.(left-button: mask; right-button: UNmask) 
    126                 Note that the interactive region selection is available only 
    127                 when GUI plotter is active. 
     125                mouse drawing.(left-button: mask; right-button: UNmask)
     126                Note that the interactive region selection is available only
     127                when GUI plotter is active.
    128128
    129129                Parameters:
    130130                    once:     If specified as True, you can modify masks only
    131                               once. Else if False, you can modify them repeatedly. 
     131                              once. Else if False, you can modify them repeatedly.
    132132                    showmask: If specified as True, the masked regions are plotted
    133133                              on the plotter.
    134134                              Note this parameter is valid only when once=True.
    135                               Otherwise, maskes are forced to be plotted for reference. 
     135                              Otherwise, maskes are forced to be plotted for reference.
    136136                """
    137137                # Return if GUI is not active
     
    181181                if self.event != None:
    182182                        self._region_start(self.event)
    183                 else: 
     183                else:
    184184                        self.p._plotter.register('button_press',None)
    185185                        self.p._plotter.register('button_press',self._region_start)
     
    205205        def _region_draw(self,event):
    206206                sameaxes=(event.inaxes == self.rect['axes'])
    207                 if sameaxes: 
     207                if sameaxes:
    208208                        xnow=event.x
    209209                        ynow=event.y
     
    224224                # Delete the rubber band
    225225                self.p._plotter.figmgr.toolbar.release(event)
    226                
    227                 if event.inaxes == self.rect['axes']: 
     226
     227                if event.inaxes == self.rect['axes']:
    228228                        xend=event.x
    229229                        yend=event.y
     
    235235                        xdataend=self.xdataold
    236236                        ydataend=self.ydataold
    237                        
     237
    238238                self.rect['world'][2:4] = [xdataend, ydataend]
    239239                self.rect['pixel'][2:4] = [xend, yend]
     
    300300                                if len(ifs) > 1:
    301301                                        for k in xrange(len(ifs)-1):
    302                                                 self._polygons.append(self.p._plotter.subplots[j]['axes'].axvspan(projs[k][i][0],projs[k][i][1],facecolor='#aaaaaa'))                   
     302                                                self._polygons.append(self.p._plotter.subplots[j]['axes'].axvspan(projs[k][i][0],projs[k][i][1],facecolor='#aaaaaa'))
    303303                                self._polygons.append(self.p._plotter.subplots[j]['axes'].axvspan(msks[i][0],msks[i][1],facecolor='yellow'))
    304304                self.p._plotter.canvas.draw()
     
    314314                              Specifying the callback function here will overwrite
    315315                              the one set by set_callback(func)
    316                
     316
    317317                Note this function is automatically called at the end of
    318                 select_mask() if once=True. 
     318                select_mask() if once=True.
    319319                """
    320320                if callback: self.callback=callback
     
    324324                if not self.newplot:
    325325                        self.clear_polygon()
    326                 else: 
     326                else:
    327327                        self.p._plotter.unmap()
    328328                        self.p._plotter = None
     
    334334        def clear_polygon(self):
    335335                """
    336                 Erase masks plots from the plotter. 
     336                Erase masks plots from the plotter.
    337337                """
    338338                if len(self._polygons)>0:
     
    347347                Get the interactively selected channel mask.
    348348                Returns:
    349                     A list of channel mask. 
     349                    A list of channel mask.
    350350                """
    351351                return self.mask
    352 
    353 
  • trunk/python/lagflagger.py

    r1823 r1826  
    1 from asap import scantable
     1__all_ = ['lagplotter']
     2
     3from asap.scantable import scantable
    24from matplotlib.pylab import *
    35from numpy import array, ma, logical_not
  • trunk/python/linecatalog.py

    r1819 r1826  
    77__revision__ = "$Revision$"
    88from asap._asap import linecatalog as lcbase
    9 from asap import rcParams
    10 from asap import asaplog
     9from asap.parameters import rcParams
     10from asap.logging import asaplog
    1111import os
    1212
     
    130130        if k < 0: k = self.nrow()-k
    131131        return self.get_row(k)
    132 
    133 
    134 
    135 
    136 
  • trunk/python/opacity.py

    r1823 r1826  
     1__all__ = ["model", "skydip"]
    12import os
    23import math
    3 from asap import scantable
    4 from asap import merge
    5 from asap import fitter
    6 from asap import selector
    7 from asap import rcParams
     4from asap.scantable import scantable
     5from asap.asapmath import merge
     6from asap.asapfitter import fitter
     7from asap.selector import selector
     8from asap.parameters import rcParams
    89from asap._asap import atmosphere
    910
     
    4546            elevation:     observatory elevation about sea level (in meters)
    4647        """
    47         self._atm = atmosphere(temperature, self._to_pascals(pressure), 
     48        self._atm = atmosphere(temperature, self._to_pascals(pressure),
    4849                               humidity)
    4950        self.set_observatory_elevation(elevation)
  • trunk/python/selector.py

    r1819 r1826  
    11from asap._asap import selector as _selector
    2 from asap import unique, _to_list
     2from asap.utils import unique, _to_list
    33
    44class selector(_selector):
     
    165165        Set a sequence of row numbers (0-based). Power users Only!
    166166        NOTICE row numbers can be changed easily by sorting,
    167         prior selection, etc. 
     167        prior selection, etc.
    168168        Parameters:
    169169            rows:    a list of integers. Default [] is to unset the selection.
    170170        """
    171         vec = _to_list(rows, int) 
     171        vec = _to_list(rows, int)
    172172        if isinstance(vec,list):
    173173            self._setrows(vec)
     
    177177    def set_types(self, types=[]):
    178178        """
    179         Set a sequence of source types. 
     179        Set a sequence of source types.
    180180        Parameters:
    181181            types:    a list of integers. Default [] is to unset the selection.
    182182        """
    183         vec = _to_list(types, int) 
     183        vec = _to_list(types, int)
    184184        if isinstance(vec,list):
    185185            self._settypes(vec)
  • trunk/python/simplelinefinder.py

    r1823 r1826  
    11import math
    2 from asap import asaplog
     2from asap.logging import asaplog
    33
    44class StatCalculator:
     
    77       self.s2=0.
    88       self.cnt=0
    9    
     9
    1010   def mean(self):
    1111       if self.cnt<=0:
    1212          raise RuntimeError, "At least one data point has to be defined"
    1313       return self.s/float(self.cnt)
    14    
     14
    1515   def variance(self):
    1616       if self.cnt<=1:
    1717          raise RuntimeError, "At least two data points has to be defined"
    1818       return math.sqrt((self.s2/self.cnt)-(self.s/self.cnt)**2+1e-12)
    19    
     19
    2020   def rms(self):
    2121       """
     
    2525          raise RuntimeError, "At least one data point has to be defined"
    2626       return math.sqrt(self.s2/self.cnt)
    27  
     27
    2828   def add(self, pt):
    2929       self.s = self.s + pt
     
    3636       A simplified class to search for spectral features. The algorithm assumes that the bandpass
    3737       is taken out perfectly and no spectral channels are flagged (except some edge channels).
    38        It works with a list or tuple rather than a scantable and returns the channel pairs. 
     38       It works with a list or tuple rather than a scantable and returns the channel pairs.
    3939       There is an optional feature to attempt to split the detected lines into components, although
    40        it should be used with caution. This class is largely intended to be used with scripts. 
    41        
     40       it should be used with caution. This class is largely intended to be used with scripts.
     41
    4242       The fully featured version of the algorithm working with scantables is called linefinder.
    4343   '''
    44    
     44
    4545   def __init__(self):
    4646      '''
    47          Initialize the class. 
     47         Initialize the class.
    4848      '''
    4949      self._median = None
    5050      self._rms = None
    51    
     51
    5252   def writeLog(self, str):
    5353      """
    5454         Write user defined string into log file
    55       """ 
     55      """
    5656      asaplog.push(str)
    5757
    5858   def invertChannelSelection(self, nchan, chans, edge = (0,0)):
    5959      """
    60          This method converts a tuple with channel ranges to a tuple which covers all channels 
     60         This method converts a tuple with channel ranges to a tuple which covers all channels
    6161         not selected by the original tuple (optionally edge channels can be discarded)
    62  
    63          nchan - number of channels in the spectrum. 
     62
     63         nchan - number of channels in the spectrum.
    6464         chans - tuple (with even number of elements) containing start and stop channel for all selected ranges
    6565         edge - one number or two element tuple (separate values for two ends) defining how many channels to reject
     
    6969      """
    7070      if nchan<=1:
    71          raise RuntimeError, "Number of channels is supposed to be at least 2, you have %i"% nchan     
     71         raise RuntimeError, "Number of channels is supposed to be at least 2, you have %i"% nchan
    7272      if len(chans)%2!=0:
    7373         raise RuntimeError, "chans is supposed to be a tuple with even number of elements"
     
    106106         spc - tuple with the spectrum (first is the vector of abcissa values, second is the spectrum itself)
    107107         vel_range - a 2-element tuple with start and stop velocity of the range
    108        
     108
    109109         return: a 2-element tuple with channels
    110110         Note, if supplied range is completely outside the spectrum, an empty tuple will be returned
     
    145145      """
    146146         A helper method to compare x and y by absolute value (to do sorting)
    147          
     147
    148148         x - first value
    149149         y - second value
    150          
     150
    151151         return -1,0 or 1 depending on the result of comparison
    152152      """
     
    157157      else:
    158158         return 0
    159          
     159
    160160   def rms(self):
    161161      """
     
    167167         raise RuntimeError, "call find_lines before using the rms method"
    168168      return self._rms
    169    
     169
    170170   def median(self):
    171171      """
     
    176176         raise RuntimeError, "call find_lines before using the median method"
    177177      return self._median
    178    
     178
    179179   def _mergeIntervals(self, lines, spc):
    180180      """
    181181         A helper method to merge intervals.
    182          
     182
    183183         lines - list of tuples with first and last channels of all intervals
    184184         spc - spectrum (to be able to test whether adjacent intervals have the
     
    196196             raise RuntimeError, "this shouldn't have happened!"
    197197          lines.pop(toberemoved[i])
    198          
     198
    199199   def _splitIntervals(self,lines,spc,threshold=3,minchan=3):
    200200      """
     
    203203         Noise is dealt with by taking into account only those extrema, where a difference with
    204204         respect to surrounding spectral points exceeds threshold times rms (stored inside this
    205          class, so the main body of the line detection should be executed first) and there are 
    206          at least minchan such points.     
     205         class, so the main body of the line detection should be executed first) and there are
     206         at least minchan such points.
    207207      """
    208208      if minchan<1:
     
    219219              if wasIncreasing != None:
    220220                 if isIncreasing != wasIncreasing:
    221                     derivSignReversals.append((ch,isIncreasing)) 
     221                    derivSignReversals.append((ch,isIncreasing))
    222222              wasIncreasing = isIncreasing
    223223          if len(derivSignReversals)==0:
     
    237237             newlines.append((startchan,line[1]))
    238238      return newlines
    239                  
     239
    240240   def find_lines(self,spc,threshold=3,edge=0,minchan=3, tailsearch = True, splitFeatures = False):
    241241      """
     
    243243         taken out perfectly and no channels are flagged within the spectrum. A detection
    244244         is reported if consequtive minchan number of channels is consistently above or
    245          below the median value. The threshold is given in terms of the rms calculated 
    246          using 80% of the lowest data points by the absolute value (with respect to median) 
    247          
     245         below the median value. The threshold is given in terms of the rms calculated
     246         using 80% of the lowest data points by the absolute value (with respect to median)
     247
    248248         spc - a list or tuple with the spectrum, no default
    249249         threshold - detection threshold, default is 3 sigma, see above for the definition
     
    254254         tailsearch - if True (default), the algorithm attempts to widen each line until
    255255                    its flux crosses the median. It merges lines if necessary. Set this
    256                     option off if you need to split the lines according to some criterion                   
     256                    option off if you need to split the lines according to some criterion
    257257         splitFeatures - if True, the algorithm attempts to split each detected spectral feature into
    258258                    a number of spectral lines (just one local extremum). The default action is
    259259                    not to do it (may give an adverse results if the noise is high)
    260          
     260
    261261         This method returns a list of tuples each containing start and stop 0-based channel
    262262         number of every detected line. Empty list if nothing has been detected.
    263      
     263
    264264         Note. The median and rms about this median is stored inside this class and can
    265265         be obtained with rms and median methods.
     
    270270         raise RuntimeError, "edge is too high (%i), you rejected all channels (%i)" % (edge, len(spc))
    271271      if threshold<=0:
    272          raise RuntimeError, "threshold parameter of find_lines should be positive, you have %s" % threshold     
     272         raise RuntimeError, "threshold parameter of find_lines should be positive, you have %s" % threshold
    273273      if minchan<=0:
    274274         raise RuntimeError, "minchan parameter of find_lines should be positive, you have %s" % minchan
    275      
    276       # temporary storage to get statistics, apply edge rejection here 
     275
     276      # temporary storage to get statistics, apply edge rejection here
    277277      tmpspc = spc[edge:len(spc)-edge+1]
    278278      if len(tmpspc)<2:
    279          raise RuntimeError, "Too many channels are rejected. Decrease edge parameter or provide a longer spectrum."       
     279         raise RuntimeError, "Too many channels are rejected. Decrease edge parameter or provide a longer spectrum."
    280280      tmpspc.sort()
    281281      self._median=tmpspc[len(tmpspc)/2]
     
    286286      sc = StatCalculator()
    287287      for i in tmpspc[:-int(0.2*len(tmpspc))]:
    288           sc.add(i)         
     288          sc.add(i)
    289289      self._rms=sc.rms()
    290      
    291       self.writeLog("Spectral line detection with edge=%i, threshold=%f, minchan=%i and tailsearch=%s" % (edge,threshold, minchan, tailsearch)) 
    292       self.writeLog("statistics: median=%f, rms=%f" % (self._median, self._rms))     
    293      
     290
     291      self.writeLog("Spectral line detection with edge=%i, threshold=%f, minchan=%i and tailsearch=%s" % (edge,threshold, minchan, tailsearch))
     292      self.writeLog("statistics: median=%f, rms=%f" % (self._median, self._rms))
     293
    294294      #actual line detection
    295295      lines=[]
     
    319319      if nchan>=minchan:
    320320         lines.append((startchan,len(spc)-edge-1))
    321      
     321
    322322      if tailsearch:
    323323         for i in range(len(lines)):
     
    325325             curRange = list(lines[i])
    326326             for x in range(curRange[0],edge,-1):
    327                  isAbove=(spc[x] > self._median)             
     327                 isAbove=(spc[x] > self._median)
    328328                 if wasAbove == None:
    329329                    wasAbove = isAbove
     
    332332                    break
    333333             for x in range(curRange[1],len(spc)-edge):
    334                  isAbove=(spc[x] > self._median)             
     334                 isAbove=(spc[x] > self._median)
    335335                 if isAbove!=wasAbove:
    336336                    curRange[1]=x-1
    337337                    break
    338338             lines[i]=tuple(curRange)
    339          self._mergeIntervals(lines,spc)                           
     339         self._mergeIntervals(lines,spc)
    340340      if splitFeatures:
    341341         return self._splitIntervals(lines,spc,threshold,minchan)
    342       return lines         
     342      return lines
Note: See TracChangeset for help on using the changeset viewer.