index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
65,325
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/distortion/models.py
from __future__ import division # confidence high import types # Import PyDrizzle utility modules import mutil import numpy as np import mutil from mutil import combin yes = True no = False ################# # # # Geometry/Distortion Classes # # ################# class GeometryModel: """ Base class for Distortion model. There will be a separate class for each type of model/filetype used with drizzle, i.e., IDCModel and DrizzleModel. Each class will know how to apply the distortion to a single point and how to convert coefficients to an input table suitable for the drizzle task. Coefficients will be stored in CX,CY arrays. """ # # # # # # # NORDER = 3 def __init__(self): " This will open the given file and determine its type and norder." # Method to read in coefficients from given table and # populate the n arrays 'cx' and 'cy'. # This will be different for each type of input file, # IDCTAB vs. drizzle table. # Set these up here for all sub-classes to use... # But, calculate norder and cx,cy arrays in detector specific classes. self.cx = None self.cy = None self.refpix = None self.norder = self.NORDER # Keep track of computed zero-point for distortion coeffs self.x0 = None self.y0 = None # default values for these attributes self.direction = 'forward' self.pscale = 1.0 def shift(self,cx,cy,xs,ys): """ Shift reference position of coefficients to new center where (xs,ys) = old-reference-position - subarray/image center. This will support creating coeffs files for drizzle which will be applied relative to the center of the image, rather than relative to the reference position of the chip. """ _cxs = np.zeros(shape=cx.shape,dtype=cx.dtype) _cys = np.zeros(shape=cy.shape,dtype=cy.dtype) _k = self.norder + 1 # loop over each input coefficient for m in xrange(_k): for n in xrange(_k): if m >= n: # For this coefficient, shift by xs/ys. _ilist = range(m, _k) # sum from m to k for i in _ilist: _jlist = range(n, i - (m-n)+1) # sum from n to i-(m-n) for j in _jlist: _cxs[m,n] += cx[i,j]*combin(j,n)*combin((i-j),(m-n))*pow(xs,(j-n))*pow(ys,((i-j)-(m-n))) _cys[m,n] += cy[i,j]*combin(j,n)*combin((i-j),(m-n))*pow(xs,(j-n))*pow(ys,((i-j)-(m-n))) return _cxs,_cys def convert(self, tmpname, xref=None,yref=None,delta=yes): """ Open up an ASCII file, output coefficients in drizzle format after converting them as necessary. First, normalize these coefficients to what drizzle expects Normalize the coefficients by the MODEL/output plate scale. 16-May-2002: Revised to work with higher order polynomials by John Blakeslee. 27-June-2002: Added ability to shift coefficients to new center for support of subarrays. """ cx = self.cx/self.pscale cy = self.cy/self.pscale x0 = self.refpix['XDELTA'] + cx[0,0] y0 = self.refpix['YDELTA'] + cy[0,0] #xr = self.refpix['XREF'] #yr = self.refpix['YREF'] xr = self.refpix['CHIP_XREF'] yr = self.refpix['CHIP_YREF'] ''' if xref != None: # Shift coefficients for use with drizzle _xs = xref - self.refpix['XREF'] + 1.0 _ys = yref - self.refpix['YREF'] + 1.0 if _xs != 0 or _ys != 0: cxs,cys= self.shift(cx, cy, _xs, _ys) cx = cxs cy = cys # We only want to apply this shift to coeffs # for subarray images. if delta == no: cxs[0,0] = cxs[0,0] - _xs cys[0,0] = cys[0,0] - _ys # Now, apply only the difference introduced by the distortion.. # i.e., (undistorted - original) shift. x0 += cxs[0,0] y0 += cys[0,0] ''' self.x0 = x0 #+ 1.0 self.y0 = y0 #+ 1.0 # Now, write out the coefficients into an ASCII # file in 'drizzle' format. lines = [] lines.append('# Polynomial distortion coefficients\n') lines.append('# Extracted from "%s" \n'%self.name) lines.append('refpix %f %f \n'%(xr,yr)) if self.norder==3: lines.append('cubic\n') elif self.norder==4: lines.append('quartic\n') elif self.norder==5: lines.append('quintic\n') else: raise ValueError("Drizzle cannot handle poly distortions of order %d"%self.norder) str = '%16.8f %16.8g %16.8g %16.8g %16.8g \n'% (x0,cx[1,1],cx[1,0],cx[2,2],cx[2,1]) lines.append(str) str = '%16.8g %16.8g %16.8g %16.8g %16.8g \n'% (cx[2,0],cx[3,3],cx[3,2],cx[3,1],cx[3,0]) lines.append(str) if self.norder>3: str = '%16.8g %16.8g %16.8g %16.8g %16.8g \n'% (cx[4,4],cx[4,3],cx[4,2],cx[4,1],cx[4,0]) lines.append(str) if self.norder>4: str = '%16.8g %16.8g %16.8g %16.8g %16.8g %16.8g \n'% (cx[5,5],cx[5,4],cx[5,3],cx[5,2],cx[5,1],cx[5,0]) lines.append(str) lines.append("\n") str = '%16.8f %16.8g %16.8g %16.8g %16.8g \n'% (y0,cy[1,1],cy[1,0],cy[2,2],cy[2,1]) lines.append(str) str = '%16.8g %16.8g %16.8g %16.8g %16.8g \n'% (cy[2,0],cy[3,3],cy[3,2],cy[3,1],cy[3,0]) lines.append(str) if self.norder>3: str = '%16.8g %16.8g %16.8g %16.8g %16.8g \n'% (cy[4,4],cy[4,3],cy[4,2],cy[4,1],cy[4,0]) lines.append(str) if self.norder>4: str = '%16.8g %16.8g %16.8g %16.8g %16.8g %16.8g \n'% (cy[5,5],cy[5,4],cy[5,3],cy[5,2],cy[5,1],cy[5,0]) lines.append(str) output = open(tmpname,'w') output.writelines(lines) output.close() def apply(self, pixpos,scale=1.0,order=None): """ Apply coefficients to a pixel position or a list of positions. This should be the same for all coefficients tables. Return the geometrically-adjusted position in arcseconds from the reference position as a tuple (x,y). Compute delta from reference position """ """ scale actually is a ratio of pscale/self.model.pscale what is pscale? """ if self.cx == None: return pixpos[:,0],pixpos[:,1] if order is None: order = self.norder # Apply in the same way that 'drizzle' would... _cx = self.cx / (self.pscale * scale) _cy = self.cy / (self.pscale * scale) _convert = no _p = pixpos # Do NOT include any zero-point terms in CX,CY here # as they should not be scaled by plate-scale like rest # of coeffs... This makes the computations consistent # with 'drizzle'. WJH 17-Feb-2004 _cx[0,0] = 0. _cy[0,0] = 0. if isinstance(_p,types.ListType) or isinstance(_p,types.TupleType): _p = np.array(_p,dtype=np.float64) _convert = yes dxy = _p - (self.refpix['XREF'],self.refpix['YREF']) # Apply coefficients from distortion model here... c = _p * 0. for i in range(order+1): for j in range(i+1): c[:,0] = c[:,0] + _cx[i][j] * pow(dxy[:,0],j) * pow(dxy[:,1],(i-j)) c[:,1] = c[:,1] + _cy[i][j] * pow(dxy[:,0],j) * pow(dxy[:,1],(i-j)) xc = c[:,0] yc = c[:,1] # Convert results back to same form as original input if _convert: xc = xc.tolist() yc = yc.tolist() # If a single tuple was input, return just a single tuple if len(xc) == 1: xc = xc[0] yc = yc[0] return xc,yc def setPScaleCoeffs(self,pscale): self.cx[1,1] = pscale self.cy[1,0] = pscale self.refpix['PSCALE'] = pscale self.pscale = pscale class IDCModel(GeometryModel): """ This class will open the IDCTAB, select proper row based on chip/direction and populate cx,cy arrays. We also need to read in SCALE, XCOM,YCOM, XREF,YREF as well. """ def __init__(self, idcfile, date=None, chip=1, direction='forward', filter1='CLEAR1',filter2='CLEAR2',offtab=None, binned=1, tddcorr=False): GeometryModel.__init__(self) # # Norder must be derived from the coeffs file itself, # then the arrays can be setup. Thus, it needs to be # done in the sub-class, not in the base class. # Read in table. # Populate cx,cy,scale, and other variables here. # self.name = idcfile self.cx,self.cy,self.refpix,self.norder = mutil.readIDCtab(idcfile, chip=chip,direction=direction,filter1=filter1,filter2=filter2, date=date, offtab=offtab,tddcorr=tddcorr) if 'empty_model' in self.refpix and self.refpix['empty_model']: pass else: self.refpix['PSCALE'] = self.refpix['PSCALE'] * binned self.cx = self.cx * binned self.cy = self.cy * binned self.refpix['XREF'] = self.refpix['XREF'] / binned self.refpix['YREF'] = self.refpix['YREF'] / binned self.refpix['XSIZE'] = self.refpix['XSIZE'] / binned self.refpix['YSIZE'] = self.refpix['YSIZE'] / binned self.pscale = self.refpix['PSCALE'] class WCSModel(GeometryModel): """ This class sets up a distortion model based on coefficients found in the image header. """ def __init__(self,header,rootname): GeometryModel.__init__(self) if 'rootname' in header: self.name = header['rootname'] else: self.name = rootname self.name += '_sip' if 'wfctdd' in header and header['wfctdd'] == 'T': self.name += '_tdd' # Initialize all necessary distortion arrays with # default model... #self.cx,self.cy,self.refpix,self.order = mutil.defaultModel() # Read in values from header, and update distortion arrays. self.cx,self.cy,self.refpix,self.norder = mutil.readWCSCoeffs(header) self.pscale = self.refpix['PSCALE'] class DrizzleModel(GeometryModel): """ This class will read in an ASCII Cubic drizzle coeffs file and populate the cx,cy arrays. """ def __init__(self, idcfile, scale = None): GeometryModel.__init__(self) # # We now need to read in the file, populate cx,cy, and # other variables as necessary. # self.name = idcfile self.cx,self.cy,self.refpix,self.norder = mutil.readCubicTable(idcfile) # scale is the ratio wcs.pscale/model.pscale. # model.pscale for WFPC2 is passed from REFDATA. # This is needed for WFPC2 binned data. if scale != None: self.pscale = scale else: self.pscale = self.refpix['PSCALE'] """ The above definition looks wrong. In one case it's a ratio in the other it's pscale. """ class TraugerModel(GeometryModel): """ This class will read in the ASCII Trauger coeffs file, convert them to SIAF coefficients, then populate the cx,cy arrays. """ NORDER = 3 def __init__(self, idcfile,lam): GeometryModel.__init__(self) self.name = idcfile self.cx,self.cy,self.refpix,self.norder = mutil.readTraugerTable(idcfile,lam) self.pscale = self.refpix['PSCALE'] # # Read in file here. # Populate cx,cy, and other variables. #
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,326
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/traits102/trait_notifiers.py
#------------------------------------------------------------------------------- # # Define the classes needed to implement and support the trait change # notification mechanism. # # Written by: David C. Morrill # # Date: 06/21/2002 # # Refactored into a separate module: 07/04/2003 # # Symbols defined: TraitChangeNotifier # EventChangeNotify # TraitChangeNotifyWrapper # StaticAnyTraitChangeNotifyWrapper # StaticTraitChangeNotifyWrapper # InstanceTraitNotifier # ClassTraitNotifier # SpecificTraitNotifier # SpecificEventNotifier # AnyAndSpecificTraitNotifier # AnyAndSpecificEventNotifier # # (c) Copyright 2002, 2003 by Enthought, Inc. # #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- # Imports: #------------------------------------------------------------------------------- from __future__ import absolute_import, division # confidence high import sys import traceback from types import MethodType from .trait_base import TraitNotifier from .trait_delegates import TraitEvent #------------------------------------------------------------------------------- # 'TraitChangeNotifier' class: #------------------------------------------------------------------------------- class TraitChangeNotifier: #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, object, name, anytrait_notifiers ): self.trait_notifiers = [] self.anytrait_notifiers = anytrait_notifiers cls = object.__class__ cls_notifier = cls.__dict__.get( TraitNotifier ) self.trait_notifier = self.anytrait_notifier = None trait_notifier = getattr( cls, name + '_changed', None ) if trait_notifier is not None: if cls_notifier is not None: notifier = cls_notifier.notifiers.get( name ) if notifier is not None: self.trait_notifier = notifier.notifier if self.trait_notifier is None: self.trait_notifier = StaticTraitChangeNotifyWrapper( trait_notifier ) anytrait_notifier = getattr( cls, 'anytrait_changed', None ) if anytrait_notifier is not None: if cls_notifier is not None: self.anytrait_notifier = cls_notifier.anytrait_notifier else: self.anytrait_notifier = StaticAnyTraitChangeNotifyWrapper( anytrait_notifier ) #---------------------------------------------------------------------------- # Add a new handler: #---------------------------------------------------------------------------- def add ( self, handler ): trait_notifiers = self.trait_notifiers for cur_notifier in trait_notifiers: # NOTE: 'is' seems like it should work, but it doesn't: #if handler is cur_notifier.handler: if handler == cur_notifier.handler: return 0 trait_notifiers.append( TraitChangeNotifyWrapper( handler ) ) return 1 #---------------------------------------------------------------------------- # Remove an existing handler: #---------------------------------------------------------------------------- def remove ( self, handler ): trait_notifiers = self.trait_notifiers for cur_notifier in trait_notifiers: # NOTE: 'is' seems like it should work, but it doesn't: #if handler is cur_notifier.handler: if handler == cur_notifier.handler: trait_notifiers.remove( cur_notifier ) return 1 return 0 #---------------------------------------------------------------------------- # Set a new value on the object: #---------------------------------------------------------------------------- def __call__ ( self, object, name, value, default ): obj_dict = object.__dict__ old_value = obj_dict.get( name, default ) try: if old_value != value: obj_dict[ name ] = value if self.trait_notifier is not None: self.trait_notifier( object, name, old_value, value ) for notifier in self.trait_notifiers[:]: notifier( object, name, old_value, value ) if self.anytrait_notifier is not None: self.anytrait_notifier( object, name, old_value, value ) for notifier in self.anytrait_notifiers[:]: notifier( object, name, old_value, value ) return value else: obj_dict[ name ] = value return value except: obj_dict[ name ] = value if self.trait_notifier is not None: self.trait_notifier( object, name, old_value, value ) for notifier in self.trait_notifiers[:]: notifier( object, name, old_value, value ) if self.anytrait_notifier is not None: self.anytrait_notifier( object, name, old_value, value ) for notifier in self.anytrait_notifiers[:]: notifier( object, name, old_value, value ) return value #---------------------------------------------------------------------------- # Set a new value on the object (with deferred notification): #---------------------------------------------------------------------------- def deferred ( self, object, name, value, default ): obj_dict = object.__dict__ old_value = obj_dict.get( name, default ) try: if old_value != value: obj_dict[ name ] = value tnotifier = getattr( object, TraitNotifier ) if self.trait_notifier is not None: tnotifier.defer_notify( self.trait_notifier, object, name, old_value, value ) for notifier in self.trait_notifiers: tnotifier.defer_notify( notifier, object, name, old_value, value ) if self.anytrait_notifier is not None: tnotifier.defer_notify( self.anytrait_notifier, object, name, old_value, value ) for notifier in self.anytrait_notifiers: tnotifier.defer_notify( notifier, object, name, old_value, value ) return value else: obj_dict[ name ] = value return value except: obj_dict[ name ] = value tnotifier = getattr( object, TraitNotifier ) if self.trait_notifier is not None: tnotifier.defer_notify( self.trait_notifier, object, name, old_value, value ) for notifier in self.trait_notifiers: tnotifier.defer_notify( notifier, object, name, old_value, value ) if self.anytrait_notifier is not None: tnotifier.defer_notify( self.anytrait_notifier, object, name, old_value, value ) for notifier in self.anytrait_notifiers: tnotifier.defer_notify( notifier, object, name, old_value, value ) return value #------------------------------------------------------------------------------- # 'EventChangeNotifier' class: #------------------------------------------------------------------------------- class EventChangeNotifier ( TraitChangeNotifier ): #---------------------------------------------------------------------------- # Set a new value on the object: #---------------------------------------------------------------------------- def __call__ ( self, object, name, value, default ): if self.trait_notifier is not None: self.trait_notifier( object, name, None, value ) for notifier in self.trait_notifiers[:]: notifier( object, name, None, value ) if self.anytrait_notifier is not None: self.anytrait_notifier( object, name, None, value ) for notifier in self.anytrait_notifiers[:]: notifier( object, name, None, value ) return value def deferred ( self, object, name, value, default ): tnotifier = getattr( object, TraitNotifier ) if self.trait_notifier is not None: tnotifier.defer_notify( self.trait_notifier, object, name, None, value ) for notifier in self.trait_notifiers: tnotifier.defer_notify( notifier, object, name, None, value ) if self.anytrait_notifier is not None: tnotifier.defer_notify( self.anytrait_notifier, object, name, None, value ) for notifier in self.anytrait_notifiers: tnotifier.defer_notify( notifier, object, name, None, value ) return value #------------------------------------------------------------------------------- # 'TraitChangeNotifyWrapper' class: #------------------------------------------------------------------------------- class TraitChangeNotifyWrapper: def __init__ ( self, handler ): self.handler = handler adjust = 0 func = handler if type( handler ) is MethodType: adjust = 1 if sys.version_info[0] >= 3: func = handler.__func__ else: func = handler.im_func if sys.version_info[0] >= 3: argcount = func.__code__.co_argcount - adjust else: argcount = func.func_code.co_argcount - adjust self.__call__ = getattr( self, 'call_%d' % argcount ) def call_0 ( self, object, trait_name, old, new ): try: self.handler() except: traceback.print_exc() def call_1 ( self, object, trait_name, old, new ): try: self.handler( new ) except: traceback.print_exc() def call_2 ( self, object, trait_name, old, new ): try: self.handler( trait_name, new ) except: traceback.print_exc() def call_3 ( self, object, trait_name, old, new ): try: self.handler( object, trait_name, new ) except: traceback.print_exc() def call_4 ( self, object, trait_name, old, new ): try: self.handler( object, trait_name, old, new ) except: traceback.print_exc() #------------------------------------------------------------------------------- # 'StaticAnyTraitChangeNotifyWrapper' class: #------------------------------------------------------------------------------- class StaticAnyTraitChangeNotifyWrapper: def __init__ ( self, handler ): self.handler = handler if sys.version_info[0] >= 3: argcount = handler.__code__.co_argcount else: argcount = handler.func_code.co_argcount self.__call__ = getattr( self, 'call_%d' % argcount ) def call_0 ( self, object, trait_name, old, new ): try: self.handler() except: traceback.print_exc() def call_1 ( self, object, trait_name, old, new ): try: self.handler( object ) except: traceback.print_exc() def call_2 ( self, object, trait_name, old, new ): try: self.handler( object, trait_name ) except: traceback.print_exc() def call_3 ( self, object, trait_name, old, new ): try: self.handler( object, trait_name, new ) except: traceback.print_exc() def call_4 ( self, object, trait_name, old, new ): try: self.handler( object, trait_name, old, new ) except: traceback.print_exc() #------------------------------------------------------------------------------- # 'StaticTraitChangeNotifyWrapper' class: #------------------------------------------------------------------------------- class StaticTraitChangeNotifyWrapper: def __init__ ( self, handler ): self.handler = handler if sys.version_info[0] >= 3: argcount = handler.__code__.co_argcount else: argcount = handler.func_code.co_argcount self.__call__ = getattr( self, 'call_%d' % argcount ) def call_0 ( self, object, trait_name, old, new ): try: self.handler() except: traceback.print_exc() def call_1 ( self, object, trait_name, old, new ): try: self.handler( object ) except: traceback.print_exc() def call_2 ( self, object, trait_name, old, new ): try: self.handler( object, new ) except: traceback.print_exc() def call_3 ( self, object, trait_name, old, new ): try: self.handler( object, old, new ) except: traceback.print_exc() def call_4 ( self, object, trait_name, old, new ): try: self.handler( object, trait_name, old, new ) except: traceback.print_exc() #------------------------------------------------------------------------------- # 'InstanceTraitNotifier' class: #------------------------------------------------------------------------------- class InstanceTraitNotifier: def __init__ ( self, object, class_notifier ): TraitNotifier.__init__ ( self ) self.object = object self.deferrals = None self.deferral_level = 0 self.active_notifiers = 0 self.notifiers = {} self.anytrait_notifiers = [] self.binder = InstanceTraitNotifierBinder( self, '_notifier_for', TraitChangeNotifier ) self.event_binder = InstanceTraitNotifierBinder( self, '_event_notifier_for', EventChangeNotifier ) if class_notifier is not None: obj_id = id( object ) info = class_notifier.deferrals.get( obj_id ) if info is not None: self.deferral_level, deferrals = info self.deferrals = {} for trait_name in deferrals.keys(): notifiers, old_value, new_value = deferrals[ trait_name ] for notifier in notifiers.values(): self.defer_notify( notifier, object, trait_name, old_value, new_value ) del class_notifier.deferrals[ obj_id ] def _set_trait_value ( self, object, name, value, default ): return self.notifiers.get( name, self.binder )( object, name, value, default ) def _set_trait_value_deferred ( self, object, name, value, default ): return self.notifiers.get( name, self.binder ).deferred( object, name, value, default ) def _set_event_value ( self, object, name, value, default ): return self.notifiers.get( name, self.event_binder )( object, name, value, default ) def _set_event_value_deferred ( self, object, name, value, default ): return self.notifiers.get( name, self.event_binder ).deferred( object, name, value, default ) def add ( self, handler, name ): if name == 'anytrait': anytrait_notifiers = self.anytrait_notifiers if len( anytrait_notifiers ) == 0: notifiers = self.notifiers for name, notifier in notifiers.items(): if not isinstance( notifier, TraitChangeNotifier ): mutates_to = TraitChangeNotifier if isinstance( self.object._trait( name ).setter, TraitEvent ): mutates_to = EventChangeNotifier notifiers[ name ] = mutates_to( self.object, name, anytrait_notifiers ) anytrait_notifiers.append( TraitChangeNotifyWrapper( handler ) ) else: notifier = self.notifiers.get( name, None ) if not isinstance( notifier, TraitChangeNotifier ): mutates_to = TraitChangeNotifier if isinstance( self.object._trait( name ).setter, TraitEvent ): mutates_to = EventChangeNotifier self.notifiers[ name ] = notifier = mutates_to( self.object, name, self.anytrait_notifiers ) self.active_notifiers += notifier.add( handler ) def remove ( self, handler, name ): if name == 'anytrait': anytrait_notifiers = self.anytrait_notifiers for notifier in anytrait_notifiers: # NOTE: 'is' seems like it should work, but it doesn't: #if handler is notifier.handler: if handler == notifier.handler: anytrait_notifiers.remove( notifier ) if len( anytrait_notifiers ) == 0: object = self.object if self.active_notifiers == 0: self.move_deferrals_to_class() else: notifiers = self.notifiers for name, notifier in notifiers.items(): if len( notifier.trait_notifiers ) == 0: notifiers[ name ] = object._notifier_for( name ) else: notifiers = self.notifiers notifier = notifiers.get( name, None ) if isinstance( notifier, TraitChangeNotifier ): self.active_notifiers -= notifier.remove( handler ) if ((len( notifier.trait_notifiers ) == 0) and (len( self.anytrait_notifiers ) == 0)): object = self.object notifiers[ name ] = object._notifier_for( name ) if self.active_notifiers == 0: self.move_deferrals_to_class() def reset_trait_value ( self, object ): obj_dict = object.__dict__ if self.deferral_level == 0: obj_dict[ '_set_trait_value' ] = self._set_trait_value obj_dict[ '_set_event_value' ] = self._set_event_value else: obj_dict[ '_set_trait_value' ] = self._set_trait_value_deferred obj_dict[ '_set_event_value' ] = self._set_event_value_deferred def defer_trait_change ( self, object, defer = True ): if defer: self.deferral_level += 1 if self.deferral_level == 1: self.deferrals = {} object._reset_trait_value() else: self.deferral_level -= 1 if self.deferral_level == 0: deferrals = self.deferrals for trait_name in deferrals.keys(): notifiers, old_value, new_value = deferrals[ trait_name ] for notifier in notifiers.values(): notifier( object, trait_name, old_value, new_value ) self.deferrals = None object._reset_trait_value() def defer_notify ( self, notifier, object, trait_name, old, new ): info = self.deferrals.setdefault( trait_name, [ {}, old, new ] ) info[0].setdefault( id( notifier ), notifier ) info[2] = new def move_deferrals_to_class ( self ): object = self.object del object.__dict__[ TraitNotifier ] deferrals = self.deferrals if deferrals is not None: cls_notifier = object._class_notifier() info = cls_notifier.deferrals.setdefault( id( object ), [ 0, {} ] ) info[0] = self.deferral_level for trait_name in deferrals.keys(): notifiers, old_value, new_value = deferrals[ trait_name ] for notifier in notifiers.values(): cls_notifier.defer_notify( notifier, object, trait_name, old_value, new_value ) self.deferrals = None self.object = self.notifiers = None object._reset_trait_value() #------------------------------------------------------------------------------- # 'InstanceTraitNotifierBinder' class: #------------------------------------------------------------------------------- class InstanceTraitNotifierBinder: def __init__ ( self, tnotifier, notifier_for, notifier_factory ): self.tnotifier = tnotifier self.notifier_for = getattr( tnotifier.object, notifier_for ) self.notifier_factory = notifier_factory def __call__ ( self, object, name, value, default ): tnotifier = self.tnotifier if len( tnotifier.anytrait_notifiers ) == 0: notifier = self.notifier_for( name ) else: notifier = self.notifier_factory( object, name, tnotifier.anytrait_notifiers ) tnotifier.notifiers[ name ] = notifier return notifier( object, name, value, default ) def deferred ( self, object, name, value, default ): tnotifier = self.tnotifier if len( tnotifier.anytrait_notifiers ) == 0: notifier = self.notifier_for( name ) else: notifier = self.notifier_factory( object, name, tnotifier.anytrait_notifiers ) tnotifier.notifiers[ name ] = notifier return notifier.deferred( object, name, value, default ) #------------------------------------------------------------------------------- # 'ClassTraitNotifier' class: #------------------------------------------------------------------------------- class ClassTraitNotifier: def __init__ ( self, cls ): TraitNotifier.__init__( self ) self.cls = cls self.notifiers = {} self.deferrals = {} self.bind_factory = self.no_anytrait_changed self.event_bind_factory = self.event_no_anytrait_changed handler = getattr( cls, 'anytrait_changed', None ) if handler is not None: self.anytrait_notifier = StaticAnyTraitChangeNotifyWrapper( handler ) self.bind_factory = self.has_anytrait_changed self.event_bind_factory = self.event_has_anytrait_changed self.binder = ClassTraitNotifierBinder( self.notifiers, self.bind_factory ) self.event_binder = ClassTraitNotifierBinder( self.notifiers, self.event_bind_factory ) def _set_trait_value ( self, object, name, value, default ): return self.notifiers.get( name, self.binder )( object, name, value, default ) def _set_trait_value_deferred ( self, object, name, value, default ): return self.notifiers.get( name, self.binder ).deferred( object, name, value, default ) def notifier_for ( self, name ): notifier = self.notifiers.get( name, None ) if notifier is None: self.notifiers[ name ] = notifier = self.bind_factory( name ) return notifier def no_anytrait_changed ( self, name ): notifier = getattr( self.cls, name + '_changed', None ) if notifier is None: return simple_set_trait_value return SpecificTraitNotifier( StaticTraitChangeNotifyWrapper( notifier )) def has_anytrait_changed ( self, name ): notifier = getattr( self.cls, name + '_changed', None ) if notifier is None: return SpecificTraitNotifier( self.anytrait_notifier ) return AnyAndSpecificTraitNotifier( self.anytrait_notifier, notifier ) def _set_event_value ( self, object, name, value, default ): return self.notifiers.get( name, self.event_binder )( object, name, value, default ) def _set_event_value_deferred ( self, object, name, value, default ): return self.notifiers.get( name, self.event_binder ).deferred( object, name, value, default ) def event_notifier_for ( self, name ): notifier = self.notifiers.get( name, None ) if notifier is None: self.notifiers[ name ] = notifier = self.event_bind_factory( name ) return notifier def event_no_anytrait_changed ( self, name ): notifier = getattr( self.cls, name + '_changed', None ) if notifier is None: return ignore_set_trait_value return SpecificEventNotifier( StaticTraitChangeNotifyWrapper( notifier )) def event_has_anytrait_changed ( self, name ): notifier = getattr( self.cls, name + '_changed', None ) if notifier is None: return SpecificEventNotifier( self.anytrait_notifier ) return AnyAndSpecificEventNotifier( self.anytrait_notifier, notifier ) def event_anytrait_changed ( self, object, name, value, default ): self.anytrait_notifier( object, name, None, value ) return value def reset_trait_value ( self, object ): obj_dict = object.__dict__ if self.deferrals.get( id( object ) ) is None: obj_dict[ '_set_trait_value' ] = self._set_trait_value obj_dict[ '_set_event_value' ] = self._set_event_value else: obj_dict[ '_set_trait_value' ] = self._set_trait_value_deferred obj_dict[ '_set_event_value' ] = self._set_event_value_deferred def defer_trait_change ( self, object, defer = True ): obj_id = id( object ) if defer: info = self.deferrals.setdefault( obj_id, [ 0, {} ] ) info[0] += 1 if info[0] == 1: object._reset_trait_value() else: info = self.deferrals.get( obj_id ) if info is not None: info[0] -= 1 if info[0] == 0: deferrals = info[1] for trait_name in deferrals.keys(): notifiers, old_value, new_value = deferrals[ trait_name ] for notifier in notifiers.values(): notifier( object, trait_name, old_value, new_value ) del self.deferrals[ obj_id ] object._reset_trait_value() def defer_notify ( self, notifier, object, trait_name, old, new ): info = self.deferrals[ id( object ) ][1].setdefault( trait_name, [ {}, old, new ] ) info[0].setdefault( id( notifier ), notifier ) info[2] = new #------------------------------------------------------------------------------- # 'ClassTraitNotifierBinder' class: #------------------------------------------------------------------------------- class ClassTraitNotifierBinder: def __init__ ( self, notifiers, bind_factory ): self.notifiers = notifiers self.bind_factory = bind_factory def __call__ ( self, object, name, value, default ): self.notifiers[ name ] = notifier = self.bind_factory( name ) return notifier( object, name, value, default ) def deferred ( self, object, name, value, default ): self.notifiers[ name ] = notifier = self.bind_factory( name ) return notifier.deferred( object, name, value, default ) #------------------------------------------------------------------------------- # 'SimpleSetTraitValue' class: #------------------------------------------------------------------------------- class SimpleSetTraitValue: def __call__ ( self, object, name, value, default ): object.__dict__[ name ] = value return value def deferred ( self, object, name, value, default ): object.__dict__[ name ] = value return value simple_set_trait_value = SimpleSetTraitValue() #------------------------------------------------------------------------------- # 'IgnoreSetTraitValue' class: #------------------------------------------------------------------------------- class IgnoreSetTraitValue: def __call__ ( self, object, name, value, default ): pass def deferred ( self, object, name, value, default ): pass ignore_set_trait_value = IgnoreSetTraitValue() #------------------------------------------------------------------------------- # 'SpecificTraitNotifier' class: #------------------------------------------------------------------------------- class SpecificTraitNotifier: def __init__ ( self, notifier ): self.notifier = notifier def __call__ ( self, object, name, value, default ): obj_dict = object.__dict__ old_value = obj_dict.get( name, default ) try: if old_value != value: obj_dict[ name ] = value self.notifier( object, name, old_value, value ) return value else: obj_dict[ name ] = value return value except: obj_dict[ name ] = value self.notifier( object, name, old_value, value ) return value def deferred ( self, object, name, value, default ): obj_dict = object.__dict__ old_value = obj_dict.get( name, default ) try: if old_value != value: obj_dict[ name ] = value getattr( object.__class__, TraitNotifier ).defer_notify( self.notifier, object, name, old_value, value ) return value else: obj_dict[ name ] = value return value except: obj_dict[ name ] = value getattr( object.__class__, TraitNotifier ).defer_notify( self.notifier, object, name, old_value, value ) return value #------------------------------------------------------------------------------- # 'SpecificEventNotifier' class: #------------------------------------------------------------------------------- class SpecificEventNotifier: def __init__ ( self, notifier ): self.notifier = notifier def __call__ ( self, object, name, value, default ): self.notifier( object, name, None, value ) return value def deferred ( self, object, name, value, default ): getattr( object.__class__, TraitNotifier ).defer_notify( self.notifier, object, name, None, value ) return value #------------------------------------------------------------------------------- # 'AnyAndSpecificTraitNotifier' class: #------------------------------------------------------------------------------- class AnyAndSpecificTraitNotifier: def __init__ ( self, anytrait_notifier, notifier ): self.anytrait_notifier = anytrait_notifier self.notifier = StaticTraitChangeNotifyWrapper( notifier ) def __call__ ( self, object, name, value, default ): obj_dict = object.__dict__ old_value = obj_dict.get( name, default ) try: if old_value != value: obj_dict[ name ] = value self.notifier( object, name, old_value, value ) self.anytrait_notifier( object, name, old_value, value ) return value else: obj_dict[ name ] = value return value except: obj_dict[ name ] = value self.notifier( object, name, old_value, value ) self.anytrait_notifier( object, name, old_value, value ) return value def deferred ( self, object, name, value, default ): obj_dict = object.__dict__ old_value = obj_dict.get( name, default ) try: if old_value != value: obj_dict[ name ] = value tnotifier = getattr( object.__class__, TraitNotifier ) tnotifier.defer_notify( self.notifier, object, name, old_value, value ) tnotifier.defer_notify( self.anytrait_notifier, object, name, old_value, value ) return value else: obj_dict[ name ] = value return value except: obj_dict[ name ] = value tnotifier = getattr( object.__class__, TraitNotifier ) tnotifier.defer_notify( self.notifier, object, name, old_value, value ) tnotifier.defer_notify( self.anytrait_notifier, object, name, old_value, value ) return value #------------------------------------------------------------------------------- # 'AnyAndSpecificEventNotifier' class: #------------------------------------------------------------------------------- class AnyAndSpecificEventNotifier: def __init__ ( self, anytrait_notifier, notifier ): self.anytrait_notifier = anytrait_notifier self.notifier = StaticTraitChangeNotifyWrapper( notifier ) def __call__ ( self, object, name, value, default ): self.notifier( object, name, None, value ) self.anytrait_notifier( object, name, None, value ) return value def deferred ( self, object, name, value, default ): tnotifier = getattr( object.__class__, TraitNotifier ) tnotifier.defer_notify( self.notifier, object, name, None, value ) tnotifier.defer_notify( self.anytrait_notifier, object, name, None, value ) return value
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,327
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/makewcs.py
""" MAKEWCS.PY - Updated the WCS in an image header so that it matches the geometric distortion defined in an IDC table which is referenced in the image header. License: http://www.stsci.edu/resources/software_hardware/pyraf/LICENSE This version tries to implement a full updating of the WCS based on information about the V2/V3 plane which is obtained from th IDCTAB and, in the case of WFPC2, the OFFTAB. The only parameters from the original WCS which are retained are the CRVALs of the reference chip. The original WCS are first copied to MCD1_1 etc before being updated. :UPINCD History: First try, Richard Hook, ST-ECF/STScI, August 2002. Version 0.0.1 (WJH) - Obtain IDCTAB using PyDrizzle function. Version 0.1 (WJH) - Added support for processing image lists. Revised to base CD matrix on ORIENTAT, instead of PA_V3 Supports subarrays by shifting coefficients as needed. Version 0.2 (WJH) - Implemented orientation computation based on PA_V3 using Troll function from Colin to compute new ORIENTAT value. Version 0.3 (WJH) - Supported filter dependent distortion models in IDCTAB fixed bugs in applying Troll function to WCS. Version 0.4 (WJH) - Updated to support use of 'defaultModel' for generic cases: XREF/YREF defaults to image center and idctab name defaults to None. Version 0.5 (WJH) - Added support for WFPC2 OFFTAB updates, which updates the CRVALs. However, for WFPC2 data, the creation of the backup values does not currently work. :MAKEWCS History: MAKEWCS V0.0 (RNH) - Created new version to implement more complete WCS creation based on a reference tangent plane. V0.1 (RNH) - First working version for tests. May 20th 2004. V0.11 (RNH) - changed reference chip for ACS/WFC. May 26th 2004. V0.2 (WJH) - Removed all dependencies from IRAF and use new WCSObject class for all WCS operations. V0.4 (WJH/CJH) - Corrected logic for looping of extension in FITS image. V0.5 (RNH) - Chip to chip CRVAL shifting logic change. V0.6 (CJH/WJH) - Added support for non-associated STIS data. V0.6.2 (WJH) - Added support for NICMOS data. This required new versions of wcsutil and fileutil in PyDrizzle. V0.6.3 (WJH) - Modified to support new version of WCSUtil which correctly sets up and uses archived WCS keywords. V0.7.0 (WJH) - Revised algorithm to work properly with subarray images. Also, simplified keyword access using PyFITS object. V0.8.0 (CJH) - Modified to work with either numarray or numpy through the use of the numerix interface layer. """ from __future__ import division, print_function # confidence high from stsci.tools import numerixenv numerixenv.check() #import iraf from math import * import os.path from astropy.io import fits as pyfits from . import drutil from .distortion import models, mutil from stsci.tools import fileutil, wcsutil, parseinput import numpy as N yes = True no = False # Define parity matrices for supported detectors. # These provide conversion from XY to V2/V3 coordinate systems. # Ideally, this information could be included in IDCTAB... PARITY = {'WFC':[[1.0,0.0],[0.0,-1.0]],'HRC':[[-1.0,0.0],[0.0,1.0]], 'SBC':[[-1.0,0.0],[0.0,1.0]],'default':[[1.0,0.0],[0.0,1.0]], 'WFPC2':[[-1.0,0.],[0.,1.0]],'STIS':[[-1.0,0.],[0.,1.0]], 'NICMOS':[[-1.0,0.],[0.,1.0]], 'UVIS':[[-1.0,0.0],[0.0,1.0]], 'IR':[[-1.0,0.0],[0.0,1.0]] } NUM_PER_EXTN = {'ACS':3,'WFPC2':1,'STIS':3,'NICMOS':5, 'WFC3':3} __version__ = '1.1.7 (6 Jul 2010)' def run(input,quiet=yes,restore=no,prepend='O', tddcorr=True): print("+ MAKEWCS Version %s" % __version__) _prepend = prepend files = parseinput.parseinput(input)[0] newfiles = [] if files == []: print("No valid input files found.\n") raise IOError for image in files: #find out what the input is imgfits,imgtype = fileutil.isFits(image) # Check for existence of waiver FITS input, and quit if found. if imgfits and imgtype == 'waiver': """ errormsg = '\n\nPyDrizzle does not support waiver fits format.\n' errormsg += 'Convert the input files to GEIS or multiextension FITS.\n\n' raise ValueError, errormsg """ newfilename = fileutil.buildNewRootname(image, extn='_c0h.fits') # Convert GEIS image to MEF file newimage = fileutil.openImage(image,writefits=True,fitsname=newfilename,clobber=True) del newimage # Work with new file image = newfilename newfiles.append(image) # If a GEIS image is provided as input, create a new MEF file with # a name generated using 'buildFITSName()' and update that new MEF file. if not imgfits: # Create standardized name for MEF file newfilename = fileutil.buildFITSName(image) # Convert GEIS image to MEF file newimage = fileutil.openImage(image,writefits=True,fitsname=newfilename,clobber=True) del newimage # Work with new file image = newfilename newfiles.append(image) if not quiet: print("Input files: ",files) # First get the name of the IDC table #idctab = drutil.getIDCFile(_files[0][0],keyword='idctab')[0] idctab = drutil.getIDCFile(image,keyword='idctab')[0] _found = fileutil.findFile(idctab) if idctab == None or idctab == '': print('#\n No IDCTAB specified. No correction can be done for file %s.Quitting makewcs\n' %image) #raise ValueError continue elif not _found: print('#\n IDCTAB: ',idctab,' could not be found. \n') print('WCS keywords for file %s will not be updated.\n' %image) #raise IOError continue _phdu = image + '[0]' _instrument = fileutil.getKeyword(_phdu,keyword='INSTRUME') if _instrument == 'WFPC2': Nrefchip, Nrefext = getNrefchip(image) else: Nrefchip = None Nrefext = None if _instrument not in NUM_PER_EXTN: raise ValueError("Instrument %s not supported yet. Exiting..." \ %_instrument) _detector = fileutil.getKeyword(_phdu, keyword='DETECTOR') _nimsets = get_numsci(image) for i in range(_nimsets): if image.find('.fits') > 0: _img = image+'[sci,'+repr(i+1)+']' else: _img = image+'['+repr(i+1)+']' if not restore: if not quiet: print('Updating image: ', _img) _update(_img,idctab, _nimsets, apply_tdd=False, quiet=quiet,instrument=_instrument,prepend=_prepend, nrchip=Nrefchip, nrext = Nrefext) if _instrument == 'ACS' and _detector == 'WFC': tddswitch = fileutil.getKeyword(_phdu,keyword='TDDCORR') # This logic requires that TDDCORR be in the primary header # and set to PERFORM in order to turn this on at all. It can # be turned off by setting either tddcorr=False or setting # the keyword to anything but PERFORM or by deleting the # keyword altogether. PyDrizzle will rely simply on the # values of alpha and beta as computed here to apply the # correction to the coefficients. if (tddcorr and tddswitch != 'OMIT'): print('Applying time-dependent distortion corrections...') _update(_img,idctab, _nimsets, apply_tdd=True, \ quiet=quiet,instrument=_instrument,prepend=_prepend, nrchip=Nrefchip, nrext = Nrefext) else: if not quiet: print('Restoring original WCS values for',_img) restoreCD(_img,_prepend) #fimg = fileutil.openImage(image,mode='update') #if 'TDDCORR' in fimg[0].header and fimg[0].header['TDDCORR'] == 'PERFORM': # fimg[0].header['TDDCORR'] = 'COMPLETE' #fimg.close() if newfiles == []: return files else: return newfiles def restoreCD(image,prepend): _prepend = prepend try: _wcs = wcsutil.WCSObject(image) _wcs.restoreWCS(prepend=_prepend) del _wcs except: print('ERROR: Could not restore WCS keywords for %s.'%image) def _update(image,idctab,nimsets,apply_tdd=False, quiet=None,instrument=None,prepend=None,nrchip=None, nrext=None): tdd_xyref = {1: [2048, 3072], 2:[2048, 1024]} _prepend = prepend _dqname = None # Make a copy of the header for keyword access # This copy includes both Primary header and # extension header hdr = fileutil.getHeader(image) # Try to get the instrument if we don't have it already instrument = readKeyword(hdr,'INSTRUME') binned = 1 # Read in any specified OFFTAB, if present (WFPC2) offtab = readKeyword(hdr,'OFFTAB') dateobs = readKeyword(hdr,'DATE-OBS') if not quiet: print("OFFTAB, DATE-OBS: ",offtab,dateobs) print("-Updating image ",image) if not quiet: print("-Reading IDCTAB file ",idctab) # Get telescope orientation from image header # If PA_V# is not present of header, try to get it from the spt file pvt = readKeyword(hdr,'PA_V3') if pvt == None: sptfile = fileutil.buildNewRootname(image, extn='_spt.fits') if os.path.exists(sptfile): spthdr = fileutil.getHeader(sptfile) pvt = readKeyword(spthdr,'PA_V3') if pvt != None: pvt = float(pvt) else: print('PA_V3 keyword not found, WCS cannot be updated. Quitting ...') raise ValueError # Find out about instrument, detector & filters detector = readKeyword(hdr,'DETECTOR') Nrefchip=1 if instrument == 'WFPC2': filter1 = readKeyword(hdr,'FILTNAM1') filter2 = readKeyword(hdr,'FILTNAM2') mode = readKeyword(hdr,'MODE') if os.path.exists(fileutil.buildNewRootname(image, extn='_c1h.fits')): _dqname = fileutil.buildNewRootname(image, extn='_c1h.fits') dqhdr = pyfits.getheader(_dqname,1) dqext = readKeyword(dqhdr, 'EXTNAME') if mode == 'AREA': binned = 2 Nrefchip=nrchip elif instrument == 'NICMOS': filter1 = readKeyword(hdr,'FILTER') filter2 = None elif instrument == 'WFC3': filter1 = readKeyword(hdr,'FILTER') filter2 = None # use value of 'BINAXIS' keyword to set binning value for WFC3 data binned = readKeyword(hdr,'BINAXIS1') else: filter1 = readKeyword(hdr,'FILTER1') filter2 = readKeyword(hdr,'FILTER2') if filter1 == None or filter1.strip() == '': filter1 = 'CLEAR' else: filter1 = filter1.strip() if filter2 == None or filter2.strip() == '': filter2 = 'CLEAR' else: filter2 = filter2.strip() if filter1.find('CLEAR') == 0: filter1 = 'CLEAR' if filter2.find('CLEAR') == 0: filter2 = 'CLEAR' # Set up parity matrix for chip if instrument == 'WFPC2' or instrument =='STIS' or instrument == 'NICMOS': parity = PARITY[instrument] elif detector in PARITY: parity = PARITY[detector] else: raise ValueError('Detector ',detector, ' Not supported at this time. Exiting...') # Get the VAFACTOR keyword if it exists, otherwise set to 1.0 # we also need the reference pointing position of the target # as this is where _va_key = readKeyword(hdr,'VAFACTOR') if _va_key != None: VA_fac = float(_va_key) else: VA_fac=1.0 if not quiet: print('VA factor: ',VA_fac) #ra_targ = float(readKeyword(hdr,'RA_TARG')) #dec_targ = float(readKeyword(hdr,'DEC_TARG')) # Get the chip number _c = readKeyword(hdr,'CAMERA') _s = readKeyword(hdr,'CCDCHIP') _d = readKeyword(hdr,'DETECTOR') if _c != None and str(_c).isdigit(): chip = int(_c) elif _s == None and _d == None: chip = 1 else: if _s: chip = int(_s) elif str(_d).isdigit(): chip = int(_d) else: chip = 1 # For the ACS/WFC case the chip number doesn't match the image # extension nr = 1 if (instrument == 'ACS' and detector == 'WFC') or (instrument == 'WFC3' and detector == 'UVIS'): if nimsets > 1: Nrefchip = 2 else: Nrefchip = chip elif instrument == 'NICMOS': Nrefchip = readKeyword(hdr,'CAMERA') elif instrument == 'WFPC2': nr = nrext else: if nimsets > 1: nr = Nrefchip if not quiet: print("-PA_V3 : ",pvt," CHIP #",chip) # Extract the appropriate information from the IDCTAB #fx,fy,refpix,order=fileutil.readIDCtab(idctab,chip=chip,direction='forward', # filter1=filter1,filter2=filter2,offtab=offtab,date=dateobs) idcmodel = models.IDCModel(idctab, chip=chip, direction='forward', date=dateobs, filter1=filter1, filter2=filter2, offtab=offtab, binned=binned, tddcorr=apply_tdd) fx = idcmodel.cx fy = idcmodel.cy refpix = idcmodel.refpix order = idcmodel.norder # Determine whether to perform time-dependent correction # Construct matrices neded to correct the zero points for TDD if apply_tdd: #alpha,beta = mutil.compute_wfc_tdd_coeffs(dateobs,skew_coeffs) alpha = refpix['TDDALPHA'] beta = refpix['TDDBETA'] tdd = N.array([[beta, alpha], [alpha, -beta]]) mrotp = fileutil.buildRotMatrix(2.234529)/2048. else: alpha = 0.0 beta = 0.0 # Get the original image WCS Old=wcsutil.WCSObject(image,prefix=_prepend) # Reset the WCS keywords to original archived values. Old.restore() # # Look for any subarray offset # ltv1,ltv2 = drutil.getLTVOffsets(image) # # If reference point is not centered on distortion model # shift coefficients to be applied relative to observation # reference position # offsetx = Old.crpix1 - ltv1 - refpix['XREF'] offsety = Old.crpix2 - ltv2 - refpix['YREF'] shiftx = refpix['XREF'] + ltv1 shifty = refpix['YREF'] + ltv2 if ltv1 != 0. or ltv2 != 0.: ltvoffx = ltv1 + offsetx ltvoffy = ltv2 + offsety offshiftx = offsetx + shiftx offshifty = offsety + shifty else: ltvoffx = 0. ltvoffy = 0. offshiftx = 0. offshifty = 0. if ltv1 != 0. or ltv2 != 0.: fx,fy = idcmodel.shift(idcmodel.cx,idcmodel.cy,offsetx,offsety) # Extract the appropriate information for reference chip ridcmodel = models.IDCModel(idctab, chip=Nrefchip, direction='forward', date=dateobs, filter1=filter1, filter2=filter2, offtab=offtab, binned=binned, tddcorr=apply_tdd) rfx = ridcmodel.cx rfy = ridcmodel.cy rrefpix = ridcmodel.refpix rorder = ridcmodel.norder """ rfx,rfy,rrefpix,rorder=mutil.readIDCtab(idctab,chip=Nrefchip, direction='forward', filter1=filter1,filter2=filter2,offtab=offtab, date=dateobs,tddcorr=apply_tdd) """ # Create the reference image name rimage = image.split('[')[0]+"[sci,%d]" % nr if not quiet: print("Reference image: ",rimage) # Create the tangent plane WCS on which the images are defined # This is close to that of the reference chip R=wcsutil.WCSObject(rimage) R.write_archive(rimage) R.restore() # Reacd in declination of target (for computing orientation at aperture) # Note that this is from the reference image #dec = float(fileutil.getKeyword(rimage,'CRVAL2')) #crval1 = float(fileutil.getKeyword(rimage,'CRVAL1')) #crval1 = float(R.crval1) #crval2 = dec dec = float(R.crval2) # Get an approximate reference position on the sky rref = (rrefpix['XREF']+ltvoffx, rrefpix['YREF']+ltvoffy) crval1,crval2=R.xy2rd(rref) if apply_tdd: # Correct zero points for TDD tddscale = (R.pscale/fx[1][1]) rxy0 = N.array([[tdd_xyref[Nrefchip][0]-2048.],[ tdd_xyref[Nrefchip][1]-2048.]]) xy0 = N.array([[tdd_xyref[chip][0]-2048.], [tdd_xyref[chip][1]-2048.]]) rv23_corr = N.dot(mrotp,N.dot(tdd,rxy0))*tddscale v23_corr = N.dot(mrotp,N.dot(tdd,xy0))*tddscale else: rv23_corr = N.array([[0],[0]]) v23_corr = N.array([[0],[0]]) # Convert the PA_V3 orientation to the orientation at the aperture # This is for the reference chip only - we use this for the # reference tangent plane definition # It has the same orientation as the reference chip v2ref = rrefpix['V2REF'] + rv23_corr[0][0]*0.05 v3ref = rrefpix['V3REF'] - rv23_corr[1][0]*0.05 v2 = refpix['V2REF'] + v23_corr[0][0]*0.05 v3 = refpix['V3REF'] - v23_corr[1][0] *0.05 pv = wcsutil.troll(pvt,dec,v2ref,v3ref) # Add the chip rotation angle if rrefpix['THETA']: pv += rrefpix['THETA'] # Set values for the rest of the reference WCS R.crval1=crval1 R.crval2=crval2 R.crpix1=0.0 + offshiftx R.crpix2=0.0 + offshifty R_scale=rrefpix['PSCALE']/3600.0 R.cd11=parity[0][0] * cos(pv*pi/180.0)*R_scale R.cd12=parity[0][0] * -sin(pv*pi/180.0)*R_scale R.cd21=parity[1][1] * sin(pv*pi/180.0)*R_scale R.cd22=parity[1][1] * cos(pv*pi/180.0)*R_scale ##print R R_cdmat = N.array([[R.cd11,R.cd12],[R.cd21,R.cd22]]) if not quiet: print(" Reference Chip Scale (arcsec/pix): ",rrefpix['PSCALE']) # Offset and angle in V2/V3 from reference chip to # new chip(s) - converted to reference image pixels off = sqrt((v2-v2ref)**2 + (v3-v3ref)**2)/(R_scale*3600.0) # Here we must include the PARITY if v3 == v3ref: theta=0.0 else: theta = atan2(parity[0][0]*(v2-v2ref),parity[1][1]*(v3-v3ref)) if rrefpix['THETA']: theta += rrefpix['THETA']*pi/180.0 dX=(off*sin(theta)) + offshiftx dY=(off*cos(theta)) + offshifty # Check to see whether we are working with GEIS or FITS input _fname,_iextn = fileutil.parseFilename(image) if _fname.find('.fits') < 0: # Input image is NOT a FITS file, so # build a FITS name for it's copy. _fitsname = fileutil.buildFITSName(_fname) else: _fitsname = None # Create a new instance of a WCS if _fitsname == None: _new_name = image else: _new_name = _fitsname+'['+str(_iextn)+']' #New=wcsutil.WCSObject(_new_name,new=yes) New = Old.copy() # Calculate new CRVALs and CRPIXs New.crval1,New.crval2=R.xy2rd((dX,dY)) New.crpix1=refpix['XREF'] + ltvoffx New.crpix2=refpix['YREF'] + ltvoffy # Account for subarray offset # Angle of chip relative to chip if refpix['THETA']: dtheta = refpix['THETA'] - rrefpix['THETA'] else: dtheta = 0.0 # Create a small vector, in reference image pixel scale # There is no parity effect here ??? delXX=fx[1,1]/R_scale/3600. delYX=fy[1,1]/R_scale/3600. delXY=fx[1,0]/R_scale/3600. delYY=fy[1,0]/R_scale/3600. # Convert to radians rr=dtheta*pi/180.0 # Rotate the vectors dXX= cos(rr)*delXX - sin(rr)*delYX dYX= sin(rr)*delXX + cos(rr)*delYX dXY= cos(rr)*delXY - sin(rr)*delYY dYY= sin(rr)*delXY + cos(rr)*delYY # Transform to sky coordinates a,b=R.xy2rd((dX+dXX,dY+dYX)) c,d=R.xy2rd((dX+dXY,dY+dYY)) # Calculate the new CDs and convert to degrees New.cd11=diff_angles(a,New.crval1)*cos(New.crval2*pi/180.0) New.cd12=diff_angles(c,New.crval1)*cos(New.crval2*pi/180.0) New.cd21=diff_angles(b,New.crval2) New.cd22=diff_angles(d,New.crval2) # Apply the velocity aberration effect if applicable if VA_fac != 1.0: # First shift the CRVALs apart # New.crval1 = ra_targ + VA_fac*(New.crval1 - ra_targ) # New.crval2 = dec_targ + VA_fac*(New.crval2 - dec_targ) # First shift the CRVALs apart # This is now relative to the reference chip, not the # target position. New.crval1 = R.crval1 + VA_fac*diff_angles(New.crval1, R.crval1) New.crval2 = R.crval2 + VA_fac*diff_angles(New.crval2, R.crval2) # and scale the CDs New.cd11 = New.cd11*VA_fac New.cd12 = New.cd12*VA_fac New.cd21 = New.cd21*VA_fac New.cd22 = New.cd22*VA_fac New_cdmat = N.array([[New.cd11,New.cd12],[New.cd21,New.cd22]]) # Store new one # archive=yes specifies to also write out archived WCS keywords # overwrite=no specifies do not overwrite any pre-existing archived keywords New.write(fitsname=_new_name,overwrite=no,quiet=quiet,archive=yes) if _dqname: _dq_iextn = _iextn.replace('sci', dqext.lower()) _new_dqname = _dqname +'['+_dq_iextn+']' dqwcs = wcsutil.WCSObject(_new_dqname) dqwcs.write(fitsname=_new_dqname, wcs=New,overwrite=no,quiet=quiet, archive=yes) """ Convert distortion coefficients into SIP style values and write out to image (assumed to be FITS). """ #First the CD matrix: f = refpix['PSCALE']/3600.0 a = fx[1,1]/3600.0 b = fx[1,0]/3600.0 c = fy[1,1]/3600.0 d = fy[1,0]/3600.0 det = (a*d - b*c)*refpix['PSCALE'] # Write to header fimg = fileutil.openImage(_new_name,mode='update') _new_root,_nextn = fileutil.parseFilename(_new_name) _new_extn = fileutil.getExtn(fimg,_nextn) # Transform the higher-order coefficients for n in range(order+1): for m in range(order+1): if n >= m and n>=2: # Form SIP-style keyword names Akey="A_%d_%d" % (m,n-m) Bkey="B_%d_%d" % (m,n-m) # Assign them values Aval= f*(d*fx[n,m]-b*fy[n,m])/det Bval= f*(a*fy[n,m]-c*fx[n,m])/det _new_extn.header.update(Akey,Aval) _new_extn.header.update(Bkey,Bval) # Update the SIP flag keywords as well #iraf.hedit(image,"CTYPE1","RA---TAN-SIP",verify=no,show=no) #iraf.hedit(image,"CTYPE2","DEC--TAN-SIP",verify=no,show=no) _new_extn.header.update("CTYPE1","RA---TAN-SIP") _new_extn.header.update("CTYPE2","DEC--TAN-SIP") # Finally we also need the order #iraf.hedit(image,"A_ORDER","%d" % order,add=yes,verify=no,show=no) #iraf.hedit(image,"B_ORDER","%d" % order,add=yes,verify=no,show=no) _new_extn.header.update("A_ORDER",order) _new_extn.header.update("B_ORDER",order) # Update header with additional keywords required for proper # interpretation of SIP coefficients by PyDrizzle. _new_extn.header.update("IDCSCALE",refpix['PSCALE']) _new_extn.header.update("IDCV2REF",refpix['V2REF']) _new_extn.header.update("IDCV3REF",refpix['V3REF']) _new_extn.header.update("IDCTHETA",refpix['THETA']) _new_extn.header.update("OCX10",fx[1][0]) _new_extn.header.update("OCX11",fx[1][1]) _new_extn.header.update("OCY10",fy[1][0]) _new_extn.header.update("OCY11",fy[1][1]) #_new_extn.header.update("TDDXOFF",rv23_corr[0][0] - v23_corr[0][0]) #_new_extn.header.update("TDDYOFF",-(rv23_corr[1][0] - v23_corr[1][0])) # Report time-dependent coeffs, if computed if instrument == 'ACS' and detector == 'WFC': _new_extn.header.update("TDDALPHA",alpha) _new_extn.header.update("TDDBETA",beta) # Close image now fimg.close() del fimg def diff_angles(a,b): """ Perform angle subtraction a-b taking into account small-angle differences across 360degree line. """ diff = a - b if diff > 180.0: diff -= 360.0 if diff < -180.0: diff += 360.0 return diff def readKeyword(hdr,keyword): try: value = hdr[keyword] except KeyError: value = None # NOTE: Need to clean up the keyword.. Occasionally the keyword value # goes right up to the "/" FITS delimiter, and iraf.keypar is incapable # of realizing this, so it incorporates "/" along with the keyword value. # For example, after running "pydrizzle" on the image "j8e601bkq_flt.fits", # the CD keywords look like this: # # CD1_1 = 9.221627430999639E-06/ partial of first axis coordinate w.r.t. x # CD1_2 = -1.0346992614799E-05 / partial of first axis coordinate w.r.t. y # # so for CD1_1, iraf.keypar returns: # "9.221627430999639E-06/" # # So, the following piece of code CHECKS for this and FIXES the string, # very simply by removing the last character if it is a "/". # This fix courtesy of Anton Koekemoer, 2002. if type(value) == type(''): if value[-1:] == '/': value = value[:-1] return value def get_numsci(image): """ Find the number of SCI extensions in the image. Input: image - name of single input image """ handle = fileutil.openImage(image) num_sci = 0 for extn in handle: if 'extname' in extn.header: if extn.header['extname'].lower() == 'sci': num_sci += 1 handle.close() return num_sci def shift_coeffs(cx,cy,xs,ys,norder): """ Shift reference position of coefficients to new center where (xs,ys) = old-reference-position - subarray/image center. This will support creating coeffs files for drizzle which will be applied relative to the center of the image, rather than relative to the reference position of the chip. Derived directly from PyDrizzle V3.3d. """ _cxs = N.zeros(shape=cx.shape,dtype=cx.dtype.name) _cys = N.zeros(shape=cy.shape,dtype=cy.dtype.name) _k = norder + 1 # loop over each input coefficient for m in range(_k): for n in range(_k): if m >= n: # For this coefficient, shift by xs/ys. _ilist = N.array(list(range(_k - m))) + m # sum from m to k for i in _ilist: _jlist = N.array(list(range( i - (m-n) - n + 1))) + n # sum from n to i-(m-n) for j in _jlist: _cxs[m,n] = _cxs[m,n] + cx[i,j]*pydrizzle._combin(j,n)*pydrizzle._combin((i-j),(m-n))*pow(xs,(j-n))*pow(ys,((i-j)-(m-n))) _cys[m,n] = _cys[m,n] + cy[i,j]*pydrizzle._combin(j,n)*pydrizzle._combin((i-j),(m-n))*pow(xs,(j-n))*pow(ys,((i-j)-(m-n))) _cxs[0,0] = _cxs[0,0] - xs _cys[0,0] = _cys[0,0] - ys #_cxs[0,0] = 0. #_cys[0,0] = 0. return _cxs,_cys def getNrefchip(image,instrument='WFPC2'): """ This handles the fact that WFPC2 subarray observations may not include chip 3 which is the default reference chip for full observations. Also for subarrays chip 3 may not be the third extension in a MEF file. It is a kludge but this whole module is one big kludge. ND """ hdu = fileutil.openImage(image) if instrument == 'WFPC2': detectors = [img.header['DETECTOR'] for img in hdu[1:]] if 3 not in detectors: Nrefchip=detectors[0] Nrefext = 1 else: Nrefchip = 3 Nrefext = detectors.index(3) + 1 hdu.close() return Nrefchip, Nrefext _help_str = """ makewcs - a task for updating an image header WCS to make it consistent with the distortion model and velocity aberration. This task will read in a distortion model from the IDCTAB and generate a new WCS matrix based on the value of ORIENTAT. It will support subarrays by shifting the distortion coefficients to image reference position before applying them to create the new WCS, including velocity aberration. Original WCS values will be moved to an O* keywords (OCD1_1,...). Currently, this task will only support ACS and WFPC2 observations. Parameters ---------- input: str The filename(s) of image(s) to be updated given either as: * a single image with extension specified, * a substring common to all desired image names, * a wildcarded filename * '@file' where file is a file containing a list of images quiet: bool turns off ALL reporting messages: 'yes' or 'no'(default) prepend: char This parameter specifies what prefix letter should be used to create a new set of WCS keywords for recording the original values [Default: 'O'] restore: bool restore WCS for all input images to defaults if possible: 'yes' or 'no'(default) tddcorr: bool applies the time-dependent skew terms to the SIP coefficients written out to the header: 'yes' or True or, 'no' or False (default). Notes ----- This function can be run using the syntax: makewcs.run(image,quiet=no,prepend='O',restore=no,tddcorr=True) An example of how this can be used is given as:: >>> import makewcs >>> makewcs.run('raw') # This will update all _raw files in directory >>> makewcs.run('j8gl03igq_raw.fits[sci,1]') """ def help(): print(_help_str) run.__doc__ = _help_str
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,328
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/__init__.py
from __future__ import absolute_import, division, print_function # confidence high from stsci.tools import numerixenv numerixenv.check() yes = True # 1 no = False # 0 from .drutil import DEFAULT_IDCDIR from math import * from .version import * def PyDrizzle(input, output=None, field=None, units=None, section=None, kernel=None,pixfrac=None,bits_final=0,bits_single=0, wt_scl='exptime', fillval=0.,idckey='', in_units='counts', idcdir=DEFAULT_IDCDIR,memmap=0,dqsuffix=None,prodonly=False, shiftfile=None,updatewcs=True): from . import pydrizzle from . import process_input asndict, ivmlist, output = process_input.process_input( input, output=output, prodonly=prodonly, updatewcs=updatewcs, shiftfile=shiftfile) if not asndict: return None p = pydrizzle._PyDrizzle(asndict, output=output,field=field, units=units, idckey=idckey, section=section, kernel= kernel, pixfrac=pixfrac, bits_single=bits_single, bits_final=bits_final, wt_scl=wt_scl, fillval=fillval, in_units=in_units, idcdir=idcdir, memmap=memmap, dqsuffix=dqsuffix) return p def help(): from . import pydrizzle print(pydrizzle._PyDrizzle.__doc__)
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,329
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/traits102/standard.py
#------------------------------------------------------------------------------- # # Define a set of standard, commonly useful predefined traits. # # Written by: David C. Morrill # # Date: 07/28/2003 # # Symbols defined: # # (c) Copyright 2002, 2003 by Enthought, Inc. # #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- # Imports: #------------------------------------------------------------------------------- from __future__ import absolute_import, division # confidence high from .traits import Trait from .trait_handlers import TraitString, TraitPrefixList, TraitEnum, TraitList from .trait_base import trait_editors #------------------------------------------------------------------------------- # Trait Editor definitions: #------------------------------------------------------------------------------- trait_editors = trait_editors() if trait_editors: boolean_editor = trait_editors.TraitEditorBoolean() else: boolean_editor = None #------------------------------------------------------------------------------- # Boolean traits: #------------------------------------------------------------------------------- false_trait = Trait( False, TraitEnum( False, True ), editor = boolean_editor ) true_trait = Trait( True, false_trait ) flexible_true_trait = Trait( 'true', { 'true': 1, 't': 1, 'yes': 1, 'y': 1, 'on': 1, 1: 1, 'false': 0, 'f': 0, 'no': 0, 'n': 0, 'off': 0, 0: 0 }, editor = boolean_editor ) flexible_false_trait = Trait( 'false', flexible_true_trait ) #------------------------------------------------------------------------------- # Zip Code related traits: #------------------------------------------------------------------------------- # 5 digit zip code (DDDDD): zipcode_5_trait = Trait( '99999', TraitString( regex = r'^\d{5,5}$' ) ) # 9 digit zip code (DDDDD-DDDD): zipcode_9_trait = Trait( '99999-9999', TraitString( regex = r'^\d{5,5}[ -]?\d{4,4}$' ) ) #------------------------------------------------------------------------------- # United States state related traits: #------------------------------------------------------------------------------- # Long form of the 50 United States state names: us_states_long_trait = Trait( 'Texas', TraitPrefixList( [ 'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming' ] ) ) # Abbreviated form of the 50 United States state names: us_states_short_trait = Trait( 'TX', [ 'AL', 'AK', 'AR', 'AZ', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'HI', 'ID', 'IA', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MI', 'MO', 'MN', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NY', 'NV', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VA', 'VT', 'WA', 'WI', 'WV', 'WY' ] ) # Long form of all United States state and territory names: all_us_states_long_trait = Trait( 'Texas', TraitPrefixList( [ 'Alabama', 'Alaska', 'American Samoa', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'District of Columbia','Florida', 'Georgia', 'Guam', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Puerto Rico', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virgin Islands', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming' ] ) ) # Abbreviated form of all United States state and territory names: all_us_states_short_trait = Trait( 'TX', [ 'AL', 'AK', 'AS', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'GU', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'PR', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VI', 'VA', 'WA', 'WV', 'WI', 'WY' ] ) #------------------------------------------------------------------------------- # Word country related traits: #------------------------------------------------------------------------------- # Long form of world country names: countries_long_trait = Trait( 'United States', TraitPrefixList( [ 'Afghanistan', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bhutan', 'Bolivia', 'Bosnia and Herzegovina', 'Botswana', 'Brazil', 'Brunei', 'Bulgaria', 'Burkina Faso', 'Burma/Myanmar', 'Burundi', 'Cambodia', 'Cameroon', 'Canada', 'Cape Verde', 'Central African Republic', 'Chad', 'Chile', 'China', 'Colombia', 'Comoros', 'Congo', 'Democratic Republic of Congo', 'Costa Rica', 'Cote d\'Ivoire/Ivory Coast', 'Croatia', 'Cuba', 'Cyprus', 'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic', 'East Timor', 'Ecuador', 'Egypt', 'El Salvador', 'Equatorial Guinea', 'Eritrea', 'Estonia', 'Ethiopia', 'Fiji', 'Finland', 'France', 'Gabon', 'Gambia', 'Georgia', 'Germany', 'Ghana', 'Greece', 'Grenada', 'Guatemala', 'Guinea', 'Guinea-Bissau', 'Guyana', 'Haiti', 'Honduras', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Iran', 'Iraq', 'Ireland', 'Israel', 'Italy', 'Jamaica', 'Japan', 'Jordan', 'Kazakstan', 'Kenya', 'Kiribati', 'North Korea', 'South Korea', 'Kuwait', 'Kyrgyzstan', 'Laos', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Macedonia', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands', 'Mauritania', 'Mauritius', 'Mexico', 'Micronesia', 'Moldova', 'Monaco', 'Mongolia', 'Morocco', 'Mozambique', 'Namibia', 'Nauru', 'Nepal', 'Netherlands', 'New Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'Norway', 'Oman', 'Pakistan', 'Palau', 'Panama', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines', 'Poland', 'Portugal', 'Qatar', 'Romania', 'Russian Federation East of the Ural Mountains', 'Russian Federation West of the Ural Mountains', 'Rwanda', 'Saint Kitts and Nevis', 'Saint Lucia', 'Saint Vincent and the Grenadines', 'Samoa', 'San Marino', 'Sao Tome and Principe', 'Saudi Arabia', 'Senegal', 'Seychelles', 'Sierra Leone', 'Singapore', 'Slovakia', 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'Spain', 'Sri Lanka', 'Sudan', 'Suriname', 'Swaziland', 'Sweden', 'Switzerland', 'Syria', 'Taiwan', 'Tajikistan', 'Tanzania', 'Thailand', 'Togo', 'Tonga', 'Trinidad and Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Tuvalu', 'Uganda', 'Ukraine', 'United Arab Emirates', 'United Kingdom', 'United States', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Vatican City', 'Venezuela', 'Vietnam', 'Yemen', 'Yugoslavia', 'Zambia', 'Zimbabwe' ] ) ) #------------------------------------------------------------------------------- # Calendar related traits: #------------------------------------------------------------------------------- # Long form of month names: month_long_trait = Trait( 'January', TraitPrefixList( [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] ), cols = 2 ) # Short form of month names: month_short_trait = Trait( 'Jan', [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ], cols = 2 ) # Long form of day of week names: day_of_week_long_trait = Trait( 'Sunday', TraitPrefixList( [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ] ), cols = 1 ) # Short form of day of week names: day_of_week_short_trait = Trait( 'Sun', [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ], cols = 1 ) #------------------------------------------------------------------------------- # Telephone Number related traits: #------------------------------------------------------------------------------- # Local United States phone number: phone_short_trait = Trait( '555-1212', TraitString( regex = r'^\d{3,3}[ -]?\d{4,4}$' ) ) # Long distance United States phone number: phone_long_trait = Trait( '800-555-1212', TraitString( regex = r'^\d{3,3}[ -]?\d{3,3}[ -]?\d{4,4}$|' r'^\(\d{3,3}\) ?\d{3,3}[ -]?\d{4,4}$' ) ) #------------------------------------------------------------------------------- # Miscellaneous traits: #------------------------------------------------------------------------------- # United States Social Security Number: ssn_trait = Trait( '000-00-0000', TraitString( regex = r'^\d{3,3}[ -]?\d{2,2}[ -]?\d{4,4}$' ) ) #------------------------------------------------------------------------------- # Simple List Based Traits: #------------------------------------------------------------------------------- # Define an unbounded, initially empty, list of 'string's trait: string_list_trait = Trait( [], TraitList( '' ) ) # Define an unbounded, initially empty, list of 'int's trait: int_list_trait = Trait( [], TraitList( 0 ) ) # Define an unbounded, initially empty, list of 'float's trait: float_list_trait = Trait( [], TraitList( 0.0 ) ) # Define an unbounded, initially empty, list of 'complex's trait: complex_list_trait = Trait( [], TraitList( 1j ) )
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,330
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/drutil.py
""" Utility functions for PyDrizzle that rely on PyRAF's interface to IRAF tasks. """ # # Revision History: # Nov 2001: Added function (getLTVOffsets) for reading subarray offsets # from extension header's LTV keywords. WJH # Mar 2002: Restructured to only contain IRAF based functions. # 20-Sept-2002: Replaced all calls to 'keypar' with calls to 'hselect'. # This eliminates any parameter writing, making it safer for # pipeline/multi-process use. # 24-Sept-2003: Replaced all calls to hselect with calls to # fileutil.getKeyword() to remove dependencies on IRAF. # Also, replaced 'yes' and 'no' with Python Bool vars. # from __future__ import division, print_function # confidence medium import os from math import ceil,floor import numpy as np from numpy import linalg from stsci.tools import fileutil from stsci.tools.fileutil import buildRotMatrix # Convenience definitions DEGTORAD = fileutil.DEGTORAD no = False yes = True # Constants IDCTAB = 1 DRIZZLE = 2 TRAUGER = 3 try: DEFAULT_IDCDIR = fileutil.osfn('stsdas$pkg/analysis/dither/drizzle/coeffs/') except: DEFAULT_IDCDIR = os.getcwd() """ def factorial(n): #Compute a factorial for integer n. m = 1 for i in range(int(n)): m = m * (i+1) return m def combin(j,n): #Return the combinatorial factor for j in n. return (factorial(j) / (factorial(n) * factorial( (j-n) ) ) ) """ ################# # # # Utility Functions based on IRAF # # ################# def findNumExt(filename): # Open the file given by 'rootname' and return the # number of extensions written out for the observation. # It will be up to the Exposure classes to determine how # many IMSETS they have to work with. # # Only look in the primary extension or first group. #_s = iraf.hselect(filename,'NEXTEND',expr='yes',Stdout=1) _s = fileutil.getKeyword(filename,keyword='NEXTEND') if not _s: _s = fileutil.getKeyword(filename,keyword='GCOUNT') # This may need to be changed to support simple image without # extensions (such as simple FITS images). if _s == '': raise ValueError("There are NO extensions to be read in this image!") return _s # Utility function to extract subarray offsets # from LTV keywords. Could be expanded to use # different keywords for some cases. # Added: 7-Nov-2001 WJH def getLTVOffsets(rootname,header=None): _ltv1 = None _ltv2 = None if header: if 'LTV1' in header: _ltv1 = header['LTV1'] if 'LTV2' in header: _ltv2 = header['LTV2'] else: _ltv1 = fileutil.getKeyword(rootname,'LTV1') _ltv2 = fileutil.getKeyword(rootname,'LTV2') if _ltv1 == None: _ltv1 = 0. if _ltv2 == None: _ltv2 = 0. return _ltv1,_ltv2 def getChipId(header): if 'CCDCHIP' in header: chip = int(header['CCDCHIP']) elif 'DETECTOR' in header and str(header['DETECTOR']).isdigit(): chip = int(header['DETECTOR']) elif 'CAMERA' in header and str(header['CAMERA']).isdigit(): chip = int(header['CAMERA']) else: chip = 1 return chip def getIDCFile(image,keyword="",directory=None): # Open the primary header of the file and read the name of # the IDCTAB. # Parameters: # header - primary and extension header object to read IDCTAB info # # keyword(optional) - header keyword with name of IDCTAB # --OR-- 'HEADER' if need to build IDCTAB name from scratch # (default value: 'IDCTAB') # directory(optional) - directory with default drizzle coeffs tables # (default value: 'drizzle$coeffs') # # This function needs to be generalized to support # keyword='HEADER', as would be the case for WFPC2 data. # if type(image) == type(''): # We were provided an image name, so read in the header... header = fileutil.getHeader(image) else: # otherwise, we were provided an image header we can work with directly header = image if keyword.lower() == 'header': idcfile,idctype = __getIDCTAB(header) if (idcfile == None): idcfile,idctype = __buildIDCTAB(header,directory) elif keyword.lower() == 'idctab': # keyword specifies header keyword with IDCTAB name idcfile,idctype = __getIDCTAB(header) elif keyword == '': idcfile = None idctype = None else: # Need to build IDCTAB filename from scratch idcfile,idctype = __buildIDCTAB(header,directory,kw = keyword) # Account for possible absence of IDCTAB name in header if idcfile == 'N/A': idcfile = None if idcfile != None and idcfile != '': # Now we need to recursively expand any IRAF symbols to full paths... #if directory: idcfile = fileutil.osfn(idcfile) if idcfile == None: print('WARNING: No valid distortion coefficients available!') print('Using default unshifted, unscaled, unrotated model.') return idcfile,idctype def __buildIDCTAB(header, directory, kw = 'cubic'): # Need to build IDCTAB filename from scratch instrument = header['INSTRUME'] if instrument != 'NICMOS': detector = header['DETECTOR'] else: detector = str(header['CAMERA']) # Default non-IDCTAB distortion model """ if (kw == None): keyword = 'cubic' else : """ keyword = kw if not directory: default_dir = DEFAULT_IDCDIR else: default_dir = directory if instrument == 'WFPC2': if detector == 1: detname = 'pc' else: detname = 'wf' idcfile = default_dir+detname+str(detector)+'-'+keyword.lower() elif instrument == 'STIS': idcfile = default_dir+'stis-'+detector.lower() elif instrument == 'NICMOS': if detector != None: idcfile = default_dir+'nic-'+detector else: idcfile = None else: idcfile = None idctype = getIDCFileType(fileutil.osfn(idcfile)) return idcfile,idctype def __getIDCTAB(header): # keyword specifies header keyword with IDCTAB name try: idcfile = header['idctab'] except: print('Warning: No IDCTAB specified in header!') idcfile = None return idcfile,'idctab' def getIDCFileType(idcfile): """ Open ASCII IDCFILE to determine the type: cubic,trauger,... """ if idcfile == None: return None ifile = open(idcfile,'r') # Search for the first line of the coefficients _line = fileutil.rAsciiLine(ifile) # Search for first non-commented line... while _line[0] == '#': _line = fileutil.rAsciiLine(ifile) _type = _line.lower().rstrip() if _type in ['cubic','quartic','quintic'] or _type.find('poly') > -1: _type = 'cubic' elif _type == 'trauger': _type = 'trauger' else: _type = None ifile.close() del ifile return _type # # Function to read Trauger ASCII file and return cubic coefficients # """ def readTraugerTable(idcfile,wavelength): # Return a default geometry model if no coefficients filename # is given. This model will not distort the data in any way. if idcfile == None: return fileutil.defaultModel() # Trauger coefficients only result in a cubic file... order = 3 numco = 10 a_coeffs = [0] * numco b_coeffs = [0] * numco indx = _MgF2(wavelength) ifile = open(idcfile,'r') # Search for the first line of the coefficients _line = fileutil.rAsciiLine(ifile) while _line[:7].lower() != 'trauger': _line = fileutil.rAsciiLine(ifile) # Read in each row of coefficients,split them into their values, # and convert them into cubic coefficients based on # index of refraction value for the given wavelength # Build X coefficients from first 10 rows of Trauger coefficients j = 0 while j < 20: _line = fileutil.rAsciiLine(ifile) if _line == '': continue _lc = _line.split() if j < 10: a_coeffs[j] = float(_lc[0])+float(_lc[1])*(indx-1.5)+float(_lc[2])*(indx-1.5)**2 else: b_coeffs[j-10] = float(_lc[0])+float(_lc[1])*(indx-1.5)+float(_lc[2])*(indx-1.5)**2 j = j + 1 ifile.close() del ifile # Now, convert the coefficients into a Numeric array # with the right coefficients in the right place. # Populate output values now... fx = np.zeros(shape=(order+1,order+1),dtype=np.float64) fy = np.zeros(shape=(order+1,order+1),dtype=np.float64) # Assign the coefficients to their array positions fx[0,0] = 0. fx[1] = np.array([a_coeffs[2],a_coeffs[1],0.,0.],dtype=np.float64) fx[2] = np.array([a_coeffs[5],a_coeffs[4],a_coeffs[3],0.],dtype=np.float64) fx[3] = np.array([a_coeffs[9],a_coeffs[8],a_coeffs[7],a_coeffs[6]],dtype=np.float64) fy[0,0] = 0. fy[1] = np.array([b_coeffs[2],b_coeffs[1],0.,0.],dtype=np.float64) fy[2] = np.array([b_coeffs[5],b_coeffs[4],b_coeffs[3],0.],dtype=np.float64) fy[3] = np.array([b_coeffs[9],b_coeffs[8],b_coeffs[7],b_coeffs[6]],dtype=np.float64) # Used in Pattern.computeOffsets() refpix = {} refpix['XREF'] = None refpix['YREF'] = None refpix['V2REF'] = None refpix['V3REF'] = None refpix['XDELTA'] = 0. refpix['YDELTA'] = 0. refpix['PSCALE'] = None refpix['DEFAULT_SCALE'] = no refpix['centered'] = yes return fx,fy,refpix,order """ def rotateCubic(fxy,theta): # This function transforms cubic coefficients so that # they calculate pixel positions oriented by theta (the same # orientation as the PC). # Parameters: fxy - cubic-coefficients Numeric array # theta - angle to rotate coefficients # Returns new array with same order as 'fxy' # # Set up some simplifications newf = fxy * 0. cost = np.cos(DEGTORAD(theta)) sint = np.sin(DEGTORAD(theta)) cos2t = pow(cost,2) sin2t = pow(sint,2) cos3t = pow(cost,3) sin3t = pow(sint,3) # Now compute the new coefficients newf[1][1] = fxy[1][1] * cost - fxy[1][0] * sint newf[1][0] = fxy[1][1] * sint + fxy[1][0] * cost newf[2][2] = fxy[2][2] * cos2t - fxy[2][1] * cost * sint + fxy[2][0] * sin2t newf[2][1] = fxy[2][2] * 2 * cost * sint + fxy[2][1] * (cos2t - sin2t) + fxy[2][0] * 2 * sint * cost newf[2][0] = fxy[2][2] * sin2t + fxy[2][1] * cost * sint + fxy[2][0] * cos2t newf[3][3] = fxy[3][3] * cos3t - fxy[3][2] * sint * cos2t + fxy[3][1] * sin2t * cost - fxy[3][0] * sin3t newf[3][2] = fxy[3][3] * 3. * cos2t * sint + fxy[3][2]* (cos3t - 2. * sin2t * cost) +fxy[3][1] * (sin3t + 2 * sint * cos2t) - fxy[3][0] * sin2t * cost newf[3][1] = fxy[3][3] * 3. * cost * sin2t + fxy[3][2] *(2.*cos2t*sint - sin3t) + fxy[3][1] * (2 * sin2t * cost + cos3t) + fxy[3][0] * sint * cos2t newf[3][0] = fxy[3][3] * sin3t + fxy[3][2] * sin2t * cost + fxy[3][1] * sint * cos2t + fxy[3][0] * cos3t return newf def rotatePos(pos, theta,offset=None,scale=None): if scale == None: scale = 1. if offset == None: offset = np.array([0.,0.],dtype=np.float64) mrot = buildRotMatrix(theta) xr = ((pos[0] * mrot[0][0]) + (pos[1]*mrot[0][1]) )/ scale + offset[0] yr = ((pos[0] * mrot[1][0]) + (pos[1]*mrot[1][1]) )/ scale + offset[1] return xr,yr # Function for determining the positions of the image # corners after applying the geometry model. # Returns a dictionary with the limits and size of the # image. def getRange(members,ref_wcs,verbose=None): xma,yma = [],[] xmi,ymi = [],[] #nref_x, nref_y = [], [] # Compute corrected positions of each chip's common point crpix = (ref_wcs.crpix1,ref_wcs.crpix2) ref_rot = ref_wcs.orient _rot = ref_wcs.orient - members[0].geometry.wcslin.orient for member in members: # Need to make sure this is populated with proper defaults # for ALL exposures! _model = member.geometry.model _wcs = member.geometry.wcs _wcslin = member.geometry.wcslin _theta = _wcslin.orient - ref_rot # Need to scale corner positions to final output scale _scale =_wcslin.pscale/ ref_wcs.pscale # Compute the corrected,scaled corner positions for each chip #xyedge = member.calcNewEdges(pscale=ref_wcs.pscale) xypos = member.geometry.calcNewCorners() * _scale if _theta != 0.0: #rotate coordinates to match output orientation # Now, rotate new coord _mrot = buildRotMatrix(_theta) xypos = np.dot(xypos,_mrot) _oxmax = np.maximum.reduce(xypos[:,0]) _oymax = np.maximum.reduce(xypos[:,1]) _oxmin = np.minimum.reduce(xypos[:,0]) _oymin = np.minimum.reduce(xypos[:,1]) # Update the corners attribute of the member with the # positions of the computed, distortion-corrected corners #member.corners['corrected'] = np.array([(_oxmin,_oymin),(_oxmin,_oymax),(_oxmax,_oymin),(_oxmax,_oymax)],dtype=np.float64) member.corners['corrected'] = xypos xma.append(_oxmax) yma.append(_oymax) xmi.append(_oxmin) ymi.append(_oymin) #nrefx = (_oxmin+_oxmax) * ref_wcs.pscale/ _wcslin.pscale #nrefy = (_oymin+_oymax) * ref_wcs.pscale/ _wcslin.pscale #nref_x.append(nrefx) #nref_y.append(nrefy) #if _rot != 0.: # mrot = buildRotMatrix(_rot) # nref = np.dot(np.array([nrefx,nrefy]),_mrot) # Determine the full size of the metachip xmax = np.maximum.reduce(xma) ymax = np.maximum.reduce(yma) ymin = np.minimum.reduce(ymi) xmin = np.minimum.reduce(xmi) # Compute offset from center that distortion correction shifts the image. # This accounts for the fact that the output is no longer symmetric around # the reference position... # Scale by ratio of plate-scales so that DELTAs are always in input frame # """ Keep the computation of nref in reference chip space. Using the ratio below is almost correct for ACS and wrong for WFPC2 subarrays """ ##_ratio = ref_wcs.pscale / _wcslin.pscale ##nref = ( (xmin + xmax)*_ratio, (ymin + ymax)*_ratio ) nref = ( (xmin + xmax), (ymin + ymax)) #print 'nref_x, nref_y', nref_x, nref_y #nref = (np.maximum.reduce(nref_x), np.maximum.reduce(nref_y)) if _rot != 0.: _mrot = buildRotMatrix(_rot) nref = np.dot(nref,_mrot) # Now, compute overall size based on range of pixels and offset from center. #xsize = int(xmax - xmin + nref[0]) #ysize = int(ymax - ymin + nref[1]) # Add '2' to each dimension to allow for fractional pixels at the # edge of the image. Also, 'drizzle' centers the output, so # adding 2 only expands image by 1 row on each edge. # An additional two is added to accomodate floating point errors in drizzle. xsize = int(ceil(xmax)) - int(floor(xmin)) ysize = int(ceil(ymax)) - int(floor(ymin)) meta_range = {} meta_range = {'xmin':xmin,'xmax':xmax,'ymin':ymin,'ymax':ymax,'nref':nref} meta_range['xsize'] = xsize meta_range['ysize'] = ysize if verbose: print('Meta_WCS:') print(' NREF :',nref) print(' X range :',xmin,xmax) print(' Y range :',ymin,ymax) print(' Computed Size: ',xsize,ysize) return meta_range def computeRange(corners): """ Determine the range spanned by an array of pixel positions. """ _xrange = (np.minimum.reduce(corners[:,0]),np.maximum.reduce(corners[:,0])) _yrange = (np.minimum.reduce(corners[:,1]),np.maximum.reduce(corners[:,1])) return _xrange,_yrange def convertWCS(inwcs,drizwcs): """ Copy WCSObject WCS into Drizzle compatible array.""" drizwcs[0] = inwcs.crpix1 drizwcs[1] = inwcs.crval1 drizwcs[2] = inwcs.crpix2 drizwcs[3] = inwcs.crval2 drizwcs[4] = inwcs.cd11 drizwcs[5] = inwcs.cd21 drizwcs[6] = inwcs.cd12 drizwcs[7] = inwcs.cd22 return drizwcs def updateWCS(drizwcs,inwcs): """ Copy output WCS array from Drizzle into WCSObject.""" inwcs.crpix1 = drizwcs[0] inwcs.crval1 = drizwcs[1] inwcs.crpix2 = drizwcs[2] inwcs.crval2 = drizwcs[3] inwcs.cd11 = drizwcs[4] inwcs.cd21 = drizwcs[5] inwcs.cd12 = drizwcs[6] inwcs.cd22 = drizwcs[7] inwcs.pscale = np.sqrt(np.power(inwcs.cd11,2)+np.power(inwcs.cd21,2)) * 3600. inwcs.orient = np.arctan2(inwcs.cd12,inwcs.cd22) * 180./np.pi def wcsfit(img_geom, ref): """ Perform a linear fit between 2 WCS for shift, rotation and scale. Based on 'WCSLIN' from 'drutil.f'(Drizzle V2.9) and modified to allow for differences in reference positions assumed by PyDrizzle's distortion model and the coeffs used by 'drizzle'. Parameters: img - ObsGeometry instance for input image ref_wcs - Undistorted WCSObject instance for output frame """ # Define objects that we need to use for the fit... img_wcs = img_geom.wcs in_refpix = img_geom.model.refpix # Only work on a copy to avoid unexpected behavior in the # call routine... ref_wcs = ref.copy() # Convert the RA/Dec positions back to X/Y in output product image _cpix_xyref = np.zeros((4,2),dtype=np.float64) # Start by setting up an array of points +/-0.5 pixels around CRVAL1,2 # However, we must shift these positions by 1.0pix to match what # drizzle will use as its reference position for 'align=center'. _cpix = (img_wcs.crpix1,img_wcs.crpix2) _cpix_arr = np.array([_cpix,(_cpix[0],_cpix[1]+1.), (_cpix[0]+1.,_cpix[1]+1.),(_cpix[0]+1.,_cpix[1])], dtype=np.float64) # Convert these positions to RA/Dec _cpix_rd = img_wcs.xy2rd(_cpix_arr) for pix in range(len(_cpix_rd[0])): _cpix_xyref[pix,0],_cpix_xyref[pix,1] = ref_wcs.rd2xy((_cpix_rd[0][pix],_cpix_rd[1][pix])) # needed to handle correctly subarrays and wfpc2 data if img_wcs.delta_refx == 0.0 and img_wcs.delta_refy == 0.0: offx, offy = (0.0,0.0) else: offx, offy = (1.0, 1.0) # Now, apply distortion model to input image XY positions _cpix_xyc = np.zeros((4,2),dtype=np.float64) _cpix_xyc[:,0],_cpix_xyc[:,1] = img_geom.apply(_cpix_arr - (offx, offy), order=1) if in_refpix: _cpix_xyc += (in_refpix['XDELTA'], in_refpix['YDELTA']) # Perform a fit between: # - undistorted, input positions: _cpix_xyc # - X/Y positions in reference frame: _cpix_xyref abxt,cdyt = fitlin(_cpix_xyc,_cpix_xyref) # This correction affects the final fit when you are fitting # a WCS to itself (no distortion coeffs), so it needs to be # taken out in the coeffs file by modifying the zero-point value. # WJH 17-Mar-2005 abxt[2] -= ref_wcs.crpix1 + offx cdyt[2] -= ref_wcs.crpix2 + offy return abxt,cdyt def fitlin(imgarr,refarr): """ Compute the least-squares fit between two arrays. A Python translation of 'FITLIN' from 'drutil.f' (Drizzle V2.9). """ # Initialize variables _mat = np.zeros((3,3),dtype=np.float64) _xorg = imgarr[0][0] _yorg = imgarr[0][1] _xoorg = refarr[0][0] _yoorg = refarr[0][1] _sigxox = 0. _sigxoy = 0. _sigxo = 0. _sigyox = 0. _sigyoy = 0. _sigyo = 0. _npos = len(imgarr) # Populate matrices for i in range(_npos): _mat[0][0] += np.power((imgarr[i][0] - _xorg),2) _mat[0][1] += (imgarr[i][0] - _xorg) * (imgarr[i][1] - _yorg) _mat[0][2] += (imgarr[i][0] - _xorg) _mat[1][1] += np.power((imgarr[i][1] - _yorg),2) _mat[1][2] += imgarr[i][1] - _yorg _sigxox += (refarr[i][0] - _xoorg)*(imgarr[i][0] - _xorg) _sigxoy += (refarr[i][0] - _xoorg)*(imgarr[i][1] - _yorg) _sigxo += refarr[i][0] - _xoorg _sigyox += (refarr[i][1] - _yoorg)*(imgarr[i][0] -_xorg) _sigyoy += (refarr[i][1] - _yoorg)*(imgarr[i][1] - _yorg) _sigyo += refarr[i][1] - _yoorg _mat[2][2] = _npos _mat[1][0] = _mat[0][1] _mat[2][0] = _mat[0][2] _mat[2][1] = _mat[1][2] # Now invert this matrix _mat = linalg.inv(_mat) _a = _sigxox*_mat[0][0]+_sigxoy*_mat[0][1]+_sigxo*_mat[0][2] _b = -1*(_sigxox*_mat[1][0]+_sigxoy*_mat[1][1]+_sigxo*_mat[1][2]) #_x0 = _sigxox*_mat[2][0]+_sigxoy*_mat[2][1]+_sigxo*_mat[2][2] _c = _sigyox*_mat[1][0]+_sigyoy*_mat[1][1]+_sigyo*_mat[1][2] _d = _sigyox*_mat[0][0]+_sigyoy*_mat[0][1]+_sigyo*_mat[0][2] #_y0 = _sigyox*_mat[2][0]+_sigyoy*_mat[2][1]+_sigyo*_mat[2][2] _xt = _xoorg - _a*_xorg+_b*_yorg _yt = _yoorg - _d*_xorg-_c*_yorg return [_a,_b,_xt],[_c,_d,_yt] def getRotatedSize(corners,angle): """ Determine the size of a rotated (meta)image.""" # If there is no rotation, simply return original values if angle == 0.: _corners = corners else: # Find center #_xr,_yr = computeRange(corners) #_cen = ( ((_xr[1] - _xr[0])/2.)+_xr[0],((_yr[1]-_yr[0])/2.)+_yr[0]) _rotm = buildRotMatrix(angle) # Rotate about the center #_corners = np.dot(corners - _cen,_rotm) _corners = np.dot(corners,_rotm) return computeRange(_corners)
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,331
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/traits102/tktrait_sheet.py
#-------------------------------------------------------------------------------- # # Define a Tkinter based trait sheet mechanism for visually editing the # values of traits. # # Written by: David C. Morrill # # Date: 10/15/2002 # # (c) Copyright 2002 by Enthought, Inc. # #-------------------------------------------------------------------------------- #-------------------------------------------------------------------------------- # Imports: #-------------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function # confidence medium import sys import os.path import re if sys.version_info[0] >= 3: import tkinter as tk import tkinter.messagebox as mb import tkinter.simpledialog as sd import tkinter.colorchooser as cc import tkinter.font as tf else: import Tkinter as tk import tkMessageBox as mb import tkSimpleDialog as sd import tkColorChooser as cc import tkFont as tf if sys.version_info[0] >= 3: from functools import reduce import Pmw from .traits import Trait, HasTraits, TraitError, HasDynamicTraits, \ trait_editors from .trait_sheet import TraitEditor, TraitSheetHandler, TraitMonitor, \ TraitGroup, TraitGroupList, default_trait_sheet_handler from types import ModuleType #------------------------------------------------------------------------------- # Module initialization: #------------------------------------------------------------------------------- trait_editors( __name__ ) #------------------------------------------------------------------------------- # Constants: #------------------------------------------------------------------------------- # Boolean values: TRUE = 1 FALSE = 0 # Basic sequence types: basic_sequence_types = [ list, tuple ] # Standard width of an image bitmap: standard_bitmap_width = 120 # Standard colors: WHITE = '#FFFFFF' # Standard color samples: color_choices = ( 0, 128, 192, 255 ) color_samples = [ None ] * 48 i = 0 for r in color_choices: for g in color_choices: for b in ( 0, 128, 255 ): color_samples[i] = '#%02X%02X%02X' % ( r, g, b ) i += 1 # List of available font facenames: facenames = None # Standard font point sizes: point_sizes = [ '8', '9', '10', '11', '12', '14', '16', '18', '20', '22', '24', '26', '28', '36', '48', '72' ] # Global switch governing whether or not tooltips are displayed in trait # sheet dialogs: tooltips_enabled = TRUE # Pattern of all digits: all_digits = re.compile( r'\d+' ) #-------------------------------------------------------------------------------- # 'TraitSheetDialog' class: #-------------------------------------------------------------------------------- class TraitSheetDialog ( tk.Toplevel ): #----------------------------------------------------------------------------- # Initialize the object: #----------------------------------------------------------------------------- def __init__ ( self, object, traits = None, handler = default_trait_sheet_handler, parent = None, title = None ): if title is None: title = '%s Traits' % object.__class__.__name__ tk.Toplevel.__init__( self, parent ) self.title( title ) self.bind( '<Destroy>', self.on_close_page ) self.bind( '<Escape>', self.on_close_key ) self.object = object self.handler = handler # Create the actual trait sheet panel: TraitSheet( self, object, traits, handler ).grid( row = 0 ) # Find a nice place on the screen to display the trait sheet so # that it overlays the object as little as possible: if not handler.position( self, object ): #??? self.Centre( wx.wxBOTH ) pass self.resizable( FALSE, FALSE ) #----------------------------------------------------------------------------- # Close the trait sheet window: #----------------------------------------------------------------------------- def on_close_page ( self, event ): self.handler.close( self, self.object ) #---------------------------------------------------------------------------- # Handle the user hitting the 'Esc'ape key: #---------------------------------------------------------------------------- def on_close_key ( self ): self.on_close_page() self.destroy() #-------------------------------------------------------------------------------- # 'TraitPanel' class: #-------------------------------------------------------------------------------- class TraitPanel ( tk.Frame ): #----------------------------------------------------------------------------- # Initialize the object: #----------------------------------------------------------------------------- def __init__ ( self, parent ): tk.Frame.__init__( self, parent ) pass ### NOT IMPLEMENTED YET #---------------------------------------------------------------------------- # Add a TraitSheet to the panel: #---------------------------------------------------------------------------- def add ( self, sheet ): pass ### NOT IMPLEMENTED YET #---------------------------------------------------------------------------- # Remove a TraitSheet from the panel: #---------------------------------------------------------------------------- def remove ( self, sheet ): pass ### NOT IMPLEMENTED YET #---------------------------------------------------------------------------- # Get the size of the panel: #---------------------------------------------------------------------------- def size ( self ): return ( 0, 0 ) ### NOT IMPLEMENTED YET #---------------------------------------------------------------------------- # Set the size and position of the panel: #---------------------------------------------------------------------------- def position ( self, x, y, dx, dy ): pass ### NOT IMPLEMENTED YET #---------------------------------------------------------------------------- # Destroy the panel: #---------------------------------------------------------------------------- def destroy ( self ): pass ### NOT IMPLEMENTED YET #-------------------------------------------------------------------------------- # 'TraitSheet' class: #-------------------------------------------------------------------------------- class TraitSheet ( tk.Frame ): #----------------------------------------------------------------------------- # Initialize the object: #----------------------------------------------------------------------------- def __init__ ( self, parent, object, traits = None, handler = default_trait_sheet_handler ): tk.Frame.__init__( self, parent ) self.object = object self.handler = handler self.tooltip = None # If no traits were specified: if traits is None: # Get them from the specified object: traits = object.editable_traits() # Try to make sure that we now have either a single TraitGroup, or # a list of TraitGroups: kind = type( traits ) if kind == str: # Convert the single trait name into a TraitGroup: traits = TraitGroup( traits, show_border = FALSE ) elif ((kind in basic_sequence_types) or isinstance( traits, TraitGroupList )): if len( traits ) == 0: # Empty trait list, leave the panel empty: return if not isinstance( traits[0], TraitGroup ): # Convert a simple list of trait elements into a single, # TraitGroup, possibly containing multiple items: traits = TraitGroup( show_border = FALSE, *traits ) # Create the requested style of trait sheet editor: if isinstance( traits, TraitGroup ): # Single page dialog: self.add_page( traits, self ) else: # Multi-tab notebook: self.add_tabs( traits ) #----------------------------------------------------------------------------- # Create a tab (i.e. notebook) style trait editor: #----------------------------------------------------------------------------- def add_tabs ( self, traits ): # Create the notebook: nb = Pmw.NoteBook( self ) nb.grid( row = 0, column = 0, sticky = 'new' ) count = 0 for pg in traits: # Create the new notebook page: page_name = pg.label if page_name is None: count += 1 page_name = 'Page %d' % count self.add_page( pg, nb.add( page_name ) ) # Size the notebook to fit the pages it contains: nb.setnaturalsize() #----------------------------------------------------------------------------- # Create a single trait editor page: #----------------------------------------------------------------------------- def add_page ( self, pg, parent, default_style = 'simple' ): default_style = pg.style or default_style object = pg.object or self.object row_incr = col_incr = 0 if pg.orientation == 'horizontal': col_incr = 1 else: row_incr = 1 show_labels = pg.show_labels_ row = col = 0 cols = 1 + show_labels for pge in pg.values: if isinstance( pge, TraitGroup ): if pge.show_border_: box = Pmw.Group( parent, tag_text = pge.label or '' ) box.grid( row = row, column = col, sticky = 'new', padx = 4 ) frame = tk.Frame( box.interior() ) frame.grid( row = 0, column = 0, sticky = 'news', padx = 4, pady = 3 ) box.interior().columnconfigure( 0, weight = 1 ) self.add_page( pge, frame, default_style ) else: self.add_page( pge, parent ) if row_incr: parent.columnconfigure( 0, weight = 1 ) row += row_incr col += col_incr else: name = pge.name or ' ' if name == '-': tk.Frame( parent, bg = '#A0A0A0' ).grid( row = row, column = 0, columnspan = cols, sticky = 'ew' ) parent.rowconfigure( row, minsize = 9 ) row += 1 continue if name == ' ': name = '5' if all_digits.match( name ): parent.rowconfigure( row, minsize = int( name ) ) row += 1 continue editor = pge.editor style = pge.style or default_style pge_object = pge.object or object if editor is None: try: editor = pge_object._base_trait( name ).get_editor() except: pass if editor is None: continue label = None if show_labels: label = pge.label_for( object ) self.add_trait( parent, row, object, name, label, editor, style == 'simple' ) parent.columnconfigure( 1, weight = 1 ) # Advance to the next row in the grid: row += 1 # Allocate any extra space to an imaginary row following last one used: parent.rowconfigure( row, weight = 1 ) #----------------------------------------------------------------------------- # Add a trait to the trait sheet: #----------------------------------------------------------------------------- def add_trait ( self, parent, row, object, trait_name, description, editor, is_simple ): global tooltips_enabled col = 0 if description is not None: suffix = ':'[ description[-1:] == '?': ] label = tk.Label( parent, text = (description + suffix).capitalize(), anchor = 'e' ) label.grid( row = row, sticky = 'new', padx = 0, pady = 2 ) col = 1 desc = object._base_trait( trait_name ).desc if (desc is not None) and tooltips_enabled: if self.tooltip is None: self.tooltip = Pmw.Balloon( self, state = 'balloon' ) self.tooltip.bind( label, 'Specifies ' + desc ) label.bind( '<B2-ButtonRelease>', self.on_toggle_help ) if is_simple: control = editor.simple_editor( object, trait_name, description, self.handler, parent ) control.bind( '<B2-ButtonRelease>', editor.on_restore ) else: control = editor.custom_editor( object, trait_name, description, self.handler, parent ) control.grid( row = row, column = col, sticky = 'ew', padx = 4, pady = 2 ) control.object = object control.trait_name = trait_name control.description = description control.original_value = getattr( object, trait_name ) control.handler = self.handler return control #----------------------------------------------------------------------------- # Toggle whether user sees tooltips or not: #----------------------------------------------------------------------------- def on_toggle_help ( self, event ): global tooltips_enabled tooltips_enabled = not tooltips_enabled if self.tooltip is not None: self.tooltip.configure( state = ( 'none', 'balloon' )[ tooltips_enabled ] ) #-------------------------------------------------------------------------------- # 'tkTraitEditor' class: #-------------------------------------------------------------------------------- class tkTraitEditor ( TraitEditor ): #----------------------------------------------------------------------------- # Create a static view of the current value of the 'trait_name' # trait of 'object': #----------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): control = tk.Label( parent, text = self.str( object, trait_name ), relief = tk.SUNKEN ) control.object = object control.trait_name = trait_name control.description = description control.handler = handler control.original_value = getattr( object, trait_name ) control.bind( '<B1-ButtonRelease>', self.on_popup ) control.bind( '<3>', self.on_restore ) return control #----------------------------------------------------------------------------- # Invoke the pop-up editor for an object trait: #----------------------------------------------------------------------------- def on_popup ( self, event ): control = event.widget if hasattr( self, 'popup_editor' ): self.popup_editor( control.object, control.trait_name, control.description, control.handler, control ) #----------------------------------------------------------------------------- # Restore the original value of the object's trait: #----------------------------------------------------------------------------- def on_restore ( self, event ): control = event.widget object = control.object trait_name = control.trait_name old_value = getattr( object, trait_name ) new_value = control.original_value setattr( object, trait_name, new_value ) control.handler.changed( object, trait_name, new_value, old_value, FALSE ) self.update( object, trait_name, control ) #----------------------------------------------------------------------------- # Update the contents of a previously created viewer control with the new # value of the 'trait_name' trait of 'object': #----------------------------------------------------------------------------- def update ( self, object, trait_name, control ): control.configure( text = self.str( object, trait_name ) ) #----------------------------------------------------------------------------- # Handle a 'TraitError' exception: #----------------------------------------------------------------------------- def error ( self, description, excp, parent ): mb.showerror( description + ' value error', str( excp ) ) #-------------------------------------------------------------------------------- # 'TraitEditorText' class: #-------------------------------------------------------------------------------- class TraitEditorText ( tkTraitEditor ): #----------------------------------------------------------------------------- # Initialize the object: #----------------------------------------------------------------------------- def __init__ ( self, dic = {}, auto_set = TRUE ): self.dic = dic self.auto_set = auto_set #----------------------------------------------------------------------------- # Interactively edit the 'trait_name' text trait of 'object': #----------------------------------------------------------------------------- def popup_editor ( self, object, trait_name, description, handler, control ): while TRUE: value = sd.askstring( 'Prompt', 'Enter the new %s value:' % trait_name, initialvalue = getattr( object, trait_name ) ) if value is None: return if value in self.dic: value = self.dic[ value ] try: self.set( object, trait_name, value, handler ) self.update( object, trait_name, control ) except TraitError as excp: self.error( description, excp, object.window ) #----------------------------------------------------------------------------- # Create an in-place editable view of the current value of the # 'trait_name' trait of 'object': #----------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): var = tk.StringVar() var.set( self.str( object, trait_name ) ) control = tk.Entry( parent, textvariable = var ) control.var = var control.value = self.get_value( control ) control.bind( '<Return>', self.on_enter ) control.bind( '<3>', self.on_restore ) if self.auto_set: control.bind( '<KeyRelease>', self.on_key ) return control #----------------------------------------------------------------------------- # Update the contents of a previously created viewer control with the new # value of the 'trait' trait of 'object': #----------------------------------------------------------------------------- def update ( self, object, trait_name, control ): control.var.set( self.str( object, trait_name ) ) control.configure( bg = WHITE ) #----------------------------------------------------------------------------- # Handle the user pressing the 'Enter' key in the edit control: #----------------------------------------------------------------------------- def on_enter ( self, event ): control = event.widget try: self.set( control.object, control.trait_name, self.get_value( control ), control.handler ) except TraitError as excp: self.error( control.description, excp, control ) #----------------------------------------------------------------------------- # Handle the user releasing a key in the edit control: #----------------------------------------------------------------------------- def on_key ( self, event ): control = event.widget value = self.get_value( control ) if value != control.value: control.value = value try: setattr( control.object, control.trait_name, value ) color = WHITE except: color = '#FFC0C0' control.configure( bg = color ) #----------------------------------------------------------------------------- # Get the actual value corresponding to what the user typed: #----------------------------------------------------------------------------- def get_value ( self, control ): value = control.var.get().strip() if value not in self.dic: return value return self.dic[ value ] #-------------------------------------------------------------------------------- # 'TraitEditorEnum' class: #-------------------------------------------------------------------------------- class TraitEditorEnum ( tkTraitEditor ): #----------------------------------------------------------------------------- # Initialize the object: #----------------------------------------------------------------------------- def __init__ ( self, values, cols = 1 ): self.cols = cols self.mapped = (type( values ) is dict) if self.mapped: sorted = list(values.values()) sorted.sort() col = sorted[0].find( ':' ) + 1 if col > 0: self.sorted = [ x[ col: ] for x in sorted ] for n, v in values.items(): values[n] = v[ col: ] else: self.sorted = sorted self.values = values else: if not type( values ) in basic_sequence_types: handler = values if isinstance( handler, Trait ): handler = handler.setter if hasattr( handler, 'map' ): values = list(handler.map.keys()) values.sort() else: values = handler.values self.values = [ str( x ) for x in values ] #----------------------------------------------------------------------------- # Create an in-place simple view of the current value of the # 'trait_name' trait of 'object': #----------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): delegate = tkDelegate( self.on_value_changed ) values = self.all_values() control = Pmw.ComboBox( parent, dropdown = TRUE, selectioncommand = delegate(), scrolledlist_items = values, listheight = min( 150, len( values ) * 24 ) ) delegate.control = control control.selectitem( self.current_value( object, trait_name ) ) return control #---------------------------------------------------------------------------- # Create an in-place custom view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def custom_editor ( self, object, trait_name, description, handler, parent ): # Create a panel to hold all of the radio buttons: panel = tk.Frame( parent ) # Get the current trait value: cur_value = self.current_value( object, trait_name ) # Initialize loop data: values = self.all_values() n = len( values ) cols = self.cols rows = (n + cols - 1) // cols var = tk.StringVar() delegate = tkDelegate( self.on_click, var = var, panel = panel ) incr = [ n // cols ] * cols rem = n % cols for i in range( cols ): incr[i] += (rem > i) incr[-1] = -(reduce( lambda x, y: x + y, incr[:-1], 0 ) - 1) # Add the set of all possible choices to the panel: index = 0 for i in range( rows ): for j in range( cols ): value = values[ index ] control = tk.Radiobutton( panel, text = value.capitalize(), value = value, variable = var, command = delegate() ) control.grid( row = i, column = j, sticky = 'w' ) if value == cur_value: var.set( value ) index += incr[j] n -= 1 if n <= 0: break for j in range( cols ): panel.columnconfigure( j, weight = 1 ) # Return the panel as the result: return panel #---------------------------------------------------------------------------- # Return the set of all possible values: #---------------------------------------------------------------------------- def all_values ( self ): if self.mapped: return self.sorted return self.values #---------------------------------------------------------------------------- # Return the current value of the object trait: #---------------------------------------------------------------------------- def current_value ( self, object, trait_name ): if self.mapped: return self.values[ getattr( object, trait_name + '_' ) ] return str( getattr( object, trait_name ) ) #----------------------------------------------------------------------------- # Handle the user selecting a new value from the combo box: #----------------------------------------------------------------------------- def on_value_changed ( self, delegate, value ): control = delegate.control try: value = int( value ) except: pass self.set( control.object, control.trait_name, value, control.handler ) #---------------------------------------------------------------------------- # Handle the user clicking one of the 'custom' radio buttons: #---------------------------------------------------------------------------- def on_click ( self, delegate ): panel = delegate.panel value = delegate.var.get() try: value = int( value ) except: pass self.set( panel.object, panel.trait_name, value, panel.handler ) #-------------------------------------------------------------------------------- # 'TraitEditorImageEnum' class: #-------------------------------------------------------------------------------- class TraitEditorImageEnum ( TraitEditorEnum ): #----------------------------------------------------------------------------- # Initialize the object: #----------------------------------------------------------------------------- def __init__ ( self, values, suffix = '', cols = 1, path = None ): TraitEditorEnum.__init__( self, values ) self.suffix = suffix self.cols = cols if type( path ) is ModuleType: path = os.path.join( os.path.dirname( path.__file__ ), 'images' ) self.path = path #----------------------------------------------------------------------------- # Interactively edit the 'trait_name' trait of 'object': #----------------------------------------------------------------------------- def popup_editor ( self, object, trait_name, description, handler, control ): TraitEditorImageDialog( object, trait_name, description, control, handler, self ) #----------------------------------------------------------------------------- # Create an in-place editable view of the current value of the # 'trait_name' trait of 'object': #----------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): control = tk.Button( parent, image = bitmap_cache( self.current_value( object, trait_name ) + self.suffix, self.path ), bg = WHITE ) control.configure( command = tkDelegate( self.on_popup, widget = control )() ) return control #---------------------------------------------------------------------------- # Create an in-place custom view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def custom_editor ( self, object, trait_name, description, handler, parent ): # Create a panel to hold all of the radio buttons: panel = tk.Frame( parent ) # Save the information the event handler needs: panel.object = object panel.trait_name = trait_name panel.handler = handler # Add the image buttons to the panel: self.create_image_grid( panel, self.on_click ) # Return the panel as the result: return panel #---------------------------------------------------------------------------- # Populate a specified window with a grid of image buttons: #---------------------------------------------------------------------------- def create_image_grid ( self, parent, handler ): # Add the set of all possible choices: i = 0 cols = self.cols for value in self.all_values(): control = tk.Button( parent, image = bitmap_cache( value + self.suffix, self.path ), command = tkDelegate( handler, parent = parent, value = value )() ) control.grid( row = i // cols, column = i % cols, sticky = 'w', padx = 2, pady = 2 ) i += 1 parent.columnconfigure( cols, weight = 1 ) #----------------------------------------------------------------------------- # Update the contents of a previously created viewer control with the new # value of the 'trait' trait of 'object': #----------------------------------------------------------------------------- def update ( self, object, trait_name, control ): control.configure( image = bitmap_cache( self.current_value( object, trait_name ) + self.suffix, self.path ) ) #---------------------------------------------------------------------------- # Handle the user clicking one of the image buttons: #---------------------------------------------------------------------------- def on_click ( self, delegate ): parent = delegate.parent self.set( parent.object, parent.trait_name, delegate.value, parent.handler ) #-------------------------------------------------------------------------------- # 'TraitEditorCheckList' class: #-------------------------------------------------------------------------------- class TraitEditorCheckList ( tkTraitEditor ): #----------------------------------------------------------------------------- # Initialize the object: #----------------------------------------------------------------------------- def __init__ ( self, values, cols = 1 ): self.cols = cols self.values = values if type( values[0] ) is str: self.values = [ ( x, x.capitalize() ) for x in values ] self.mapping = mapping = {} for value, key in self.values: mapping[ key ] = value #----------------------------------------------------------------------------- # Create an in-place simple view of the current value of the # 'trait_name' trait of 'object': #----------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): delegate = tkDelegate( self.on_value_changed ) labels = self.all_labels() control = Pmw.ComboBox( parent, dropdown = TRUE, selectioncommand = delegate(), scrolledlist_items = labels, listheight = min( 150, len( labels ) * 24 ) ) delegate.control = control try: control.selectitem( self.all_values().index( self.current_value( object, trait_name )[0] ) ) except: pass return control #---------------------------------------------------------------------------- # Create an in-place custom view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def custom_editor ( self, object, trait_name, description, handler, parent ): # Create a panel to hold all of the radio buttons: panel = tk.Frame( parent ) # Get the current trait value: cur_value = self.current_value( object, trait_name ) # Create a sizer to manage the radio buttons: labels = self.all_labels() values = self.all_values() n = len( values ) cols = self.cols rows = (n + cols - 1) // cols incr = [ n // cols ] * cols rem = n % cols for i in range( cols ): incr[i] += (rem > i) incr[-1] = -(reduce( lambda x, y: x + y, incr[:-1], 0 ) - 1) # Add the set of all possible choices: index = 0 for i in range( rows ): for j in range( cols ): if n > 0: value = values[ index ] var = tk.IntVar() delegate = tkDelegate( self.on_click, var = var, panel = panel, value = value ) control = tk.Checkbutton( panel, text = labels[ index ], variable = var, command = delegate() ) control.grid( row = i, column = j, sticky = 'w' ) var.set( value in cur_value ) index += incr[j] n -= 1 if n <= 0: break for j in range( cols ): panel.columnconfigure( j, weight = 1 ) # Return the panel as the result: return panel #---------------------------------------------------------------------------- # Return the set of all possible labels: #---------------------------------------------------------------------------- def all_labels ( self ): return [ x[1] for x in self.values ] #---------------------------------------------------------------------------- # Return the set of all possible values: #---------------------------------------------------------------------------- def all_values ( self ): return [ x[0] for x in self.values ] #---------------------------------------------------------------------------- # Return whether or not the current value is a string or not: #---------------------------------------------------------------------------- def is_string ( self, object, trait_name ): return (type( getattr( object, trait_name ) ) is str) #---------------------------------------------------------------------------- # Return the current value of the object trait: #---------------------------------------------------------------------------- def current_value ( self, object, trait_name ): value = getattr( object, trait_name ) if value is None: return [] if type( value ) is not str: return value return [ x.strip() for x in value.split( ',' ) ] #----------------------------------------------------------------------------- # Handle the user selecting a new value from the combo box: #----------------------------------------------------------------------------- def on_value_changed ( self, delegate, value ): control = delegate.control value = self.mapping[ value ] if not self.is_string( control.object, control.trait_name ): value = [ value ] self.set( control.object, control.trait_name, value, control.handler ) #---------------------------------------------------------------------------- # Handle the user clicking one of the 'custom' radio buttons: #---------------------------------------------------------------------------- def on_click ( self, delegate ): panel = delegate.panel value = delegate.value cur_value = self.current_value( panel.object, panel.trait_name ) if delegate.var.get(): cur_value.append( value ) else: cur_value.remove( value ) if self.is_string( panel.object, panel.trait_name ): cur_value = ','.join( cur_value ) self.set( panel.object, panel.trait_name, cur_value, panel.handler ) #-------------------------------------------------------------------------------- # 'TraitEditorBoolean' class: #-------------------------------------------------------------------------------- class TraitEditorBoolean ( tkTraitEditor ): #----------------------------------------------------------------------------- # Create an in-place editable view of the current value of the # 'trait_name' trait of 'object': #----------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): var = tk.IntVar() control = tk.Checkbutton( parent, text = '', variable = var, anchor = 'w' ) control.configure( command = tkDelegate( self.on_value_changed, control = control, var = var )() ) try: value = getattr( object, trait_name + '_' ) except: value = getattr( object, trait_name ) var.set( value ) return control #----------------------------------------------------------------------------- # Handle the user clicking on the checkbox: #----------------------------------------------------------------------------- def on_value_changed ( self, delegate ): control = delegate.control self.set( control.object, control.trait_name, delegate.var.get(), control.handler ) #-------------------------------------------------------------------------------- # 'TraitEditorRange class: #-------------------------------------------------------------------------------- class TraitEditorRange ( TraitEditorEnum ): #----------------------------------------------------------------------------- # Initialize the object: #----------------------------------------------------------------------------- def __init__ ( self, handler, cols = 1 , auto_set = True): if isinstance( handler, Trait ): handler = handler.setter self.low = handler.low self.high = handler.high self.cols = cols self.auto_set = auto_set self.is_float = (type( self.low ) is float) #----------------------------------------------------------------------------- # Create an in-place editable view of the current value of the # 'trait_name' trait of 'object': #----------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): value = self.str( object, trait_name ) var = tk.StringVar() var.set(value) if self.is_float or abs( self.high - self.low ) > 1000: control = tk.Entry( parent, textvariable = var ) control.var = var control.value = value control.bind( '<Return>', self.on_enter ) control.bind( '<KeyRelease>', self.on_key ) control.bind( '<3>', self.on_restore ) else: control = Pmw.Counter( parent ) control.configure( datatype = { 'counter': self.on_value_changed, 'control': control, 'min_value': self.low, 'max_value': self.high } ) control._counterEntry.setentry( str( value ) ) return control #---------------------------------------------------------------------------- # Create an in-place custom view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def custom_editor ( self, object, trait_name, description, handler, parent ): if abs( self.high - self.low ) > 15: return self.simple_editor( object, trait_name, description, handler, parent ) return TraitEditorEnum.custom_editor( self, object, trait_name, description, handler, parent ) #---------------------------------------------------------------------------- # Return the set of all possible values: #---------------------------------------------------------------------------- def all_values ( self ): return [ str( x ) for x in range( self.low, self.high + 1 ) ] #---------------------------------------------------------------------------- # Return the current value of the object trait: #---------------------------------------------------------------------------- def current_value ( self, object, trait_name ): return str( getattr( object, trait_name ) ) #----------------------------------------------------------------------------- # Update the contents of a previously created viewer control with the new # value of the 'trait' trait of 'object': #----------------------------------------------------------------------------- def update ( self, object, trait_name, control ): if isinstance( control, tk.Entry ): control.var.set( self.str( object, trait_name ) ) control.configure( bg = WHITE ) else: control.entryfield.configure( text = str( getattr( object, trait_name ) ) ) #----------------------------------------------------------------------------- # Handle the user selecting a new value from the spin control: #----------------------------------------------------------------------------- def on_value_changed ( self, value, factor, incr, control = None, min_value = None, max_value = None ): value = min( max_value, max( min_value, int( value ) + factor * incr ) ) try: self.set( control.object, control.trait_name, value, control.handler ) return str( value ) except: raise ValueError #----------------------------------------------------------------------------- # Handle the user pressing the 'Enter' key in thfvalue = getattr( object, trait_name )e edit control: #----------------------------------------------------------------------------- def on_enter ( self, event ): control = event.widget try: self.set( control.object, control.trait_name, control.var.get().strip(), control.handler ) except TraitError as excp: self.error( control.description, excp, control ) #----------------------------------------------------------------------------- # Handle the user releasing a key in the edit control: #----------------------------------------------------------------------------- def on_key ( self, event ): control = event.widget value = control.var.get() if value != control.value: control.value = value try: setattr( control.object, control.trait_name, value ) color = WHITE except: color = '#FFC0C0' control.configure( bg = color ) #------------------------------------------------------------------------------- # 'TraitEditorImageDialog' class: #------------------------------------------------------------------------------- class TraitEditorImageDialog ( tk.Toplevel ): #----------------------------------------------------------------------------- # Initialize the object: #----------------------------------------------------------------------------- def __init__ ( self, object, trait_name, description, control, handler, editor ): tk.Toplevel.__init__( self, control ) self.title( 'Choose ' + description ) self.bind( '<Escape>', self.on_close_key ) # Initialize instance data: self.object = object self.trait_name = trait_name self.control = control self.handler = handler self.editor = editor # Create the grid of image buttons: editor.create_image_grid( self, self.on_click ) #---------------------------------------------------------------------------- # Handle the user hitting the 'Esc'ape key: #---------------------------------------------------------------------------- def on_close_key ( self ): self.destroy() #---------------------------------------------------------------------------- # Handle the user clicking one of the choice buttons: #---------------------------------------------------------------------------- def on_click ( self, delegate ): self.editor.set( self.object, self.trait_name, delegate.value, self.handler ) self.editor.update( self.object, self.trait_name, self.control ) self.destroy() #-------------------------------------------------------------------------------- # Convert an image file name to a cached bitmap: #-------------------------------------------------------------------------------- # Bitmap cache dictionary (indexed by filename): _bitmap_cache = {} ### NOTE: This needs major improvements: app_path = None traits_path = None def bitmap_cache ( name, path = None ): global app_path, traits_path if path is None: if traits_path is None: from . import traits traits_path = os.path.join( os.path.dirname( traits.__file__ ), 'images' ) path = traits_path elif path == '': if app_path is None: app_path = os.path.join( os.path.dirname( sys.argv[0] ), '..', 'images' ) path = app_path filename = os.path.abspath( os.path.join( path, name.replace( ' ', '_' ).lower() + '.gif' ) ) bitmap = _bitmap_cache.get( filename ) if bitmap is None: bitmap = _bitmap_cache[ filename ] = tk.PhotoImage( file = filename ) return bitmap #------------------------------------------------------------------------------- # Standard colors: #------------------------------------------------------------------------------- standard_colors = { 'aquamarine': '#70DB93', 'black': '#000000', 'blue': '#0000FF', 'blue violet': '#9F5F9F', 'brown': '#A52A2A', 'cadet blue': '#5F9F9F', 'coral': '#FF7F00', 'cornflower blue': '#42426F', 'cyan': '#00FFFF', 'dark green': '#2F4F2F', 'dark grey': '#2F2F2F', 'dark olive green': '#4F4F2F', 'dark orchid': '#9932CC', 'dark slate blue': '#6B238E', 'dark slate grey': '#2F4F4F', 'dark turquoise': '#7093DB', 'dim grey': '#545454', 'firebrick': '#8E2323', 'forest green': '#238E23', 'gold': '#CC7F32', 'goldenrod': '#DBDB70', 'green': '#00FF00', 'green yellow': '#93DB70', 'grey': '#808080', 'indian red': '#4F2F2F', 'khaki': '#9F9F5F', 'light blue': '#BFD8D8', 'light grey': '#C0C0C0', 'light steel': '#000000', 'lime green': '#32CC32', 'magenta': '#FF00FF', 'maroon': '#8E236B', 'medium aquamarine': '#32CC99', 'medium blue': '#3232CC', 'medium forest green': '#6B8E23', 'medium goldenrod': '#EAEAAD', 'medium orchid': '#9370DB', 'medium sea green': '#426F42', 'medium slate blue': '#7F00FF', 'medium spring green': '#7FFF00', 'medium turquoise': '#70DBDB', 'medium violet red': '#DB7093', 'midnight blue': '#2F2F4F', 'navy': '#23238E', 'orange': '#CC3232', 'orange red': '#FF007F', 'orchid': '#DB70DB', 'pale green': '#8FBC8F', 'pink': '#BC8FEA', 'plum': '#EAADEA', 'purple': '#B000FF', 'red': '#FF0000', 'salmon': '#6F4242', 'sea green': '#238E6B', 'sienna': '#8E6B23', 'sky blue': '#3299CC', 'slate blue': '#007FFF', 'spring green': '#00FF7F', 'steel blue': '#236B8E', 'tan': '#DB9370', 'thistle': '#D8BFD8', 'turquoise': '#ADEAEA', 'violet': '#4F2F4F', 'violet red': '#CC3299', 'wheat': '#D8D8BF', 'white': '#FFFFFF', 'yellow': '#FFFF00', 'yellow green': '#99CC32' } #-------------------------------------------------------------------------------- # Convert a number into a Tkinter color string: #-------------------------------------------------------------------------------- def num_to_color ( object, name, value ): if type( value ) is str: if ((len( value ) == 7) and (value[0] == '#') and (eval( '0x' + value[1:] ) >= 0)): return value raise TraitError return '#%06X' % int( value ) num_to_color.info = ("a string of the form '#RRGGBB' or a number, which in " "hex is of the form 0xRRGGBB, where RR is red, GG is " "green, and BB is blue") #-------------------------------------------------------------------------------- # 'TraitEditorColor' class: #-------------------------------------------------------------------------------- class TraitEditorColor ( tkTraitEditor ): #----------------------------------------------------------------------------- # Interactively edit the 'trait_name' color trait of 'object': #----------------------------------------------------------------------------- def popup_editor ( self, object, trait_name, description, handler, control ): color = cc.askcolor( self.to_tk_color( object, trait_name ) )[1].upper() if color is not None: self.set( object, trait_name, self.from_tk_color( color ), handler ) self.update( object, trait_name, control ) #----------------------------------------------------------------------------- # Create a static view of the current value of the 'trait_name' # trait of 'object': #----------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): control = tkTraitEditor.simple_editor( self, object, trait_name, description, handler, parent ) self.update_color( object, trait_name, control ) return control #---------------------------------------------------------------------------- # Create an in-place custom view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def custom_editor ( self, object, trait_name, description, handler, parent ): # Create a panel to hold all of the buttons: panel = tk.Frame( parent ) panel.color = self.simple_editor( object, trait_name, description, handler, panel ) panel.color.grid( row = 0, column = 0, sticky = 'nesw' ) # Add all of the color choice buttons: panel2 = tk.Frame( panel ) for i in range( len( color_samples ) ): tk.Button( panel2, bg = color_samples[i], font = 'Helvetica 1', command = tkDelegate( self.on_click, panel = panel, color = color_samples[i] )() ).grid( row = i // 12, column = i % 12, sticky = 'ew' ) for i in range( 12 ): panel2.columnconfigure( i, weight = 1 ) panel2.grid( row = 0, column = 1, sticky = 'nesw', padx = 4 ) panel.columnconfigure( 0, minsize = 70 ) panel.columnconfigure( 1, weight = 1 ) # Return the panel as the result: return panel #---------------------------------------------------------------------------- # Handle the user clicking one of the 'custom' color buttons: #---------------------------------------------------------------------------- def on_click ( self, delegate ): panel = delegate.panel self.set( panel.object, panel.trait_name, self.from_tk_color( delegate.color ), panel.handler ) self.update( panel.object, panel.trait_name, panel.color ) #----------------------------------------------------------------------------- # Update the contents of a previously created viewer control with the new # value of the 'trait' trait of 'object': #----------------------------------------------------------------------------- def update ( self, object, trait_name, control ): tkTraitEditor.update( self, object, trait_name, control ) self.update_color( object, trait_name, control ) #------------------------------------------------------------------------------- # Update the foreground/background colors of the control widget: #------------------------------------------------------------------------------- def update_color ( self, object, trait_name, control ): bg_color = self.to_tk_color( object, trait_name ) red = eval( '0x%s' % bg_color[1:3] ) green = eval( '0x%s' % bg_color[3:5] ) blue = eval( '0x%s' % bg_color[5:7] ) fg_color = ( '#FFFFFF', '#000000' )[ (red > 192) or(green > 192) or(blue > 192) ] control.configure( bg = bg_color, fg = fg_color ) #------------------------------------------------------------------------------- # Get the Tkinter color equivalent of the object trait: #------------------------------------------------------------------------------- def to_tk_color ( self, object, trait_name ): try: cur_color = getattr( object, trait_name + '_' ) except: cur_color = getattr( object, trait_name ) if cur_color is None: return WHITE return cur_color #------------------------------------------------------------------------------- # Get the application equivalent of a Tkinter value: #------------------------------------------------------------------------------- def from_tk_color ( self, color ): return color #------------------------------------------------------------------------------- # Define Tkinter specific color traits: #------------------------------------------------------------------------------- # Create a singleton color editor: color_editor = TraitEditorColor() # Color traits: color_trait = Trait( 'white', standard_colors, num_to_color, editor = color_editor ) clear_color_trait = Trait( 'clear', None, standard_colors, { 'clear': None }, num_to_color, editor = color_editor ) #-------------------------------------------------------------------------------- # Convert a string into a valid Tkinter font (if possible): #-------------------------------------------------------------------------------- slant_types = [ 'roman', 'italic' ] weight_types = [ 'bold' ] font_noise = [ 'pt', 'point', 'family' ] def str_to_font ( object, name, value ): try: size = 10 family = [] slant = 'roman' weight = 'normal' underline = overstrike = 0 for word in value.split(): lword = word.lower() if lword in slant_types: slant = lword elif lword in weight_types: weight = lword elif lword == 'underline': underline = 1 elif lword == 'overstrike': overstrike = 1 elif lword not in font_noise: try: size = int( lword ) except: family.append( word ) if len( family ) == 0: family = [ 'Helvetica' ] return tf.Font( family = ' '.join( family ), size = size, weight = weight, slant = slant, underline = underline, overstrike = overstrike ) except: pass raise TraitError str_to_font.info = ( "a string describing a font (e.g. '12 pt bold italic' " "or 'Arial bold 14 point')" ) #-------------------------------------------------------------------------------- # 'TraitEditorFont' class: #-------------------------------------------------------------------------------- class TraitEditorFont ( tkTraitEditor ): #----------------------------------------------------------------------------- # Create a static view of the current value of the 'trait_name' # trait of 'object': #----------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): control = tkTraitEditor.simple_editor( self, object, trait_name, description, handler, parent ) control.is_custom = FALSE self.update_font( object, trait_name, control ) return control #---------------------------------------------------------------------------- # Create an in-place custom view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def custom_editor ( self, object, trait_name, description, handler, parent ): # Create a panel to hold all of the buttons: panel = tk.Frame( parent ) # Add the standard font control: font = panel.font = self.simple_editor( object, trait_name, description, handler, panel ) font.configure( anchor = 'w' ) font.is_custom = TRUE font.grid( row = 0, column = 0, columnspan = 2, sticky = 'ew', pady = 3 ) # Add all of the font choice controls: delegate = tkDelegate( self.on_value_changed, panel = panel ) values = self.all_facenames() panel.facename = control = Pmw.ComboBox( panel, dropdown = TRUE, selectioncommand = delegate(), scrolledlist_items = values, listheight = min( 150, len( values ) * 24 ) ) control.grid( row = 1, column = 0 ) panel.pointsize = control = Pmw.ComboBox( panel, dropdown = TRUE, selectioncommand = delegate(), scrolledlist_items = point_sizes ) control.grid( row = 1, column = 1, padx = 4 ) # Initialize the control's with the object's current trait value: self.update_font( object, trait_name, font ) # Return the panel as the result: return panel #----------------------------------------------------------------------------- # Update the contents of a previously created viewer control with the new # value of the 'trait' trait of 'object': #----------------------------------------------------------------------------- def update ( self, object, trait_name, control ): tkTraitEditor.update( self, object, trait_name, control ) self.update_font( object, trait_name, control ) #------------------------------------------------------------------------------- # Update the font of the control widget: #------------------------------------------------------------------------------- def update_font ( self, object, trait_name, control ): cur_font = self.to_tk_font( object, trait_name ) size = cur_font.cget( 'size' ) if control.is_custom: panel = control.master try: panel.facename.selectitem( cur_font.cget( 'family' ) ) except: panel.facename.selectitem( 0 ) try: panel.pointsize.selectitem( size ) except: panel.pointsize.selectitem( '10' ) cur_font.configure( size = min( 10, size ) ) control.configure( font = cur_font ) #----------------------------------------------------------------------------- # Return the text representation of the 'trait' trait of 'object': #----------------------------------------------------------------------------- def str ( self, object, trait_name ): font = getattr( object, trait_name ) size = font.cget( 'size' ) family = font.cget( 'family' ) slant = font.cget( 'slant' ) weight = font.cget( 'weight' ) return '%s point %s %s %s' % ( size, family, slant.capitalize(), weight.capitalize() ) #---------------------------------------------------------------------------- # Return a list of all available font facenames: #---------------------------------------------------------------------------- def all_facenames ( self ): return ( 'Courier', 'Times', 'Helvetica', 'Arial', 'Verdana' ) #---------------------------------------------------------------------------- # Handle the user selecting a new facename or point size: #---------------------------------------------------------------------------- def on_value_changed ( self, delegate, unused ): panel = delegate.panel size = panel.pointsize.get() family = panel.facename.get() font = tkFont.Font( family = family, size = size ) self.set( panel.object, panel.trait_name, self.from_tk_font( font ), panel.handler ) self.update( panel.object, panel.trait_name, panel.font ) #------------------------------------------------------------------------------- # Return a Tkinter Font object corresponding to a specified object's font # trait: #------------------------------------------------------------------------------- def to_tk_font ( self, object, trait_name ): return getattr( object, trait_name ) #------------------------------------------------------------------------------- # Get the application equivalent of a Tkinter Font value: #------------------------------------------------------------------------------- def from_tk_font ( self, font ): return font #------------------------------------------------------------------------------- # Define a Tkinter specific font trait: #------------------------------------------------------------------------------- font_trait = Trait( 'Arial 10', tf.Font, str_to_font, editor = TraitEditorFont() ) #------------------------------------------------------------------------------- # 'tkDelegate' class: #------------------------------------------------------------------------------- class tkDelegate: #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, delegate = None, **kw ): self.delegate = delegate for name, value in kw.items(): setattr( self, name, value ) #---------------------------------------------------------------------------- # Return the handle method for the delegate: #---------------------------------------------------------------------------- def __call__ ( self ): return self.on_event #---------------------------------------------------------------------------- # Handle an event: #---------------------------------------------------------------------------- def on_event ( self, *args ): self.delegate( self, *args )
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,332
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/process_input.py
from __future__ import division, print_function # confidence high from stsci.tools import parseinput, fileutil, readgeis, asnutil, irafglob from astropy.io import fits as pyfits import os from . import makewcs """ Process input to pydrizzle. Input can be one of - a python list of files - a comma separated string of filenames (including wild card characters) - an association table - an @file (can have a second column with names of ivm files) No mixture of instruments is allowed. No mixture of association tables, @files and regular fits files is allowed. Files can be in GEIS or MEF format (but not waiver fits). Runs some sanity checks on the input files. If necessary converts files to MEF format (this should not be left to makewcs because 'updatewcs' may be False). Runs makewcs. Returns an association table, ivmlist, output name """ def atfile_sci(f): return f.split()[0] def atfile_ivm(f): return f.split()[1] def process_input(input, output=None, ivmlist=None, updatewcs=True, prodonly=False, shiftfile=None): ivmlist = None oldasndict = None if (isinstance(input, list) == False) and \ ('_asn' in input or '_asc' in input) : # Input is an association table # Get the input files, and run makewcs on them oldasndict = asnutil.readASNTable(input, prodonly=prodonly) if not output: output = oldasndict['output'] filelist = [fileutil.buildRootname(fname) for fname in oldasndict['order']] elif (isinstance(input, list) == False) and \ (input[0] == '@') : # input is an @ file f = open(input[1:]) # Read the first line in order to determine whether # IVM files have been specified in a second column... line = f.readline() f.close() # Parse the @-file with irafglob to extract the input filename filelist = irafglob.irafglob(input, atfile=atfile_sci) # If there is a second column... if len(line.split()) == 2: # ...parse out the names of the IVM files as well ivmlist = irafglob.irafglob(input, atfile=atfile_ivm) else: #input is a string or a python list try: filelist, output = parseinput.parseinput(input, outputname=output) #filelist.sort() except IOError: raise # sort the list of input files # this ensures the list of input files has the same order on all platforms # it can have ifferent order because listdir() uses inode order, not unix type order filelist.sort() newfilelist, ivmlist = checkFiles(filelist, ivmlist) if not newfilelist: buildEmptyDRZ(input,output) return None, None, output #make an asn table at the end if updatewcs: pydr_input = runmakewcs(newfilelist) else: pydr_input = newfilelist # AsnTable will handle the case when output==None if not oldasndict: oldasndict = asnutil.ASNTable(pydr_input, output=output) oldasndict.create() if shiftfile: oldasndict.update(shiftfile=shiftfile) asndict = update_member_names(oldasndict, pydr_input) # Build output filename drz_extn = '_drz.fits' for img in newfilelist: # special case logic to automatically recognize when _flc.fits files # are provided as input and produce a _drc.fits file instead if '_flc.fits' in img: drz_extn = '_drc.fits' break if output in [None,'']: output = fileutil.buildNewRootname(asndict['output'], extn=drz_extn) else: if '.fits' in output.lower(): pass elif drz_extn[:4] not in output.lower(): output = fileutil.buildNewRootname(output, extn=drz_extn) print('Setting up output name: ',output) return asndict, ivmlist, output def checkFiles(filelist, ivmlist = None): """ 1. Converts waiver fits sciece and data quality files to MEF format 2. Converts all GEIS science and data quality files to MEF format 3. Checks for stis association tables 4. Checks if kw idctab exists, if not tries to populate it based on the spt file 5. Removes files with EXPTIME=0 and the corresponding ivm files 6. Removes files with NGOODPIX == 0 (to exclude saturated images) """ #newfilelist = [] removed_files = [] translated_names = [] newivmlist = [] if ivmlist == None: ivmlist = [None for l in filelist] sci_ivm = zip(filelist, ivmlist) for file in sci_ivm: #find out what the input is # if science file is not found on disk, add it to removed_files for removal try: imgfits,imgtype = fileutil.isFits(file[0]) except IOError: print("Warning: File %s could not be found\n" %file[0]) print("Removing file %s from input list" %file[0]) removed_files.append(file) continue if file[1] != None: #If an ivm file is not found on disk # Remove the corresponding science file try: ivmfits,ivmtype = fileutil.isFits(file[1]) except IOError: print("Warning: File %s could not be found\n" %file[1]) print("Removing file %s from input list" %file[0]) removed_files.append(file) # Check for existence of waiver FITS input, and quit if found. # Or should we print a warning and continue but not use that file if imgfits and imgtype == 'waiver': newfilename = waiver2mef(file[0], convert_dq=True) if newfilename == None: print("Removing file %s from input list - could not convert waiver to mef" %file[0]) removed_files.append(file[0]) else: translated_names.append(newfilename) # If a GEIS image is provided as input, create a new MEF file with # a name generated using 'buildFITSName()' # Convert the corresponding data quality file if present if not imgfits: newfilename = geis2mef(file[0], convert_dq=True) if newfilename == None: print("Removing file %s from input list - could not convert geis to mef" %file[0]) removed_files.append(file[0]) else: translated_names.append(newfilename) if file[1] != None: if ivmfits and ivmtype == 'waiver': print("Warning: PyDrizzle does not support waiver fits format.\n") print("Convert the input files to GEIS or multiextension FITS.\n") print("File %s appears to be in waiver fits format \n" %file[1]) print("Removing file %s from input list" %file[0]) removed_files.append(file[0]) if not ivmfits: newfilename = geis2mef(file[1], convert_dq=False) if newfilename == None: print("Removing file %s from input list" %file[0]) removed_files.append(file[0]) else: newivmlist.append(newfilename) newfilelist, ivmlist = update_input(filelist, ivmlist, removed_files) if newfilelist == []: return [], [] """ errormsg = "\n No valid input was found. Quitting ...\n" raise IOError, errormsg """ if translated_names != []: # Since we don't allow input from different instruments # we can abandon the original input list and provide as # input only the translated names removed_expt_files = check_exptime(translated_names) newfilelist, ivmlist = update_input(translated_names, newivmlist, removed_expt_files) else: # check for STIS association files. This must be done before # the check for EXPTIME in order to handle correctly stis # assoc files if pyfits.getval(newfilelist[0], 'INSTRUME') == 'STIS': newfilelist, ivmlist = checkStisFiles(newfilelist, ivmlist) #removed_files = check_exptime(newflist) removed_expt_files = check_exptime(newfilelist) newfilelist, ivmlist = update_input(newfilelist, ivmlist, removed_expt_files) if removed_expt_files: errorstr = "#############################################\n" errorstr += "# #\n" errorstr += "# ERROR: #\n" errorstr += "# #\n" errorstr += "# The following files were excluded from #\n" errorstr += "# Multidrizzle processing because their #\n" errorstr += "# header keyword EXPTIME values were 0.0: #\n" for name in removed_expt_files: errorstr += " "+ str(name) + "\n" errorstr += "# #\n" errorstr += "#############################################\n\n" print(errorstr) removed_ngood_files = checkNGOODPIX(newfilelist) newfilelist, ivmlist = update_input(newfilelist, ivmlist, removed_ngood_files) if removed_ngood_files: msgstr = "####################################\n" msgstr += "# #\n" msgstr += "# WARNING: #\n" msgstr += "# NGOODPIX keyword value of 0 in #\n" for name in removed_ngood_files: msgstr += " "+ str(name) + "\n" msgstr += "# has been detected. Images with #\n" msgstr += "# no valid pixels will not be #\n" msgstr += "# used during processing. If you #\n" msgstr += "# wish this file to be used in #\n" msgstr += "# processing, please check its DQ #\n" msgstr += "# array and reset driz_sep_bits #\n" msgstr += "# and final_bits parameters #\n" msgstr += "# to accept flagged pixels. #\n" msgstr += "# #\n" msgstr += "####################################\n" print(msgstr) return newfilelist, ivmlist def waiver2mef(sciname, newname=None, convert_dq=True): """ Converts a GEIS science file and its corresponding data quality file (if present) to MEF format Writes out both files to disk. Returns the new name of the science image. """ def convert(file): newfilename = fileutil.buildNewRootname(file, extn='_c0h.fits') try: newimage = fileutil.openImage(file,writefits=True, fitsname=newfilename,clobber=True) del newimage return newfilename except IOError: print('Warning: File %s could not be found' % file) return None newsciname = convert(sciname) if convert_dq: dq_name = convert(fileutil.buildNewRootname(sciname, extn='_c1h.fits')) return newsciname def geis2mef(sciname, convert_dq=True): """ Converts a GEIS science file and its corresponding data quality file (if present) to MEF format Writes out both files to disk. Returns the new name of the science image. """ def convert(file): newfilename = fileutil.buildFITSName(file) try: newimage = fileutil.openImage(file,writefits=True, fitsname=newfilename, clobber=True) del newimage return newfilename except IOError: print('Warning: File %s could not be found' % file) return None newsciname = convert(sciname) if convert_dq: dq_name = convert(sciname.split('.')[0] + '.c1h') return newsciname def checkStisFiles(filelist, ivmlist=None): newflist = [] newilist = [] if len(filelist) != len(ivmlist): errormsg = "Input file list and ivm list have different lenghts\n" errormsg += "Quitting ...\n" raise ValueError(errormsg) for t in zip(filelist, ivmlist): sci_count = stisObsCount(t[0]) if sci_count >1: newfilenames = splitStis(t[0], sci_count) newflist.extend(newfilenames) if t[1] != None: newivmnames = splitStis(t[1], sci_count) newilist.extend(newivmnames) else: newilist.append(None) elif sci_count == 1: newflist.append(t[0]) newilist.append(t[1]) else: errormsg = "No valid 'SCI extension in STIS file\n" raise ValueError(errormsg) return newflist, newilist def runmakewcs(input): """ Runs make wcs and recomputes the WCS keywords input: a list of files output: returns a list of names of the modified files (For GEIS files returns the translated names.) """ newNames = makewcs.run(input) return newNames def check_exptime(filelist): """ Removes files with EXPTIME==0 from filelist. """ removed_files = [] for f in filelist: if fileutil.getKeyword(f, 'EXPTIME') <= 0: removed_files.append(f) return removed_files def checkNGOODPIX(filelist): """ Only for ACS, and STIS, check NGOODPIX If all pixels are 'bad' on all chips, exclude this image from further processing. Similar checks requiring comparing 'driz_sep_bits' against WFPC2 c1f.fits arrays and NICMOS DQ arrays will need to be done separately (and later). """ removed_files = [] for inputfile in filelist: if (fileutil.getKeyword(inputfile,'instrume') == 'ACS') \ or fileutil.getKeyword(inputfile,'instrume') == 'STIS': _file = fileutil.openImage(inputfile) _ngood = 0 for extn in _file: if 'EXTNAME' in extn.header and extn.header['EXTNAME'] == 'SCI': _ngood += extn.header['NGOODPIX'] _file.close() if (_ngood == 0): removed_files.append(inputfile) return removed_files def update_input(filelist, ivmlist=None, removed_files=None): """ Removes files flagged to be removed from the input filelist. Removes the corresponding ivm files if present. """ newfilelist = [] if removed_files == []: return filelist, ivmlist else: sci_ivm = list(zip(filelist, ivmlist)) for f in removed_files: result=[sci_ivm.remove(t) for t in sci_ivm if t[0] == f ] ivmlist = [el[1] for el in sci_ivm] newfilelist = [el[0] for el in sci_ivm] return newfilelist, ivmlist def stisObsCount(input): """ Input: A stis multiextension file Output: Number of stis science extensions in input """ count = 0 f = pyfits.open(input) for ext in f: if 'extname' in ext.header: if (ext.header['extname'].upper() == 'SCI'): count += 1 f.close() return count def splitStis(stisfile, sci_count): """ Purpose ======= Split a STIS association file into multiple imset MEF files. Split the corresponding spt file if present into single spt files. If an spt file can't be split or is missing a Warning is printed. Output: a list with the names of the new flt files. """ newfiles = [] f = pyfits.open(stisfile) hdu0 = f[0].copy() for count in range(1,sci_count+1): #newfilename = rootname+str(count)+'.fits' fitsobj = pyfits.HDUList() fitsobj.append(hdu0) hdu = f['sci',count].copy() fitsobj.append(hdu) rootname = hdu.header['EXPNAME'] newfilename = fileutil.buildNewRootname(rootname, extn='_flt.fits') try: # Verify error array exists if f['err',count].data == None: raise ValueError # Verify dq array exists if f['dq',count].data == None: raise ValueError # Copy the err extension hdu = f['err',count].copy() fitsobj.append(hdu) # Copy the dq extension hdu = f['dq',count].copy() fitsobj.append(hdu) except: errorstr = "\n###############################\n" errorstr += "# #\n" errorstr += "# ERROR: #\n" errorstr += "# The input image: #\n" errorstr += " " + str(stisfile) +"\n" errorstr += "# does not contain required #\n" errorstr += "# image extensions. Each #\n" errorstr += "# must contain populated sci,#\n" errorstr += "# dq, and err arrays. #\n" errorstr += "# #\n" errorstr += "###############################\n" raise ValueError(errorstr) # Update the 'EXTNER' keyword to indicate the new extnesion number # for the single exposure files. fitsobj[1].header['EXTVER'] = 1 fitsobj[2].header['EXTVER'] = 1 fitsobj[3].header['EXTVER'] = 1 # Determine if the file you wish to create already exists on the disk. # If the file does exist, replace it. if (os.path.exists(newfilename)): os.remove(newfilename) print(" Replacing "+newfilename+"...") # Write out the new file fitsobj.writeto(newfilename) newfiles.append(newfilename) f.close() sptfilename = fileutil.buildNewRootname(stisfile, extn='_spt.fits') try: sptfile = pyfits.open(sptfilename) except IOError: print('SPT file not found %s \n' % sptfilename) sptfile=None if sptfile: hdu0 = sptfile[0].copy() try: for count in range(1,sci_count+1): fitsobj = pyfits.HDUList() fitsobj.append(hdu0) hdu = sptfile[count].copy() fitsobj.append(hdu) rootname = hdu.header['EXPNAME'] newfilename = fileutil.buildNewRootname(rootname, extn='_spt.fits') fitsobj[1].header['EXTVER'] = 1 if (os.path.exists(newfilename)): os.remove(newfilename) print(" Replacing "+newfilename+"...") # Write out the new file fitsobj.writeto(newfilename) except: print("Warning: Unable to split spt file %s " % sptfilename) sptfile.close() return newfiles def update_member_names(oldasndict, pydr_input): """ Purpose ======= Given an association dictionary with rootnames and a list of full file names, it will update the names in the member dictionary to contain '_*' extension. For example a rootname of 'u9600201m' will be replaced by 'u9600201m_c0h' making sure that a MEf file is passed as an input and not the corresponding GEIS file. """ omembers = oldasndict['members'].copy() nmembers = {} translated_names = [f.split('.fits')[0] for f in pydr_input] newkeys = [fileutil.buildNewRootname(file) for file in pydr_input] for okey, oval in omembers.items(): if okey in newkeys: nkey = pydr_input[newkeys.index(okey)] nmembers[nkey.split('.fits')[0]] = oval # replace should be always True to cover the case when flt files were removed # and the case when names were translated oldasndict.pop('members') oldasndict.update(members=nmembers, replace=True) oldasndict['order'] = translated_names return oldasndict def buildEmptyDRZ(input, output): """ METHOD : _buildEmptyDRZ PURPOSE : Create an empty DRZ file in a valid FITS format so that the HST pipeline can handle the Multidrizzle zero expossure time exception where all data has been excluded from processing. INPUT : None OUTPUT : DRZ file on disk """ if output == None: if len(input) == 1: oname = fu.buildNewRootname(input[0]) else: oname = 'final' _drzextn = '_drz.fits' if '_flc.fits' in input[0]: _drzextn = '_drc.fits' output = fileutil.buildNewRootname(oname,extn=_drzextn) else: if 'drz' not in output: output = fileutil.buildNewRootname(output,extn='_drz.fits') print('Setting up output name: ',output) # Open the first image of the excludedFileList to use as a template to build # the DRZ file. inputfile = parseinput.parseinput(input)[0] try : img = pyfits.open(inputfile[0]) except: raise IOError('Unable to open file %s \n' %inputfile) # Create the fitsobject fitsobj = pyfits.HDUList() # Copy the primary header hdu = img[0].copy() fitsobj.append(hdu) # Modify the 'NEXTEND' keyword of the primary header to 3 for the #'sci, wht, and ctx' extensions of the newly created file. fitsobj[0].header['NEXTEND'] = 3 # Create the 'SCI' extension hdu = pyfits.ImageHDU(header=img['sci',1].header.copy(),data=None) hdu.header['EXTNAME'] = 'SCI' fitsobj.append(hdu) # Create the 'WHT' extension hdu = pyfits.ImageHDU(header=img['sci',1].header.copy(),data=None) hdu.header['EXTNAME'] = 'WHT' fitsobj.append(hdu) # Create the 'CTX' extension hdu = pyfits.ImageHDU(header=img['sci',1].header.copy(),data=None) hdu.header['EXTNAME'] = 'CTX' fitsobj.append(hdu) # Add HISTORY comments explaining the creation of this file. fitsobj[0].header.add_history("** Multidrizzle has created this empty DRZ **") fitsobj[0].header.add_history("** product because all input images were **") fitsobj[0].header.add_history("** excluded from processing because their **") fitsobj[0].header.add_history("** header EXPTIME values were 0.0. If you **") fitsobj[0].header.add_history("** still wish to use this data make the **") fitsobj[0].header.add_history("** EXPTIME values in the header non-zero. **") # Change the filename in the primary header to reflect the name of the output # filename. fitsobj[0].header['FILENAME'] = str(output) #+"_drz.fits" # Change the ROOTNAME keyword to the ROOTNAME of the output PRODUCT _drzsuffix = 'drz' if 'drc' in output: _drzsuffix = 'drc' fitsobj[0].header['ROOTNAME'] = str(output.split('_%s.fits'%_drzsuffix)[0]) print('self.output', output) # Modify the ASN_MTYP keyword to contain "PROD-DTH" so it can be properly # ingested into the archive catalog. fitsobj[0].header['ASN_MTYP'] = 'PROD-DTH' errstr = "#############################################\n" errstr += "# #\n" errstr += "# ERROR: #\n" errstr += "# Multidrizzle has created this empty DRZ #\n" errstr += "# product because all input images were #\n" errstr += "# excluded from processing because their #\n" errstr += "# header EXPTIME values were 0.0. If you #\n" errstr += "# still wish to use this data make the #\n" errstr += "# EXPTIME values in the header non-zero. #\n" errstr += "# #\n" errstr += "#############################################\n\n" print(errstr) # If the file is already on disk delete it and replace it with the # new file dirfiles = os.listdir(os.curdir) if (dirfiles.count(output) > 0): os.remove(output) print(" Replacing "+output+"...") # Write out the empty DRZ file fitsobj.writeto(output) return
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,333
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/traits102/wxmenu.py
#=============================================================================== # # Dynamically construct wxPython Menus or MenuBars from a supplied string # string description of the menu. # # Written By: David C. Morrill # # Date: 01/24/2002 # # Version: 0.1 # # (c) Copyright 2002 by Enthought, Inc. # #=============================================================================== # # Menu Description Syntax: # # submenu_label {help_string} # menuitem_label | accelerator {help_string} [~/-name]: code # - # # where: # submenu_label = Label of a sub menu # menuitem_label = Label of a menu item # help_string = Help string to display on the status line (optional) # accelerator = Accelerator key (e.g. Ctrl-C) (| and key are optional) # [~] = Menu item checkable, but not checked initially (optional) # [/] = Menu item checkable, and checked initially (optional) # [-] = Menu item disabled initially (optional) # [name] = Symbolic name used to refer to menu item (optional) # code = Python code invoked when menu item is selected # #=============================================================================== #=============================================================================== # Imports: #=============================================================================== from __future__ import division, print_function # confidence high import wxPython.wx as wx import re import sys if PY3K: import builtins exec_ = getattr(builtins, "exec") else: def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" if _globs_ is None: frame = sys._getframe(1) _globs_ = frame.f_globals if _locs_ is None: _locs_ = frame.f_locals del frame elif _locs_ is None: _locs_ = _globs_ exec("exec _code_ in _globs_, _locs_") #=============================================================================== # Constants: #=============================================================================== TRUE = 1 FALSE = 0 DEBUG = TRUE help_pat = re.compile( r'(.*){(.*)}(.*)' ) options_pat = re.compile( r'(.*)\[(.*)\](.*)' ) key_map = { 'F1': wx.WXK_F1, 'F2': wx.WXK_F2, 'F3': wx.WXK_F3, 'F4': wx.WXK_F4, 'F5': wx.WXK_F5, 'F6': wx.WXK_F6, 'F7': wx.WXK_F7, 'F8': wx.WXK_F8, 'F9': wx.WXK_F9, 'F10': wx.WXK_F10, 'F11': wx.WXK_F11, 'F12': wx.WXK_F12 } #=============================================================================== # 'MakeMenu' class: #=============================================================================== class MakeMenu: # Initialize the globally unique menu ID: cur_id = 1000 def __init__ ( self, desc, owner, popup = FALSE, window = None ): self.owner = owner if window is None: window = owner self.window = window self.indirect = getattr( owner, 'call_menu', None ) self.names = {} self.desc = desc.split( '\n' ) self.index = 0 self.keys = [] if popup: self.menu = menu = wx.wxMenu() self.parse( menu, -1 ) else: self.menu = menu = wx.wxMenuBar() self.parse( menu, -1 ) window.SetMenuBar( menu ) if len( self.keys ) > 0: window.SetAcceleratorTable( wx.wxAcceleratorTable( self.keys ) ) #============================================================================ # Recursively parse menu items from the description: #============================================================================ def parse ( self, menu, indent ): while TRUE: # Make sure we have not reached the end of the menu description yet: if self.index >= len( self.desc ): return # Get the next menu description line and check its indentation: dline = self.desc[ self.index ] line = dline.lstrip() indented = len( dline ) - len( line ) if indented <= indent: return # Indicate that the current line has been processed: self.index += 1 # Check for a blank or comment line: if (line == '') or (line[0:1] == '#'): continue # Check for a menu separator: if line[0:1] == '-': menu.AppendSeparator() continue # Allocate a new menu ID: MakeMenu.cur_id += 1 cur_id = MakeMenu.cur_id # Extract the help string (if any): help = '' match = help_pat.search( line ) if match: help = ' ' + match.group(2).strip() line = match.group(1) + match.group(3) # Check for a menu item: col = line.find( ':' ) if col >= 0: handler = line[ col + 1: ].strip() if handler != '': if self.indirect: self.indirect( cur_id, handler ) handler = self.indirect else: try: exec('def handler(event,self=self.owner):\n %s\n' % handler) except: handler = null_handler else: try: exec_('def handler(event,self=self.owner):\n%s\n' % (self.get_body(indented), ), _globs_=globals()) except: handler = null_handler wx.EVT_MENU( self.window, cur_id, handler ) not_checked = checked = disabled = FALSE line = line[ : col ] match = options_pat.search( line ) if match: line = match.group(1) + match.group(3) not_checked, checked, disabled, name = option_check( '~/-', match.group(2).strip() ) if name != '': self.names[ name ] = cur_id setattr( self.owner, name, MakeMenuItem( self, cur_id ) ) label = line.strip() col = label.find( '|' ) if col >= 0: key = label[ col + 1: ].strip() label = '%s%s%s' % ( label[ : col ].strip(), '\t', key ) key = key.upper() flag = wx.wxACCEL_NORMAL col = key.find( '-' ) if col >= 0: flag = { 'CTRL': wx.wxACCEL_CTRL, 'SHIFT': wx.wxACCEL_SHIFT, 'ALT': wx.wxACCEL_ALT }.get( key[ : col ].strip(), wx.wxACCEL_CTRL ) key = key[ col + 1: ].strip() code = key_map.get( key, None ) if code is None: code = ord( key ) self.keys.append( wx.wxAcceleratorEntry( flag, code, cur_id ) ) menu.Append( cur_id, label, help, not_checked or checked ) if checked: menu.Check( cur_id, TRUE ) if disabled: menu.Enable( cur_id, FALSE ) continue # Else must be the start of a sub menu: submenu = wx.wxMenu() label = line.strip() # Recursively parse the sub-menu: self.parse( submenu, indented ) # Add the menu to its parent: try: menu.AppendMenu( cur_id, label, submenu, help ) except: # Handle the case where 'menu' is really a 'MenuBar' (which does # not understand 'MenuAppend'): menu.Append( submenu, label ) #============================================================================ # Return the body of an inline method: #============================================================================ def get_body ( self, indent ): result = [] while self.index < len( self.desc ): line = self.desc[ self.index ] if (len( line ) - len( line.lstrip() )) <= indent: break result.append( line ) self.index += 1 result = '\n'.join( result ).rstrip() if result != '': return result return ' pass' #============================================================================ # Return the id associated with a specified name: #============================================================================ def get_id ( self, name ): if type( name ) is str: return self.names[ name ] return name #============================================================================ # Check (or uncheck) a menu item specified by name: #============================================================================ def checked ( self, name, check = None ): if check is None: return self.menu.IsChecked( self.get_id( name ) ) self.menu.Check( self.get_id( name ), check ) #============================================================================ # Enable (or disable) a menu item specified by name: #============================================================================ def enabled ( self, name, enable = None ): if enable is None: return self.menu.IsEnabled( self.get_id( name ) ) self.menu.Enable( self.get_id( name ), enable ) #============================================================================ # Get/Set the label for a menu item: #============================================================================ def label ( self, name, label = None ): if label is None: return self.menu.GetLabel( self.get_id( name ) ) self.menu.SetLabel( self.get_id( name ), label ) #=============================================================================== # 'MakeMenuItem' class: #=============================================================================== class MakeMenuItem: def __init__ ( self, menu, id ): self.menu = menu self.id = id def checked ( self, check = None ): return self.menu.checked( self.id, check ) def toggle ( self ): checked = not self.checked() self.checked( checked ) return checked def enabled ( self, enable = None ): return self.menu.enabled( self.id, enable ) def label ( self, label = None ): return self.menu.label( self.id, label ) #=============================================================================== # Determine whether a string contains any specified option characters, and # remove them if it does: #=============================================================================== def option_check ( test, str ): result = [] for char in test: col = str.find( char ) result.append( col >= 0 ) if col >= 0: str = str[ : col ] + str[ col + 1: ] return result + [ str.strip() ] #=============================================================================== # Null menu option selection handler: #=============================================================================== def null_handler ( event ): print('null_handler invoked') pass
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,334
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/distortion/mutil.py
from __future__ import division, print_function # confidence high from stsci.tools import fileutil, wcsutil import numpy as np import calendar import datetime # Set up IRAF-compatible Boolean values yes = True no = False # This function read the IDC table and generates the two matrices with # the geometric correction coefficients. # # INPUT: FITS object of open IDC table # OUTPUT: coefficient matrices for Fx and Fy # ### If 'tabname' == None: This should return a default, undistorted ### solution. # def readIDCtab (tabname, chip=1, date=None, direction='forward', filter1=None,filter2=None, offtab=None,tddcorr=False): """ Read IDCTAB, and optional OFFTAB if sepcified, and generate the two matrices with the geometric correction coefficients. If tabname == None, then return a default, undistorted solution. If offtab is specified, dateobs also needs to be given. """ # Return a default geometry model if no IDCTAB filename # is given. This model will not distort the data in any way. if tabname == None: print('Warning: No IDCTAB specified! No distortion correction will be applied.') return defaultModel() # Implement default values for filters here to avoid the default # being overwritten by values of None passed by user. if filter1 == None or filter1.find('CLEAR') == 0: filter1 = 'CLEAR' if filter2 == None or filter2.find('CLEAR') == 0: filter2 = 'CLEAR' # Insure that tabname is full filename with fully expanded # IRAF variables; i.e. 'jref$mc41442gj_idc.fits' should get # expanded to '/data/cdbs7/jref/mc41442gj_idc.fits' before # being used here. # Open up IDC table now... try: ftab = fileutil.openImage(tabname) except: err_str = "------------------------------------------------------------------------ \n" err_str += "WARNING: the IDCTAB geometric distortion file specified in the image \n" err_str += "header was not found on disk; namely, %s \n"%tabname err_str += "Please verify that your environment variable \n" err_str += "(one of 'jref'/'uref'/'oref'/'nref') has been correctly defined. \n" err_str += "If you do not have the IDCTAB file, you may obtain the latest version \n" err_str += "of it from the relevant instrument page on the STScI HST website: \n" err_str += "http://www.stsci.edu/hst/ For WFPC2, STIS and NICMOS data, the \n" err_str += "present run will continue using the old coefficients provided in \n" err_str += "the Dither Package (ca. 1995-1998). \n" err_str += "------------------------------------------------------------------------ \n" raise IOError(err_str) phdr = ftab['PRIMARY'].header # First, check to see if the TDD coeffs are present, if not, complain and quit skew_coeffs = None if 'TDD_DATE' in phdr: print('Reading TDD coefficients from ',tabname) skew_coeffs = read_tdd_coeffs(phdr) # Using coefficients read in from IDCTAB Primary header #skew_coeffs = {'TDD_A0':phdr['TDD_A0'],'TDD_A1':phdr["TDD_A1"], # 'TDD_B0':phdr['TDD_B0'],'TDD_B1':phdr['TDD_B1'], # 'TDD_D0':phdr['TDD_D0'],'TDD_DATE':phdr['TDD_DATE']} #We need to read in the coefficients from the IDC # table and populate the Fx and Fy matrices. if 'DETECTOR' in phdr: detector = phdr['DETECTOR'] else: if 'CAMERA' in phdr: detector = str(phdr['CAMERA']) else: detector = 1 # Set default filters for SBC if detector == 'SBC': if filter1 == 'CLEAR': filter1 = 'F115LP' filter2 = 'N/A' if filter2 == 'CLEAR': filter2 = 'N/A' # Read FITS header to determine order of fit, i.e. k norder = phdr['NORDER'] if norder < 3: order = 3 else: order = norder fx = np.zeros(shape=(order+1,order+1),dtype=np.float64) fy = np.zeros(shape=(order+1,order+1),dtype=np.float64) #Determine row from which to get the coefficients. # How many rows do we have in the table... fshape = ftab[1].data.shape colnames = ftab[1].data.names row = -1 # Loop over all the rows looking for the one which corresponds # to the value of CCDCHIP we are working on... for i in xrange(fshape[0]): try: # Match FILTER combo to appropriate row, #if there is a filter column in the IDCTAB... if 'FILTER1' in colnames and 'FILTER2' in colnames: filt1 = ftab[1].data.field('FILTER1')[i] if filt1.find('CLEAR') > -1: filt1 = filt1[:5] filt2 = ftab[1].data.field('FILTER2')[i] if filt2.find('CLEAR') > -1: filt2 = filt2[:5] else: if 'OPT_ELEM' in colnames: filt1 = ftab[1].data.field('OPT_ELEM') if filt1.find('CLEAR') > -1: filt1 = filt1[:5] else: filt1 = filter1 if 'FILTER' in colnames: _filt = ftab[1].data.field('FILTER')[i] if _filt.find('CLEAR') > -1: _filt = _filt[:5] if 'OPT_ELEM' in colnames: filt2 = _filt else: filt1 = _filt filt2 = 'CLEAR' else: filt2 = filter2 except: # Otherwise assume all rows apply and compare to input filters... filt1 = filter1 filt2 = filter2 if 'DETCHIP' in colnames: detchip = ftab[1].data.field('DETCHIP')[i] if not str(detchip).isdigit(): detchip = 1 else: detchip = 1 if 'DIRECTION' in colnames: direct = ftab[1].data.field('DIRECTION')[i].lower().strip() else: direct = 'forward' if filt1 == filter1.strip() and filt2 == filter2.strip(): if direct == direction.strip(): if int(detchip) == int(chip) or int(detchip) == -999: row = i break if row < 0: err_str = '\nProblem finding row in IDCTAB! Could not find row matching:\n' err_str += ' CHIP: '+str(detchip)+'\n' err_str += ' FILTERS: '+filter1+','+filter2+'\n' ftab.close() del ftab raise LookupError,err_str else: print('- IDCTAB: Distortion model from row',str(row+1),'for chip',detchip,':',filter1.strip(),'and',filter2.strip()) # Read in V2REF and V3REF: this can either come from current table, # or from an OFFTAB if time-dependent (i.e., for WFPC2) theta = None if 'V2REF' in colnames: v2ref = ftab[1].data.field('V2REF')[row] v3ref = ftab[1].data.field('V3REF')[row] else: # Read V2REF/V3REF from offset table (OFFTAB) if offtab: v2ref,v3ref,theta = readOfftab(offtab, date, chip=detchip) else: v2ref = 0.0 v3ref = 0.0 if theta == None: if 'THETA' in colnames: theta = ftab[1].data.field('THETA')[row] else: theta = 0.0 refpix = {} refpix['XREF'] = ftab[1].data.field('XREF')[row] refpix['YREF'] = ftab[1].data.field('YREF')[row] refpix['XSIZE'] = ftab[1].data.field('XSIZE')[row] refpix['YSIZE'] = ftab[1].data.field('YSIZE')[row] refpix['PSCALE'] = round(ftab[1].data.field('SCALE')[row],8) refpix['V2REF'] = v2ref refpix['V3REF'] = v3ref refpix['THETA'] = theta refpix['XDELTA'] = 0.0 refpix['YDELTA'] = 0.0 refpix['DEFAULT_SCALE'] = yes refpix['centered'] = no # Now that we know which row to look at, read coefficients into the # numeric arrays we have set up... # Setup which column name convention the IDCTAB follows # either: A,B or CX,CY if 'CX10' in ftab[1].data.names: cxstr = 'CX' cystr = 'CY' else: cxstr = 'A' cystr = 'B' for i in xrange(norder+1): if i > 0: for j in xrange(i+1): xcname = cxstr+str(i)+str(j) ycname = cystr+str(i)+str(j) fx[i,j] = ftab[1].data.field(xcname)[row] fy[i,j] = ftab[1].data.field(ycname)[row] ftab.close() del ftab # If CX11 is 1.0 and not equal to the PSCALE, then the # coeffs need to be scaled if fx[1,1] == 1.0 and abs(fx[1,1]) != refpix['PSCALE']: fx *= refpix['PSCALE'] fy *= refpix['PSCALE'] if tddcorr: print(" *** Computing ACS Time Dependent Distortion Coefficients *** ") alpha,beta = compute_wfc_tdd_coeffs(date, skew_coeffs) fx,fy = apply_wfc_tdd_coeffs(fx, fy, alpha, beta) refpix['TDDALPHA'] = alpha refpix['TDDBETA'] = beta else: refpix['TDDALPHA'] = 0.0 refpix['TDDBETA'] = 0.0 # Return arrays and polynomial order read in from table. # NOTE: XREF and YREF are stored in Fx,Fy arrays respectively. return fx,fy,refpix,order def readOfftab(offtab, date, chip=None): #Read V2REF,V3REF from a specified offset table (OFFTAB). # Return a default geometry model if no IDCTAB filenam e # is given. This model will not distort the data in any way. if offtab == None: return 0.,0. # Provide a default value for chip if chip: detchip = chip else: detchip = 1 # Open up IDC table now... try: ftab = fileutil.openImage(offtab) except: raise IOError,"Offset table '%s' not valid as specified!" % offtab #Determine row from which to get the coefficients. # How many rows do we have in the table... fshape = ftab[1].data.shape colnames = ftab[1].data.names row = -1 row_start = None row_end = None v2end = None v3end = None date_end = None theta_end = None num_date = convertDate(date) # Loop over all the rows looking for the one which corresponds # to the value of CCDCHIP we are working on... for ri in xrange(fshape[0]): i = fshape[0] - ri - 1 if 'DETCHIP' in colnames: detchip = ftab[1].data.field('DETCHIP')[i] else: detchip = 1 obsdate = convertDate(ftab[1].data.field('OBSDATE')[i]) # If the row is appropriate for the chip... # Interpolate between dates if int(detchip) == int(chip) or int(detchip) == -999: if num_date <= obsdate: date_end = obsdate v2end = ftab[1].data.field('V2REF')[i] v3end = ftab[1].data.field('V3REF')[i] theta_end = ftab[1].data.field('THETA')[i] row_end = i continue if row_end == None and (num_date > obsdate): date_end = obsdate v2end = ftab[1].data.field('V2REF')[i] v3end = ftab[1].data.field('V3REF')[i] theta_end = ftab[1].data.field('THETA')[i] row_end = i continue if num_date > obsdate: date_start = obsdate v2start = ftab[1].data.field('V2REF')[i] v3start = ftab[1].data.field('V3REF')[i] theta_start = ftab[1].data.field('THETA')[i] row_start = i break ftab.close() del ftab if row_start == None and row_end == None: print('Row corresponding to DETCHIP of ',detchip,' was not found!') raise LookupError elif row_start == None: print('- OFFTAB: Offset defined by row',str(row_end+1)) else: print('- OFFTAB: Offset interpolated from rows',str(row_start+1),'and',str(row_end+1)) # Now, do the interpolation for v2ref, v3ref, and theta if row_start == None or row_end == row_start: # We are processing an observation taken after the last calibration date_start = date_end v2start = v2end v3start = v3end _fraction = 0. theta_start = theta_end else: _fraction = float((num_date - date_start)) / float((date_end - date_start)) v2ref = _fraction * (v2end - v2start) + v2start v3ref = _fraction * (v3end - v3start) + v3start theta = _fraction * (theta_end - theta_start) + theta_start return v2ref,v3ref,theta def readWCSCoeffs(header): #Read distortion coeffs from WCS header keywords and #populate distortion coeffs arrays. # Read in order for polynomials _xorder = header['a_order'] _yorder = header['b_order'] order = max(max(_xorder,_yorder),3) fx = np.zeros(shape=(order+1,order+1),dtype=np.float64) fy = np.zeros(shape=(order+1,order+1),dtype=np.float64) # Set up refpix refpix = {} refpix['XREF'] = header['crpix1'] refpix['YREF'] = header['crpix2'] refpix['XSIZE'] = header['naxis1'] refpix['YSIZE'] = header['naxis2'] refpix['PSCALE'] = header['IDCSCALE'] if 'PAMSCALE' in header: refpix['PAMSCALE'] = header['PAMSCALE'] else: refpix['PSCALE'] = header['IDCSCALE'] refpix['V2REF'] = header['IDCV2REF'] refpix['V3REF'] = header['IDCV3REF'] refpix['THETA'] = header['IDCTHETA'] refpix['XDELTA'] = 0.0 refpix['YDELTA'] = 0.0 refpix['DEFAULT_SCALE'] = yes refpix['centered'] = no # Set up template for coeffs keyword names cxstr = 'A_' cystr = 'B_' fx[0][0] = 0.0 fy[0][0] = 0.0 fx[1][0] = header['OCX10'] fx[1][1] = header['OCX11'] fy[1][0] = header['OCY10'] fy[1][1] = header['OCY11'] # Read coeffs into their own matrix for i in xrange(_xorder+1): for j in xrange(i+1): xcname = cxstr+str(j)+'_'+str(i-j) ycname = cystr+str(j)+'_'+str(i-j) if xcname in header: fx[i,j] = (fx[1][1]*header[xcname] + fx[1][0]*header[ycname]) fy[i,j] = (fy[1][1]*header[xcname] + fy[1][0]*header[ycname]) return fx,fy,refpix,order def readTraugerTable(idcfile,wavelength): # Return a default geometry model if no coefficients filename # is given. This model will not distort the data in any way. if idcfile == None: return fileutil.defaultModel() # Trauger coefficients only result in a cubic file... order = 3 numco = 10 a_coeffs = [0] * numco b_coeffs = [0] * numco indx = _MgF2(wavelength) ifile = open(idcfile,'r') # Search for the first line of the coefficients _line = fileutil.rAsciiLine(ifile) while _line[:7].lower() != 'trauger': _line = fileutil.rAsciiLine(ifile) # Read in each row of coefficients,split them into their values, # and convert them into cubic coefficients based on # index of refraction value for the given wavelength # Build X coefficients from first 10 rows of Trauger coefficients j = 0 while j < 20: _line = fileutil.rAsciiLine(ifile) if _line == '': continue _lc = _line.split() if j < 10: a_coeffs[j] = float(_lc[0])+float(_lc[1])*(indx-1.5)+float(_lc[2])*(indx-1.5)**2 else: b_coeffs[j-10] = float(_lc[0])+float(_lc[1])*(indx-1.5)+float(_lc[2])*(indx-1.5)**2 j = j + 1 ifile.close() del ifile # Now, convert the coefficients into a Numeric array # with the right coefficients in the right place. # Populate output values now... fx = np.zeros(shape=(order+1,order+1),dtype=np.float64) fy = np.zeros(shape=(order+1,order+1),dtype=np.float64) # Assign the coefficients to their array positions fx[0,0] = 0. fx[1] = np.array([a_coeffs[2],a_coeffs[1],0.,0.],dtype=np.float64) fx[2] = np.array([a_coeffs[5],a_coeffs[4],a_coeffs[3],0.],dtype=np.float64) fx[3] = np.array([a_coeffs[9],a_coeffs[8],a_coeffs[7],a_coeffs[6]],dtype=np.float64) fy[0,0] = 0. fy[1] = np.array([b_coeffs[2],b_coeffs[1],0.,0.],dtype=np.float64) fy[2] = np.array([b_coeffs[5],b_coeffs[4],b_coeffs[3],0.],dtype=np.float64) fy[3] = np.array([b_coeffs[9],b_coeffs[8],b_coeffs[7],b_coeffs[6]],dtype=np.float64) # Used in Pattern.computeOffsets() refpix = {} refpix['XREF'] = None refpix['YREF'] = None refpix['V2REF'] = None refpix['V3REF'] = None refpix['XDELTA'] = 0. refpix['YDELTA'] = 0. refpix['PSCALE'] = None refpix['DEFAULT_SCALE'] = no refpix['centered'] = yes return fx,fy,refpix,order def readCubicTable(idcfile): # Assumption: this will only be used for cubic file... order = 3 # Also, this function does NOT perform any scaling on # the coefficients, it simply passes along what is found # in the file as is... # Return a default geometry model if no coefficients filename # is given. This model will not distort the data in any way. if idcfile == None: return fileutil.defaultModel() ifile = open(idcfile,'r') # Search for the first line of the coefficients _line = fileutil.rAsciiLine(ifile) _found = no while _found == no: if _line[:7] in ['cubic','quartic','quintic'] or _line[:4] == 'poly': found = yes break _line = fileutil.rAsciiLine(ifile) # Read in each row of coefficients, without line breaks or newlines # split them into their values, and create a list for A coefficients # and another list for the B coefficients _line = fileutil.rAsciiLine(ifile) a_coeffs = _line.split() x0 = float(a_coeffs[0]) _line = fileutil.rAsciiLine(ifile) a_coeffs[len(a_coeffs):] = _line.split() # Scale coefficients for use within PyDrizzle for i in range(len(a_coeffs)): a_coeffs[i] = float(a_coeffs[i]) _line = fileutil.rAsciiLine(ifile) b_coeffs = _line.split() y0 = float(b_coeffs[0]) _line = fileutil.rAsciiLine(ifile) b_coeffs[len(b_coeffs):] = _line.split() # Scale coefficients for use within PyDrizzle for i in range(len(b_coeffs)): b_coeffs[i] = float(b_coeffs[i]) ifile.close() del ifile # Now, convert the coefficients into a Numeric array # with the right coefficients in the right place. # Populate output values now... fx = np.zeros(shape=(order+1,order+1),dtype=np.float64) fy = np.zeros(shape=(order+1,order+1),dtype=np.float64) # Assign the coefficients to their array positions fx[0,0] = 0. fx[1] = np.array([a_coeffs[2],a_coeffs[1],0.,0.],dtype=np.float64) fx[2] = np.array([a_coeffs[5],a_coeffs[4],a_coeffs[3],0.],dtype=np.float64) fx[3] = np.array([a_coeffs[9],a_coeffs[8],a_coeffs[7],a_coeffs[6]],dtype=np.float64) fy[0,0] = 0. fy[1] = np.array([b_coeffs[2],b_coeffs[1],0.,0.],dtype=np.float64) fy[2] = np.array([b_coeffs[5],b_coeffs[4],b_coeffs[3],0.],dtype=np.float64) fy[3] = np.array([b_coeffs[9],b_coeffs[8],b_coeffs[7],b_coeffs[6]],dtype=np.float64) # Used in Pattern.computeOffsets() refpix = {} refpix['XREF'] = None refpix['YREF'] = None refpix['V2REF'] = x0 refpix['V3REF'] = y0 refpix['XDELTA'] = 0. refpix['YDELTA'] = 0. refpix['PSCALE'] = None refpix['DEFAULT_SCALE'] = no refpix['centered'] = yes return fx,fy,refpix,order def factorial(n): """ Compute a factorial for integer n. """ m = 1 for i in range(int(n)): m = m * (i+1) return m def combin(j,n): """ Return the combinatorial factor for j in n.""" return (factorial(j) / (factorial(n) * factorial( (j-n) ) ) ) def defaultModel(): """ This function returns a default, non-distorting model that can be used with the data. """ order = 3 fx = np.zeros(shape=(order+1,order+1),dtype=np.float64) fy = np.zeros(shape=(order+1,order+1),dtype=np.float64) fx[1,1] = 1. fy[1,0] = 1. # Used in Pattern.computeOffsets() refpix = {} refpix['empty_model'] = yes refpix['XREF'] = None refpix['YREF'] = None refpix['V2REF'] = 0. refpix['XSIZE'] = 0. refpix['YSIZE'] = 0. refpix['V3REF'] = 0. refpix['XDELTA'] = 0. refpix['YDELTA'] = 0. refpix['PSCALE'] = None refpix['DEFAULT_SCALE'] = no refpix['THETA'] = 0. refpix['centered'] = yes return fx,fy,refpix,order # Function to compute the index of refraction for MgF2 at # the specified wavelength for use with Trauger coefficients def _MgF2(lam): _sig = pow((1.0e7/lam),2) return np.sqrt(1.0 + 2.590355e10/(5.312993e10-_sig) + 4.4543708e9/(11.17083e9-_sig) + 4.0838897e5/(1.766361e5-_sig)) def convertDate(date): """ Converts the DATE-OBS date string into an integer of the number of seconds since 1970.0 using calendar.timegm(). INPUT: DATE-OBS in format of 'YYYY-MM-DD'. OUTPUT: Date (integer) in seconds. """ _dates = date.split('-') _val = 0 _date_tuple = (int(_dates[0]), int(_dates[1]), int(_dates[2]), 0, 0, 0, 0, 0, 0) return calendar.timegm(_date_tuple) # # # Time-dependent skew correction functions # # def read_tdd_coeffs(phdr): ''' Read in the TDD related keywords from the PRIMARY header of the IDCTAB ''' skew_coeffs = {} skew_coeffs['TDD_DATE'] = phdr['TDD_DATE'] skew_coeffs['TDDORDER'] = phdr['TDDORDER'] skew_coeffs['TDD_A'] = [] skew_coeffs['TDD_B'] = [] # Now read in all TDD coefficient keywords for k in range(skew_coeffs['TDDORDER']+1): skew_coeffs['TDD_A'].append(phdr['TDD_A'+str(k)]) skew_coeffs['TDD_B'].append(phdr['TDD_B'+str(k)]) return skew_coeffs def compute_wfc_tdd_coeffs(dateobs,skew_coeffs): ''' Compute the alpha and beta terms for the ACS/WFC time-dependent skew correction as described in ACS ISR 07-08 by J. Anderson. ''' # default date of 2004.5 = 2004-7-1 #datedefault = datetime.datetime(2004,7,1) #dday = 2004.5 if not isinstance(dateobs,float): year,month,day = dateobs.split('-') rdate = datetime.datetime(int(year),int(month),int(day)) rday = float(rdate.strftime("%j"))/365.25 + rdate.year else: rday = dateobs if skew_coeffs is None: if rday > 2009.0: err_str = "------------------------------------------------------------------------ \n" err_str += "WARNING: the IDCTAB geometric distortion file specified in the image \n" err_str += " header did not have the time-dependent distortion coefficients. \n" err_str += " The pre-SM4 time-dependent skew solution will be used by default.\n" err_str += " Please update IDCTAB with new reference file from HST archive. \n" err_str += "------------------------------------------------------------------------ \n" print(err_str) #alpha = 0.095 + 0.090*(rday-dday)/2.5 #beta = -0.029 - 0.030*(rday-dday)/2.5 # Using default pre-SM4 coefficients skew_coeffs = {'TDD_A':[0.095,0.090/2.5], 'TDD_B':[-0.029,-0.030/2.5], 'TDD_DATE':2004.5,'TDDORDER':1} # Jay's code only computes the alpha/beta values based on a decimal year # with only 3 digits, so this line reproduces that when needed for comparison # with his results. #rday = float(('%0.3f')%rday) # The zero-point terms account for the skew accumulated between # 2002.0 and 2004.5, when the latest IDCTAB was delivered. #alpha = 0.095 + 0.090*(rday-dday)/2.5 #beta = -0.029 - 0.030*(rday-dday)/2.5 alpha = 0 beta = 0 # Compute skew terms, allowing for non-linear coefficients as well for c in range(len(skew_coeffs['TDD_A'])): alpha += skew_coeffs['TDD_A'][c]* np.power(rday-skew_coeffs['TDD_DATE'],c) beta += skew_coeffs['TDD_B'][c]*np.power(rday-skew_coeffs['TDD_DATE'],c) return alpha,beta def apply_wfc_tdd_coeffs(cx,cy,alpha,beta): ''' Apply the WFC TDD coefficients directly to the distortion coefficients. ''' # Initialize variables to be used theta_v2v3 = 2.234529 scale_idc = 0.05 scale_jay = 0.04973324715 idctheta = theta_v2v3 idcrad = fileutil.DEGTORAD(idctheta) #idctheta = fileutil.RADTODEG(N.arctan2(cx[1,0],cy[1,0])) # Pre-compute the entire correction prior to applying it to the coeffs mrotp = fileutil.buildRotMatrix(idctheta) mrotn = fileutil.buildRotMatrix(-idctheta) abmat = np.array([[beta,alpha],[alpha,beta]]) tdd_mat = np.array([[1+(beta/2048.), alpha/2048.],[alpha/2048.,1-(beta/2048.)]],np.float64) abmat1 = np.dot(tdd_mat, mrotn) abmat2 = np.dot(mrotp,abmat1) icxy = np.dot(abmat2,[cx.ravel(),cy.ravel()]) icx = icxy[0] icy = icxy[1] icx.shape = cx.shape icy.shape = cy.shape return icx,icy def rotate_coeffs(cx,cy,rot,scale=1.0): ''' Rotate poly coeffs by 'rot' degrees. ''' mrot = fileutil.buildRotMatrix(rot)*scale rcxy = np.dot(mrot,[cx.ravel(),cy.ravel()]) rcx = rcxy[0] rcy = rcxy[1] rcx.shape = cx.shape rcy.shape = cy.shape return rcx,rcy
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,335
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/traits102/pmw_demo.py
from __future__ import division, print_function # confidence high import sys import Pmw if sys.version_info[0] >= 3: import Tkinter as tk else: import tkinter as tk class Demo: def __init__(self, parent): # Create two buttons to launch the dialog. w = tk.Button(parent, text = 'Show application modal dialog', command = self.showAppModal) w.pack(padx = 8, pady = 8) w = tk.Button(parent, text = 'Show global modal dialog', command = self.showGlobalModal) w.pack(padx = 8, pady = 8) w = tk.Button(parent, text = 'Show dialog with "no grab"', command = self.showDialogNoGrab) w.pack(padx = 8, pady = 8) w = tk.Button(parent, text = 'Show toplevel window which\n' + 'will not get a busy cursor', command = self.showExcludedWindow) w.pack(padx = 8, pady = 8) # Create the dialog. self.dialog = Pmw.Dialog(parent, buttons = ('OK', 'Apply', 'Cancel', 'Help'), defaultbutton = 'OK', title = 'My dialog', command = self.execute) self.dialog.withdraw() # Add some contents to the dialog. w = tk.Label(self.dialog.interior(), text = 'Pmw Dialog\n(put your widgets here)', background = 'black', foreground = 'white', pady = 20) w.pack(expand = 1, fill = 'both', padx = 4, pady = 4) # Create the window excluded from showbusycursor. self.excluded = Pmw.MessageDialog(parent, title = 'I still work', message_text = 'This window will not get\n' + 'a busy cursor when modal dialogs\n' + 'are activated. In addition,\n' + 'you can still interact with\n' + 'this window when a "no grab"\n' + 'modal dialog is displayed.') self.excluded.withdraw() Pmw.setbusycursorattributes(self.excluded.component('hull'), exclude = 1) def showAppModal(self): self.dialog.activate(geometry = 'centerscreenalways') def showGlobalModal(self): self.dialog.activate(globalMode = 1) def showDialogNoGrab(self): self.dialog.activate(globalMode = 'nograb') def showExcludedWindow(self): self.excluded.show() def execute(self, result): print('You clicked on', result) if result not in ('Apply', 'Help'): self.dialog.deactivate(result)
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,336
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/xytosky.py
from __future__ import absolute_import, division, print_function # confidence high import copy, os from astropy.io import fits as pyfits import numpy as np from numpy import char as C from math import * from . import pydrizzle from stsci.tools import wcsutil # Convenience definitions... yes = True no = False ################# # # # Interface to IRAF version # This version requires 'wcsutil_iraf.py' # __version__= '1.1 (12-Feb-2007)' # # ################# def XYtoSky_pars(input,x=None,y=None,coords=None,colnames=None,linear=yes, idckey='IDCTAB',hms=no,output=None,verbose=yes): #Determine whether we are working with a single input pos or # a file with multiple positions if not coords: # Working with a single position xy = (x,y) else: xy = [] # Read multiple positions from specified/default columns # First, find out what kind of file we are working with: FITS or ASCII. if coords.find('.fits') > 0: # Find out names of columns to read from the FITS table if not colnames: # Assume column names of 'X','Y' _clist = ['X','Y'] else: _clist = colnames.split(',') # Open FITS table and read appropriate columns _ftab = pyfits.open(coords) # # NOTE: assumes columns are listed in order of X,Y! # x = _ftab[1].data.field(_clist[0]).tolist() y = _ftab[1].data.field(_clist[1]).tolist() for i in range(len(x)): xy.append([x[i],y[i]]) _ftab.close() del _ftab else: # Open the ASCII table _ifile = open(coords) _lines = _ifile.readlines() _ifile.close() # Get the column names, if specified if colnames: _clist = colnames.split(',') else: _clist = ['1','2'] # Convert strings to ints for use in parsing the lines of the file for n in range(len(_clist)): _clist[n] = int(_clist[n]) - 1 # Read in lines and convert appropriate columns to X,Y lists for line in _lines: line = line.strip() # Convert from tab delimited to space delimited line.replace('\t',' ') if len(line) > 0 and line[0] != '#': _xy = line.split() # Append floating point value from specified column x = float(_xy[_clist[0]]) y = float(_xy[_clist[1]]) xy.append([x,y]) # # Get ra/dec position or Python list of ra/dec positions # radec = XYtoSky(input, xy, idckey=idckey, linear=linear, verbose=no) # # Now format the output for the user... # # Break out the values into separate lists... if isinstance(radec, type([]) ): radd,decdd = [],[] for pos in radec: radd.append(pos[0]) decdd.append(pos[1]) radd = np.array(radd) decdd = np.array(decdd) else: radd = np.array([radec[0]]) decdd = np.array([radec[1]]) if hms: # Convert value(s) to HMS format from decimal degrees # Returns as Python lists of string values ra,dec = wcsutil.ddtohms(radd,decdd,verbose=verbose) else: ra,dec = radd,decdd # Print out what the user wants to see if not output or verbose: # If they input a list, but don't specify an output file, # the only way they are going to get results is to print them # to the screen. for i in range(len(ra)): print('RA (deg.) = ',ra[i],', Dec (deg.)= ',dec[i]) # If user wants to output to a file... if output: _olines = [] if output == coords: if coords.find('.fits') > 0: # User is appending to a FITS table. _fout = pyfits.open(coords,'update') # We need to touch the data so that it can be in memory for # creating the col_defs object _fout[1].data _tcol = _fout[1].columns raname = 'RA' decname = 'Dec' # create columns for RA and Dec arrays if hms: # We are working with lists of strings racol = pyfits.Column(name=raname,format='24a',array=C.array(ra)) deccol = pyfits.Column(name=decname,format='24a',array=C.array(dec)) else: # normal numpy objects racol = pyfits.Column(name=raname,format='1d',array=ra) deccol = pyfits.Column(name=decname,format='1d',array=dec) # Add columns to table now. _tcol.add_col(racol) _tcol.add_col(deccol) # Update table by replacing old HDU with new one _thdu = pyfits.new_table(_tcol) del _fout[1] _fout.append(_thdu) _fout.close() del _fout del _thdu del _tcol else: # If user wants to append results to an ASCII coord file... _olines.insert(0,'# Image: '+input+'\n') _olines.insert(0,'# RA Dec positions computed by PyDrizzle\n') pos = 0 for line in _lines: line = line.strip() if line[0] != '#' and line != '': line = line + ' '+ str(ra[pos])+' '+str(dec[pos])+'\n' pos = pos + 1 _olines.append(line) _ofile = open(output,'w') _ofile.writelines(_olines) _ofile.close() else: # Otherwise, user wants to create new file... _olines.append('# RA Dec positions computed by PyDrizzle\n') _olines.append('# Image: '+input+'\n') if coords: for pos in range(len(ra)): _str = str(ra[pos])+' '+str(dec[pos])+'\n' _olines.append(_str) else: _str = str(ra)+' '+str(dec)+'\n' _olines.append(_str) _ofile = open(output,'w') _ofile.writelines(_olines) _ofile.close() return ra,dec ################# # # # Coordinate Transformation Functions # # ################# def XYtoSky(input, pos, idckey='IDCTAB', linear=yes, verbose=no): """ Convert input pixel position(s) into RA/Dec position(s). Output will be either an (ra,dec) pair or a 'list' of (ra,dec) pairs, not a numpy, to correspond with the input position(s). Parameter: input - Filename with extension specification of image pos - Either a single [x,y] pair or a list of [x,y] pairs. idckey - Keyword which points to the IDC table to be used. linear - If no, apply distortion correction for image. """ # Start by making sure we have a valid extension specification. _insplit = input.split('[') if len(_insplit) == 1: raise IOError('No extension specified for input image!') # Now we need to insure that the input is an array: if not isinstance(pos,np.ndarray): if np.array(pos).ndim > 1: pos = np.array(pos,dtype=np.float64) # Set up Exposure object _exposure = pydrizzle.Exposure(input,idckey=idckey) ra,dec = _exposure.geometry.XYtoSky(pos,linear=linear,verbose=verbose) if not isinstance(ra,np.ndarray): # We are working with a single input, return single values return ra,dec else: # We are working with arrays, so we need to convert them # from 2 arrays with RA in one and Dec in the other to 1 array # with pairs of RA/Dec values. _radec = np.zeros(shape=(len(ra),2),dtype=ra.dtype) _radec[:,0] = ra _radec[:,1] = dec return _radec.tolist()
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,337
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/outputimage.py
from __future__ import division, print_function # confidence medium import types from astropy.io import fits as pyfits from stsci.tools import fileutil, readgeis yes = True no = False RESERVED_KEYS = ['NAXIS','BITPIX','DATE','IRAF-TLM','XTENSION','EXTNAME','EXTVER'] EXTLIST = ('SCI', 'WHT', 'CTX') DTH_KEYWORDS=['CD1_1','CD1_2', 'CD2_1', 'CD2_2', 'CRPIX1', 'CRPIX2','CRVAL1', 'CRVAL2', 'CTYPE1', 'CTYPE2'] class OutputImage: """ This class manages the creation of the array objects which will be used by Drizzle. The three arrays, SCI/WHT/CTX, will be setup either as extensions in a single multi-extension FITS file, or as separate FITS files. """ def __init__(self, plist, build=yes, wcs=None, single=no, blot=no): """ The object 'plist' must contain at least the following members: plist['output'] - name of output FITS image (for SCI) plist['outnx'] - size of X axis for output array plist['outny'] - size of Y axis for output array If 'single=yes', then 'plist' also needs to contain: plist['outsingle'] plist['outsweight'] plist['outscontext'] If 'blot=yes', then 'plist' also needs: plist['data'] plist['outblot'] plist['blotnx'],plist['blotny'] If 'build' is set to 'no', then each extension/array must be in separate FITS objects. This would also require: plist['outdata'] - name of output SCI FITS image plist['outweight'] - name of output WHT FITS image plist['outcontext'] - name of output CTX FITS image Optionally, the overall exposure time information can be passed as: plist['texptime'] - total exptime for output plist['expstart'] - start time of combined exposure plist['expend'] - end time of combined exposure """ self.build = build self.single = single self.parlist = plist _nimgs = len(self.parlist) self.bunit = None self.units = 'cps' if not blot: self.output = plist[0]['output'] self.shape = (plist[0]['outny'],plist[0]['outnx']) else: self.output = plist[0]['outblot'] self.shape = (plist[0]['blotny'],plist[0]['blotnx']) # Keep track of desired output WCS computed by PyDrizzle self.wcs = wcs # # Apply special operating switches: # single - separate output for each input # if single: _outdata = plist[0]['outsingle'] _outweight = plist[0]['outsweight'] _outcontext = plist[0]['outscontext'] # Only report values appropriate for single exposure self.texptime = plist[0]['exptime'] self.expstart = plist[0]['expstart'] self.expend = plist[0]['expend'] else: _outdata = plist[0]['outdata'] _outweight = plist[0]['outweight'] _outcontext = plist[0]['outcontext'] # Report values appropriate for entire combined product self.texptime = plist[0]['texptime'] self.expstart = plist[0]['texpstart'] self.expend = plist[_nimgs-1]['texpend'] if blot: _outdata = plist[0]['outblot'] if not self.build or single: self.output = _outdata self.outdata = _outdata self.outweight = _outweight self.outcontext = _outcontext def set_bunit(self,bunit): """ Method used to update the value of the bunit attribute.""" self.bunit = bunit def set_units(self,units): """ Method used to record what units were specified by the user for the output product.""" self.units = units def writeFITS(self, template, sciarr, whtarr, ctxarr=None, versions=None, extlist=EXTLIST, overwrite=yes): """ Generate PyFITS objects for each output extension using the file given by 'template' for populating headers. The arrays will have the size specified by 'shape'. """ if fileutil.findFile(self.output): if overwrite: print('Deleting previous output product: ',self.output) fileutil.removeFile(self.output) else: print('WARNING: Output file ',self.output,' already exists and overwrite not specified!') print('Quitting... Please remove before resuming operations.') raise IOError # Default value for NEXTEND when 'build'== True nextend = 3 if not self.build: nextend = 0 if self.outweight: if overwrite: if fileutil.findFile(self.outweight): print('Deleting previous output WHT product: ',self.outweight) fileutil.removeFile(self.outweight) else: print('WARNING: Output file ',self.outweight,' already exists and overwrite not specified!') print('Quitting... Please remove before resuming operations.') raise IOError if self.outcontext: if overwrite: if fileutil.findFile(self.outcontext): print('Deleting previous output CTX product: ',self.outcontext) fileutil.removeFile(self.outcontext) else: print('WARNING: Output file ',self.outcontext,' already exists and overwrite not specified!') print('Quitting... Please remove before resuming operations.') raise IOError # Get default headers from multi-extension FITS file # If input data is not in MEF FITS format, it will return 'None' # and those headers will have to be generated from drizzle output # file FITS headers. # NOTE: These are HEADER objects, not HDUs prihdr,scihdr,errhdr,dqhdr = getTemplates(template,extlist) if prihdr == None: # Use readgeis to get header for use as Primary header. _indx = template.find('[') if _indx < 0: _data = template else: _data = template[:_indx] fpri = readgeis.readgeis(_data) prihdr = fpri[0].header.copy() fpri.close() del fpri # Setup primary header as an HDU ready for appending to output FITS file prihdu = pyfits.PrimaryHDU(header=prihdr,data=None) # Start by updating PRIMARY header keywords... prihdu.header.update('EXTEND',pyfits.TRUE,after='NAXIS') prihdu.header.update('NEXTEND',nextend) prihdu.header.update('FILENAME', self.output) # Update the ROOTNAME with the new value as well _indx = self.output.find('_drz') if _indx < 0: prihdu.header.update('ROOTNAME', self.output) else: prihdu.header.update('ROOTNAME', self.output[:_indx]) # Get the total exposure time for the image # If not calculated by PyDrizzle and passed through # the pardict, then leave value from the template image. if self.texptime: prihdu.header.update('EXPTIME', self.texptime) prihdu.header.update('EXPSTART', self.expstart) prihdu.header.update('EXPEND', self.expend) #Update ASN_MTYPE to reflect the fact that this is a product # Currently hard-wired to always output 'PROD-DTH' as MTYPE prihdu.header.update('ASN_MTYP', 'PROD-DTH') # Update DITHCORR calibration keyword if present # Remove when we can modify FITS headers in place... if 'DRIZCORR' in prihdu.header: prihdu.header.update('DRIZCORR','COMPLETE') if 'DITHCORR' in prihdu.header: prihdu.header.update('DITHCORR','COMPLETE') prihdu.header.update('NDRIZIM',len(self.parlist), comment='Drizzle, No. images drizzled onto output') self.addDrizKeywords(prihdu.header,versions) if scihdr: del scihdr['OBJECT'] if 'CCDCHIP' in scihdr: scihdr.update('CCDCHIP','-999') if 'NCOMBINE' in scihdr: scihdr.update('NCOMBINE', self.parlist[0]['nimages']) # If BUNIT keyword was found and reset, then if self.bunit is not None: scihdr.update('BUNIT',self.bunit,comment="Units of science product") if self.wcs: # Update WCS Keywords based on PyDrizzle product's value # since 'drizzle' itself doesn't update that keyword. scihdr.update('ORIENTAT',self.wcs.orient) scihdr.update('CD1_1',self.wcs.cd11) scihdr.update('CD1_2',self.wcs.cd12) scihdr.update('CD2_1',self.wcs.cd21) scihdr.update('CD2_2',self.wcs.cd22) scihdr.update('CRVAL1',self.wcs.crval1) scihdr.update('CRVAL2',self.wcs.crval2) scihdr.update('CRPIX1',self.wcs.crpix1) scihdr.update('CRPIX2',self.wcs.crpix2) scihdr.update('VAFACTOR',1.0) # Remove any reference to TDD correction if 'TDDALPHA' in scihdr: del scihdr['TDDALPHA'] del scihdr['TDDBETA'] # Remove '-SIP' from CTYPE for output product if scihdr['ctype1'].find('SIP') > -1: scihdr.update('ctype1', scihdr['ctype1'][:-4]) scihdr.update('ctype2',scihdr['ctype2'][:-4]) # Remove SIP coefficients from DRZ product for k in scihdr.items(): if (k[0][:2] in ['A_','B_']) or (k[0][:3] in ['IDC','SCD'] and k[0] != 'IDCTAB') or \ (k[0][:6] in ['SCTYPE','SCRVAL','SNAXIS','SCRPIX']): del scihdr[k[0]] self.addPhotKeywords(scihdr,prihdu.header) ########## # Now, build the output file ########## if self.build: print('-Generating multi-extension output file: ',self.output) fo = pyfits.HDUList() # Add primary header to output file... fo.append(prihdu) hdu = pyfits.ImageHDU(data=sciarr,header=scihdr,name=extlist[0]) fo.append(hdu) # Build WHT extension here, if requested... if errhdr: errhdr.update('CCDCHIP','-999') hdu = pyfits.ImageHDU(data=whtarr,header=errhdr,name=extlist[1]) hdu.header.update('EXTVER',1) if self.wcs: # Update WCS Keywords based on PyDrizzle product's value # since 'drizzle' itself doesn't update that keyword. hdu.header.update('ORIENTAT',self.wcs.orient) hdu.header.update('CD1_1',self.wcs.cd11) hdu.header.update('CD1_2',self.wcs.cd12) hdu.header.update('CD2_1',self.wcs.cd21) hdu.header.update('CD2_2',self.wcs.cd22) hdu.header.update('CRVAL1',self.wcs.crval1) hdu.header.update('CRVAL2',self.wcs.crval2) hdu.header.update('CRPIX1',self.wcs.crpix1) hdu.header.update('CRPIX2',self.wcs.crpix2) hdu.header.update('VAFACTOR',1.0) fo.append(hdu) # Build CTX extension here # If there is only 1 plane, write it out as a 2-D extension if self.outcontext: if ctxarr.shape[0] == 1: _ctxarr = ctxarr[0] else: _ctxarr = ctxarr else: _ctxarr = None hdu = pyfits.ImageHDU(data=_ctxarr,header=dqhdr,name=extlist[2]) hdu.header.update('EXTVER',1) if self.wcs: # Update WCS Keywords based on PyDrizzle product's value # since 'drizzle' itself doesn't update that keyword. hdu.header.update('ORIENTAT',self.wcs.orient) hdu.header.update('CD1_1',self.wcs.cd11) hdu.header.update('CD1_2',self.wcs.cd12) hdu.header.update('CD2_1',self.wcs.cd21) hdu.header.update('CD2_2',self.wcs.cd22) hdu.header.update('CRVAL1',self.wcs.crval1) hdu.header.update('CRVAL2',self.wcs.crval2) hdu.header.update('CRPIX1',self.wcs.crpix1) hdu.header.update('CRPIX2',self.wcs.crpix2) hdu.header.update('VAFACTOR',1.0) fo.append(hdu) fo.writeto(self.output) fo.close() del fo, hdu else: print('-Generating simple FITS output: ',self.outdata) fo = pyfits.HDUList() hdu = pyfits.PrimaryHDU(data=sciarr, header=prihdu.header) # Append remaining unique header keywords from template DQ # header to Primary header... if scihdr: for _card in scihdr.ascard: if (_card.key not in RESERVED_KEYS and _card.key not in hdu.header): hdu.header.ascard.append(_card) del hdu.header['PCOUNT'] del hdu.header['GCOUNT'] self.addPhotKeywords(hdu.header, prihdu.header) hdu.header.update('filename', self.outdata) # Add primary header to output file... fo.append(hdu) fo.writeto(self.outdata) del fo,hdu if self.outweight and whtarr != None: # We need to build new PyFITS objects for each WHT array fwht = pyfits.HDUList() if errhdr: errhdr.update('CCDCHIP','-999') hdu = pyfits.PrimaryHDU(data=whtarr, header=prihdu.header) # Append remaining unique header keywords from template DQ # header to Primary header... if errhdr: for _card in errhdr.ascard: if (_card.key not in RESERVED_KEYS and _card.key not in hdu.header): hdu.header.ascard.append(_card) hdu.header.update('filename', self.outweight) hdu.header.update('CCDCHIP','-999') if self.wcs: # Update WCS Keywords based on PyDrizzle product's value # since 'drizzle' itself doesn't update that keyword. hdu.header.update('ORIENTAT',self.wcs.orient) hdu.header.update('CD1_1',self.wcs.cd11) hdu.header.update('CD1_2',self.wcs.cd12) hdu.header.update('CD2_1',self.wcs.cd21) hdu.header.update('CD2_2',self.wcs.cd22) hdu.header.update('CRVAL1',self.wcs.crval1) hdu.header.update('CRVAL2',self.wcs.crval2) hdu.header.update('CRPIX1',self.wcs.crpix1) hdu.header.update('CRPIX2',self.wcs.crpix2) hdu.header.update('VAFACTOR',1.0) # Add primary header to output file... fwht.append(hdu) fwht.writeto(self.outweight) del fwht,hdu # If a context image was specified, build a PyFITS object # for it as well... if self.outcontext and ctxarr != None: fctx = pyfits.HDUList() # If there is only 1 plane, write it out as a 2-D extension if ctxarr.shape[0] == 1: _ctxarr = ctxarr[0] else: _ctxarr = ctxarr hdu = pyfits.PrimaryHDU(data=_ctxarr, header=prihdu.header) # Append remaining unique header keywords from template DQ # header to Primary header... if dqhdr: for _card in dqhdr.ascard: if (_card.key not in RESERVED_KEYS and _card.key not in hdu.header): hdu.header.ascard.append(_card) hdu.header.update('filename', self.outcontext) if self.wcs: # Update WCS Keywords based on PyDrizzle product's value # since 'drizzle' itself doesn't update that keyword. hdu.header.update('ORIENTAT',self.wcs.orient) hdu.header.update('CD1_1',self.wcs.cd11) hdu.header.update('CD1_2',self.wcs.cd12) hdu.header.update('CD2_1',self.wcs.cd21) hdu.header.update('CD2_2',self.wcs.cd22) hdu.header.update('CRVAL1',self.wcs.crval1) hdu.header.update('CRVAL2',self.wcs.crval2) hdu.header.update('CRPIX1',self.wcs.crpix1) hdu.header.update('CRPIX2',self.wcs.crpix2) hdu.header.update('VAFACTOR',1.0) fctx.append(hdu) fctx.writeto(self.outcontext) del fctx,hdu def addPhotKeywords(self,hdr,phdr): """ Insure that this header contains all the necessary photometry keywords, moving them into the extension header if necessary. This only moves keywords from the PRIMARY header if the keywords do not already exist in the SCI header. """ PHOTKEYS = ['PHOTFLAM','PHOTPLAM','PHOTBW','PHOTZPT','PHOTMODE'] for pkey in PHOTKEYS: if pkey not in hdr: # Make sure there is a copy PRIMARY header, if so, copy it if pkey in phdr: # Copy keyword from PRIMARY header hdr.update(pkey,phdr[pkey]) # then delete it from PRIMARY header to avoid duplication del phdr[pkey] else: # If there is no such keyword to be found, define a default if pkey != 'PHOTMODE': hdr.update(pkey,0.0) else: hdr.update(pkey,'') def addDrizKeywords(self,hdr,versions): """ Add drizzle parameter keywords to header. """ # Extract some global information for the keywords _geom = 'User parameters' _imgnum = 0 for pl in self.parlist: # Start by building up the keyword prefix based # on the image number for the chip _imgnum += 1 _keyprefix = 'D%03d'%_imgnum if type(pl['driz_mask']) != type(''): _driz_mask_name = 'static mask' else: _driz_mask_name = pl['driz_mask'] hdr.update(_keyprefix+'VER',pl['driz_version'][:44], comment='Drizzle, task version') # Then the source of the geometric information hdr.update(_keyprefix+'GEOM','User parameters', comment= 'Drizzle, source of geometric information') # Now we continue to add the other items using the same # "stem" hdr.update(_keyprefix+'DATA',pl['data'][:64], comment= 'Drizzle, input data image') hdr.update(_keyprefix+'DEXP',pl['exptime'], comment= 'Drizzle, input image exposure time (s)') hdr.update(_keyprefix+'OUDA',pl['outdata'][:64], comment= 'Drizzle, output data image') hdr.update(_keyprefix+'OUWE',pl['outweight'][:64], comment= 'Drizzle, output weighting image') hdr.update(_keyprefix+'OUCO',pl['outcontext'][:64], comment= 'Drizzle, output context image') hdr.update(_keyprefix+'MASK',_driz_mask_name[:64], comment= 'Drizzle, input weighting image') # Process the values of WT_SCL to be consistent with # what IRAF Drizzle would output if pl['wt_scl'] == 'exptime': _wtscl = pl['exptime'] elif pl['wt_scl'] == 'expsq': _wtscl = pl['exptime']*pl['exptime'] else: _wtscl = pl['wt_scl'] hdr.update(_keyprefix+'WTSC',_wtscl, comment= 'Drizzle, weighting factor for input image') hdr.update(_keyprefix+'KERN',pl['kernel'], comment= 'Drizzle, form of weight distribution kernel') hdr.update(_keyprefix+'PIXF',pl['pixfrac'], comment= 'Drizzle, linear size of drop') hdr.update(_keyprefix+'COEF',pl['coeffs'][:64], comment= 'Drizzle, coefficients file name ') hdr.update(_keyprefix+'XGIM',pl['xgeoim'][:64], comment= 'Drizzle, X distortion image name ') hdr.update(_keyprefix+'YGIM',pl['ygeoim'][:64], comment= 'Drizzle, Y distortion image name ') hdr.update(_keyprefix+'LAM',pl['plam'], comment='Drizzle, wavelength applied for transformation (nm)') # Only put the next entries is we are NOT using WCS hdr.update(_keyprefix+'SCAL',pl['scale'], comment= 'Drizzle, scale (pixel size) of output image') # Convert the rotation angle back to degrees hdr.update(_keyprefix+'ROT',float("%0.8f"%pl['rot']), comment= 'Drizzle, rotation angle, degrees anticlockwise') # Check the SCALE and units # The units are INPUT pixels on entry to this routine hdr.update(_keyprefix+'XSH',pl['xsh'], comment= 'Drizzle, X shift applied') hdr.update(_keyprefix+'YSH',pl['ysh'], comment= 'Drizzle, Y shift applied') hdr.update(_keyprefix+'SFTU','output', comment='Drizzle, units used for shifts') hdr.update(_keyprefix+'SFTF','output', comment= 'Drizzle, frame in which shifts were applied') hdr.update(_keyprefix+'EXKY','EXPTIME', comment= 'Drizzle, exposure keyword name in input image') hdr.update(_keyprefix+'INUN','counts', comment= 'Drizzle, units of input image - counts or cps') hdr.update(_keyprefix+'OUUN',self.units, comment= 'Drizzle, units of output image - counts or cps') hdr.update(_keyprefix+'FVAL',pl['fillval'], comment= 'Drizzle, fill value for zero weight output pix') OFF=0.5 hdr.update(_keyprefix+'INXC',float(pl['blotnx']//2)+OFF, comment= 'Drizzle, reference center of input image (X)') hdr.update(_keyprefix+'INYC',float(pl['blotny']//2)+OFF, comment= 'Drizzle, reference center of input image (Y)') hdr.update(_keyprefix+'OUXC',float(pl['outnx']//2)+OFF, comment= 'Drizzle, reference center of output image (X)') hdr.update(_keyprefix+'OUYC',float(pl['outny']//2)+OFF, comment= 'Drizzle, reference center of output image (Y)') # Add version information as HISTORY cards to the header if versions != None: ver_str = "PyDrizzle processing performed using: " hdr.add_history(ver_str) for k in versions.keys(): ver_str = ' '+str(k)+' Version '+str(versions[k]) hdr.add_history(ver_str) def getTemplates(fname,extlist): # Obtain default headers for output file # If the output file already exists, use it # If not, use an input file for this information. # # NOTE: Returns 'pyfits.Header' objects, not HDU objects! # if fname == None: print('No data files for creating FITS output.') raise Exception froot,fextn = fileutil.parseFilename(fname) if fextn is not None: fnum = fileutil.parseExtn(fextn)[1] ftemplate = fileutil.openImage(froot,mode='readonly') prihdr = pyfits.Header(cards=ftemplate['PRIMARY'].header.ascard.copy()) del prihdr['pcount'] del prihdr['gcount'] if fname.find('.fits') > 0 and len(ftemplate) > 1: # Setup which keyword we will use to select each # extension... _extkey = 'EXTNAME' defnum = fileutil.findKeywordExtn(ftemplate,_extkey,extlist[0]) # # Now, extract the headers necessary for output (as copies) # 1. Find the SCI extension in the template image # 2. Make a COPY of the extension header for use in new output file if fextn in [None,1]: extnum = fileutil.findKeywordExtn(ftemplate,_extkey,extlist[0]) else: extnum = (extlist[0],fnum) scihdr = pyfits.Header(cards=ftemplate[extnum].header.ascard.copy()) scihdr.update('extver',1) if fextn in [None,1]: extnum = fileutil.findKeywordExtn(ftemplate,_extkey,extlist[1]) else: # there may or may not be a second type of extension in the template count = 0 for f in ftemplate: if 'extname' in f.header and f.header['extname'] == extlist[1]: count += 1 if count > 0: extnum = (extlist[1],fnum) else: # Use science header for remaining headers extnum = (extlist[0],fnum) errhdr = pyfits.Header(cards=ftemplate[extnum].header.ascard.copy()) errhdr.update('extver',1) if fextn in [None,1]: extnum = fileutil.findKeywordExtn(ftemplate,_extkey,extlist[2]) else: count = 0 for f in ftemplate: if 'extname' in f.header and f.header['extname'] == extlist[2]: count += 1 if count > 0: extnum = (extlist[2],fnum) else: # Use science header for remaining headers extnum = (extlist[0],fnum) dqhdr = pyfits.Header(cards=ftemplate[extnum].header.ascard.copy()) dqhdr.update('extver',1) else: # Create default headers from scratch scihdr = None errhdr = None dqhdr = None ftemplate.close() del ftemplate # Now, safeguard against having BSCALE and BZERO try: del scihdr['bscale'] del scihdr['bzero'] del errhdr['bscale'] del errhdr['bzero'] del dqhdr['bscale'] del dqhdr['bzero'] except: # If these don't work, they didn't exist to start with... pass # At this point, check errhdr and dqhdr to make sure they # have all the requisite keywords (as listed in updateDTHKeywords). # Simply copy them from scihdr if they don't exist... if errhdr != None and dqhdr != None: for keyword in DTH_KEYWORDS: if keyword not in errhdr: errhdr.update(keyword,scihdr[keyword]) if keyword not in dqhdr: dqhdr.update(keyword,scihdr[keyword]) return prihdr,scihdr,errhdr,dqhdr
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,338
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/imtype.py
from __future__ import division # confidence high import types from astropy.io import fits as pyfits from stsci.tools import fileutil class Imtype: """ Class which determines the format of the file, how to access the SCI data array, and if available, any DQ array as well. The syntax for accessing the data will then be kept as attributes for use by other tasks/classes. Parameters: filename - name of file to be examined handle - PyFITS-style file handle for image dqsuffix - suffix for DQ array for non-MEF files If 'dqsuffix' is not provided and the file is GEIS formatted, then this class will search for a '.c1h' extension by default, and return None if not found. """ def __init__(self,filename,handle=None,dqsuffix=None): self.handle = handle self.filename = filename self.dqfile = filename self.seperator = ',' # Used for parsing EXTN syntax self.dq_suffix = dqsuffix self.dq_extname = 'dq' self.sci_extname = 'sci' self.sci_extn = '['+self.sci_extname+',1]' # default specification for SCI extension/group self.dq_extn = '['+self.dq_extname+',1]' # default specification for DQ extension/group if filename: if filename.find('.fits') > -1: if handle and len(handle) == 1: # Simple FITS image: # Let the Exposure class find the SCI array. self.sci_extn = None self.dq_extn = None self.dq_extname = None self.sci_extname = None else: # GEIS image self.seperator = '[' if not dqsuffix: _dqsuffix = '.c1h' _indx = filename.rfind('.') if fileutil.findFile(filename[:_indx]+_dqsuffix): self.dq_suffix = '.c1h' else: self.dq_suffix = None self.sci_extn = '[1]' self.dq_extn = '[1]' self.dq_extname = '1' self.sci_extname = '1' def makeSciName(self,extver,section=None): """ Returns the properly formatted filename to access the SCI extension.""" if section == None: _extname = self.filename+self._setSciExtn(extn=extver) else: _extname = self.filename+'[sci,'+str(section)+']' return _extname def makeDQName(self,extver): """ Create the name of the file which contains the DQ array. For multi-extension FITS files, this will be the same file as the SCI array. """ if not self.dq_suffix: _dqname = self.dqfile else: _dqname = fileutil.buildNewRootname(self.dqfile,extn=self.dq_suffix) if self.dq_extn: _dqname += self._setDQExtn(extn=extver) elif self.dq_suffix: _dqname = _dqname+'[0]' else: _dqname = None return _dqname def _setDQExtn(self, extn=None): """ Builds extension specification for accessing DQ extension/group. """ if extn != None: if self.dq_extn: _lensep = len(self.seperator) _indx = self.dq_extn.find(self.seperator) + _lensep return self.dq_extn[:_indx]+repr(extn)+self.dq_extn[_indx+1:] else: return '' else: return self.dq_extn def _setSciExtn(self,extn=None): """ Builds extension specification for accessing SCI extension/group. """ if extn != None: if self.sci_extn: _lensep = len(self.seperator) _indx = self.sci_extn.find(self.seperator) + _lensep return self.sci_extn[:_indx]+repr(extn)+self.sci_extn[_indx+1:] else: return '' else: return self.sci_extn
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,339
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/obsgeometry.py
from __future__ import absolute_import, print_function # confidence medium import types, os, copy from math import ceil, floor # Import PyDrizzle utility modules from stsci.tools import fileutil, wcsutil from .distortion import models,mutil import numpy as np from . import drutil yes = True no = False class ObsGeometry: """ Base class for Observation's geometric information. This class must know how to recognize the different types of distortion coefficients tables and instantiate the correct class for it. """ def __init__(self, rootname, idcfile, idckey=None, chip=1, direction="forward", header=None, pa_key=None, new=None, date=None, rot=None, ref_pscale=1.0,binned=1, mt_wcs=None): """ We need to setup the proper object for the GeometryModel based on the format of the provided idctab. We need to trap attempts to address values of 'chip' that are not part of the observation; such as in sub-arrays. """ self.header = header self.wcs = mt_wcs _offtab = None _filt1 = None _filt2 = None if self.header and (idckey == None or idckey.lower() == 'idctab'): # Try to read in filter names for use in ObsGeometry try: _filtnames = fileutil.getFilterNames(self.header) _filters = _filtnames.split(',') _filt1 = _filters[0] if len(_filters) > 1: _filt2 = _filters[1] else: _filt2 = '' if _filt1.find('CLEAR') > -1: _filt1 = _filt1[:6] if _filt2.find('CLEAR') > -1: _filt2 = _filt2[:6] if _filt1.strip() == '': _filt1 = 'CLEAR1' if _filt2.strip() == '': _filt2 = 'CLEAR2' # Also check to see if an OFFTAB file has been specified if 'OFFTAB' in self.header: _offtab = self.header['offtab'] except: print('! Warning: Using default filter settings of CLEAR.') if _filt1 == None: _filt1 = 'CLEAR1' _filt2 = 'CLEAR2' self.idcfile = idcfile self.direction = direction self.filter1 = _filt1 self.filter2 = _filt2 self.ikey = None self.date = date self.tddcorr = False # Default values for VAFACTOR correction #self.vafactor = 1.0 #self.delta_x = 0.0 #self.delta_y = 0.0 # Default values for secondary shift (tweak-shift values) # These pixel shifts will ALWAYS be in terms of 'input' pixels # Set in 'applyAsnShifts' self.gpar_xsh = 0.0 self.gpar_ysh = 0.0 self.gpar_rot = 0.0 self.def_rot = None if not new: if self.wcs == None: self.wcs = wcsutil.WCSObject(rootname,header=self.header) # Look for SIP WCS. If found, use an archived, unmodified version # of CD matrix instead of regular CD matrix to avoid applying # SIP corrections/TDD corrections twice if self.wcs.ctype1.find('SIP') > -1: pass else: self.wcs = self.wcs[str(chip)] self.wcs.recenter() self.wcslin = self.wcs.copy() # Implement time-dependent skew for those cases where it is needed # Read in the time dependent distrotion skew terms # default date of 2004.5 = 2004-7-1 self.alpha = self.header.get('TDDALPHA', 0.0) self.beta = self.header.get('TDDBETA', 0.0) if self.alpha != 0 or self.beta != 0: self.tddcorr = True # Based on the filetype, open the correct geometry model if idckey != None: ikey = idckey.lower() else: ikey = 'idctab' self.ikey = ikey if ikey == 'idctab': self.model = models.IDCModel(self.idcfile, chip=chip, direction=self.direction, date=self.date, filter1=_filt1, filter2=_filt2, offtab=_offtab, binned=binned, tddcorr=self.tddcorr) elif ikey == 'cubic': scale = self.wcs.pscale / ref_pscale self.model = models.DrizzleModel(self.idcfile, scale=scale) self.model.pscale = scale self.model.refpix['PSCALE'] = self.model.pscale self.model.refpix['XREF'] = self.wcs.naxis1/2. self.model.refpix['YREF'] = self.wcs.naxis2/2. _chip_rot = fileutil.RADTODEG(np.arctan2(self.model.cy[1][0],self.model.cx[1][0])) if rot != None: _theta = _chip_rot - rot _cx = drutil.rotateCubic(self.model.cx,_theta) _cy = drutil.rotateCubic(self.model.cy,_theta) self.model.cx = _cx self.model.cy = _cy self.def_rot = rot else: self.def_rot = _chip_rot elif ikey == 'trauger': _lam = self.header['PHOTPLAM'] self.model = models.TraugerModel(self.idcfile,float(_lam)/10.) elif ikey == 'wcs': if 'IDCSCALE' in self.header: self.model = models.WCSModel(self.header, rootname) else: print('WARNING: Not all SIP-related keywords found!') print(' Reverting to use of IDCTAB for distortion.') self.model = models.IDCModel(self.idcfile, chip=chip, direction=self.direction, date=self.date, filter1=_filt1, filter2=_filt2, offtab=_offtab, binned=binned, tddcorr=self.tddcorr) else: raise ValueError("Unknown type of coefficients table %s"%idcfile) if self.idcfile == None and ikey != 'wcs': #Update default model with WCS plate scale self.model.setPScaleCoeffs(self.wcs.pscale) # Insure that a default model pscale has been set if self.model.refpix['PSCALE'] == None: self.model.pscale = 1.0 self.model.refpix['PSCALE'] = self.model.pscale if self.model.refpix['XREF'] == None: self.model.refpix['XREF'] = self.wcs.naxis1/2. self.model.refpix['YREF'] = self.wcs.naxis2/2. # Determine whether there is any offset for the image # as in the case of subarrays (based on LTV keywords) _ltv1,_ltv2 = drutil.getLTVOffsets(rootname,header=self.header) if float(_ltv1) != 0. or float(_ltv2) != 0.: self.wcs.offset_x = self.wcslin.offset_x = -float(_ltv1) self.wcs.offset_y = self.wcslin.offset_y = -float(_ltv2) _delta_refx = (self.wcs.crpix1 + self.wcs.offset_x) - self.model.refpix['XREF'] _delta_refy = (self.wcs.crpix2 + self.wcs.offset_y) - self.model.refpix['YREF'] self.wcs.delta_refx = self.wcslin.delta_refx = _delta_refx self.wcs.delta_refy = self.wcslin.delta_refy = _delta_refy self.wcs.subarray = self.wcslin.subarray = yes self.wcs.chip_xref = self.wcs.offset_x + self.wcs.crpix1 self.wcs.chip_yref = self.wcs.offset_y + self.wcs.crpix2 # CHIP_X/YREF will be passed as refpix to drizzle through # the coefficients files. This is necessary to account for the # fact that drizzle applies the model in the image frame # while refpix in the the model is defined in the full frame. # This affects subarrays and polarized observations. self.model.refpix['CHIP_XREF'] = self.wcs.crpix1 - self.wcs.delta_refx self.model.refpix['CHIP_YREF'] = self.wcs.crpix2 - self.wcs.delta_refy else: self.wcs.offset_x = self.wcslin.offset_x = 0. self.wcs.offset_y = self.wcslin.offset_y = 0. # Need to account for off-center reference pixel in distortion coeffs self.wcs.delta_refx = self.wcslin.delta_refx = (self.wcs.naxis1/2.0) - self.model.refpix['XREF'] self.wcs.delta_refy = self.wcslin.delta_refy = (self.wcs.naxis2/2.0) - self.model.refpix['YREF'] self.wcs.subarray = self.wcslin.subarray = no self.wcs.chip_xref = self.wcs.naxis1/2. self.wcs.chip_yref = self.wcs.naxis2/2. self.model.refpix['CHIP_XREF'] = self.model.refpix['XREF'] self.model.refpix['CHIP_YREF'] = self.model.refpix['YREF'] # Generate linear WCS to linear CD matrix self.undistortWCS() else: # For new images with no distortion, CD matrix is sufficient. self.wcs = wcsutil.WCSObject(None) self.wcslin = wcsutil.WCSObject(None) self.model = models.GeometryModel() self.wcs.offset_x = self.wcslin.offset_x = 0. self.wcs.offset_y = self.wcslin.offset_y = 0. self.wcs.delta_refx = self.wcslin.delta_refx = 0. self.wcs.delta_refy = self.wcslin.delta_refy = 0. self.wcs.subarray = self.wcslin.subarray = no def apply(self, pixpos,delta=None,pscale=None,verbose=no,order=None): """ This method applies the model to a pixel position to calculate the new position. Depending on the value of direction, this could mean going from distorted/raw to a corrected positions or the other way around. If a specific pixel scale is provided, this will be used to determine the final output position. """ """ verify that pscale is wcs.pscale ... """ if delta == None: # Use default from table. deltax = 0. deltay = 0. else: deltax = delta[0] deltay = delta[1] if pscale == None: pscale = self.model.pscale _ratio = pscale / self.model.pscale # Put input positions into full frame coordinates... pixpos = pixpos + np.array((self.wcs.offset_x,self.wcs.offset_y),dtype=np.float64) #v2,v3 = self.model.apply(pixpos, scale=pscale) v2,v3 = self.model.apply(pixpos,scale=_ratio,order=order) # If there was no distortion applied to # the pixel position, simply shift by new # reference point. if self.model.cx == None: if self.model.refpix != None: if self.model.refpix['XREF'] == None: refpos = (self.wcs.crpix1,self.wcs.crpix2) else: refpos = (self.model.refpix['XREF'],self.model.refpix['YREF']) else: refpos = (self.wcs.crpix1,self.wcs.crpix2) xpos = v2 - refpos[0] + deltax - self.wcs.offset_x/_ratio ypos = v3 - refpos[1] + deltay - self.wcs.offset_y/_ratio else: # For sub-arrays, we need to account for the offset # between the CRPIX of the sub-array and the model reference # position in the full frame coordinate system. # In addition, the LTV value (offset_x,offset_y) needs to be # removed again as well. WJH 12 Sept 2004 # For full images, this correction will be ZERO. # This offset, though, has to be scaled by the relative plate-scales. # #v2 = v2 / pscale #v3 = v3 / pscale xpos = v2 + deltax - (self.wcs.delta_refx / _ratio) ypos = v3 + deltay - (self.wcs.delta_refy / _ratio) # Return the geometrically-adjusted position as a tuple (x,y) return xpos,ypos def applyVAFactor(self, vafactor, ra_targ, dec_targ): """ Correct the distortion coefficients for the effects of velocity aberration, IF the VAFACTOR value is present. This method relies on RA_TARG and DEC_TARG to provide the information on where the telescope was pointing, the point which serves as the center of the radial velocity aberration. """ if vafactor != 1.0 and vafactor: self.vafactor = vafactor # Convert ra_targ, dec_targ into X,Y position relative to this chip targ_x,targ_y = self.wcslin.rd2xy((ra_targ,dec_targ)) delta_x = targ_x - self.wcslin.crpix1 delta_y = targ_y - self.wcslin.crpix2 #self.delta_x = delta_x*(vafactor - 1.0)*self.wcslin.pscale #self.delta_y = delta_y*(vafactor - 1.0)*self.wcslin.pscale self.delta_x = delta_x*vafactor self.delta_y = delta_y*vafactor # Now, shift coefficients to the X/Y position of the target aperture _xcs,_ycs = self.model.shift(self.model.cx,self.model.cy,delta_x,delta_y) #_xc = self.model.cx #_yc = self.model.cy # Apply VAFACTOR for i in range(self.model.norder+1): for j in range(i+1): _xcs[i][j] *= np.power(vafactor,i) _ycs[i][j] *= np.power(vafactor,i) _xc,_yc = self.model.shift(_xcs,_ycs,-delta_x,-delta_y) # Update coefficients with these values self.model.cx = _xc self.model.cy = _yc def wtraxy(self,pixpos,wcs,verbose=False): """ Converts input pixel position 'pixpos' into an X,Y position in WCS. Made this function compatible with list input, as well as single tuple input..apply """ # Insure that input wcs is centered for proper results # Added 1-Dec-2004. wcs.recenter() _ab,_cd = drutil.wcsfit(self,wcs) _orient = fileutil.RADTODEG(np.arctan2(_ab[1],_cd[0])) _scale = wcs.pscale/self.wcslin.pscale _xoff = _ab[2] _yoff = _cd[2] # changed from self.wcs.naxis[1/2] _naxis = (wcs.naxis1,wcs.naxis2) _rot_mat = fileutil.buildRotMatrix(_orient) if isinstance(pixpos, tuple): pixpos = [pixpos] _delta_x,_delta_y = self.apply(pixpos) if verbose: print('Raw corrected position: ',_delta_x,_delta_y) _delta_x += self.model.refpix['XDELTA'] _delta_y += self.model.refpix['YDELTA'] if verbose: print('Fully corrected position: ',_delta_x,_delta_y) _delta = np.zeros((len(pixpos),2),dtype=np.float32) _delta[:,0] = _delta_x _delta[:,1] = _delta_y # Need to 0.5 offset to xp,yp to compute the offset in the same way that # 'drizzle' computes it. #_xp = _naxis[0]/2. + 0.5 #_yp = _naxis[1]/2. + 0.5 _xp = _naxis[0]/2. _yp = _naxis[1]/2. _xt = _xoff + _xp _yt = _yoff + _yp if verbose: print('XSH,YSH: ',_xoff,_yoff) print('XDELTA,YDELTA: ',self.model.refpix['XDELTA'],self.model.refpix['YDELTA']) print('XREF,YREF: ',self.model.refpix['XREF'],self.model.refpix['YREF']) print('xt,yt: ',_xt,_yt,' based on xp,yp: ',_xp,_yp) _xy_corr = np.dot(_delta,_rot_mat) / _scale _delta[:,0] = _xy_corr[:,0] + _xt _delta[:,1] = _xy_corr[:,1] + _yt if len(pixpos) == 1: return _delta[0] else: return _delta #return (_x_out,_y_out) def invert(self,pixpos,outwcs,error=None,maxiter=None): """ This method is the reverse of "apply" - it finds a position which, when distorted, maps to "pixpos". The method is iterative and is modelled on that in "tranback" in the dither package. pixpos is an x,y pixel position tuple. pixpos is assumed to be in the appropriate sub-array coordinates. Richard Hook, ST-ECF/STScI, January 2003 """ # Set an appropriate value of error, if not supplied if error == None: error=0.001 # Set a sensible number of iterations as default if maxiter == None: maxiter=10 # Put input positions into full frame coordinates... # Also convert X,Y tuple to a numpy pp = np.array([pixpos]) + np.array((self.wcs.offset_x,self.wcs.offset_y),dtype=np.float64) # We are going to work with three x,y points as a Numpy array pos=np.zeros((3,2),dtype=np.float64) # We also need a matrix of the shifts shift=np.zeros((2,2),dtype=np.float64) # Setup an initial guess - just the first pixel pos[0]=[self.wcs.crpix1,self.wcs.crpix2] # Loop around until we get close enough (determined by the optional error value) for i in range(maxiter): # Offset by 1 in X and Y pos[1]=pos[0]+[1.0,0.0] pos[2]=pos[0]+[0.0,1.0] # Apply the forward transform for this chip tout=self.wtraxy(pos,outwcs) # Convert back to Numpy out=np.array(tout,dtype=np.float64) # Work out the shifts matrix shift[0]=out[1]-out[0] shift[1]=out[2]-out[0] # Invert the matrix (this probably should be a separate method) shift = np.linalg.inv(shift) # Determine the X and Y errors errors=pp-out[0] # Keep the old position before updating it old=pos[0].copy() # Update the position pos[0]=[old[0]+errors[0,0]*shift[0,0]+errors[0,1]*shift[1,0], \ old[1]+errors[0,0]*shift[0,1]+errors[0,1]*shift[1,1]] # Check the size of the error ev=np.sqrt(np.power(pos[0,0]-old[0],2) + np.power(pos[0,1]-old[1],2)) # Stop looping if close enough if ev < error: break # Return the new position as a tuple return pos[0,0],pos[0,1] def undistortWCS(self,shape=None): """ This method applies the distortion to a 1x1 box at the reference position and updates the WCS based on the results. This method is based directly on the 'drizzle' subroutine 'UPWCS' written by R. Hook. """ # Check to see if we have a valid model to apply to the WCS if self.model.cx == None: return # define the reference point _cpix1 = self.wcs.crpix1 _cpix2 = self.wcs.crpix2 if not shape: _cen = (_cpix1, _cpix2) else: _cen = (shape[0]/2. + 0.5,shape[1]/2. + 0.5) _xy = np.array([(_cpix1,_cpix2),(_cpix1+1.,_cpix2),(_cpix1,_cpix2+1.)],dtype=np.float64) # _xdelta = self.model.refpix['XDELTA'] _ydelta = self.model.refpix['YDELTA'] # apply the distortion to them _xc,_yc = self.apply(_xy) _xc += _xdelta + _cen[0] _yc += _ydelta + _cen[1] # Now, work out the effective CD matrix of the transformation _am = _xc[1] - _xc[0] _bm = _xc[2] - _xc[0] _cm = _yc[1] - _yc[0] _dm = _yc[2] - _yc[0] _cd_mat = np.array([[_am,_bm],[_cm,_dm]],dtype=np.float64) # Check the determinant for singularity _det = (_am * _dm) - (_bm * _cm) if ( _det == 0.0): print('Matrix is singular! Can NOT update WCS.') return _cd_inv = np.linalg.inv(_cd_mat) _a = _cd_inv[0,0] _b = _cd_inv[0,1] _c = _cd_inv[1,0] _d = _cd_inv[1,1] self.wcslin.cd11 = _a * self.wcs.cd11 + _c * self.wcs.cd12 self.wcslin.cd21 = _a * self.wcs.cd21 + _c * self.wcs.cd22 self.wcslin.cd12 = _b * self.wcs.cd11 + _d * self.wcs.cd12 self.wcslin.cd22 = _b * self.wcs.cd21 + _d * self.wcs.cd22 self.wcslin.orient = np.arctan2(self.wcslin.cd12,self.wcslin.cd22) * 180./np.pi self.wcslin.pscale = np.sqrt(np.power(self.wcslin.cd11,2)+np.power(self.wcslin.cd21,2))*3600. # Compute new size and reference pixel position... _wcorners = self.calcNewCorners() _x0 = int(floor(np.minimum.reduce(_wcorners[:,0]))) if _x0 > 0: _xmin = 0.0 else: _xmin = _x0 _y0 = int(floor(np.minimum.reduce(_wcorners[:,1]))) if _y0 > 0: _ymin = 0.0 else: _ymin = _y0 _naxis1 = int(ceil(np.maximum.reduce(_wcorners[:,0]))) - _xmin _naxis2 = int(ceil(np.maximum.reduce(_wcorners[:,1]))) - _ymin self.wcslin.naxis1 = int(_naxis1) self.wcslin.naxis2 = int(_naxis2) self.wcslin.crpix1 = self.wcslin.naxis1/2. self.wcslin.crpix2 = self.wcslin.naxis2/2. # Compute the position of the distortion-corrected image center _center = self.apply([(self.wcs.crpix1,self.wcs.crpix2)]) self.wcslin.cenx = self.wcslin.crpix1 - _center[0] self.wcslin.ceny = self.wcslin.crpix2 - _center[1] def XYtoSky(self, pos,verbose=no,linear=no): """ This method applies the distortion model to a pixel position and calculates the sky position in RA/Dec. """ if not linear and self.model.refpix != None: # Perform full solution including distortion # Now we need to insure that the input is an array: if not isinstance(pos,np.ndarray): if np.array(pos).ndim > 1: pos = np.array(pos,dtype=np.float64) else: pos = np.array([pos],dtype=np.float64) dcx,dcy = self.apply(pos,verbose=no) if dcx != None: # Account for displacement of center for sub-arrays _cpos = (dcx +self.wcslin.cenx, dcy + self.wcslin.ceny ) # Now apply linear CD matrix appropriate to model xsky,ysky = self.wcslin.xy2rd(_cpos) else: xsky,ysky = self.wcs.xy2rd(pos) else: print('RA/Dec positions without using distortion coefficients:') xsky,ysky = self.wcs.xy2rd(pos) # Format the results for easy understanding, if desired... if verbose: rastr,decstr = wcsutil.ddtohms(xsky,ysky,verbose=verbose) print('RA: ',rastr,' Dec: ',decstr) # Return the skypos as a tuple (x,y) return xsky,ysky def SkytoXY(self, skypos, verbose=no, hour=no): """ This method applies the model to an RA/Dec and calculates the pixel position. RA and Dec need to be in decimal form! This needs to be expanded to include full distortion model as well, i.e. inverse distortion solution. """ x,y = self.wcs.rd2xy(skypos,hour=hour) if verbose: print('X = ',x,' Y = ',y) # Return the pixel position as a tuple (x,y) # return pos return x,y def calcNewCorners(self): """ This method will compute a new shape based on the positions of the corners AFTER applying the geometry model. These new position for each corner should be calculated by calling self.geometry.apply() on each corner position. This should also take into account the output scale as well. Values for the corners must go from 0, not 1, since it is a Python array. WJH, 17-Mar-2005 """ corners = np.zeros(shape=(4,2),dtype=np.float64) xin = [0] * 4 yin = [0] * 4 xin[0]=0. xin[1]=0. xin[2]=self.wcs.naxis1 xin[3]=self.wcs.naxis1 yin[0]=0. yin[1]=self.wcs.naxis2 yin[2]=self.wcs.naxis2 yin[3]=0. corners[:,0] = xin corners[:,1] = yin corners[:,0],corners[:,1] = self.apply(corners) corners += (self.model.refpix['XDELTA'],self.model.refpix['YDELTA']) return corners
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,340
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/traits102/tkmenu.py
#=============================================================================== # # Dynamically construct Tkinter Menus from a supplied string string # description of the menu. # # Written By: David C. Morrill # # Date: 10/15/2002 # # Version: 0.1 # # (c) Copyright 2002 by Enthought, Inc. # #=============================================================================== # # Menu Description Syntax: # # submenu_label {help_string} # menuitem_label | accelerator {help_string} [~/-name]: code # - # # where: # submenu_label = Label of a sub menu # menuitem_label = Label of a menu item # help_string = Help string to display on the status line (optional) # accelerator = Accelerator key (e.g. Ctrl-C) (| and key are optional) # [~] = Menu item checkable, but not checked initially (optional) # [/] = Menu item checkable, and checked initially (optional) # [-] = Menu item disabled initially (optional) # [name] = Symbolic name used to refer to menu item (optional) # code = Python code invoked when menu item is selected # #=============================================================================== #=============================================================================== # Imports: #=============================================================================== from __future__ import division, print_function # confidence high import re import sys PY3K = sys.version_info[0] >= 3 if PY3K: import Tkinter as tk else: import tkinter as tk if PY3K: import builtins exec_ = getattr(builtins, "exec") else: def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" if _globs_ is None: frame = sys._getframe(1) _globs_ = frame.f_globals if _locs_ is None: _locs_ = frame.f_locals del frame elif _locs_ is None: _locs_ = _globs_ exec("exec _code_ in _globs_, _locs_") #=============================================================================== # Constants: #=============================================================================== TRUE = 1 FALSE = 0 DEBUG = TRUE help_pat = re.compile( r'(.*){(.*)}(.*)' ) options_pat = re.compile( r'(.*)\[(.*)\](.*)' ) #=============================================================================== # 'MakeMenu' class: #=============================================================================== class MakeMenu: def __init__ ( self, desc, owner, popup = FALSE, window = None ): self.owner = owner if window is None: window = owner self.window = window self.desc = desc.split( '\n' ) self.index = 0 self.menus = [] if popup: self.menu = menu = tk.Menu( window, tearoff = FALSE ) self.parse( menu, -1 ) else: self.menubar = tk.Frame( window, relief = tk.RAISED, borderwidth = 1 ) self.parse( None, -1 ) self.menubar.tk_menuBar( *self.menus ) #============================================================================ # Recursively parse menu items from the description: #============================================================================ def parse ( self, menu, indent ): cur_id = 0 while TRUE: # Make sure we have not reached the end of the menu description yet: if self.index >= len( self.desc ): return # Get the next menu description line and check its indentation: dline = self.desc[ self.index ] line = dline.lstrip() indented = len( dline ) - len( line ) if indented <= indent: return # Indicate that the current line has been processed: self.index += 1 # Check for a blank or comment line: if (line == '') or (line[0:1] == '#'): continue # Check for a menu separator: if line[0:1] == '-': menu.add_separator() cur_id += 1 continue # Extract the help string (if any): help = '' match = help_pat.search( line ) if match: help = ' ' + match.group(2).strip() line = match.group(1) + match.group(3) # Check for a menu item: col = line.find( ':' ) if col >= 0: handler = line[ col + 1: ].strip() if handler != '': try: exec('def handler(event=None,self=self.owner):\n %s\n' % handler) except: handler = null_handler else: try: exec_('def handler(event=None,self=self.owner):\n%s\n' % (self.get_body(indented), ), _globs_=globals()) except: handler = null_handler not_checked = checked = disabled = FALSE line = line[ : col ] match = options_pat.search( line ) if match: line = match.group(1) + match.group(3) not_checked, checked, disabled, name = option_check( '~/-', match.group(2).strip() ) check_var = None if not_checked or checked: check_var = tk.IntVar() check_var.set( checked ) if name != '': setattr( self.owner, name, MakeMenuItem( menu, cur_id, check_var ) ) label = line.strip().replace( '&', '' ) col = label.find( '|' ) if col >= 0: key_name = label[ col + 1: ].strip() label = label[ : col ].strip() self.window.bind( self.binding_for( key_name ), handler ) if checked or not_checked: menu.add_checkbutton( label = label, command = handler, variable = check_var ) else: menu.add_command( label = label, command = handler ) if col >= 0: menu.entryconfig( cur_id, accelerator = key_name ) if disabled: menu.entryconfig( cur_id, state = tk.DISABLED ) cur_id += 1 continue # Else must be the start of a sub menu: label = line.strip().replace( '&', '' ) if menu is None: menubar = tk.Menubutton( self.menubar, text = label ) self.menus.append( menubar ) menubar.pack( side = tk.LEFT ) menubar[ 'menu' ] = submenu = tk.Menu( menubar, tearoff = FALSE ) else: submenu = tk.Menu( menu, tearoff = FALSE ) menu.add_cascade( label = label, menu = submenu ) # Recursively parse the sub-menu: self.parse( submenu, indented ) cur_id += 1 #============================================================================ # Return the body of an inline method: #============================================================================ def get_body ( self, indent ): result = [] while self.index < len( self.desc ): line = self.desc[ self.index ] if (len( line ) - len( line.lstrip() )) <= indent: break result.append( line ) self.index += 1 result = '\n'.join( result ).rstrip() if result != '': return result return ' pass' #---------------------------------------------------------------------------- # Return the correct Tk binding for a specified key: #---------------------------------------------------------------------------- def binding_for ( self, key_name ): key_name = key_name.replace( 'Ctrl-', 'Control-' ) if key_name[-2:-1] == '-': key_name = key_name[:-1] + key_name[-1].lower() return '<%s>' % key_name #=============================================================================== # 'MakeMenuItem' class: #=============================================================================== class MakeMenuItem: def __init__ ( self, menu, id, var ): self.menu = menu self.id = id self.var = var def checked ( self, check = None ): if check is not None: self.var.set( check ) return check return self.var.get() def toggle ( self ): checked = not self.checked() self.checked( checked ) return checked def enabled ( self, enable = None ): if enable is not None: self.menu.entryconfig( self.id, state = ( tk.DISABLED, tk.NORMAL )[ enable ] ) return enable return (self.menu.entrycget( self.id, 'state' ) == tk.NORMAL) def label ( self, label = None ): if label is not None: self.menu.entryconfig( self.id, label = label ) return label return self.menu.entrycget( self.id, 'label' ) #=============================================================================== # Determine whether a string contains any specified option characters, and # remove them if it does: #=============================================================================== def option_check ( test, str ): result = [] for char in test: col = str.find( char ) result.append( col >= 0 ) if col >= 0: str = str[ : col ] + str[ col + 1: ] return result + [ str.strip() ] #=============================================================================== # Null menu option selection handler: #=============================================================================== def null_handler ( event ): print('null_handler invoked') pass
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,341
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/traits102/trait_errors.py
#------------------------------------------------------------------------------- # # Define the standard exceptions issued by traits. # # Written by: David C. Morrill # # Date: 06/21/2002 # # Refactored into a separate module: 07/04/2003 # # (c) Copyright 2002, 2003 by Enthought, Inc. # #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- # Imports: #------------------------------------------------------------------------------- from __future__ import absolute_import, division # confidence high from .trait_base import class_of #------------------------------------------------------------------------------- # 'TraitError' class: #------------------------------------------------------------------------------- class TraitError ( Exception ): def __init__ ( self, args = None, name = None, info = None, value = None ): if name is None: self.args = args else: # Save the information, in case the 'args' object is not the correct # one, and we need to regenerate the message later: self.name = name self.info = info self.value = value self.desc = None self.prefix = 'The' self.set_desc( None, args ) def set_desc ( self, desc, object = None ): if hasattr( self, 'desc' ): if desc is not None: self.desc = desc if object is not None: self.object = object self.set_args() def set_prefix ( self, prefix ): if hasattr( self, 'prefix' ): self.prefix = prefix self.set_args() def set_args ( self ): if self.desc is None: extra = '' else: extra = ' specifies %s and' % self.desc self.args = ( "%s '%s' trait of %s instance%s must be %s, " "but a value of %s was specified." % ( self.prefix, self.name, class_of( self.object ), extra, self.info, self.value ) ) #------------------------------------------------------------------------------- # 'DelegationError' class: #------------------------------------------------------------------------------- class DelegationError ( TraitError ): def __init__ ( self, args ): self.args = args
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,342
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/traits102/trait_base.py
#------------------------------------------------------------------------------- # # Define common, low-level capabilities needed by the 'traits' package. # # Written by: David C. Morrill # # Date: 06/21/2002 # # Refactored into a separate module: 07/04/2003 # # Symbols defined: SequenceTypes # Undefined # trait_editors # class_of # # (c) Copyright 2002, 2003 by Enthought, Inc. # #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- # Imports: #------------------------------------------------------------------------------- from __future__ import division # confidence high import sys if sys.version_info[0] >= 3: PY2 = False long = int unicode = str else: PY2 = True #------------------------------------------------------------------------------- # Constants: #------------------------------------------------------------------------------- SequenceTypes = ( list, tuple ) TraitNotifier = '__trait_notifier__' #------------------------------------------------------------------------------- # 'UndefinedObject' class: #------------------------------------------------------------------------------- class UndefinedObject: def __repr__ ( self ): return '<undefined>' #------------------------------------------------------------------------------- # 'SelfObject' class: #------------------------------------------------------------------------------- class SelfObject: def __repr__ ( self ): return '<self>' #------------------------------------------------------------------------------- # Create singleton-like instances (so users don't have to): #------------------------------------------------------------------------------- Undefined = UndefinedObject() # Undefined trait name and/or value Self = SelfObject() # Global object reference to current 'object' #------------------------------------------------------------------------------- # Define a special 'string' coercion function: #------------------------------------------------------------------------------- def strx ( arg ): if type( arg ) in StringTypes: return str( arg ) raise TypeError #------------------------------------------------------------------------------- # Define a special 'unicode' string coercion function: #------------------------------------------------------------------------------- def unicodex ( arg ): if type( arg ) in StringTypes: return unicode( arg ) raise TypeError #------------------------------------------------------------------------------- # Define a special 'int' coercion function: #------------------------------------------------------------------------------- def intx ( arg ): try: return int( arg ) except: try: return int( float( arg ) ) except: return int( long( arg ) ) #------------------------------------------------------------------------------- # Define a special 'long' coercion function: #------------------------------------------------------------------------------- def longx ( arg ): try: return long( arg ) except: return long( float( arg ) ) #------------------------------------------------------------------------------- # Define a special 'float' coercion function: #------------------------------------------------------------------------------- def floatx ( arg ): try: return float( arg ) except: return float( long( arg ) ) #------------------------------------------------------------------------------- # Define a special 'complex' coercion function: #------------------------------------------------------------------------------- def complexx ( arg ): try: return complex( arg ) except: return complex( long( arg ) ) #------------------------------------------------------------------------------- # Define a special 'boolean' coercion function: #------------------------------------------------------------------------------- def booleanx ( arg ): if arg: return True return False #------------------------------------------------------------------------------- # Constants: #------------------------------------------------------------------------------- NumericFuncs = { int: ( intx, 'an integer' ), float: ( floatx, 'a floating point number' ) } if PY2: NumericFuncs[long] = ( longx, 'a long integer' ) StringTypes = ( str, unicode, int, long, float, complex ) else: StringTypes = ( str, int, float, complex ) #------------------------------------------------------------------------------- # Define a mapping from types to coercion functions: #------------------------------------------------------------------------------- CoercableFuncs = { int: intx, float: floatx, str: strx, bool: booleanx, complex: complexx } if PY2: CoercableFuncs[long] = longx CoercableFuncs[unicode] = unicodex #------------------------------------------------------------------------------- # Return the module defining the set of trait editors we should use: #------------------------------------------------------------------------------- trait_editors_module = None trait_editors_module_name = None def trait_editors ( module_name = None ): global trait_editors_module, trait_editors_module_name if module_name is not None: if module_name != trait_editors_module_name: trait_editors_module_name = module_name trait_editors_module = None return # Determine actual module name for traits package traits_prefix = 'enthought.traits' for key in sys.modules.keys(): if key.find('.traits') > -1: traits_prefix = key if trait_editors_module is None: if trait_editors_module_name is None: try: __import__( 'wxPython' ) trait_editors_module_name = traits_prefix[:-6]+'wxtrait_sheet' except ImportError: try: __import__( 'Tkinter' ) trait_editors_module_name = traits_prefix[:-6]+'tktrait_sheet' except ImportError: return None try: trait_editors_module = sys.modules[ trait_editors_module_name ] except: try: trait_editors_module = __import__( trait_editors_module_name ) for item in trait_editors_module_name.split( '.' )[1:]: trait_editors_module = getattr( trait_editors_module, item ) except ImportError: trait_editors_module = None return trait_editors_module #------------------------------------------------------------------------------- # Return a string containing the class name of an object with the correct # article (a or an) preceding it (e.g. 'an Image', 'a PlotValue'): #------------------------------------------------------------------------------- def class_of ( object ): if type( object ) is str: name = object else: name = object.__class__.__name__ if name[:1].lower() in 'aeiou': return 'an ' + name return 'a ' + name
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,343
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/exposure.py
# Author: Warren Hack # Program: exposure.py # Purpose: # This class will provide the basic functionality for keeping # track of an exposure's parameters, including distortion model, # WCS information, and metachip shape. # # Version: # 0.1.0 -- Created -- Warren Hack # 0.1.1 -- DGEOFILE logic set to work with N/A as input # # 0.1.2 -- Removed diagnostic print statements related to # the use of DGEO files. -- CJH # 0.1.3 -- Removed expansion of DGEOFILE path to avoid reporting # pipeline directories in output drizzle keywords. -- WJH # 0.1.4 -- Implemented support for providing subarray sections # of DGEOFILEs for subarray exposures. # from __future__ import absolute_import, division, print_function # confidence medium import os from . import buildmask from . import drutil from . import arrdriz from .obsgeometry import ObsGeometry from stsci.tools import fileutil, wcsutil from math import ceil,floor import numpy as np yes = True # 1 no = False # 0 __version__ = '0.1.4' ################# # # # Exposure Classes # # ################# class Exposure: """ This class will provide the basic functionality for keeping track of an exposure's parameters, including distortion model, WCS information, and metachip shape. """ def __init__(self,expname, handle=None, dqname=None, idckey=None, new=no,wcs=None,mask=None,pa_key=None, parity=None, idcdir=None, rot=None, extver=1, exptime=None, ref_pscale=1.0, binned=1, mt_wcs=None, group_indx = None): # This name should be formatted for use in image I/O self.name = fileutil.osfn(expname) # osfn() will expand '.' unnecessarily, potentially # creating a string-length problem for 'drizzle', which # is limited to strings of 80 chars. _path,_name = os.path.split(self.name) # if path for this filename is the same as the current dir, # then there is no need to pass along the path. if _path == os.getcwd(): self.name = _name # Keep track of any associated mask file created for # this exposure from its DQ file, or other mask file. _fname,_extn = fileutil.parseFilename(expname) _open = False # Make sure we have an open file handle to use for getting the # header and data arrays. if not handle and not new: handle = fileutil.openImage(expname) _open = True # If no extension was specified, try to interrogate the file # to find whether the SCI array is in the Primary # (as in Simple FITS) or first extension (as in MEF). if handle and _extn == None: if handle[0].data == None: # Primary extension specified and no data present. # Try looking for data in next extension. if len(handle) > 1 and handle[1].data != None: _extn = 1 expname += '[1]' else: raise IOError("No valid image data in %s.\n"%expname) else: _extn = 0 self.dgeoname = None self.xgeoim = "" self.ygeoim = "" self.exptime = exptime self.group_indx = group_indx if not new: # Read in a copy of the header for this exposure/group/extension _header = fileutil.getHeader(expname,handle=handle) _chip = drutil.getChipId(_header) self.chip = str(_chip) # Keep track of any distortion correction images provided # for this chip self.dgeoname = fileutil.getKeyword(expname,'DGEOFILE',handle=handle) self.xgeoim,self.ygeoim = self.getDGEOExtn() if self.exptime == None: self.exptime = float(_header['EXPTIME']) if self.exptime == 0.: self.exptime = 1.0 # # Extract photometric transformation keywords # If they do not exist, use default values of 0 and 1 # self.plam = float(fileutil.getKeyword(expname,'PHOTPLAM',handle=handle)) / 10. if self.plam == None: # Setup a default value in case this keyword does not exist self.plam = 555. self.photzpt = float(fileutil.getKeyword(expname,'PHOTZPT',handle=handle)) if self.photzpt == None: self.photzpt = 0.0 self.photflam = float(fileutil.getKeyword(expname,'PHOTFLAM',handle=handle)) if self.photflam == None: self.photflam = 1.0 # Read in date-obs from primary header if _header: if 'date-obs' in _header: self.dateobs = _header['date-obs'] elif 'date_obs' in _header: self.dateobs = _header['date_obs'] else: self.dateobs = None else: self.dateobs = None # Initialize the value of BUNIT based on the header information, if # the header has the keyword if 'BUNIT' in _header and _header['BUNIT'].find('ergs') < 0: self.bunit = _header['BUNIT'] else: self.bunit = 'ELECTRONS' else: _chip = 1 _header = None self.chip = str(_chip) # Set a default value for pivot wavelength self.plam = 555. self.photzpt = 0.0 self.photflam = 1.0 self.dateobs = None if self.exptime == None: self.exptime = 1. self.parity = parity self.header = _header self.extver = extver # Create a pointer to the mask file's data array # and the name of the original input DQ file self.maskname = None self.singlemaskname = None self.masklist = None if mask != None: # Specifies filenames to be used if created. self.maskname = mask[0] self.singlemaskname = mask[1] self.masklist = mask[2] self.dqname = dqname # Remember the name of the coeffs file generated for this chip self.coeffs = self.buildCoeffsName() # Read the name of idcfile from image header if not explicitly # provided by user. if idckey != None and idckey.lower() != 'wcs': _indx = expname.find('[') if _indx > -1: _idc_fname = expname[:_indx]+'[0]' else: _idc_fname = expname+'[0]' idcfile, idctype = drutil.getIDCFile(self.header,keyword=idckey, directory=idcdir) else: idcfile = None idctype = None if (idckey != None) and (idckey.lower() == 'header'): idckey = idctype # Get distortion model and WCS info. self.geometry = ObsGeometry(expname, idcfile, idckey=idckey, chip=_chip, new=new, header=self.header, pa_key=pa_key, rot=rot, date=self.dateobs, ref_pscale=ref_pscale, binned=binned, mt_wcs=mt_wcs) # Remember the name and type of the IDC file used... self.idcfile = idcfile self.idctype = idctype # Remember the names of the filters used for the exposure self.filters = self.geometry.filter1+','+self.geometry.filter2 # Define shape here... # nx,ny,pixel scale # if wcs != None: # We have been passed a WCS to use self.geometry.wcs = wcs self.geometry.model.pscale = wcs.pscale if expname != None: self.geometry.wcs.rootname = expname self.naxis1 = self.geometry.wcs.naxis1 self.naxis2 = self.geometry.wcs.naxis2 self.pscale = self.geometry.wcs.pscale self.shape = (self.naxis1,self.naxis2,self.pscale) # Keep track of the positions of the corners of the exposure # both for the RAW image and the # distortion-corrected, unscaled, unrotated image self.corners = {'raw':np.zeros((4,2),dtype=np.float64),'corrected':np.zeros((4,2),dtype=np.float64)} self.setCorners() # Generate BLOT output name specific to this Exposure _blot_extn = '_sci'+repr(extver)+'_blt.fits' self.outblot = fileutil.buildNewRootname(self.name,extn=_blot_extn) # Keep track of undistorted frame's position relative to metachip # Zero-point offset for chip relative to meta-chip product # These values get computed using 'setSingleOffsets' from 'writeCoeffs' # to insure that the final XDELTA/YDELTA values have been computed. self.product_wcs = self.geometry.wcslin self.xzero = 0. self.yzero = 0. self.chip_shape = (0.,0.) self.xsh2 = 0. self.ysh2 = 0. if _open: handle.close() del handle def set_bunit(self,value=None): """Sets the value of bunit to user specified value, if one is provided. """ if value is not None and self.bunit is not None: self.bunit = value def setCorners(self): """ Initializes corners for the raw image. """ self.corners['raw'] = np.array([(1.,1.),(1.,self.naxis2),(self.naxis1,1.),(self.naxis1,self.naxis2)],dtype=np.float64) def setSingleOffsets(self): """ Computes the zero-point offset and shape of undistorted single chip relative to the full final output product metachip. """ _wcs = self.geometry.wcs _corners = np.array([(1.,1.),(1.,_wcs.naxis2),(_wcs.naxis1,1.),(_wcs.naxis1,_wcs.naxis2)],dtype=np.int64) _wc = self.geometry.wtraxy(_corners,self.product_wcs) _xrange = (_wc[:,0].min(),_wc[:,0].max()) _yrange = (_wc[:,1].min(),_wc[:,1].max()) self.xzero = int(_xrange[0] - 1) self.yzero = int(_yrange[0] - 1) if self.xzero < 0: self.xzero = 0 if self.yzero < 0: self.yzero = 0 _out_naxis1 = int(ceil(_xrange[1]) - floor(_xrange[0])) _out_naxis2 = int(ceil(_yrange[1]) - floor(_yrange[0])) _max_x = _out_naxis1 + self.xzero _max_y = _out_naxis2 + self.yzero if _max_x > self.product_wcs.naxis1: _out_naxis1 -= (_max_x - self.product_wcs.naxis1) if _max_y > self.product_wcs.naxis2: _out_naxis2 -= (_max_y - self.product_wcs.naxis2) self.chip_shape = (_out_naxis1,_out_naxis2) self.xsh2 = int(ceil((self.product_wcs.naxis1 - _out_naxis1)/2.)) - self.xzero self.ysh2 = int(ceil((self.product_wcs.naxis2 - _out_naxis2)/2.)) - self.yzero def getShape(self): """ This method gets the shape after opening and reading the input image. This version will be the default way of doing this, but each instrument may override this method with one specific to their data format. """ return self.shape def setShape(self,size,pscale): """ This method will set the shape for a new file if there is no image header information. Size will be defined as (nx,ny) and pixel size """ self.shape = (size[0],size[1],pscale) def buildCoeffsName(self): """ Define the name of the coeffs file used for this chip. """ indx = self.name.rfind('.') return self.name[:indx]+'_coeffs'+self.chip+'.dat' def writeCoeffs(self): """ Write out coeffs file for this chip. """ # Pass along the reference position assumed by Drizzle # based on 'align=center' according to the conventions # described in the help page for 'drizzle'. 26Mar03 WJH # # coord for image array reference pixel in full chip coords # if 'empty_model' not in self.geometry.model.refpix: _xref = self.geometry.wcs.chip_xref _yref = self.geometry.wcs.chip_yref else: _xref = None _yref = None # If we have a subarray, pass along the offset reference position _delta = not (self.geometry.wcslin.subarray) # Set up the idcfile for use by 'drizzle' self.geometry.model.convert(self.coeffs,xref=_xref,yref=_yref,delta=_delta) # set exposure zero-point, now that all values are computed... self.setSingleOffsets() def getDGEOExtn(self): """ Builds filename with extension to access distortion correction image extension appropriate to each chip. """ # If no DGEOFILE has been given, then simply return blanks # and 'drizzle' will not use any. if not self.dgeoname or self.dgeoname == 'N/A': return '','' # Open file for introspection. fimg = fileutil.openImage(self.dgeoname) dx_extver = None dy_extver = None # Find which extensions match this chip ID # We need to identify both a DX and DY EXTNAME extension for hdu in fimg: hdr = hdu.header if 'CCDCHIP' not in hdr: _chip = 1 else: _chip = int(hdr['CCDCHIP']) if 'EXTNAME' in hdr: _extname = hdr['EXTNAME'].lower() if _chip == int(self.chip): if _extname == 'dx': dx_extver = hdr['EXTVER'] if _extname == 'dy': dy_extver = hdr['EXTVER'] fimg.close() del fimg # Set the name for each extension here... _dxgeo = self.dgeoname+'[DX,'+str(dx_extver)+']' _dygeo = self.dgeoname+'[DY,'+str(dy_extver)+']' return _dxgeo,_dygeo def getDGEOArrays(self): """ Return numpy objects for the distortion correction image arrays. If no DGEOFILE is specified, it will return empty 2x2 arrays. """ # Instantiate array objects for distortion correction image arrays if self.xgeoim == '': # No distortion image specified. # Defaulting to empty 2x2 array. xgdim = ygdim = 2 _pxg = np.zeros((ygdim,xgdim),dtype=np.float32) _pyg = np.zeros((ygdim,xgdim),dtype=np.float32) else: # Open distortion correction FITS file _xgfile = fileutil.openImage(self.xgeoim) #_xgfile.info() # Access the extensions which correspond to this Exposure _xgname,_xgext = fileutil.parseFilename(self.xgeoim) _ygname,_ygext = fileutil.parseFilename(self.ygeoim) _pxgext = fileutil.getExtn(_xgfile,extn=_xgext) _pygext = fileutil.getExtn(_xgfile,extn=_ygext) # Copy out the numpy objects for output _ltv1 = int(self.geometry.wcs.offset_x) _ltv2 = int(self.geometry.wcs.offset_y) if _ltv1 != 0. or _ltv2 != 0.: # subarray section only _pxg = _pxgext.data[_ltv2:_ltv2+self.naxis2,_ltv1:_ltv1+self.naxis1].copy() _pyg = _pygext.data[_ltv2:_ltv2+self.naxis2,_ltv1:_ltv1+self.naxis1].copy() else: # full array _pxg = _pxgext.data.copy() _pyg = _pygext.data.copy() # Close file handles now... _xgfile.close() del _xgfile return _pxg,_pyg def applyDeltaWCS(self,dcrval=None,dcrpix=None,drot=None,dscale=None): """ Apply shifts to the WCS of this exposure. Shifts are always relative to the current value and in the same reference frame. """ in_wcs = self.geometry.wcs in_wcslin = self.geometry.wcslin if dcrpix: _crval = in_wcs.xy2rd((in_wcs.crpix1-dcrpix[0],in_wcs.crpix2-dcrpix[1])) elif dcrval: _crval = (in_wcs.crval1 - dcrval[0],in_wcs.crval2 - dcrval[1]) else: _crval = None _orient = None _scale = None if drot: _orient = in_wcs.orient + drot if dscale: _scale = in_wcs.pscale * dscale _crpix = (in_wcs.crpix1,in_wcs.crpix2) in_wcs.updateWCS(pixel_scale=_scale,orient=_orient,refval=_crval,refpos=_crpix) in_wcslin.updateWCS(pixel_scale=_scale,orient=_orient,refval=_crval,refpos=_crpix) def calcNewEdges(self,pscale=None): """ This method will compute arrays for all the pixels around the edge of an image AFTER applying the geometry model. Parameter: delta - offset from nominal crpix center position Output: xsides - array which contains the new positions for all pixels along the LEFT and RIGHT edges ysides - array which contains the new positions for all pixels along the TOP and BOTTOM edges The new position for each pixel is calculated by calling self.geometry.apply() on each position. """ # build up arrays for pixel positions for the edges # These arrays need to be: array([(x,y),(x1,y1),...]) numpix = self.naxis1*2 + self.naxis2 * 2 border = np.zeros(shape=(numpix,2),dtype=np.float64) # Now determine the appropriate values for this array # We also need to account for any subarray offsets xmin = 1. xmax = self.naxis1 ymin = 1. ymax = self.naxis2 # Build range of pixel values for each side # Add 1 to make them consistent with pixel numbering in IRAF # Also include the LTV offsets to represent position in full chip # since the model works relative to full chip positions. xside = np.arange(self.naxis1) + xmin yside = np.arange(self.naxis2) + ymin #Now apply them to the array to generate the appropriate tuples #bottom _range0 = 0 _range1 = self.naxis1 border[_range0:_range1,0] = xside border[_range0:_range1,1] = ymin #top _range0 = _range1 _range1 = _range0 + self.naxis1 border[_range0:_range1,0] = xside border[_range0:_range1,1] = ymax #left _range0 = _range1 _range1 = _range0 + self.naxis2 border[_range0:_range1,0] = xmin border[_range0:_range1,1] = yside #right _range0 = _range1 _range1 = _range0 + self.naxis2 border[_range0:_range1,0] = xmax border[_range0:_range1,1] = yside # calculate new edge positions border[:,0],border[:,1] = self.geometry.apply(border,pscale=pscale) #print 'Calculated corrected border positions at ',_ptime() #Now apply any chip-to-chip offset from REFPIX _refpix = self.geometry.model.refpix if _refpix != None: _ratio = pscale / _refpix['PSCALE'] _delta = (_refpix['XDELTA']/_ratio, _refpix['YDELTA']/_ratio) else: _delta = (0.,0.) return border + _delta def getWCS(self): return self.geometry.wcs def showWCS(self): print(self.geometry.wcs) def runDriz(self,pixfrac=1.0,kernel='turbo',fillval='INDEF'): """ Runs the 'drizzle' algorithm on this specific chip to create a numpy object of the undistorted image. The resulting drizzled image gets returned as a numpy object. """ # # Perform drizzling... # _wcs = self.geometry.wcs _wcsout = self.product_wcs # Rigorously compute the orientation changes from WCS # information using algorithm provided by R. Hook from WDRIZZLE. abxt,cdyt = drutil.wcsfit(self.geometry, self.product_wcs) # Compute the rotation and shifts between input and reference WCS. xsh = abxt[2] ysh = cdyt[2] rot = fileutil.RADTODEG(np.arctan2(abxt[1],cdyt[0])) scale = self.product_wcs.pscale / self.geometry.wcslin.pscale # Now, trim the final output to only match this chip _out_naxis1,_out_naxis2 = self.chip_shape # # Insure that the coeffs file was created # if not os.path.exists(self.coeffs): self.writeCoeffs() # A image buffer needs to be setup for converting the input # arrays (sci and wht) from FITS format to native format # with respect to byteorder and byteswapping. # This buffer should be reused for each input. # _outsci = np.zeros((_out_naxis2,_out_naxis1),dtype=np.float32) _outwht = np.zeros((_out_naxis2,_out_naxis1),dtype=np.float32) _inwcs = np.zeros([8],dtype=np.float64) # Only one chip will ever be drizzled using this method, so # the context image will only ever contain 1 bit-plane _outctx = np.zeros((_out_naxis2,_out_naxis1),dtype=np.int32) # Read in the distortion correction arrays, if specifij8cw08n4q_raw.fitsed _pxg,_pyg = self.getDGEOArrays() # Open the SCI image _expname = self.name _handle = fileutil.openImage(_expname,mode='readonly',memmap=0) _fname,_extn = fileutil.parseFilename(_expname) _sciext = fileutil.getExtn(_handle,extn=_extn) # Make a local copy of SCI array and WCS info #_insci = _sciext.data.copy() _inwcs = drutil.convertWCS(wcsutil.WCSObject(_fname,header=_sciext.header),_inwcs) # Compute what plane of the context image this input would # correspond to: _planeid = 1 # Select which mask needs to be read in for drizzling _inwht = np.ones((self.naxis2,self.naxis1),dtype=np.float32) # Default case: wt_scl = exptime _wtscl = self.exptime # Set additional parameters needed by 'drizzle' _expin = self.exptime #_in_un = 'counts' #_shift_fr = 'output' #_shift_un = 'output' _uniqid = 1 ystart = 0 nmiss = 0 nskip = 0 _vers = '' # # This call to 'arrdriz.tdriz' uses the F2C syntax # _dny = self.naxis2 # Call 'drizzle' to perform image combination _vers,nmiss,nskip = arrdriz.tdriz(_sciext.data.copy(),_inwht, _outsci, _outwht, _outctx, _uniqid, ystart, 1, 1, _dny, xsh,ysh, 'output','output', rot,scale, self.xsh2,self.ysh2, 1.0, 1.0, 0.0, 'output', _pxg,_pyg, 'center', pixfrac, kernel, self.coeffs, 'counts', _expin,_wtscl, fillval, _inwcs, nmiss, nskip, 1,0.,0.) # # End of F2C syntax # if nmiss > 0: print('! Warning, ',nmiss,' points were outside the output image.') if nskip > 0: print('! Note, ',nskip,' input lines were skipped completely.') # Close image handle _handle.close() del _handle,_fname,_extn,_sciext del _inwht del _pxg,_pyg del _outwht,_outctx return _outsci
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,344
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/traits102/wxtrait_sheet.py
#------------------------------------------------------------------------------- # # Define a wxPython based trait sheet mechanism for visually editing the # values of traits. # # Written by: David C. Morrill # # Date: 07/10/2002 # # (c) Copyright 2002 by Enthought, Inc. # #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- # Imports: #------------------------------------------------------------------------------- from __future__ import absolute_import, division # confidence medium import sys import os.path import re from string import ascii_lowercase from wxPython import wx from wxmenu import MakeMenu from .traits import Trait, HasTraits, TraitError, HasDynamicTraits, \ trait_editors from .trait_sheet import TraitEditor, TraitSheetHandler, TraitMonitor, \ TraitGroup, TraitGroupList, default_trait_sheet_handler from types import ModuleType from math import log10 if sys.version_info[0] >= 3: from functools import reduce #------------------------------------------------------------------------------- # Module initialization: #------------------------------------------------------------------------------- trait_editors( __name__ ) #------------------------------------------------------------------------------- # Constants: #------------------------------------------------------------------------------- # Basic sequence types: basic_sequence_types = [ list, tuple ] # Standard width of an image bitmap: standard_bitmap_width = 120 # Standard color samples: color_choices = ( 0, 128, 192, 255 ) color_samples = [ None ] * 48 i = 0 for r in color_choices: for g in color_choices: for b in ( 0, 128, 255 ): color_samples[i] = wx.wxColour( r, g, b ) i += 1 # List of available font facenames: facenames = None # Standard font point sizes: point_sizes = [ '8', '9', '10', '11', '12', '14', '16', '18', '20', '22', '24', '26', '28', '36', '48', '72' ] # Global switch governing whether or not tooltips are displayed in trait # sheet dialogs: tooltips_enabled = True # Pattern of all digits: all_digits = re.compile( r'\d+' ) # Color used to highlight input errors: error_color = wx.wxColour( 255, 192, 192 ) # Width of a scrollbar: scrollbar_dx = wx.wxSystemSettings_GetSystemMetric( wx.wxSYS_VSCROLL_X ) # Screen size: screen_dx = wx.wxSystemSettings_GetSystemMetric( wx.wxSYS_SCREEN_X ) screen_dy = wx.wxSystemSettings_GetSystemMetric( wx.wxSYS_SCREEN_Y ) #------------------------------------------------------------------------------- # Position one window near another: #------------------------------------------------------------------------------- def position_near ( origin, target ): x, y = origin.ClientToScreenXY( 0, 0 ) y -= 30 # Approximate adjustment for window title bar dx, dy = target.GetSizeTuple() if (x + dx) > screen_dx: x = screen_dx - dx if x < 0: x = 0 if (y + dy) > screen_dy: y = screen_dy - dy if y < 0: y = 0 target.SetPosition( wx.wxPoint( x, y ) ) #------------------------------------------------------------------------------- # Initialize an editor control: #------------------------------------------------------------------------------- class Undefined: pass def init_control ( control, object, trait_name, description, handler, original_value = Undefined ): control.object = object control.trait_name = trait_name control.description = description control.handler = handler if original_value is Undefined: control.original_value = getattr( object, trait_name ) else: control.original_value = original_value #------------------------------------------------------------------------------- # 'TraitSheetAppHandler' class: #------------------------------------------------------------------------------- class TraitSheetAppHandler ( TraitSheetHandler ): #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, app ): self.app = app self.modified = False #---------------------------------------------------------------------------- # Notification that a trait sheet has been closed: #---------------------------------------------------------------------------- def close ( self, trait_sheet, object ): rc = True if self.modified: dlg = wx.wxMessageDialog( trait_sheet, 'Changes have been made.\nDiscard changes?', '%s Traits' % object.__class__.__name__ ) result = dlg.ShowModal() dlg.Destroy() rc = (result == wx.wxID_OK) return rc #---------------------------------------------------------------------------- # Notification that a trait sheet has modified a trait of its # associated object: #---------------------------------------------------------------------------- def changed ( self, object, trait_name, new_value, old_value, is_set ): self.modified = True self.save_button.Enable( True ) #---------------------------------------------------------------------------- # Create extra content to add to the trait sheet: #---------------------------------------------------------------------------- def init ( self, trait_sheet, object ): self.sheet = trait_sheet vsizer = wx.wxBoxSizer( wx.wxVERTICAL ) hsizer = wx.wxBoxSizer( wx.wxHORIZONTAL ) vsizer.Add( wx.wxStaticLine( trait_sheet, -1 ), 1, wx.wxEXPAND | wx.wxTOP, 4 ) vsizer.Add( hsizer, 0, wx.wxALIGN_RIGHT ) self.save_button = button = wx.wxButton( trait_sheet, -1, 'Save changes' ) hsizer.Add( button, 0, wx.wxALL, 4 ) wx.EVT_BUTTON( trait_sheet, button.GetId(), self.save ) button.Enable( False ) button = wx.wxButton( trait_sheet, -1, 'Cancel' ) hsizer.Add( button, 0, wx.wxALL, 4 ) wx.EVT_BUTTON( trait_sheet, button.GetId(), trait_sheet.close_page ) return vsizer #---------------------------------------------------------------------------- # Handle the user requesting that all changes to the object be saved: #---------------------------------------------------------------------------- def save ( self, event ): self.modified = False self.app.save_ok = True self.sheet.close_page() #------------------------------------------------------------------------------- # 'TraitSheetApp' class: #------------------------------------------------------------------------------- class TraitSheetApp ( wx.wxApp ): #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, object, traits = None ): self.object = object self.traits = traits self.save_ok = False wx.wxInitAllImageHandlers() wx.wxApp.__init__( self, 1, 'debug.log' ) self.MainLoop() #---------------------------------------------------------------------------- # Handle application initialization: #---------------------------------------------------------------------------- def OnInit ( self ): self.SetTopWindow( TraitSheetDialog( self.object, self.traits, TraitSheetAppHandler( self ) ) ) return True #------------------------------------------------------------------------------- # 'TraitSheetDialog' class: #------------------------------------------------------------------------------- class TraitSheetDialog ( wx.wxDialog ): #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, object, traits = None, handler = default_trait_sheet_handler, parent = None, title = None ): if title is None: title = '%s Traits' % object.__class__.__name__ wx.wxDialog.__init__( self, parent, -1, title ) wx.EVT_CLOSE( self, self.close_page ) wx.EVT_CHAR( self, self.on_key ) self.object = object self.handler = handler # Create the actual trait sheet panel: sizer = wx.wxBoxSizer( wx.wxVERTICAL ) sw = wx.wxScrolledWindow( self ) trait_sheet = TraitSheet( sw, object, traits, handler ) sizer.Add( trait_sheet, 0, wx.wxALL, 4 ) tsdx, tsdy = trait_sheet.GetSizeTuple() tsdx += 8 tsdy += 8 extra = handler.init( self, object ) if extra is not None: sizer.Add( extra, 1, wx.wxEXPAND ) max_dy = (2 * screen_dy) // 3 sw.SetAutoLayout( True ) sw.SetSizer( sizer ) sw.SetSize( wx.wxSize( tsdx + ((tsdy > max_dy) * scrollbar_dx), min( tsdy, max_dy ) ) ) sw.SetScrollRate( 0, 1 ) sw_sizer = wx.wxBoxSizer( wx.wxVERTICAL ) sw_sizer.Add( sw ) sw_sizer.Fit( self ) # Find a nice place on the screen to display the trait sheet so # that it overlays the object as little as possible: if not handler.position( self, object ): if parent is None: self.Centre( wx.wxBOTH ) else: position_near( parent, self ) self.Show( True ) #---------------------------------------------------------------------------- # Close the trait sheet window: #---------------------------------------------------------------------------- def close_page ( self, event = None ): if self.handler.close( self, self.object ): self.Destroy() #---------------------------------------------------------------------------- # Handle the user hitting the 'Esc'ape key: #---------------------------------------------------------------------------- def on_key ( self, event ): if event.GetKeyCode() == 0x1B: self.on_close_page( event ) #------------------------------------------------------------------------------- # 'TraitPanel' class: #------------------------------------------------------------------------------- class TraitPanel ( wx.wxPanel ): #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, parent ): # wx.wxPanel.__init__( self, parent, -1, style = wx.wxSUNKEN_BORDER ) wx.wxPanel.__init__( self, parent, -1 ) self.SetSizer( wx.wxBoxSizer( wx.wxVERTICAL ) ) self._size = None self._need_layout = True #---------------------------------------------------------------------------- # Add a TraitSheet to the panel: #---------------------------------------------------------------------------- def add ( self, sheet ): self.GetSizer().Add( sheet, 0, wx.wxEXPAND ) self._size = None self._need_layout = True #---------------------------------------------------------------------------- # Remove a TraitSheet from the panel: #---------------------------------------------------------------------------- def remove ( self, sheet ): sheet.Destroy() self._size = None self._need_layout = True #---------------------------------------------------------------------------- # Get the size of the panel: #---------------------------------------------------------------------------- def size ( self ): if self._size is None: self._size = self.GetSizer().GetMinSize() return self._size #---------------------------------------------------------------------------- # Set the size and position of the panel: #---------------------------------------------------------------------------- def position ( self, x, y, dx, dy ): self.SetDimensions( x, y, dx, dy ) if self._need_layout: self._need_layout = False self.Layout() #---------------------------------------------------------------------------- # Destroy the panel: #---------------------------------------------------------------------------- def destroy ( self ): self.Destroy() #------------------------------------------------------------------------------- # 'TraitSheet' class: #------------------------------------------------------------------------------- class TraitSheet ( wx.wxPanel ): #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, parent, object, traits = None, handler = default_trait_sheet_handler ): wx.wxPanel.__init__( self, parent, -1 ) self.object = object self.handler = handler # If no traits were specified: if traits is None: # Get them from the specified object: traits = object.editable_traits() # Try to make sure that we now have either a single TraitGroup, or # a list of TraitGroups: kind = type( traits ) if kind is str: # Convert the single trait name into a TraitGroup: traits = TraitGroup( traits, show_border = False, style = 'custom' ) elif ((kind in basic_sequence_types) or isinstance( traits, TraitGroupList )): if len( traits ) == 0: # Empty trait list, leave the panel empty: return if not isinstance( traits[0], TraitGroup ): # Convert a simple list of trait elements into a single, # TraitGroup, possibly containing multiple items: traits = TraitGroup( show_border = False, style = 'custom', *traits ) # Create the requested style of trait sheet editor: if isinstance( traits, TraitGroup ): # Single page dialog: sizer = self.add_page( traits, self ) self.SetAutoLayout( True ) self.SetSizer( sizer ) sizer.Fit( self ) else: # Multi-tab notebook: self.add_tabs( traits ) #---------------------------------------------------------------------------- # Create a tab (i.e. notebook) style trait editor: #---------------------------------------------------------------------------- def add_tabs ( self, traits ): # Create the notebook, add it to the the dialog's sizer: nb = wx.wxNotebook( self, -1 ) nbs = wx.wxNotebookSizer( nb ) count = 0 for pg in traits: # Create the new notebook page and add it to the notebook: panel = wx.wxPanel( nb, -1 ) page_name = pg.label if page_name is None: count += 1 page_name = 'Page %d' % count nb.AddPage( panel, page_name ) sizer = self.add_page( pg, panel ) panel.SetAutoLayout( True ) panel.SetSizer( sizer ) nbs.Fit( nb ) dx, dy = nb.GetSizeTuple() size = wx.wxSize( max( len( traits ) * 54, 260, dx ), dy ) nb.SetSize( size ) self.SetSize( size ) #---------------------------------------------------------------------------- # Create a single trait editor page: #---------------------------------------------------------------------------- def add_page ( self, pg, parent, box = None, default_style = 'simple' ): default_style = pg.style or default_style object = pg.object or self.object if pg.orientation == 'horizontal': rsizer = wx.wxBoxSizer( wx.wxVERTICAL ) if box is not None: psizer = wx.wxStaticBoxSizer( box, wx.wxHORIZONTAL ) else: psizer = wx.wxBoxSizer( wx.wxHORIZONTAL ) rsizer.Add( psizer, 0, wx.wxEXPAND ) elif box is not None: rsizer = psizer = wx.wxStaticBoxSizer( box, wx.wxVERTICAL ) else: rsizer = psizer = wx.wxBoxSizer( wx.wxVERTICAL ) sizer = None show_labels = pg.show_labels_ for pge in pg.values: if isinstance( pge, TraitGroup ): box = None if pge.show_border_: box = wx.wxStaticBox( parent, -1, pge.label or '' ) psizer.Add( self.add_page( pge, parent, box, default_style ), 0, wx.wxEXPAND | wx.wxALL, 2 ) else: if sizer is None: cols = 1 + show_labels sizer = wx.wxFlexGridSizer( 0, cols, 2, 4 ) if show_labels: sizer.AddGrowableCol( 1 ) name = pge.name or ' ' if name == '-': for i in range( cols ): sizer.Add( wx.wxStaticLine( parent, -1 ), 0, wx.wxTOP | wx.wxBOTTOM | wx.wxEXPAND, 2 ) continue if name == ' ': name = '5' if all_digits.match( name ): n = int( name ) for i in range( cols ): sizer.Add( n, n ) continue editor = pge.editor style = pge.style or default_style pge_object = pge.object or object if editor is None: try: editor = pge_object._base_trait( name ).get_editor() except: pass if editor is None: continue label = None if show_labels: label = pge.label_for( object ) self.add_trait( parent, sizer, pge_object, name, label, editor, style ) if sizer is not None: psizer.Add( sizer, 1, wx.wxALL | wx.wxEXPAND, 1 ) if rsizer is not psizer: rsizer.Add( wx.wxPanel( parent, -1 ), 1, wx.wxEXPAND ) return rsizer #---------------------------------------------------------------------------- # Add a trait to the trait sheet: #---------------------------------------------------------------------------- def add_trait ( self, parent, sizer, object, trait_name, description, editor, style ): if description is not None: suffix = ':'[ description[-1:] == '?': ] label = wx.wxStaticText( parent, -1, description + suffix, style = wx.wxALIGN_RIGHT ) sizer.Add( label, 0, wx.wxEXPAND | wx.wxALIGN_CENTER ) desc = object._base_trait( trait_name ).desc if desc is not None: label.SetToolTip( wx.wxToolTip( 'Specifies ' + desc ) ) wx.EVT_RIGHT_UP( label, self.on_toggle_help ) if style == 'custom': control = editor.custom_editor( object, trait_name, description, self.handler, parent ) elif style == 'readonly': control = editor.readonly_editor( object, trait_name, description, self.handler, parent ) else: if style == 'simple': control = editor.simple_editor( object, trait_name, description, self.handler, parent ) else: control = editor.text_editor( object, trait_name, description, self.handler, parent ) wx.EVT_RIGHT_UP( control, editor.on_restore ) init_control( control, object, trait_name, description, self.handler ) sizer.Add( control, 1, editor.layout_style() ) return control #---------------------------------------------------------------------------- # Display a help message to the user indicating the purpose of a trait: #---------------------------------------------------------------------------- def on_toggle_help ( self, event ): global tooltips_enabled tooltips_enabled = not tooltips_enabled wx.wxToolTip_Enable( tooltips_enabled ) #------------------------------------------------------------------------------- # 'wxTraitEditor' class: #------------------------------------------------------------------------------- class wxTraitEditor ( TraitEditor ): #---------------------------------------------------------------------------- # Create an in-place read only view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def readonly_editor ( self, object, trait_name, description, handler, parent ): control = wx.wxTextCtrl( parent, -1, self.str( object, trait_name ), style = wx.wxTE_READONLY ) TraitMonitor( object, trait_name, control, self.on_trait_change_text ) return control #---------------------------------------------------------------------------- # Create an in-place text editable view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def text_editor ( self, object, trait_name, description, handler, parent ): control = wx.wxTextCtrl( parent, -1, self.str( object, trait_name ), style = wx.wxTE_PROCESS_ENTER ) wx.EVT_KILL_FOCUS( control, self.on_text_enter ) wx.EVT_TEXT_ENTER( parent, control.GetId(), self.on_text_enter ) TraitMonitor( object, trait_name, control, self.on_trait_change_text ) return control #---------------------------------------------------------------------------- # Handle the user pressing the 'Enter' key in the edit control: #---------------------------------------------------------------------------- def on_text_enter ( self, event ): control = event.GetEventObject() try: self.set( control.object, control.trait_name, control.GetValue(), control.handler ) return True except TraitError as excp: self.error( control.description, excp, control ) return False #---------------------------------------------------------------------------- # Handle the object trait changing value outside the editor: #---------------------------------------------------------------------------- def on_trait_change_text ( self, control, new ): if not hasattr( control, 'updating' ): new_value = self.str_value( new ) if control.GetValue() != new_value: control.SetValue( new_value ) #---------------------------------------------------------------------------- # Create a static view of the current value of the 'trait_name' # trait of 'object': #---------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): control = wx.wxTextCtrl( parent, -1, self.str( object, trait_name ), style = wx.wxTE_READONLY ) wx.EVT_LEFT_UP( control, self.on_popup ) TraitMonitor( object, trait_name, control, self.on_trait_change_text ) return control #---------------------------------------------------------------------------- # Invoke the pop-up editor for an object trait: #---------------------------------------------------------------------------- def on_popup ( self, event ): self.on_popup_control( event.GetEventObject() ) def on_popup_control ( self, control ): if hasattr( self, 'popup_editor' ): self.popup_editor( control.object, control.trait_name, control.description, control.handler, control ) #---------------------------------------------------------------------------- # Restore the original value of the object's trait: #---------------------------------------------------------------------------- def on_restore ( self, event ): control = event.GetEventObject() object = control.object trait_name = control.trait_name old_value = getattr( object, trait_name ) new_value = control.original_value setattr( object, trait_name, new_value ) control.handler.changed( object, trait_name, new_value, old_value, False ) #---------------------------------------------------------------------------- # Handle a 'TraitError' exception: #---------------------------------------------------------------------------- def error ( self, description, excp, parent ): dlg = wx.wxMessageDialog( parent, str( excp ), description + ' value error', wx.wxOK | wx.wxICON_INFORMATION ) dlg.ShowModal() dlg.Destroy() #---------------------------------------------------------------------------- # Return the layout style for this trait editor's control: #---------------------------------------------------------------------------- def layout_style ( self ): return wx.wxEXPAND #------------------------------------------------------------------------------- # 'TraitEditorInstance' class: #------------------------------------------------------------------------------- class TraitEditorInstance ( wxTraitEditor ): #---------------------------------------------------------------------------- # Create a static view of the current value of the 'trait_name' # trait of 'object': #---------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): value = getattr( object, trait_name ) if value is None: control = wx.wxButton( parent, -1, 'None' ) control.Enable( False ) else: control = wx.wxButton( parent, -1, value.__class__.__name__ ) wx.EVT_BUTTON( parent, control.GetId(), self.on_popup ) TraitMonitor( object, trait_name, control, self.on_trait_change_text ) return control #---------------------------------------------------------------------------- # Invoke the pop-up editor for an object trait: #---------------------------------------------------------------------------- def on_popup_control ( self, control ): object = getattr( control.object, control.trait_name ) if isinstance( object, HasTraits ): traits = object.editable_traits() try: wrap = (not isinstance( traits, TraitGroup )) if wrap: wrap = (not isinstance( traits[0], TraitGroup )) except: wrap = True if wrap: traits = TraitGroup( show_border = False, style = 'simple', *traits ) TraitSheetDialog( object, traits, control.handler, control ) #------------------------------------------------------------------------------- # 'TraitEditorText' class: #------------------------------------------------------------------------------- class TraitEditorText ( wxTraitEditor ): #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, dic = {}, auto_set = True, evaluate = False ): self.dic = dic self.auto_set = auto_set self.evaluate = evaluate #---------------------------------------------------------------------------- # Interactively edit the 'trait_name' text trait of 'object': #---------------------------------------------------------------------------- def popup_editor ( self, object, trait_name, description, handler, parent = None ): while True: dialog = wx.wxTextEntryDialog( parent or object.window, 'Enter the new %s value:' % trait_name, defaultValue = getattr( object, trait_name ) ) if dialog.ShowModal() != wx.wxID_OK: return try: self.set( object, trait_name, self.get_value( dialog ), handler ) return True except TraitError as excp: self.error( description, excp, object.window ) return False #---------------------------------------------------------------------------- # Create an in-place editable view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): control = wx.wxTextCtrl( parent, -1, self.str( object, trait_name ), style = wx.wxTE_PROCESS_ENTER ) wx.EVT_KILL_FOCUS( control, self.on_enter ) wx.EVT_TEXT_ENTER( parent, control.GetId(), self.on_enter ) if self.auto_set: wx.EVT_TEXT( parent, control.GetId(), self.on_key ) TraitMonitor( object, trait_name, control, self.on_trait_change_text ) return control #---------------------------------------------------------------------------- # Handle the user pressing the 'Enter' key in the edit control: #---------------------------------------------------------------------------- def on_enter ( self, event ): control = event.GetEventObject() try: self.set( control.object, control.trait_name, self.get_value( control ), control.handler ) except TraitError as excp: self.error( control.description, excp, control ) #---------------------------------------------------------------------------- # Handle the user changing the contents of the edit control: #---------------------------------------------------------------------------- def on_key ( self, event ): owner = control = event.GetEventObject() control.updating = True if not hasattr( owner, 'object' ): owner = control.GetParent() try: self.set( owner.object, owner.trait_name, self.get_value( control ), owner.handler ) color = wx.wxWHITE except: color = error_color del control.updating control.SetBackgroundColour( color ) control.Refresh() #---------------------------------------------------------------------------- # Get the actual value corresponding to what the user typed: #---------------------------------------------------------------------------- def get_value ( self, control ): value = control.GetValue().strip() if self.evaluate: value = eval( value ) if value not in self.dic: return value return self.dic[ value ] #------------------------------------------------------------------------------- # 'TraitEditorEnum' class: #------------------------------------------------------------------------------- class TraitEditorEnum ( wxTraitEditor ): #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, values, cols = 1 ): self.cols = cols self.mapped = (type( values ) is dict) if self.mapped: sorted = list(values.values()) sorted.sort() col = sorted[0].find( ':' ) + 1 if col > 0: self.sorted = [ x[ col: ] for x in sorted ] for n, v in values.items(): values[n] = v[ col: ] else: self.sorted = sorted self.values = values else: if not type( values ) in basic_sequence_types: handler = values if isinstance( handler, Trait ): handler = handler.setter if hasattr( handler, 'map' ): values = list(handler.map.keys()) values.sort() else: values = handler.values self.values = [ str( x ) for x in values ] #---------------------------------------------------------------------------- # Create an in-place simple view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): control = wx.wxChoice( parent, -1, wx.wxPoint( 0, 0 ), wx.wxSize( 100, 20 ), self.all_values() ) try: control.SetStringSelection( self.current_value( object, trait_name ) ) except: pass wx.EVT_CHOICE( parent, control.GetId(), self.on_value_changed ) TraitMonitor( object, trait_name, control, self.on_trait_change_choice ) return control #---------------------------------------------------------------------------- # Create an in-place custom view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def custom_editor ( self, object, trait_name, description, handler, parent ): # Create a panel to hold all of the radio buttons: panel = wx.wxPanel( parent, -1 ) # Get the current trait value: cur_value = self.current_value( object, trait_name ) # Create a sizer to manage the radio buttons: values = self.all_values() n = len( values ) cols = self.cols rows = (n + cols - 1) // cols incr = [ n // cols ] * cols rem = n % cols for i in range( cols ): incr[i] += (rem > i) incr[-1] = -(reduce( lambda x, y: x + y, incr[:-1], 0 ) - 1) if cols > 1: sizer = wx.wxGridSizer( 0, cols, 2, 4 ) else: sizer = wx.wxBoxSizer( wx.wxVERTICAL ) # Add the set of all possible choices: style = wx.wxRB_GROUP index = 0 for i in range( rows ): for j in range( cols ): if n > 0: value = label = values[ index ] if label[:1] in ascii_lowercase: label = label.capitalize() control = wx.wxRadioButton( panel, -1, label, style = style ) control.value = value style = 0 control.SetValue( value == cur_value ) wx.EVT_RADIOBUTTON( panel, control.GetId(), self.on_click ) index += incr[j] n -= 1 else: control = wx.wxRadioButton( panel, -1, '' ) control.value = '' control.Show( False ) sizer.Add( control, 0, wx.wxNORTH, 5 ) # Set-up the layout: panel.SetAutoLayout( True ) panel.SetSizer( sizer ) sizer.Fit( panel ) if self.mapped: trait_name += '_' TraitMonitor( object, trait_name, panel, self.on_trait_change_radio ) # Return the panel as the result: return panel #---------------------------------------------------------------------------- # Return the set of all possible values: #---------------------------------------------------------------------------- def all_values ( self ): if self.mapped: return self.sorted return self.values #---------------------------------------------------------------------------- # Return the current value of the object trait: #---------------------------------------------------------------------------- def current_value ( self, object, trait_name ): if self.mapped: return self.values[ getattr( object, trait_name + '_' ) ] return str( getattr( object, trait_name ) ) #---------------------------------------------------------------------------- # Handle the user selecting a new value from the combo box: #---------------------------------------------------------------------------- def on_value_changed ( self, event ): control = event.GetEventObject() value = event.GetString() try: value = int( value ) except: pass self.set( control.object, control.trait_name, value, control.handler ) #---------------------------------------------------------------------------- # Handle the user clicking one of the 'custom' radio buttons: #---------------------------------------------------------------------------- def on_click ( self, event ): control = event.GetEventObject() parent = control.GetParent() value = control.value try: value = int( value ) except: pass self.set( parent.object, parent.trait_name, value, parent.handler ) #---------------------------------------------------------------------------- # Handle the object trait changing value outside the editor: #---------------------------------------------------------------------------- def on_trait_change_choice ( self, control, new ): try: control.SetStringSelection( str( new ) ) except: pass def on_trait_change_radio ( self, control, new ): for button in control.GetChildren(): button.SetValue( button.value == new ) #------------------------------------------------------------------------------- # 'TraitEditorImageEnum' class: #------------------------------------------------------------------------------- class TraitEditorImageEnum ( TraitEditorEnum ): #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, values, suffix = '', cols = 1, path = None ): TraitEditorEnum.__init__( self, values ) self.suffix = suffix self.cols = cols if type( path ) is ModuleType: path = os.path.join( os.path.dirname( path.__file__ ), 'images' ) self.path = path #---------------------------------------------------------------------------- # Interactively edit the 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def popup_editor ( self, object, trait_name, description, handler, parent = None ): return TraitEditorImageDialog( object, trait_name, description, parent, handler, self ).ShowModal() #---------------------------------------------------------------------------- # Create an in-place read only view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def readonly_editor ( self, object, trait_name, description, handler, parent ): control = ImageControl( parent, bitmap_cache( self.current_value( object, trait_name ) + self.suffix, False, self.path ) ) #control.SetBackgroundColour( wx.wxWHITE ) TraitMonitor( object, trait_name, control, self.on_trait_change_image ) return control #---------------------------------------------------------------------------- # Create an in-place editable view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): control = self.readonly_editor( object, trait_name, description, handler, parent ) control.Selected( True ) control.Handler( self.on_popup_control ) return control #---------------------------------------------------------------------------- # Create an in-place custom view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def custom_editor ( self, object, trait_name, description, handler, parent ): # Create a panel to hold all of the radio buttons: panel = wx.wxPanel( parent, -1 ) # Add the image buttons to the panel: self.create_image_grid( panel, getattr( object, trait_name ), self.on_click ) # Return the panel as the result: return panel #---------------------------------------------------------------------------- # Populate a specified window with a grid of image buttons: #---------------------------------------------------------------------------- def create_image_grid ( self, parent, cur_value, handler ): # Create the main sizer: if self.cols > 1: sizer = wx.wxGridSizer( 0, self.cols, 0, 0 ) else: sizer = wx.wxBoxSizer( wx.wxVERTICAL ) # Add the set of all possible choices: cur_value = str( cur_value ) for value in self.all_values(): control = ImageControl( parent, bitmap_cache( value + self.suffix, False, self.path ), value == cur_value, handler ) control.value = value sizer.Add( control, 0, wx.wxALL, 2 ) # Finish setting up the control layout: parent.SetAutoLayout( True ) parent.SetSizer( sizer ) sizer.Fit( parent ) #---------------------------------------------------------------------------- # Handle the object trait changing value outside the editor: #---------------------------------------------------------------------------- def on_trait_change_image ( self, control, new ): control.Bitmap( bitmap_cache( new + self.suffix, False, self.path ) ) #---------------------------------------------------------------------------- # Return the layout style for this trait editor's control: #---------------------------------------------------------------------------- def layout_style ( self ): return 0 #---------------------------------------------------------------------------- # Handle the user clicking one of the image buttons: #---------------------------------------------------------------------------- def on_click ( self, control ): parent= control.GetParent() self.set( parent.object, parent.trait_name, control.value, parent.handler ) #------------------------------------------------------------------------------- # 'TraitEditorCheckList' class: #------------------------------------------------------------------------------- class TraitEditorCheckList ( wxTraitEditor ): #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, values, cols = 1 ): self.cols = cols self.values = values if type( values[0] ) is str: self.values = [ ( x, x.capitalize() ) for x in values ] self.mapping = mapping = {} for value, key in self.values: mapping[ key ] = value #---------------------------------------------------------------------------- # Create an in-place simple view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): control = wx.wxChoice( parent, -1, wx.wxPoint( 0, 0 ), wx.wxSize( 100, 20 ), self.all_labels() ) try: control.SetSelection( self.all_values().index( self.current_value( object, trait_name )[0] ) ) except: pass wx.EVT_CHOICE( parent, control.GetId(), self.on_value_changed ) TraitMonitor( object, trait_name, control, on_trait_change_choice ) return control #---------------------------------------------------------------------------- # Create an in-place custom view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def custom_editor ( self, object, trait_name, description, handler, parent ): # Create a panel to hold all of the radio buttons: panel = wx.wxPanel( parent, -1 ) # Get the current trait value: cur_value = self.current_value( object, trait_name ) # Create a sizer to manage the radio buttons: labels = self.all_labels() values = self.all_values() n = len( values ) cols = self.cols rows = (n + cols - 1) // cols incr = [ n // cols ] * cols rem = n % cols for i in range( cols ): incr[i] += (rem > i) incr[-1] = -(reduce( lambda x, y: x + y, incr[:-1], 0 ) - 1) if cols > 1: sizer = wx.wxGridSizer( 0, cols, 2, 4 ) else: sizer = wx.wxBoxSizer( wx.wxVERTICAL ) # Add the set of all possible choices: index = 0 for i in range( rows ): for j in range( cols ): if n > 0: control = wx.wxCheckBox( panel, -1, labels[ index ] ) control.value = value = values[ index ] control.SetValue( value in cur_value ) wx.EVT_CHECKBOX( panel, control.GetId(), self.on_click ) index += incr[j] n -= 1 else: control = wx.wxCheckBox( panel, -1, '' ) control.Show( False ) sizer.Add( control, 0, wx.wxNORTH, 5 ) # Set-up the layout: panel.SetAutoLayout( True ) panel.SetSizer( sizer ) sizer.Fit( panel ) TraitMonitor( object, trait_name, panel, self.on_trait_change_list ) # Return the panel as the result: return panel #---------------------------------------------------------------------------- # Return the set of all possible labels: #---------------------------------------------------------------------------- def all_labels ( self ): return [ x[1] for x in self.values ] #---------------------------------------------------------------------------- # Return the set of all possible values: #---------------------------------------------------------------------------- def all_values ( self ): return [ x[0] for x in self.values ] #---------------------------------------------------------------------------- # Return whether or not the current value is a string or not: #---------------------------------------------------------------------------- def is_string ( self, object, trait_name ): return (type( getattr( object, trait_name ) ) is str) #---------------------------------------------------------------------------- # Return the current value of the object trait: #---------------------------------------------------------------------------- def current_value ( self, object, trait_name ): return self.parse_value( getattr( object, trait_name ) ) #---------------------------------------------------------------------------- # Parse a value into a list: #---------------------------------------------------------------------------- def parse_value ( self, value ): if value is None: return [] if type( value ) is not str: return value return [ x.strip() for x in value.split( ',' ) ] #---------------------------------------------------------------------------- # Handle the user selecting a new value from the combo box: #---------------------------------------------------------------------------- def on_value_changed ( self, event ): control = event.GetEventObject() value = self.mapping[ event.GetString() ] if not self.is_string( control.object, control.trait_name ): value = [ value ] self.set( control.object, control.trait_name, value, control.handler ) #---------------------------------------------------------------------------- # Handle the user clicking one of the 'custom' check boxes: #---------------------------------------------------------------------------- def on_click ( self, event ): control = event.GetEventObject() parent = control.GetParent() value = control.value cur_value = self.current_value( parent.object, parent.trait_name ) if control.GetValue(): cur_value.append( value ) else: cur_value.remove( value ) if self.is_string( parent.object, parent.trait_name ): cur_value = ','.join( cur_value ) self.set( parent.object, parent.trait_name, cur_value, parent.handler ) #---------------------------------------------------------------------------- # Handle the object trait changing value outside the editor: #---------------------------------------------------------------------------- def on_trait_change_choice ( self, control, new ): try: control.SetSelection( self.all_values().index( self.parse_value( new )[0] ) ) except: pass def on_trait_change_list ( self, panel, new ): new_values = self.parse_value( new ) for control in panel.GetChildren(): if control.IsShown(): control.SetValue( control.value in new_values ) #------------------------------------------------------------------------------- # 'TraitEditorBoolean' class: #------------------------------------------------------------------------------- class TraitEditorBoolean ( wxTraitEditor ): #---------------------------------------------------------------------------- # Create an in-place read only view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def readonly_editor ( self, object, trait_name, description, handler, parent ): control = wx.wxTextCtrl( parent, -1, '', style = wx.wxTE_READONLY ) try: value = getattr( object, trait_name + '_' ) trait_name += '_' except: value = getattr( object, trait_name ) TraitMonitor( object, trait_name, control, self.on_trait_change_readonly ) self.on_trait_change_readonly( control, value ) return control #---------------------------------------------------------------------------- # Handle the object trait changing value outside the editor: #---------------------------------------------------------------------------- def on_trait_change_readonly ( self, control, new ): if new: control.SetValue( 'True' ) else: control.SetValue( 'False' ) #---------------------------------------------------------------------------- # Create an in-place editable view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): control = wx.wxCheckBox( parent, -1, '' ) try: value = getattr( object, trait_name + '_' ) trait_name += '_' except: value = getattr( object, trait_name ) control.SetValue( value ) wx.EVT_CHECKBOX( parent, control.GetId(), self.on_value_changed ) TraitMonitor( object, trait_name, control, self.on_trait_change_check ) return control #---------------------------------------------------------------------------- # Handle the user clicking on the checkbox: #---------------------------------------------------------------------------- def on_value_changed ( self, event ): control = event.GetEventObject() self.set( control.object, control.trait_name, control.GetValue(), control.handler ) #---------------------------------------------------------------------------- # Handle the object trait changing value outside the editor: #---------------------------------------------------------------------------- def on_trait_change_check ( self, control, new ): control.SetValue( new ) #------------------------------------------------------------------------------- # 'TraitEditorRange class: #------------------------------------------------------------------------------- class TraitEditorRange ( TraitEditorEnum ): #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, handler, cols = 1, auto_set = True ): if isinstance( handler, Trait ): handler = handler.setter self.low = handler.low self.high = handler.high self.is_float = (type( self.low ) is float) self.cols = cols self.auto_set = auto_set self.mapped = False #---------------------------------------------------------------------------- # Create an in-place editable view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): if self.is_float or (abs( self.high - self.low ) > 100): self.format = '%d' if self.is_float: self.format = '%%.%df' % max( 0, 4 - int( log10( self.high - self.low ) ) ) panel = wx.wxPanel( parent, -1 ) sizer = wx.wxBoxSizer( wx.wxHORIZONTAL ) fvalue = getattr( object, trait_name ) try: fvalue_text = self.format % fvalue 1 / (self.low <= fvalue <= self.high) except: fvalue_text = '' fvalue = self.low ivalue = int( (float( fvalue - self.low ) / (self.high - self.low)) * 10000 ) label_lo = wx.wxStaticText( panel, -1, '999.999', style = wx.wxALIGN_RIGHT | wx.wxST_NO_AUTORESIZE ) sizer.Add( label_lo, 0, wx.wxALIGN_CENTER ) panel.slider = slider = wx.wxSlider( panel, -1, ivalue, 0, 10000, size = wx.wxSize( 100, 20 ), style = wx.wxSL_HORIZONTAL | wx.wxSL_AUTOTICKS ) slider.SetTickFreq( 1000, 1 ) slider.SetPageSize( 1000 ) slider.SetLineSize( 100 ) wx.EVT_SCROLL( slider, self.on_scroll ) sizer.Add( slider, 1, wx.wxEXPAND ) label_hi = wx.wxStaticText( panel, -1, '999.999' ) sizer.Add( label_hi, 0, wx.wxALIGN_CENTER ) panel.text = text = wx.wxTextCtrl( panel, -1, fvalue_text, size = wx.wxSize( 60, 20 ), style = wx.wxTE_PROCESS_ENTER ) wx.EVT_KILL_FOCUS( text, self.on_enter ) wx.EVT_TEXT_ENTER( panel, text.GetId(), self.on_enter ) sizer.Add( text, 0, wx.wxLEFT | wx.wxEXPAND, 8 ) # Set-up the layout: panel.SetAutoLayout( True ) panel.SetSizer( sizer ) sizer.Fit( panel ) label_lo.SetLabel( str( self.low ) ) label_hi.SetLabel( str( self.high ) ) panel.is_enum = False TraitMonitor( object, trait_name, panel, self.on_trait_change_slider ) # Return the panel as the result: return panel else: value = getattr( object, trait_name ) control = wx.wxSpinCtrl( parent, -1, str( value ), min = self.low, max = self.high, initial = value ) wx.EVT_SPINCTRL( parent, control.GetId(), self.on_value_changed ) TraitMonitor( object, trait_name, control, self.on_trait_change_spinner ) return control #---------------------------------------------------------------------------- # Create an in-place custom view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def custom_editor ( self, object, trait_name, description, handler, parent ): if ((type( self.low ) is float) or (abs( self.high - self.low ) > 15)): return self.simple_editor( object, trait_name, description, handler, parent ) control = TraitEditorEnum.custom_editor( self, object, trait_name, description, handler, parent ) control.is_enum = True return control #---------------------------------------------------------------------------- # Return the set of all possible values: #---------------------------------------------------------------------------- def all_values ( self ): return [ str( x ) for x in range( self.low, self.high + 1 ) ] #---------------------------------------------------------------------------- # Return the current value of the object trait: #---------------------------------------------------------------------------- def current_value ( self, object, trait_name ): return str( getattr( object, trait_name ) ) #---------------------------------------------------------------------------- # Handle the user selecting a new value from the spin control: #---------------------------------------------------------------------------- def on_value_changed ( self, event ): control = event.GetEventObject() self.set( control.object, control.trait_name, control.GetValue(), control.handler ) #---------------------------------------------------------------------------- # Handle the user pressing the 'Enter' key in the edit control: #---------------------------------------------------------------------------- def on_enter ( self, event ): control = text = event.GetEventObject() slider = None if not hasattr( control, 'object' ): control = control.GetParent() slider = control.slider try: value = text.GetValue().strip() self.set( control.object, control.trait_name, value, control.handler ) if slider is not None: slider.SetValue( int( ((float( value ) - self.low) / (self.high - self.low)) * 10000 ) ) except TraitError as excp: self.error( control.description, excp, control ) #---------------------------------------------------------------------------- # Handle the user changing the contents of the edit control: #---------------------------------------------------------------------------- def on_key ( self, event ): control = event.GetEventObject() try: setattr( control.object, control.trait_name, control.GetValue().strip() ) color = wx.wxWHITE except: color = error_color control.SetBackgroundColour( color ) control.Refresh() #---------------------------------------------------------------------------- # Handle the user changing the current slider value: #---------------------------------------------------------------------------- def on_scroll ( self, event ): control = event.GetEventObject().GetParent() value = self.low + ((float( event.GetPosition() ) / 10000.0) * (self.high - self.low)) control.text.SetValue( self.format % value ) event_type = event.GetEventType() if ((event_type == wx.wxEVT_SCROLL_ENDSCROLL) or (self.auto_set and (event_type == wx.wxEVT_SCROLL_THUMBTRACK))): self.set( control.object, control.trait_name, value, control.handler ) #---------------------------------------------------------------------------- # Handle the object trait changing value outside the editor: #---------------------------------------------------------------------------- def on_trait_change_spinner ( self, control, new ): try: control.SetValue( int( new ) ) except: pass def on_trait_change_slider ( self, control, new ): try: new_text = self.format % new 1 / (self.low <= new <= self.high) except: new_text = '' new = self.low ivalue = int( (float(new - self.low) / (self.high - self.low)) * 10000.0) control.text.SetValue( new_text ) control.slider.SetValue( ivalue ) #------------------------------------------------------------------------------- # 'TraitEditorComplex class: #------------------------------------------------------------------------------- class TraitEditorComplex ( TraitEditorText ): #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, editors, auto_set = True ): TraitEditorText.__init__( self, auto_set = auto_set ) self.editors = editors #---------------------------------------------------------------------------- # Create an in-place custom view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def custom_editor ( self, object, trait_name, description, handler, parent ): # Create a panel to hold all of the component trait editors: panel = wx.wxPanel( parent, -1 ) sizer = wx.wxBoxSizer( wx.wxVERTICAL ) # Add all of the component trait editors: for editor in self.editors: control = editor.custom_editor( object, trait_name, description, handler, panel ) init_control( control, object, trait_name, description, handler ) sizer.Add( control, 1, editor.layout_style() ) # Set-up the layout: panel.SetAutoLayout( True ) panel.SetSizer( sizer ) sizer.Fit( panel ) # Return the panel as the result: return panel #------------------------------------------------------------------------------- # 'TraitEditorList class: #------------------------------------------------------------------------------- class TraitEditorList ( wxTraitEditor ): # Normal list item menu: list_menu = """ Add before [menu_before]: self.add_before() Add after [menu_after]: self.add_after() --- Delete [menu_delete]: self.delete_item() --- Move up [menu_up]: self.move_up() Move down [menu_down]: self.move_down() Move to top [menu_top]: self.move_top() Move to bottom [menu_bottom]: self.move_bottom() """ # Empty list item menu: empty_list_menu = """ Add: self.add_empty() """ #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, trait_handler, rows = 5 ): self.trait_handler = trait_handler self.rows = rows #---------------------------------------------------------------------------- # Create an in-place read only view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def readonly_editor ( self, object, trait_name, description, handler, parent ): return self.list_editor( object, trait_name, description, handler, parent, 'readonly_editor' ) #---------------------------------------------------------------------------- # Create an in-place text editable view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def text_editor ( self, object, trait_name, description, handler, parent ): return self.list_editor( object, trait_name, description, handler, parent, 'text_editor' ) #---------------------------------------------------------------------------- # Create an in-place editable view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): return self.list_editor( object, trait_name, description, handler, parent, 'simple_editor' ) #---------------------------------------------------------------------------- # Create an in-place custom view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def custom_editor ( self, object, trait_name, description, handler, parent ): return self.list_editor( object, trait_name, description, handler, parent, 'custom_editor' ) #---------------------------------------------------------------------------- # Create an editable list view of the current value of the 'trait_name' # trait of 'object': #---------------------------------------------------------------------------- def list_editor ( self, object, trait_name, description, handler, parent, type ): # Create all of the list item trait editors: trait_handler = self.trait_handler resizable = ((trait_handler.min_items != trait_handler.max_items) and (type != 'readonly_editor')) item_trait = trait_handler.item_trait list_pane = wx.wxScrolledWindow( parent, -1 ) init_control( list_pane, object, trait_name, description, handler, None ) list_pane.editor = editor = getattr( item_trait.get_editor(), type ) list_sizer = wx.wxFlexGridSizer( 0, 1 + resizable, 0, 0 ) list_sizer.AddGrowableCol( resizable ) values = getattr( object, trait_name ) index = 0 width, height = 100, 18 is_fake = (resizable and (len( values ) == 0)) if is_fake: values = [ item_trait.default_value ] for value in values: width = height = 0 if resizable: control = ImageControl( list_pane, bitmap_cache( 'list_editor', False ), -1, self.popup_menu ) width, height = control.GetSize() width += 4 try: proxy = ListItemProxy( object, trait_name, index, item_trait, value ) pcontrol = editor( proxy, 'value', description, handler, list_pane ) if resizable: control.pcontrol = pcontrol init_control( pcontrol, proxy, 'value', description, handler, value ) except: if not is_fake: raise pcontrol = wx.wxButton( list_pane, -1, 'sample' ) width2, height2 = pcontrol.GetSize() width += width2 height = max( height, height2 ) if resizable: list_sizer.Add( control, 0, wx.wxLEFT | wx.wxRIGHT, 2 ) list_sizer.Add( pcontrol, 1, wx.wxEXPAND ) index += 1 list_pane.SetAutoLayout( True ) list_pane.SetSizer( list_sizer ) if is_fake: self.cur_control = control self.empty_list( list_pane ) control.Destroy() pcontrol.Destroy() rows = [ self.rows, 1 ][ type == 'simple_editor' ] list_pane.SetSize( wx.wxSize( width + ((trait_handler.max_items > rows) * scrollbar_dx), height * rows ) ) list_pane.SetScrollRate( 0, height ) return list_pane #---------------------------------------------------------------------------- # Add a new value at the specified list index: #---------------------------------------------------------------------------- def add_item ( self, offset ): controls = self.get_controls() list, index = self.get_info() index += offset item_trait = self.trait_handler.item_trait value = item_trait.default_value list[ index: index ] = [ value ] list_pane = self.cur_control.GetParent() control = ImageControl( list_pane, bitmap_cache( 'list_editor', False ), -1, self.popup_menu ) proxy = ListItemProxy( list_pane.object, list_pane.trait_name, index, item_trait, value ) pcontrol = list_pane.editor( proxy, 'value', list_pane.description, list_pane.handler, list_pane ) control.pcontrol = pcontrol init_control( pcontrol, proxy, 'value', list_pane.description, list_pane.handler, value ) controls[ index: index ] = [ ( control, pcontrol ) ] self.reload_sizer( controls, -2 ) #---------------------------------------------------------------------------- # Create an empty list entry (so the user can add a new item): #---------------------------------------------------------------------------- def empty_list ( self, list_pane ): control = ImageControl( list_pane, bitmap_cache( 'list_editor', False ), -1, self.popup_empty_menu ) control.is_empty = True proxy = ListItemProxy( list_pane.object, list_pane.trait_name, -1, None, None ) pcontrol = wx.wxStaticText( list_pane, -1, ' (Empty List)' ) control.pcontrol = pcontrol pcontrol.object = proxy self.reload_sizer( [ ( control, pcontrol ) ] ) #---------------------------------------------------------------------------- # Display the empty list editor popup menu: #---------------------------------------------------------------------------- def popup_empty_menu ( self, control ): self.cur_control = control control.PopupMenuXY( MakeMenu( self.empty_list_menu, self, True, control ).menu, 0, 0 ) #---------------------------------------------------------------------------- # Display the list editor popup menu: #---------------------------------------------------------------------------- def popup_menu ( self, control ): self.cur_control = control proxy = control.pcontrol.object index = proxy.index menu = MakeMenu( self.list_menu, self, True, control ).menu len_list = len( proxy.list() ) not_full = (len_list < self.trait_handler.max_items) self.menu_before.enabled( not_full ) self.menu_after.enabled( not_full ) self.menu_delete.enabled( len_list > self.trait_handler.min_items ) self.menu_up.enabled( index > 0 ) self.menu_top.enabled( index > 0 ) self.menu_down.enabled( index < (len_list - 1) ) self.menu_bottom.enabled( index < (len_list - 1) ) control.PopupMenuXY( menu, 0, 0 ) #---------------------------------------------------------------------------- # Insert a new item before the current item: #---------------------------------------------------------------------------- def add_before ( self ): self.add_item( 0 ) #---------------------------------------------------------------------------- # Insert a new item after the current item: #---------------------------------------------------------------------------- def add_after ( self ): self.add_item( 1 ) #---------------------------------------------------------------------------- # Add a new item when the list is empty: #---------------------------------------------------------------------------- def add_empty ( self ): self.add_item( 0 ) self.delete_item() #---------------------------------------------------------------------------- # Delete the current item: #---------------------------------------------------------------------------- def delete_item ( self ): controls = self.get_controls() list, index = self.get_info() control, pcontrol = controls[ index ] del controls[ index ] if hasattr( control, 'is_empty' ): self.reload_sizer( controls, 2 ) else: del list[ index ] if len( list ) == 0: self.empty_list( control.GetParent() ) else: self.reload_sizer( controls, 2 ) control.Destroy() pcontrol.Destroy() #---------------------------------------------------------------------------- # Move the current item up one in the list: #---------------------------------------------------------------------------- def move_up ( self ): controls = self.get_controls() list, index = self.get_info() controls[index-1], controls[index] = controls[index], controls[index-1] list[index-1], list[index] = list[index], list[index-1] self.reload_sizer( controls ) #---------------------------------------------------------------------------- # Move the current item down one in the list: #---------------------------------------------------------------------------- def move_down ( self ): controls = self.get_controls() list, index = self.get_info() controls[index+1], controls[index] = controls[index], controls[index+1] list[index+1], list[index] = list[index], list[index+1] self.reload_sizer( controls ) #---------------------------------------------------------------------------- # Move the current item to the top of the list: #---------------------------------------------------------------------------- def move_top ( self ): controls = self.get_controls() list, index = self.get_info() control = [ controls[ index ] ] item = [ list[ index ] ] del controls[ index ] del list[ index ] controls[0:0] = control list[0:0] = item self.reload_sizer( controls ) #---------------------------------------------------------------------------- # Move the current item to the bottom of the list: #---------------------------------------------------------------------------- def move_bottom ( self ): controls = self.get_controls() list, index = self.get_info() control = controls[ index ] item = list[ index ] del controls[ index ] del list[ index ] controls.append( control ) list.append( item ) self.reload_sizer( controls ) #---------------------------------------------------------------------------- # Return the associated object list and current item index: #---------------------------------------------------------------------------- def get_info ( self ): cur_control = self.cur_control proxy = self.cur_control.pcontrol.object return ( proxy.list(), proxy.index ) #---------------------------------------------------------------------------- # Return all controls in the correct index order as ( button, proxy ) pairs: #---------------------------------------------------------------------------- def get_controls ( self ): cur_control = self.cur_control result = [] controls = cur_control.GetParent().GetChildren() for i in range( 0, len( controls ), 2 ): result.append( ( controls[i], controls[i+1] ) ) result.sort( lambda x, y: cmp( x[1].object.index, y[1].object.index ) ) return result #---------------------------------------------------------------------------- # Reload the layout from the specified list of ( button, proxy ) pairs: #---------------------------------------------------------------------------- def reload_sizer ( self, controls, extra = 0 ): list = self.cur_control.GetParent() sizer = list.GetSizer() for i in range( 2 * len( controls ) + extra ): sizer.Remove( 0 ) index = 0 for control, pcontrol in controls: sizer.Add( control, 0, wx.wxLEFT | wx.wxRIGHT, 2 ) sizer.Add( pcontrol, 1, wx.wxEXPAND ) pcontrol.object.index = index index += 1 sizer.Layout() list.SetVirtualSize( sizer.GetMinSize() ) #------------------------------------------------------------------------------- # 'ListItemProxy' class: #------------------------------------------------------------------------------- class ListItemProxy ( HasDynamicTraits ): def __init__ ( self, object, trait_name, index, trait, value ): HasDynamicTraits.__init__( self ) self.add_trait( 'value', trait ) self.object = object self.trait_name = trait_name self.index = index self.value = value def list ( self ): return getattr( self.object, self.trait_name ) def value_changed ( self, old_value, new_value ): self.list()[ self.index ] = new_value #------------------------------------------------------------------------------- # 'TraitEditorFile' class: #------------------------------------------------------------------------------- class TraitEditorFile ( TraitEditorText ): #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, filter = None ): TraitEditorText.__init__( self ) self.filter = filter #---------------------------------------------------------------------------- # Create an in-place simple view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): panel = wx.wxPanel( parent, -1 ) sizer = wx.wxBoxSizer( wx.wxHORIZONTAL ) control = wx.wxTextCtrl( panel, -1, self.str( object, trait_name ), style = wx.wxTE_PROCESS_ENTER ) init_control( control, object, trait_name, description, handler ) wx.EVT_KILL_FOCUS( control, self.on_enter ) wx.EVT_TEXT_ENTER( panel, control.GetId(), self.on_enter ) wx.EVT_TEXT( panel, control.GetId(), self.on_key ) sizer.Add( control, 1, wx.wxEXPAND | wx.wxALIGN_CENTER ) button = wx.wxButton( panel, -1, 'Browse...' ) button.filename = control sizer.Add( button, 0, wx.wxLEFT | wx.wxALIGN_CENTER, 8 ) wx.EVT_BUTTON( panel, button.GetId(), self.on_browse ) panel.SetAutoLayout( True ) panel.SetSizer( sizer ) sizer.Fit( panel ) TraitMonitor( object, trait_name, control, self.on_trait_change_text ) return panel #---------------------------------------------------------------------------- # Interactively edit the 'trait_name' color trait of 'object': #---------------------------------------------------------------------------- def on_browse ( self, event ): control = event.GetEventObject() parent = control.GetParent() dlg = wx.wxFileDialog( control, message = 'Select a file' ) dlg.SetFilename( control.filename.GetValue() ) if self.filter is not None: dlg.SetWildcard( self.filter ) rc = (dlg.ShowModal() == wx.wxID_OK) filename = os.path.abspath( dlg.GetPath() ) dlg.Destroy() if rc: control.filename.SetValue( filename ) self.set( parent.object, parent.trait_name, filename, parent.handler ) #------------------------------------------------------------------------------- # 'TraitEditorImageDialog' class: #------------------------------------------------------------------------------- class TraitEditorImageDialog ( wx.wxDialog ): #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, object, trait_name, description, parent, handler, editor ): wx.wxDialog.__init__( self, parent, -1, 'Choose ' + description ) wx.EVT_CLOSE( self, self.on_close_dialog ) # Initialize instance data: self.object = object self.trait_name = trait_name self.handler = handler self.editor = editor # Create the grid of image buttons: if editor.mapped: trait_name == '_' editor.create_image_grid( self, getattr( object, trait_name ), self.on_click ) # Position the dialog: position_near( parent, self ) #---------------------------------------------------------------------------- # Close the dialog: #---------------------------------------------------------------------------- def on_close_dialog ( self, event, rc = False ): self.EndModal( rc ) self.Destroy() #---------------------------------------------------------------------------- # Handle the user clicking one of the choice buttons: #---------------------------------------------------------------------------- def on_click ( self, control ): self.editor.set( self.object, self.trait_name, control.value, self.handler ) #------------------------------------------------------------------------------- # Convert an image file name to a cached bitmap: #------------------------------------------------------------------------------- # Bitmap cache dictionary (indexed by filename): _bitmap_cache = {} ### NOTE: This needs major improvements: app_path = None traits_path = None def bitmap_cache ( name, standard_size, path = None ): global app_path, traits_path if path is None: if traits_path is None: from . import traits traits_path = os.path.join( os.path.dirname( traits.__file__ ), 'images' ) path = traits_path elif path == '': if app_path is None: app_path = os.path.join( os.path.dirname( sys.argv[0] ), '..', 'images' ) path = app_path filename = os.path.abspath( os.path.join( path, name.replace( ' ', '_' ).lower() + '.gif' ) ) bitmap = _bitmap_cache.get( filename + ('*'[ not standard_size: ]) ) if bitmap is not None: return bitmap std_bitmap = bitmap = wx.wxBitmapFromImage( wx.wxImage( filename ) ) _bitmap_cache[ filename ] = bitmap dx = bitmap.GetWidth() if dx < standard_bitmap_width: dy = bitmap.GetHeight() std_bitmap = wx.wxEmptyBitmap( standard_bitmap_width, dy ) dc1 = wx.wxMemoryDC() dc2 = wx.wxMemoryDC() dc1.SelectObject( std_bitmap ) dc2.SelectObject( bitmap ) dc1.SetPen( wx.wxTRANSPARENT_PEN ) dc1.SetBrush( wx.wxWHITE_BRUSH ) dc1.DrawRectangle( 0, 0, standard_bitmap_width, dy ) dc1.Blit( (standard_bitmap_width - dx) // 2, 0, dx, dy, dc2, 0, 0 ) _bitmap_cache[ filename + '*' ] = std_bitmap if standard_size: return std_bitmap return bitmap #------------------------------------------------------------------------------- # Standard colors: #------------------------------------------------------------------------------- standard_colors = { 'aquamarine': wx.wxNamedColour( 'aquamarine' ), 'black': wx.wxNamedColour( 'black' ), 'blue': wx.wxNamedColour( 'blue' ), 'blue violet': wx.wxNamedColour( 'blue violet' ), 'brown': wx.wxNamedColour( 'brown' ), 'cadet blue': wx.wxNamedColour( 'cadet blue' ), 'coral': wx.wxNamedColour( 'coral' ), 'cornflower blue': wx.wxNamedColour( 'cornflower blue' ), 'cyan': wx.wxNamedColour( 'cyan' ), 'dark grey': wx.wxNamedColour( 'dark grey' ), 'dark green': wx.wxNamedColour( 'dark green' ), 'dark olive green': wx.wxNamedColour( 'dark olive green' ), 'dark orchid': wx.wxNamedColour( 'dark orchid' ), 'dark slate blue': wx.wxNamedColour( 'dark slate blue' ), 'dark slate grey': wx.wxNamedColour( 'dark slate grey' ), 'dark turquoise': wx.wxNamedColour( 'dark turquoise' ), 'dim grey': wx.wxNamedColour( 'dim grey' ), 'firebrick': wx.wxNamedColour( 'firebrick' ), 'forest green': wx.wxNamedColour( 'forest green' ), 'gold': wx.wxNamedColour( 'gold' ), 'goldenrod': wx.wxNamedColour( 'goldenrod' ), 'grey': wx.wxNamedColour( 'grey' ), 'green': wx.wxNamedColour( 'green' ), 'green yellow': wx.wxNamedColour( 'green yellow' ), 'indian red': wx.wxNamedColour( 'indian red' ), 'khaki': wx.wxNamedColour( 'khaki' ), 'light blue': wx.wxNamedColour( 'light blue' ), 'light grey': wx.wxNamedColour( 'light grey' ), 'light steel': wx.wxNamedColour( 'light steel' ), 'blue': wx.wxNamedColour( 'blue' ), 'lime green': wx.wxNamedColour( 'lime green' ), 'magenta': wx.wxNamedColour( 'magenta' ), 'maroon': wx.wxNamedColour( 'maroon' ), 'medium aquamarine': wx.wxNamedColour( 'medium aquamarine' ), 'medium blue': wx.wxNamedColour( 'medium blue' ), 'medium forest green': wx.wxNamedColour( 'medium forest green' ), 'medium goldenrod': wx.wxNamedColour( 'medium goldenrod' ), 'medium orchid': wx.wxNamedColour( 'medium orchid' ), 'medium sea green': wx.wxNamedColour( 'medium sea green' ), 'medium slate blue': wx.wxNamedColour( 'medium slate blue' ), 'medium spring green': wx.wxNamedColour( 'medium spring green' ), 'medium turquoise': wx.wxNamedColour( 'medium turquoise' ), 'medium violet red': wx.wxNamedColour( 'medium violet red' ), 'midnight blue': wx.wxNamedColour( 'midnight blue' ), 'navy': wx.wxNamedColour( 'navy' ), 'orange': wx.wxNamedColour( 'orange' ), 'orange red': wx.wxNamedColour( 'orange red' ), 'orchid': wx.wxNamedColour( 'orchid' ), 'pale green': wx.wxNamedColour( 'pale green' ), 'pink': wx.wxNamedColour( 'pink' ), 'plum': wx.wxNamedColour( 'plum' ), 'purple': wx.wxNamedColour( 'purple' ), 'red': wx.wxNamedColour( 'red' ), 'salmon': wx.wxNamedColour( 'salmon' ), 'sea green': wx.wxNamedColour( 'sea green' ), 'sienna': wx.wxNamedColour( 'sienna' ), 'sky blue': wx.wxNamedColour( 'sky blue' ), 'slate blue': wx.wxNamedColour( 'slate blue' ), 'spring green': wx.wxNamedColour( 'spring green' ), 'steel blue': wx.wxNamedColour( 'steel blue' ), 'tan': wx.wxNamedColour( 'tan' ), 'thistle': wx.wxNamedColour( 'thistle' ), 'turquoise': wx.wxNamedColour( 'turquoise' ), 'violet': wx.wxNamedColour( 'violet' ), 'violet red': wx.wxNamedColour( 'violet red' ), 'wheat': wx.wxNamedColour( 'wheat' ), 'white': wx.wxNamedColour( 'white' ), 'yellow': wx.wxNamedColour( 'yellow' ), 'yellow green': wx.wxNamedColour( 'yellow green' ), } #------------------------------------------------------------------------------- # Convert a number into a wxColour object: #------------------------------------------------------------------------------- def num_to_color ( object, name, value ): num = int( value ) return wx.wxColour( num // 0x10000, (num // 0x100) & 0xFF, num & 0xFF ) num_to_color.info = ('a number, which in hex is of the form 0xRRGGBB, where ' 'RR is red, GG is green, and BB is blue') #------------------------------------------------------------------------------- # 'TraitEditorColor' class: #------------------------------------------------------------------------------- class TraitEditorColor ( wxTraitEditor ): #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self ): self.color_data = wx.wxColourData() #---------------------------------------------------------------------------- # Interactively edit the 'trait_name' color trait of 'object': #---------------------------------------------------------------------------- def popup_editor ( self, object, trait_name, description, handler, parent = None ): if not hasattr( parent, 'is_custom' ): # Fixes a problem with the edit field having the focus: parent.ReleaseMouse() return TraitEditorColorDialog( object, trait_name, description, parent, handler, self ).ShowModal() self.color_data.SetColour( self.to_wx_color( object, trait_name ) ) self.color_data.SetChooseFull( True ) dialog = wx.wxColourDialog( parent or object.window, self.color_data ) if dialog.ShowModal() == wx.wxID_OK: panel = parent if panel is not None: panel = panel.GetParent() self.set( object, trait_name, self.from_wx_color( dialog.GetColourData().GetColour(), panel ), handler ) return True return False #---------------------------------------------------------------------------- # Create a view of the current value of the 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def create_editor ( self, object, trait_name, description, handler, parent, factory ): control = factory( self, object, trait_name, description, handler, parent ) self.set_color( control, self.to_wx_color( object, trait_name ) ) try: getattr( object, trait_name + '_' ) TraitMonitor( object, trait_name, control, self.on_trait_change_text ) TraitMonitor( object, trait_name + '_', control, self.on_trait_change_color ) except: TraitMonitor( object, trait_name, control, self.on_trait_change_both ) return control #---------------------------------------------------------------------------- # Create a read only view of the current value of the 'trait_name' # trait of 'object': #---------------------------------------------------------------------------- def readonly_editor ( self, object, trait_name, description, handler, parent ): return self.create_editor( object, trait_name, description, handler, parent, wxTraitEditor.readonly_editor ) #---------------------------------------------------------------------------- # Create a static view of the current value of the 'trait_name' # trait of 'object': #---------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): return self.create_editor( object, trait_name, description, handler, parent, wxTraitEditor.simple_editor ) #---------------------------------------------------------------------------- # Create an in-place custom view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def custom_editor ( self, object, trait_name, description, handler, parent ): # Create a panel to hold all of the buttons: panel = wx.wxPanel( parent, -1 ) sizer = wx.wxBoxSizer( wx.wxHORIZONTAL ) control = panel.color = self.simple_editor( object, trait_name, description, handler, panel ) control.is_custom = True init_control( control, object, trait_name, description, handler, None ) control.SetSize( wx.wxSize( 72, 72 ) ) sizer.Add( control, 0, wx.wxEXPAND | wx.wxRIGHT, 4 ) # Add all of the color choice buttons: sizer2 = wx.wxGridSizer( 0, 12, 0, 0 ) for i in range( len( color_samples ) ): control = wx.wxButton( panel, -1, '', size = wx.wxSize( 18, 18 ) ) control.SetBackgroundColour( color_samples[i] ) wx.EVT_BUTTON( panel, control.GetId(), self.on_click ) sizer2.Add( control ) sizer.Add( sizer2 ) # Set-up the layout: panel.SetAutoLayout( True ) panel.SetSizer( sizer ) sizer.Fit( panel ) # Return the panel as the result: return panel #---------------------------------------------------------------------------- # Handle the user clicking one of the 'custom' radio buttons: #---------------------------------------------------------------------------- def on_click ( self, event ): control = event.GetEventObject() parent = control.GetParent() self.set( parent.object, parent.trait_name, self.from_wx_color( control.GetBackgroundColour(), parent ), parent.handler ) #---------------------------------------------------------------------------- # Set the color of the 'current color' control: #---------------------------------------------------------------------------- def set_color ( self, control, color ): control.SetBackgroundColour( color ) if ((color.Red() > 192) or (color.Blue() > 192) or (color.Green() > 192)): control.SetForegroundColour( wx.wxBLACK ) else: control.SetForegroundColour( wx.wxWHITE ) #---------------------------------------------------------------------------- # Handle the object trait changing value outside the editor: #---------------------------------------------------------------------------- def on_trait_change_color ( self, control, new ): self.set_color( control, self.to_wx_color( new ) ) def on_trait_change_both ( self, control, new ): self.on_trait_change_text( control, new ) self.on_trait_change_color( control, new ) #---------------------------------------------------------------------------- # Get the current object trait color: #---------------------------------------------------------------------------- def get_cur_color ( self, object, trait_name ): try: return getattr( object, trait_name + '_' ) except: return getattr( object, trait_name ) #---------------------------------------------------------------------------- # Get the wxPython color equivalent of the object trait: #---------------------------------------------------------------------------- def to_wx_color ( self, object, trait_name = None ): if trait_name is None: color = object else: color = self.get_cur_color( object, trait_name ) if color is None: color = wx.wxWHITE return color #---------------------------------------------------------------------------- # Get the application equivalent of a wxPython value: #---------------------------------------------------------------------------- def from_wx_color ( self, color, panel = None ): return color #------------------------------------------------------------------------------- # Define wxPython specific color traits: #------------------------------------------------------------------------------- # Create a singleton color editor: color_editor = TraitEditorColor() # Color traits: color_trait = Trait( 'white', wx.wxColour, wx.wxColourPtr, standard_colors, num_to_color, editor = color_editor ) clear_color_trait = Trait( 'clear', None, wx.wxColour, wx.wxColourPtr, standard_colors, { 'clear': None }, num_to_color, editor = color_editor ) #------------------------------------------------------------------------------- # 'TraitEditorColorDialog' class: #------------------------------------------------------------------------------- class TraitEditorColorDialog ( wx.wxDialog ): #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, object, trait_name, description, parent, handler, editor ): wx.wxDialog.__init__( self, parent, -1, 'Choose ' + description ) wx.EVT_CLOSE( self, self.on_close_dialog ) panel = editor.custom_editor( object, trait_name, description, handler, self ) # Initialize instance data: panel.object = object panel.trait_name = trait_name panel.handler = handler panel.editor = editor sizer = wx.wxBoxSizer( wx.wxVERTICAL ) sizer.Add( panel ) self.SetAutoLayout( True ) self.SetSizer( sizer ) sizer.Fit( self ) position_near( parent, self ) #---------------------------------------------------------------------------- # Close the dialog: #---------------------------------------------------------------------------- def on_close_dialog ( self, event, rc = False ): self.EndModal( rc ) self.Destroy() #------------------------------------------------------------------------------- # Convert a string into a valid 'wxFont' object (if possible): #------------------------------------------------------------------------------- font_families = { 'default': wx.wxDEFAULT, 'decorative': wx.wxDECORATIVE, 'roman': wx.wxROMAN, 'script': wx.wxSCRIPT, 'swiss': wx.wxSWISS, 'modern': wx.wxMODERN } font_styles = { 'slant': wx.wxSLANT, 'italic': wx.wxITALIC } font_weights = { 'light': wx.wxLIGHT, 'bold': wx.wxBOLD } font_noise = [ 'pt', 'point', 'family' ] def str_to_font ( object, name, value ): try: point_size = 10 family = wx.wxDEFAULT style = wx.wxNORMAL weight = wx.wxNORMAL underline = 0 facename = [] for word in value.split(): lword = word.lower() if lword in font_families: family = font_families[ lword ] elif lword in font_styles: style = font_styles[ lword ] elif lword in font_weights: weight = font_weights[ lword ] elif lword == 'underline': underline = 1 elif lword not in font_noise: try: point_size = int( lword ) except: facename.append( word ) return wx.wxFont( point_size, family, style, weight, underline, ' '.join( facename ) ) except: pass raise TraitError( object, name, 'a font descriptor string', repr( value ) ) str_to_font.info = ( "a string describing a font (e.g. '12 pt bold italic " "swiss family Arial' or 'default 12')" ) #------------------------------------------------------------------------------- # 'TraitEditorFont' class: #------------------------------------------------------------------------------- class TraitEditorFont ( wxTraitEditor ): #---------------------------------------------------------------------------- # Interactively edit the 'trait_name' font trait of 'object': #---------------------------------------------------------------------------- def popup_editor ( self, object, trait_name, description, handler, parent = None ): font_data = wx.wxFontData() font_data.SetInitialFont( self.to_wx_font( object, trait_name ) ) dialog = wx.wxFontDialog( parent or object.window, font_data ) if dialog.ShowModal() == wx.wxID_OK: self.set( object, trait_name, self.from_wx_font( dialog.GetFontData().GetChosenFont() ), handler ) return True return False #---------------------------------------------------------------------------- # Create a view of the current value of the 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def create_editor ( self, object, trait_name, description, handler, parent, factory ): control = factory( self, object, trait_name, description, handler, parent ) self.on_trait_change_simple( control, getattr( object, trait_name ) ) TraitMonitor( object, trait_name, control, self.on_trait_change_simple ) return control #---------------------------------------------------------------------------- # Create a read only view of the current value of the 'trait_name' # trait of 'object': #---------------------------------------------------------------------------- def readonly_editor ( self, object, trait_name, description, handler, parent ): return self.create_editor( object, trait_name, description, handler, parent, wxTraitEditor.readonly_editor ) #---------------------------------------------------------------------------- # Create a static view of the current value of the 'trait_name' # trait of 'object': #---------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): return self.create_editor( object, trait_name, description, handler, parent, wxTraitEditor.simple_editor ) #---------------------------------------------------------------------------- # Create an in-place custom view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def custom_editor ( self, object, trait_name, description, handler, parent ): # Create a panel to hold all of the buttons: panel = wx.wxPanel( parent, -1 ) sizer = wx.wxBoxSizer( wx.wxVERTICAL ) # Add the standard font control: font = panel.font = self.simple_editor( object, trait_name, description, handler, panel ) init_control( font, object, trait_name, description, handler, None ) sizer.Add( font, 0, wx.wxEXPAND | wx.wxBOTTOM, 3 ) # Add all of the font choice controls: sizer2 = wx.wxBoxSizer( wx.wxHORIZONTAL ) control = panel.facename = wx.wxChoice( panel, -1, wx.wxPoint( 0, 0 ), wx.wxSize( 100, 20 ), self.all_facenames() ) sizer2.Add( control, 2, wx.wxEXPAND ) wx.EVT_CHOICE( panel, control.GetId(), self.on_value_changed ) control = panel.pointsize = wx.wxChoice( panel, -1, wx.wxPoint( 0, 0 ), wx.wxSize( 30, 20 ), point_sizes ) sizer2.Add( control, 1, wx.wxEXPAND | wx.wxRIGHT, 3 ) wx.EVT_CHOICE( panel, control.GetId(), self.on_value_changed ) sizer.Add( sizer2, 0, wx.wxEXPAND ) # Initialize the control's with the object's current trait value: self.on_trait_change_custom( font, getattr( object, trait_name ) ) # Set-up the layout: panel.SetAutoLayout( True ) panel.SetSizer( sizer ) sizer.Fit( panel ) TraitMonitor( object, trait_name, font, self.on_trait_change_custom ) # Return the panel as the result: return panel #---------------------------------------------------------------------------- # Handle the object trait changing value outside the editor: #---------------------------------------------------------------------------- def on_trait_change_simple ( self, control, new ): self.on_trait_change_text( control, new ) font = self.to_wx_font( new ) font.SetPointSize( min( 10, font.GetPointSize() ) ) control.SetFont( font ) def on_trait_change_custom ( self, control, new ): self.on_trait_change_text( control, new ) font = self.to_wx_font( new ) panel = control.GetParent() try: panel.facename.SetStringSelection( font.GetFaceName() ) except: panel.facename.SetSelection( 0 ) try: panel.pointsize.SetStringSelection( str( font.GetPointSize() ) ) except: panel.pointsize.SetSelection( 0 ) font.SetPointSize( min( 10, font.GetPointSize() ) ) control.SetFont( font ) #---------------------------------------------------------------------------- # Return the text representation of the specified object trait value: #---------------------------------------------------------------------------- def str_value ( self, font ): weight = { wx.wxLIGHT: ' Light', wx.wxBOLD: ' Bold' }.get( font.GetWeight(), '' ) style = { wx.wxSLANT: ' Slant', wx.wxITALIC:' Italic' }.get( font.GetStyle(), '' ) return '%s point %s%s%s' % ( font.GetPointSize(), font.GetFaceName(), style, weight ) #---------------------------------------------------------------------------- # Return a list of all available font facenames: #---------------------------------------------------------------------------- def all_facenames ( self ): global facenames if facenames is None: facenames = FontEnumerator().facenames() facenames.sort() return facenames #---------------------------------------------------------------------------- # Handle the user selecting a new facename or point size: #---------------------------------------------------------------------------- def on_value_changed ( self, event ): control = event.GetEventObject().GetParent() pointsize = int( control.pointsize.GetLabel() ) facename = control.facename.GetLabel() font = wx.wxFont( pointsize, wx.wxDEFAULT, wx.wxNORMAL, wx.wxNORMAL, faceName = facename ) self.set( control.object, control.trait_name, self.from_wx_font( font ), control.handler ) #---------------------------------------------------------------------------- # Return a wxFont object corresponding to a specified object's font trait: #---------------------------------------------------------------------------- def to_wx_font ( self, object, trait_name = None ): if trait_name is None: return object return getattr( object, trait_name ) #---------------------------------------------------------------------------- # Get the application equivalent of a wxPython value: #---------------------------------------------------------------------------- def from_wx_font ( self, font ): return font #------------------------------------------------------------------------------- # Define a wxPython specific font trait: #------------------------------------------------------------------------------- font_trait = Trait( 'Arial 10', wx.wxFont, wx.wxFontPtr, str_to_font, editor = TraitEditorFont() ) #------------------------------------------------------------------------------- # 'FontEnumerator' class: #------------------------------------------------------------------------------- class FontEnumerator ( wx.wxFontEnumerator ): #---------------------------------------------------------------------------- # Return a list of all available font facenames: #---------------------------------------------------------------------------- def facenames ( self ): self._facenames = [] self.EnumerateFacenames() return self._facenames #---------------------------------------------------------------------------- # Add a facename to the list of facenames: #---------------------------------------------------------------------------- def OnFacename ( self, facename ): self._facenames.append( facename ) return True #------------------------------------------------------------------------------- # 'ImageControl' class: #------------------------------------------------------------------------------- class ImageControl ( wx.wxWindow ): # Pens used to draw the 'selection' marker: _selectedPenDark = wx.wxPen( wx.wxSystemSettings_GetColour( wx.wxSYS_COLOUR_3DSHADOW ), 1, wx.wxSOLID ) _selectedPenLight = wx.wxPen( wx.wxSystemSettings_GetColour( wx.wxSYS_COLOUR_3DHIGHLIGHT ), 1, wx.wxSOLID ) #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, parent, bitmap, selected = None, handler = None ): wx.wxWindow.__init__( self, parent, -1, size = wx.wxSize( bitmap.GetWidth() + 10, bitmap.GetHeight() + 10 ) ) self._bitmap = bitmap self._selected = selected self._handler = handler self._mouse_over = False self._button_down = False # Set up the 'paint' event handler: wx.EVT_PAINT( self, self._on_paint ) # Set up mouse event handlers: wx.EVT_LEFT_DOWN( self, self._on_left_down ) wx.EVT_LEFT_UP( self, self._on_left_up ) wx.EVT_ENTER_WINDOW( self, self._on_enter ) wx.EVT_LEAVE_WINDOW( self, self._on_leave ) #---------------------------------------------------------------------------- # Get/Set the current selection state of the image: #---------------------------------------------------------------------------- def Selected ( self, selected = None ): if selected is not None: selected = (selected != 0) if selected != self._selected: if selected: for control in self.GetParent().GetChildren(): if (isinstance( control, ImageControl ) and control.Selected()): control.Selected( False ) break self._selected = selected self.Refresh() return self._selected #---------------------------------------------------------------------------- # Get/Set the current bitmap image: #---------------------------------------------------------------------------- def Bitmap ( self, bitmap = None ): if bitmap is not None: if bitmap != self._bitmap: self._bitmap = bitmap self.Refresh() return self._bitmap #---------------------------------------------------------------------------- # Get/Set the current click handler: #---------------------------------------------------------------------------- def Handler ( self, handler = None ): if handler is not None: if handler != self._handler: self._handler = handler self.Refresh() return self._handler #---------------------------------------------------------------------------- # Handle the mouse entering the control: #---------------------------------------------------------------------------- def _on_enter ( self, event = None ): if self._selected is not None: self._mouse_over = True self.Refresh() #---------------------------------------------------------------------------- # Handle the mouse leaving the control: #---------------------------------------------------------------------------- def _on_leave ( self, event = None ): if self._mouse_over: self._mouse_over = False self.Refresh() #---------------------------------------------------------------------------- # Handle the user pressing the mouse button: #---------------------------------------------------------------------------- def _on_left_down ( self, event = None ): if self._selected is not None: self.CaptureMouse() self._button_down = True self.Refresh() #---------------------------------------------------------------------------- # Handle the user clicking the control: #---------------------------------------------------------------------------- def _on_left_up ( self, event = None ): need_refresh = self._button_down if need_refresh: self.ReleaseMouse() self._button_down = False if self._selected is not None: wdx, wdy = self.GetClientSizeTuple() x = event.GetX() y = event.GetY() if (0 <= x < wdx) and (0 <= y < wdy): if self._selected != -1: self.Selected( True ) need_refresh = False if self._handler is not None: self._handler( self ) if need_refresh: self.Refresh() #---------------------------------------------------------------------------- # Handle the control being re-painted: #---------------------------------------------------------------------------- def _on_paint ( self, event = None ): wdc = wx.wxPaintDC( self ) wdx, wdy = self.GetClientSizeTuple() bitmap = self._bitmap bdx = bitmap.GetWidth() bdy = bitmap.GetHeight() wdc.DrawBitmap( bitmap, (wdx - bdx) // 2, (wdy - bdy) // 2, True ) pens = [ self._selectedPenLight, self._selectedPenDark ] bd = self._button_down if self._mouse_over: wdc.SetBrush( wx.wxTRANSPARENT_BRUSH ) wdc.SetPen( pens[ bd ] ) wdc.DrawLine( 0, 0, wdx, 0 ) wdc.DrawLine( 0, 1, 0, wdy ) wdc.SetPen( pens[ 1 - bd ] ) wdc.DrawLine( wdx - 1, 1, wdx - 1, wdy ) wdc.DrawLine( 1, wdy - 1, wdx - 1, wdy - 1 ) if self._selected == True: wdc.SetBrush( wx.wxTRANSPARENT_BRUSH ) wdc.SetPen( pens[ bd ] ) wdc.DrawLine( 1, 1, wdx - 1, 1 ) wdc.DrawLine( 1, 1, 1, wdy - 1 ) wdc.DrawLine( 2, 2, wdx - 2, 2 ) wdc.DrawLine( 2, 2, 2, wdy - 2 ) wdc.SetPen( pens[ 1 - bd ] ) wdc.DrawLine( wdx - 2, 2, wdx - 2, wdy - 1 ) wdc.DrawLine( 2, wdy - 2, wdx - 2, wdy - 2 ) wdc.DrawLine( wdx - 3, 3, wdx - 3, wdy - 2 ) wdc.DrawLine( 3, wdy - 3, wdx - 3, wdy - 3 )
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,345
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/traits102/trait_delegates.py
#------------------------------------------------------------------------------- # # Define the classes to handled 'synched' and 'unsynched' delegated traits. # # Written by: David C. Morrill # # Date: 06/21/2002 # # Refactored into a separate module: 07/04/2003 # # Symbols defined: TraitGetterSetter # TraitDelegate # TraitDelegateSynched # TraitEvent # TraitProperty # # (c) Copyright 2002, 2003 by Enthought, Inc. # #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- # Imports: #------------------------------------------------------------------------------- from __future__ import absolute_import, division, nested_scopes # confidence high import sys if sys.version_info[0] >= 3: ClassType = type InstanceType = type from types import MethodType else: from types import MethodType, InstanceType, ClassType from .trait_base import Undefined, CoercableFuncs, class_of, trait_editors from .trait_errors import TraitError, DelegationError #------------------------------------------------------------------------------- # Constants: #------------------------------------------------------------------------------- EmptyDict = {} HasTraits = None # Patched by 'traits.py' once class is defined! #------------------------------------------------------------------------------- # 'TraitGetterSetter' class (Abstract class): #------------------------------------------------------------------------------- class TraitGetterSetter: def metadata ( self ): return getattr( self, '__traits_metadata__', {} ) #------------------------------------------------------------------------------- # 'TraitDelegate' class: #------------------------------------------------------------------------------- class TraitDelegate (TraitGetterSetter ): __traits_metadata__ = { 'type': 'delegate' } def __init__ ( self, delegate = None, mutate_or_prefix = False ): self._delegate = delegate self.delegate = self.get_delegate self.getattr = self.getattr_method self.setattr = self.setattr # Performance hack! self.prefix = '' self.mutate = False if type( mutate_or_prefix ) is str: self.prefix = mutate_or_prefix self.name = self.replace_name if mutate_or_prefix[-1:] == '*': self.prefix = mutate_or_prefix[:-1] self.name = self.prefix_name if mutate_or_prefix == '*': self.name = self.classprefix_name else: self.mutate = mutate_or_prefix # Handle the special case of a delegate that disallows everything: if delegate is None: self.getattr = self.getattr_locked self.setattr = self.setattr_locked #---------------------------------------------------------------------------- # Return the delegate for a specified object: #---------------------------------------------------------------------------- def get_delegate ( self, object ): if hasattr( object, self._delegate ): delegate = getattr( object, self._delegate ) if type( delegate ) is MethodType: self.getattr = self.getattr_method self.delegate = delegate return delegate( object ) self.getattr = getattr( self, 'getattr_trait_' + self.name.__name__ ) self.delegate = self._getattr return self._getattr( object ) #---------------------------------------------------------------------------- # Return a delegate stored as an object trait: #---------------------------------------------------------------------------- def _getattr ( self, object ): return getattr( object, self._delegate ) #---------------------------------------------------------------------------- # Define variations on creating the trait name to delegate to: #---------------------------------------------------------------------------- def name ( self, object, name ): return name def replace_name ( self, object, name ): return self.prefix def prefix_name ( self, object, name ): return self.prefix + name def classprefix_name ( self, object, name ): return object.__prefix__ + name #---------------------------------------------------------------------------- # Return an object delegate's value for a specified trait: # (for the case where the delegate is a trait) # # Note: There is one variant for each type of delegate 'name'. They are # expanded out this way to eliminate a method call to 'self.name' # and thus optimize the delegation 'getattr' code path. #---------------------------------------------------------------------------- def getattr_trait_name ( self, object, name, value ): try: return getattr( getattr( object, self._delegate ), name ) except: return self.getattr_exception( object, name, value ) def getattr_trait_replace_name ( self, object, name, value ): try: return getattr( getattr( object, self._delegate ), self.prefix ) except: return self.getattr_exception( object, name, value ) def getattr_trait_prefix_name ( self, object, name, value ): try: return getattr( getattr( object, self._delegate ), self.prefix + name ) except: return self.getattr_exception( object, name, value ) def getattr_trait_classprefix_name ( self, object, name, value ): try: return getattr( getattr( object, self._delegate ), object.__prefix__ + name ) except: return self.getattr_exception( object, name, value ) #---------------------------------------------------------------------------- # Common exception handler for a trait delegate: #---------------------------------------------------------------------------- def getattr_exception ( self, object, name, value ): if getattr( object, self._delegate ) is None: if value is not Undefined: return value raise DelegationError( "Attempted to get the '%s' trait of %s instance, " "but its '%s' delegate is not defined." % ( name, class_of( object ), self._delegate ) ) else: raise DelegationError( "Attempted to get the '%s' trait of %s instance, " "but its '%s' delegate does not have the trait defined." % ( name, class_of( object ), self._delegate ) ) #---------------------------------------------------------------------------- # Return an object delegate's value for a specified trait: # (for the case where the delegate is a method) #---------------------------------------------------------------------------- def getattr_method ( self, object, name, value ): delegate = self.delegate( object ) try: return getattr( delegate, self.name( object, name ) ) except: if delegate is None: if value is not Undefined: return value raise DelegationError( "Attempted to get the '%s' trait of %s instance, " "but its '%s' delegate is not defined." % ( name, class_of( object ), self._delegate ) ) else: raise DelegationError( "Attempted to get the '%s' trait of %s instance, " "but its '%s' delegate does not have the trait defined." % ( name, class_of( object ), self._delegate ) ) #---------------------------------------------------------------------------- # Throw an exception when a 'locked' trait is referenced: #---------------------------------------------------------------------------- def getattr_locked ( self, object, name, value ): raise AttributeError("%s instance has no attribute '%s'" % ( object.__class__.__name__, name )) #---------------------------------------------------------------------------- # Validate the value for a particular object delegate's trait: #---------------------------------------------------------------------------- def setattr ( self, object, name, value, default ): try: delegate_name = self.name( object, name ) delegate = self.delegate( object ) while True: handler = delegate._trait( delegate_name ).setter if not isinstance( handler, TraitDelegate ): break delegate = handler.delegate( delegate ) except AttributeError: if delegate is None: raise DelegationError( "Attempted to set the '%s' trait of %s instance, " "but its '%s' delegate is not defined." % ( name, class_of( object ), self._delegate ) ) else: raise DelegationError( "Attempted to set the '%s' trait of %s instance, but " "its '%s' delegate does not have any traits defined." % ( name, class_of( object ), self._delegate ) ) except: raise DelegationError( "Attempted to set the '%s' trait of %s instance, but its " "'%s' delegate does not have a trait with that name." % ( name, class_of( object ), self._delegate ) ) if self.mutate: # Modify the delegate object: try: return handler.setattr( delegate, delegate_name, value, default ) except TraitError as excp: # The exception is for the wrong object. Fix it, then pass it on: excp.set_desc( delegate._trait( delegate_name ).desc, object ) raise excp else: # Modify the original object: try: return handler.setattr( object, name, value, default ) except TraitError as excp: # Add the trait description to the exception: excp.set_desc( delegate._trait( delegate_name ).desc ) raise excp #---------------------------------------------------------------------------- # Throw an exception when a 'locked' trait is set: #---------------------------------------------------------------------------- def setattr_locked ( self, object, name, value, default ): raise TraitError("%s instance does not have a '%s' trait" % ( class_of( object ).capitalize(), name )) #---------------------------------------------------------------------------- # Get the base trait for a particular object delegate's trait: #---------------------------------------------------------------------------- def base_trait ( self, object, name ): try: delegate = self.delegate( object ) while True: trait = delegate._trait( self.name( object, name ) ) handler = trait.setter if not isinstance( handler, TraitDelegate ): break delegate = handler.delegate( delegate ) return trait except AttributeError: if delegate is None: raise DelegationError( "Attempted to get the underlying '%s' trait of a " "%s instance, but its '%s' delegate is not defined." % ( name, object.__class__.__name__, self._delegate ) ) else: raise DelegationError( "Attempted to get the underlying '%s' trait of a " "%s instance, but its '%s' delegate does not have any " "traits defined." % ( name, object.__class__.__name__, self._delegate ) ) except: raise DelegationError( "Attempted to get the underlying '%s' trait of a " "%s instance, but its '%s' delegate does not have a " "trait with that name." % ( name, object.__class__.__name__, self._delegate ) ) #------------------------------------------------------------------------------- # 'TraitDelegateSynched' class: #------------------------------------------------------------------------------- class TraitDelegateSynched ( TraitDelegate ): def __init__ ( self, delegate = None, mutate_or_prefix = False ): self.original_setattr = self.setattr TraitDelegate.__init__( self, delegate, mutate_or_prefix ) if delegate is not None: self.getattr = self.getattr_init self.setattr = self.setattr_init #---------------------------------------------------------------------------- # Decide which type of attribute getter to use the very first time this # trait is used to get the trait's value: #---------------------------------------------------------------------------- def getattr_init ( self, object, name, value ): self.delegate_init( object ) return self.getattr( object, name, value ) #---------------------------------------------------------------------------- # Validate the value for a particular object delegate's trait: #---------------------------------------------------------------------------- def setattr_init ( self, object, name, value, default ): self.delegate_init( object ) self.setattr( object, name, value, default ) #---------------------------------------------------------------------------- # Bind the getattr/settatr methods the first time delegation occurs: #---------------------------------------------------------------------------- def delegate_init ( self, object ): self.get_delegate( object ) self.setattr = self.original_setattr if self.getattr != self.getattr_method: self.getattr = self.getattr_synched if not self.mutate: self.setattr = self.setattr_synched #---------------------------------------------------------------------------- # Return an object delegate's value for a specified trait: # (for the case where the delegate is an attribute) #---------------------------------------------------------------------------- def getattr_synched ( self, object, name, value ): delegate = self.delegate( object ) try: delegate_name = self.name( object, name ) value = getattr( delegate, delegate_name ) if not isinstance( delegate, HasTraits ): return value setattr( object, name, value ) dict = object.__dict__ delegates = dict.get( '__delegates__', None ) if delegates is None: dict[ '__delegates__' ] = delegates = {} handlers = delegates.get( self._delegate, None ) if handlers is None: delegates[ self._delegate ] = handlers = {} object.on_trait_change( self.delegate_changed, self._delegate ) handler = lambda v: object._set_trait_value( object, name, v, None ) handlers[ name ] = ( handler, delegate_name ) delegate.on_trait_change( handler, delegate_name ) return value except: return self.getattr_exception( object, name, value ) #---------------------------------------------------------------------------- # Handle one of an object's delegates being assigned a new value: #---------------------------------------------------------------------------- def delegate_changed ( self, object, trait_name, old, new ): handlers = object.__delegates__[ trait_name ] for name, info in handlers.items(): handler, delegate_name = info old.on_trait_change( handler, delegate_name, True ) new.on_trait_change( handler, delegate_name ) object._set_trait_value( object, name, getattr( new, delegate_name ), None ) #---------------------------------------------------------------------------- # Validate the value for a particular object delegate's trait: #---------------------------------------------------------------------------- def setattr_synched ( self, object, name, value, default ): TraitDelegate.setattr( self, object, name, value, default ) handlers = object.__dict__.get( '__delegates__', EmptyDict ).get( self._delegate, EmptyDict ) info = handlers.get( name, None ) if info is not None: handler, delegate_name = info self.delegate( object ).on_trait_change( handler, delegate_name, True ) del handlers[ name ] #------------------------------------------------------------------------------- # 'TraitEvent' class: #------------------------------------------------------------------------------- class TraitEvent ( TraitGetterSetter ): __traits_metadata__ = { 'type': 'event' } #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, klass = None ): if klass is None: self.validate = self.any_value_validate else: self.kind = klass kind = type( klass ) if kind is not ClassType: self.validate = self.type_validate if kind is not type: self.kind = kind try: self.coerce = CoercableFuncs[ kind ] except: self.coerce = self.identity def validate ( self, object, name, value ): if isinstance( value, self.kind ): return value raise TraitError( object, name, '%s instance' % class_of( self.kind.__name__ ), value ) def any_value_validate ( self, object, name, value ): return value def type_validate ( self, object, name, value ): try: return self.coerce( value ) except: pass if type( value ) is InstanceType: kind = class_of( value ) else: kind = repr( value ) raise TraitError( object, name, 'of %s' % str( self.kind )[1:-1], '%s (i.e. %s)' % ( str( type( value ) )[1:-1], kind ) ) def identity ( self, value ): if type( value ) is self.kind: return value raise TraitError def setattr ( self, object, name, value, default ): return object._set_event_value( object, name, self.validate( object, name, value ), default ) def getattr ( self, object, name, value ): raise AttributeError( "the %s trait of %s instance is an 'event', " "which is write only" % ( name, class_of( object ) ) ) #------------------------------------------------------------------------------- # 'TraitProperty' class: #------------------------------------------------------------------------------- class TraitProperty ( TraitGetterSetter ): __traits_metadata__ = { 'type': 'property' } #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, fget = None, fset = None ): if fget is not None: self.getattr = PropertyGetWrapper( fget ) if fset is not None: self.setattr = PropertySetWrapper( fset ) self.get_editor = self._get_editor def setattr ( self, object, name, value, default ): raise AttributeError( "the %s trait of %s instance is read only" % ( name, class_of( object ) ) ) def getattr ( self, object, name, value ): raise AttributeError( "the %s trait of %s instance is write only" % ( name, class_of( object ) ) ) def _get_editor ( self, trait ): return trait_editors().TraitEditorText( evaluate = True, auto_set = False ) #------------------------------------------------------------------------------- # 'PropertySetWrapper' class: #------------------------------------------------------------------------------- class PropertySetWrapper: def __init__ ( self, handler ): self.handler = handler if sys.version_info[0] >= 3: argcount = handler.__code__.co_argcount else: argcount = handler.func_code.co_argcount self.__call__ = getattr( self, 'call_%d' % argcount ) def call_0 ( self, object, trait_name, value, default ): return self.handler() def call_1 ( self, object, trait_name, value, default ): return self.handler( object ) def call_2 ( self, object, trait_name, value, default ): return self.handler( object, value ) def call_3 ( self, object, trait_name, value, default ): return self.handler( object, trait_name, value ) #------------------------------------------------------------------------------- # 'PropertyGetWrapper' class: #------------------------------------------------------------------------------- class PropertyGetWrapper: def __init__ ( self, handler ): self.handler = handler if sys.version_info[0] >= 3: argcount = handler.__code__.co_argcount else: argcount = handler.func_code.co_argcount self.__call__ = getattr( self, 'call_%d' % argcount ) def call_0 ( self, object, trait_name, default ): return self.handler() def call_1 ( self, object, trait_name, default ): return self.handler( object ) def call_2 ( self, object, trait_name, default ): return self.handler( object, trait_name )
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,346
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/traits102/traits.py
#------------------------------------------------------------------------------- # # Define a 'traits' mix-in class that allows other classes to easily define # 'type-checked' and/or 'delegated' traits for their instances. # # Note: A 'trait' is a synonym for 'property', but is used instead of the # word 'property' to differentiate it from the Python language 'property' # feature. # # Written by: David C. Morrill # # Date: 06/21/2002 # # Symbols defined: Trait # HasTraits # HasDynamicTraits # Disallow # ReadOnly # DefaultPythonTrait # # (c) Copyright 2002 by Enthought, Inc. # #------------------------------------------------------------------------------- # # To use the 'HasTraits' class, you must do two things: # # 1) Make 'HasTraits' one of the base classes for the class which is to have # traits. # # 2) Define a '__traits__' class attribute for the class which is a # dictionary whose keys are the desired trait names, and whose values # are one of the following: # - default_value # - ( default_value, other_value_2, other_value_3, ... ) # - Trait( ... ) # - TraitDelegate( ... ) # #------------------------------------------------------------------------------- # # The following is an example of a class which defines several traits: # # class MyClass ( other_class, traits.HasTraits ): # # __traits__ = { # 'an_int': -1, # 'color': [ 'red', 'blue', 'yellow' ], # 'foo': Trait( None, complex_test ), # 'sine': Trait( 0.0, traits.TraitRange( -1.0, 1.0 ) ), # 'window': [ None, wx.wxWindow ], # 'anything': Trait( 'nothing', traits.AnyValue ), # 'combo': [ 1, 'hello', wx.wxWindow ], # 'size': Trait( 'small', TraitPrefixList( [ # 'small', 'medium', 'large' ] ) ) # } # # def combo_changed ( self, old_value, new_value ): # ... rest of notifier definition # # ... rest of class definition... # # 'MyClass' defines these traits: # - an_int: Must be an integer, and has a default value of -1. # - color: Must be one of the strings: 'red', 'blue', 'yellow', and has # a default value of 'red'. # - foo: Must have a valid value accepted by the 'complex_test' # function, and has a default value of 'None'. # - sine: Must be a float in the range from -1.0 to 1.0, and has a # default value of 0.0. # - window: Must be an instance of the wx.wxWindow class or None, and # has a default value of 'None'. # - anything: Can have any type of value. Its default value is the string # 'nothing' # - combo: Must be either the number 1, the string 'hello', or an # instance of the wx.wxWindow class. The default value is 1. # The 'combo_changed' method will be called each time the # trait is successfully assigned a new value. # - size: Must be one of the strings 'small', 'medium', or 'large' (or # any non-ambiguous prefix, such as 's', 'smal', 'me', ...). # The default value is 'small'. If the user assigns an # abbreviation, the full value will be assigned to the trait. # # There are many more types and variations on traits available. Refer to # the documentation for more details. # #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- # Imports: #------------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function # confidence medium from __future__ import nested_scopes import sys if sys.version_info[0] >= 3: ClassType = type InstanceType = type from types import MethodType, FunctionType else: from types import MethodType, FunctionType, InstanceType, ClassType from .trait_base import SequenceTypes, Undefined, Self, trait_editors, \ class_of, TraitNotifier from .trait_errors import TraitError, DelegationError from .trait_handlers import TraitHandler, TraitReadOnly, TraitInstance, \ TraitFunction, TraitType, TraitEnum, TraitComplex, \ TraitMap, TraitString, AnyValue, TraitThisClass from .trait_delegates import TraitGetterSetter, TraitDelegate from .trait_notifiers import InstanceTraitNotifier, ClassTraitNotifier #------------------------------------------------------------------------------- # Constants: #------------------------------------------------------------------------------- import sys if sys.version_info[0] >= 3: PY2 = False long = int unicode = str else: PY2 = True ConstantTypes = ( int, long, float, complex, str, unicode, type(None)) PythonTypes = ( str, unicode, int, long, float, complex, list, tuple, dict, type, FunctionType, MethodType, ClassType, InstanceType, type(None) ) TypeTypes = ( str, unicode, int, long, float, complex, list, tuple, dict, bool ) ClassTypes = ( type, ClassType ) CallableTypes = ( FunctionType, MethodType ) CopyTypes = ( list, dict ) #------------------------------------------------------------------------------- # Create a custom class on the fly. Taken from six.py #------------------------------------------------------------------------------- def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {}) #------------------------------------------------------------------------------- # 'Trait' class: #------------------------------------------------------------------------------- class Trait: #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, default_value, *value_type, **keywords ): setter = None is_getter_setter = isinstance( default_value, TraitGetterSetter ) if is_getter_setter: getter = default_value default_value = Undefined else: getter = self if (len( value_type ) == 0) and (type( default_value ) in SequenceTypes): default_value, value_type = default_value[0], default_value if len( value_type ) == 0: if is_getter_setter: setter = getter elif isinstance( default_value, Trait ): dic = default_value.__dict__.copy() dic.update( keywords ) keywords = dic elif isinstance( default_value, TraitHandler ): setter = default_value default_value = None else: typeValue = type( default_value ) if typeValue is ClassType: if default_value is TraitThisClass: setter = TraitThisClass() default_value = None else: setter = TraitInstance( default_value ) default_value = None elif typeValue is InstanceType: setter = TraitInstance( default_value.__class__ ) elif typeValue is str: setter = TraitString( keywords ) elif typeValue in TypeTypes: setter = TraitType( typeValue ) elif type( typeValue ) is TypeType: setter = TraitInstance( default_value ) default_value = None else: setter = TraitInstance( default_value.__class__ ) else: enum = [] other = [] map = {} self.do_list( value_type, enum, map, other ) if ((default_value is None) and ((len( enum ) == 1) and (enum[0] is None)) and ((len( other ) == 1) and isinstance( other[0], TraitInstance ))): enum = [] if len( enum ) > 0: other.append( TraitEnum( enum ) ) if len( map ) > 0: other.append( TraitMap( map ) ) if len( other ) == 0: setter = TraitHandler() elif len( other ) == 1: setter = other[0] if isinstance( setter, TraitGetterSetter ): getter = setter elif isinstance( setter, Trait ): dic = setter.__dict__.copy() dic.update( keywords ) dic[ 'default_value' ] = default_value keywords = dic elif ((default_value is None) and isinstance( setter, TraitInstance )): setter.allow_none() else: setter = TraitComplex( other ) # Save the results as traits: self.default_value = default_value self.getter = getter self.setter = setter # Copy all the metadata into the trait definition: for name, value in keywords.items(): setattr( self, name, value ) # If the setter has any metadata, copy it also: if ((setter is not None) and (getattr( setter, 'metadata', None ) is not None)): for name, value in setter.metadata().items(): setattr( self, name, value ) #---------------------------------------------------------------------------- # Return 'None' for undefined traits of the Trait object: #---------------------------------------------------------------------------- def __getattr__ ( self, name ): if name[0:2] == '__': raise AttributeError("%s instance has no attribute '%s'" % ( self.__class__.__name__, name )) return None #---------------------------------------------------------------------------- # Determine the correct TraitHandler for each item in a list: #---------------------------------------------------------------------------- def do_list ( self, list, enum, map, other ): for item in list: if item in PythonTypes: other.append( TraitType( item ) ) else: typeItem = type( item ) if typeItem in ConstantTypes: enum.append( item ) elif typeItem in SequenceTypes: self.do_list( item, enum, map, other ) elif typeItem is dict: map.update( item ) elif typeItem in CallableTypes: other.append( TraitFunction( item ) ) elif item is TraitThisClass: other.append( TraitThisClass() ) elif (isinstance( item, TraitHandler ) or isinstance( item, TraitGetterSetter ) or isinstance( item, Trait )): other.append( item ) elif typeItem in ClassTypes: other.append( TraitInstance( item ) ) else: other.append( TraitHandler() ) #---------------------------------------------------------------------------- # Default handler for initializing trait values: #---------------------------------------------------------------------------- def getattr ( self, object, name, value ): if value is Self: return object if type( value ) not in CopyTypes: return object.__setattr__( name, value ) if type( value ) is list: return object.__setattr__( name, value[:] ) return object.__setattr__( name, value.copy() ) #---------------------------------------------------------------------------- # Return the trait editor associated with this trait: #---------------------------------------------------------------------------- def get_editor ( self ): if self.editor is None: try: self.editor = self.setter.get_editor( self ) except: pass return self.editor #------------------------------------------------------------------------------- # 'PythonTrait' class: #------------------------------------------------------------------------------- class PythonTrait ( Trait ): #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self ): self.default_value = None self.getter = self self.setter = self #---------------------------------------------------------------------------- # Default handler for initializing trait values: #---------------------------------------------------------------------------- def getattr ( self, object, name, value ): raise AttributeError("%s instance has no attribute '%s'" % ( object.__class__.__name__, name )) #---------------------------------------------------------------------------- # Validate the value for a particular object delegate's trait: #---------------------------------------------------------------------------- def setattr ( self, object, name, value, default ): object.__dict__[ name ] = value return value #------------------------------------------------------------------------------- # 'MappedTrait' class: #------------------------------------------------------------------------------- class MappedTrait ( Trait ): #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self ): self.default_value = None self.getter = self self.setter = AnyValue #---------------------------------------------------------------------------- # Default handler for initializing trait values: #---------------------------------------------------------------------------- def getattr ( self, object, name, value ): getattr( object, name[:-1] ) return object.__dict__[ name ] #------------------------------------------------------------------------------- # Create singleton-like instances (so users don't have to): #------------------------------------------------------------------------------- Disallow = TraitDelegate() # Disallow getting and/or setting a trait ReadOnly = Trait( Undefined, TraitReadOnly() ) # Read-only trait DefaultPythonTrait = PythonTrait() # Trait w/standard Python semantics # This special trait is only for internal use: TheMappedTrait = MappedTrait() # Create the (unique) mapped trait #------------------------------------------------------------------------------- # 'SimpleTest' class: #------------------------------------------------------------------------------- class SimpleTest: def __init__ ( self, value ): self.value = value def __call__ ( self, test ): return test == self.value #------------------------------------------------------------------------------- # 'HasTraits' class: #------------------------------------------------------------------------------- class HasTraits: #---------------------------------------------------------------------------- # Define default traits that mimic standard Python behavior: #---------------------------------------------------------------------------- __traits__ = { '*': DefaultPythonTrait } #---------------------------------------------------------------------------- # Initialize the trait values of an object (optional): #---------------------------------------------------------------------------- def __init__ ( self, **traits ): for name, value in traits.items(): setattr( self, name, value ) #--------------------------------------------------------------------------- # Handle a trait or attribute being deleted: #--------------------------------------------------------------------------- def __delattr__ ( self, name ): try: del self.__dict__[ name ] self.__getattr__( name ) except KeyError: return #---------------------------------------------------------------------------- # Handle fetching an undefined trait or attribute: # # Note: This code is written 'strangely' in order to optimize the case of # delegated traits, which are the worst case scenario for # traits. Simplifying the code may therefore have a negative # performance impact on this important sub-case. #---------------------------------------------------------------------------- def __getattr__ ( self, name ): try: trait = self.__traits__[ name ] getattr = trait.getter.getattr except (AttributeError, KeyError): trait = self._trait( name ) getattr = trait.getter.getattr try: return getattr( self, name, trait.default_value ) except DelegationError as excp: raise DelegationError(excp) except TraitError as excp: raise TraitError('%s %s' % ( str( excp )[:-1], 'as the default value. The trait must be assigned a ' 'valid value before being used.' )) #---------------------------------------------------------------------------- # Handle setting a trait or normal attribute: #---------------------------------------------------------------------------- def __setattr__ ( self, name, value ): try: trait = self.__traits__[ name ] return trait.setter.setattr( self, name, value, trait.default_value ) except (AttributeError, KeyError): trait = self._trait( name ) try: return trait.setter.setattr( self, name, value, trait.default_value ) except TraitError as excp: excp.set_desc( trait.desc ) raise TraitError(excp) except TraitError as excp: excp.set_desc( trait.desc ) raise TraitError(excp) #---------------------------------------------------------------------------- # Return the string representation of an object with traits: #---------------------------------------------------------------------------- def __call__ ( self, showHelp = 0 ): names = self._trait_names() if len( names ) == 0: return '' result = [] pad = max( [ len( x ) for x in names ] ) + 1 maxval = 78 - pad names.sort() for name in names: try: value = repr( getattr( self, name ) ).replace( '\n', '\\n' ) if len( value ) > maxval: value = '%s...%s' % ( value[: (maxval - 2) // 2 ], value[ -((maxval - 3) // 2): ] ) except: value = '<undefined>' lname = (name + ':').ljust( pad ) if showHelp: result.append( '%s %s\n The value must be %s.' % ( lname, value, self._base_trait( name ).setter.info() ) ) else: result.append( '%s %s' % ( lname, value ) ) print('\n'.join( result )) #---------------------------------------------------------------------------- # Shortcut for setting object traits: #---------------------------------------------------------------------------- def set ( self, **traits ): for name, value in traits.items(): setattr( self, name, value ) return self #---------------------------------------------------------------------------- # Reset some or all of an object's traits to their default values: #---------------------------------------------------------------------------- def reset_traits ( self, traits = None ): unresetable = [] if traits is None: traits = self._trait_names() for name in traits: try: delattr( self, name ) except AttributeError: unresetable.append( name ) return unresetable #---------------------------------------------------------------------------- # Set the object's traits based upon those of another object: #---------------------------------------------------------------------------- def clone_traits ( self, other, traits = None ): unassignable = [] if traits is None: traits = self._trait_names() for name in traits: try: setattr( self, name, getattr( other, name ) ) except: unassignable.append( name ) return unassignable #--------------------------------------------------------------------------- # Return a list of all trait names which match a set of metadata: #--------------------------------------------------------------------------- def traits ( self, **metadata ): result = [] for meta_name, meta_eval in metadata.items(): if type( meta_eval ) is not FunctionType: metadata[ meta_name ] = SimpleTest( meta_eval ) for name in self._trait_names(): trait = self._trait( name ) for meta_name, meta_eval in metadata.items(): if not meta_eval( getattr( trait, meta_name ) ): break else: result.append( name ) return result #---------------------------------------------------------------------------- # Edit the object's traits: #---------------------------------------------------------------------------- def edit_traits ( self, traits = None ): trait_editors().TraitSheetDialog( self, traits ) #---------------------------------------------------------------------------- # Configure the object's traits: #---------------------------------------------------------------------------- def configure_traits ( self, filename = None, edit = True, traits = None ): if filename is not None: fd = None try: fd = open( filename, 'rb' ) if sys.version_info[0] >= 3: import pickle self.clone_traits( pickle.Unpickler( fd ).load() ) else: import cPickle self.clone_traits( cPickle.Unpickler( fd ).load() ) except: if fd is not None: fd.close() if edit: try: clone = self.__class__() clone.clone_traits( self ) except: clone = None app = trait_editors().TraitSheetApp( self, traits ) if (not app.save_ok) and (clone is not None): self.clone_traits( clone ) elif (filename is not None) and app.save_ok: fd = None try: fd = open( filename, 'wb' ) if sys.version_info[0] >= 3: import pickle pickle.Pickler( fd, True ).dump( self ) else: import cPickle cPickle.Pickler( fd, True ).dump( self ) except: if fd is not None: fd.close() return False return True #---------------------------------------------------------------------------- # Return the list of editable traits: #---------------------------------------------------------------------------- def editable_traits ( self ): try: # Use the object's specified editable traits: return self.__editable_traits__ except: # Otherwise, derive it from all of the object's traits: names = self._trait_names() names.sort() return names #---------------------------------------------------------------------------- # Add a new trait: #---------------------------------------------------------------------------- def add_trait ( self, name, trait ): self.__traits__[ name ] = trait # If it is a trait 'class' definition, rebuild the class list: if name[-1:] == '*': self._init_class_list() #---------------------------------------------------------------------------- # Return the definition of a specified trait: #---------------------------------------------------------------------------- def get_trait ( self, name ): return self._trait( name ) #---------------------------------------------------------------------------- # Synchronize the value of two traits: #---------------------------------------------------------------------------- def sync_trait ( self, trait_name, object, alias = None, mutual = True ): if alias is None: alias = trait_name self.on_trait_change( lambda value: setattr( object, alias, value ), trait_name ) if mutual: object.on_trait_change( lambda value: setattr( self, trait_name, value ), alias ) #---------------------------------------------------------------------------- # Add/Remove a handler for a specified trait being changed: # # If no trait_name is specified, the handler will be invoked for any trait # change. #---------------------------------------------------------------------------- def on_trait_change ( self, handler, trait_name = None, remove = False ): trait_name = trait_name or 'anytrait' dict = self.__dict__ notifiers = dict.get( TraitNotifier, None ) # Handle a trait notifier being removed: if remove: if notifiers is not None: notifiers.remove( handler, trait_name ) return # Handle a trait notifier being added: if notifiers is None: dict[ TraitNotifier ] = notifiers = InstanceTraitNotifier( self, self.__class__.__dict__.get( TraitNotifier ) ) notifiers.reset_trait_value( self ) notifiers.add( handler, trait_name ) #--------------------------------------------------------------------------- # Allow trait change notifications to be deferred to later or be # processed immediately: #--------------------------------------------------------------------------- def defer_trait_change ( self, defer = True ): self._object_notifier().defer_trait_change( self, defer ) #--------------------------------------------------------------------------- # Get the object or class level notifier manager: #--------------------------------------------------------------------------- def _object_notifier ( self ): notifier = self.__dict__.get( TraitNotifier ) if notifier is not None: return notifier return self._class_notifier() #---------------------------------------------------------------------------- # Return the class-level notifier for a specific trait: #---------------------------------------------------------------------------- def _notifier_for ( self, name ): return self._class_notifier().notifier_for( name ) #---------------------------------------------------------------------------- # Return the class-level event notifier for a specific trait: #---------------------------------------------------------------------------- def _event_notifier_for ( self, name ): return self._class_notifier().event_notifier_for( name ) #---------------------------------------------------------------------------- # Return the object's class-level notifier manager: #---------------------------------------------------------------------------- def _class_notifier ( self ): cls = self.__class__ notifier = cls.__dict__.get( TraitNotifier ) if notifier is None: notifier = ClassTraitNotifier( cls ) setattr( cls, TraitNotifier, notifier ) return notifier #---------------------------------------------------------------------------- # Set up the class-level 'set trait value' handler: #---------------------------------------------------------------------------- def _reset_trait_value ( self ): self._object_notifier().reset_trait_value( self ) #---------------------------------------------------------------------------- # Change an object trait: #---------------------------------------------------------------------------- def _set_trait_value ( self, object, name, value, default ): self._reset_trait_value() return self._set_trait_value( object, name, value, default ) #---------------------------------------------------------------------------- # Change an object 'event' trait: #---------------------------------------------------------------------------- def _set_event_value ( self, object, name, value, default ): self._reset_trait_value() return self._set_event_value( object, name, value, default ) #---------------------------------------------------------------------------- # Get the list of all valid trait names: #---------------------------------------------------------------------------- def _trait_names ( self ): return [ x for x in self.__traits__.keys() if (x[-1:] not in '*_') and (x[:1] != '_') ] #---------------------------------------------------------------------------- # Get the Trait object for a specified trait: #---------------------------------------------------------------------------- def _trait ( self, name ): # Get the information associated with the trait: trait = self.__traits__.get( name ) if isinstance( trait, Trait ): return trait # If the trait does not have any information yet, get it: traits = self.__traits__ if trait is None: # Get the list of trait 'classes': # Note: If the class list has not been constructed yet, then build # it, and also 'inherit' traits from superclasses. This is why # the recursive call to '_trait' is made, since the traits # dictionary may have been updated by inheritance. class_list = traits.get( '**' ) if class_list is None: self._init_class_list() return self._trait( name ) # Handle the special case of 'mapped' traits: if name[-1:] == '_': trait = self._trait( name[:-1] ) setter = trait.setter if isinstance( setter, TraitDelegate ): traits[ name ] = trait return trait if isinstance( setter, TraitHandler ) and setter.is_mapped(): try: traits[ name ] = trait = Trait( setter.map.get( trait.default_value ), setter.reverse() ) except: traits[ name ] = trait = TheMappedTrait return trait # Find the first (i.e. longest) matching class prefix in the list: for cls in class_list: # If it does, map it to the same trait as that class: if cls == name[ : len( cls ) ]: trait = traits[ cls + '*' ] break # else trait is not in the right form, convert it: else: trait = Trait( trait ) # Cache the trait information for the next time: traits[ name ] = trait # Return the trait information (a 'Trait' object): return trait #---------------------------------------------------------------------------- # Get the base Trait object for a specified trait: #---------------------------------------------------------------------------- def _base_trait ( self, name ): trait = self._trait( name ) if isinstance( trait.setter, TraitDelegate ): return trait.setter.base_trait( self, name ) return trait #---------------------------------------------------------------------------- # Initialize the class list for all currently defined traits: #---------------------------------------------------------------------------- def _init_class_list ( self ): # Get the current set of traits: traits = self.__traits__ # Make sure that trait inheritance has already been performed: class_list = traits.get( '**' ) if class_list is None: # Get all traits defined by subclasses that implement HasTraits: traits = {} self._inherit( self.__class__, traits ) # Now replace our class traits dictionary with the updated one: self.__class__.__traits__ = traits # Initialize the class list: class_list = [] # Make sure there is a definition for the 'undefined' trait: trait = traits.get( '*' ) if trait is None: traits[ '*' ] = trait = DefaultPythonTrait elif not isinstance( trait, Trait ): traits[ '*' ] = trait = Trait( trait ) # Always make traits that look like '__system__' traits have # the standard Python behavior: traits[ '__*' ] = DefaultPythonTrait # Now check every defined trait: for key, trait in traits.items(): # If the trait name ends in a 'wildcard' (*), add it: if key[-1:] == '*': class_list.append( key[:-1] ) if not isinstance( trait, Trait ): traits[ key ] = Trait( trait ) # Make sure the prefixes are sorted from longest to shortest: class_list.sort( key=lambda x: len( x ), reverse=True ) # Save the result: traits[ '**' ] = class_list #---------------------------------------------------------------------------- # Inherit traits from a specified class: #---------------------------------------------------------------------------- def _inherit ( self, cls, traits ): has_traits = (cls is HasTraits) if not has_traits: for base in cls.__bases__: has_traits |= self._inherit( base, traits ) if has_traits: traits.update( cls.__traits__ ) return has_traits #------------------------------------------------------------------------------ # 'MetaTraits' class: #------------------------------------------------------------------------------ class _MetaTraits ( type ): def __new__ ( cls, name, bases, classdict ): traits = classdict.get( '__traits__' ) for name, value in classdict.items(): if isinstance( value, Trait ): if traits is None: classdict[ '__traits__' ] = traits = {} traits[ name ] = value del classdict[ name ] return super( _MetaTraits, cls ).__new__( cls, name, bases, classdict ) #------------------------------------------------------------------------------- # 'HasObjectTraits' class: #------------------------------------------------------------------------------- class HasObjectTraits ( with_metaclass(_MetaTraits, HasTraits, object) ): pass #------------------------------------------------------------------------------- # 'HasDynamicTraits' class: #------------------------------------------------------------------------------- class HasDynamicTraits ( HasTraits ): #---------------------------------------------------------------------------- # Initialize the trait values of an object (optional): #---------------------------------------------------------------------------- def __init__ ( self, **traits ): if self.__traits__.get( '**' ) is None: self._init_class_list() self.__traits__ = self.__traits__.copy() HasTraits.__init__( self, **traits ) #------------------------------------------------------------------------------- # 'HasDynamicObjectTraits' class: #------------------------------------------------------------------------------- class HasDynamicObjectTraits ( with_metaclass(_MetaTraits, HasDynamicTraits, object) ): pass #------------------------------------------------------------------------------- # 'TraitProxy' class: #------------------------------------------------------------------------------- class TraitProxy ( HasDynamicTraits ): #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, object, *trait_names ): HasDynamicTraits.__init__( self ) self._object = object delegate = TraitDelegate( '_object', True ) for trait_name in trait_names: self.add_trait( trait_name, delegate ) def anytrait_changed ( self, trait_name, old, new ): setattr( self._object, trait_name, new ) #------------------------------------------------------------------------------- # Handle circular module dependencies: #------------------------------------------------------------------------------- from . import trait_handlers trait_handlers.Trait = Trait from . import trait_delegates trait_delegates.HasTraits = HasTraits
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,347
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/traits102/trait_handlers.py
#------------------------------------------------------------------------------- # # Define the base 'TraitHandler' class and a standard set of TraitHandler # subclasses for use with the 'traits' package. # # A trait handler mediates the assignment of values to object traits. It # verifies (through the TraitHandler's 'validate' method) that a specified # value is consistent with the object trait, and generates a 'TraitError' # exception if not. # # Written by: David C. Morrill # # Date: 06/21/2002 # # Refactored into a separate module: 07/04/2003 # # Symbols defined: TraitHandler # TraitRange # TraitType # TraitString # TraitInstance # TraitFunction # TraitEnum # TraitPrefixList # TraitMap # TraitPrefixMap # TraitMapReverse # TraitComplex # TraitReadOnly # TraitList # # (c) Copyright 2002, 2003 by Enthought, Inc. # #------------------------------------------------------------------------------- from __future__ import absolute_import, division # confidence high #------------------------------------------------------------------------------- # Imports: #------------------------------------------------------------------------------- import sys import re if sys.version_info[0] >= 3: InstanceType = type else: from types import InstanceType from .trait_base import strx, SequenceTypes, Undefined, NumericFuncs, \ StringTypes, CoercableFuncs, trait_editors, class_of from .trait_errors import TraitError from .trait_delegates import TraitEvent Trait = None # Patched by 'traits.py' once class is defined! #------------------------------------------------------------------------------- # 'TraitHandler' class (base class for all trait handlers): #------------------------------------------------------------------------------- class TraitHandler: __traits_metadata__ = { 'type': 'trait' } def validate ( self, object, name, value ): raise TraitError( "The '%s' trait of %s instance has an unknown type. " "Contact the developer to correct the problem." % ( name, class_of( object ) ) ) def setattr ( self, object, name, value, default ): return object._set_trait_value( object, name, self.validate( object, name, value ), default ) def error ( self, object, name, value ): raise TraitError( object, name, self.info(), value ) def info ( self ): return 'a legal value' def repr ( self, value ): if type( value ) is InstanceType: return 'class ' + value.__class__.__name__ return repr( value ) def is_mapped ( self ): return False def get_editor ( self, trait ): return trait_editors().TraitEditorText() def metadata ( self ): return getattr( self, '__traits_metadata__', {} ) #------------------------------------------------------------------------------- # 'TraitRange' class: #------------------------------------------------------------------------------- class TraitRange ( TraitHandler ): def __init__ ( self, low, high ): self.low = self.high = None self.range( low, high ) self.coerce, self.type_desc = NumericFuncs[ type( low ) ] def range ( self, low = None, high = None ): if low is not None: self.low = low if high is not None: self.high = high return ( self.low, self.high ) def validate ( self, object, name, value ): try: cvalue = self.coerce( value ) if (((self.low is None) or (self.low <= cvalue)) and ((self.high is None) or (self.high >= cvalue))): return cvalue except: pass self.error( object, name, self.repr( value ) ) def info ( self ): if self.low is None: if self.high is None: return self.type_desc return '%s <= %s' % ( self.type_desc, self.high ) elif self.high is None: return '%s >= %s' % ( self.type_desc, self.low ) return '%s in the range from %s to %s' % ( self.type_desc, self.low, self.high ) def get_editor ( self, trait ): auto_set = trait.auto_set if auto_set is None: auto_set = True return trait_editors().TraitEditorRange( self, cols = trait.cols or 3, auto_set = auto_set ) #------------------------------------------------------------------------------- # 'TraitString' class: #------------------------------------------------------------------------------- class TraitString ( TraitHandler ): def __init__ ( self, dic = {}, **keywords ): self.minlen = dic.get( 'minlen', None ) if sys.version_info[0] >= 3: maxintsize = sys.maxsize else: maxintsize = sys.maxint if self.minlen is None: self.minlen = max( 0, keywords.get( 'minlen', 0 ) ) self.maxlen = max( self.minlen, (dic.get( 'maxlen', 0 ) or keywords.get( 'maxlen', maxintsize )) ) self.regex = (dic.get( 'regex', '' ) or keywords.get( 'regex', '' ) ) if self.regex != '': self.match = re.compile( self.regex ).match def match ( self, value ): return True def validate ( self, object, name, value ): try: value = strx( value ) if ((self.minlen <= len( value ) <= self.maxlen) and (self.match( value ) is not None)): return value except: pass self.error( object, name, self.repr( value ) ) def info ( self ): msg = '' if sys.version_info[0] >= 3: maxintsize = sys.maxsize else: maxintsize = sys.maxint if (self.minlen != 0) and (self.maxlen != maxintsize): msg = ' between %d and %d characters long' % ( self.minlen, self.maxlen ) elif self.maxlen != maxintsize: msg = ' <= %d characters long' % self.maxlen elif self.minlen != 0: msg = ' >= %d characters long' % self.minlen if self.regex != '': if msg != '': msg += ' and' msg += (" matching the pattern '%s'" % self.regex) return 'a string' + msg #------------------------------------------------------------------------------- # 'TraitType' class: #------------------------------------------------------------------------------- class TraitType ( TraitHandler ): def __init__ ( self, aType ): if type( aType ) is not type: aType = type( aType ) self.aType = aType try: self.coerce = CoercableFuncs[ aType ] except: self.coerce = self.identity def validate ( self, object, name, value ): try: return self.coerce( value ) except: pass if type( value ) is InstanceType: kind = class_of( value ) else: kind = repr( value ) self.error( object, name, '%s (i.e. %s)' % ( str( type( value ) )[1:-1], kind ) ) def info ( self ): return 'of %s' % str( self.aType )[1:-1] def identity ( self, value ): if type( value ) is self.aType: return value raise TraitError def get_editor ( self, trait ): return trait_editors().TraitEditorText( evaluate = True ) #------------------------------------------------------------------------------- # 'TraitInstance' class: #------------------------------------------------------------------------------- class TraitInstance ( TraitHandler ): def __init__ ( self, aClass, or_none = 0 ): if aClass is None: aClass, or_none = or_none, aClass if type( aClass ) is InstanceType: aClass = aClass.__class__ self.aClass = aClass if or_none is None: self.allow_none() def allow_none ( self ): self.validate = self.validate_none self.info = self.info_none def validate ( self, object, name, value ): if isinstance( value, self.aClass ): return value self.validate_failed( object, name, value ) def info ( self ): return class_of( self.aClass.__name__ ) def validate_none ( self, object, name, value ): if isinstance( value, self.aClass ) or (value is None): return value self.validate_failed( object, name, value ) def info_none ( self ): return class_of( self.aClass.__name__ ) + ' or None' def validate_failed ( self, object, name, value ): kind = type( value ) if kind is InstanceType: msg = 'class %s' % value.__class__.__name__ else: msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) ) self.error( object, name, msg ) def get_editor ( self, trait ): return trait_editors().TraitEditorInstance() #------------------------------------------------------------------------------- # 'TraitThisClass' class: #------------------------------------------------------------------------------- class TraitThisClass ( TraitInstance ): def __init__ ( self, or_none = 0 ): if or_none is None: self.allow_none() def validate ( self, object, name, value ): if isinstance( value, object.__class__ ): return value self.validate_failed( object, name, value ) def validate_none ( self, object, name, value ): if isinstance( value, object.__class__ ) or (value is None): return value self.validate_failed( object, name, value ) def info ( self ): return 'an instance of the same type as the receiver' def info_none ( self ): return 'an instance of the same type as the receiver or None' #------------------------------------------------------------------------------- # 'TraitClass' class: #------------------------------------------------------------------------------- class TraitClass ( TraitHandler ): def __init__ ( self, aClass ): if type( aClass ) is InstanceType: aClass = aClass.__class__ self.aClass = aClass def validate ( self, object, name, value ): try: if type( value ) == str: value = value.strip() col = value.rfind( '.' ) if col >= 0: module_name = value[:col] class_name = value[col + 1:] module = sys.modules.get( module_name ) if module is None: exec( 'import ' + module_name ) module = sys.modules[ module_name ] value = getattr( module, class_name ) else: value = globals().get( value ) if issubclass( value, self.aClass ): return value except: pass self.error( object, name, self.repr( value ) ) def info ( self ): return 'a subclass of ' + self.aClass.__name__ #------------------------------------------------------------------------------- # 'TraitFunction' class: #------------------------------------------------------------------------------- class TraitFunction ( TraitHandler ): def __init__ ( self, aFunc ): self.aFunc = aFunc def validate ( self, object, name, value ): try: return self.aFunc( object, name, value ) except TraitError: self.error( object, name, self.repr( value ) ) def info ( self ): try: return self.aFunc.info except: if self.aFunc.__doc__: return self.aFunc.__doc__ return 'a legal value' #------------------------------------------------------------------------------- # 'TraitEnum' class: #------------------------------------------------------------------------------- class TraitEnum ( TraitHandler ): def __init__ ( self, *values ): if (len( values ) == 1) and (type( values[0] ) in SequenceTypes): values = values[0] self.values = values def validate ( self, object, name, value ): if value in self.values: return value self.error( object, name, self.repr( value ) ) def info ( self ): return ' or '.join( [ repr( x ) for x in self.values ] ) def get_editor ( self, trait ): return trait_editors().TraitEditorEnum( self, cols = trait.cols or 3 ) #------------------------------------------------------------------------------- # 'TraitPrefixList' class: #------------------------------------------------------------------------------- class TraitPrefixList ( TraitHandler ): def __init__ ( self, *values ): if (len( values ) == 1) and (type( values[0] ) in SequenceTypes): values = values[0] self.values = values self.values_ = values_ = {} for key in values: values_[ key ] = key def validate ( self, object, name, value ): try: if value not in self.values_: match = None n = len( value ) for key in self.values: if value == key[:n]: if match is not None: match = None break match = key if match is None: self.error( object, name, self.repr( value ) ) self.values_[ value ] = match return self.values_[ value ] except: self.error( object, name, self.repr( value ) ) def info ( self ): return (' or '.join( [ repr( x ) for x in self.values ] ) + ' (or any unique prefix)') def get_editor ( self, trait ): return trait_editors().TraitEditorEnum( self, cols = trait.cols or 3 ) #------------------------------------------------------------------------------- # 'TraitMap' class: #------------------------------------------------------------------------------- class TraitMap ( TraitHandler ): def __init__ ( self, map ): self.map = map def validate ( self, object, name, value ): try: if value in self.map: return value except: pass self.error( object, name, self.repr( value ) ) def setattr ( self, object, name, value, default ): old_value = object.__dict__.get( name, Undefined ) value = self.validate( object, name, value ) if value != old_value: object.__dict__[ name + '_' ] = self.map[ value ] object._set_trait_value( object, name, value, default ) return value def info ( self ): keys = [ repr( x ) for x in self.map.keys() ] keys.sort() return ' or '.join( keys ) def reverse ( self ): if not hasattr( self, '_reverse' ): self._reverse = TraitMapReverse( self.map ) return self._reverse def is_mapped ( self ): return True def get_editor ( self, trait ): return trait_editors().TraitEditorEnum( self, cols = trait.cols or 3 ) #------------------------------------------------------------------------------- # 'TraitPrefixMap' class: #------------------------------------------------------------------------------- class TraitPrefixMap ( TraitMap ): def __init__ ( self, map ): self.map = map self._map = _map = {} for key in map.keys(): _map[ key ] = key def validate ( self, object, name, value ): try: if not value in self._map: match = None n = len( value ) for key in self.map.keys(): if value == key[:n]: if match is not None: match = None break match = key if match is None: self.error( object, name, self.repr( value ) ) self._map[ value ] = match return self._map[ value ] except: self.error( object, name, self.repr( value ) ) def setattr ( self, object, name, value, default ): value = self.validate( object, name, value ) old_value = object.__dict__.get( name, Undefined ) if value != old_value: object.__dict__[ name + '_' ] = self.map[ value ] object._set_trait_value( object, name, value, default ) return value def info ( self ): return TraitMap.info( self ) + ' (or any unique prefix)' #------------------------------------------------------------------------------- # 'TraitMapReverse' class: #------------------------------------------------------------------------------- class TraitMapReverse ( TraitHandler ): def __init__ ( self, map ): self.map = rmap = {} for key, value in map.items(): if value not in rmap: rmap[ value ] = [ key ] else: rmap[ value ].append( key ) def validate ( self, object, name, value ): try: if value in self.map: return value except: pass self.error( object, name, self.repr( value ) ) def setattr ( self, object, name, value, default ): value = self.validate( object, name, value ) object.__dict__[ name ] = value if object.__dict__.get( name[:-1], Undefined ) not in self.map[ value ]: object._set_trait_value( object, name[:-1], self.map[ value ][0], Undefined ) return value def info ( self ): keys = [ repr( x ) for x in self.map.keys() ] keys.sort() return ' or '.join( keys ) #------------------------------------------------------------------------------- # 'TraitComplex' class: #------------------------------------------------------------------------------- class TraitComplex ( TraitHandler ): def __init__ ( self, *handlers ): if (len( handlers ) == 1) and (type( handlers[0] ) in SequenceTypes): handlers = handlers[0] self.handlers = [] for handler in handlers: if isinstance( handler, Trait ): handler = handler.setter if handler.is_mapped(): if not hasattr( self, 'map_handlers' ): self.map_handlers = [] self.setattr = self.mapped_setattr self.info = self.mapped_info self.is_mapped = self.mapped_is_mapped self.map_handlers.append( handler ) else: self.handlers.append( handler ) def validate ( self, object, name, value ): for handler in self.handlers: try: return handler.validate( object, name, value ) except TraitError: pass self.error( object, name, self.repr( value ) ) def info ( self ): return ' or '.join( [ x.info() for x in self.handlers ] ) def mapped_setattr ( self, object, name, value, default ): for handler in self.handlers: try: result = handler.setattr( object, name, value, default ) object.__dict__[ name + '_' ] = result return result except TraitError: pass for handler in self.map_handlers: try: return handler.setattr( object, name, value, default ) except TraitError: pass self.error( object, name, self.repr( value ) ) def mapped_info ( self ): return ' or '.join( [ x.info() for x in self.handlers + self.map_handlers ] ) def mapped_is_mapped ( self ): return True def get_editor ( self, trait ): the_editors = [ x.get_editor( trait ) for x in self.handlers ] if self.is_mapped(): the_editors.extend( [ x.get_editor( trait ) for x in self.map_handlers ] ) text_editor = trait_editors().TraitEditorText count = 0 editors = [] for editor in the_editors: if issubclass( text_editor, editor.__class__ ): count += 1 if count > 1: continue editors.append( editor ) editors.sort( lambda x, y: cmp( id( x.__class__ ), id( y.__class__ ) ) ) return trait_editors().TraitEditorComplex( editors ) #------------------------------------------------------------------------------- # 'TraitAny' class: #------------------------------------------------------------------------------- class TraitAny ( TraitHandler ): def validate ( self, object, name, value ): return value def info ( self ): return 'any value' #------------------------------------------------------------------------------- # Create a singleton-like instance (so users don't have to): #------------------------------------------------------------------------------- AnyValue = TraitAny() # Allow any value for a trait #------------------------------------------------------------------------------- # 'TraitReadOnly' class: #------------------------------------------------------------------------------- class TraitReadOnly ( TraitHandler ): def validate ( self, object, name, value ): no_key = (name not in object.__dict__) if no_key: return value if ((value is not Undefined) and (no_key or (getattr( object, name ) is Undefined))): return value raise TraitError( "The '%s' trait of %s instance is read only." % ( name, class_of( object ) ) ) def info ( self ): return 'any value' #------------------------------------------------------------------------------- # 'TraitList' class: #------------------------------------------------------------------------------- class TraitList ( TraitHandler ): info_trait = None if sys.version_info[0] >= 3: maxintsize = sys.maxsize else: maxintsize = sys.maxint def __init__ ( self, trait = None, min_items = None, max_items = None, items = True ): if trait is None: trait = AnyValue if not isinstance( trait, Trait ): trait = Trait( trait ) self.item_trait = trait self.min_items = min_items or 0 self.max_items = max_items or maxintsize self.items = items def validate ( self, object, name, value ): if (isinstance( value, list ) and (self.min_items <= len( value ) <= self.max_items)): if self.items and (not hasattr( object, name + '_items' )): if self.info_trait is None: self.info_trait = TraitEvent( 0 ) object.add_trait( name + '_items', self.info_trait ) list_value = TraitListObject( self, object, name, self.items ) list_value[:] = value return list_value self.error( object, name, self.repr( value ) ) def info ( self ): if self.min_items == 0: if self.max_items == maxintsize: size = 'of items' else: size = ' of at most %d items' % self.max_items else: if self.max_items == maxintsize: size = ' of at least %d items' % self.min_items else: size = ' of from %d to %d items' % ( self.min_items, self.max_items ) return 'a list%s which are %s' % ( size, self.item_trait.setter.info() ) def get_editor ( self, trait ): return trait_editors().TraitEditorList( self, trait.rows or 5 ) #------------------------------------------------------------------------------- # 'TraitListObject' class: #------------------------------------------------------------------------------- class TraitListObject ( list ): def __init__ ( self, trait, object, name, items ): self.trait = trait self.object = object self.name = name self.name_items = None if items: self.name_items = name + '_items' def __setitem__ ( self, key, value ): try: list.__setitem__( self, key, self.trait.item_trait.setter.validate( self.object, self.name, value ) ) if self.name_items is not None: setattr( self.object, self.name_items, 0 ) except TraitError as excp: excp.set_prefix( 'Each element of the' ) raise excp def __setslice__ ( self, i, j, values ): delta = len( values ) - (min( j, len( self ) ) - max( 0, i )) if self.trait.min_items <= (len( self ) + delta) <= self.trait.max_items: try: object = self.object name = self.name trait = self.trait.item_trait validate = trait.setter.validate list.__setslice__( self, i, j, [ validate( object, name, value ) for value in values ] ) if self.name_items is not None: setattr( self.object, self.name_items, 0 ) return except TraitError as excp: excp.set_prefix( 'Each element of the' ) raise excp self.len_error( len( self ) + delta ) def __delitem__ ( self, key ): if self.trait.min_items <= (len( self ) - 1): list.__delitem__( self, key ) if self.name_items is not None: setattr( self.object, self.name_items, 0 ) return self.len_error( len( self ) - 1 ) def __delslice__ ( self, i, j ): delta = min( j, len( self ) ) - max( 0, i ) if self.trait.min_items <= (len( self ) - delta): list.__delslice__( self, i, j ) if self.name_items is not None: setattr( self.object, self.name_items, 0 ) return self.len_error( len( self ) - delta ) def append ( self, value ): if self.trait.min_items <= (len( self ) + 1) <= self.trait.max_items: try: list.append( self, self.trait.item_trait.setter.validate( self.object, self.name, value ) ) if self.name_items is not None: setattr( self.object, self.name_items, 0 ) return except TraitError as excp: excp.set_prefix( 'Each element of the' ) raise excp self.len_error( len( self ) + 1 ) def extend ( self, xlist ): if (self.trait.min_items <= (len( self ) + len( xlist )) <= self.trait.max_items): object = self.object name = self.name validate = self.trait.item_trait.setter.validate try: list.extend( self, [ validate( object, name, value ) for value in xlist ] ) if self.name_items is not None: setattr( self.object, self.name_items, 0 ) return except TraitError as excp: excp.set_prefix( 'The elements of the' ) raise excp self.len_error( len( self ) + len( xlist ) ) def remove ( self, value ): if self.trait.min_items < len( self ): list.remove( self, value ) if self.name_items is not None: setattr( self.object, self.name_items, 0 ) else: self.len_error( len( self ) - 1 ) def len_error ( self, len ): raise TraitError( "The '%s' trait of %s instance must be %s, " "but you attempted to change its length to %d element%s." % ( self.name, class_of( self.object ), self.trait.info(), len, 's'[ len == 1: ] ) )
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,348
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/traits102/trait_sheet.py
#------------------------------------------------------------------------------- # # Define the set of abstract classes needed to define the notion of a # graphical 'trait sheet' for use with the 'traits' module. # # Note: This module provides abstract definitions only. Concrete implementaions # are GUI toolkit specific and are provided by the following modules: # # - wxtrait_sheet.py: wxPython # - tktrait_sheet.py: Tkinter # # Written by: David C. Morrill # # Date: 10/07/2002 # # (c) Copyright 2002 by Enthought, Inc. # #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- # Imports: #------------------------------------------------------------------------------- from __future__ import absolute_import, division # confidence high from .trait_base import SequenceTypes from .trait_handlers import TraitPrefixList from .traits import Trait, HasTraits, ReadOnly from string import ascii_lowercase, ascii_uppercase #------------------------------------------------------------------------------- # Trait definitions: #------------------------------------------------------------------------------- none_or_string = Trait( None, None, str ) true_trait = Trait( 'true', { 'true': 1, 't': 1, 'yes': 1, 'y': 1, 'on': 1, 1: 1, 'false': 0, 'f': 0, 'no': 0, 'n': 0, 'off': 0, 0: 0 } ) style_trait = Trait( None, None, TraitPrefixList( 'simple', 'custom', 'text', 'readonly' ) ) object_trait = Trait( None, None, HasTraits ) basic_sequence_types = [ list, tuple ] #------------------------------------------------------------------------------- # 'TraitSheetHandler' class: #------------------------------------------------------------------------------- class TraitSheetHandler: #---------------------------------------------------------------------------- # Set the initial position of a trait sheet: #---------------------------------------------------------------------------- def position ( self, trait_sheet, object ): return 0 #---------------------------------------------------------------------------- # Notification that a trait sheet is being closed: #---------------------------------------------------------------------------- def close ( self, trait_sheet, object ): return 1 #---------------------------------------------------------------------------- # Notification that a trait sheet has modified a trait of its # associated object: #---------------------------------------------------------------------------- def changed ( self, object, trait_name, new_value, old_value, is_set ): pass #---------------------------------------------------------------------------- # Create extra content to add to the trait sheet: #---------------------------------------------------------------------------- def init ( self, trait_sheet, object ): return None # Create a default TraitSheetHandler: default_trait_sheet_handler = TraitSheetHandler() #------------------------------------------------------------------------------- # 'TraitEditor' class: #------------------------------------------------------------------------------- class TraitEditor: #---------------------------------------------------------------------------- # Interactively edit the 'trait_name' trait of 'object' in a # self-contained dialog: #---------------------------------------------------------------------------- # def popup_editor ( self, object, trait_name, description, handler, # parent = None ): # return 0 #---------------------------------------------------------------------------- # Create a simple, imbeddable text view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def text_editor ( self, object, trait_name, description, handler, parent ): raise NotImplementedError #---------------------------------------------------------------------------- # Create a simple, imbeddable view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def simple_editor ( self, object, trait_name, description, handler, parent ): raise NotImplementedError #---------------------------------------------------------------------------- # Create a custom, imbeddable view of the current value of the # 'trait_name' trait of 'object': #---------------------------------------------------------------------------- def custom_editor ( self, object, trait_name, description, handler, parent ): return self.simple_editor( object, trait_name, description, handler, parent ) #---------------------------------------------------------------------------- # Set a specified object trait value: #---------------------------------------------------------------------------- def set ( self, object, trait_name, value, handler ): original_value = getattr( object, trait_name ) setattr( object, trait_name, value ) handler.changed( object, trait_name, value, original_value, True ) #---------------------------------------------------------------------------- # Return the text representation of the 'trait' trait of 'object': #---------------------------------------------------------------------------- def str ( self, object, trait_name ): return self.str_value( getattr( object, trait_name ) ) #---------------------------------------------------------------------------- # Return the text representation of a specified object trait value: #---------------------------------------------------------------------------- def str_value ( self, value ): return str( value ) #------------------------------------------------------------------------------- # 'TraitMonitor' class: #------------------------------------------------------------------------------- class TraitMonitor: #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, object, trait_name, control, on_trait_change_handler ): self.control = control self.on_trait_change_handler = on_trait_change_handler object.on_trait_change( self.on_trait_change, trait_name ) #---------------------------------------------------------------------------- # Handle an object trait being changed: #---------------------------------------------------------------------------- def on_trait_change ( self, object, trait_name, new ): try: self.on_trait_change_handler( self.control, new ) except: # NOTE: This code handles the case where a trait editor window has # been destroyed, but we don't know about it. Attempting to update the # now non-existent control generates an exception. We catch it here, # then disconnect the handler so it doesn't happen again: object.on_trait_change( self.on_trait_change, trait_name, remove = True ) #------------------------------------------------------------------------------- # 'TraitGroupItem' class: #------------------------------------------------------------------------------- class TraitGroupItem ( HasTraits ): __traits__ = { 'name': none_or_string, 'label': none_or_string, 'style': style_trait, 'editor': Trait( None, None, TraitEditor ), 'object': object_trait } #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, *value, **traits ): HasTraits.__init__( self, **traits ) if (len( value ) == 1) and (type( value[0] ) in SequenceTypes): value = value[0] for data in value: if type( data ) is str: if self.name is None: self.name = data elif self.label is None: self.label = data else: self.style = data elif isinstance( data, TraitEditor ): self.editor = data else: self.object = data #--------------------------------------------------------------------------- # Create a clone of the object: #--------------------------------------------------------------------------- def clone ( self ): clone = self.__class__() clone.clone_traits( self ) return clone #---------------------------------------------------------------------------- # Return the user interface label for a specified object's trait: #---------------------------------------------------------------------------- def label_for ( self, object ): return ( self.label or (self.object or object)._base_trait( self.name ).label or self.user_name_for( self.name ) ) #---------------------------------------------------------------------------- # Return a 'user-friendly' name for a specified trait: #---------------------------------------------------------------------------- def user_name_for ( self, name ): name = name.replace( '_', ' ' ).capitalize() result = '' last_lower = 0 for c in name: if (c in ascii_uppercase) and last_lower: result += ' ' last_lower = (c in ascii_lowercase) result += c return result #---------------------------------------------------------------------------- # Return the TraitEditor object for a specified object's trait: #---------------------------------------------------------------------------- def editor_for ( self, object ): return (self.editor or (self.object or object)._base_trait( self.name ).editor) #------------------------------------------------------------------------------- # 'TraitGroup' class: #------------------------------------------------------------------------------- class TraitGroup ( HasTraits ): __traits__ = { 'values': ReadOnly, 'label': none_or_string, 'style': style_trait, 'orientation': Trait( 'vertical', TraitPrefixList( 'vertical', 'horizontal' ) ), 'show_border': true_trait, 'show_labels': true_trait, 'object': object_trait } #---------------------------------------------------------------------------- # Initialize the object: #---------------------------------------------------------------------------- def __init__ ( self, *values, **traits ): HasTraits.__init__( self, **traits ) _values = [] for value in values: if (isinstance( value, TraitGroup ) or isinstance( value, TraitGroupItem )): _values.append( value ) else: _values.append( TraitGroupItem( value ) ) self.values = _values #--------------------------------------------------------------------------- # Create a clone of the object: #--------------------------------------------------------------------------- def clone ( self ): clone = self.__class__() clone.clone_traits( self, [ 'label', 'style', 'orientation', 'show_border', 'show_labels' ] ) clone_values_append = clone.values.append for value in self.values: clone_values_append( value.clone() ) return clone #--------------------------------------------------------------------------- # Handle merging a TraitGroup with other editable traitsL #--------------------------------------------------------------------------- def __add__ ( self, other ): return merge_trait_groups( self, other ) #------------------------------------------------------------------------------- # 'TraitGroupList' class: #------------------------------------------------------------------------------- class TraitGroupList ( list ): #--------------------------------------------------------------------------- # Handle merging a TraitGroup with other editable traitsL #--------------------------------------------------------------------------- def __add__ ( self, other ): return merge_trait_groups( self, other ) #------------------------------------------------------------------------------- # 'MergeTraitGroups' class: #------------------------------------------------------------------------------- class MergeTraitGroups: #--------------------------------------------------------------------------- # Merge two trait groups: #--------------------------------------------------------------------------- def __call__ ( self, group1, group2 ): return getattr( self, '%s_%s' % ( self._kind( group1 ), self._kind( group2 ) ) )( group1, group2 ) #--------------------------------------------------------------------------- # Return a string describing the kind of group specified: #--------------------------------------------------------------------------- def _kind ( self, group ): if isinstance( group, TraitGroup ): return 'tg' if (isinstance( group, TraitGroupList ) or (type( group ) in basic_sequence_types)): if (len( group ) == 0) or (type( group[0] ) is str): return 'strl' return 'tgl' return 'str' #--------------------------------------------------------------------------- # Merge one TraitGroup into another: #--------------------------------------------------------------------------- def _merge ( self, dest_group, src_group ): values = dest_group.values n = len( values ) for value in src_group.values: if isinstance( value, TraitGroupItem ) or (value.label is None): values.append( value ) else: label = value.label for i in range( n ): merge_item = values[i] if (isinstance( merge_item, TraitGroup ) and (label == merge_item.label)): self._merge( merge_item, value ) break else: values.append( value ) #--------------------------------------------------------------------------- # Handle the various combinations of arguments: #--------------------------------------------------------------------------- def str_str ( self, group1, group2 ): return TraitGroupList( [ group1, group2 ] ) def str_strl ( self, group1, group2 ): return TraitGroupList( [ group1 ] + group2 ) def str_tg ( self, group1, group2 ): return TraitGroupList( [ TraitGroup( group1, label = 'Main' ), group2 ] ) def str_tgl ( self, group1, group2 ): return TraitGroupList( [ TraitGroup( group1, label = 'Main' ) ] + group2 ) def strl_str ( self, group1, group2 ): return TraitGroupList( group1 + [ group2 ] ) def strl_strl ( self, group1, group2 ): return TraitGroupList( group1 + group2 ) def strl_tg ( self, group1, group2 ): return TraitGroupList( [ TraitGroup( label = 'Main', *group1 ), group2 ] ) def strl_tgl ( self, group1, group2 ): return TraitGroupList( [ TraitGroup( label = 'Main', *group1 ) ] + group2 ) def tg_str ( self, group1, group2 ): return TraitGroupList( [ group1, TraitGroup( group2, label = 'Other' ) ] ) def tg_strl ( self, group1, group2 ): return TraitGroupList( [ group1, TraitGroup( label = 'Other', *group2 ) ] ) def tg_tg ( self, group1, group2 ): return self.tgl_tgl( [ group1 ], [ group2 ] ) def tg_tgl ( self, group1, group2 ): return self.tgl_tgl( [ group1 ], group2 ) def tgl_str ( self, group1, group2 ): return TraitGroupList( [ group1, TraitGroup( group2, name = 'Other' ) ] ) def tgl_strl ( self, group1, group2 ): return TraitGroupList( [ group1, TraitGroup( name = 'Other', *group2 ) ] ) def tgl_tg ( self, group1, group2 ): return self.tgl_tgl( group1, [ group2 ] ) def tgl_tgl ( self, group1, group2 ): result = TraitGroupList() page = 0 for group in group1: group = group.clone() if group.label is None: page += 1 group.label = 'Page %d' % page result.append( group ) for group in group2: label = group.label if label is None: page += 1 group.label = 'Page %d' % page result.append( group ) else: for merge_group in result: if label == merge_group.label: self._merge( merge_group, group ) break else: result.append( group ) return result # Create a singleton instance which can be used to merge trait groups: merge_trait_groups = MergeTraitGroups() """ A trait_element is: - A string (specifying a trait name) - A tuple containing 1 to 3 elements: - 1 string: trait name - 2 strings: trait name and UI label - 1 string and 1 TraitEditor: trait name and editor - 2 strings and 1 TraitEditor: trait name, UI label and editor A Trait Sheet description can be: - A string (edit the single trait whose name is specified by the string) - A list of trait_elements: (simple non-tabbed trait sheet, vertically oriented, two-column using UI labels and simple editor) - A TraitGroup (simple non-tabbed trait sheet using layout specified by the TraitGroup contents) - A list of TraitGroup's (Each TraitGroup defines a notebook tab, the contents of which are defined by the TraitGroup's contents) Each element passed to a TraitGroup constructor can be: - A trait_element (defines a single trait to be editor) - A TraitGroup (defines a nested group of traits to be edited) Examples of Trait Sheet descriptions: [ 'foo', 'bar', 'baz' ] [ TraitGroup( 'foo', 'bar', 'baz', label = 'Main' ), TraitGroup( 'color', 'style', 'weight', label = 'Border' ) ] [ TraitGroup( ( 'foo', 'Enter Foo' ), ( 'bar', 'Enter Bar', TraitEditBar() ), 'baz', label = 'Main' ), TraitGroup( 'color', 'style', 'weight', label = 'Border' ) ] [ TraitGroup( TraitGroup( 'foo', 'bar', 'baz', label = 'Group 1' ), TraitGroup( 'color', 'style', 'weight', label = 'Line', border = 'no', orientation = 'horizontal', show_labels = 'no', style = 'custom' ), label = 'Main' ), """
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,349
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/pattern.py
from __future__ import absolute_import, division # confidence medium from stsci.tools import fileutil, wcsutil from . import imtype, buildmask from .exposure import Exposure import numpy as np from . import drutil #from pydrizzle import __version__ __version__ = '6.xxx' from stsci.tools.fileutil import RADTODEG, DEGTORAD DEFAULT_PARITY = [[1.0,0.0],[0.0,1.0]] yes = True no = False ################# # # # Custom Parameter Dictionary Class # # ################# class ParDict(dict): def __init__(self): dict.__init__(self) def __str__(self): if self['xsh'] == None: _xsh = repr(self['xsh']) else: _xsh = '%0.4f'%self['xsh'] if self['ysh'] == None: _ysh = repr(self['ysh']) else: _ysh = '%0.4f'%self['ysh'] # Insure that valid strings are available for # 'driz_mask' and 'single_driz_mask' if self['driz_mask'] == None: _driz_mask = '' else: _driz_mask = self['driz_mask'] if self['single_driz_mask'] == None: _sdriz_mask = '' else: _sdriz_mask = self['single_driz_mask'] _str = '' _str += 'Parameters for input chip: '+self['data']+'\n' _str += ' Shifts: %s %s\n'%(_xsh,_ysh) _str += ' Output size: %d %d \n'%(self['outnx'],self['outny']) _str += ' Rotation: %0.4g deg. Scale: %0.4f \n'%(self['rot'],self['scale']) _str += ' pixfrac: %0.4f Kernel: %s Units: %s\n'%(self['pixfrac'],self['kernel'],self['units']) _str += ' ORIENTAT: %0.4g deg. Pixel Scale: %0.4f arcsec/pix\n'%(self['orient'],self['outscl']) _str += ' Center at RA: %0.9g Dec: %0.9f \n'%(self['racen'],self['deccen']) _str += ' Output product: %s\n'%self['output'] _str += ' Coeffs: '+self['coeffs']+' Geomode: '+self['geomode']+'\n' _str += ' XGeoImage : '+self['xgeoim']+'\n' _str += ' YGeoImage : '+self['ygeoim']+'\n' _str += ' Single mask file: '+_sdriz_mask+'\n' _str += ' Final mask file : '+_driz_mask+'\n' _str += ' Output science : '+self['outdata']+'\n' _str += ' Output weight : '+self['outweight']+'\n' _str += ' Output context : '+self['outcontext']+'\n' _str += ' Exptime -- total: %0.4f single: %0.4f\n'%(self['texptime'],self['exptime']) _str += ' start: %s end: %s\n'%(repr(self['expstart']),repr(self['expend'])) _str += ' Single image products-- output: %s\n'%self['outsingle'] _str += ' weight: %s \n '%self['outsweight'] _str += ' Blot output: %s \n'%self['outblot'] _str += ' Size of original image to blot: %d %d \n'%(self['blotnx'],self['blotny']) _str += '\n' return _str class Pattern(object): """ Set default values for these to be overridden by instrument specific class variables as necessary. """ IDCKEY = 'IDCTAB' PARITY = {'detector':DEFAULT_PARITY} REFDATA = {'detector':[[1.,1.],[1.,1.]]} NUM_IMSET = 3 # Number of extensions in an IMSET PA_KEY = 'PA_V3' DETECTOR_NAME = 'detector' COPY_SUFFIX = '.orig' # suffix to use for filename of copy def __init__(self, filename, output=None, pars=None): # Set these up for use... self.members = [] self.pars = pars self.output = output self.name = filename # Set default value, to be reset as needed by sub-class self.nmembers = 1 self.nimages = 1 # Extract bit values to be used for this instrument self.bitvalue = self.pars['bits'] # Set IDCKEY, if specified by user... if self.pars['idckey'] == '': self.idckey = self.IDCKEY else: self.idckey = self.pars['idckey'] self.idcdir = self.pars['idcdir'] # Keyword which provides PA_V3 value; ie., orientation of # telescope at center axis relative to North. # Each instrument has their own pre-defined keyword; mostly, PA_V3 self.pa_key = self.PA_KEY self.exptime = None self.binned = 1 # These attributes are used for keeping track of the reference # image used for computing the shifts, and the shifts computed # for each observation, respectively. self.offsets = None self.v2com = None self.v3com = None # Read in Primary Header to reduce the overhead of getting # keyword values and setup PyFITS object # as self.header and self.image_handle # image_handle = self.getHeaderHandle() if self.pars['section'] != None: # If a section was specified, check the length of the list # for the number of groups specified... self.nmembers = len(self.pars['section']) # Determine type of input image and syntax needed to read data self.imtype = imtype.Imtype(filename,handle=self.image_handle, dqsuffix=self.pars['dqsuffix']) # Keep file I/O localized to same method/routine if image_handle: image_handle.close() if self.header and self.DETECTOR_NAME in self.header: self.detector = self.header[self.DETECTOR_NAME] else: self.detector = 'detector' def getHeaderHandle(self): """ Sets up the PyFITS image handle and Primary header as self.image_handle and self.header. When Pattern being used for output product, filename will be set to None and this returns None for header and image_handle. """ _numsci = 0 if self.name: _handle = fileutil.openImage(self.name,mode='readonly',memmap=self.pars['memmap']) _fname,_extn = fileutil.parseFilename(self.name) _hdr = _handle['PRIMARY'].header.copy() # Count number of SCI extensions for _fext in _handle: if 'extname' in _fext.header and _fext.header['extname'] == 'SCI': _numsci += 1 if _extn and _extn > 0: # Append correct extension/chip/group header to PRIMARY... for _card in fileutil.getExtn(_handle,_extn).header.ascard: _hdr.ascard.append(_card) else: # Default to None _handle = None _hdr = None # Set attribute to point to these products self.image_handle = None self.header = _hdr self.nmembers = _numsci return _handle def closeHandle(self): """ Closes image_handle. """ if self.image_handle: self.image_handle.close() #print 'Closing file handle for image: ',self.name self.image_handle = None def addMembers(self,filename): """ Build rootname for each SCI extension, and create the mask image from the DQ extension. It would then append a new Exposure object to 'members' list for each extension. """ self.detector = detector = str(self.header[self.DETECTOR_NAME]) if self.pars['section'] == None: self.pars['section'] = [None] * self.nmembers extver_indx = list(range(1,self.nmembers+1)) group_indx = list(range(1,self.nmembers+1)) else: extver_indx = self.pars['section'] group_indx = [1] # Build rootname here for each SCI extension... for i in range(self.nmembers): _extver = self.pars['section'][i] _sciname = self.imtype.makeSciName(i+1,section=_extver) _dqname = self.imtype.makeDQName(extver_indx[i]) _extname = self.imtype.dq_extname # Build mask files based on input 'bits' parameter values _masklist = [] _masknames = [] # # If we have a valid bits value... # Creat the name of the output mask file _maskname = buildmask.buildMaskName(_dqname,extver_indx[i]) _masknames.append(_maskname) # Create the actual mask file now... outmask = buildmask.buildMaskImage(_dqname,self.bitvalue[0],_maskname,extname=_extname,extver=extver_indx[i]) _masklist.append(outmask) # # Check to see if a bits value was provided for single drizzling... # Different bits value specified for single drizzle step # create new filename for single_drizzle mask file _maskname = _maskname.replace('final_mask','single_mask') _masknames.append(_maskname) # Create new mask file with different bit value. outmask = buildmask.buildMaskImage(_dqname,self.bitvalue[1],_maskname,extname=_extname,extver=extver_indx[i]) # Add new name to list for single drizzle step _masklist.append(outmask) _masklist.append(_masknames) self.members.append(Exposure(_sciname, idckey=self.idckey, dqname=_dqname, mask=_masklist, pa_key=self.pa_key, parity=self.PARITY[detector], idcdir=self.pars['idcdir'], group_indx = group_indx[i], binned=self.binned, handle=self.image_handle,extver=i+1,exptime=self.exptime[0], mt_wcs=self.pars['mt_wcs'])) def setBunit(self,value=None): """Set the bunit attribute for each member. Default value defined in Exposure class is 'ELECTRONS' If a new value is given as input, it will override the default. """ if value is not None: for member in self.members: member.set_bunit(value) def getProductCorners(self): """ Compute the product's corner positions based on input exposure's corner positions. """ _prodcorners = [] for member in self.members: _prodcorners += member.corners['corrected'].tolist() self.product.corners['corrected'] = np.array(_prodcorners,dtype=np.float64) def buildProduct(self,filename,output): """ Create Exposure object for meta-chip product after applying distortion model to input members. """ #output_wcs = self._buildMetachip(psize=_psize,orient=_rot) output_wcs = self.buildMetachip() # For each member, update WCSLIN to account for chip-to-chip # offsets, [X/Y]DELTA in refpix. # Update the final output size with the meta-chip size self.size = (output_wcs.naxis1,output_wcs.naxis2) # Need to compute shape for dither product here based on output_shapes # and reference pixels for each observation. self.product = Exposure(self.rootname,wcs=output_wcs, new=yes) self.product.exptime = self.exptime # Preserve the original WCS as WCSLIN... self.product.geometry.wcslin = self.product.geometry.wcs.copy() # Combine all corner positions for each input into product's corner self.getProductCorners() def buildMetachip(self,update=yes): """ Build up the new metashape based on the corrected size and position for each Exposure. (Pattern method) """ # Build an initial value for size of meta-chip _geo_ref = self.members[0].geometry _wcs_ref = _geo_ref.wcslin _model_ref = _geo_ref.model # Get pscale from linearized WCS pscale = _wcs_ref.pscale _shape = (_wcs_ref.naxis1,_wcs_ref.naxis2,pscale) # Build new WCS for output metachip here # It will be based on the undistorted version of members[0] WCS meta_wcs = _wcs_ref.copy() # Now, check to see if members have subarray offsets, but was # taken as a full image... if len(self.members) > 1 and _geo_ref.wcs.subarray == yes: for member in self.members: member.geometry.wcslin.subarray = no member.geometry.model.refpix['centered'] = no #Determine range of pixel values for corrected image # Using verbose=yes will return additional info on range calculation meta_range = drutil.getRange(self.members,meta_wcs,verbose=no) # Update WCS based on new size xsize = int(meta_range['xsize']) ysize = int(meta_range['ysize']) meta_wcs.naxis1 = xsize meta_wcs.naxis2 = ysize cen = ((xsize/2.),(ysize/2.)) meta_wcs.recenter() _nref = meta_range['nref'] for member in self.members: member.corners['corrected'] -= (_nref[0]/2.,_nref[1]/2.) if update: # Shifts position of CRPIX to reflect new size # Instead of being centered on (0.,0.) like the original guess. # CRVAL for this position remains the same, though, as it is still # the same point in the sky/image. # # We need this in order to correctly handle WFPC2 data where # the XDELTA/YDELTA values are computed relative to the image center # already, so we don't need this correction. if not _model_ref.refpix['centered']: _nref = meta_range['nref'] for member in self.members: _refpix = member.geometry.model.refpix # Update XDELTA,YDELTA (zero-point of coefficients) to adjust for # uncentered output _refpix['XDELTA'] -= _nref[0]/2. _refpix['YDELTA'] -= _nref[1]/2. # # TROLL computation not needed, as this get corrected for both # in 'recenter()' and in 'wcsfit'... # WJH 19-Feb-2004 # # Do a full fit between the input WCS and meta_wcs now... # # Rigorously compute the orientation changes from WCS # information using algorithm provided by R. Hook from WDRIZZLE. abxt,cdyt = drutil.wcsfit(self.members[0].geometry, meta_wcs) #Compute the rotation between input and reference from fit coeffs. _delta_rot = RADTODEG(np.arctan2(abxt[1],cdyt[0])) _crpix = (meta_wcs.crpix1 + abxt[2], meta_wcs.crpix2 + cdyt[2]) meta_wcs.crval1,meta_wcs.crval2 = meta_wcs.xy2rd(_crpix) # Insure output WCS has exactly orthogonal CD matrix #meta_wcs.rotateCD(meta_wcs.orient+_delta_rot) meta_wcs.updateWCS(orient=meta_wcs.orient+_delta_rot) return meta_wcs def transformMetachip(self,ref): """ This method transforms this Exposure's WCS to be consistent with the provided reference WCS 'ref'. This method only operates on the product MetaChip, with the original WCS being preserved as 'wcslin'. Primarily, this transformation involves scaling and rotating the chip to match the reference frame values. Also, any specified size for the output frame would replace the default rotated/scaled size. All rotations would be about the center, and the reference pixel position gets shifted to accomodate this rotation. """ # Start by getting product WCS # Use values from 'wcslin' as they will keep track of the # default situation _in_wcs = self.product.geometry.wcslin _out_wcs = self.product.geometry.wcs # Make sure that wcslin has all the WCS information if _in_wcs.rootname == 'New': # Copy the original WCS data into 'wcslin' to preserve the values _in_wcs = self.product.geometry.wcs.copy() #_dcrpix = (_in_wcs.naxis1/2.- _in_wcs.crpix1,_in_wcs.naxis2/2.- _in_wcs.crpix2) # Check to see if there is any rotation needed if ref.orient != None: _angle = _in_wcs.orient - ref.wcs.orient _ref_orient = ref.wcs.orient else: _angle = 0. _ref_orient = _in_wcs.orient # Apply any pixel scale changes to delta_crpix and size of axes if ref.psize != None: _scale = _in_wcs.pscale / ref.wcs.pscale _ref_pscale = ref.wcs.pscale else: _scale = 1.0 _ref_pscale = _in_wcs.pscale if ref.wcs.naxis1 != 0 and ref.wcs.naxis2 != 0: _naxis1 = ref.wcs.naxis1 _naxis2 = ref.wcs.naxis2 # Delta between same-scaled frames _delta_cens = (ref.wcs.naxis1/_scale - _in_wcs.naxis1,ref.wcs.naxis2/_scale - _in_wcs.naxis2) else: _delta_cens = (0.,0.) _naxis1 = _in_wcs.naxis1 _naxis2 = _in_wcs.naxis2 _delta_cen = (_naxis1 - _in_wcs.naxis1, _naxis2 - _in_wcs.naxis2) # Rotate axes as necessary if _angle != 0.: # Rotate axes to find default rotated size and new center _xrange,_yrange = drutil.getRotatedSize(self.product.corners['corrected'],_angle) _range = [_xrange[1] - _xrange[0] + _delta_cens[0]/2.,_yrange[1] - _yrange[0] + _delta_cens[1]/2.] #_dcrpix = ((_xrange[0] + _xrange[1])/2.,(_yrange[0] + _yrange[1])/2.) else: _range = [_naxis1,_naxis2] # Now update CD matrix and reference position _out_wcs.naxis1 = int(_range[0]) _out_wcs.naxis2 = int(_range[1]) _crpix = (_in_wcs.crpix1 + _delta_cen[0]/2., _in_wcs.crpix2 + _delta_cen[1]/2.) if _scale != 0.: _out_wcs.updateWCS(orient=_ref_orient,pixel_scale=_ref_pscale) _delta_crpix = (_naxis1 - _out_wcs.naxis1, _naxis2 - _out_wcs.naxis2) else: _out_wcs.rotateCD(_ref_orient) _delta_crpix = (0.,0.) _out_wcs.crpix1 = _crpix[0] - _delta_crpix[0]/2. _out_wcs.crpix2 = _crpix[1] - _delta_crpix[1]/2. _out_wcs.recenter() """ # Update the size and rotated position of reference pixel _cen = (_out_wcs.naxis1/2.,_out_wcs.naxis2/2.) _out_wcs.crval1,_out_wcs.crval2 = _out_wcs.xy2rd(_cen) _out_wcs.crpix1 = _cen[0] _out_wcs.crpix2 = _cen[1] """ def getShifts(self,member,wcs): """ Translate the delta's in RA/Dec for each image's shift into a shift of the undistorted image. Input: member - Exposure class for chip wcs - PyDrizzle product WCS object Output: [xsh, ysh, rot, scale] - Returns the full set of shift information as a list """ if self.pars['delta_ra'] == 0.0 and self.pars['delta_dec'] == 0.0: xsh = 0.0 ysh = 0.0 drot = 0.0 dscale = 1.0 else: # translate delta's into shifts ncrpix1,ncrpix2 = wcs.rd2xy((wcs.crval1+self.pars['delta_ra'], wcs.crval2+self.pars['delta_dec'])) xsh = ncrpix1 - wcs.crpix1 ysh = ncrpix2 - wcs.crpix2 drot= -self.pars['rot'] dscale = self.pars['scale'] return [xsh,ysh,drot,dscale] # This method would use information from the product class and exposure class # to build the complete parameter list for running the 'drizzle' task def buildPars(self,ref=None): """This method would build a list of parameters to run 'drizzle' one a single input image. The reference image info 'ref' will be passed as a SkyField object. The default output reference frame will be passed as 'def_wcs' for comparison to the user's selected object 'ref'. """ # pars contains the drizzle parameters for each input(in order): # data,outdata,outnx,outny,scale,xsh,ysh,rot parlist = [] # Now define the default WCS for this product def_wcs = self.product.geometry.wcslin.copy() if ref != None: # Extract the total exptime for this output object if ref.exptime == None: _texptime = self.exptime else: _texptime = ref.exptime # # Initialize the SkyField Object with the # user settings. _field = ref # Transform self.product.geometry.wcs to match ref.wcs #self.transformMetachip(_field) _out_wcs = self.product.geometry.wcs.copy() #if not ref.dither or ref.dither == None: # Check to make sure we have a complete WCS # if not, fill in using the product's default WCS _field.mergeWCS(_out_wcs) _field.wcs.rootname=def_wcs.rootname self.product.geometry.wcslin = _out_wcs self.product.geometry.wcs = _field.wcs.copy() # Set reference for computing shifts to be transformed # product's WCS ref_wcs = _field.wcs else: # # Single observation case... # # Define a default WCS ref_wcs = self.product.geometry.wcslin.copy() # Update product WCS to reflect default value again self.product.geometry.wcs = ref_wcs.copy() # Extract the total exposure time _texptime = self.product.exptime # Insure that reference WCS is properly centered in order to # correctly fit to each input WCS ref_wcs.recenter() # Convert shifts into delta RA/Dec values for member in self.members: in_wcs = member.geometry.wcslin in_wcs_orig = member.geometry.wcs #_delta_rot = in_wcs.orient - ref_wcs.orient #_scale = ref_wcs.pscale / in_wcs.pscale # Compute offset based on shiftfile values xsh,ysh,drot,dscale = self.getShifts(member,ref_wcs) # Rigorously compute the orientation changes from WCS # information using algorithm provided by R. Hook from WDRIZZLE. abxt,cdyt = drutil.wcsfit(member.geometry, ref_wcs) # Compute the rotation between input and reference from fit coeffs. _delta_roty = _delta_rot = RADTODEG(np.arctan2(abxt[1],cdyt[0])) _delta_rotx = RADTODEG(np.arctan2(abxt[0],cdyt[1])) # Compute scale from fit to allow WFPC2 (and similar) data to be handled correctly _scale = 1./np.sqrt(abxt[0]**2 + abxt[1]**2) # Correct for additional shifts from shiftfile now _delta_x = abxt[2] _delta_y = cdyt[2] # Start building parameter dictionary for this chip parameters = ParDict() parameters['data'] = member.name parameters['output'] = self.output parameters['exposure'] = member parameters['group'] = member.group_indx parameters['instrument'] = self.instrument parameters['detector'] = self.detector parameters['driz_mask'] = member.maskname parameters['single_driz_mask'] = member.singlemaskname # Setup parameters for special cases here... parameters['outsingle'] = self.outsingle parameters['outsweight'] = self.outsweight parameters['outscontext'] = self.outscontext parameters['outblot'] = member.outblot parameters['blotnx'] = member.naxis1 parameters['blotny'] = member.naxis2 #Setup parameters for normal operations parameters['outdata'] = self.outdata parameters['outweight'] = self.outweight parameters['outcontext'] = self.outcontext parameters['outnx'] = ref_wcs.naxis1 parameters['outny'] = ref_wcs.naxis2 parameters['xsh'] = _delta_x + xsh parameters['ysh'] = _delta_y + ysh parameters['alpha'] = member.geometry.alpha parameters['beta'] = member.geometry.beta # Calculate any rotation relative to the orientation # AFTER applying ONLY the distortion coefficients without # applying any additional rotation... parameters['rot'] = _delta_rot - drot # Keep track of both the exposure information and # the combined product exposure time information. # Single exposure information will be used for 'single=yes' # header updates... parameters['exptime'] = self.exptime[0] parameters['expstart'] = self.exptime[1] parameters['expend'] = self.exptime[2] parameters['texptime'] = _texptime[0] parameters['texpstart'] = _texptime[1] parameters['texpend'] = _texptime[2] # Need to revise how this gets computed... # The pixel scale of the product corresponds to the # desired output pixel scale, and the model pscale for # the member represents the un-scaled pixel size for the input. parameters['scale'] = _scale * dscale # Parameters only used by 'wdrizzle' parameters['geomode'] = 'wcs' parameters['racen'] = ref_wcs.crval1 parameters['deccen'] = ref_wcs.crval2 parameters['orient'] = ref_wcs.orient parameters['outscl'] = ref_wcs.pscale parameters['gpar_xsh'] = member.geometry.gpar_xsh - xsh parameters['gpar_ysh'] = member.geometry.gpar_ysh - ysh parameters['gpar_rot'] = member.geometry.gpar_rot - drot # Insure that the product WCS applied to each exposure gets set member.product_wcs = ref_wcs # Set up the idcfile for use by 'drizzle' member.writeCoeffs() parameters['coeffs'] = member.coeffs parameters['plam'] = member.plam # Set up the distortion image names as parameters parameters['xgeoim'] = member.xgeoim parameters['ygeoim'] = member.ygeoim # Now pass along the remainder of the user specified parameters if self.pars['units'] != None: parameters['units'] = self.pars['units'] else: parameters['units'] = 'cps' if self.pars['in_units'] != None: parameters['in_units'] = self.pars['in_units'] else: parameters['in_units'] = 'counts' if self.pars['pixfrac'] != None: parameters['pixfrac'] = self.pars['pixfrac'] else: parameters['pixfrac'] = 1.0 if self.pars['kernel'] != None: parameters['kernel'] = self.pars['kernel'] else: parameters['kernel'] = 'square' if self.pars['wt_scl'] != None: parameters['wt_scl'] = self.pars['wt_scl'] else: parameters['wt_scl'] = 'exptime' if self.pars['fillval'] != None: parameters['fillval'] = str(self.pars['fillval']) else: parameters['fillval'] = 'INDEF' # Parameters useful for header keywords parameters['version'] = 'PyDrizzle Version '+__version__ parameters['driz_version'] = '' parameters['nimages'] = self.nimages parameters['bunit'] = member.bunit parlist.append(parameters) # Now, combine them for a complete set of pars for all exposures # in this pattern/observation. # return parlist def computeCubicCoeffs(self): """ Method for converting cubic and Trauger coefficients tables into a usable form. It also replaces 'computeOffsets' for those tables as well. """ # For each chip in the observation... _pscale1 = None for img in self.members: _chip = img.chip _detector = str(img.header[self.DETECTOR_NAME]) # scale all chips to first chip plate scale... if _pscale1 == None or img.chip == '1': _pscale1 = self.REFDATA[_detector]['psize'] _reftheta = self.REFDATA[_detector]['theta'] _v2ref = 0. _v3ref = 0. _nmembers = 0 for img in self.members: # ... get the model and type of coefficients table used... _model = img.geometry.model _ikey = img.geometry.ikey _chip = img.chip _detector = str(img.header[self.DETECTOR_NAME]) _refdata = self.REFDATA[_detector] # ... determine the plate scale and scaling factor between chips... if img.chip == '1': _pscale = _refdata['psize'] _ratio = 1.0 else: _pscale = _refdata['psize'] _ratio = _refdata['psize'] / _pscale1 # Record the plate scale for each chip's model that was used # to compute the coefficients, not the plate scale from the # image header. _model.pscale = _pscale _model.refpix['PSCALE'] = _pscale if _ikey == 'trauger': _ratio = 1. # V2REF/V3REF was not available in idc file, so we # must use our own data... _model.refpix['V2REF'] = _refdata['xoff'] _model.refpix['V3REF'] = _refdata['yoff'] else: _model.refpix['V2REF'] = _refdata['xoff'] * _pscale _model.refpix['V3REF'] = _refdata['yoff'] * _pscale # Correct the coefficients for the differences in plate scales _model.cx = _model.cx * np.array([_model.pscale/_ratio],dtype=np.float64) _model.cy = _model.cy * np.array([_model.pscale/_ratio],dtype=np.float64) _model.refpix['XREF'] = self.REFPIX['x'] _model.refpix['YREF'] = self.REFPIX['y'] # Correct the offsets for the plate scales as well... _model.refpix['XDELTA'] = _refdata['xoff'] _model.refpix['YDELTA'] = _refdata['yoff'] _model.refpix['centered'] = yes if _ikey != 'trauger': _model.refpix['V2REF'] = _model.refpix['V2REF'] / _ratio _model.refpix['V3REF'] = _model.refpix['V3REF'] / _ratio _v2ref += _model.refpix['V2REF'] _v3ref += _model.refpix['V3REF'] _nmembers += 1 def computeOffsets(self,parity=None,refchip=None): """ This version of 'computeOffsets' calculates the zero-point shifts to be included in the distortion coefficients table used by 'drizzle'. It REQUIRES a parity matrix to convert from V2/V3 coordinates into detector image X/Y coordinates. This matrix will be specific to each detector. """ vref = [] # Check to see if any chip-to-chip offsets need to be computed at all if len(self.members) == 1: refp = self.members[0].geometry.model.refpix refp['XDELTA'] = 0. refp['YDELTA'] = 0. #refp['centered'] = yes return # Set up the parity matrix here for a SINGLE chip if parity == None: # Use class defined dictionary as default parity = self.PARITY # Get reference chip information ref_model=None for member in self.members: if not refchip or refchip == int(member.chip): ref_model = member.geometry.model ref_scale = ref_model.refpix['PSCALE'] ref_v2v3 = np.array([ref_model.refpix['V2REF'],ref_model.refpix['V3REF']]) ref_theta = ref_model.refpix['THETA'] if ref_theta == None: ref_theta = 0.0 ref_pmat = np.dot(fileutil.buildRotMatrix(ref_theta), member.parity) ref_xy = (ref_model.refpix['XREF'],ref_model.refpix['YREF']) break if not ref_model: ref_scale = 1.0 ref_theta = 0.0 ref_v2v3 = [0.,0.] ref_xy = [0.,0.] ref_pmat = np.array([[1.,0.],[0.,1.0]]) # Now compute the offset for each chip # Compute position of each chip's common point relative # to the output chip's reference position. for member in self.members: in_model = member.geometry.model refp = in_model.refpix pscale = in_model.pscale memwcs = member.geometry.wcs v2v3 = np.array([in_model.refpix['V2REF'],in_model.refpix['V3REF']]) scale = refp['PSCALE'] theta = refp['THETA'] if theta == None: theta = 0.0 chipcen = ( (memwcs.naxis1/2.) + memwcs.offset_x, (memwcs.naxis2/2.) + memwcs.offset_y) """ Changed two lines below starting with '##'. The reasoning is that this function computes the offsets between the chips in an observation in model space based on a reference chip. That's why xypos shoulf be coomputed in reference chip space and offset_xy (X/YDELTA) should be chip specific. """ ##xypos = np.dot(ref_pmat,v2v3-ref_v2v3) / scale + ref_xy xypos = np.dot(ref_pmat,v2v3-ref_v2v3) / ref_scale #+ ref_xy chiprot = fileutil.buildRotMatrix(theta - ref_theta) offcen = ((refp['XREF'] - chipcen[0]), (refp['YREF'] - chipcen[1])) # Update member's geometry model with computed # reference position... #refp['XDELTA'] = vref[i][0] - v2com + chip.geometry.delta_x #refp['YDELTA'] = vref[i][1] - v3com + chip.geometry.delta_y ##offset_xy = np.dot(chiprot,xypos-offcen)*scale/ref_scale offset_xy = np.dot(chiprot,xypos)*ref_scale/scale - offcen if 'empty_model' in refp and refp['empty_model'] == True: offset_xy[0] += ref_xy[0] * scale/ref_scale offset_xy[1] += ref_xy[1] * scale/ref_scale refp['XDELTA'] = offset_xy[0] refp['YDELTA'] = offset_xy[1] # Only set centered to yes for full exposures... if member.geometry.wcs.subarray != yes: refp['centered'] = no else: refp['centered'] = yes def setNames(self,filename,output): """ Define standard name attibutes: outname - Default final output name outdata - Name for drizzle science output outsingle - Name for output for single image """ self.rootname = filename self.outname = output # Define FITS output filenames for intermediate products # to be used when 'build=no' self.outdata = fileutil.buildNewRootname(output,extn='_sci.fits') self.outweight = fileutil.buildNewRootname(output,extn='_weight.fits') self.outcontext = fileutil.buildNewRootname(output,extn='_context.fits') # Define output file names for separate output for each input self.outsingle = fileutil.buildNewRootname(filename,extn='_single_sci.fits') self.outsweight = fileutil.buildNewRootname(filename,extn='_single_wht.fits') self.outscontext = None #self.outscontext = fileutil.buildNewRootname(filename,extn='_single_ctx.fits') ######## # # User interface methods # ######## def getWCS(self): return self.members[0].getWCS() def getMember(self,memname): """ Return the class instance for the member with name memname.""" member = None for mem in self.members: if mem.name == memname: member = mem return member def getMemberNames(self): """ Return the names of all members for this Class. Output: [{self.name:[list of member names]}] """ memlist = [] for member in self.members: memlist.append(member.name) return [{self.name:memlist}] def getExptime(self): _exptime = float(self.header['EXPTIME']) if _exptime == 0.: _exptime = 1.0 if 'EXPSTART' in self.header: _expstart = float(self.header['EXPSTART']) _expend = float(self.header['EXPEND']) else: _expstart = 0. _expend = _exptime return (_exptime,_expstart,_expend) def DeltaXYtoOffset(self,delta): """ Converts provided delta(x,y) pixel offset into a delta(RA,Dec) offset in arcseconds. """ _wcs = self.product.getWCS() _geom = self.product.geometry new_rd = _geom.XYtoSky((_wcs.crpix1 - delta[0],_wcs.crpix2 - delta[1])) delta_ra = (_wcs.crval1 - new_rd[0]) * 3600. delta_dec = (_wcs.crval2 - new_rd[1]) * 3600. return (delta_ra,delta_dec)
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,350
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/pydrizzle.py
from __future__ import absolute_import, division, print_function # confidence medium from .drutil import DEFAULT_IDCDIR from stsci.tools import fileutil, wcsutil, asnutil import os, types, sys import shutil from . import arrdriz from . import outputimage from .pattern import * from .observations import * # Hackish, but not invalid from .__init__ import __version__ #import buildasn #import p_m_input from astropy.io import fits as pyfits import numpy as np yes = True # 1 no = False # 0 # default_pars is passed as a default parameter dictionary in selectInstrument. # Looks like this is not needed any more. 'default_rot' was originally 'rot'. _default_pars = {'psize':None,'default_rot':None,'idckey':None} INSTRUMENT = ["ACS","WFPC2","STIS","NICMOS","WFC3"] class _PyDrizzle: """ Program to process and/or dither-combine image(s) using (t)drizzle. To create an object named 'test' that corresponds to a drizzle product: --> test = pydrizzle.PyDrizzle(input) where input is the FULL filename of an ACS observation or ASN table. This computes all the parameters necessary for running drizzle on all the input images. Once this object is created, you can run drizzle using: --> test.run() The 'clean()' method can be used to remove files which would interfere with running Drizzle again using the 'run()' method after a product has already been created. Optional parameters: output User-specified name for output products field User-specified parameters for output image includes: psize, orient, ra, dec, shape units Units for final product: 'counts' or 'cps'(DEFAULT) section Extension/group to be drizzled: list or single FITS extension(s) or group(s) syntax ('1' or 'sci,1') or None (DEFAULT: Use all chips). kernel Specify which kernel to use in TDRIZZLE 'square'(default),'point','gaussian','turbo','tophat' pixfrac drizzle pixfrac value (Default: 1.0) idckey User-specified keyword for determining IDCTAB filename 'IDCTAB'(ACS default),'TRAUGER'(WFPC2),'CUBIC'(WFPC2) idcdir User-specified directory for finding coeffs files: 'drizzle$coeffs' (default) bits_single Specify DQ values to be considered good when drizzling with 'single=yes'. (Default: 0) bits_final Specify DQ values to be considered good when drizzling with 'single=no'. (Default: 0) updatewcs Flag whether to run makewcs on the input (Default: True) Bits parameters will be interpreted as: None - No DQ information to be used, no mask created Int - sum of DQ values to be considered good Optional Parameters for '.run()': build create multi-extension output: yes (Default) or no save keeps the individual inputs from drizzle: yes or no (Default) single drizzle to separate output for each input: yes or no (Default) blot run blot on drizzled products: yes or no (Default) clean remove coeffs and static mask files: yes or no (Default) Optional Parameters for '.clean()': coeffs Removes coeffs and static mask files: yes or no (Default) final Removes final product: yes or no (Default) Usage of optional parameters: --> test = pydrizzle.PyDrizzle('test_asn.fits',units='counts') To keep the individual 'drizzle' output products: --> test.run(save=yes) Output frame parameters can be modified 'on-the-fly' using 'resetPars'. Given an already drizzled image 'refimg_drz.fits' as a reference, reset drizzle parameters using: --> wcsref = wcsutil.WCSObject('refimg_drz.fits[sci,1]') --> f = pydrizzle.SkyField(wcs=wcsref) Use either: --> test.resetPars(wcsref) Or: --> test.resetPars(f) Return to default parameters using no parameters at all: --> test.resetPars() More help on SkyField objects and their parameters can be obtained using: --> f.help() """ def __init__(self, input, output=None, field=None, units=None, section=None, kernel=None,pixfrac=None,bits_final=0,bits_single=0, wt_scl='exptime', fillval=0.,idckey='', in_units='counts', idcdir=DEFAULT_IDCDIR,memmap=0,dqsuffix=None): if idcdir == None: idcdir = DEFAULT_IDCDIR print('Starting PyDrizzle Version ',__version__,' at ', _ptime()) self.input = input self.output = output asndict = input # Insure that the section parameter always becomes a list if isinstance(section,list) == False and section != None: section = [section] # Set the default value for 'build' self.build = yes # Extract user-specified parameters, if any have been set... # 'field' will be a SkyField object... if field != None: psize = field.psize orient = field.orient orient_rot = orient else: psize = None orient = None orient_rot = 0. #self.pars['orient_rot'] was originaly self.pars['rot']. It is set based on # orientat but it looks like it is not used. In SkyField.mergeWCS() rot is #defined again based on orientat. # These can also be set by the user. # Minimum set needed: psize, rot, and idckey self.pars = {'psize':psize,'units':units,'kernel':kernel,'orient_rot':orient_rot, 'pixfrac':pixfrac,'idckey':idckey,'wt_scl':wt_scl, 'fillval':fillval,'section':section, 'idcdir':idcdir+os.sep, 'memmap':memmap,'dqsuffix':dqsuffix, 'in_units':in_units, 'bits':[bits_final,bits_single], 'mt_wcs': None} # Watch out for any errors. # If they arise, all open files need to be closed... self.observation = None self.parlist = None if len(asndict['order']) > 1: self.observation = DitherProduct(asndict,output=output,pars=self.pars) else: inroot = asndict['order'][0] pardict = asndict['members'][inroot] infile = fileutil.buildRootname(inroot) if infile == None: raise IOError('No product found for association table.') # Append user specified parameters to shifts dictionary pardict.update(self.pars) #self.observation = selectInstrument(infile,output,pars=pardict) self.observation = selectInstrument(infile,self.output,pars=pardict) """ if self.output == None: self.output = fileutil.buildNewRootname(asndict['output'],extn='_drz.fits') print 'Setting up output name: ',output else: self.output = output """ # This call puts together the parameters for the input image # with those for the output to create a final parameter list # for running 'drizzle'. # It relies on the buildPars() methods for each exposure to # generate a complete set of parameters for all inputs # self.translateShifts(asndict) self.parlist = self.observation.buildPars(ref=field) # Something went wrong, so we need to make sure all file # handles get closed... #self.close() #print 'PyDrizzle could not initialize due to errors.' self.observation.closeHandle() # Let the user know parameters have been successfully calculated print('Drizzle parameters have been calculated. Ready to .run()...') print('Finished calculating parameters at ',_ptime()) def translateShifts(self, asndict): """ Translate the shifts specified in the ASNDICT (as read in from the shiftfile) into offsets in the sky, so they can be translated back into the WCS of the PyDrizzle output product. NOTE: Only works with 'delta' shifts now, and requires that a 'refimage' be specified. """ # for each set of shifts, translate them into delta(ra,dec) based on refwcs for img in asndict['order']: xsh = asndict['members'][img]['xshift'] ysh = asndict['members'][img]['yshift'] if xsh == 0.0 and ysh == 0.0: delta_ra = 0.0 delta_dec = 0.0 else: #check the units for the shifts... if asndict['members'][img]['shift_units'] == 'pixels': # Initialize the reference WCS for use in translation # NOTE: This assumes that a 'refimage' has been specified for # every set of shifts. refwcs = wcsutil.WCSObject(asndict['members'][img]['refimage']) cp1 = refwcs.crpix1 cp2 = refwcs.crpix2 nra,ndec = refwcs.xy2rd((cp1+xsh,cp2+ysh)) delta_ra = refwcs.crval1-nra delta_dec = refwcs.crval2-ndec else: # Shifts already in units of RA/Dec (decimal degrees) # No conversion necessary delta_ra = xsh delta_dec = ysh asndict['members'][img]['delta_ra'] = delta_ra asndict['members'][img]['delta_dec'] = delta_dec def clean(self,coeffs=no,final=no): """ Removes intermediate products from disk. """ for img in self.parlist: # If build == no, then we do not want to delete the only # products created by PyDrizzle; namely, # outdata, outcontext, outweight if self.build == yes: fileutil.removeFile([img['outdata'],img['outcontext'],img['outweight']]) fileutil.removeFile([img['outsingle'],img['outsweight']]) #fileutil.removeFile([img['outsingle'],img['outsweight'],img['outscontext']]) fileutil.removeFile(img['outblot']) if coeffs: os.remove(img['coeffs']) if img['driz_mask'] != None: fileutil.removeFile(img['driz_mask']) if img['single_driz_mask'] != None: fileutil.removeFile(img['single_driz_mask']) if final: fileutil.removeFile(self.output) # Run 'drizzle' here... # def run(self,save=no,build=yes,blot=no,single=no,clean=no,interp='linear',sinscl=1.0, debug=no): """Perform drizzle operation on input to create output. This method would rely on the buildPars() method for the output product to produce correct parameters based on the inputs. The output for buildPars() is a list of dictionaries, one for each input, that matches the primary parameters for an IRAF drizzle task. This method would then loop over all the entries in the list and run 'drizzle' for each entry. """ # Store the value of build set by the user for use, if desired, # in the 'clean()' method. self.build = build self.debug = debug print('PyDrizzle: drizzle task started at ',_ptime()) _memmap = self.pars['memmap'] # Check for existance of output file. if single == no and build == yes and fileutil.findFile(self.output): print('Removing previous output product...') os.remove(self.output) # # Setup the versions info dictionary for output to PRIMARY header # The keys will be used as the name reported in the header, as-is # _versions = {'PyDrizzle':__version__,'Astropy':astropy.__version__,'Numpy':np.__version__} # Set parameters for each input and run drizzle on it here. if blot: # # Run blot on data... # _hdrlist = [] for plist in self.parlist: _insci = np.zeros((plist['outny'],plist['outnx']),dtype=np.float32) _outsci = np.zeros((plist['blotny'],plist['blotnx']),dtype=np.float32) _hdrlist.append(plist) # Open input image as PyFITS object if plist['outsingle'] != plist['outdata']: _data = plist['outsingle'] else: _data = plist['outdata'] # PyFITS can be used here as it will always operate on # output from PyDrizzle (which will always be a FITS file) # Open the input science file _fname,_sciextn = fileutil.parseFilename(_data) _inimg = fileutil.openImage(_fname) # Return the PyFITS HDU corresponding to the named extension _scihdu = fileutil.getExtn(_inimg,_sciextn) _insci = _scihdu.data.copy() # Read in the distortion correction arrays, if specified _pxg,_pyg = plist['exposure'].getDGEOArrays() # Now pass numpy objects to callable version of Blot... #runBlot(plist) build=no misval = 0.0 kscale = 1.0 xmin = 1 xmax = plist['outnx'] ymin = 1 ymax = plist['outny'] # # Convert shifts to input units # xsh = plist['xsh'] * plist['scale'] ysh = plist['ysh'] * plist['scale'] # ARRDRIZ.TBLOT needs to be updated to support 'poly5' interpolation, # and exptime scaling of output image. # """ # # This call to 'arrdriz.tdriz' uses the F2PY syntax # arrdriz.tblot(_insci, _outsci,xmin,xmax,ymin,ymax, plist['xsh'],plist['ysh'], plist['rot'],plist['scale'], kscale, _pxg, _pyg, 'center',interp, plist['coeffs'], plist['exptime'], misval, sinscl, 1) # # End of F2PY syntax # """ # # This call to 'arrdriz.tdriz' uses the F2C syntax # if (_insci.dtype > np.float32): #WARNING: Input array recast as a float32 array _insci = _insci.astype(np.float32) t = arrdriz.tblot(_insci, _outsci,xmin,xmax,ymin,ymax, xsh,ysh, plist['rot'],plist['scale'], kscale, 0.0,0.0, 1.0,1.0, 0.0, 'output', _pxg, _pyg, 'center',interp, plist['coeffs'], plist['exptime'], misval, sinscl, 1,0.0,0.0) # # End of F2C syntax # # Write output Numpy objects to a PyFITS file # Blotting only occurs from a drizzled SCI extension # to a blotted SCI extension... _header = fileutil.getHeader(plist['data']) _wcs = wcsutil.WCSObject(plist['data'],header=_header) _outimg = outputimage.OutputImage(_hdrlist, build=no, wcs=_wcs, blot=yes) _outimg.outweight = None _outimg.outcontext = None _outimg.writeFITS(plist['data'],_outsci,None,versions=_versions) #_buildOutputFits(_outsci,None,plist['outblot']) _insci *= 0. _outsci *= 0. _inimg.close() del _inimg _hdrlist = [] del _pxg,_pyg del _insci,_outsci del _outimg else: # # Perform drizzling... # # Only work on a copy of the product WCS, so that when # this gets updated for the output image, it does not # modify the original WCS computed by PyDrizzle _wcs = self.observation.product.geometry.wcs.copy() _numctx = {'all':len(self.parlist)} # if single: # Determine how many chips make up each single image for plist in self.parlist: plsingle = plist['outsingle'] if plsingle in _numctx: _numctx[plsingle] += 1 else: _numctx[plsingle] = 1 # # A image buffer needs to be setup for converting the input # arrays (sci and wht) from FITS format to native format # with respect to byteorder and byteswapping. # This buffer should be reused for each input. # plist = self.parlist[0] _outsci = np.zeros((plist['outny'],plist['outnx']),dtype=np.float32) _outwht = np.zeros((plist['outny'],plist['outnx']),dtype=np.float32) _inwcs = np.zeros([8],dtype=np.float64) # Compute how many planes will be needed for the context image. _nplanes = int((_numctx['all']-1) / 32) + 1 # For single drizzling or when context is turned off, # minimize to 1 plane only... if single or self.parlist[0]['outcontext'] == '': _nplanes = 1 # Always initialize context images to a 3-D array # and only pass the appropriate plane to drizzle as needed _outctx = np.zeros((_nplanes,plist['outny'],plist['outnx']),dtype=np.int32) # Keep track of how many chips have been processed # For single case, this will determine when to close # one product and open the next. _numchips = 0 _nimg = 0 _hdrlist = [] for plist in self.parlist: # Read in the distortion correction arrays, if specifij8cw08n4q_raw.fitsed _pxg,_pyg = plist['exposure'].getDGEOArrays() _hdrlist.append(plist) # Open the SCI image _expname = plist['data'] _handle = fileutil.openImage(_expname,mode='readonly',memmap=0) _fname,_extn = fileutil.parseFilename(_expname) _sciext = fileutil.getExtn(_handle,extn=_extn) # Make a local copy of SCI array and WCS info #_insci = _sciext.data.copy() _inwcs = drutil.convertWCS(wcsutil.WCSObject(_fname,header=_sciext.header),_inwcs) # Determine output value of BUNITS # and make sure it is not specified as 'ergs/cm...' # we want to use the actual value from the input image header directly # when possible in order to account for any unit conversions that may # be applied to the input image between initialization of PyDrizzle # and the calling of this run() method. if ('bunit' in _sciext.header and _sciext.header['bunit'] not in ['','N/A']): _bunit = _sciext.header['bunit'] else: # default based on instrument-specific logic _bunit = plist['bunit'] _bindx = _bunit.find('/') if plist['units'] == 'cps': # If BUNIT value does not specify count rate already... if _bindx < 1: # ... append '/SEC' to value _bunit += '/S' else: # reset _bunit here to None so it does not # overwrite what is already in header _bunit = None else: if _bindx > 0: # remove '/S' _bunit = _bunit[:_bindx] else: # reset _bunit here to None so it does not # overwrite what is already in header _bunit = None # Compute what plane of the context image this input would # correspond to: _planeid = int(_numchips /32) # Select which mask needs to be read in for drizzling if single: _mask = plist['single_driz_mask'] else: _mask = plist['driz_mask'] # Check to see whether there is a mask_array at all to use... if type(_mask) == type('') : if _mask != None and _mask != '': _wht_handle = fileutil.openImage(_mask,mode='readonly',memmap=0) _inwht = _wht_handle[0].data.astype(np.float32) _wht_handle.close() del _wht_handle else: print('No weight or mask file specified! Assuming all pixels are good.') _inwht = np.ones((plist['blotny'],plist['blotnx']),dtype=np.float32) elif _mask != None: _inwht = _mask.astype(np.float32) else: print('No weight or mask file specified! Assuming all pixels are good.') _inwht = np.ones((plist['blotny'],plist['blotnx']),dtype=np.float32) if plist['wt_scl'] != None: if type(plist['wt_scl']) == type(''): if plist['wt_scl'].isdigit() == False : # String passed in as value, check for 'exptime' or 'expsq' _wtscl_float = None try: _wtscl_float = float(plist['wt_scl']) except ValueError: _wtscl_float = None if _wtscl_float != None: _wtscl = _wtscl_float elif plist['wt_scl'] == 'expsq': _wtscl = plist['exptime']*plist['exptime'] else: # Default to the case of 'exptime', if # not explicitly specified as 'expsq' _wtscl = plist['exptime'] else: # int value passed in as a string, convert to float _wtscl = float(plist['wt_scl']) else: # We have a non-string value passed in... _wtscl = float(plist['wt_scl']) else: # Default case: wt_scl = exptime _wtscl = plist['exptime'] #print 'WT_SCL: ',plist['wt_scl'],' _wtscl: ',_wtscl # Set additional parameters needed by 'drizzle' _in_units = plist['in_units'] if _in_units == 'cps': _expin = 1.0 else: _expin = plist['exptime'] _shift_fr = 'output' _shift_un = 'output' _uniqid = _numchips + 1 ystart = 0 nmiss = 0 nskip = 0 _vers = plist['driz_version'] _con = yes _imgctx = _numctx['all'] if single: _imgctx = _numctx[plist['outsingle']] #if single or (plist['outcontext'] == '' and single == yes): if _nplanes == 1: _con = no # We need to reset what gets passed to TDRIZ # when only 1 context image plane gets generated # to prevent overflow problems with trying to access # planes that weren't created for large numbers of inputs. _planeid = 0 _uniqid = ((_uniqid-1) % 32) + 1 """ # # This call to 'arrdriz.tdriz' uses the F2PY syntax # #_dny = plist['blotny'] # Call 'drizzle' to perform image combination tdriz,nmiss,nskip,_vers = arrdriz.tdriz( _sciext.data,_inwht, _outsci, _outwht, _outctx[_planeid], _con, _uniqid, ystart, 1, 1, plist['xsh'],plist['ysh'], 'output','output', plist['rot'],plist['scale'], _pxg,_pyg, 'center', plist['pixfrac'], plist['kernel'], plist['coeffs'], 'counts', _expin,_wtscl, plist['fillval'], _inwcs, 1, nmiss, nskip,_vers) # # End of F2PY syntax # """ # # This call to 'arrdriz.tdriz' uses the F2C syntax # _dny = plist['blotny'] # Call 'drizzle' to perform image combination if (_sciext.data.dtype > np.float32): #WARNING: Input array recast as a float32 array _sciext.data = _sciext.data.astype(np.float32) _vers,nmiss,nskip = arrdriz.tdriz(_sciext.data,_inwht, _outsci, _outwht, _outctx[_planeid], _uniqid, ystart, 1, 1, _dny, plist['xsh'],plist['ysh'], 'output','output', plist['rot'],plist['scale'], 0.0,0.0, 1.0,1.0,0.0,'output', _pxg,_pyg, 'center', plist['pixfrac'], plist['kernel'], plist['coeffs'], _in_units, _expin,_wtscl, plist['fillval'], _inwcs, nmiss, nskip, 1,0.0,0.0) """ _vers,nmiss,nskip = arrdriz.tdriz(_sciext.data,_inwht, _outsci, _outwht, _outctx[_planeid], _uniqid, ystart, 1, 1, _dny, plist['xsh'],plist['ysh'], 'output','output', plist['rot'],plist['scale'], _pxg,_pyg, 'center', plist['pixfrac'], plist['kernel'], plist['coeffs'], 'counts', _expin,_wtscl, plist['fillval'], _inwcs, nmiss, nskip, 1) """ # # End of F2C syntax # plist['driz_version'] = _vers if nmiss > 0: print('! Warning, ',nmiss,' points were outside the output image.') if nskip > 0: print('! Note, ',nskip,' input lines were skipped completely.') # Close image handle _handle.close() del _handle,_fname,_extn,_sciext del _inwht del _pxg,_pyg # Remember the name of the first image that goes into # this particular product # This will insure that the header reports the proper # values for the start of the exposure time used to make # this product; in particular, TIME-OBS and DATE-OBS. if _numchips == 0: _template = plist['data'] if _nimg == 0 and self.debug == yes: # Only update the WCS from drizzling the # first image in the list, just like IRAF DRIZZLE drutil.updateWCS(_inwcs,_wcs) #print '[run] Updated WCS now:' #print _wcs # Increment number of chips processed for single output _numchips += 1 if _numchips == _imgctx: ########################### # # IMPLEMENTATION REQUIREMENT: # # Need to implement scaling of the output image # from 'cps' to 'counts' in the case where 'units' # was set to 'counts'... 21-Mar-2005 # ########################### # Start by determining what exposure time needs to be used # to rescale the product. if single: _expscale = plist['exptime'] else: _expscale = plist['texptime'] #If output units were set to 'counts', rescale the array in-place if plist['units'] == 'counts': np.multiply(_outsci, _expscale, _outsci) # # Write output arrays to FITS file(s) and reset chip counter # _outimg = outputimage.OutputImage(_hdrlist, build=build, wcs=_wcs, single=single) _outimg.set_bunit(_bunit) _outimg.set_units(plist['units']) _outimg.writeFITS(_template,_outsci,_outwht,ctxarr=_outctx,versions=_versions) del _outimg # # Reset chip counter for next output image... # _numchips = 0 _nimg = 0 np.multiply(_outsci,0.,_outsci) np.multiply(_outwht,0.,_outwht) np.multiply(_outctx,0,_outctx) _hdrlist = [] else: _nimg += 1 del _outsci,_outwht,_inwcs,_outctx, _hdrlist # Remove temp files, if desired # Files to be removed are: # parlist['coeffs'] # parlist['driz_mask'] if not save and clean: for img in self.parlist: fileutil.removeFile(img['coeffs']) if img['driz_mask'] != None: fileutil.removeFile(img['driz_mask']) if img['single_driz_mask'] != None: fileutil.removeFile(img['single_driz_mask']) print('PyDrizzle drizzling completed at ',_ptime()) def resetPars(self,field=None,pixfrac=None,kernel=None,units=None): """ Recompute the output parameters based on a new SkyField or WCSObject object. """ if field and not isinstance(field, SkyField): if isinstance(field, wcsutil.WCSObject): _ref = SkyField(wcs=field) else: raise TypeError('No valid WCSObject or SkyField object entered...') else: _ref = field # Create new version of the parlist with the new values of the # parameters based on the reference image. new_parlist = self.observation.buildPars(ref=_ref) # Copy the parameters from the new parlist into the existing # parlist (self.parlist) to preserve any changes/updates made # to the parlist externally to PyDrizzle. for i in range(len(self.parlist)): for key in new_parlist[i]: self.parlist[i][key] = new_parlist[i][key] del new_parlist if pixfrac or kernel or units: #print 'resetting additional parameter(s)...' for p in self.parlist: if kernel: p['kernel'] = kernel if pixfrac: p['pixfrac'] = pixfrac if units: if units == 'counts' or units == 'cps': p['units'] = units else: print('Units ',units,' not valid! Parameter not reset.') print('Please use either "cps" or "counts".') def help(self): """ Run the module level help function to provide syntax information. """ help() def printPars(self,pars='xsh,ysh,rot,scale,outnx,outny,data',format=no): """ Prints common parameters for review. """ if format: _title = pars.replace(',',' ') print(_title) print('-'*72) _pars = pars.split(',') for pl in self.parlist: for _p in _pars: print(pl[_p], end=' ') print('') def getMember(self,memname): """ Returns the class instance for the specified member name.""" return self.observation.getMember(memname) def _ptime(): import time # Format time values for keywords IRAF-TLM, and DATE _ltime = time.localtime(time.time()) tlm_str = time.strftime('%H:%M:%S (%d/%m/%Y)',_ltime) #date_str = time.strftime('%Y-%m-%dT%H:%M:%S',_ltime) return tlm_str ################# class SkyField: """ An class for specifying the parameters and building a WCS object for a user-specified drizzle product. The user may optionally modify the values for: psize - size of image's pixels in arc-seconds orient - value of ORIENTAT for the field shape - tuple containing the sizes of the field's x/y axes ra,dec - position of the center of the field decimal (124.5678) or sexagesimal string _in quotes_ ('hh:mm:ss.ss') crpix - tuple for pixel position of reference point in output image Usage: To specify a new field with a fixed output size of 1024x1024: --> field = pydrizzle.SkyField(shape=(1024,1024)) The 'set()' method modifies one of the parameters listed above without affecting the remainder of the parameters. --> field.set(psize=0.1,orient=0.0) --> field.set(ra=123.45678,dec=0.1000,crpix=(521,576)) View the WCS or user-specified values for this object: --> print field """ def __init__(self,shape=None,psize=None,wcs=None): self.shape = shape self.ra = None self.dec = None self.orient = None self.psize = psize self.crpix = None # Set up proper shape tuple for WCSObject if shape != None and psize != None: wshape = (shape[0],shape[1],psize) else: wshape = None if wcs: self.crpix = (wcs.crpix1,wcs.crpix2) # Specify 'new=yes' with given rootname to unambiguously create # a new WCS from scratch. if wcs == None: self.wcs = wcsutil.WCSObject("New",new=yes) else: self.wcs = wcs.copy() # Need to adjust WCS to match the 'drizzle' task # align=center conventions. WJH 29-Aug-2005 #self.wcs.crpix1 -= 1.0 #self.wcs.crpix2 -= 1.0 self.wcs.recenter() self.wcs.updateWCS(size=shape,pixel_scale=psize) # Set this to keep track of total exposure time for # output frame... Not user settable. self.exptime = None # Keep track of whether this is for a Dither product or not self.dither = None def mergeWCS(self,wcs,overwrite=yes): """ Sets up the WCS for this object based on another WCS. This method will NOT update object attributes other than WCS, as all other attributes reflect user-settings. """ # # Start by making a copy of the input WCS... # if self.wcs.rootname == 'New': self.wcs = wcs.copy() else: return self.wcs.recenter() if self.ra == None: _crval = None else: _crval = (self.ra,self.dec) if self.psize == None: _ratio = 1.0 _psize = None # Need to resize the WCS for any changes in pscale else: _ratio = wcs.pscale / self.psize _psize = self.psize if self.orient == None: _orient = None _delta_rot = 0. else: _orient = self.orient _delta_rot = wcs.orient - self.orient _mrot = fileutil.buildRotMatrix(_delta_rot) if self.shape == None: _corners = np.array([[0.,0.],[wcs.naxis1,0.],[0.,wcs.naxis2],[wcs.naxis1,wcs.naxis2]]) _corners -= (wcs.naxis1/2.,wcs.naxis2/2.) _range = drutil.getRotatedSize(_corners,_delta_rot) shape = ((_range[0][1] - _range[0][0])*_ratio,(_range[1][1]-_range[1][0])*_ratio) old_shape = (wcs.naxis1*_ratio,wcs.naxis2*_ratio) _cen = (shape[0]/2., shape[1]/2.) #if _delta_rot == 0.: # _crpix = (self.wcs.crpix1,self.wcs.crpix2) #else: # Rotate original scaled crpix position to new orientation #_crpix = N.dot((wcs.crpix1*_ratio - _cen[0],wcs.crpix2*_ratio -_cen[1]),_mrot)+_cen _crpix = _cen else: shape = self.shape if self.crpix == None: _crpix = (self.shape[0]/2.,self.shape[1]/2.) else: _crpix = self.crpix # Set up the new WCS based on values from old one. self.wcs.updateWCS(pixel_scale=_psize,orient=_orient,refpos=_crpix,refval=_crval) self.wcs.naxis1 = int(shape[0]) self.wcs.naxis2 = int(shape[1]) def set(self,psize=None,orient=None,ra=None,dec=None, shape=None,crpix=None): """ Modifies the attributes of the SkyField and updates it's WCS when appropriate. """ # Converts(if necessary), then updates the RA and Dec. _ra,_dec = None,None if ra != None: if repr(ra).find(':') > 0: _hms = repr(ra)[1:-1].split(':') if _hms[0][0] == '-': _sign = -1 else: _sign = 1 for i in range(len(_hms)): _hms[i] = float(_hms[i]) _ra = _sign * (_hms[0] + ((_hms[1] + _hms[2]/60.) / 60.)) * 15. else: _ra = float(ra) self.ra = _ra if dec != None: if repr(dec).find(':') > 0: _dms = repr(dec)[1:-1].split(':') if _dms[0][0] == '-': _sign = -1 else: _sign = 1 for i in range(len(_dms)): _dms[i] = float(_dms[i]) _dec = _sign * (_dms[0] + ((_dms[1] + _dms[2]/60.) / 60.)) else: _dec = float(dec) self.dec = _dec if self.ra != None and self.dec != None: _crval = (self.ra,self.dec) else: _crval = None # Updates the shape, and reference position, # only if a new value is specified. _crpix = None if crpix == None: if shape != None: self.shape = shape _crpix = (self.shape[0]/2.,self.shape[1]/2.) else: _crpix = crpix self.crpix=_crpix if psize != None: self.psize = psize if orient != None: self.orient = orient # Updates the WCS with all the changes, if there is enough info. self.wcs.updateWCS(pixel_scale=psize,orient=orient,refpos=_crpix, refval=_crval,size=self.shape) def __str__(self): """ Prints the WCS information set for this object. """ if self.psize != None and self.orient != None: block = self.wcs.__str__() else: block = 'User parameters for SkyField object: \n' block = block + ' ra = '+repr(self.ra)+' \n' block = block + ' dec = '+repr(self.dec)+' \n' block = block + ' shape = '+repr(self.shape)+' \n' block = block + ' crpix = '+repr(self.crpix)+' \n' block = block + ' psize = '+repr(self.psize)+' \n' block = block + ' orient = '+repr(self.orient)+' \n' block = block + ' No WCS.\n' return block def help(self): """ Creates and prints usage information for this class. """ print(self.__doc__) class DitherProduct(Pattern): """ Builds an object for a set of dithered inputs, each of which will be one of the Observation objects. """ def __init__(self, prodlist, output=None, pars=None): if output is None: # Build temporary output drizzle product name if prodlist['output'].find('.fits') < 0: if prodlist['output'].rfind('_drz') < 0: output = fileutil.buildNewRootname(prodlist['output'],extn='_drz.fits') else: output = prodlist['output']+'.fits' else: output = prodlist['output'] else: if '.fits' not in output: output += '.fits' # Setup a default exposure to contain the results Pattern.__init__(self, None, output=output, pars=pars) self.pars = prodlist['members'] self.nmembers = self.nimages = len(prodlist['members']) self.offsets = None self.addMembers(prodlist,pars,output) if len(self.members) == 0: print('No suitable inputs from ASN table. Quitting PyDrizzle...') raise Exception self.exptime = self.getExptime() self.buildProduct(output) def closeHandle(self): """ Close image handle for each member.""" for member in self.members: member.closeHandle() def buildProduct(self,output): # Build default Metachip based on unmodified header WCS values output_wcs = self.buildMetachip() self.size = (output_wcs.naxis1,output_wcs.naxis2) self.product = Exposure(output,wcs=output_wcs,new=yes) self.product.geometry.wcslin = self.product.geometry.wcs.copy() # Compute default offsets between all inputs... # This will be used when applying relative shifts from ASN table # or shiftfile. self.computeOffsets() # Preserve default DitherProduct Metachip WCS as wcslin self.product.exptime = self.exptime # Update the corners arrays for the product now... self.product.setCorners() #self.product.corners['corrected'] = self.product.corners['raw'] _prodcorners = [] for prod in self.members: _prodcorners += prod.product.corners['corrected'].tolist() self.product.corners['corrected'] = np.array(_prodcorners,dtype=np.float64) def computeOffsets(self): """ This method will rely on final product's 'rd2xy' method to compute offsets between the different input chips. """ ref_wcs = self.product.geometry.wcs ref_crv= (ref_wcs.crval1,ref_wcs.crval2) _tot_ref = {'pix_shift':(0.,0.),'ra_shift':(0.,0.), 'val':999999999.,'name':''} _member_num = 0 for member in self.members: in_wcs = member.product.geometry.wcs x,y = ref_wcs.rd2xy((in_wcs.crval1,in_wcs.crval2)) xoff = x - ref_wcs.crpix1 yoff = y - ref_wcs.crpix2 raoff = (in_wcs.crval1 - ref_wcs.crval1,in_wcs.crval2 - ref_wcs.crval2) _delta_rot = in_wcs.orient - ref_wcs.orient # Determine which image has the smallest offset _tot = np.sqrt(np.power(xoff,2)+np.power(yoff,2)) """ # Use first image as reference if _member_num == 0: _tot_ref['val'] = _tot _tot_ref['pix_shift'] = (xoff,yoff) _tot_ref['name'] = member.rootname _tot_ref['ra_shift'] = raoff # This will be used primarily for manual verification _tot_ref['wcs'] = in_wcs """ _member_num += 1 # Keep track of the results for later use/comparison member.offsets = {'pixels':(xoff,yoff),'arcseconds':raoff} """ for member in self.members: member.refimage = _tot_ref """ def getExptime(self): """ Add up the exposure time for all the members in the pattern, since 'drizzle' doesn't have the necessary information to correctly set this itself. """ _exptime = 0. _start = [] _end = [] for member in self.members: _memexp = member.product.exptime _exptime = _exptime + _memexp[0] _start.append(_memexp[1]) _end.append(_memexp[2]) _expstart = min(_start) _expend = max(_end) return (_exptime,_expstart,_expend) def addMembers(self,prodlist,pars,output): """ For each entry in prodlist, append the appropriate type of Observation to the members list. If it's a moving target observation apply the wcs of the first observation to all other observations. """ member = prodlist['order'][0] filename = fileutil.buildRootname(member) mtflag = fileutil.getKeyword(filename, 'MTFLAG') if mtflag == 'T': mtpars = pars.copy() # necessary in order to avoid problems with use of pars in next loop mt_member = selectInstrument(filename,output, pars=mtpars) mt_wcs = {} for member in mt_member.members: mt_wcs[member.chip] = member.geometry.wcs pars['mt_wcs'] = mt_wcs del mt_member for memname in prodlist['order']: pardict = self.pars[memname] pardict.update(pars) filename = fileutil.buildRootname(memname) if filename: self.members.append(selectInstrument(filename,output,pars=pardict)) else: print('No recognizable input! Not building parameters for ',memname) def getMember(self,memname): """ Return the class instance for the member with name memname.""" member = None for mem in self.members: member = mem.getMember(memname) if member != None: break return member def getMemberNames(self): """ Returns a dictionary with one key for each member. The value for each key is a list of all the extension/chip names that make up each member. Output: {member1:[extname1,extname2,...],...} """ memlist = [] for member in self.members: memlist.extend(member.getMemberNames()) return memlist def buildPars(self,ref=None): # If an output field is specified, update product WCS to match if ref != None: _field = ref _field.mergeWCS(self.product.geometry.wcslin) #_field.exptime = self.exptime # Update product WCS based on input self.transformMetachip(_field) #_field.mergeWCS(self.product.geometry.wcs) else: _field = SkyField() _field.mergeWCS(self.product.geometry.wcslin) # Reset Product WCS to reflect use of default WCS self.product.geometry.wcs = self.product.geometry.wcslin.copy() _field.exptime = self.exptime # Specify that this product comes represents a dither product # not just a single observation product. _field.dither = yes # Copy the new reference WCS into the product WCS self.product.geometry.wcs = _field.wcs.copy() parlist = [] for member in self.members: parlist = parlist + member.buildPars(ref=_field) # Set value for number of images combined by PyDrizzle # based on DitherPattern attribute. for pl in parlist: pl['nimages'] = self.nimages return parlist def buildMetachip(self): """ This method combines the results of the member's buildMetachip() methods into a composite WCS. (DitherProduct method) """ prodlist = [] _ref = self.members[0].product.geometry # Get pscale from model pscale = _ref.model.pscale for member in self.members: # merge the corrected shapes into a corrected meta-chip here # Start by computing the corected positions for reference points prodlist.append(member.product) # Use first input image WCS as initial reference WCS meta_wcs = _ref.wcs.copy() ref_crval = (meta_wcs.crval1,meta_wcs.crval2) ref_crpix = (meta_wcs.crpix1,meta_wcs.crpix2) # Specify the output orientation angle ref_orient = meta_wcs.orient _delta_x = _delta_y = 0.0 _xr,_yr,_dpx,_dpy = [],[],[],[] # Compute offsets for each input relative to this reference WCS for member in prodlist: _wcs = member.geometry.wcs # Rigorously compute the orientation changes from WCS # information using algorithm provided by R. Hook from WDRIZZLE. abxt,cdyt = drutil.wcsfit(member.geometry, meta_wcs) # Compute the rotation between input and reference from fit coeffs. _angle = RADTODEG(np.arctan2(abxt[1],cdyt[0])) _dpos = (abxt[2],cdyt[2]) _delta_x += _dpos[0] _delta_y += _dpos[1] _dpx.append(_dpos[0]) _dpy.append(_dpos[1]) # Compute the range of pixels each input spans in the # output meta-frame coordinates # Each product in this list could have a different plate scale. # apply _scale = _wcs.pscale / meta_wcs.pscale # Now, account for any rotation difference between # input and output frames #_angle = meta_wcs.orient - _wcs.orient _xrange,_yrange = drutil.getRotatedSize(member.corners['corrected'],_angle) #_range = [(_xrange[1] - _xrange[0]),(_yrange[1] - _yrange[0])] #_range[0] *= _scale #_range[1] *= _scale _xr.append(_dpos[0] + _xrange[0]*_scale) _xr.append(_dpos[0] + _xrange[1]*_scale) _yr.append(_dpos[1] + _yrange[0]*_scale) _yr.append(_dpos[1] + _yrange[1]*_scale) # Determine the full size of the metachip _xmin = np.minimum.reduce(_xr) _ymin = np.minimum.reduce(_yr) _xmax = np.maximum.reduce(_xr) _ymax = np.maximum.reduce(_yr) _dxmin = np.minimum.reduce(_dpx) _dymin = np.minimum.reduce(_dpy) _dxmax = np.maximum.reduce(_dpx) _dymax = np.maximum.reduce(_dpy) _nimg = len(prodlist) _delta_x /= _nimg _delta_y /= _nimg # Computes the offset from center of the overall set of shifts # as applied to the pixels. This insures that the visible pixels # are centered in the output. _delta_dx = ((_xmax - _delta_x) + (_xmin - _delta_x))/2. _delta_dy = ((_ymax - _delta_y) + (_ymin - _delta_y))/2. if _xmin > 0.: _xmin = 0. if _ymin > 0.: _ymin = 0. # Need to account for overall offset in images. # by adding in average offset induced by shifts to # output size: delta_dx/dy. # This accounts for relative offsets that are not centered # on the final output image. #xsize = int(_xmax - _xmin + 2.0 + abs(_delta_dx) ) #ysize = int(_ymax - _ymin + 2.0 + abs(_delta_dy) ) xsize = int(_xmax - _xmin) ysize = int(_ymax - _ymin) # Compute difference between new size and # original size of meta_wcs frame. _dxsize = xsize - meta_wcs.naxis1 _dysize = ysize - meta_wcs.naxis2 # Update reference WCS for new size meta_wcs.naxis1 = xsize meta_wcs.naxis2 = ysize _cen = (float(xsize)/2.,float(ysize)/2.) # Determine offset of centers from center of image. # d[x/y]size : difference between input and output frame sizes # delta_[x/y] : average of all shifts applied to input images # delta_d[x/y]: amount off-center of all shifts # # Need to take into account overall offset in shifts, such that # minimum, not maximum, shift is always 0.0. This is needed to allow # subarrays to align properly with full frame observations without # introducing an overall offset to the output. WJH 13 Sept 2004. # _nref = ( _dxsize/2. - _delta_x - _delta_dx, _dysize/2. - _delta_y - _delta_dy) # Have to adjust the CRPIX by how much the center needs to shift # to fit into the reference frame. meta_wcs.crpix1 = meta_wcs.crpix1 + _nref[0] meta_wcs.crpix2 = meta_wcs.crpix2 + _nref[1] meta_wcs.recenter() return meta_wcs # # # Set up default pars dictionary for external calls def selectInstrument(filename,output,pars=_default_pars): """ Method which encapsulates the logic for determining which class to instantiate for each file. """ # Determine the instrument... instrument = fileutil.getKeyword(filename+'[0]','INSTRUME') #try: # ... then create an appropriate object. if instrument == INSTRUMENT[0]: member = ACSObservation(filename,output,pars=pars) elif instrument == INSTRUMENT[1]: member = WFPCObservation(filename,output,pars=pars) elif instrument == INSTRUMENT[2]: member = STISObservation(filename,output,pars=pars) elif instrument == INSTRUMENT[3]: member = NICMOSObservation(filename,output,pars=pars) elif instrument == INSTRUMENT[4]: member = WFC3Observation(filename,output,pars=pars) else: #raise AttributeError, "Instrument '%s' not supported now."%instrument member = GenericObservation(filename,output,pars=pars) #except: # raise IOError,"Image %s could not be processed."%filename return member
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,351
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/traits102/__init__.py
#------------------------------------------------------------------------------- # # Define a 'traits' package that allows other classes to easily define # 'type-checked' and/or 'delegated' traits for their instances. # # Note: A 'trait' is a synonym for 'property', but is used instead of the # word 'property' to differentiate it from the Python language 'property' # feature. # # Written by: David C. Morrill # # Date: 06/21/2002 # # (c) Copyright 2002 by Enthought, Inc. # #------------------------------------------------------------------------------- from __future__ import absolute_import, division # confidence high from .trait_base import Undefined, Self, trait_editors from .trait_errors import TraitError, DelegationError from .traits import HasTraits, HasObjectTraits, HasDynamicTraits, \ HasDynamicObjectTraits, Trait, Disallow, ReadOnly, \ DefaultPythonTrait, TraitProxy from .trait_handlers import TraitHandler, TraitRange, TraitType, TraitString, \ TraitInstance, TraitThisClass, TraitClass, \ TraitFunction, TraitEnum, TraitMap from .trait_handlers import TraitList, TraitPrefixList, TraitPrefixMap, \ TraitComplex, AnyValue from .trait_delegates import TraitGetterSetter, TraitDelegate, \ TraitDelegateSynched, TraitEvent, TraitProperty from .trait_sheet import TraitSheetHandler, TraitEditor, TraitGroup, \ TraitGroupItem, TraitGroupList, merge_trait_groups
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,352
spacetelescope/pydrizzle
refs/heads/master
/pydrizzle/observations.py
from __future__ import division # confidence medium from .pattern import * from stsci.tools import fileutil from .distortion import mutil import numpy as np class ACSObservation(Pattern): """This class defines an observation with information specific to ACS WFC exposures, including knowledge of how to mosaic both chips.""" # Define a class variable for the gap between the chips PARITY = {'WFC':[[1.0,0.0],[0.0,-1.0]],'HRC':[[-1.0,0.0],[0.0,1.0]],'SBC':[[-1.0,0.0],[0.0,1.0]]} def __init__(self, filename, output, pars=None): # Now, initialize Pattern with all member Exposures... Pattern.__init__(self, filename, output=output, pars=pars) self.instrument = 'ACS' # build required name attributes: # outname, output, outsingle self.setNames(filename,output) # Set EXPTIME for exposure self.exptime = self.getExptime() # Build up list of chips in observation self.addMembers(filename) # Only need to worry about IDC tables for ACS... self.computeOffsets() # Set up the input members and create the product meta-chip self.buildProduct(filename, output) class GenericObservation(Pattern): """ This class defines an observation stored in a Simple FITS format; i.e., only a Primary header and image without extensions. """ REFPIX = {'x':512.,'y':512.} DETECTOR_NAME = 'INSTRUME' def __init__(self, filename, output, pars=None): # Now initialize Pattern with all member exposures... Pattern.__init__(self, filename, output=output, pars=pars) # Determine the instrument... if 'INSTRUME' in self.header: _instrument = self.header['INSTRUME'] else: _instrument = self.DETECTOR_NAME self.instrument = _instrument if 'crpix1' in self.header: self.REFPIX['x'] = self.header['crpix1'] self.REFPIX['y'] = self.header['crpix2'] else: self.REFPIX['x'] = self.header['naxis1'] /2. self.REFPIX['y'] = self.header['naxis2'] /2. # build output rootnames here... self.setNames(filename,output) # Set EXPTIME for exposure self.exptime = self.getExptime() self.nmembers = 1 # Now, build list of members and initialize them self.addMembers(filename) _ikey = self.members[0].geometry.ikey if _ikey != 'idctab' and _ikey != 'wcs' : # Correct distortion coefficients to match output pixel scale self.computeCubicCoeffs() else: self.computeOffsets() # Set up the input members and create the product meta-chip self.buildProduct(filename, output) class STISObservation(Pattern): """This class defines an observation with information specific to STIS exposures. """ # Default coefficients table to use for this instrument IDCKEY = 'cubic' __theta = 0.0 __parity = fileutil.buildRotMatrix(__theta) * np.array([[-1.,1.],[-1.,1.]]) PARITY = {'CCD':__parity,'NUV-MAMA':__parity,'FUV-MAMA':__parity} # The dictionaries 'REFDATA' and 'REFPIX' are required for use with # cubic and Trauger coefficients tables in 'computeCubicCoeffs'. # # This information provides the absolute relationship between the chips # Latest plate scales: 0.05071, 0.0246 #REFDATA = {'CCD':{'psize':0.05,'xoff':0.0,'yoff':0.0,'v2':-213.999,'v3':-224.897,'theta':__theta}, # 'NUV-MAMA':{'psize':0.024,'xoff':0.0,'yoff':0.0,'v2':-213.999,'v3':-224.897,'theta':__theta}, # 'FUV-MAMA':{'psize':0.024,'xoff':0.0,'yoff':0.0,'v2':-213.999,'v3':-224.897,'theta':__theta}} #REFPIX = {'x':512.,'y':512.} def __init__(self, filename, output, pars=None): # Now initialize Pattern with all member exposures... Pattern.__init__(self, filename, output=output, pars=pars) self.instrument = 'STIS' self.__theta = 0.0 self.REFDATA = {'CCD':{'psize':0.05,'xoff':0.0,'yoff':0.0,'v2':-213.999,'v3':-224.897,'theta':self.__theta}, 'NUV-MAMA':{'psize':0.024,'xoff':0.0,'yoff':0.0,'v2':-213.999,'v3':-224.897,'theta':self.__theta}, 'FUV-MAMA':{'psize':0.024,'xoff':0.0,'yoff':0.0,'v2':-213.999,'v3':-224.897,'theta':self.__theta}} self.REFPIX = {'x':512.,'y':512.} # build output rootnames here... self.setNames(filename,output) # Set EXPTIME for exposure self.exptime = self.getExptime() # Now, build list of members and initialize them self.addMembers(filename) if self.members[0].geometry.ikey != 'idctab': # Correct distortion coefficients to match output pixel scale self.computeCubicCoeffs() else: self.computeOffsets() # Set up the input members and create the product meta-chip self.buildProduct(filename, output) def getExptime(self): header = fileutil.getHeader(self.name+'[sci,1]') _exptime = float(header['EXPTIME']) if _exptime == 0.: _exptime = 1.0 if 'EXPSTART' in header: _expstart = float(header['EXPSTART']) _expend = float(header['EXPEND']) else: _expstart = 0. _expend = _exptime return (_exptime,_expstart,_expend) class NICMOSObservation(Pattern): """This class defines an observation with information specific to NICMOS exposures. """ # Default coefficients table to use for this instrument IDCKEY = 'cubic' DETECTOR_NAME = 'camera' NUM_IMSET = 5 __theta = 0.0 __parity = fileutil.buildRotMatrix(__theta) * np.array([[-1.,1.],[-1.,1.]]) PARITY = {'1':__parity,'2':__parity,'3':__parity} # The dictionaries 'REFDATA' and 'REFPIX' are required for use with # cubic and Trauger coefficients tables in 'computeCubicCoeffs'. # # This information provides the absolute relationship between the chips # Latest plate scales: 0.05071, 0.0246 #REFDATA = {'1':{'psize':0.0432,'xoff':0.0,'yoff':0.0,'v2':-296.9228,'v3':290.1827,'theta':__theta}, # '2':{'psize':0.076,'xoff':0.0,'yoff':0.0,'v2':-319.9464,'v3':311.8579,'theta':__theta}, # '3':{'psize':0.0203758,'xoff':0.0,'yoff':0.0,'v2':-249.8170,'v3':235.2371,'theta':__theta}} #REFPIX = {'x':128.,'y':128.} def __init__(self, filename, output, pars=None): # Now initialize Pattern with all member exposures... Pattern.__init__(self, filename, output=output, pars=pars) self.instrument = 'NICMOS' self.__theta = 0.0 self.REFDATA = {'1':{'psize':0.0432,'xoff':0.0,'yoff':0.0,'v2':-296.9228,'v3':290.1827,'theta':self.__theta}, '2':{'psize':0.076,'xoff':0.0,'yoff':0.0,'v2':-319.9464,'v3':311.8579,'theta':self.__theta}, '3':{'psize':0.203758,'xoff':0.0,'yoff':0.0,'v2':-249.8170,'v3':235.2371,'theta':self.__theta}} self.REFPIX = {'x':128.,'y':128.} # build output rootnames here... self.setNames(filename,output) # Set EXPTIME for exposure self.exptime = self.getExptime() # Now, build list of members and initialize them self.addMembers() if self.members[0].geometry.ikey != 'idctab': # Correct distortion coefficients to match output pixel scale self.computeCubicCoeffs() else: self.computeOffsets() # Set up the input members and create the product meta-chip self.buildProduct(filename, output) def addMembers(self): """ Build rootname for each SCI extension, and create the mask image from the DQ extension. It would then append a new Exposure object to 'members' list for each extension. """ self.detector = detector = str(self.header[self.DETECTOR_NAME]) if self.pars['section'] == None: self.pars['section'] = [None]*self.nmembers # Build rootname here for each SCI extension... for i in range(self.nmembers): _sciname = self.imtype.makeSciName(i+1,section=self.pars['section'][i]) _dqname = self.imtype.makeDQName(i+1) _extname = self.imtype.dq_extname # Build mask files based on input 'bits' parameter values _masklist = [] _masknames = [] # # If we have a valid bits value... # Creat the name of the output mask file _maskname = buildmask.buildMaskName(_dqname,i+1) _masknames.append(_maskname) # Create the actual mask file now... outmask = buildmask.buildMaskImage(_dqname,self.bitvalue[0],_maskname,extname=_extname,extver=i+1) _masklist.append(outmask) # # Check to see if a bits value was provided for single drizzling... # Different bits value specified for single drizzle step # create new filename for single_drizzle mask file _maskname = _maskname.replace('final_mask','single_mask') _masknames.append(_maskname) # Create new mask file with different bit value. outmask = buildmask.buildMaskImage(_dqname,self.bitvalue[1],_maskname,extname=_extname,extver=i+1) # Add new name to list for single drizzle step _masklist.append(outmask) _masklist.append(_masknames) self.members.append(Exposure(_sciname, idckey=self.idckey, dqname=_dqname, mask=_masklist, pa_key=self.pa_key, parity=self.PARITY[detector], idcdir=self.pars['idcdir'], group_indx = i+1, handle=self.image_handle,extver=i+1,exptime=self.exptime[0], ref_pscale=self.REFDATA[self.detector]['psize'],mt_wcs=self.pars['mt_wcs'])) class WFC3Observation(Pattern): """This class defines an observation with information specific to ACS WFC exposures, including knowledge of how to mosaic both chips.""" #__theta = 45.00 #__ir_parity = fileutil.buildRotMatrix(__theta) * np.array([[-1.,1.],[-1.,1.]]) # Define a class variable for the gap between the chips PARITY = {'UVIS':[[-1.0,0.0],[0.0,1.0]],'IR':[[-1.0,0.0],[0.0,1.0]]} def __init__(self, filename, output, pars=None): # Now, initialize Pattern with all member Exposures... Pattern.__init__(self, filename, output=output, pars=pars) self.instrument = 'WFC3' # build required name attributes: # outname, output, outsingle self.setNames(filename,output) # Set EXPTIME for exposure self.exptime = self.getExptime() # Set binned factor for exposure #self.binned = fileutil.getKeyword(filename+'[sci,1]', 'BINAXIS1') # Build up list of chips in observation self.addMembers(filename) # Only need to worry about IDC tables for ACS... self.computeOffsets() # Set up the input members and create the product meta-chip self.buildProduct(filename, output) class WFPCObservation(Pattern): """This class defines an observation with information specific to WFPC2 exposures, including knowledge of how to mosaic the chips.""" # Default coefficients table to use for this instrument IDCKEY = 'idctab' # This parity is the multiplication of PC1 rotation matrix with # a flip in X for output image. #__theta = 44.67 __pmat = np.array([[-1.,0.],[0.,1.]]) __refchip = 3 PARITY = {'1':__pmat,'2':__pmat,'3':__pmat,'4':__pmat,'WFPC':__pmat} NUM_IMSET = 1 # The dictionaries 'REFDATA' and 'REFPIX' are required for use with # cubic and Trauger coefficients tables in 'computeCubicCoeffs'. # # This information provides the absolute relationship between the chips #REFDATA ={'1':{'psize':0.04554,'xoff':354.356,'yoff':343.646,'v2':2.374,'v3':-30.268,'theta':224.8480}, # '2':{'psize':0.0996,'xoff':345.7481,'yoff':375.28818,'v2':-51.368,'v3':-5.698,'theta':314.3520}, # '3':{'psize':0.0996,'xoff':366.56876,'yoff':354.79435,'v2':0.064,'v3':48.692,'theta':44.67}, # '4':{'psize':0.0996,'xoff':355.85016,'yoff':351.29183,'v2':55.044,'v3':-6.098,'theta':135.2210}} #REFPIX = {'x':400.,'y':400.} def __init__(self, filename, output, pars=None): # Now initialize Pattern with all member exposures... Pattern.__init__(self, filename, output=output, pars=pars) self.instrument = 'WFPC2' self.REFDATA ={'1':{'psize':0.04554,'xoff':354.356,'yoff':343.646,'v2':2.374,'v3':-30.268,'theta':224.8480}, '2':{'psize':0.0996,'xoff':345.7481,'yoff':375.28818,'v2':-51.368,'v3':-5.698,'theta':314.3520}, '3':{'psize':0.0996,'xoff':366.56876,'yoff':354.79435,'v2':0.064,'v3':48.692,'theta':44.67}, '4':{'psize':0.0996,'xoff':355.85016,'yoff':351.29183,'v2':55.044,'v3':-6.098,'theta':135.2210}} self.REFPIX = {'x':400.,'y':400.} gcount = None # build output rootnames here... self.setNames(filename,output) # Set EXPTIME for exposure self.exptime = self.getExptime() _mode = fileutil.getKeyword(filename, 'MODE') if _mode == 'AREA': self.binned = 2 if self.idckey == 'cubic': for l in self.REFPIX.keys(): self.REFPIX[l]= self.REFPIX[l] / self.binned for l in self.REFDATA.keys(): self.REFDATA[l]['psize'] = self.REFDATA[l]['psize'] * self.binned self.REFDATA[l]['xoff'] = self.REFDATA[l]['xoff'] / self.binned self.REFDATA[l]['yoff'] = self.REFDATA[l]['yoff'] / self.binned # Now, build list of members and initialize them self.addMembers(filename) self.setBunit('COUNTS') chips = [int(member.chip) for member in self.members] try: chip_ind = chips.index(self.__refchip) except ValueError: chip_ind = 0 self.refchip = chips[chip_ind] if self.members[0].geometry.ikey != 'idctab': # Correct distortion coefficients to match output pixel scale self.computeCubicCoeffs() else: #self.computeOffsets(refchip=self.__refchip) self.computeOffsets(refchip=self.refchip) # Determine desired orientation of product self.setOrient() # Set up the input members and create the product meta-chip self.buildProduct(filename, output) # Correct the crpix position of the metachip product # in order to account for 'align=center' convention. #self.product.geometry.wcs.crpix1 -= 1.0 #self.product.geometry.wcs.crpix2 -= 1.0 def addMembers(self,filename): # The PC chip defines the orientation of the metachip, so use # it for the PARITY as well. self.detector = 'WFPC' _chip1_rot = None # Build rootname here for each SCI extension... if self.pars['section'] == None: self.pars['section'] = [None] * self.nmembers group_indx = list(range(1,self.nmembers+1)) else: group_indx = self.pars['section'] for i in range(self.nmembers): _extname = self.imtype.makeSciName(i+1,section=self.pars['section'][i]) _detnum = fileutil.getKeyword(_extname,self.DETECTOR_NAME) # Start by looking for the corresponding WFPC2 'c1h' files _dqfile, _dqextn = self._findDQFile() # Reset dqfile name in ImType class to point to new file self.imtype.dqfile = _dqfile self.imtype.dq_extn = _dqextn # Build mask file for this member chip _dqname = self.imtype.makeDQName(extver=group_indx[i]) _masklist = [] _masknames = [] if _dqname != None: _maskname = buildmask.buildMaskName(fileutil.buildNewRootname(_dqname),_detnum) else: _maskname = None _masknames.append(_maskname) outmask = buildmask.buildShadowMaskImage(_dqname,_detnum,group_indx[i],_maskname, bitvalue=self.bitvalue[0], binned=self.binned) _masklist.append(outmask) _maskname = _maskname.replace('final_mask','single_mask') _masknames.append(_maskname) outmask = buildmask.buildShadowMaskImage(_dqname,_detnum,group_indx[i],_maskname, bitvalue=self.bitvalue[1], binned=self.binned) _masklist.append(outmask) _masklist.append(_masknames) self.members.append(Exposure(_extname, idckey=self.idckey, dqname=_dqname, mask=_masklist, parity=self.PARITY[str(i+1)], idcdir=self.pars['idcdir'], group_indx = i+1, rot=_chip1_rot, handle=self.image_handle, extver=_detnum, exptime=self.exptime[0], ref_pscale=self.REFDATA['1']['psize'], binned=self.binned)) if self.idckey != 'idctab': _chip1_rot = self.members[0].geometry.def_rot def _findDQFile(self): """ Find the DQ file which corresponds to the input WFPC2 image. """ dqfile="" dqextn = "" if self.name.find('.fits') < 0: # Working with a GEIS image... dqfile = self.name[:-2]+'1h' dqextn = '[sdq,1]' else: # Looking for c1f FITS DQ file... # In the WFPC2 pipeline the extensions are called 'c0f' and 'c1f' # and EXTNAME is 'sci'. Files are in MEF format. # Readgeis creates output with extensions 'c0h' and 'c1h' # and EXPNAME is 'sdq' # Hence the code below ... if 'c0h.fits' in self.name: dqfile = self.name.replace('0h.fits','1h.fits') dqextn = '[sdq,1]' elif 'c0f.fits' in self.name: dqfile = self.name.replace('0f.fits','1f.fits') dqextn = '[sci,1]' elif 'c0m.fits' in self.name: dqfile = self.name.replace('0m.fits','1m.fits') dqextn = '[sci,1]' return dqfile, dqextn def setOrient(self): """ Determine desired orientation of product.""" meta_orient = None for exp in self.members: if int(exp.chip) == 1: meta_orient = exp.geometry.wcslin.orient if meta_orient == None: meta_orient = self.members[0].geometry.wcslin.orient # Set orient for all groups # Dither coefficients rotate all chips to chip 1 orientation # if not using Trauger coefficients for exp in self.members: exp.geometry.wcs.orient = meta_orient # We need to correct each chip's full-frame reference # position to account for 'align=center' convention. #exp.geometry.wcs.chip_xref += 1.0 #exp.geometry.wcs.chip_yref += 1.0
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,353
spacetelescope/pydrizzle
refs/heads/master
/setup_hooks.py
import os import platform import sys def setup_hook(config): if platform.architecture()[0] == '64bit': # This should suffice, since for an extension module we still need to # use whatever architecture Python was built for f2c_macros = [('Skip_f2c_Undefs', 1), ('Allow_TYQUAD', 1), ('INTEGER_STAR_8', 1)] f2c_files = ['ftell64_.c', 'pow_qq.c', 'qbitbits.c', 'qbitshft.c'] else: f2c_macros = [('Skip_f2c_Undefs', 1)] f2c_files = ['ftell_.c'] if sys.platform == 'win32': f2c_macros += [('USE_CLOCK', 1), ('MSDOS', 1), ('NO_ONEXIT', 1)] f2c_files = [os.path.join('libf2c', f) for f in f2c_files] ext = config['extension=pydrizzle.arrdriz'] ext['define_macros'] += '\n' + '\n'.join('%s=%s' % m for m in f2c_macros) ext['sources'] += '\n' + '\n'.join(f2c_files)
{"/pydrizzle/traits102/trait_notifiers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/makewcs.py": ["/pydrizzle/__init__.py"], "/pydrizzle/__init__.py": ["/pydrizzle/drutil.py"], "/pydrizzle/traits102/standard.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_base.py"], "/pydrizzle/traits102/tktrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/process_input.py": ["/pydrizzle/__init__.py"], "/pydrizzle/xytosky.py": ["/pydrizzle/__init__.py"], "/pydrizzle/obsgeometry.py": ["/pydrizzle/__init__.py"], "/pydrizzle/traits102/trait_errors.py": ["/pydrizzle/traits102/trait_base.py"], "/pydrizzle/exposure.py": ["/pydrizzle/__init__.py", "/pydrizzle/obsgeometry.py"], "/pydrizzle/traits102/wxtrait_sheet.py": ["/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_sheet.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_delegates.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py"], "/pydrizzle/traits102/traits.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_notifiers.py", "/pydrizzle/traits102/__init__.py"], "/pydrizzle/traits102/trait_handlers.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/trait_delegates.py"], "/pydrizzle/traits102/trait_sheet.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/traits.py"], "/pydrizzle/pattern.py": ["/pydrizzle/__init__.py", "/pydrizzle/exposure.py"], "/pydrizzle/pydrizzle.py": ["/pydrizzle/drutil.py", "/pydrizzle/__init__.py", "/pydrizzle/pattern.py", "/pydrizzle/observations.py"], "/pydrizzle/traits102/__init__.py": ["/pydrizzle/traits102/trait_base.py", "/pydrizzle/traits102/trait_errors.py", "/pydrizzle/traits102/traits.py", "/pydrizzle/traits102/trait_handlers.py", "/pydrizzle/traits102/trait_delegates.py", "/pydrizzle/traits102/trait_sheet.py"], "/pydrizzle/observations.py": ["/pydrizzle/pattern.py"]}
65,363
mothaibatacungmua/AI-course
refs/heads/master
/bayesian/uniform_sampling.py
import numpy as np import matplotlib.pyplot as plt s = np.random.uniform(0, 1, 10000) count, bins, ignored = plt.hist(s, 20, normed=True) plt.plot(bins, np.ones_like(bins), linewidth=2, color='r') plt.show()
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,364
mothaibatacungmua/AI-course
refs/heads/master
/multiagent/multiAgents.py
# multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to http://ai.berkeley.edu. # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel (pabbeel@cs.berkeley.edu). from util import manhattanDistance from game import Directions import random, util from game import Agent import sys class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def __init__(self): self.posSaved = {} def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" currentPos = gameState.getPacmanPosition() self.setPositionReward(currentPos) return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" #return successorGameState.getScore() oldFood = currentGameState.getFood() return self.calcKNearestFoodReward(3, newPos, oldFood, newFood, successorGameState.getCapsules(), successorGameState.getWalls()) + \ self.calcGhostReward(newGhostStates, newPos) + \ self.calcScaredReward(newGhostStates, newPos) + \ self.getPositionReward(newPos) FOOD_REWARD = 2 CAPSULE_REWARD = 4 GHOST_REWARD = -5 DECAY = 0.8 OLD_POS_REWARD = -0.5 def getPositionReward(self, pos): if self.posSaved.has_key(pos): return self.posSaved[pos] return 0 def setPositionReward(self, pos): if self.posSaved.has_key(pos): self.posSaved[pos] = self.posSaved[pos] + ReflexAgent.OLD_POS_REWARD return self.posSaved[pos] self.posSaved[pos] = 0 return 0 def calcKNearestFoodReward(self, k, pacmanPos, oldFoodGrid, newFoodGrid, capsulesList, walls): closed = [] queue = util.Queue() queue.push(pacmanPos) closed.append(pacmanPos) findFood = 0 totalScore = 0.0 count = 0 while not queue.isEmpty(): travel = queue.pop() count = count + 1 #print count #print travel if newFoodGrid[travel[0]][travel[1]]: findFood = findFood + 1 if travel in capsulesList: totalScore = totalScore + pow(ReflexAgent.DECAY,manhattanDistance(pacmanPos, travel)) * ReflexAgent.CAPSULE_REWARD else: totalScore = totalScore + pow(ReflexAgent.DECAY,manhattanDistance(pacmanPos, travel)) * ReflexAgent.FOOD_REWARD if findFood == k: break for i in [-1, 0, 1]: if (travel[0] + i) < 0 or (travel[0] + i) > (newFoodGrid.width - 1): continue for j in [-1, 0, 1]: if (travel[1] + j) < 0 or (travel[1] + j) > (newFoodGrid.height - 1): continue newTravel = (travel[0] + i, travel[1] + j) if walls[travel[0] + i][travel[1] + j] or (newTravel in closed): continue closed.append(newTravel) queue.push(newTravel) if findFood == 0: score = 0 else: score = 1.0/findFood * totalScore if oldFoodGrid[pacmanPos[0]][pacmanPos[1]]: score = score + ReflexAgent.FOOD_REWARD #print '--\n' #print pacmanPos #print 'Food score:%0.3f' % score return score def calcGhostReward(self, ghostStates, pacmanPos): numGhosts = len(ghostStates) totalScore = 0.0 for ghostState in ghostStates: totalScore = totalScore + (ghostState.scaredTimer == 0) *(\ ReflexAgent.GHOST_REWARD * \ (manhattanDistance(pacmanPos, ghostState.getPosition()) == 1) + 2*ReflexAgent.GHOST_REWARD * \ (manhattanDistance(pacmanPos, ghostState.getPosition()) == 0)) #print 'Ghost reward:%0.3f' % totalScore return totalScore def calcScaredReward(self, ghostStates, pacmanPos): totalScore = 0.0 for ghostState in ghostStates: totalScore = totalScore + (ghostState.scaredTimer > 0)*(ghostState.scaredTimer - manhattanDistance(pacmanPos, ghostState.getPosition())) return totalScore def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ FOOD_REWARD = 2 CAPSULE_REWARD = 4 GHOST_REWARD = -5 DECAY = 0.8 OLD_POS_REWARD = -0.5 def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def __init__(self, *args, **kwargs): self.posSaved = {} MultiAgentSearchAgent.__init__(self, *args, **kwargs) def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" pacmanIndex = 0 ghostIndex = 1 numberAgents = gameState.getNumAgents() maxGhostIndex = numberAgents - 1 maxScore, action = self.maxNode(gameState, 1, pacmanIndex, maxGhostIndex) return action #util.raiseNotDefined() def maxNode(self, gameState, depth, pacmanIndex, maxGhostIndex): if depth > self.depth: return (self.evaluationFunction(gameState), None) legalMoves = gameState.getLegalActions(pacmanIndex) if len(legalMoves) == 0: return (self.evaluationFunction(gameState), None) calcMins = [] firstGhostIndex = 1 for action in legalMoves: successorGameState = gameState.generateSuccessor(pacmanIndex, action) calcMins.append(self.minNode(successorGameState, depth, firstGhostIndex,maxGhostIndex, pacmanIndex)[0]) maxScore = max(calcMins) indices = [i for i in range(len(calcMins)) if calcMins[i] == maxScore] return (maxScore, legalMoves[indices[0]]) def minNode(self, gameState, depth, ghostIndex, maxGhostIndex, pacmanIndex): legalMoves = gameState.getLegalActions(ghostIndex) if len(legalMoves) == 0: return (self.evaluationFunction(gameState), None) calcMins = [] if ghostIndex < maxGhostIndex: for action in legalMoves: successorGameState = gameState.generateSuccessor(ghostIndex, action) calcMins.append(self.minNode(successorGameState, depth, ghostIndex + 1, maxGhostIndex, pacmanIndex)[0]) if ghostIndex == maxGhostIndex: for action in legalMoves: successorGameState = gameState.generateSuccessor(ghostIndex, action) calcMins.append(self.maxNode(successorGameState, depth + 1, pacmanIndex, maxGhostIndex)[0]) minScore = min(calcMins) indices = [i for i in range(len(calcMins)) if calcMins[i] == minScore] return (minScore, legalMoves[indices[0]]) class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def __init__(self, *args, **kwargs): self.posSaved = {} MultiAgentSearchAgent.__init__(self, *args, **kwargs) def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" #util.raiseNotDefined() pacmanIndex = 0 ghostIndex = 1 numberAgents = gameState.getNumAgents() maxGhostIndex = numberAgents - 1 alpha = -sys.maxint beta = sys.maxint maxScore, action = self.maxNode(alpha, beta, gameState, 1, pacmanIndex, maxGhostIndex) return action def maxNode(self, alpha, beta, gameState, depth, pacmanIndex, maxGhostIndex): if depth > self.depth: return (self.evaluationFunction(gameState), None) legalMoves = gameState.getLegalActions(pacmanIndex) if len(legalMoves) == 0: return (self.evaluationFunction(gameState), None) firstGhostIndex = 1 v = -sys.maxint * 1.0 track = None for action in legalMoves: successorGameState = gameState.generateSuccessor(pacmanIndex, action) t = v v = max(v, self.minNode(alpha, beta, successorGameState, depth, firstGhostIndex,maxGhostIndex, pacmanIndex)[0]) if t != v: track = action #prunning if (v > beta): return (v, action) alpha = max(alpha, v) return (v, track) def minNode(self, alpha, beta, gameState, depth, ghostIndex, maxGhostIndex, pacmanIndex): legalMoves = gameState.getLegalActions(ghostIndex) if len(legalMoves) == 0: return (self.evaluationFunction(gameState), None) calcMins = [] v = sys.maxint * 1.0 track = None for action in legalMoves: successorGameState = gameState.generateSuccessor(ghostIndex, action) t = v if ghostIndex < maxGhostIndex: v = min(v, self.minNode(alpha, beta, successorGameState, depth, ghostIndex + 1, maxGhostIndex, pacmanIndex)[0]) else: v = min(v, self.maxNode(alpha, beta, successorGameState, depth + 1, pacmanIndex, maxGhostIndex)[0]) if t != v: track = action #prunning if (v < alpha): return (v, action) beta = min(beta, v) return (v, track) class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def __init__(self, *args, **kwargs): self.posSaved = {} MultiAgentSearchAgent.__init__(self, *args, **kwargs) def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" #util.raiseNotDefined() pacmanIndex = 0 ghostIndex = 1 numberAgents = gameState.getNumAgents() maxGhostIndex = numberAgents - 1 maxScore, action = self.maxNode(gameState, 1, pacmanIndex, maxGhostIndex) return action def maxNode(self, gameState, depth, pacmanIndex, maxGhostIndex): if depth > self.depth: return (self.evaluationFunction(gameState), None) legalMoves = gameState.getLegalActions(pacmanIndex) if len(legalMoves) == 0: return (self.evaluationFunction(gameState), None) calcMins = [] firstGhostIndex = 1 for action in legalMoves: successorGameState = gameState.generateSuccessor(pacmanIndex, action) calcMins.append(self.expectNode(successorGameState, depth, firstGhostIndex,maxGhostIndex, pacmanIndex)[0]) maxScore = max(calcMins) indices = [i for i in range(len(calcMins)) if calcMins[i] == maxScore] return (maxScore, legalMoves[random.choice(indices)]) def expectNode(self, gameState, depth, ghostIndex, maxGhostIndex, pacmanIndex): legalMoves = gameState.getLegalActions(ghostIndex) if len(legalMoves) == 0: return (self.evaluationFunction(gameState), None) totalScore = 0.0 for action in legalMoves: successorGameState = gameState.generateSuccessor(ghostIndex, action) if ghostIndex < maxGhostIndex: totalScore = totalScore + self.expectNode(successorGameState, depth, ghostIndex + 1, maxGhostIndex, pacmanIndex)[0] else: totalScore = totalScore + self.maxNode(successorGameState, depth + 1, pacmanIndex, maxGhostIndex)[0] return (totalScore/len(legalMoves), None) FOOD_REWARD = 2 CAPSULE_REWARD = 4 GHOST_REWARD = -5 DECAY = 0.8 CLEAR_REWARD = 20 def calcKNearestFoodReward(k, pacmanPos, foodGrid, capsulesList, walls): closed = [] queue = util.Queue() queue.push(pacmanPos) closed.append(pacmanPos) findFood = 0 totalScore = 0.0 count = 0 while not queue.isEmpty(): travel = queue.pop() count = count + 1 #print count #print travel if foodGrid[travel[0]][travel[1]]: findFood = findFood + 1 if travel in capsulesList: totalScore = totalScore + pow(DECAY,manhattanDistance(pacmanPos, travel)) * CAPSULE_REWARD else: totalScore = totalScore + pow(DECAY,manhattanDistance(pacmanPos, travel)) * FOOD_REWARD if findFood == k: break for i in [-1, 0, 1]: if (travel[0] + i) < 0 or (travel[0] + i) > (foodGrid.width - 1): continue for j in [-1, 0, 1]: if (travel[1] + j) < 0 or (travel[1] + j) > (foodGrid.height - 1): continue newTravel = (travel[0] + i, travel[1] + j) if walls[travel[0] + i][travel[1] + j] or (newTravel in closed): continue closed.append(newTravel) queue.push(newTravel) if findFood == 0: score = 0 else: score = 1.0/findFood * totalScore return score def calcGhostReward(ghostStates, pacmanPos): numGhosts = len(ghostStates) totalScore = 0.0 for ghostState in ghostStates: totalScore = totalScore + (ghostState.scaredTimer == 0) *(\ GHOST_REWARD * \ (manhattanDistance(pacmanPos, ghostState.getPosition()) == 1) + 2*GHOST_REWARD * \ (manhattanDistance(pacmanPos, ghostState.getPosition()) == 0)) return totalScore def calcScaredReward(ghostStates, pacmanPos): totalScore = 0.0 for ghostState in ghostStates: totalScore = totalScore + (ghostState.scaredTimer > 0)*(ghostState.scaredTimer - manhattanDistance(pacmanPos, ghostState.getPosition())) return totalScore def calcRemainFood(gameState): foodGrid = gameState.getFood() numFoods = gameState.getNumFood() score = (foodGrid.height * foodGrid.width - numFoods) if numFoods == 0: score = score + CLEAR_REWARD return score def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" pacmanPos = currentGameState.getPacmanPosition() ghostStates = currentGameState.getGhostStates() capsulesList = currentGameState.getCapsules() walls = currentGameState.getWalls() foodGrid = currentGameState.getFood() A = calcKNearestFoodReward(3, pacmanPos, foodGrid, capsulesList, walls) B = calcGhostReward(ghostStates, pacmanPos) C = calcScaredReward(ghostStates, pacmanPos) D = calcRemainFood(currentGameState) alpha = 0.2 beta = 0.5 gamma = 0.1 theta = 0.2 return (alpha*A + beta*B + gamma*C + theta*D) # Abbreviation better = betterEvaluationFunction
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,365
mothaibatacungmua/AI-course
refs/heads/master
/PyML/theano/const.py
from layer import \ ConvPoolLayer, \ HiddenLayer, \ BatchNormalizationLayer, \ DropoutLayer, \ LogisticRegression LAYER_TYPES = { 'ConvPoolLayer': ConvPoolLayer, 'HiddenLayer': HiddenLayer, 'BatchNormalizationLayer': BatchNormalizationLayer, 'DropoutLayer': DropoutLayer, 'LogisticRegressionLayer': LogisticRegression }
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,366
mothaibatacungmua/AI-course
refs/heads/master
/blackjack/blackjack.py
import sys import re import random # Credit: https://inst.eecs.berkeley.edu/~cs188/sp08/projects/blackjack/blackjack.py # Note that this solution ignores naturals. # A hand is represented as a pair (total, ace) where: # - total is the point total of cards in the hand (counting aces as 1) # - ace is true iff the hand contains an ace # Return the empty hand. def empty_hand(): return (0, False) # Return whether the hand has a useable ace # Note that a hand may contain an ace, but it might not be useable def hand_has_useable_ace(hand): total, ace = hand return ((ace) and (total + 10) <= 21) # Return the value of the hand # The value of the hand is either total or total + 10 (if the ace is useable) def hand_value(hand): total, ace = hand if (hand_has_useable_ace(hand)): return (total + 10) else: return total # Update a hand by adding a card to it # Return the new hand def hand_add_card(hand, card): total, ace = hand total += card if card == 1: ace = True; return (total,ace) # Return the reward of the game (-1, 0, or 1) given the final player and dealer # hands def game_reward(player_hand, dealer_hand): player_val = hand_value(player_hand) dealer_val = hand_value(dealer_hand) if player_val > 21: return -1.0 elif dealer_val > 21: return 1.0 elif player_val < dealer_val: return -1.0 elif player_val == dealer_val: return 0.0 elif player_val > dealer_val: return 1.0 # Draw a card from an unbiased deck. # Return the face value of the card (1 to 10) def draw_card_unbiased(): card = random.randint(1, 13) if card > 10: card = 10 return card # Draw a card from a biased deck rich in tens and aces # Return the face value of the card (1 to 10) def draw_card_biased(): # choose ace with probability 11/130 r = random.randint(1,130) if r <= 11: return 1 # choose ten with probability 11/130 if r <= 22: return 10 # else choose 2-9, J, Q, K with equal probability card = random.randint(2, 12) if card > 10: card = 10 return card # Deal a player hand given the function to draw cards # Return only the hand def deal_player_hand(draw): hand = empty_hand() hand = hand_add_card(hand, draw()) hand = hand_add_card(hand, draw()) while hand_value(hand) < 11: hand = hand_add_card(hand, draw()) return hand # Deal the first card of a dealer hand given the function to draw cards. # Return the hand and the shown card def deal_dealer_hand(draw): hand = empty_hand() card = draw() hand = hand_add_card(hand, card) return hand, card # Play the dealer hand using the fixed strategy for the dealer # Return the resulting dealer hand def play_dealer_hand(hand, draw): while hand_value(hand) < 17: hand = hand_add_card(hand, draw()) return hand # States are tuples (card, val, useable) where # - card is the card the dealer is showing # - val is the current value of the player's hand # - useable is whether or not the player has a useable ace # Action are either stay (False) or hit(True) def select_random_state(all_states): n = len(all_states) r = random.randint(0, n-1) state = all_states[r] return state # Select an action at random def select_random_action(): r = random.randint(1, 2) return (r == 1) # Select the best action using current Q-values def select_best_action(Q, state): if Q[(state, True)] > Q[(state, False)]: return True return False # Select an action according to the epsilon-greddy policy def select_e_greedy_action(Q, state, epsilon): r = random.random() if r < epsilon: return select_random_action() return select_best_action(Q, state) # Given the state, return the player and dealer hand consistent with it def hands_from_state(state): card, val, useable = state if useable: val -= 10 player_hand = (val, useable) dealer_hand = empty_hand() dealer_hand = hand_add_card(dealer_hand, card) return card, dealer_hand, player_hand # Given the dealer's card and player's hand, return state def state_from_hands(card, player_hand): val = hand_value(player_hand) useable = hand_has_useable_ace(player_hand) return (card, val, useable) # Return a list of the possible states def state_list(): states = [] for card in range(1,11): for val in range(11, 21): states.append((card, val, False)) states.append((card, val, True)) return states # Return a map of all (state, action) pairs -> values (initially zero) def initialize_state_action_value_map(): states = state_list() M = {} for state in states: M[(state, False)] = 0.0 M[(state, True)] = 0.0 return M # Print a (state, action) -> value map def print_state_action_value_map(M): for useable in [True, False]: if useable: print 'Useable ace' else: print 'No useable ace' print 'Values for staying' for val in range(21, 10, -1): for card in range(1, 11): print "%5.2f" % M[((card, val, useable), False)], ' ', print '| %d' % val print 'Values for hitting:' for val in range(21, 10, -1): for card in range(1, 11): print '%5.2f' % M[((card, val, useable), True)], ' ', print '| %d' % val print ' ' # Print the state-action-value function (Q) def print_Q(Q): print '---- Q(s,a) ----' print_state_action_value_map(Q) # Print the state-value function (V) given the Q-values def print_V(Q): print '---- V(s) ----' for useable in [True, False]: if useable: print 'Usable ace' else: print 'No useable ace' for val in range(21, 10, -1): for card in range(1, 11): if Q[((card, val, useable), True)] > Q[((card, val, useable), False)]: print '%5.2f' % Q[((card, val, useable), True)], ' ', else: print '%5.2f' % Q[((card, val, useable), False)], ' ', print '| %d' % val print ' ' # Print a policy given the Q-values def print_policy(Q): print '---- Policy ----' for useable in [True, False]: if useable: print 'Usable ace' else: print 'No useable ace' for val in range(21, 10, -1): for card in range(1, 11): if Q[((card, val, useable), True)] > Q[((card, val, useable), False)]: print 'X', else: print ' ', print '| %d' % val print ' ' # Initialize Q-values so that they produce the intial policy of sticking # only 20 or 21 def initialize_Q(): states = state_list() M = {} for state in states: card, val, useable = state if val < 20: M[(state, False)] = -0.001 M[(state, True)] = 0.001 else: M[(state, False)] = 0.001 M[(state, True)] = 0.001 return M # Initialize number of times each (state, action) pair has been observed def initialize_count(): count = initialize_state_action_value_map() return count # Monte-Carlo ES # # Run Monte-Carlo for the specified number of iterations and return Q-values def monte_carlo_es(draw, n_iter): # initialize Q and observation count Q = initialize_Q() count = initialize_count() # get list of all states all_states = state_list() # iterate for n in range(0, n_iter): # initialize list of (state, action) pairs encountered in episode sa_list = [] # pick starting (state, action) using exploring starts state = select_random_state(all_states) action = select_random_action() dealer_card, dealer_hand, player_hand = hands_from_state(state) # update the (state, action) list sa_list.append((state, action)) # generate the episode while action: player_hand = hand_add_card(player_hand, draw()) if hand_value(player_hand) > 21: break state = state_from_hands(dealer_card, player_hand) action = select_best_action(Q, state) sa_list.append((state, action)) # allow the dealer to play dealer_hand = play_dealer_hand(dealer_hand, draw) R = game_reward(player_hand, dealer_hand) # update Q using average return for sa in sa_list: Q[sa] = (Q[sa] * count[sa] + R)/ (count[sa] + 1) count[sa] += 1 return Q # Q-learning # # Run Q-learning for the specified number of iterations and return the Q-values # In this implementation, alpha decreases over time def q_learning(draw, n_iter, alpha, epsilon): # initialize Q and count Q = initialize_Q() count = initialize_count() # get list of all states all_states = state_list() # iterate for n in range(0, n_iter): # initialize state state = select_random_state(all_states) dealer_card, dealer_hand, player_hand = hands_from_state(state) # choose actions, update Q while(True): action = select_e_greedy_action(Q, state, epsilon) sa = (state, action) if action: # draw a card, update state player_hand = hand_add_card(player_hand, draw()) # check if busted if hand_value(player_hand) > 21: # update Q-value count[sa] += 1.0 Q[sa] = Q[sa] + alpha/count[sa] * (-1.0 - Q[sa]) break else: # update Q-value s_next = state_from_hands(dealer_card, player_hand) q_best = Q[(s_next, False)] if Q[(s_next, True)] > Q[(s_next, False)]: q_best = Q[(s_next, True)] count[sa] += 1.0 Q[sa] = Q[sa] + alpha/count[sa] * (q_best - Q[sa]) # update state state = s_next else: # allow the dealer to play dealer_hand = play_dealer_hand(dealer_hand, draw) # compute return R = game_reward(player_hand, dealer_hand) # update Q-value count[sa] += 1.0 Q[sa] = Q[sa] + alpha/count[sa] * (R - Q[sa]) return Q # Sarsa def sarsa(draw, n_iter, alpha, epsilon): # initialize Q and count Q = initialize_Q() count = initialize_count() # get list of all states all_states = state_list() # iterate for n in range(0, n_iter): # initialize state state = select_random_state(all_states) dealer_card, dealer_hand, player_hand = hands_from_state(state) # choose actions, update Q while (True): action = select_e_greedy_action(Q, state, epsilon) sa = (state, action) if action: # draw a card, update state player_hand = hand_add_card(player_hand, draw()) # check if busted if hand_value(player_hand) > 21: # update Q-value count[sa] += 1.0 Q[sa] = Q[sa] + alpha / count[sa] * (-1.0 - Q[sa]) break else: s_next = state_from_hands(dealer_card, player_hand) action_ep = select_e_greedy_action(Q, s_next, epsilon) q_eq = Q[(s_next, action_ep)] count[sa] += + 1.0 Q[sa] = Q[sa] + alpha / count[sa] * (q_eq - Q[sa]) # update state state = s_next else: # allow the dealer to play dealer_hand = play_dealer_hand(dealer_hand, draw) # compute return R = game_reward(player_hand, dealer_hand) # update Q-value count[sa] += 1.0 Q[sa] = Q[sa] + alpha / count[sa] * (R - Q[sa]) return Q # Compute the expected value of the game using the learned Q-values or Sarsa def expected_gain(draw, Q, n_iter): gain = 0.0 for n in range(n_iter): player_hand = deal_player_hand(draw) dealer_hand = deal_dealer_hand(draw) state = state_from_hands(dealer_hand, player_hand) v = Q[(state, False)] if Q[(state, True)] > v: v = Q[(state, True)] gain = gain + v print 'Expected gain: %6.3f' % (gain / float(n_iter)) print ' ' # main progam # set parameters if __name__ == '__main__': n_iter_mc = 10000000 n_iter_q = 10000000 n_games = 100000 alpha = 1 epsilon = 0.1 # run learning algorithms print 'MONTE CARLO ES -- UNBIASED DECK' Q = monte_carlo_es(draw_card_unbiased, n_iter_mc) print_Q(Q) print_V(Q) print_policy(Q) expected_gain(draw_card_unbiased, Q, n_games) print 'MONTE CARLO ES -- BIASED DECK' Q = monte_carlo_es(draw_card_biased, n_iter_q) print_Q(Q) print_V(Q) print_policy(Q) expected_gain(draw_card_biased, Q, n_games) print 'Q-LEARNING -- UNBIASED DECK' Q = q_learning(draw_card_unbiased, n_iter_q, alpha, epsilon) print_Q(Q) print_V(Q) print_policy(Q) expected_gain(draw_card_unbiased, Q, n_games) print 'Q-LEARNING -- BIASED DECK' Q = q_learning(draw_card_biased, n_iter_q, alpha, epsilon) print_Q(Q) print_V(Q) print_policy(Q) expected_gain(draw_card_biased, Q, n_games) print 'SASRA-LEARNING -- UNBIASED DECK' Q = sarsa(draw_card_unbiased, n_iter_q, alpha, epsilon) print_Q(Q) print_V(Q) print_policy(Q) expected_gain(draw_card_unbiased, Q, n_games) print 'SASRA-LEARNING -- BIASED DECK' Q = sarsa(draw_card_biased, n_iter_q, alpha, epsilon) print_Q(Q) print_V(Q) print_policy(Q) expected_gain(draw_card_biased, Q, n_games)
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,367
mothaibatacungmua/AI-course
refs/heads/master
/PyML/libs/mnist_loader.py
import cPickle import gzip import numpy as np import matplotlib.pyplot as plt import matplotlib import theano import theano.tensor as T mnist_train = None mnist_validation = None mnist_test = None def load_data(): global mnist_train, mnist_validation, mnist_test if mnist_train is None: f = gzip.open('../data/mnist.pkl.gz') mnist_train, mnist_validation, mnist_test = cPickle.load(f) f.close() return mnist_train, mnist_validation, mnist_test def display_image(index): train, validation, test = load_data() pixels_arr = train[0][index] mat = pixels_arr.reshape(28, 28) plt.figure(figsize=(3,3)) #plt.imshow(mat, cmap='gray') plt.imshow(mat, cmap=matplotlib.cm.binary) plt.show() def neunet_data_wrapper(): train, validation, test = load_data() train_inputs = [np.reshape(x, (784, 1)) for x in train[0]] train_outputs = [vectorized_result(y) for y in train[1]] train_data = zip(train_inputs, train_outputs) validation_inputs = [np.reshape(x, (784,1)) for x in validation[0]] validation_outputs = [vectorized_result(y) for y in validation[1]] validation_data = zip(validation_inputs, validation_outputs) test_inputs = [np.reshape(x, (784,1)) for x in test[0]] test_outputs = [vectorized_result(y) for y in test[1]] test_data = zip(test_inputs, test_outputs) return (train_data, validation_data, test_data) def vectorized_result(j): e = np.zeros((10, 1)) e[j] = 1.0 return e def softmax_data_wrapper(): train, validation, test = load_data() return (train, validation, test) def svm_data_wrapper(): return softmax_data_wrapper() def shared_dat(Xy, borrow=True): X, y = Xy shared_X = theano.shared(np.asarray(X, dtype=theano.config.floatX), borrow=borrow) shared_y = theano.shared(np.asarray(y, dtype=theano.config.floatX), borrow=borrow) return shared_X, T.cast(shared_y, 'int32') ''' if __name__ == '__main__': display_image(10) pass '''
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,368
mothaibatacungmua/AI-course
refs/heads/master
/bayesian/discrete_inverse_CDF.py
import matplotlib.pyplot as plt import numpy as np x = np.arange(0, 6, 0.01) y = [np.floor(x[i])/6 for i in range(0, len(x))] fig, ax = plt.subplots() ax.plot(x, y) ax.grid(True) ax.set_title('CDF of Fair Six-Sided Side') u = np.random.uniform(0, 1, 10000) dice_samples = [] for i in u: if 0 <= i and i < 1.0/6: dice_samples.append(1) elif 1.0/6 <= i and i < 2.0/6: dice_samples.append(2) elif 2.0/6 <= i and i < 3.0/6: dice_samples.append(3) elif 3.0 / 6 <= i and i < 4.0 / 6: dice_samples.append(4) elif 4.0 / 6 <= i and i < 5.0 / 6: dice_samples.append(5) elif 5.0 / 6 <= i and i < 6.0 / 6: dice_samples.append(6) probs = [0.] for i in range(1,7): probs.append(dice_samples.count(i)) probs = np.array(probs)*1. / len(dice_samples) estimated_cdf = np.cumsum(probs) outcomes = np.arange(0, 7, 1) print probs fig, ax = plt.subplots() ax.plot(outcomes, estimated_cdf) ax.grid(True) ax.set_title('Estimated CDF of Fair Six-Sided Side') plt.show()
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,369
mothaibatacungmua/AI-course
refs/heads/master
/PyML/theano/latent_gaussian.py
import matplotlib.pyplot as plt import numpy as np import theano from theano import tensor as T epsilon = np.array(1e-4, dtype=theano.config.floatX) def normal_cdf(x, location=0, scale=1): location = T.cast(location, theano.config.floatX) scale = T.cast(scale, theano.config.floatX) div = T.sqrt(2 * scale ** 2 + epsilon) div = T.cast(div, theano.config.floatX) erf_arg = (x - location) / div return .5 * (1 + T.erf(erf_arg + epsilon)) rng = np.random.RandomState(123456) N = 500 hidden_nodes = 30 e_samples = np.asarray(np.random.exponential(0.5, N), dtype=theano.config.floatX) log_samples = np.log(e_samples) fig, ax = plt.subplots() ax.hist(e_samples, 30, normed=True, color='red') ax.set_title('Origin Skewness Distribution') Wh = theano.shared(value=np.asarray(rng.uniform(-1, 1, (hidden_nodes,)), dtype=theano.config.floatX), borrow=True) bh = theano.shared(value=np.zeros((hidden_nodes,), dtype=theano.config.floatX),borrow=True) Wo = theano.shared(value=np.asarray(rng.normal(size=(hidden_nodes,)), dtype=theano.config.floatX),borrow=True) bo = theano.shared(np.cast[theano.config.floatX](0.0),borrow=True) params = [Wh, bh, Wo, bo] x = T.dvector('x') shapex = T.shape(x)[0] h = T.outer(Wh,x) + T.transpose(T.tile(bh,(shapex,1))) f = theano.function([x], h) print f(e_samples) a = 1/(1 + T.exp(-h)) output = T.dot(Wo,a) + T.tile(bo, (1,shapex)) sorted_output = output.sort() pe = T.dvector('x') output_fn = theano.function([x], output) #fff = theano.function([x], sorted_output) cost = T.sqr(normal_cdf(sorted_output) - pe).sum()/shapex cost_fn = theano.function([x, pe], cost) uniform_pe = np.asarray(np.arange(1, N+1), dtype=theano.config.floatX)/N print cost_fn(e_samples, uniform_pe) #grad = [T.grad(cost, param) for param in params] learning_rate = 0.25 gamma = 0.9 # momentum updates = [] for param in params: param_update = theano.shared(param.get_value() * 0.) updates.append((param, param - learning_rate * param_update)) updates.append((param_update, gamma * param_update + (1. - gamma) * T.grad(cost, param))) train = theano.function(inputs=[x, pe],outputs=cost,updates=updates) #theano.scan(lambda ,sequences=output) #plt.show() nloops = 40000 for i in range(0, nloops): train_cost = train(log_samples, uniform_pe) if (i% 1000) == 0: print "iter:%d, cost:%08f\n" % (i, train_cost) latent_gaussian = output_fn(log_samples) latent_gaussian = np.reshape(latent_gaussian, (N, 1)) fig, ax = plt.subplots() ax.hist(latent_gaussian, 30, normed=True, color='red') ax.set_title('Latent variable Gaussian distribution') plt.show()
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,370
mothaibatacungmua/AI-course
refs/heads/master
/PyML/neunet/Adam.py
import numpy as np import random from monitor import monitor def update_mini_batch( network, mini_batch, eta, lmbda, n, epsilon, time, fraction_1, fraction_2, moments_w, moments_b): grad_b = [np.zeros(b.shape) for b in network.biases] grad_w = [np.zeros(w.shape) for w in network.weights] for x, y in mini_batch: delta_grad_b, delta_grad_w = network.backprop(x, y) grad_b = [gb + dgb for gb, dgb in zip(grad_b, delta_grad_b)] grad_w = [gw + dgw for gw, dgw in zip(grad_w, delta_grad_w)] moments_b = [(fraction_1*past[0]+(1-fraction_1)*(gb/len(mini_batch)), fraction_2*past[1] + (1-fraction_2)*(gb/len(mini_batch)) ** 2) for past, gb in zip(moments_b, grad_b)] moments_w = [(fraction_1*past[0]+(1-fraction_1)*(gw/len(mini_batch) + (lmbda/n)*w), fraction_2*past[1] + (1-fraction_2)*(gw/len(mini_batch) + (lmbda/n)*w) ** 2) for past, gw, w in zip(moments_w, grad_w,network.weights)] delta_b = [eta*m[0]/(1-fraction_1**time)/(np.sqrt(m[1]/(1-fraction_2**time)) + epsilon) for m in moments_b] delta_w = [eta*m[0]/(1-fraction_1**time)/(np.sqrt(m[1]/(1-fraction_2**time)) + epsilon) for m in moments_w] network.weights = [w - delta for w, delta in zip(network.weights, delta_w)] network.biases = [b - delta for b, delta in zip(network.biases, delta_b)] return moments_b, moments_w def Adam( network, training_data, epochs, mini_batch_size, eta, epsilon=0.00000001, lmbda = 0.0, fraction_1=0.9,fraction_2=0.9999, evaluation_data=None, monitor_evaluation_cost=False, monitor_evaluation_accuracy=False, monitor_training_cost=False, monitor_training_accuracy=False): n = len(training_data) moments_b = [(np.zeros(b.shape),np.zeros(b.shape)) for b in network.biases] moments_w = [(np.zeros(w.shape),np.zeros(w.shape)) for w in network.weights] evaluation_cost, evaluation_accuracy = [], [] training_cost, training_accuracy = [], [] for j in xrange(epochs): random.shuffle(training_data) mini_batches = [ training_data[k:k+mini_batch_size] for k in xrange(0, n, mini_batch_size) ] print "epochs[%d]" % j for mini_batch in mini_batches: moments_b, moments_w = update_mini_batch( network, mini_batch, eta, lmbda, n, epsilon, j+1, fraction_1, fraction_2, moments_b, moments_w ) monitor(network, training_data, evaluation_data, training_cost,training_accuracy,evaluation_cost,evaluation_accuracy, lmbda, monitor_evaluation_cost, monitor_evaluation_accuracy, monitor_training_cost, monitor_training_accuracy) return training_cost, training_accuracy, evaluation_cost, evaluation_accuracy
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,371
mothaibatacungmua/AI-course
refs/heads/master
/checker/tf_qvalue_net.py
import sys import numpy as np import tensorflow as tf class QValueNet(object): def __init__(self, game_size): self.game_size = game_size X = tf.placeholder(tf.float32, shape=(1, game_size * game_size), name="state") y = tf.placeholder(tf.float32, shape=(2), name="score") self.w1 = tf.get_variable("w1", shape=(self.game_size ** 2, 100), dtype=tf.float32, initializer=tf.random_normal_initializer(mean=0, stddev=0.01)) self.b1 = tf.get_variable("b1", shape=(100), dtype=tf.float32, initializer=tf.constant_initializer()) self.w2 = tf.get_variable("w2", shape=(100, 50), dtype=tf.float32, initializer=tf.random_normal_initializer(mean=0, stddev=0.01)) self.b2 = tf.get_variable("b2", shape=(50), dtype=tf.float32, initializer=tf.constant_initializer()) self.w3 = tf.get_variable("w3", shape=(50, 2), dtype=tf.float32, initializer=tf.random_normal_initializer(mean=0, stddev=0.01)) self.b3 = tf.get_variable("b3", shape=(2), dtype=tf.float32, initializer=tf.constant_initializer()) h1 = tf.sigmoid(tf.matmul(X, self.w1) + self.b1) h2 = tf.sigmoid(tf.matmul(h1, self.w2) + self.b2) self.pred = tf.sigmoid(tf.matmul(h2, self.w3) + self.b3) self.cost = tf.reduce_mean(tf.squared_difference(y, self.pred)) self.params = [self.w1, self.b1, self.w2, self.b2, self.w3, self.b3] self.train_op = self._build_train_op() self.predict_op = self._build_predict_op() self.sess = tf.Session() init_op = tf.global_variables_initializer() self.sess.run(init_op) pass def _build_train_op(self): lrn_rate = 0.01 opt = tf.train.RMSPropOptimizer(lrn_rate) trainable_variables = tf.trainable_variables() train_op = opt.minimize(self.cost, var_list=trainable_variables) return train_op def _build_predict_op(self): return self.pred def train(self, X, y): X = np.asarray(X, dtype=np.float32) X = np.reshape(X, (-1)) X = X[np.newaxis, :] y = np.asarray(y, dtype=np.float32) self.train_op.run(feed_dict={"state:0":X, "score:0":y}, session=self.sess) def predict(self, X): X = np.asarray(X, dtype=np.float32) X = np.reshape(X, (-1)) X = X[np.newaxis, :] return self.predict_op.eval(feed_dict={"state:0":X}, session=self.sess)[0]
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,372
mothaibatacungmua/AI-course
refs/heads/master
/PyML/theano/mlp.py
import theano.tensor as T import numpy as np from net import MLP, train_mlp from layer import LogisticRegression, logistic_error,DropoutLayer,HiddenLayer from PyML.libs import softmax_data_wrapper,shared_dat ''' Code based on: http://deeplearning.net/tutorial/ ''' if __name__ == '__main__': train, test, validation = softmax_data_wrapper() # index to [index]minibatch X = T.matrix('X') y = T.ivector('y') rng = np.random.RandomState(123456) classifier = MLP(X, y, logistic_error, L2_reg=0.0) #classifier.add_layer(HiddenLayer(28*28, 100, rng=rng)) #classifier.add_layer(HiddenLayer(100, 60, rng=rng)) #classifier.add_layer(LogisticRegression(60, 10)) classifier.add_layer(DropoutLayer(parent=HiddenLayer, p_dropout=0.1, npred=28 * 28, nclass=100, rng=rng)) classifier.add_layer(DropoutLayer(parent=HiddenLayer, p_dropout=0.2, npred=100, nclass=60, rng=rng)) classifier.add_layer(DropoutLayer(parent=LogisticRegression, p_dropout=0.3, npred=60, nclass=10)) train_mlp(shared_dat(train), shared_dat(test), shared_dat(validation), classifier)
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,373
mothaibatacungmua/AI-course
refs/heads/master
/PyML/libs/neunet_plots.py
import matplotlib.pyplot as plt import numpy as np def plot_training_cost(training_cost, num_epochs, training_cost_xmin): fig = plt.figure() ax = fig.add_subplot(111) ax.plot(np.arange(training_cost_xmin, num_epochs), training_cost[training_cost_xmin:num_epochs], color='#2A6EA6') ax.set_xlim([training_cost_xmin, num_epochs]) ax.grid(True) ax.set_xlabel('Epoch') ax.set_title('Cost on the training data') plt.show() def plot_tranining_accuracy(training_accuracy, num_epochs, tranining_accuracy_xmin): fig = plt.figure() ax = fig.add_subplot(111) ax.plot(np.arange(tranining_accuracy_xmin, num_epochs), training_accuracy[tranining_accuracy_xmin:num_epochs], color='#2A6EA6') ax.set_xlim([tranining_accuracy_xmin, num_epochs]) ax.grid(True) ax.set_xlabel('Epoch') ax.set_title('Accuracy (%) on the training data') plt.show() def plot_test_cost(test_cost, num_epochs, test_accuracy_xmin): fig = plt.figure() ax = fig.add_subplot(111) ax.plot(np.arange(test_accuracy_xmin, num_epochs), test_cost[test_accuracy_xmin:num_epochs], color='#2A6EA6') ax.set_xlim([test_accuracy_xmin, num_epochs]) ax.grid(True) ax.set_xlabel('Epoch') ax.set_title('Cost on the test data') plt.show() def plot_test_accuracy(test_accuracy, num_epochs, test_accuracy_xmin): fig = plt.figure() ax = fig.add_subplot(111) ax.plot(np.arange(test_accuracy_xmin, num_epochs), test_accuracy[test_accuracy_xmin:num_epochs], color='#2A6EA6') ax.set_xlim([test_accuracy_xmin, num_epochs]) ax.grid(True) ax.set_xlabel('Epoch') ax.set_title('Accuracy (%) on the test data') plt.show() def plot_comparing(training_cost, test_cost, num_epochs, xmin): fig = plt.figure() ax = fig.add_subplot(111) # Plot tranining costs ax.plot(np.arange(xmin, num_epochs), training_cost[xmin:num_epochs], label='Tranining cost', color='#2A6EA6') # Plot test costs ax.plot(np.arange(xmin, num_epochs), test_cost[xmin:num_epochs], label='Test cost', color='#FFCD33') ax.set_xlim([xmin, num_epochs-1]) ax.set_xlabel('Epoch') ax.set_ylabel('Cost') plt.legend(loc='upper right') plt.show()
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,374
mothaibatacungmua/AI-course
refs/heads/master
/bayesian/continous_inverse_CDF.py
import matplotlib.pyplot as plt import numpy as np import matplotlib.patches as mpatches alpha = 1. nsamp = 10000 #f = alpha * exp(-alpha * x) #F = 1 - exp(-alpha * x) x = np.arange(0, 10, 0.01) f = alpha* np.exp(-alpha * x) fig, ax = plt.subplots() real, = ax.plot(x, f, linewidth=2) ax.text(1.5, 0.9, r'$f(x)=1 - e^{-\alpha x}$', fontsize=14) ax.grid(True) ax.set_title('Inverse PDF for Exponential Distribution') u = np.random.uniform(0, 1, 10000) samples = 1/alpha*np.log(1/(1-u)) #note: shifting 1 for CDF sampling = ax.hist(samples, 30, normed=True, color='red') red_patch = mpatches.Patch(color='red') plt.legend([real, red_patch], ['Real', 'Estimasted']) plt.show()
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,375
mothaibatacungmua/AI-course
refs/heads/master
/PyML/neunet/AdaGrad.py
import numpy as np import random from monitor import monitor ''' AdaGrad's intuition explaining https://www.youtube.com/watch?v=0qUAb94CpOw ''' def update_mini_batch( network, mini_batch, eta, lmbda, n, epsilon, AdaGrad_b, AdaGrad_w): grad_b = [np.zeros(b.shape) for b in network.biases] grad_w = [np.zeros(w.shape) for w in network.weights] for x, y in mini_batch: delta_grad_b, delta_grad_w = network.backprop(x, y) grad_b = [gb + dgb for gb, dgb in zip(grad_b, delta_grad_b)] grad_w = [gw + dgw for gw, dgw in zip(grad_w, delta_grad_w)] AdaGrad_b = [past + (gb/len(mini_batch)) ** 2 for past, gb in zip(AdaGrad_b, grad_b)] AdaGrad_w = [past + (gw/len(mini_batch) + (lmbda/n)*w) ** 2 for past, gw, w in zip(AdaGrad_w, grad_w,network.weights)] network.weights = [w - (eta/np.sqrt(ada_w + epsilon))*(gw/len(mini_batch) + (lmbda/n)*w) for w, gw, ada_w in zip(network.weights, grad_w, AdaGrad_w)] network.biases = [b - (eta/np.sqrt(ada_b + epsilon))*(gb/len(mini_batch)) for b, gb, ada_b in zip(network.biases, grad_b, AdaGrad_b)] return AdaGrad_b, AdaGrad_w def AdaGrad( network, training_data, epochs, mini_batch_size, eta, epsilon=0.00000001, lmbda = 0.0, evaluation_data=None, monitor_evaluation_cost=False, monitor_evaluation_accuracy=False, monitor_training_cost=False, monitor_training_accuracy=False): n = len(training_data) AdaGrad_b = [np.zeros(b.shape) for b in network.biases] AdaGrad_w = [np.zeros(w.shape) for w in network.weights] evaluation_cost, evaluation_accuracy = [], [] training_cost, training_accuracy = [], [] for j in xrange(epochs): random.shuffle(training_data) mini_batches = [ training_data[k:k+mini_batch_size] for k in xrange(0, n, mini_batch_size) ] print "epochs[%d]" % j for mini_batch in mini_batches: AdaGrad_b, AdaGrad_w = update_mini_batch( network, mini_batch, eta, lmbda, n, epsilon, AdaGrad_b, AdaGrad_w ) monitor(network, training_data, evaluation_data, training_cost,training_accuracy,evaluation_cost,evaluation_accuracy, lmbda, monitor_evaluation_cost, monitor_evaluation_accuracy, monitor_training_cost, monitor_training_accuracy) return training_cost, training_accuracy, evaluation_cost, evaluation_accuracy
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,376
mothaibatacungmua/AI-course
refs/heads/master
/PyML/neunet/choxe/CNN_BN.py
import os import numpy as np import tensorflow as tf from choxe import load_data from math import ceil, floor class Convl2D(object): def __init__(self, input, nin_feature_maps, nout_feature_maps, filter_shape, strides=(1,1), activation='relu', using_bias=False, padding='SAME'): self.input = input self.nin_feature_maps = nin_feature_maps self.activation = activation self.using_bias = using_bias self.strides = strides self.padding = padding wshape = [filter_shape[0], filter_shape[1], nin_feature_maps, nout_feature_maps] weights = tf.Variable(tf.truncated_normal(wshape, stddev=0.1), trainable=True) if self.using_bias: bias = tf.Variable(tf.constant(0.1, shape=[nout_feature_maps]), trainable=True) self.bias = bias self.weights = weights if self.using_bias: self.params = [self.weights, self.bias] else: self.params = [self.weights] pass def output(self): linout = tf.nn.conv2d(self.input, self.weights, strides=[1, self.strides[0], self.strides[1], 1], padding=self.padding) if self.using_bias: linout = linout + self.bias if self.activation == 'relu': self.output = tf.nn.relu(linout) else: self.output = linout return self.output class MaxPooling2D(object): def __init__(self, input, pooling_size, padding='SAME'): self.input = input if pooling_size == None: pooling_size = [1, 2, 2, 1] self.pooling_size = pooling_size self.padding = padding def output(self): # pooling_size = stride_size strides = self.pooling_size self.output = tf.nn.max_pool(self.input, ksize=self.pooling_size, strides=strides, padding=self.padding) return self.output pass class AvgPooling2D(object): def __init__(self, input, pooling_size, padding='SAME'): self.input = input if pooling_size == None: pooling_size = [1, 2, 2, 1] self.pooling_size = pooling_size self.padding = padding def output(self): strides = self.pooling_size self.output = tf.nn.avg_pool(self.input, ksize=self.pooling_size, strides=strides, padding=self.padding) return self.output pass class FullConnectedLayer(object): def __init__(self, input, n_in, n_out, activation='relu'): self.input = input self.activation = activation weights = tf.Variable(tf.truncated_normal([n_in, n_out], mean=0.0, stddev=0.05), trainable=True) bias = tf.Variable(tf.zeros([n_out]), trainable=True) self.weights = weights self.bias = bias self.params = [self.weights, self.bias] def output(self): z = tf.matmul(self.input, self.weights) + self.bias if self.activation == 'relu': self.output = tf.nn.relu(z) elif self.activation == 'tanh': self.output = tf.nn.tanh(z) elif self.activation == 'sigmoid': self.output = tf.nn.sigmoid(z) return self.output pass class SoftmaxLayer(object): def __init__(self, input, n_in, n_out): self.input = input weights = tf.Variable(tf.random_normal([n_in, n_out],mean=0.0, stddev=0.05), trainable=True) bias = tf.Variable(tf.zeros([n_out]), trainable=True) self.weights = weights self.bias = bias self.params = [self.weights, self.bias] def output(self): z = tf.matmul(self.input, self.weights) + self.bias self.output = tf.nn.softmax(z) return self.output pass ''' paper: https://arxiv.org/abs/1502.03167 ref: http://stackoverflow.com/questions/33949786/how-could-i-use-batch-normalization-in-tensorflow ''' def batch_norm(X, phase_train): with tf.variable_scope('bn'): params_shape = [X.get_shape()[-1]] beta = tf.Variable(tf.constant(0.0, shape=params_shape), name='beta', trainable=True) gamma = tf.Variable(tf.constant(0.0, shape=params_shape), name='gamma', trainable=True) batch_mean, batch_var = tf.nn.moments(X, [0,1,2], name='moments') ema = tf.train.ExponentialMovingAverage(decay=0.5) # see section 3.1 in the paper def moving_avg_update(): ema_apply_op = ema.apply([batch_mean, batch_var]) with tf.control_dependencies([ema_apply_op]): return tf.identity(batch_mean), tf.identity(batch_var) mean, var = tf.cond(phase_train, moving_avg_update, lambda: (ema.average(batch_mean), ema.average(batch_var))) normed = tf.nn.batch_normalization(X, mean, var, beta, gamma, 1e-3) return normed def evaluation(y_pred, y): correct = tf.equal(tf.argmax(y_pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct, tf.float32)) return accuracy def cnn_bn_model(X, y, dropout_prob, phase_train): ''' + -1 for size of mini-batch, + 256x256 is size of image + 3 is three channels RBG ''' X_image = tf.reshape(X, [-1, 256, 256, 3]) ''' output height and width padding "SAME": out_height = ceil(float(in_height) / float(strides[1])) out_width = ceil(float(in_width) / float(strides[2])) output height and width padding "VALID": out_height = ceil(float(in_height - filter_height + 1) / float(strides[1])) out_width = ceil(float(in_width - filter_width + 1) / float(strides[2])) ref: https://www.tensorflow.org/api_docs/python/nn/convolution#conv2d ''' def compute_output_size(input_size, filter_size, strides, padding): if padding == 'SAME': out_height = ceil(float(input_size[0]) / float(strides[0])) out_width = ceil(float(input_size[1]) / float(strides[1])) else: #padding == 'VALID' out_height = ceil(float(input_size[0] - filter_size[0] + 1) / float(strides[0])) out_width = ceil(float(input_size[1] - filter_size[1] + 1) / float(strides[1])) return (int(out_height), int(out_width)) # Layer 1, convol window 7x7, stride width = 2, stride height = 2 with max pooling, padding = SAME # Number input channels = 3, number output channels = 64 with tf.variable_scope('conv_1'): conv1 = Convl2D(X_image, 3, 64, (7, 7), strides=(2,2), padding='SAME') conv1_bn = batch_norm(conv1.output(), phase_train) conv1_out = tf.nn.relu(conv1_bn) pool1 = MaxPooling2D(conv1_out, [1, 2, 2, 1], padding='SAME') pool1_out = pool1.output() # Layer 2, convol window 3x3, stride width = 1, stride height = 1 without pooling, padding = SAME # Number output channels: 64, number output channels = 64 with tf.variable_scope('conv_2'): conv2 = Convl2D(pool1_out, 64, 64, (3,3), strides=(1,1), padding='SAME') conv2_bn = batch_norm(conv2.output(), phase_train) conv2_out = tf.nn.relu(conv2_bn) # Layer 3, convol window 3x3, stride width = 1, stride height = 1 without pooling, padding = SAME # Number output channels: 64, number output channels = 64 with tf.variable_scope('conv_3'): conv3 = Convl2D(conv2_out, 64, 64, (3,3), strides=(1,1), padding='SAME') conv3_bn = batch_norm(conv3.output(), phase_train) conv3_out = tf.nn.relu(conv3_bn) # Layer 4, convol window 3x3, stride width = 1, stride height = 1 with avg pooling, padding = VALID # Number output channels: 64, number output channels = 128 with tf.variable_scope('conv_4'): conv4 = Convl2D(conv3_out, 64, 128, (3, 3), strides=(1, 1), padding='VALID') conv4_bn = batch_norm(conv4.output(), phase_train) conv4_out = tf.nn.relu(conv4_bn) pool4 = AvgPooling2D(conv4_out, [1, 2, 2, 1], padding='SAME') pool4_out = pool4.output() #print pool4_out.get_shape() output_size = pool4_out.get_shape()[1:3] flat_size = int(output_size[0])*int(output_size[1])*128 pool4_flatten = tf.reshape(pool4_out, [-1, flat_size]) # Layer 5: full connected layer with dropout with tf.variable_scope('fc1'): fc1 = FullConnectedLayer(pool4_flatten, flat_size, 1000) fc1_out = fc1.output() fc1_dropped = tf.nn.dropout(fc1_out, dropout_prob) y_pred = SoftmaxLayer(fc1_dropped, 1000, 3).output() cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(y_pred), reduction_indices=[1])) loss = cross_entropy accuracy = evaluation(y_pred, y) return loss, accuracy, y_pred SAVE_SESS = 'cnn_bn_choxe.ckpt' BATCH_SIZE = 100 if __name__ == '__main__': TASK = 'train' X = tf.placeholder(tf.float32, [None, 256, 256, 3]) y = tf.placeholder(tf.float32, [None, 3]) dropout_prob = tf.placeholder(tf.float32) phase_train = tf.placeholder(tf.bool, name='phase_train') loss, accuracy, y_pred = cnn_bn_model(X, y, dropout_prob, phase_train) #Train model learning_rate = 0.01 train_op = tf.train.RMSPropOptimizer(learning_rate).minimize(loss) #vars_to_save = tf.trainable_variables() init_op = tf.global_variables_initializer() if TASK == 'test': restore_sess = True elif TASK == 'train': restore_sess = False else: assert 1==0, "Task isn't supported" saver = tf.train.Saver() train_X, train_y, test_X, test_y = load_data() N = train_y.shape[0] num_batches = floor(N / BATCH_SIZE) with tf.Session() as sess: if TASK == 'train': sess.run(init_op, feed_dict={phase_train:True}) else: sess.run(init_op, feed_dict={phase_train:False}) if restore_sess: saver.restore(sess, SAVE_SESS) if TASK == 'train': print '\nTraining...' for i in range(1, 10000): mini_batch_index = i if mini_batch_index > num_batches: mini_batch_index = 1 batch_x = train_X[(mini_batch_index-1)*BATCH_SIZE:mini_batch_index*BATCH_SIZE] batch_y = train_y[(mini_batch_index-1)*BATCH_SIZE:mini_batch_index*BATCH_SIZE] train_op.run(feed_dict={X: batch_x, y: batch_y, dropout_prob: 0.5, phase_train: True}) if i % 200 == 0: cv_fd = {X: batch_x, y: batch_y, dropout_prob: 1.0, phase_train: False} train_loss = loss.eval(feed_dict = cv_fd) train_accuracy = accuracy.eval(feed_dict = cv_fd) print 'Step, loss, accurary = %6d: %8.4f, %8.4f' % (i,train_loss, train_accuracy) ''' print '\nTesting...' test_fd = {X: test_X, y: test_y, dropout_prob: 1.0, phase_train: False} print(' accuracy = %8.4f' % accuracy.eval(test_fd)) ''' # Save the session if TASK == 'train': saver.save(sess, SAVE_SESS)
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,377
mothaibatacungmua/AI-course
refs/heads/master
/PyML/neunet/basic_network.py
import random import numpy as np from libs import sigmoid, sigmoid_prime """ ~~~~~~~~ NOTE: A bag of tricks for mini-batch gradient descent 1: Initializing the weights randomly and rescaling the weights by sqrt 2: Shifting the inputs to change the error surface, making the means of input is zero 3: Scaling the inputs to change the error surface, making the variances of input is one """ class Network(object): def __init__(self, sizes): self.num_layers = len(sizes) self.sizes = sizes self.biases = [np.random.randn(y,1) for y in sizes[1:]] self.weights = [np.random.randn(y, x) for x, y in zip(sizes[:-1], sizes[:1])] def feedforward(self, a): for b,w in zip(self.biases, self.weights): a = sigmoid(np.dot(w, a) + b) pass def SGD(self, training_data, epochs, mini_batch_size, eta, test_data = None): if test_data: n_test = len(test_data) n = len(training_data) for j in xrange(epochs): random.shuffle(training_data) mini_batches = [training_data[k:k+mini_batch_size] for k in xrange(0, n, mini_batch_size)] for mini_batch in mini_batches: self.update_mini_batch(mini_batch, eta) if test_data: return (self.evaluate(test_data), n_test) pass def evaluate(self, test_data): test_results = [(np.argmax(self.feedforward(x)), y) for (x,y) in test_data] return sum(int(x == y) for (x,y) in test_results) def update_mini_batch(self, mini_batch, eta): grad_b = [np.zeros(b.shape) for b in self.biases] grad_w = [np.zeros(w.shape) for w in self.weights] for x, y in mini_batch: delta_grad_b, delta_grad_w = self.backprop(x, y) grad_b = [gd + dgd for gd, dgd in zip(grad_b, delta_grad_b)] grad_w = [gw + dgw for gw, dgw in zip(grad_w, delta_grad_w)] self.weights = [w - (eta/len(mini_batch))*gdw for w, gdw in zip(self.weights, grad_w)] self.biases = [w - (eta/len(mini_batch))*gdb for b, gdb in zip(self.biases, grad_b)] pass def backprop(self, x, y): grad_b = [np.zeros(b.shape) for b in self.biases] grad_w = [np.zeros(w.shape) for w in self.weights] #foward pass activation = x activations = [x] zs = [] for b,w in zip(self.biases, self.weights): z = np.dot(w, activation) + b zs.append(z) activation = sigmoid(z) activations.append(activation) #backward pass delta = self.cost_derivative(activations[-1], y) * sigmoid_prime(zs[-1]) grad_b[-1] = delta grad_w[-1] = np.dot(delta, activations[-2].tranpose()) for l in xrange(2, self.num_layers): z = zs[-l] sp = sigmoid_prime(z) delta = np.dot(self.weights[-l+1].tranpose(), delta)*sp grad_b[-l] = delta grad_w[-l] = np.dot(delta, activations[-l-1].tranpose()) return (grad_b, grad_w) def cost_derivative(self, output_activations, y): return (output_activations - y)
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,378
mothaibatacungmua/AI-course
refs/heads/master
/bayesian/rejection_sampling.py
import matplotlib.pyplot as plt import numpy as np import scipy.stats #f(x) = exp(-(x-1)^2/(2x))*(x+1)/12 delta_x = 0.01 x = np.arange(0.01, 20, delta_x) fig, ax = plt.subplots() f = lambda x: np.exp(-(x-1)**2/(2*x)) * (x+1)/12 fx = f(x) Fx = np.cumsum(fx) * delta_x ax.plot(x, fx, label='$f(x)$') ax.plot(x, Fx, label='$F(x)$', color='g') ax.legend(loc=0, fontsize=16) ax.set_title('True distribution') M = .3 # scale factor u1 = np.random.uniform(size=10000)*15 u2 = np.random.uniform(size=10000) idx = np.where(u2 <= f(u1)/M) samples = u1[idx] fig, ax = plt.subplots() ax.plot(x, fx, label='$f(x)$', linewidth=2) sampling = ax.hist(samples, 30, normed=True, color='red') ax.set_ylim([0.0, 1.0]) ax.set_title('Estimated distribution by uniform distribution') fig, ax = plt.subplots() ax.plot(u1, u2, '.', label='rejected', alpha=.3) ax.plot(u1[idx], u2[idx], 'g.', label='accepted', alpha=.3) ax.legend(fontsize=16) ch = scipy.stats.chi2(4) h = lambda x: f(x)/ch.pdf(x) fig, ax = plt.subplots(1, 2) fig.set_size_inches(12, 4) ax[0].plot(x, fx, label='$f(x)$') ax[0].plot(x, ch.pdf(x), label='$g(x)$') ax[0].legend(loc=0, fontsize=18) ax[1].plot(x, h(x)) ax[1].set_title('$h(x)=f(x)/g(x)$', fontsize=18) hmax = h(x).max() print hmax u1 = ch.rvs(10000) u2 = np.random.uniform(0.,1., 10000) idx = np.where(u2 <= h(u1)/hmax) v = u1[idx] fig, ax = plt.subplots() ax.hist(v, 30, normed=True) ax.plot(x, fx, 'r', linewidth=2, label='$f(x)$') ax.set_title('Estimated distribution by chi-square distribution') ax.legend(fontsize=16) fig, ax = plt.subplots() ax.plot(u1, u2, '.', label='rejected', alpha=.3) ax.plot(u1[idx], u2[idx], 'g.', label='accepted', alpha=.3) ax.plot(x, h(x)/hmax, linewidth=2, label='$h(x)$') ax.legend(fontsize=16) plt.show()
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,379
mothaibatacungmua/AI-course
refs/heads/master
/checker/checker.py
import random from tf_qvalue_net import QValueNet EMPTY = 0 PLAYER_X = 1 PLAYER_O = 2 DRAW = 3 # define number of checkers to win NUM_TO_WIN = 4 NAMES = [' ', 'X', 'O'] WIN_REWARD = 10.0 class BoardGame(object): def __init__(self, size): self.width = size self.height = size self.board_format = self.gen_board_format() def gen_board_format(self): board_format = "" delim = "\n|" + "-" * (4 * self.width - 1) + '|\n' board_format += delim for i in range(self.height): f_row = [] for j in range(self.width): f_row.append(" {" + str(i*self.width + j) + "} ") board_format += "|" + "|".join(f_row) + "|" board_format += delim return board_format def print_board(self, state): cells = [] for i in range(self.height): for j in range(self.width): cells.append(NAMES[state[i][j]]) print self.board_format.format(*cells) class Agent(object): def __init__(self, game, order, learning=True): self.epsilon = 0.1 self.game = game self.order = order self.learning = learning self.prev_state = None self.prev_score = 0.0 self.alpha = 0.1 pass def random_move(self, state): available = [] for i in range(self.game.size): for j in range(self.game.size): if state[i][j] == EMPTY: available.append((i, j)) return random.choice(available) def episode_over(self, state, last_move): gameover = self.game.is_game_over(state, last_move) if gameover != EMPTY: # update weights of neunet value = WIN_REWARD output = [0, 0] output[self.order - 1] = value output[self.order % 2] = -value if self.learning: self.game.train_state(state, output) self.prev_state = None self.prev_score = 0.0 def greedy_move(self, state): maxval = -50000.0 maxmove = None size = self.game.size for i in range(size): for j in range(size): if state[i][j] == EMPTY: state[i][j] = self.order val = self.lookup(state, (i, j)) state[i][j] = EMPTY if val > maxval: maxval = val maxmove = (i, j) self.backup(maxval) return maxmove def action(self): r = random.random() current_state = self.game.get_current_state() if r < self.epsilon: move = self.random_move(current_state) else: move = self.greedy_move(current_state) self.prev_state = current_state self.prev_score = self.lookup(self.prev_state, self.game.last_move) self.game.move(self.order, move) self.episode_over(self.game.get_current_state(), move) def look_ahead(self, state): size = self.game.size competitor = self.order%2 + 1 for i in range(size): for j in range(size): if state[i][j] == EMPTY: state[i][j] = competitor if self.game.is_game_over(state, (i, j)) == competitor: state[i][j] = EMPTY return -WIN_REWARD state[i][j] = EMPTY return self.game.get_state_value(state)[self.order-1] def lookup(self, state, move): gameover = self.game.is_game_over(state, move) if gameover == EMPTY: return self.look_ahead(state) else: return WIN_REWARD def backup(self, nextval): if not (self.prev_state is None) and self.learning: value = self.prev_score + self.alpha*(nextval - self.prev_score) output = [0, 0] output[self.order-1] = value output[self.order%2] = -value self.game.train_state(self.prev_state, output) class Checker(object): def __init__(self, size): self.board = BoardGame(size) self.size = size self._current_state = self.empty_state() self.current_player = PLAYER_X self.last_move = None self.qvaluenn = QValueNet(size) def reset(self): self._current_state = self.empty_state() self.current_player = PLAYER_X self.last_move = None def get_current_state(self): return self._current_state def get_reward(self, gameover, current_player): if gameover == current_player: return WIN_REWARD elif gameover == EMPTY: return 0 else: return -WIN_REWARD def move(self, player, move): self.last_move = move self._current_state[move[0]][move[1]] = player self.current_player = player pass def empty_state(self): state = [[EMPTY]*self.size for i in range(self.size)] return state def gen_random_state(self): state = self.empty_state() for i in range(self.size): for j in range(self.size): state[i][j] = random.randint(EMPTY, PLAYER_O) return state # X_player always plays first def get_last_move(self, state): count_x = 0 count_o = 0 for i in range(self.size): for j in range(self.size): if state[i][j] == PLAYER_O: count_o += 1 if state[i][j] == PLAYER_X: count_x += 1 if count_o == count_x: return PLAYER_O return PLAYER_X # last_move is a tuple to present the coordinate of the last move # the previous game state isn't always over yet. def is_game_over(self, state, last_move): # check horizontal def get_range(x, y, size, delta_x, delta_y): l_p = [(x, y)] t_x = x t_y = y count = 0 while True: t_x += delta_x t_y += delta_y if t_x < 0 or t_x >= size: break if t_y < 0 or t_y >= size: break count += 1 if count > NUM_TO_WIN: break l_p.append((t_x, t_y)) t_x = x t_y = y count = 0 while True: t_x -= delta_x t_y -= delta_y if t_x < 0 or t_x >= size: break if t_y < 0 or t_y >= size: break count += 1 if count > NUM_TO_WIN: break l_p.append((t_x, t_y)) if delta_x != 0: l_p = sorted(l_p, key=lambda x:x[0]) else: l_p = sorted(l_p, key=lambda x:x[1]) return l_p def is_win(state, list_points, player): #print list_points if len(list_points) < NUM_TO_WIN: return EMPTY i = 0 p = list_points[i] while i < len(list_points): while state[p[0]][p[1]] != player: i += 1 if i > (len(list_points) - NUM_TO_WIN): return EMPTY p = list_points[i] j = i p = list_points[j] while state[p[0]][p[1]] == player and j < len(list_points): j += 1 if j == len(list_points): break p = list_points[j] if (j - i) >= NUM_TO_WIN: return player i = j return EMPTY if not last_move: return EMPTY for (delta_x, delta_y) in zip([0,1,1,1], [1,0,1,-1]): list_points = get_range(last_move[0], last_move[1], self.size, delta_x, delta_y) winner = is_win(state, list_points, state[last_move[0]][last_move[1]]) if winner != EMPTY: return winner for i in range(self.size): for j in range(self.size): if state[i][j] == EMPTY: return EMPTY return DRAW def convert_state(self, state): v = [] for i in range(self.size): for j in range(self.size): v.append(state[i][j]) return v # add neural network here # return the approximation of the state-value winning of the input state def get_state_value(self, state): state_value = self.qvaluenn.predict(self.convert_state(state)) return state_value # add a state to training the neural network def train_state(self, state, output): c_in = self.convert_state(state) self.qvaluenn.train(c_in, output) def play(self, agent_x, agent_o, monitor=False): def print_winner(winner): if winner == PLAYER_X: return 'X' elif winner == PLAYER_O: return 'O' else: return 'DRAW' i = 0 winner = self.is_game_over(self._current_state, self.last_move) while winner == EMPTY: if monitor: print "\n" print "State-value:" print self.get_state_value(self._current_state) print "\n" self.board.print_board(self._current_state) raw_input() if i%2 == 0: agent_x.action() else: agent_o.action() winner = self.is_game_over(self._current_state, self.last_move) i += 1 if monitor: print "Game Over, winner:%s!\n" % print_winner(winner) print "State-value:" print self.get_state_value(self._current_state) self.board.print_board(self._current_state) self.reset() pass if __name__ == '__main__': game = Checker(5) bot_x = Agent(game, PLAYER_X, learning=True) bot_o = Agent(game, PLAYER_O, learning=True) print "Trainning...\n" bot_x.epsilon = 0.2 bot_o.epsilon = 0.2 for i in range(50000): if (i % 10) == 0: print 'Iteration:%d\n' % i if i >= 10000: bot_x.epsilon = 0.15 bot_o.epsilon = 0.15 if i >= 20000: bot_x.epsilon = 0.10 bot_o.epsilon = 0.10 game.play(bot_x, bot_o, monitor=False) bot_x.learning = False bot_o.learning = False bot_x.epsilon = 0.0 box_o.epsilon = 0.0 print "Testing...\n" for i in range(100): game.play(bot_x, bot_o, monitor=True) ''' state = [[2,1,2,1,1], [1,0,0,1,1], [2,2,1,2,1], [2,2,1,2,1], [2,2,0,2,0]] last_move = (0, 4) game = Checker(5) game.board.print_board(state) print game.is_game_over(state, last_move) '''
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,380
mothaibatacungmua/AI-course
refs/heads/master
/NLP/Assignment3/B.py
import A from sklearn.feature_extraction import DictVectorizer import sys import main import collections import nltk from sklearn import svm from sklearn.ensemble import AdaBoostClassifier from sklearn.tree import DecisionTreeClassifier import math from nltk.corpus import wordnet as wn # You might change the window size window_size = 15 def normalize_tokens(tokens, language): """Remove punctuation, apply stemming.""" try: stopwords = set(nltk.corpus.stopwords.words(language)) except IOError: stopwords = {} return [t for t in tokens if t.isalnum() and t not in stopwords] def relevance(data): ''' :param data: list of instances for a given lexelt with the following structure: { [(instance_id, left_context, head, right_context, sense_id), ...] } :return: ''' rel = collections.defaultdict(float) total = collections.defaultdict(float) corpus_tokens = set() sen_set = set() for (instance_id, left_context, head, right_context, sense_id) in data: left_tokens = normalize_tokens(nltk.word_tokenize(left_context.lower()), language) right_tokens = normalize_tokens(nltk.word_tokenize(right_context.lower()), language) tokens = left_tokens + right_tokens corpus_tokens.update(tokens) sen_set.update([sense_id]) for w in (tokens): rel[(w, sense_id)] += 1. total[w] += 1. score = {k:math.log(v/(total[k[0]]-v+1)) for k,v in rel.iteritems()} results = {} #print sen_set for sense_id in sen_set: list_key = [(k[0], v) for k,v in score.iteritems() if k[1]==sense_id] #print sense_id list_key = sorted(list_key, key=lambda v:v[1], reverse=True) #print list_key results[sense_id] = list_key[0][0] return results # B.1.a,b,c,d def extract_features(data, language, rel_dict=None): ''' :param data: list of instances for a given lexelt with the following structure: { [(instance_id, left_context, head, right_context, sense_id), ...] } :return: features: A dictionary with the following structure { instance_id: {f1:count, f2:count,...} ... } labels: A dictionary with the following structure { instance_id : sense_id } ''' features = {} labels = {} exclude_chars = [u',', u';', u'"', u"'", u'?', u'/', u')', u'(', u'*', u'&', u'%', u':', u';'] corpus_tokens = set() try: stemmer = nltk.stem.snowball.SnowballStemmer(language) except ValueError: stemmer = nltk.stem.lancaster.LancasterStemmer() # implement your code here for (instance_id, left_context, head, right_context, sense_id) in data: left_tokens = [stemmer.stem(t) for t in normalize_tokens(nltk.word_tokenize(left_context.lower()), language)][-window_size:] right_tokens = [stemmer.stem(t) for t in normalize_tokens(nltk.word_tokenize(right_context.lower()), language)][:window_size] corpus_tokens.update(left_tokens + right_tokens) labels[instance_id] = sense_id features[instance_id] = collections.defaultdict(float) for (instance_id, left_context, head, right_context, sense_id) in data: left_tokens = normalize_tokens(nltk.word_tokenize(left_context.lower()), language) right_tokens = normalize_tokens(nltk.word_tokenize(right_context.lower()), language) tks = [stemmer.stem(t) for t in left_tokens] + [stemmer.stem(t) for t in right_tokens] for w in corpus_tokens: if w not in exclude_chars: features[instance_id][u'TK_'+w] = tks.count(w)*1.0 for l in left_tokens[-window_size:]: if l not in exclude_chars: features[instance_id][u'LEFT_' + l] += 1.0 #adding hypernyms, synomous if language == 'en': for synset in wn.synsets(l)[:2]: for lemma in synset.lemmas()[:3]: if lemma.name() != l: features[instance_id][u'SYN_LEFT_' + lemma.name()] += 1.0 hypernyms = synset.hypernyms() #print hypernyms for h in hypernyms[:2]: lemma = h.lemmas()[0] features[instance_id][u'HYPER_LEFT_' + lemma.name()] = 1.0 for r in right_tokens[:window_size]: if r not in exclude_chars: features[instance_id][u'RIGHT_' + r] += 1.0 if language == 'en': for synset in wn.synsets(r)[:2]: for lemma in synset.lemmas()[:3]: if lemma.name() != r: features[instance_id][u'SYN_RIGHT_' + lemma.name()] += 1. hypernyms = synset.hypernyms() #print hypernyms for h in hypernyms[:2]: lemma = h.lemmas()[0] features[instance_id][u'HYPER_RIGHT_' + lemma.name()] = 1.0 #relevance score #print rel_dict for sense_id, w in rel_dict.iteritems(): if stemmer.stem(w) in tks: features[instance_id][u'REL_' + w + '_' + sense_id] = 1 #print features[instance_id] return features, labels # implemented for you def vectorize(train_features,test_features): ''' convert set of features to vector representation :param train_features: A dictionary with the following structure { instance_id: {f1:count, f2:count,...} ... } :param test_features: A dictionary with the following structure { instance_id: {f1:count, f2:count,...} ... } :return: X_train: A dictionary with the following structure { instance_id: [f1_count,f2_count, ...]} ... } X_test: A dictionary with the following structure { instance_id: [f1_count,f2_count, ...]} ... } ''' X_train = {} X_test = {} vec = DictVectorizer() vec.fit(train_features.values()) for instance_id in train_features: X_train[instance_id] = vec.transform(train_features[instance_id]).toarray()[0] for instance_id in test_features: X_test[instance_id] = vec.transform(test_features[instance_id]).toarray()[0] return X_train, X_test #B.1.e def feature_selection(X_train,X_test,y_train): ''' Try to select best features using good feature selection methods (chi-square or PMI) or simply you can return train, test if you want to select all features :param X_train: A dictionary with the following structure { instance_id: [f1_count,f2_count, ...]} ... } :param X_test: A dictionary with the following structure { instance_id: [f1_count,f2_count, ...]} ... } :param y_train: A dictionary with the following structure { instance_id : sense_id } :return: ''' # implement your code here #return X_train_new, X_test_new # or return all feature (no feature selection): return X_train, X_test # B.2 def classify(X_train, X_test, y_train): ''' Train the best classifier on (X_train, and y_train) then predict X_test labels :param X_train: A dictionary with the following structure { instance_id: [w_1 count, w_2 count, ...], ... } :param X_test: A dictionary with the following structure { instance_id: [w_1 count, w_2 count, ...], ... } :param y_train: A dictionary with the following structure { instance_id : sense_id } :return: results: a list of tuples (instance_id, label) where labels are predicted by the best classifier ''' results = [] clf = svm.LinearSVC() ''' clf = AdaBoostClassifier( DecisionTreeClassifier(max_depth=2), n_estimators=500, learning_rate=0.1) ''' # implement your code here X = [] y = [] for instance_id, s in X_train.iteritems(): X.append(s) y.append(y_train[instance_id]) clf.fit(X, y) for instance_id, s in X_test.iteritems(): results.append((instance_id, clf.predict(s)[0])) return results # run part B def run(train, test, language, answer): results = {} if language == 'English': language = 'en' if language == 'Spanish': language = 'spa' if language == 'Catalan': language = 'cat' for lexelt in train: rel_dict = relevance(train[lexelt]) train_features, y_train = extract_features(train[lexelt], language, rel_dict=rel_dict) test_features, _ = extract_features(test[lexelt], language, rel_dict=rel_dict) X_train, X_test = vectorize(train_features,test_features) X_train_new, X_test_new = feature_selection(X_train, X_test,y_train) results[lexelt] = classify(X_train_new, X_test_new,y_train) A.print_results(results, answer) if __name__ == '__main__': if len(sys.argv) != 2: #print 'Usage: python A.py <language>' #sys.exit(0) language = 'English' else: language = sys.argv[1] train_file = 'data/' + language + '-train.xml' dev_file = 'data/' + language + '-dev.xml' train = main.parse_data(train_file) test = main.parse_data(dev_file) #most_frequent_sense(test, sense_dict,language) output = 'Best-'+language+'.answer' run(train, test, language, output)
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,381
mothaibatacungmua/AI-course
refs/heads/master
/PyML/neunet/choxe/choxe.py
import cPickle import numpy from PIL import Image import os import numpy.matlib X = [] def get_img_files(fdir): count = 0 for filename in os.listdir(fdir): if filename.endswith(".jpg"): img = Image.open(open(fdir + filename)) # dimensions are (height, width, channel) resized_img = img.resize((256, 256), Image.ANTIALIAS) resized_img = numpy.asarray(resized_img, dtype='float32') / 256. X.append(resized_img) count += 1 return count def get_training_data(): global X X = [] count = get_img_files("./data/dong-co/") y1 = numpy.array([1, 0, 0]) y1 = numpy.matlib.repmat(y1, count, 1) count = get_img_files("./data/ngoai-that/") y2 = numpy.array([0, 1, 0]) y2 = numpy.matlib.repmat(y2, count, 1) count = get_img_files("./data/noi-that/") y3 = numpy.array([0, 0, 1]) y3 = numpy.matlib.repmat(y3, count, 1) #print len(X) X = numpy.asarray(X, dtype='float32') y = numpy.concatenate((y1, y2, y3), axis=0) #shuffle training data perm = numpy.random.permutation(y.shape[0]) X = X[perm] y = y[perm] return (X, y) def get_testing_data(): return (None, None) pass DATA_FILE = "choxe.pkl" def load_data(): if os.path.isfile(DATA_FILE): with open(DATA_FILE, 'rb') as pickle_file: return cPickle.load(pickle_file) else: X_train, y_train = get_training_data() X_test, y_test = get_testing_data() data = (X_train, y_train, X_test, y_test) with open(DATA_FILE, 'wb') as pickle_file: cPickle.dump(data, pickle_file, protocol=2) return data
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,382
mothaibatacungmua/AI-course
refs/heads/master
/PyML/libs/__init__.py
from sigmoid import * from mnist_loader import * from neunet_plots import *
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,383
mothaibatacungmua/AI-course
refs/heads/master
/PyML/tensorflow/tensorflow_basic/distributed.py
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) mnist.train ''' $ python example.py --job-name="ps" --task_index=0 $ python example.py --job-name="worker" --task_index=0 This example demonstrates asynchronous training See more: https://www.tensorflow.org/deploy/distributed ''' FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string("job_name", "", "Either 'ps' or 'worker'") tf.app.flags.DEFINE_integer("task_index", 0, "Index of task within the job") parameter_servers = ["172.30.0.187:2222"] workers = ["172.30.0.44:2222", "172.30.0.156:2222"] cluster = tf.train.ClusterSpec({"ps":parameter_servers, "worker":workers}) server = tf.train.Server(cluster, job_name=FLAGS.job_name, task_index=FLAGS.task_index) batch_size = 100 learning_rate = 0.01 training_epochs = 20 logs_path = "/tmp/mnist/1" def main(_): if FLAGS.job_name == 'ps': server.join() elif FLAGS.job_name == 'worker': # Assigns ops to the local worker by default. with tf.device(tf.train.replica_device_setter( worker_device="/job:worker/task:%d/gpu:0" % FLAGS.task_index, cluster=cluster )): # Build model... global_step = tf.contrib.framework.get_or_create_global_step() x = tf.placeholder(tf.float32, shape=[None, 784]) y_ = tf.placeholder(tf.float32, shape=[None, 10]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) y = tf.matmul(x, W) + b cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y, labels=y_)) # build train ops train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy, global_step=global_step) class _LoggerHook(tf.train.SessionRunHook): """Logs loss and runtime.""" def begin(self): pass def before_run(self, run_context): batch_x, batch_y = mnist.train.next_batch(100) return tf.train.SessionRunArgs([cross_entropy, global_step], feed_dict={x:batch_x, y_:batch_y}) def after_run(self, run_context, run_values): lost, global_step = run_values.results print("Iter:%d Lost:%0.5f" % (global_step, lost)) hooks = [tf.train.StopAtStepHook(last_step=10000), _LoggerHook()] with tf.train.MonitoredTrainingSession(master=server.target, is_chief=(FLAGS.task_index == 0), checkpoint_dir="", hooks=hooks, config=tf.ConfigProto(allow_soft_placement=True)) \ as mon_sess: while not mon_sess.should_stop(): mon_sess.run(train_op) if __name__ == '__main__': tf.app.run(main=main)
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,384
mothaibatacungmua/AI-course
refs/heads/master
/PyML/neunet/SGD.py
import numpy as np import random from monitor import monitor def update_mini_batch(network, mini_batch, eta, lmbda, n): grad_b = [np.zeros(b.shape) for b in network.biases] grad_w = [np.zeros(w.shape) for w in network.weights] for x, y in mini_batch: delta_grad_b, delta_grad_w = network.backprop(x, y) grad_b = [gb + dgb for gb, dgb in zip(grad_b, delta_grad_b)] grad_w = [gw + dgw for gw, dgw in zip(grad_w, delta_grad_w)] network.weights = [ (1-eta*(lmbda/n))*w - (eta/len(mini_batch))*gw for w,gw in zip(network.weights, grad_w)] network.biases = [b - (eta/len(mini_batch))*gb for b, gb in zip(network.biases, grad_b)] def SGD(network, training_data, epochs, mini_batch_size, eta, lmbda = 0.0, evaluation_data=None, monitor_evaluation_cost=False, monitor_evaluation_accuracy=False, monitor_training_cost=False, monitor_training_accuracy=False): n = len(training_data) evaluation_cost, evaluation_accuracy = [], [] training_cost, training_accuracy = [], [] for j in xrange(epochs): random.shuffle(training_data) mini_batches = [ training_data[k:k+mini_batch_size] for k in xrange(0, n, mini_batch_size) ] print "epochs[%d]" % j for mini_batch in mini_batches: update_mini_batch(network, mini_batch, eta, lmbda, n) monitor(network, training_data, evaluation_data, training_cost,training_accuracy,evaluation_cost,evaluation_accuracy, lmbda, monitor_evaluation_cost, monitor_evaluation_accuracy, monitor_training_cost, monitor_training_accuracy) return training_cost, training_accuracy, evaluation_cost, evaluation_accuracy
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,385
mothaibatacungmua/AI-course
refs/heads/master
/MDP/dispatcher.py
class Dispatcher(): def __init__(self): self.mapping_cb = {} pass def register(self, name, callback): self.mapping_cb[name] = callback pass def dispatch(self, name, *args, **kwargs): if self.mapping_cb.has_key(name): return self.mapping_cb[name](*args, **kwargs) return None pass
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,386
mothaibatacungmua/AI-course
refs/heads/master
/n-queen/backtracking.py
# [0, 0, 0, 0, 0, 0, 0, 0] def normal_backtracking(self): self.__count = 0 def select_unassigned(self, state, assignment): if len(assignment) == self.n: return None assigned_vars, unassigned_vars = self.get_unassigned_vars(assignment) return unassigned_vars[0], assigned_vars pass def search(self, state, assignment, domain_value): self.count = self.count + 1 if len(assignment) == self.n: return assignment, True var, assigned_vars = select_unassigned(self, state, assignment) clone_domain = [k[:] for k in domain_value] for i in domain_value[var]: s = state[:] s[var] = i if self.contraints(s, assigned_vars, var): clone_domain[var].remove(i) assignment.append((var, i)) assignment, goal = search(self, s, assignment, clone_domain) if goal: return assignment, True assignment.pop() return assignment, False assignment, goal = search(self, self.problem, [], self.init_domain_value()) ret = self.problem[:] for i in range(0, len(assignment)): ret[assignment[i][0]] = assignment[i][1] return ret, goal def mrv_backtracking(self): self.count = 0 def count_remain_values(self, state, domain_value, pos): count = 0 s = state[:] for i in domain_value[pos]: s[pos] = i if self.check_collision_at(s, pos): count = count + 1 return len(domain_value[pos]) - count def forward_checking(self, state, assignment, domain_value): s = state[:] assigned_vars, unassigned_vars = self.get_unassigned_vars(assignment) last_assigned = assignment[len(assignment)-1][0] for i in unassigned_vars: t = domain_value[i][:] for j in t: if self.check_collision((i, j), (last_assigned, state[last_assigned])): domain_value[i].remove(j) return domain_value def remove_inconsistent_values(self, pos_a, pos_b, domain_value): removed = False t = domain_value[pos_a][:] for i in t: inconsistent = True for j in domain_value[pos_b]: if not self.check_collision((pos_a, i), (pos_b, j)): inconsistent = False break if inconsistent: domain_value[pos_a].remove(i) removed = True return removed def AC3(self, assignment, domain_value): assigned_vars, unassigned_vars = self.get_unassigned_vars(assignment) queue = [] for i in range(0, len(unassigned_vars)): for j in range(i+1, len(unassigned_vars)): queue.insert(0, (unassigned_vars[i], unassigned_vars[j])) while len(queue) != 0: e = queue.pop() if remove_inconsistent_values(self, e[0], e[1], domain_value): for k in unassigned_vars: if k != e[0] and k != e[1]: queue.insert(0,(k, e[0])) return domain_value def select_mrv(self, state, assignment, domain_value): if len(assignment) == self.n: return None assigned_vars, unassigned_vars = self.get_unassigned_vars(assignment) unassigned_vars = sorted(unassigned_vars, key=lambda x: count_remain_values(self, state, domain_value, x)) return unassigned_vars[0], assigned_vars def search(self, state, assignment, domain_value): self.count = self.count + 1 if len(assignment) == self.n: return assignment, True var, assigned_vars = select_mrv(self, state, assignment, domain_value) clone_domain = [k[:] for k in domain_value] for i in domain_value[var]: s = state[:] s[var] = i if self.contraints(s, assigned_vars, var): clone_domain[var].remove(i) forward_domain = [k[:] for k in clone_domain] assignment.append((var, s[var])) #do forward checking if any if self.options.has_key('with_forward_checking') and self.options['with_forward_checking']: forward_checking(self, s, assignment, forward_domain) #do AC3 to remove inconsistents if any if self.options.has_key('AC3') and self.options['AC3']: AC3(self, assignment, forward_domain) assignment, goal = search(self, s, assignment, forward_domain) if goal: return assignment, True assignment.pop() return assignment, False pass assignment, goal = search(self, self.problem, [], self.init_domain_value()) ret = self.problem[:] for i in range(0, len(assignment)): ret[assignment[i][0]] = assignment[i][1] return ret, goal pass
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,387
mothaibatacungmua/AI-course
refs/heads/master
/n-queen/min_conflicts.py
import random def min_conflicts(self): if not self.options.has_key('max_step'): self.options['max_step'] = 1000 self.count = 0 def count_conflicts(self, state, pos, value): s = state[:] s[pos] = value return self.count_collision_at(s, pos) def find_min_conflict_value(self, state, pos): t = [x for x in range(0,self.n)] t = sorted(t, key=lambda x:count_conflicts(self, state, pos, x)) tt = [x for x in t if count_conflicts(self, state, pos, x)==count_conflicts(self, state, pos, t[0])] return tt[random.randint(0, len(tt)-1)] def search(self): state = self.problem[:] for i in range(0, self.options['max_step']): self.count = self.count + 1 conflict_vars = self.get_conflict_vars(state) if len(conflict_vars) == 0: return state, True var = conflict_vars[random.randint(0, len(conflict_vars)-1)] min_v = find_min_conflict_value(self, state, var) state[var] = min_v return state, False return search(self) pass
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,388
mothaibatacungmua/AI-course
refs/heads/master
/bayesian/metropolis_hastings.py
import numpy as np import scipy.stats import matplotlib.pyplot as plt np.random.seed(1234) N = 300 data = np.random.randn(N) fig,ax = plt.subplots() ax.hist(data, 40, normed=True, color='red') # mu ~ N(0, r^2) # x|mu ~ N(mu, sig^2) # mean(x)|mu ~ N(mu, 1/n*sig^2) # mu|mean(x) ~ N([(sig^2/n)*mu + r^2*mean(x)]/[(sig^2/n) + r^2], [(sig^2/n)*r^2]/[(sig^2/n) + r^2] # Compute analytically the posterior distribution mu0 = 3. r = 1. sig = 1. mu_post = (sig**2*mu0 + r**2*np.sum(data))/(sig**2 + r**2*N) sig_post = sig**2 * r**2 / (sig**2 + N*r**2) print "Posterior mean:%05f, Posterior variance:%05f" % (mu_post, sig_post) posterior = scipy.stats.norm(mu_post, sig_post).pdf x = np.arange(-6, 6, 0.01) fig, ax= plt.subplots() ax.plot(x, posterior(x), linewidth=2, color='g') ax.set_xlim(-0.2, 0.2) # Metropolis-Hastings method proposal_sd = 2. mu_prior_mu = 3. mu_prior_sd = 2. mu_init = 1.5 Ns = 10000 mu_current = mu_init posterior = [mu_current] for i in range(0, Ns): # suggest new position mu_proposal = scipy.stats.norm(mu_current, proposal_sd**2).rvs() # Compute likehood, P(X|mu_current) and P(X|mu_proposal) likehood_current = scipy.stats.norm(mu_current, 1).pdf(data).prod() likehood_proposal = scipy.stats.norm(mu_proposal, 1).pdf(data).prod() # Compute prior probability of current and proposed mu prior_current = scipy.stats.norm(mu_prior_mu, mu_prior_sd**2).pdf(mu_current) prior_proposal = scipy.stats.norm(mu_prior_mu, mu_prior_sd**2).pdf(mu_proposal) p_current = likehood_current * prior_current p_proposal = likehood_proposal * prior_proposal # Accept proposal p_accept = p_proposal / p_current accept = np.random.rand() < p_accept if accept: mu_current = mu_proposal posterior.append(mu_current) print 'MCMC posterior mean:%05f, MCMC posterior variance:%05f' % (np.mean(posterior), np.var(posterior)) fig, ax = plt.subplots() ax.hist(posterior, 30, normed=True) theorical_mean = 0.0 theorical_var = np.var(data)/len(data) ax.set_xlim([-1, 1]) i = np.arange(0, len(posterior)) fig, ax = plt.subplots() ax.plot(i, posterior) ax.set_ylim([-0.3, 0.3]) plt.show()
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,389
mothaibatacungmua/AI-course
refs/heads/master
/PyML/neunet/cross_entropy_cost.py
import numpy as np from libs import sigmoid, sigmoid_prime class CrossEntropyCost(object): @staticmethod def fn(a, y): return np.sum(np.nan_to_num(-y*np.log(a) - (1-y)*np.log(1-a))) @staticmethod def delta(z, a, y): return (a - y) @staticmethod def output_activation(a, w, b): return sigmoid(np.dot(w, a) + b)
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,390
mothaibatacungmua/AI-course
refs/heads/master
/logic-reasoning/logic.py
#!/usr/bin/env python3 # https://github.com/aimacode/aima-python/blob/master/logic.py from .utils import ( Expr, expr, first, subexpression ) import itertools class KB: def __init__(self, sentence=None): raise NotImplementedError def tell(self, sentence): "Add the sentence to the KB" raise NotImplementedError def ask(self, query): """Return a subsitution that makes the query true, or, failing that, return false""" raise NotImplementedError def ask_generator(self, query): "Yield all the substitutions that make query true" raise NotImplementedError def retract(self, sentence): "Remove sentence from the KB" raise NotImplementedError class PropKB(KB): def __init__(self, sentence=None): self.clauses = [] if sentence: self.tell(sentence) def tell(self, sentence): "Add the sentence's clauses to the KB" self.clauses.extend(conjuncts(to_cnf(sentence))) def ask_generator(self, query): "Yield the empty substitution {} if KB entails query; else no results" if tt_entails(Expr('&', self.clauses), query): yield {} def ask_if_true(self, query): "Return True if the KB entails query, else return False." for _ in self.ask_generator(query): return True return False def retract(self, sentence): "Remove the sentence's clauses from the KB." for c in conjuncts(to_cnf(sentence)): if c in self.clauses: self.clauses.remove(c) def KB_AgentProgram(KB): """A generic logical knowledge-based agent program. [Figure 7.1]""" steps = itertools.count() def program(percept): t = next(steps) KB.tell(make_percept_sentence(percept, t)) action = KB.ask(make_action_query(t)) KB.tell(make_action_sentence(action, t)) return action def make_percept_sentence(self, percept, t): return Expr("Percept")(percept, t) def make_action_query(self, t): return expr("ShouldDo(action, {})".format(t)) def make_action_sentence(self, action, t): return Expr("Did")(action[expr('action')], t) return program #______________________________________________________________________ def is_symbol(s): "A string s is a symbol if it starts with an alphabetic char" return isinstance(s, str) and s[:1].isalpha() def is_var_symbol(s): "A logic variable symbol is an initial-lowercase string" return is_symbol(s) and s[0].islower() def is_prop_symbol(s): "A proposition logic symbol is an initial-uppercase string" return is_symbol(s) and s[0].isupper() def prop_symbols(x): "Return a list of all propositional symbols in x." if not isinstance(x, Expr): return [] elif is_prop_symbol(x.op): return [x] else: return list(set(symbol for arg in x.args for symbol in prop_symbols(arg))) def variables(s): """Return a set of the variables in expression s. >>> variables(expr('F(x, x) & G(x, y) & H(y, z) & R(A, z, 2)')) == {x, y ,z} True """ return {x for x in subexpression(s) is is_variable(x)} #_______________________________________________________________________ def tt_true(s): """Is a propositional senetence a tautology? >>> tt_true('P | ~P') True """ s = expr(s) return tt_entails(True, s) def tt_entails(kb, alpha): """Does kb entail the sentence alpha? Use truth tables. For propositional kb's and sentences. [Figure 7.10]. Note that the 'kb' should be an Expr which is a conjunction of clauses. >>> tt_entails(expr('P & Q'), expr('Q')) True """ assert not variables(alpha) return tt_check_all(kb, alpha, prop_symbols(kb & alpha), {}) def tt_check_all(kb, alpha, symbols, model): "Auxiliary routine to implement tt_entails" if not symbols: if pl_true(kb, model): result = pl_true(alpha, model) assert result in (True, False) return result else: return True def pl_true(exp, model={}): """Return True if the propositional logic expression is true in the model, and False if it is false. If the model does not specify the value for every proposition, this may return None to indicate 'not obvious';this may happen even when the expression is tautological. """ if exp in (True, False): return exp op, args = exp.op, exp.args if is_prop_symbol(op): return model.get(exp) elif op == '~': p = pl_true(args[0], model) if p is None: return None else: return not p elif op == '|': result = False for arg in args: p = pl_true(arg, model) if p is True: return True if p is None: return None return result elif op == '&': result = True for arg in args: p = pl_true(arg, model) if p is False: return False if p is None: return None return result p, q = args if op == '==>': return pl_true(~p | q, model) elif op == '<==': return pl_true(p | ~q, model) pt = pl_true(p, model) if pt is None: return None qt = pl_true(q, model) if qt is None: return None if op == '<=>': return pt == qt elif op == '^': #xor or 'not equivalent' return pt != qt else: raise ValueError('illegal operator in logic expression' + str(exp)) # Convert to Conjunctive Normal Form (CNF) def to_cnf(s): """Convert a propositional logical sentence to conjunctive normal form. That is, to the form ((A | ~B | ...) & (B | C | ...) & ...) [p.253] >>> to_cnf('~(B | C)') (~B & ~C) """ s = expr(s) if isinstance(s, str): s = expr(s) s = eliminate_implication(s) s = move_not_inwards(s) return distribute_and_over_or(s) def eliminate_implication(s): "Change implication into equivalent form with only &, |, and ~ as logical operators." s = expr(s) if not s.args or is_symbol(s.op): return s args = list(map(eliminate_implication, s.args)) a, b = args[0], args[-1] if s.op == '==>': return b | ~a elif s.op == '<==': return a | ~b elif s.op == '<=>': return (a | ~b) & (b | ~a) elif s.op == '^': assert len(args) == 2 #TODO: relax this restriction return (a & ~b) | (~a & b) else: assert s.op in ('&', '|', '~') return Expr(s.op, *args) def move_not_inwards(s): """Rewrite sentence s by moving negation sign inward >>> move_not_inwards(~(A | B)) (~A & ~B) """ s = expr(s) if s.op == '~': def NOT(b): return move_not_inwards(~b) a = s.args[0] if a.op == '~': return move_not_inwards(a.args[0]) if a.op == '&': return associate('|', list(map(NOT, a.args))) if a.op == '|': return associate('&', list(map(NOT, a.args))) return s def distribute_and_over_or(s): """Given a sentence s consisting of conjunctions and disjunctions of literals, return an equivalent sentence in CNF. >>> distribute_and_over_or((A & B) | C) ((A | C) & (B | C)) """ s = expr(s) if s.op == '|': s = associate('|', s.args) if s.op != '|': return distribute_and_over_or(s) if len(s.args) == 0: return False if len(s.args) == 1: return distribute_and_over_or(s.args[0]) conj = first(arg for arg in s.args if arg.op == '&') if not conj: return s others = [a for a in s.args if a is not conj] rest = associate('|', others) return associate('&', [distribute_and_over_or(c | rest) for c in conj.args]) elif s.op == '&': return associate('&', list(map(distribute_and_over_or, s.args))) else: return s _op_identity = {'&': True, '|': False, '+': 0, '*': 1} def associate(op, args): """Given an associate op, return an expression with the same meaning as Expr(op, *args), but flattened -- that is, with nested instances of the same op promoted to the top level >>> associate('&', [(A&B),(B|C), (B&C)]) (A & B & (B|C) & B & C) >>> associate('|', [A|(B|(C|(A&B)))]) (A | B | C | (A & B)) """ args = dissociate(op, args) if len(args) == 0: return _op_identity[op] elif len(args) == 1: return args[0] else: return Expr(op, *args) def dissociate(op, args): """Given an associative op, return a flattened list result such that Expr(op, *result) means the same as Expr(op, *args). """ result = [] def collect(subargs): for arg in subargs: if arg.op == op: collect(arg.args) else: result.append(arg) collect(args) return result def conjuncts(s): """Return a list of the conjuncts in the sentence s >>> conjuncts(A & B) [A, B] >>> conjuncts(A | B) [(A | B)] """ return dissociate('&', [s]) def disjuncts(s): """Return a list of the disjuncts in the sentence s. >>> disjuncts(A | B) [A, B] >>> disjuncts(A & B) [(A & B)] """ return dissociate('|', [s]) def extend(s, var, val): "Copy the substitution s and extend it by setting var to val; return copy" s2 = s.copy() s2[var] = val return s2 def is_variable(x): "A variable is an Expr with no args and a lowercase symbol as the op." return isinstance(x, Expr) and not x.args and x.op[0].islower()
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,391
mothaibatacungmua/AI-course
refs/heads/master
/n-queen/simulated_annealing.py
def simulated_annealing(self): pass
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,392
mothaibatacungmua/AI-course
refs/heads/master
/MDP/grid.py
from dispatcher import Dispatcher from rectangle import MDPRectangle from random import randint class Grid(Dispatcher): @staticmethod def regcb(inst): inst.register("left-mouse-click", inst.cb_left_mouse_click) pass def __init__(self, canvas, x, y, num_x, num_y, rec_width, rec_height, reccls, rec_options={}): Dispatcher.__init__(self) self.canvas = canvas self.x = x self.y = y self.num_x = num_x self.num_y = num_y self.rec_width = rec_width self.rec_height = rec_height self.reccls = reccls self.rec_options = rec_options self.map_rec = {} Grid.regcb(self) def cb_left_mouse_click(self, *args, **kwargs): event = kwargs['event'] pos_x = (event.x - self.x)/self.rec_width pos_y = (event.y - self.y)/self.rec_height if self.map_rec.has_key((pos_x, pos_y)): rec = self.map_rec[(pos_x, pos_y)] rec.dispatch('left-mouse-click', *args, **kwargs) pass def draw(self, *args, **kwargs): for i in range(0, self.num_x): for j in range(0, self.num_y): new_rec = self.reccls(self.canvas, i*self.rec_width + self.x, j*self.rec_height + self.y, self.rec_width, self.rec_height, self.rec_options, *args, **kwargs) new_rec.draw() self.map_rec[(i,j)] = new_rec pass class MDPGrid(Grid): VALUE_ITER = 0 POLICY_ITER = 1 ACTION = { 'LEFT':0, 'RIGHT':1, 'TOWARD':2 } @staticmethod def regcb(inst): inst.register("left-mouse-click", inst.cb_left_mouse_click) inst.register("right-mouse-click", inst.cb_right_mouse_click) pass def __init__(self, canvas, x, y, num_x, num_y, rec_width, rec_height, rec_options={}, num_iter_id = None, text_iter = None): Grid.__init__(self,canvas, x, y, num_x, num_y, rec_width, rec_height, MDPRectangle, rec_options) MDPGrid.regcb(self) self.num_iter_id = num_iter_id self.start_point = None self.goal_point = None self.pit_point = None self.probs = None self.mode = MDPGrid.VALUE_ITER self.loop_count = 0 self.stop = False self.walls = () self.action_reward = 0.0 self.discount_factor = 0.9 self.policy = None self.text_iter = text_iter def reset(self): self.loop_count = 0 self.stop = False self.walls = () self.policy = None def config(self, probs={'LEFT':0.1, 'RIGHT':0.1, 'TOWARD':0.8}, mode = VALUE_ITER, action_reward = -0.04, discount_factor = 0.9): self.probs = probs self.mode = mode self.stop = False self.action_reward = action_reward self.discount_factor = discount_factor if mode == MDPGrid.VALUE_ITER: self.canvas.itemconfigure(self.text_iter, text="Value Iterations:") else: self.canvas.itemconfigure(self.text_iter, text="Policy Iterations:") pass def set_point(self, x, y, reward, color, sign=False): if not self.map_rec.has_key((x, y)): return False rec = self.map_rec[(x, y)] rec.change_value(reward, sign) rec.change_color(color) return True pass def set_start_point(self, x, y, color): if self.set_point(x, y, 0.0, color): self.start_point = (x, y) pass def set_goal_reward(self, x, y, reward, color): if self.set_point(x, y, reward, color, True): self.goal_point = (x, y) pass def set_pit_reward(self, x, y, reward, color): if self.set_point(x, y, reward, color): self.pit_point = (x, y) pass def set_wall(self, x, y, color): if self.set_point(x, y, None, color): self.walls = self.walls + ((x,y),) pass def get_successors(self, state): #left state left_state = (state[0]-1, state[1]) #right state right_state = (state[0]+1, state[1]) #toward state toward_state = (state[0], state[1]-1) #downward state downward_state = (state[0], state[1]+1) if not self.map_rec.has_key(left_state) or left_state in self.walls: left_state = state if not self.map_rec.has_key(right_state) or right_state in self.walls: right_state = state if not self.map_rec.has_key(toward_state) or toward_state in self.walls: toward_state = state if not self.map_rec.has_key(downward_state) or downward_state in self.walls: downward_state = state return {'WEST':left_state, 'EAST':right_state, 'SOUTH':downward_state, 'NORTH':toward_state} def calc_action_value(self, state, action, map_values): kw_successors = self.get_successors(state) ret = self.action_reward for k,v in kw_successors.iteritems(): value = map_values[v]['value'] if k == action: ret += self.discount_factor*self.probs['TOWARD']*value else: #There are a lot of if statements at here, I can make it more simple #but I want to remain them because it's eaiser to see with bellman equation if action == 'WEST' and k == 'EAST': ret += self.discount_factor * 0.0 *value if action == 'WEST' and k == 'NORTH': ret += self.discount_factor * self.probs['RIGHT'] * value if action == 'WEST' and k == 'SOUTH': ret += self.discount_factor * self.probs['LEFT'] * value if action == 'EAST' and k == 'WEST': ret += self.discount_factor * 0.0 * value if action == 'EAST' and k == 'NORTH': ret += self.discount_factor * self.probs['LEFT'] * value if action == 'EAST' and k == 'SOUTH': ret += self.discount_factor * self.probs['RIGHT'] * value if action == 'NORTH' and k == 'WEST': ret += self.discount_factor * self.probs['LEFT'] * value if action == 'NORTH' and k == 'EAST': ret += self.discount_factor * self.probs['RIGHT'] * value if action == 'NORTH' and k == 'SOUTH': ret += self.discount_factor * 0.0 * value if action == 'SOUTH' and k == 'WEST': ret += self.discount_factor * self.probs['RIGHT'] * value if action == 'SOUTH' and k == 'EAST': ret += self.discount_factor * self.probs['LEFT'] * value if action == 'SOUTH' and k == 'NORTH': ret += self.discount_factor * 0.0 * value return ret pass def calc_state_value(self, state, map_values): map_rec = self.map_rec[state] if state == self.goal_point or state == self.pit_point: return map_rec.value l = [] for action in ['NORTH', 'EAST', 'SOUTH', 'WEST']: l.append((self.calc_action_value(state, action, map_values), action)) l = sorted(l, key=lambda e: e[0], reverse=True) #if(state == (2,1)): # print l return l[0] pass def copy_map_values(self): copy_map = {} for i in range(0, self.num_x): for j in range(0, self.num_y): copy_map[(i,j)] = {'value':self.map_rec[(i,j)].value, 'dir':self.map_rec[(i,j)].direction} return copy_map def run_value_iteration(self): copy_map = self.copy_map_values() for i in range(0, self.num_x): for j in range(0, self.num_y): if (i,j) == self.goal_point or (i,j) == self.pit_point or (i,j) in self.walls: continue map_rec = self.map_rec[(i,j)] #update value and policy value, action = self.calc_state_value((i,j),copy_map) map_rec.change_value(round(value,4)) map_rec.change_direction(action) pass def copy_policy(self, policy): clone = {} for i in range(0, self.num_x): for j in range(0, self.num_y): clone[(i,j)] = {'value':policy[(i,j)]['value'], 'dir':policy[(i, j)]['dir']} return clone def policy_evaluation(self, policy, loop): for i in range(0, loop): clone = self.copy_policy(policy) # so stupid for j in range(0, self.num_x): for k in range(0, self.num_y): if (j, k) == self.goal_point or (j, k) == self.pit_point or (j, k) in self.walls: continue policy[(j,k)]['value'] = self.calc_action_value((j,k), policy[(j,k)]['dir'], clone) return policy pass def random_init_policy(self): dirs = ['NORTH', 'EAST', 'SOUTH', 'WEST'] policy = {} for i in range(0, self.num_x): for j in range(0, self.num_y): policy[(i, j)] = {'value':self.map_rec[(i, j)].value, 'dir':dirs[randint(0,3)]} return policy def run_policy_iteration(self): self.policy_evaluation(self.policy, 30) clone = self.copy_policy(self.policy) for i in range(0, self.num_x): for j in range(0, self.num_y): if (i, j) == self.goal_point or (i, j) == self.pit_point or (i, j) in self.walls: continue map_rec = self.map_rec[(i, j)] map_rec.change_value(round(self.policy[(i,j)]['value'], 4)) map_rec.change_direction(self.policy[(i,j)]['dir']) value, action = self.calc_state_value((i, j), clone) if value > self.policy[(i,j)]['value']: self.policy[i,j]['dir'] = action pass def cb_left_mouse_click(self, *args, **kwargs): if self.mode == MDPGrid.VALUE_ITER: self.run_value_iteration() if self.mode == MDPGrid.POLICY_ITER: if self.policy == None: self.policy = self.random_init_policy() self.run_policy_iteration() self.loop_count += 1 self.canvas.itemconfigure(self.num_iter_id, text = str(self.loop_count)) def cb_right_mouse_click(self, *args, **kwargs): self.reset() if kwargs.has_key('event'): kwargs.pop('event', None) self.draw(*args, **kwargs) self.config() self.set_start_point(0, 2, 'blue') self.set_goal_reward(3, 0, 1, 'green') self.set_pit_reward(3, 1, -1, 'red') self.set_wall(1, 1, 'gray')
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,393
mothaibatacungmua/AI-course
refs/heads/master
/checker/q_value_net.py
import theano import sys import numpy as np from theano import tensor as T class QValueNet(object): def __init__(self, game_size): self.train = None self.game_size = game_size X = T.vector() y = T.vector() self.w1 = self.init_weights((self.game_size ** 2, 10), "w1") self.w2 = self.init_weights((10, 20), "w2") self.wo = self.init_weights((20, 2), "wo") t = self.feedforward(X, self.w1, self.w2, self.wo) cost = T.mean(T.sqr(t - y)) params = [self.w1, self.w2, self.wo] updates = self.RMSprop(cost, params) self.train = theano.function(inputs=[X, y], outputs=cost, updates=updates, allow_input_downcast=True) self.predict = theano.function(inputs=[X], outputs=t) pass def floatX(self, X): return np.asarray(X, dtype = theano.config.floatX) def init_weights(self, shape, name): return theano.shared(self.floatX(np.random.randn(*shape) * 0.01), name=name) def RMSprop(self, cost, params, lr=0.001, rho=0.9, epsilon=1e-6): grads = T.grad(cost, wrt=params) updates = [] for p, g in zip(params, grads): acc = theano.shared(p.get_value()*0.) acc_new = rho * acc + (1-rho) * g**2 gradient_scaling = T.sqrt(acc_new + epsilon) g = g / gradient_scaling updates.append((acc, acc_new)) updates.append((p, p - lr * g)) return updates def feedforward(self, X, w1, w2, wo): a1 = T.nnet.sigmoid(T.dot(X, w1)) a2 = T.nnet.sigmoid(T.dot(a1, w2)) a_o = T.dot(a2, wo) return a_o
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,394
mothaibatacungmua/AI-course
refs/heads/master
/PyML/neunet/Adadelta.py
import numpy as np import random from monitor import monitor def update_mini_batch( network, mini_batch, lmbda, n, epsilon, fraction, RMS_b, RMS_w): grad_b = [np.zeros(b.shape) for b in network.biases] grad_w = [np.zeros(w.shape) for w in network.weights] for x, y in mini_batch: delta_grad_b, delta_grad_w = network.backprop(x, y) grad_b = [gb + dgb for gb, dgb in zip(grad_b, delta_grad_b)] grad_w = [gw + dgw for gw, dgw in zip(grad_w, delta_grad_w)] #update RMS(g) before RMS_b = [(rms[0], fraction*rms[1] + (1-fraction)*(grad / len(mini_batch)) ** 2) for rms, grad in zip(RMS_b, grad_b)] RMS_w = [(rms[0], fraction*rms[1] + (1-fraction)*(grad / len(mini_batch) + w*(lmbda / n)) ** 2) for rms, grad, w in zip(RMS_w, grad_w, network.weights)] delta_w = [-(np.sqrt(rms_w[0] + epsilon) / np.sqrt(rms_w[1] + epsilon)) * (gw/len(mini_batch) + w*(lmbda / n)) for w, gw, rms_w in zip(network.weights, grad_w, RMS_w)] delta_b = [-(np.sqrt(rms_b[0] + epsilon) / np.sqrt(rms_b[1] + epsilon)) * (gb/len(mini_batch)) for b, gb, rms_b in zip(network.biases, grad_b, RMS_b)] network.weights = [w + delta for w, delta in zip(network.weights, delta_w)] network.biases = [b + delta for b, delta in zip(network.biases, delta_b)] # update RMS(delta_parameter) after RMS_b = [(fraction * rms[0] + (1 - fraction) * delta ** 2, rms[1]) for rms, delta in zip(RMS_b, delta_b)] RMS_w = [(fraction * rms[0] + (1 - fraction) * delta ** 2, rms[1]) for rms, delta in zip(RMS_w, delta_w)] return RMS_b, RMS_w def Adadelta( network, training_data, epochs, mini_batch_size, eta, epsilon=0.00000001, lmbda=0.0, fraction = 0.9, evaluation_data=None, monitor_evaluation_cost=False, monitor_evaluation_accuracy=False, monitor_training_cost=False, monitor_training_accuracy=False): n = len(training_data) RMS_b = [(np.zeros(b.shape), np.zeros(b.shape)) for b in network.biases] RMS_w = [(np.zeros(w.shape), np.zeros(w.shape)) for w in network.weights] evaluation_cost, evaluation_accuracy = [], [] training_cost, training_accuracy = [], [] for j in xrange(epochs): random.shuffle(training_data) mini_batches = [ training_data[k:k + mini_batch_size] for k in xrange(0, n, mini_batch_size) ] print "epochs[%d]" % j for mini_batch in mini_batches: RMS_b, RMS_w = update_mini_batch( network, mini_batch, eta, lmbda, n, epsilon, fraction, RMS_b, RMS_w ) monitor(network, training_data, evaluation_data, training_cost, training_accuracy, evaluation_cost, evaluation_accuracy, lmbda, monitor_evaluation_cost, monitor_evaluation_accuracy, monitor_training_cost, monitor_training_accuracy)
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,395
mothaibatacungmua/AI-course
refs/heads/master
/PyML/neunet/run.py
from advance_network import Network from PyML.libs import neunet_data_wrapper from quadratic_cost import QuadraticCost from cross_entropy_cost import CrossEntropyCost from softmax_cost import SoftmaxCost from PyML.libs import plot_comparing, plot_training_cost, plot_test_cost training_data, validation_data, test_data = neunet_data_wrapper() print 'Trainning...' quadratic_mnist_net = Network([784, 30, 10], cost=QuadraticCost) cross_entropy_mnist_net = Network([784, 30, 10], cost=CrossEntropyCost) softmax_mnist_net = Network([784, 30, 10], cost=SoftmaxCost) epochs = 30 training_cost, training_accuracy, evaluation_cost, evaluation_accuracy = \ cross_entropy_mnist_net.AdaGrad(training_data, epochs, 10, 0.001, lmbda=0.1, epsilon=0.00000001, evaluation_data=test_data, monitor_evaluation_cost=True, monitor_evaluation_accuracy=True, monitor_training_cost=True, monitor_training_accuracy=True) #plot_training_cost(training_cost, epochs, 0) #plot_test_cost(evaluation_cost, epochs, 0) #print evaluation_accuracy plot_comparing(training_cost, evaluation_cost, epochs, 0) print 'Test accuracy: %0.2f' % evaluation_accuracy[-1] print 'Finished!'
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,396
mothaibatacungmua/AI-course
refs/heads/master
/NLP/Assignment2/solutionsB.py
import sys import nltk import math import time import collections import itertools START_SYMBOL = '*' STOP_SYMBOL = 'STOP' RARE_SYMBOL = '_RARE_' RARE_WORD_MAX_FREQ = 5 LOG_PROB_OF_ZERO = -1000 # TODO: IMPLEMENT THIS FUNCTION # Receives a list of tagged sentences and processes each sentence to generate a list of words and a list of tags. # Each sentence is a string of space separated "WORD/TAG" tokens, with a newline character in the end. # Remember to include start and stop symbols in yout returned lists, as defined by the constants START_SYMBOL and STOP_SYMBOL. # brown_words (the list of words) should be a list where every element is a list of the tags of a particular sentence. # brown_tags (the list of tags) should be a list where every element is a list of the tags of a particular sentence. def split_wordtags(brown_train): brown_words = [] brown_tags = [] for s in brown_train: tokens = s.strip().split() s_words = [START_SYMBOL]*2 s_tags = [START_SYMBOL]*2 for wtag in tokens: lidx = wtag.rindex(u'/') word = wtag[:lidx] tag = wtag[lidx+1:] s_words.append(word) s_tags.append(tag) s_words.append(STOP_SYMBOL) s_tags.append(STOP_SYMBOL) brown_words.append(s_words) brown_tags.append(s_tags) return brown_words, brown_tags # TODO: IMPLEMENT THIS FUNCTION # This function takes tags from the training data and calculates tag trigram probabilities. # It returns a python dictionary where the keys are tuples that represent the tag trigram, and the values are the log probability of that trigram def calc_trigrams(brown_tags): #print brown_tags[0] #q_values = {} #unigram_c = collections.defaultdict(int) bigram_c = collections.defaultdict(int) trigram_c = collections.defaultdict(int) for stags in brown_tags: unigram_tuples = stags bigram_tuples = list(nltk.bigrams(stags)) trigram_tuples = list(nltk.trigrams(stags)) #print unigram_tuples #for g in unigram_tuples: #unigram_c[g] += 1 for g in bigram_tuples: bigram_c[g] += 1 for g in trigram_tuples: trigram_c[g] += 1 bigram_c[(START_SYMBOL, START_SYMBOL)] = len(brown_tags) q_values = {k: math.log(float(v) / bigram_c[k[:2]], 2) for k, v in trigram_c.iteritems()} return q_values # This function takes output from calc_trigrams() and outputs it in the proper format def q2_output(q_values, filename): outfile = open(filename, "w") trigrams = q_values.keys() trigrams.sort() for trigram in trigrams: output = " ".join(['TRIGRAM', trigram[0], trigram[1], trigram[2], str(q_values[trigram])]) outfile.write(output + '\n') outfile.close() # TODO: IMPLEMENT THIS FUNCTION # Takes the words from the training data and returns a set of all of the words that occur more than 5 times (use RARE_WORD_MAX_FREQ) # brown_words is a python list where every element is a python list of the words of a particular sentence. # Note: words that appear exactly 5 times should be considered rare! def calc_known(brown_words): #print brown_words[0] known_words = set([]) com_words = collections.defaultdict(int) for swords in brown_words: for w in swords: com_words[w] += 1 for k,v in com_words.iteritems(): if v > 5: known_words.add(k) return known_words # TODO: IMPLEMENT THIS FUNCTION # Takes the words from the training data and a set of words that should not be replaced for '_RARE_' # Returns the equivalent to brown_words but replacing the unknown words by '_RARE_' (use RARE_SYMBOL constant) def replace_rare(brown_words, known_words): brown_words_rare = [] for swords in brown_words: newsw = swords[:] for i in range(len(newsw)): if not newsw[i] in known_words: newsw[i] = RARE_SYMBOL brown_words_rare.append(newsw) return brown_words_rare # This function takes the ouput from replace_rare and outputs it to a file def q3_output(rare, filename): outfile = open(filename, 'w') for sentence in rare: outfile.write(' '.join(sentence[2:-1]) + '\n') outfile.close() # TODO: IMPLEMENT THIS FUNCTION # Calculates emission probabilities and creates a set of all possible tags # The first return value is a python dictionary where each key is a tuple in which the first element is a word # and the second is a tag, and the value is the log probability of the emission of the word given the tag # The second return value is a set of all possible tags for this data set def calc_emission(brown_words_rare, brown_tags): e_values = {} taglist = set([]) wordtags = collections.defaultdict(int) tagdict = collections.defaultdict(int) for i in range(len(brown_words_rare)): for w,t in zip(brown_words_rare[i], brown_tags[i]): wordtags[(w,t)] += 1 tagdict[t] += 1 taglist.add(t) e_values = {k:math.log(v*1.0, 2) - math.log(tagdict[k[1]]*1.0, 2) for k,v in wordtags.iteritems()} taglist = set([k for k in tagdict.keys()]) return e_values, taglist # This function takes the output from calc_emissions() and outputs it def q4_output(e_values, filename): outfile = open(filename, "w") emissions = e_values.keys() emissions.sort() for item in emissions: output = " ".join([item[0], item[1], str(e_values[item])]) outfile.write(output + '\n') outfile.close() # TODO: IMPLEMENT THIS FUNCTION # This function takes data to tag (brown_dev_words), a set of all possible tags (taglist), a set of all known words (known_words), # trigram probabilities (q_values) and emission probabilities (e_values) and outputs a list where every element is a tagged sentence # (in the WORD/TAG format, separated by spaces and with a newline in the end, just like our input tagged data) # brown_dev_words is a python list where every element is a python list of the words of a particular sentence. # taglist is a set of all possible tags # known_words is a set of all known words # q_values is from the return of calc_trigrams() # e_values is from the return of calc_emissions() # The return value is a list of tagged sentences in the format "WORD/TAG", separated by spaces. Each sentence is a string with a # terminal newline, not a list of tokens. Remember also that the output should not contain the "_RARE_" symbol, but rather the # original words of the sentence! def viterbi(brown_dev_words, taglist, known_words, q_values, e_values): tagged = [] f = collections.defaultdict(float) back_pointers= {} back_pointers[(-1, START_SYMBOL, START_SYMBOL)] = START_SYMBOL f[(-1, START_SYMBOL, START_SYMBOL)] = 0.0 for sen_words in brown_dev_words: tokens = [w if w in known_words else RARE_SYMBOL for w in sen_words] for w in taglist: word_tag = (tokens[0], w) trigram = (START_SYMBOL, START_SYMBOL, w) f[(0, START_SYMBOL, w)] = f[(-1, START_SYMBOL, START_SYMBOL)] + \ q_values.get(trigram, LOG_PROB_OF_ZERO) + \ e_values.get(word_tag, LOG_PROB_OF_ZERO) back_pointers[(0, START_SYMBOL, w)] = START_SYMBOL for w in taglist: for u in taglist: word_tag = (tokens[1], u) trigram = (START_SYMBOL, w, u) f[(1, w, u)] = f.get((0, START_SYMBOL, w), LOG_PROB_OF_ZERO) + \ q_values.get(trigram, LOG_PROB_OF_ZERO) + \ e_values.get(word_tag, LOG_PROB_OF_ZERO) back_pointers[(1, w, u)] = START_SYMBOL for k in range(2, len(tokens)): for tt in taglist: for t in taglist: max_prob = float('-Inf') max_tag = '' for ttt in taglist: score = f.get((k - 1, ttt, tt), LOG_PROB_OF_ZERO) + \ q_values.get((ttt, tt, t), LOG_PROB_OF_ZERO) + \ e_values.get((tokens[k], t), LOG_PROB_OF_ZERO) if (score > max_prob): max_prob = score max_tag = ttt back_pointers[(k, tt, t)] = max_tag f[(k, tt, t)] = max_prob max_log_prob = float('-Inf') ttt_max, tt_max = None, None for (ttt, tt) in itertools.product(taglist, taglist): log_prob = q_values.get((ttt, tt, STOP_SYMBOL), LOG_PROB_OF_ZERO) + \ f.get((len(tokens) - 1, ttt, tt), LOG_PROB_OF_ZERO) if log_prob > max_log_prob: max_log_prob = log_prob ttt_max = ttt tt_max = tt sen_tagged = [] sen_tagged.append(tt_max) sen_tagged.append(ttt_max) for count, i in enumerate(range(len(tokens)-3,-1,-1)): sen_tagged.append(back_pointers[(i+2, sen_tagged[count+1], sen_tagged[count])]) sen_tagged.reverse() wtagged = [] for wt in zip(sen_words, sen_tagged): wtagged.append(wt[0]+'/'+wt[1]) wtagged.append('\n') tagged.append(' '.join(wtagged)) return tagged # This function takes the output of viterbi() and outputs it to file def q5_output(tagged, filename): outfile = open(filename, 'w') for sentence in tagged: outfile.write(sentence) outfile.close() # TODO: IMPLEMENT THIS FUNCTION # This function uses nltk to create the taggers described in question 6 # brown_words and brown_tags is the data to be used in training # brown_dev_words is the data that should be tagged # The return value is a list of tagged sentences in the format "WORD/TAG", separated by spaces. Each sentence is a string with a # terminal newline, not a list of tokens. def nltk_tagger(brown_words, brown_tags, brown_dev_words): # Hint: use the following line to format data to what NLTK expects for training training = [ zip(brown_words[i],brown_tags[i]) for i in xrange(len(brown_words)) ] # IMPLEMENT THE REST OF THE FUNCTION HERE tagged = [] default_tagger = nltk.DefaultTagger('NOUN') bigram_tagger = nltk.BigramTagger(training, backoff=default_tagger) trigram_tagger = nltk.TrigramTagger(training, backoff=bigram_tagger) for s in brown_dev_words: tagged.append(' '.join([word + '/' + tag for word, tag in trigram_tagger.tag(s)]) + '\n') return tagged # This function takes the output of nltk_tagger() and outputs it to file def q6_output(tagged, filename): outfile = open(filename, 'w') for sentence in tagged: outfile.write(sentence) outfile.close() DATA_PATH = 'data/' OUTPUT_PATH = 'output/' def main(): # start timer time.clock() # open Brown training data infile = open(DATA_PATH + "Brown_tagged_train.txt", "r") brown_train = infile.readlines() infile.close() # split words and tags, and add start and stop symbols (question 1) brown_words, brown_tags = split_wordtags(brown_train) # calculate tag trigram probabilities (question 2) q_values = calc_trigrams(brown_tags) # question 2 output q2_output(q_values, OUTPUT_PATH + 'B2.txt') # calculate list of words with count > 5 (question 3) known_words = calc_known(brown_words) # get a version of brown_words with rare words replace with '_RARE_' (question 3) brown_words_rare = replace_rare(brown_words, known_words) # question 3 output q3_output(brown_words_rare, OUTPUT_PATH + "B3.txt") # calculate emission probabilities (question 4) e_values, taglist = calc_emission(brown_words_rare, brown_tags) # question 4 output q4_output(e_values, OUTPUT_PATH + "B4.txt") # delete unneceessary data del brown_train del brown_words_rare # open Brown development data (question 5) infile = open(DATA_PATH + "Brown_dev.txt", "r") brown_dev = infile.readlines() infile.close() # format Brown development data here brown_dev_words = [] for sentence in brown_dev: brown_dev_words.append(sentence.split(" ")[:-1]) # do viterbi on brown_dev_words (question 5) viterbi_tagged = viterbi(brown_dev_words, taglist, known_words, q_values, e_values) # question 5 output q5_output(viterbi_tagged, OUTPUT_PATH + 'B5.txt') # do nltk tagging here nltk_tagged = nltk_tagger(brown_words, brown_tags, brown_dev_words) # question 6 output q6_output(nltk_tagged, OUTPUT_PATH + 'B6.txt') # print total time to run Part B print "Part B time: " + str(time.clock()) + ' sec' if __name__ == "__main__": main()
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,397
mothaibatacungmua/AI-course
refs/heads/master
/PyML/tensorflow/tensorflow_basic/hello_distributed.py
import tensorflow as tf c = tf.constant("Hello, distributed Tensorflow") server = tf.train.Server.create_local_server() sess = tf.Session(server.target) result = sess.run(c) print result
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,398
mothaibatacungmua/AI-course
refs/heads/master
/NLP/Assignment3/A.py
import main from sklearn import svm from sklearn import neighbors import sys import nltk import collections import codecs # don't change the window size window_size = 10 # A.1 def build_s(data): ''' Compute the context vector for each lexelt :param data: dic with the following structure: { lexelt: [(instance_id, left_context, head, right_context, sense_id), ...], ... } :return: dic s with the following structure: { lexelt: [w1,w2,w3, ...], ... } ''' s = collections.defaultdict(set) # implement your code here for k,v in data.iteritems(): for (instance_id, left_context, head, right_context, sense_id) in v: # left_context s[k].update(nltk.word_tokenize(left_context)[-window_size:]) # right_context s[k].update(nltk.word_tokenize(right_context)[:window_size]) s = {k:list(v) for k,v in s.iteritems()} return s # A.1 def vectorize(data, s): ''' :param data: list of instances for a given lexelt with the following structure: { [(instance_id, left_context, head, right_context, sense_id), ...] } :param s: list of words (features) for a given lexelt: [w1,w2,w3, ...] :return: vectors: A dictionary with the following structure { instance_id: [w_1 count, w_2 count, ...], ... } labels: A dictionary with the following structure { instance_id : sense_id } ''' vectors = {} labels = {} # implement your code here # exclude_chars = [u',', u';', u'"',u"'",u'?',u'/',u')',u'(',u'*',u'&',u'%',u':',u';'] for (instance_id, left_context, head, right_context, sense_id) in data: tks = nltk.word_tokenize(left_context) + nltk.word_tokenize(right_context) vectors[instance_id] = [tks.count(w) for w in s] labels[instance_id] = sense_id return vectors, labels # A.2 def classify(X_train, X_test, y_train): ''' Train two classifiers on (X_train, and y_train) then predict X_test labels :param X_train: A dictionary with the following structure { instance_id: [w_1 count, w_2 count, ...], ... } :param X_test: A dictionary with the following structure { instance_id: [w_1 count, w_2 count, ...], ... } :param y_train: A dictionary with the following structure { instance_id : sense_id } :return: svm_results: a list of tuples (instance_id, label) where labels are predicted by LinearSVC knn_results: a list of tuples (instance_id, label) where labels are predicted by KNeighborsClassifier ''' # implement your code here svm_results = [] knn_results = [] svm_clf = svm.LinearSVC() knn_clf = neighbors.KNeighborsClassifier() X = [] y = [] for instance_id, s in X_train.iteritems(): X.append(s) y.append(y_train[instance_id]) svm_clf.fit(X,y) knn_clf.fit(X,y) for instance_id, s in X_test.iteritems(): svm_results.append((instance_id, svm_clf.predict(s)[0])) knn_results.append((instance_id, knn_clf.predict(s)[0])) return svm_results, knn_results # A.3, A.4 output def print_results(results ,output_file): ''' :param results: A dictionary with key = lexelt and value = a list of tuples (instance_id, label) :param output_file: file to write output ''' # implement your code here # don't forget to remove the accent of characters using main.replace_accented(input_str) # you should sort results on instance_id before printing fo = codecs.open(output_file, encoding='utf-8', mode='w') for lexelt, instances in sorted(results.iteritems(), key=lambda d: main.replace_accented(d[0].split('.')[0])): for instance_id, sid in sorted(instances, key=lambda d: int(d[0].split('.')[-1])): fo.write(main.replace_accented(lexelt + ' ' + instance_id + ' ' + sid + '\n')) fo.close() # run part A def run(train, test, language, knn_file, svm_file): s = build_s(train) svm_results = {} knn_results = {} for lexelt in s: X_train, y_train = vectorize(train[lexelt], s[lexelt]) X_test, _ = vectorize(test[lexelt], s[lexelt]) svm_results[lexelt], knn_results[lexelt] = classify(X_train, X_test, y_train) print_results(svm_results, svm_file) print_results(knn_results, knn_file) if __name__ == '__main__': if len(sys.argv) != 2: #print 'Usage: python A.py <language>' #sys.exit(0) language = 'English' else: language = sys.argv[1] train_file = 'data/' + language + '-train.xml' dev_file = 'data/' + language + '-dev.xml' train = main.parse_data(train_file) test = main.parse_data(dev_file) #most_frequent_sense(test, sense_dict,language) svm_output = 'SVM-'+language+'.answer' knn_output = 'KNN-' + language + '.answer' run(train, test, language, knn_output, svm_output)
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,399
mothaibatacungmua/AI-course
refs/heads/master
/PyML/neunet/choxe/ResNet.py
import numpy as np import tensorflow as tf from choxe import load_data from CNN_BN import AvgPooling2D, MaxPooling2D, SoftmaxLayer, batch_norm, \ FullConnectedLayer, evaluation, Convl2D from math import floor ''' ref: https://github.com/tensorflow/models/blob/master/resnet ''' ''' Related Papers: [1] https://arxiv.org/pdf/1603.05027v2.pdf [2] https://arxiv.org/pdf/1512.03385v1.pdf [3] https://arxiv.org/pdf/1605.07146v1.pdf ''' RELU_LEAKINESS = 0.1 #http://cs231n.github.io/neural-networks-1/ def leaky_relu(x, leakiness=0.0): return tf.where(tf.less(x,0.0), leakiness * x, x, name='leaky_relu') # See Normal Residual block and Bottleneck residual block in Figure 5 in the paper [2] def residual(x, nin_feature_maps, nout_feature_maps, strides, activate_before_residual=False, phase_train=True): '''Residual unit with 2 sub layers''' if activate_before_residual: with tf.variable_scope('shared_activation'): x = batch_norm(x, phase_train) x = leaky_relu(x, RELU_LEAKINESS) orig_x = x else: with tf.variable_scope('residual_only_activation'): orig_x = x x = batch_norm(x, phase_train) x = leaky_relu(x, RELU_LEAKINESS) with tf.variable_scope('sub1'): cv = Convl2D(x, nin_feature_maps, nout_feature_maps, (3,3), strides=strides) x = cv.output() with tf.variable_scope('sub2'): x = batch_norm(x, phase_train) x = leaky_relu(x, RELU_LEAKINESS) cv = Convl2D(x, nout_feature_maps, nout_feature_maps, (3,3), strides=(1,1)) x = cv.output() with tf.variable_scope('sub_add'): if nin_feature_maps != nout_feature_maps: sub_pool = AvgPooling2D(orig_x, [1, strides[0], strides[1], 1], padding="VALID") orig_x = sub_pool.output() #Note that orig_x is a 4D tensor, last index is number of feature maps orig_x = tf.pad( orig_x, [[0,0],[0,0],[0,0], [(nout_feature_maps - nin_feature_maps)//2, (nout_feature_maps - nin_feature_maps)//2]] ) x += orig_x return x pass def bottleneck_residual(x, nin_feature_maps, nout_feature_maps, strides, activate_before_residual=False, phase_train=True): '''Bottleneck residual unit with 3 sub layers''' if activate_before_residual: with tf.variable_scope('common_bn_relu'): x = batch_norm(x, phase_train) x = leaky_relu(x, RELU_LEAKINESS) orig_x = x else: with tf.variable_scope('residual_bn_relu'): orig_x = x x = batch_norm(x, phase_train) x = leaky_relu(x, RELU_LEAKINESS) with tf.variable_scope('sub1'): cv = Convl2D(x, nin_feature_maps, nout_feature_maps/4, (1,1), strides=strides) x = cv.output() with tf.variable_scope('sub2'): x = batch_norm(x, phase_train) x = leaky_relu(x, RELU_LEAKINESS) cv = Convl2D(x, nout_feature_maps/4, nout_feature_maps/4, (3,3), strides=(1,1)) x = cv.output() with tf.variable_scope('sub3'): x = batch_norm(x, phase_train) x = leaky_relu(x, RELU_LEAKINESS) cv = Convl2D(x, nout_feature_maps/4, nout_feature_maps, (1,1), strides=(1,1)) x = cv.output() with tf.variable_scope('sub_add'): if nin_feature_maps != nout_feature_maps: cv = Convl2D(orig_x, nin_feature_maps, nout_feature_maps, (1,1),strides=strides) orig_x = cv.output() x += orig_x return x pass USING_BOTTLENECK = True NUM_RESIDUAL_UNITS = 2 def ResNet(X, y, dropout_prob, phase_train): x = tf.reshape(X, [-1, 256, 256, 3]) activate_before_residual = [True, False] if USING_BOTTLENECK: res_func = bottleneck_residual filters = [64, 128, 256] else: res_func = residual filters = [64, 64, 128] with tf.variable_scope('conv_1'): conv1 = Convl2D(x, 3, 64, (7, 7), strides=(2, 2), padding='SAME') conv1_bn = batch_norm(conv1.output(), phase_train) conv1_out = leaky_relu(conv1_bn, RELU_LEAKINESS) pool1 = MaxPooling2D(conv1_out, [1, 2, 2, 1], padding='SAME') x = pool1.output() with tf.variable_scope('unit1_0'): x = res_func(x, filters[0], filters[1], (1,1), activate_before_residual[0]) for i in range(1, NUM_RESIDUAL_UNITS): with tf.variable_scope('unit_1_%d' % i): x = res_func(x, filters[1], filters[1],(2,2), False) with tf.variable_scope('unit2_0'): x = res_func(x, filters[0], filters[1], (1, 1), activate_before_residual[1]) for i in range(1, NUM_RESIDUAL_UNITS): with tf.variable_scope('unit_1_%d' % i): x = res_func(x, filters[1], filters[1], (2, 2), False) with tf.variable_scope('last_unit'): x = batch_norm(x, phase_train) x = leaky_relu(x, RELU_LEAKINESS) output_size = x.get_shape()[1:3] x = tf.reshape(x, [-1, output_size[0] * output_size[1] * filters[1]]) #Hidden Layer: full connected layer with dropout with tf.variable_scope('fc1'): fc = FullConnectedLayer(x, output_size[0] * output_size[1] * filters[1], 1000) x = fc.output() fc_dropped = tf.nn.dropout(x, dropout_prob) #Final Layer: Softmax classification y_pred = SoftmaxLayer(fc_dropped, 1000, 3).output() cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(y_pred), reduction_indices=[1])) loss = cross_entropy accuracy = evaluation(y_pred, y) return loss, accuracy, y_pred pass SAVE_SESS = 'resnet_choxe.ckpt' BATCH_SIZE = 100 if __name__ == '__main__': TASK = 'train' X = tf.placeholder(tf.float32, [None, 256, 256, 3]) y = tf.placeholder(tf.float32, [None, 3]) dropout_prob = tf.placeholder(tf.float32) phase_train = tf.placeholder(tf.bool, name='phase_train') loss, accuracy, y_pred = ResNet(X, y, dropout_prob, phase_train) #Train model learning_rate = 0.01 train_op = tf.train.MomentumOptimizer(learning_rate, 0.9).minimize(loss) #vars_to_save = tf.trainable_variables() #Need to save the moving average variables init_op = tf.global_variables_initializer() if TASK == 'test': restore_sess = True elif TASK == 'train': restore_sess = False else: assert 1==0, "Task isn't supported" saver = tf.train.Saver() train_X, train_y, test_X, test_y = load_data() N = train_y.shape[0] num_batches = floor(N / BATCH_SIZE) with tf.Session() as sess: if TASK == 'train': sess.run(init_op, feed_dict={phase_train: True}) else: sess.run(init_op, feed_dict={phase_train: False}) if restore_sess: saver.restore(sess, SAVE_SESS) if TASK == 'train': print '\nTraining...' for i in range(1, 10000): mini_batch_index = i if mini_batch_index > num_batches: mini_batch_index = 1 batch_x = train_X[(mini_batch_index-1)*BATCH_SIZE:mini_batch_index*BATCH_SIZE] batch_y = train_y[(mini_batch_index-1)*BATCH_SIZE:mini_batch_index*BATCH_SIZE] train_op.run({X: batch_x, y: batch_y, dropout_prob: 0.5, phase_train: True}) if i % 200 == 0: cv_fd = {X: batch_x, y: batch_y, dropout_prob: 1.0, phase_train: False} train_loss = loss.eval(cv_fd) train_accuracy = accuracy.eval(cv_fd) print 'Step, loss, accurary = %6d: %8.4f, %8.4f' % (i,train_loss, train_accuracy) ''' print '\nTesting...' test_fd = {X: test_X, y: test_y, dropout_prob: 1.0, phase_train: False} print(' accuracy = %8.4f' % accuracy.eval(test_fd)) ''' # Save the session if TASK == 'train': saver.save(sess, SAVE_SESS)
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,400
mothaibatacungmua/AI-course
refs/heads/master
/PyML/neunet/quadratic_cost.py
import numpy as np from libs import sigmoid_prime, sigmoid class QuadraticCost(object): @staticmethod def fn(a, y): return 0.5*np.linalg.norm(a-y)**2 @staticmethod def delta(z, a, y): return (a-y)*sigmoid_prime(z) @staticmethod def output_activation(a, w, b): return sigmoid(np.dot(w,a)+b)
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,401
mothaibatacungmua/AI-course
refs/heads/master
/PyML/theano/conv.py
import theano from theano import tensor as T from theano.tensor.nnet import conv2d import numpy as np import pylab from PIL import Image ''' + a 4D tensor corresponding to a mini-batch of input images. The shape of the tensor is as follows: [mini-batch size, number of input feature maps, image height, image width]. + a 4D tensor corresponding to the weight matrix W. The shape of the tensor is: [number of feature maps at layer m, number of feature maps at layer m-1, filter height, filter width] ''' rng = np.random.RandomState(1234) input = T.tensor4(name='input') w_shp = (2, 3, 9, 9) w_bound = np.sqrt(3 * 9 * 9) W = theano.shared(np.asarray( rng.uniform( low=-1.0 / w_bound, high=1.0 / w_bound, size=w_shp), dtype=input.dtype), name='W' ) b_shp = (2,) b = theano.shared(np.asarray( rng.uniform(low=-.5, high=.5, size=b_shp), dtype=input.dtype), name='b' ) conv_out = conv2d(input, W) conv = theano.function([input], conv_out) output = T.nnet.sigmoid(conv_out + b.dimshuffle('x', 0, 'x', 'x')) f = theano.function([input], output) wolf = Image.open(open('3wolfmoon.jpg')) # dimensions are (height, width, channel) img = np.asarray(wolf, dtype='float64') / 256 wolf_4t = img.transpose(2, 0, 1).reshape(1, 3, 639, 516) con_op = conv(wolf_4t) print con_op.shape filtered_img = f(wolf_4t) pylab.subplot(1, 3, 1); pylab.axis('off'); pylab.imshow(img) pylab.gray() pylab.subplot(1, 3, 2); pylab.axis('off'); pylab.imshow(filtered_img[0, 0, :, :]) pylab.subplot(1, 3, 3); pylab.axis('off'); pylab.imshow(filtered_img[0, 1, :, :]) pylab.show()
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,402
mothaibatacungmua/AI-course
refs/heads/master
/PyML/neunet/softmax_cost.py
import numpy as np class SoftmaxCost(object): @staticmethod def fn(a, y): return -np.nan_to_num(np.log(a[np.argmax(y)])) @staticmethod def delta(z, a, y): return (a - y) @staticmethod def output_activation(a, w, b): z = np.dot(w, a) + b outputs = np.exp(z) outputs = outputs/np.sum(outputs) return outputs
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,403
mothaibatacungmua/AI-course
refs/heads/master
/n-queen/n-queen.py
from random import randint from backtracking import normal_backtracking, mrv_backtracking from min_conflicts import min_conflicts from hill_climbing import random_restart_hill_climbing import time class NQueen(): def __init__(self, n, problem=[]): self.n = n self.problem = problem self.count = 0 self.option = {} if len(problem) < n: self.problem = self.problem + [0]*(n - len(problem)) if len(problem) > n: self.problem = self.problem[:n] pass def gen_rand_problem(self): p = [0] * self.n for i in range(0, self.n): p[i] = randint(0, self.n - 1) self.problem = p return p def check_collision(self, pos_a, pos_b): if pos_a == None or pos_b == None: return False if (pos_a[0] == pos_b[0]) or (pos_a[1] == pos_b[1]) or (abs(pos_a[0] - pos_b[0]) == abs(pos_a[1] - pos_b[1])): return True return False def check_collision_at(self, state, pos): for i in range(0, len(state)): if i != pos: if self.check_collision((i, state[i]), (pos, state[pos])): return True return False def count_collision_at(self, state, pos): count = 0 for i in range(0, len(state)): if i != pos: if self.check_collision((i, state[i]), (pos, state[pos])): count = count + 1 return count def count_collisions(self, state): count = 0 for i in range(0, len(state)): for j in range(i + 1, len(state)): if self.check_collision((i, state[i]), (j, state[j])): count = count + 1 return count def is_goal_state(self, state): return self.count_collisions(state) == 0 def init_domain_value(self): domain_value = [[0 for i in range(0, self.n)]for j in range(0, self.n)] for i in range(0, self.n): for j in range(0, self.n): domain_value[i][j] = (self.problem[i] + j) % self.n return domain_value def get_unassigned_vars(self, assignment): assigned_vars = list(map(lambda x: x[0], assignment)) unassigned_vars = [x for x in range(0, self.n) if x not in assigned_vars] return assigned_vars, unassigned_vars def contraints(self, state, assigned_var, pos): for i in range(0, len(assigned_var)): if self.check_collision((assigned_var[i], state[assigned_var[i]]), (pos, state[pos])): return False return True def get_conflict_vars(self, state): conflicts = [] for i in range(0, len(state)): for j in range(i+1, len(state)): if self.check_collision((i, state[i]), (j, state[j])): if i not in conflicts and j not in conflicts: conflicts.append(i) conflicts.append(j) return conflicts def __normal_backtracking(self): return normal_backtracking(self) def __mrv_backtracking(self): if self.options == None: self.options = {'with_forward_checking':False, 'AC3':False} return mrv_backtracking(self) def __min_conflicts(self): if self.options == None: self.options = {'max_step':100000} return min_conflicts(self) def __random_restart_hill_climbing(self): if self.options == None: self.options = {'max_restart':1000} return random_restart_hill_climbing(self) NORMAL_BACKTRACKING = 0 MRV_BACKTRACKING = 1 MIN_CONFLICTS = 2 RANDOM_RESTART_HILL_CLIMBING = 3 def run(self, algorithms=NORMAL_BACKTRACKING, options=None): print '\n' print self.problem start_time = time.time() assignement = [] goal = False self.options = options if algorithms == NQueen.NORMAL_BACKTRACKING: assignement, goal = self.__normal_backtracking() if algorithms == NQueen.MRV_BACKTRACKING: assignement, goal = self.__mrv_backtracking() if algorithms == NQueen.MIN_CONFLICTS: assignement, goal = self.__min_conflicts() if algorithms == NQueen.RANDOM_RESTART_HILL_CLIMBING: assignement, goal = self.__random_restart_hill_climbing() end_time = time.time() print assignement print goal, self.count print "--- %s seconds ---" % (end_time - start_time) pass if __name__ == '__main__': queen_puzzle = NQueen(8) queen_puzzle.gen_rand_problem() queen_puzzle.run(algorithms=NQueen.NORMAL_BACKTRACKING) #queen_puzzle.run(algorithms=NQueen.MRV_BACKTRACKING) #queen_puzzle.run(algorithms=NQueen.MRV_BACKTRACKING, options={'with_forward_checking':True}) #queen_puzzle.run(algorithms=NQueen.MRV_BACKTRACKING, options={'with_forward_checking': True, 'AC3':True}) #queen_puzzle.run(algorithms=NQueen.MIN_CONFLICTS, options={'max_step':100000}) queen_puzzle.run(algorithms=NQueen.RANDOM_RESTART_HILL_CLIMBING, options={'max_restart':10000}) pass
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,404
mothaibatacungmua/AI-course
refs/heads/master
/PyML/theano/logistic_regression.py
from PyML.libs import softmax_data_wrapper,shared_dat import timeit import numpy as np import theano import theano.tensor as T import cPickle from layer import LogisticRegression, logistic_error ''' Code based on: http://deeplearning.net/tutorial/ ''' def SGD(train_data, test_data, validation_data, learning_rate=0.1, epochs=300, batch_size=600): X_train = train_data[0] y_train = train_data[1] X_test = test_data[0] y_test = test_data[1] X_val = validation_data[0] y_val = validation_data[1] # index to a [mini]batch index = T.lscalar() X = T.matrix('X') y = T.ivector('y') classifier = LogisticRegression(npred=28*28, nclass=10) classifier.setup(X) # Test test_model = theano.function( inputs=[index], outputs=logistic_error(classifier.predict(X), y), givens={ X: X_test[index*batch_size:(index+1)*batch_size], y: y_test[index*batch_size:(index+1)*batch_size] } ) # Validation validate_model = theano.function( inputs=[index], outputs=logistic_error(classifier.predict(X), y), givens={ X:X_val[index*batch_size:(index+1)*batch_size], y:y_val[index*batch_size:(index+1)*batch_size] } ) cost = classifier.cost_fn(y) grad_W = T.grad(cost, wrt=classifier.W) grad_b = T.grad(cost, wrt=classifier.b) updates = [ (classifier.W, classifier.W - learning_rate * grad_W), (classifier.b, classifier.b - learning_rate * grad_b) ] # Train train_model = theano.function( inputs=[index], outputs=cost, updates=updates, givens={ X:X_train[index*batch_size:(index+1)*batch_size], y:y_train[index*batch_size:(index+1)*batch_size] } ) n_train_batches = X_train.get_value(borrow=True).shape[0] // batch_size n_test_batches = X_test.get_value(borrow=True).shape[0] // batch_size n_val_batches = X_val.get_value(borrow=True).shape[0] // batch_size print('Training the model...') #Early-stopping parameters patience = 5000 patience_increase = 2 improvement_threshold = 0.995 validation_frequency = min(n_train_batches, patience // 2) best_validation_loss = np.inf test_score = 0. start_time = timeit.default_timer() done_looping = False epoch = 0 while (epoch < epochs) and (not done_looping): epoch = epoch + 1 for minibatch_index in range(n_train_batches): minibatch_train_lost = train_model(minibatch_index) iter = (epoch - 1) * n_train_batches + minibatch_index # Monitor validation error if (iter + 1) % validation_frequency == 0: validation_losses = [validate_model(i) for i in range(n_val_batches)] validation_cost = np.mean(validation_losses) print 'Epoch %i, minibatch %i/%i, validation error %f' % \ (epoch, minibatch_index + 1, n_train_batches, validation_cost * 100) # Early stopping if validation_cost < best_validation_loss: if validation_cost < best_validation_loss * improvement_threshold: patience = max(patience, iter * patience_increase) best_validation_loss = validation_cost test_losses = [test_model(i) for i in range(n_test_batches)] test_score = np.mean(test_losses) print ' Epoch %i, minibatch %i/%i, test error %f' % \ (epoch, minibatch_index + 1, n_train_batches, test_score * 100) with open('minist_logistic.pkl', 'wb') as f: cPickle.dump(classifier, f) if patience <= iter: done_looping = True break end_time = timeit.default_timer() print 'Optimization complete with best validation score of %f %%, with test performance %f %%' \ % (best_validation_loss * 100., test_score * 100.) print 'The code run for %d epochs, with %f epochs/sec' % (epoch, 1. * epoch / (end_time - start_time)) def predict(): # load trained model classifier = cPickle.load(open('minist_logistic.pkl')) # predict model predict_model = theano.function( inputs=[classifier.input], outputs=classifier.predict() ) train, test, validation = softmax_data_wrapper() predicted_values = predict_model(test[0].get_value()[:10]) print("The first 10 examples:") print(test[1][:10]) print("Predicted values for the first 10 examples in test set:") print(predicted_values) if __name__ == '__main__': train, test, validation = softmax_data_wrapper() SGD(shared_dat(train), shared_dat(test), shared_dat(validation))
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,405
mothaibatacungmua/AI-course
refs/heads/master
/PyML/neunet/CM.py
import numpy as np import random from monitor import monitor def update_mini_batch( network, mini_batch, eta, momentum, lmbda, n, veloc_b, veloc_w): grad_b = [np.zeros(b.shape) for b in network.biases] grad_w = [np.zeros(w.shape) for w in network.weights] for x, y in mini_batch: #compute gradient descents delta_grad_b, delta_grad_w = network.backprop(x, y) grad_b = [gb + dgb for gb, dgb in zip(grad_b, delta_grad_b)] grad_w = [gw + dgw for gw, dgw in zip(grad_w, delta_grad_w)] # update bias, weight velocities veloc_b = [momentum * v + (eta/len(mini_batch)) * gb for (v, gb) in zip(veloc_b, grad_b)] veloc_w = [momentum * v + (eta/len(mini_batch)) * gw for (v, gw) in zip(veloc_w, grad_w)] #update bias, weight with velocities network.biases = [b - v for (b,v) in zip(network.biases, veloc_b)] network.weights = [(1-eta*(lmbda/n))*w - v for (w, v) in zip(network.weights, veloc_w)] return veloc_b, veloc_w pass def CM(network, training_data, epochs, mini_batch_size, eta, momentum=0.9, lmbda = 0.0, evaluation_data=None, monitor_evaluation_cost=False, monitor_evaluation_accuracy=False, monitor_training_cost=False, monitor_training_accuracy=False): n = len(training_data) veloc_b = [np.zeros(b.shape) for b in network.biases] veloc_w = [np.zeros(w.shape) for w in network.weights] evaluation_cost, evaluation_accuracy = [], [] training_cost, training_accuracy = [], [] for j in xrange(epochs): random.shuffle(training_data) mini_batches = [ training_data[k:k + mini_batch_size] for k in xrange(0, n, mini_batch_size) ] print "epochs[%d]" % j for mini_batch in mini_batches: veloc_b, veloc_w = update_mini_batch( network, mini_batch, eta, momentum, lmbda, n, veloc_b, veloc_w) monitor(network, training_data, evaluation_data, training_cost, training_accuracy, evaluation_cost, evaluation_accuracy, lmbda, monitor_evaluation_cost, monitor_evaluation_accuracy, monitor_training_cost, monitor_training_accuracy) return training_cost, training_accuracy, evaluation_cost, evaluation_accuracy pass
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,406
mothaibatacungmua/AI-course
refs/heads/master
/n-queen/genetic.py
def genetic(self): pass
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,407
mothaibatacungmua/AI-course
refs/heads/master
/PyML/theano/__init__.py
from logistic_regression import *
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,408
mothaibatacungmua/AI-course
refs/heads/master
/PyML/theano/hopfield.py
import theano from theano import tensor as T import numpy as np from theano.tensor.shared_randomstreams import RandomStreams from theano.ifelse import ifelse import random N = 4 X = T.dmatrix('X') dg = np.ones(N, dtype=theano.config.floatX) W = theano.shared(value=np.zeros((N,N), dtype=theano.config.floatX)) f = T.dot(T.transpose(X), X) - T.shape(X)[0]*T.nlinalg.alloc_diag(dg) input = np.asarray([[1,-1,1,-1],[-1,-1,1,-1],[1,1,1,1],[1,1,-1,-1],[-1,-1,1,1]], dtype=theano.config.floatX) train = theano.function(inputs=[X],outputs=f,updates=[(W, W+f)]) train(input) print W.get_value() x = T.dvector('x') energy = -1/2*T.dot(T.dot(T.transpose(x), W),x) e_f0 = theano.function(inputs=[x], outputs=energy) #reconstruction state = theano.shared(value=np.zeros((N,), dtype=theano.config.floatX)) srng = RandomStreams(seed=234) idx = T.lscalar() ret = T.dot(W[idx,:], state) new_state = ifelse(T.le(ret,np.cast[theano.config.floatX](0)),-1.0,1.0) updates = [(state, T.set_subtensor(state[idx], new_state))] e_f1 = theano.function(inputs=[x, idx], outputs=energy, updates=updates) state.set_value([1,1,1,-1]) pre_e = 0.0 next_e = e_f0(state.get_value()) for i in range(0, 20): print "State %s with energy %d" % (str(state.get_value()), next_e) pre_e = next_e e_f1(state.get_value(), random.randint(0, N-1)) next_e = e_f0(state.get_value()) # 2 local minima energy # State [ 1. 1. -1. -1.] with energy -16 # State [-1. -1. 1. 1.] with energy -16
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,409
mothaibatacungmua/AI-course
refs/heads/master
/PyML/neunet/monitor.py
def monitor(network, training_data, evaluation_data, training_cost,training_accuracy, evaluation_cost, evaluation_accuracy, lmbda, monitor_evaluation_cost=False, monitor_evaluation_accuracy=False, monitor_training_cost=False, monitor_training_accuracy=False): n = len(training_data) if evaluation_data: n_vdata = len(evaluation_data) if monitor_training_cost: cost = network.total_cost(training_data, lmbda) training_cost.append(cost) if monitor_training_accuracy: accuracy = network.accuracy(training_data, convert=True) training_accuracy.append(accuracy*1.0 / n) if monitor_evaluation_cost: cost = network.total_cost(evaluation_data, lmbda) evaluation_cost.append(cost) if monitor_evaluation_accuracy: accuracy = network.accuracy(evaluation_data, convert=True) print accuracy evaluation_accuracy.append(accuracy*1.0 / n_vdata) pass
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,410
mothaibatacungmua/AI-course
refs/heads/master
/PyML/neunet/advance_network.py
import random import numpy as np from cross_entropy_cost import CrossEntropyCost from PyML.libs import sigmoid, sigmoid_prime from PyML.libs import vectorized_result from SGD import SGD from CM import CM from NAG import NAG from AdaGrad import AdaGrad from Adadelta import Adadelta from RMSprop import RMSprop from Adam import Adam class Network(object): def __init__(self, sizes, cost=CrossEntropyCost, init_method='default'): self.num_layers = len(sizes) self.sizes = sizes self.biases = None self.weights = None if init_method == 'default': self.default_weight_initializer() if init_method == 'large': self.large_weight_initialize() self.cost = cost pass def default_weight_initializer(self): self.biases = [np.random.randn(y, 1) for y in self.sizes[1:]] self.weights = [np.random.randn(y, x)/np.sqrt(x) for x,y in zip(self.sizes[:-1], self.sizes[1:])] pass def large_weight_initialize(self): self.biases = [np.random.randn(y, 1) for y in self.sizes[1:]] self.weights = [np.random.randn(y, x) for x, y in zip(self.sizes[:-1], self.sizes[1:])] pass def feedforward(self, a): for b,w in zip(self.biases, self.weights): a = sigmoid(np.dot(w, a) + b) return a pass def backprop(self, x, y, biases=None, weights=None): if biases is None: biases = self.biases if weights is None: weights = self.weights grad_b = [np.zeros(b.shape) for b in biases] grad_w = [np.zeros(w.shape) for w in weights] activation = x activations = [x] zs = [] for b, w in zip(biases, weights): z = np.dot(w, activation) + b zs.append(z) activation = sigmoid(z) activations.append(activation) #computing the activation of the output layer activations[-1] = self.cost.output_activation(activations[-2], weights[-1], biases[-1]) #backward pass delta = self.cost.delta(zs[-1], activations[-1], y) grad_b[-1] = delta grad_w[-1] = np.dot(delta, activations[-2].transpose()) for l in xrange(2, self.num_layers): z = zs[-l] sp = sigmoid_prime(z) delta = np.dot(weights[-l+1].transpose(), delta) * sp grad_b[-l] = delta grad_w[-l] = np.dot(delta, activations[-l-1].transpose()) return (grad_b, grad_w) pass def total_cost(self, data, lmbda, convert=False): cost = 0.0 for x, y in data: a = self.feedforward(x) if convert: y = vectorized_result(y) cost += self.cost.fn(a, y)/len(data) cost += 0.5*(lmbda/len(data)) * sum((np.linalg.norm(w)**2 for w in self.weights)) return cost def accuracy(self, data, convert=False): if convert: results = [(np.argmax(self.feedforward(x)), np.argmax(y)) for (x, y) in data] else: results = [(np.argmax(self.feedforward(x)), y) for (x, y) in data] return sum(int(t == y) for (t, y) in results) def SGD(self, *args, **kwargs): return SGD(self, *args, **kwargs) def CM(self, *args, **kwargs): return CM(self, *args, **kwargs) def NAG(self, *args, **kwargs): return NAG(self, *args, **kwargs) def AdaGrad(self, *args, **kwargs): return AdaGrad(self, *args, **kwargs) def Adadelta(self, *args, **kwargs): return Adadelta(self, *args, **kwargs) def L_BFGS(self, *args, **kwargs): pass def RMSprop(self, *args, **kwargs): return RMSprop(self, *args, **kwargs) def Adam(self, *args, **kwargs): return Adam(self, *args, **kwargs)
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,411
mothaibatacungmua/AI-course
refs/heads/master
/bayesian/importance_sampling.py
import numpy as np import scipy.stats # Monte Carlo N = 100 mc = [] h = lambda x: (x >= 3) * 1.0 for i in range(0, 500): samples = np.random.normal(0.,1.,N) mc.append(np.sum(h(samples))/N) mc_mean = np.sum(mc)/500 mc_var = np.var(mc) print 'Monte Carlo method, mean:%07f, var:%07f' % (mc_mean, mc_var) # Importance sampling isp_unbiased = [] isp_biased = [] f = scipy.stats.norm(0., 1.).pdf g = scipy.stats.norm(4., 1.).pdf for i in range(0, 200): samples = np.random.normal(4., 1., N) isp_unbiased.append(np.sum(f(samples)*h(samples)/g(samples))/N) g = scipy.stats.norm(2., 1.).pdf for i in range(0, 200): samples = np.random.normal(2., 1., N) isp_biased.append(np.sum(f(samples)*h(samples)/g(samples))/np.sum(f(samples)/g(samples))) print 'Unbiased Importance Sampling method, mean:%07f, var:%07f' % (np.sum(isp_unbiased)/200, np.var(isp_unbiased)) print 'Biased Importance Sampling method, mean:%07f, var:%07f' % (np.sum(isp_biased)/200, np.var(isp_biased))
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,412
mothaibatacungmua/AI-course
refs/heads/master
/MDP/rectangle.py
from dispatcher import Dispatcher import math import numpy as np class Rectangle(Dispatcher): @staticmethod def regcb(inst): pass def __init__(self, canvas, x, y, width, height, options={}): Dispatcher.__init__(self) self.obj_id = None self.canvas = canvas self.x = x self.y = y self.width = width self.height = height self.options = options def draw(self): self.obj_id = self.canvas.create_rectangle(self.x, self.y, self.x + self.width, self.y + self.height, self.options) return self.obj_id def get_obj_id(self): return self.obj_id class TextRectangle(Rectangle): @staticmethod def regcb(inst): inst.register("change-data", inst.cb_change_data) pass def __init__(self, canvas, x, y, width, height, options={}, text_options={}): Rectangle.__init__(self, canvas, x, y, width, height, options) self.text_id = None self.text_options = text_options TextRectangle.regcb(self) def draw(self): Rectangle.draw(self) self.text_id = self.canvas.create_text(self.x+self.width/2, self.y+self.height/2, self.text_options) def change_text(self, text): self.text_options['text'] = text self.canvas.itemconfigure(self.text_id, text=text) def cb_change_data(self, *args, **kwargs): pass class MouseRectangle(TextRectangle): @staticmethod def regcb(inst): inst.register("left-mouse-click", inst.cb_left_mouse_click) pass def __init__(self, canvas, x, y, width, height, options={}, text_options={}): self.count = 0 text_options['text'] = str(self.count) TextRectangle.__init__(self, canvas, x, y, width, height, options, text_options) MouseRectangle.regcb(self) def cb_left_mouse_click(self, *args, **kwargs): self.count = self.count + 1 self.change_text(str(self.count)) pass class MDPRectangle(TextRectangle): NORTH = 'NORTH' EAST = 'EAST' SOUTH = 'SOUTH' WEST = 'WEST' @staticmethod def regcb(inst): pass def __init__(self, canvas, x, y, width, height, options={}, text_options={}, init_direction = NORTH, direction_options={}): self.direction = init_direction self.direction_options = direction_options self.value = 0.0 self.dir_id = None TextRectangle.__init__(self, canvas, x, y, width, height, options, text_options) MDPRectangle.regcb(self) def calc_coords_with_direction(self, direction): tri_x0 = self.x + self.width/2 tri_y0 = self.y tri_x1 = tri_x0 - 8 tri_y1 = tri_y0 + 8 tri_x2 = tri_x0 + 8 tri_y2 = tri_y0 + 8 rot_vec_x = self.x + self.width/2 rot_vec_y = self.y + self.height/2 tri_mat = np.matrix( ((tri_x0 - rot_vec_x, tri_x1 - rot_vec_x, tri_x2 - rot_vec_x), \ (tri_y0 - rot_vec_y, tri_y1 - rot_vec_y, tri_y2 - rot_vec_y)) ) theta = 0.0 if direction == MDPRectangle.NORTH: theta = 0.0 if direction == MDPRectangle.EAST: theta = math.pi/2.0 if direction == MDPRectangle.SOUTH: theta = math.pi if direction == MDPRectangle.WEST: theta = 3.0 * math.pi /2.0 rot_mat = np.matrix((\ (math.cos(theta), -math.sin(theta)), \ (math.sin(theta), math.cos(theta))\ )) tri_mat = np.dot(rot_mat, tri_mat) tri_mat[0,] = np.add(tri_mat[0,], rot_vec_x) tri_mat[1,] = np.add(tri_mat[1,], rot_vec_y) convert = np.array(tri_mat.reshape(tri_mat.size, order='F')).flatten() return tuple(convert) pass def draw(self): TextRectangle.draw(self) self.change_text(str(self.value)) #self.draw_direction() def draw_direction(self): t = self.calc_coords_with_direction(self.direction) self.dir_id = self.canvas.create_polygon(t, self.direction_options) def change_color(self, color): self.canvas.itemconfigure(self.obj_id, fill=color) def change_value(self, value, sign=False): s = '' if value is not None: self.value = value s = str(self.value) if sign: s = '+' + s self.canvas.itemconfigure(self.text_id, text = s) def change_direction(self, direction): if self.dir_id != None: self.canvas.delete(self.dir_id) self.direction = direction self.draw_direction()
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,413
mothaibatacungmua/AI-course
refs/heads/master
/MDP/main.py
from Tkinter import* from grid import MDPGrid from rectangle import MDPRectangle import tkFont WIDTH = 500 HEIGHT = 400 OFFSET_X = 70 OFFSET_Y = 30 REC_WIDTH = 90 REC_HEIGHT = 90 root = Tk() canvas = Canvas(root, width=WIDTH, height=HEIGHT, bg="black") canvas.pack(expand=YES, fill=BOTH) def left_mouse_click(event): n_grid.dispatch('left-mouse-click', event=event) pass def right_mouse_click(event): n_grid.dispatch('right-mouse-click', event=event, \ text_options={'fill':'white'},\ init_direction = MDPRectangle.WEST, \ direction_options={'fill':'white'}) def mouse_move(event): canvas.itemconfig(x_pos, text=str(event.x)) canvas.itemconfig(y_pos, text=str(event.y)) pass x_pos = canvas.create_text(20, HEIGHT-20, text="0", fill="white") y_pos = canvas.create_text(60, HEIGHT-20, text="0", fill="white") times_font = tkFont.Font(family='Times', size=-20, weight='bold') text_iter = canvas.create_text(\ OFFSET_X + 2*REC_WIDTH-50, \ OFFSET_Y + 20 + 3*REC_HEIGHT,\ text="Value Iterations:",\ fill="yellow", font=times_font) num_iter = canvas.create_text(\ OFFSET_X + 2*REC_WIDTH+50,\ OFFSET_Y + 20 + 3*REC_HEIGHT,\ text="0", fill="yellow", font=times_font) #canvas.create_polygon((100, 100, 100, 110, 110, 100), fill = "red") canvas.bind("<Motion>", mouse_move) canvas.bind("<Button-1>", left_mouse_click) canvas.bind("<Button-3>", right_mouse_click) settings = {'fill':'black','outline': 'white'} n_grid = MDPGrid(\ canvas, x=OFFSET_X, y=OFFSET_Y,\ num_x=4, num_y=3, rec_width=REC_WIDTH,\ rec_height=REC_HEIGHT, rec_options = settings,\ num_iter_id = num_iter, text_iter = text_iter) n_grid.draw(text_options={'fill':'white'},init_direction = MDPRectangle.WEST, direction_options={'fill':'white'}) # config for 4x3 world to run MDP algorithms n_grid.config(discount_factor=1, action_reward=-0.04, mode=MDPGrid.POLICY_ITER) n_grid.set_start_point(0, 2, 'blue') n_grid.set_goal_reward(3, 0, 1, 'green') n_grid.set_pit_reward(3, 1, -1, 'red') n_grid.set_wall(1,1, 'gray') # run #root.attributes("-toolwindow", 1) root.resizable(0,0) root.mainloop()
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,414
mothaibatacungmua/AI-course
refs/heads/master
/PyML/theano/lenet.py
import theano import theano.tensor as T from net import MLP, train_mlp import numpy as np from PyML.libs import softmax_data_wrapper,shared_dat from layer import LogisticRegression, logistic_error, HiddenLayer, DropoutLayer, ConvPoolLayer ''' Code based on: http://deeplearning.net/tutorial/ ''' class Lenet(MLP): pass if __name__ == '__main__': train, test, validation = softmax_data_wrapper() # index to [index]minibatch X = T.matrix('X') y = T.ivector('y') rng = np.random.RandomState(123456) batch_size = 500 classifier = Lenet(X, y, logistic_error, L2_reg=0.0) nkernels = [50, 20] # Construct the first convolutional pooling layer: # filtering reduces the image size to (28-5+1 , 28-5+1) = (24, 24) # maxpooling reduces this further to (24/2, 24/2) = (12, 12) # 4D output tensor is thus of shape (batch_size, nkerns[0], 12, 12) classifier.add_layer(ConvPoolLayer( filter_shape=(nkernels[0], 1, 5, 5), image_shape=(batch_size, 1, 28, 28), pool_size=(2,2), rng=rng) ) # Construct the second convolutional pooling layer # filtering reduces the image size to (12-5+1, 12-5+1) = (8, 8) # maxpooling reduces this further to (8/2, 8/2) = (4, 4) # 4D output tensor is thus of shape (batch_size, nkerns[1], 4, 4) classifier.add_layer(ConvPoolLayer( filter_shape=(nkernels[1], nkernels[0], 5, 5), image_shape=(batch_size, nkernels[0], 12, 12), pool_size=(2, 2), rng=rng) ) classifier.add_layer(DropoutLayer(parent=HiddenLayer, p_dropout=0.2, npred=nkernels[1]*4*4, nclass=500, rng=rng)) classifier.add_layer(DropoutLayer(parent=LogisticRegression, p_dropout=0.3, npred=500, nclass=10)) train_mlp(shared_dat(train), shared_dat(test), shared_dat(validation), classifier, batch_size=batch_size, learning_rate=0.01)
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,415
mothaibatacungmua/AI-course
refs/heads/master
/PyML/theano/net.py
import timeit import theano import theano.tensor as T from const import LAYER_TYPES import numpy as np class MLP(object): def __init__(self, inp, target, error_fn, L1_reg=0.00, L2_reg=0.0001): self.L1 = 0 self.L2 = 0 self.L1_reg = L1_reg self.L2_reg = L2_reg self.layers = [] self.params = [] self.calc_cost = None self.input = inp self.error_fn = error_fn self.target = target def convert_output_to_input(self, prev_layer_output, prev_layer, next_layer): if prev_layer is None: if type(next_layer) != LAYER_TYPES['ConvPoolLayer']: return prev_layer_output return prev_layer_output.reshape(next_layer.image_shape) if type(prev_layer) == type(next_layer): return prev_layer_output if type(prev_layer) != LAYER_TYPES['ConvPoolLayer'] and \ type(next_layer) != LAYER_TYPES['ConvPoolLayer']: return prev_layer_output # assume that ignore_border=True if type(prev_layer) == LAYER_TYPES['ConvPoolLayer']: # the HiddenLayer being fully-connected, it operates on 2D matrices of # shape (batch_size, num_pixels) (i.e matrix of rasterized images). return prev_layer_output.flatten(2) pass def add_layer(self, layer): self.layers.append(layer) if type(layer) != LAYER_TYPES['ConvPoolLayer']: self.L1 += abs(layer.W).sum() self.L2 += (layer.W ** 2).sum() self.params += layer.params if len(self.layers) == 1: layer.setup(self.convert_output_to_input(self.input, None, layer)) return prev_layer = self.layers[-2] layer.setup(self.convert_output_to_input(prev_layer.output, prev_layer, layer)) return # feedforward phase in the testing process def _test_f(self, X, l_i): if l_i == (len(self.layers) - 2): return self.layers[l_i].feedforward(X) c_X = X if l_i == 0: c_X = self.convert_output_to_input(X, None, self.layers[0]) n_X = self.convert_output_to_input( self.layers[l_i].feedforward(c_X), self.layers[l_i], self.layers[l_i+1]) return self._test_f(n_X, l_i + 1) # feedforward phase in the training process def _train_f(self, X, l_i): if l_i == (len(self.layers) - 2): return self.layers[l_i].calc_output(X) c_X = X if l_i == 0: c_X = self.convert_output_to_input(X, None, self.layers[0]) n_X = self.convert_output_to_input( self.layers[l_i].calc_output(c_X), self.layers[l_i], self.layers[l_i + 1]) return self._train_f(n_X, l_i + 1) def cost_fn(self, X, y): last_inp = self._train_f(X, 0) return self.layers[-1].cost_fn(last_inp, y) + self.L1_reg * self.L1 + self.L2_reg * self.L2 def predict(self, X): last_inp = self._test_f(X, 0) return self.layers[-1].predict(last_inp) def gen_test_model(self, X, y, batch_size): minibatch_index = T.lscalar() return theano.function( inputs=[minibatch_index], outputs=self.error_fn(self.predict(X), y), givens={ X: X[minibatch_index * batch_size:(minibatch_index + 1) * batch_size], y: y[minibatch_index * batch_size:(minibatch_index + 1) * batch_size] } ) def gen_validate_model(self, X, y, batch_size): minibatch_index = T.lscalar() return theano.function( inputs=[minibatch_index], outputs=self.error_fn(self.predict(X), y), givens={ X: X[minibatch_index * batch_size:(minibatch_index + 1) * batch_size], y: y[minibatch_index * batch_size:(minibatch_index + 1) * batch_size] } ) def gen_train_model(self, X, y, batch_size, learning_rate, optimization='SGD'): cost = self.cost_fn(X, y) grad = [T.grad(cost, param) for param in self.params] # updates updates = [ (param, param - learning_rate * grad) for param, grad in zip(self.params, grad) ] # Train model minibatch_index = T.lscalar() return theano.function( inputs=[minibatch_index], outputs=cost, updates=updates, givens={ X: X[minibatch_index * batch_size:(minibatch_index + 1) * batch_size], y: y[minibatch_index * batch_size:(minibatch_index + 1) * batch_size] } ) def train_mlp(train_data, test_data, validation_data, neunet, learning_rate=0.1, batch_size=30, epochs=500, optimization='SGD'): X_train = train_data[0] y_train = train_data[1] X_test = test_data[0] y_test = test_data[1] X_val = validation_data[0] y_val = validation_data[1] # Test model test_model = neunet.gen_test_model(X_test, y_test, batch_size) # Validation model validate_model = neunet.gen_validate_model(X_val, y_val, batch_size) # Train model train_model = neunet.gen_train_model(X_train, y_train, batch_size, learning_rate, optimization=optimization) n_train_batches = X_train.get_value(borrow=True).shape[0] // batch_size n_test_batches = X_test.get_value(borrow=True).shape[0] // batch_size n_val_batches = X_val.get_value(borrow=True).shape[0] // batch_size print('Training the model...') # Early-stopping parameters patience = 20000 patience_increase = 2 improvement_threshold = 0.995 validation_frequency = min(n_train_batches, patience // 2) best_validation_loss = np.inf best_model = None test_score = 0. start_time = timeit.default_timer() done_looping = False epoch = 0 n = X_train.get_value(borrow=True).shape[0] while (epoch < epochs) and (not done_looping): #shuffe train data rand_perm = np.random.permutation(n) X_train = X_train[rand_perm,:] y_train = y_train[rand_perm] epoch = epoch + 1 for minibatch_index in range(n_train_batches): minibatch_train_lost = train_model(minibatch_index) iter = (epoch - 1) * n_train_batches + minibatch_index # Monitor validation error if (iter + 1) % validation_frequency == 0: validation_losses = [validate_model(i) for i in range(n_val_batches)] validation_cost = np.mean(validation_losses) print 'Epoch %i, minibatch %i/%i, validation error %f' % \ (epoch, minibatch_index + 1, n_train_batches, validation_cost * 100) # Early stopping if validation_cost < best_validation_loss: if validation_cost < best_validation_loss * improvement_threshold: patience = max(patience, iter * patience_increase) best_validation_loss = validation_cost test_losses = [test_model(i) for i in range(n_test_batches)] test_score = np.mean(test_losses) print ' Epoch %i, minibatch %i/%i, test error %f' % \ (epoch, minibatch_index + 1, n_train_batches, test_score * 100) #TODO: save MLP params if patience <= iter: done_looping = True break end_time = timeit.default_timer() print 'Optimization complete with best validation score of %f %%, with test performance %f %%' \ % (best_validation_loss * 100., test_score * 100.) print 'The code run for %d epochs, with %f epochs/sec' % (epoch, 1. * epoch / (end_time - start_time))
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,416
mothaibatacungmua/AI-course
refs/heads/master
/PyML/theano/boltzmann.py
import theano from theano import tensor as T import numpy as np from theano.tensor.shared_randomstreams import RandomStreams from theano.ifelse import ifelse import random Nh = 5 Nv = 7 learning_rate = 0.1
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,417
mothaibatacungmua/AI-course
refs/heads/master
/logic-reasoning/utils.py
import collections def first(iterable, default=None): "Return the first element of an iterable or the next element of a generator; or default." try: return iterable[0] except IndexError: return default except TypeError: return next(iterable, default) class PartialExpr: """Given 'P |'==>'| Q, first form PartialExpr('==>', P), then combine with Q.""" def __init__(self, op, lhs): self.op, self.lhs = op, lhs def __or__(self, rhs): return Expr(self.op, self.lhs, rhs) def __repr__(self): return "PartialExpr('{}', {})".format(self.op, self.lhs) class Expr(object): """A mathematical expression with an operator and 0 or more arguments. op is a str like '+' or 'sin'; args are Expression. Expr('x') or Symbol('x') creates a symbol (a nullary Expr). Expr('-', x) creates a unary; Expr('+', x, 1) creates a binary.""" def __init__(self, op, *args): self.op = str(op) self.args = args #Operator overload def __neg__(self): return Expr('-', self) def __pos__(self): return Expr('+', self) def __invert__(self): return Expr('~', self) def __add__(self, rhs): return Expr('+', self, rhs) def __sub__(self, rhs): return Expr('-', self, rhs) def __mul__(self, rhs): return Expr('*', self, rhs) def __pow__(self, rhs): return Expr('**', self, rhs) def __mod__(self, rhs): return Expr('%', self, rhs) def __and__(self, rhs): return Expr('&', self, rhs) def __xor__(self, rhs): return Expr('>>', self, rhs) def __rshift__(self, rhs): return Expr('>>', self, rhs) def __lshift__(self, rhs): return Expr('<<', self, rhs) def __truediv__(self, rhs): return Expr('/', self, rhs) def __floordiv__(self, rhs): return Expr('//', self, rhs) def __matmul__(self, rhs): return Expr('@', self, rhs) def __or__(self, rhs): "Allow both P | Q, and P |'==>'|Q." if isinstance(rhs, Expression): return Expr('|', self, rhs) else: return PartialExpr(rhs, self) # Reverse operator overloads def __radd__(self, lhs): return Expr('+', lhs, self) def __rsub__(self, lhs): return Expr('-', lhs, self) def __rmul__(self, lhs): return Expr('*', lhs, self) def __rdiv__(self, lhs): return Expr('/', lhs, self) def __rpow__(self, lhs): return Expr('**', lhs, self) def __rmod__(self, lhs): return Expr('%', lhs, self) def __rand__(self, lhs): return Expr('&', lhs, self) def __rxor__(self, lhs): return Expr('^', lhs, self) def __ror__(self, lhs): return Expr('|', lhs, self) def __rrshift__(self, lhs): return Expr('>>', lhs, self) def __rlshift__(self, lhs): return Expr('<<', lhs, self) def __rtruediv__(self, lhs): return Expr('/', lhs, self) def __rfloordiv__(self, lhs): return Expr('//', lhs, self) def __rmatmul__(self, lhs): return Expr('@', lhs, self) def __call__(self, *args): "Call: if 'f' is a Symbol, then f(0) == Expr('f', 0)." if self.args: raise ValueError('can only do a call for a symbol, not an Expr') else: return Expr(self.op, args) # Equality and repr def __eq__(self, other): "'x == y' evaluates to True or False; does not build an Expr." return (isinstance(other, Expr) and self.op == other.op and self.args == other.args) def __hash__(self): return hash(self.op) ^ hash(self.args) def __repr__(self): op = self.op args = [str(arg) for arg in self.args] if op.isidentifier(): # f(x) or f(x,y) return '{}({})'.format(op, ', '.join(args)) if args else op elif len(args == 1): # -x or -(x + 1) return op + args[0] else: opp = (' ' + op + ' ') return '(' + opp.join(args) + ')' Number = (int, float, complex) Expression = (Expr, Number) def Symbol(name): "A Symbol is just an Expr with no args" return Expr(name) def symbols(names): "Return a tuple of Symbols; names is a comma/whitespace delimited str." return tuple(Symbol(name) for name in names.replace(',', ' ').split()) def subexpression(x): "Yield the subexpression of an Expression (including x itself)" yield x if isinstance(x, Expr): for arg in x.args: yield from subexpression(arg) def expr(x): """Shortcut to create an Expression. x is a str in which: - identifiers are automatically defined as Symbols. - ==> is treated as an infix |'==>'|, as are <== and <=>. If x is already an Expression, it is returned unchanged. Example: >>> expr('P & Q ==> Q') ((P & Q) ==> Q) """ if isinstance(x, str): return eval(expr_handle_infix_ops(x), defaultkeydict(Symbol)) else: return x infix_ops = '==> <== <=>'.split() def expr_handle_infix_ops(x): """Given a str, return a new str with ==> replaced by |'==>'|, etc. >>> expr_handle_infix_ops('P ==> Q') "P |'==>'| Q" """ for op in infix_ops: x = x.replace(op, '|' + repr(op) + '|') return x class defaultkeydict(collections.defaultdict): """Like defaultdict, but the default_factory is a function of the key. >>> d = defaultkeydict(len); d['four'] 4 """ def __missing__(self, key): self[key] = result = self.default_factory(key) return result
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,418
mothaibatacungmua/AI-course
refs/heads/master
/PyML/theano/layer.py
import theano from theano import tensor as T from theano.tensor.nnet import conv2d import numpy as np from theano.tensor.signal import pool class Layer(object): def __init__(self): return NotImplementedError def calc_output(self, input): return NotImplementedError def cost_fn(self, y): return NotImplementedError def setup(self, input): return NotImplementedError def feedforward(self, input): return NotImplementedError class LogisticRegression(Layer): def __init__(self, npred=1, nclass=1): """ Initialize the parameters of the logistic regression :param npred: Number of predictors :param nclass: Number of labels need to classify """ self.W = theano.shared( value=np.zeros((npred, nclass), dtype=theano.config.floatX), borrow=True ) self.b = theano.shared( value=np.zeros((nclass,), dtype=theano.config.floatX), borrow=True ) self.output = None self.pred = None self.params = [self.W, self.b] self.input = None def calc_output(self, inp): # don't use this line because not robust for infinite # https://github.com/Theano/Theano/issues/3162 # self.softmax_prob = T.nnet.softmax(T.dot(input, self.W) + self.b) log_ratio = T.dot(inp, self.W) + self.b xdev = log_ratio - log_ratio.max(1, keepdims=True) log_softmax = xdev - T.log(T.sum(T.exp(xdev), axis=1, keepdims=True)) return T.exp(log_softmax) def cost_fn(self, X, y): return -T.mean(T.log(self.calc_output(X))[T.arange(y.shape[0]), y]) #return -T.mean(self.log_softmax[T.arange(y.shape[0]),y]) def predict(self, inp): return T.argmax(self.feedforward(inp), axis=1) def feedforward(self, inp): return self.calc_output(inp) def setup(self, inp): self.input = inp self.output = self.calc_output(inp) def logistic_error(pred, target): return T.mean(T.neq(pred, target)) class HiddenLayer(Layer): def __init__(self, npred=1, nclass=1, rng = None, W=None, b=None, activation=T.tanh): if W is None: W_values = np.asarray( rng.uniform( low=-np.sqrt(6./ (npred + nclass)), high=np.sqrt(6./ (npred + nclass)), size = (npred, nclass) ), dtype=theano.config.floatX ) if activation == theano.tensor.nnet.sigmoid: W_values *= 4 W = theano.shared(value=W_values,borrow=True) if b is None: b_values = np.zeros((nclass,), dtype=theano.config.floatX) b = theano.shared(value=b_values, borrow=True) self.W = W self.b = b self.activation_fn = activation self.output = None self.input = None self.params = [self.W, self.b] def calc_output(self, inp): output = T.dot(inp, self.W) + self.b output = (output if self.activation_fn is None else self.activation_fn(output)) return output def setup(self, inp): self.input = inp self.output = self.calc_output(inp) def feedforward(self, inp): return self.calc_output(inp) def predict(self, inp): return self.feedforward(inp) #Creator function def DropoutLayer(parent=HiddenLayer, p_dropout=0.00, *args, **kwargs): class InternalDropoutLayer(parent): def __init__(self, p_dropout=0.00, *args, **kwargs): parent.__init__(self, *args, **kwargs) self.parent = parent self.p_dropout = p_dropout # Output for testing phase def drop(self, X): rng = T.shared_randomstreams.RandomStreams(seed=234) mask = rng.binomial(n=1, p=1-self.p_dropout, size=X.shape) return X * T.cast(mask, theano.config.floatX) def calc_output(self, X): X_dropout = self.drop(X) return self.parent.calc_output(self, X_dropout) def feedforward(self, X): normal_input = (1 - self.p_dropout)*X return self.parent.feedforward(self, normal_input) InternalDropoutLayer.__name__ += '_' + parent.__name__ return InternalDropoutLayer(p_dropout, *args, **kwargs) class BatchNormalizationLayer(HiddenLayer): pass class ConvPoolLayer(object): def __init__(self, filter_shape, image_shape, pool_size=(2,2), rng=None, W=None, b=None): ''' :type filter_shape: tuple or list of length 4 :param filter_shape: (number of filters, num input feature maps, filter height, filter width) :type image_shape: tuple or list of length 4 :param image_shape: (batch_size, num_input feature maps, image height, image with) :type pool_size: tuple or list of length 2 :param pool_size: the downsampling (pooling) factor :type rng: numpy.random.RandomState :param rng: a random number generator used to initialize weights ''' assert image_shape[1] == filter_shape[1] fan_in = np.prod(filter_shape[:1]) fan_out = np.prod(filter_shape[0] * np.prod(filter_shape[2:])) W_bound = np.sqrt(6. / (fan_in + fan_out)) if not W is None: self.W = W else: self.W = theano.shared(np.asarray( rng.uniform(low=-W_bound, high=-W_bound, size=filter_shape), dtype=theano.config.floatX), borrow=True ) if not b is None: self.b = b else: self.b = theano.shared( np.zeros((filter_shape[0],), dtype=theano.config.floatX), borrow=True ) self.params = [self.W, self.b] self.output = None self.input = None self.filter_shape = filter_shape self.image_shape = image_shape self.pool_size = pool_size def calc_output(self, inp): conv_out = conv2d( input=inp, filters=self.W, filter_shape=self.filter_shape, input_shape=self.image_shape ) pooled_out = pool.pool_2d( input=conv_out, ds=self.pool_size, ignore_border=True ) # add the bias term. Since the bias is a vector (1D array), we first # reshape it to a tensor of shape (1, n_filters, 1, 1). Each bias will # thus be broadcasted across mini-batches and feature map # width & height output = T.tanh(pooled_out + self.b.dimshuffle('x', 0, 'x', 'x')) return output def setup(self, inp): self.input = inp self.output = self.calc_output(inp) def feedforward(self, inp): return self.calc_output(inp)
{"/PyML/theano/mlp.py": ["/PyML/libs/__init__.py"], "/logic-reasoning/logic.py": ["/logic-reasoning/utils.py"], "/PyML/neunet/advance_network.py": ["/PyML/libs/__init__.py"], "/PyML/theano/lenet.py": ["/PyML/libs/__init__.py"]}
65,419
Pulin93/dip_ecom
refs/heads/master
/insapp/views.py
from django.shortcuts import render from .models import FeedbackData from .forms import FeedbackFrom from django.http.response import HttpResponse import datetime date = datetime.datetime.now() def main_page(request): return render(request,'base.html') def home_page(request): return render(request,'home_page.html') def contact_page(request): return render(request,'contact_page.html') def courses_page(request): return render(request,'courses_page.html') def feedback_page(request): if request.method=="POST": fform = FeedbackFrom(request.POST) if fform.is_valid(): name = request.POST.get('name') rating = request.POST.get('rating') feedback = request.POST.get('feedback') data = FeedbackData( name=name, rating=rating, feedback=feedback, ) data.save() fform=FeedbackFrom() fdata = FeedbackData.objects.all() return render(request,'feedback_page.html',{'fform':fform,'fdata':fdata}) else: return HttpResponse("Invalid Form") else: fform=FeedbackFrom() fdata = FeedbackData.objects.all() return render(request,'feedback_page.html',{'fform':fform,'fdata':fdata}) def team_page(request): return render(request,'team_page.html') def gellery_page(request): return render(request,'gellery_page.html') def git_repo(request): pass def git_2nrepo(request): pass
{"/insapp/views.py": ["/insapp/models.py"]}
65,420
Pulin93/dip_ecom
refs/heads/master
/insapp/apps.py
from django.apps import AppConfig class InsappConfig(AppConfig): name = 'insapp'
{"/insapp/views.py": ["/insapp/models.py"]}
65,421
Pulin93/dip_ecom
refs/heads/master
/insapp/models.py
from django.db import models # Create your models here. class FeedbackData(models.Model): name = models.CharField(max_length=50) rating = models.IntegerField() data = models.DateTimeField(auto_now_add=True) feedback = models.CharField(max_length=264)
{"/insapp/views.py": ["/insapp/models.py"]}
65,422
Pulin93/dip_ecom
refs/heads/master
/insapp/migrations/0002_auto_20190523_1249.py
# Generated by Django 2.1 on 2019-05-23 07:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('insapp', '0001_initial'), ] operations = [ migrations.AlterField( model_name='feedbackdata', name='data', field=models.DateTimeField(auto_now_add=True), ), migrations.AlterField( model_name='feedbackdata', name='feedback', field=models.CharField(max_length=264), ), ]
{"/insapp/views.py": ["/insapp/models.py"]}
65,423
kamils224/STXNext_training_program
refs/heads/main
/api_projects/models.py
import os from django.db import models from django.db.models.signals import post_delete, pre_delete from django.contrib.auth import get_user_model from django.dispatch import receiver from stx_training_program.celery import app from api_projects.tasks import send_issue_notification, notify_issue_deadline User = get_user_model() class Project(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey( User, related_name="own_projects", on_delete=models.CASCADE ) creation_date = models.DateTimeField(auto_now_add=True) members = models.ManyToManyField(User, related_name="projects", blank=True) def __str__(self): return self.name class Issue(models.Model): def __init__(self, *args, **kwargs): super(Issue, self).__init__(*args, **kwargs) # save these values before update self._original_due_date = self.due_date self._original_assigne = self.assigne class Status(models.TextChoices): TODO = "todo" IN_PROGRESS = "in progress" REVIEW = "review" DONE = "done" title = models.CharField(max_length=100) description = models.TextField(blank=True) created_date = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField() status = models.CharField( max_length=20, choices=Status.choices, default=Status.TODO ) owner = models.ForeignKey( User, related_name="created_issues", on_delete=models.CASCADE ) assigne = models.ForeignKey( User, related_name="own_issues", on_delete=models.SET_NULL, blank=True, null=True, ) project = models.ForeignKey( Project, related_name="issues", on_delete=models.CASCADE ) def __str__(self): return self.title def save(self, *args, **kwargs): super(Issue, self).save(*args, **kwargs) if self._original_assigne != self.assigne: self._perform_assigne_notification() if self._original_due_date != self.due_date: self._perform_deadline_notification() def _perform_assigne_notification(self) -> str: if self.assigne is not None: send_issue_notification.delay( self.assigne.email, "New assignment", f"You are assigned to the task {self.title}", ) if self._original_assigne is not None: send_issue_notification.delay( self.assigne.email, "Assigment is removed", f"You were removed from task {self.title}", ) def _perform_deadline_notification(self): if self.assigne: current_task, _ = DateUpdateTask.objects.get_or_create(issue=self) if current_task.task_id is not None: # remove previous task due to date change app.control.revoke( task_id=current_task.task_id, terminate=True) subject = "Your task is not completed!" message = f"The time for the task {self.title} is over :(" current_task.task_id = notify_issue_deadline.s( self.pk, self.assigne.email, subject, message ).apply_async(eta=self.due_date) current_task.save() # Can be extended / changed as more tasks are needed class DateUpdateTask(models.Model): issue = models.OneToOneField( Issue, on_delete=models.CASCADE, primary_key=True, related_name="issue_task" ) task_id = models.CharField(max_length=50, unique=True, blank=True) class IssueAttachment(models.Model): file_attachment = models.FileField(upload_to="attachments/") issue = models.ForeignKey( Issue, on_delete=models.CASCADE, related_name="files") def __str__(self): return os.path.basename(self.file_attachment.name) # Note: custom fields in Issue init causes infinite loop during cascade deletion # Empty pre_delete signal fixes this issue... # source: https://code.djangoproject.com/ticket/31475 @receiver(pre_delete, sender=Issue) def clean_custom_fields(sender, instance, **kwargs): pass @receiver(post_delete, sender=IssueAttachment) def issue_attachment_delete(sender, instance, **kwargs): instance.file_attachment.delete(save=False)
{"/api_projects/models.py": ["/stx_training_program/celery.py", "/api_projects/tasks.py"], "/api_projects/serializers.py": ["/api_projects/models.py"], "/api_projects/urls.py": ["/api_projects/views.py"], "/api_accounts/views.py": ["/api_accounts/serializers.py", "/api_accounts/utils.py"], "/api_projects/views.py": ["/api_projects/models.py", "/api_projects/serializers.py", "/api_projects/permissions.py"], "/api_projects/admin.py": ["/api_projects/models.py"], "/api_accounts/urls.py": ["/api_accounts/views.py"], "/api_projects/tests.py": ["/api_projects/models.py"], "/api_projects/permissions.py": ["/api_projects/models.py"], "/api_accounts/serializers.py": ["/api_accounts/utils.py"], "/api_projects/tasks.py": ["/api_projects/models.py"]}
65,424
kamils224/STXNext_training_program
refs/heads/main
/api_projects/serializers.py
from rest_framework import serializers from rest_framework.validators import UniqueTogetherValidator from api_projects.models import Project, Issue, IssueAttachment class IssueSerializer(serializers.ModelSerializer): class Meta: model = Issue fields = "__all__" owner = serializers.ReadOnlyField(source="owner.email") assigne = serializers.ReadOnlyField(source="assigne.email") attachments = serializers.SerializerMethodField() def get_attachments(self, issue): request_meta = self.context["request"].META has_hostname = "HTTP_HOST" in request_meta hostname = request_meta["HTTP_HOST"] if has_hostname else "localhost" return ( { "id": file.pk, "name": str(file), "url": f"{hostname}{file.file_attachment.url}", } for file in issue.files.all() ) class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = "__all__" owner = serializers.ReadOnlyField(source="owner.pk") members = serializers.SerializerMethodField() issues = IssueSerializer(many=True, required=False) def get_members(self, project): # possibility to extend returned values return project.members.values("id", "email") class IssueAttachmentSerializer(serializers.ModelSerializer): class Meta: model = IssueAttachment fields = "__all__"
{"/api_projects/models.py": ["/stx_training_program/celery.py", "/api_projects/tasks.py"], "/api_projects/serializers.py": ["/api_projects/models.py"], "/api_projects/urls.py": ["/api_projects/views.py"], "/api_accounts/views.py": ["/api_accounts/serializers.py", "/api_accounts/utils.py"], "/api_projects/views.py": ["/api_projects/models.py", "/api_projects/serializers.py", "/api_projects/permissions.py"], "/api_projects/admin.py": ["/api_projects/models.py"], "/api_accounts/urls.py": ["/api_accounts/views.py"], "/api_projects/tests.py": ["/api_projects/models.py"], "/api_projects/permissions.py": ["/api_projects/models.py"], "/api_accounts/serializers.py": ["/api_accounts/utils.py"], "/api_projects/tasks.py": ["/api_projects/models.py"]}
65,425
kamils224/STXNext_training_program
refs/heads/main
/api_projects/apps.py
from django.apps import AppConfig class ApiProjectsConfig(AppConfig): name = "api_projects"
{"/api_projects/models.py": ["/stx_training_program/celery.py", "/api_projects/tasks.py"], "/api_projects/serializers.py": ["/api_projects/models.py"], "/api_projects/urls.py": ["/api_projects/views.py"], "/api_accounts/views.py": ["/api_accounts/serializers.py", "/api_accounts/utils.py"], "/api_projects/views.py": ["/api_projects/models.py", "/api_projects/serializers.py", "/api_projects/permissions.py"], "/api_projects/admin.py": ["/api_projects/models.py"], "/api_accounts/urls.py": ["/api_accounts/views.py"], "/api_projects/tests.py": ["/api_projects/models.py"], "/api_projects/permissions.py": ["/api_projects/models.py"], "/api_accounts/serializers.py": ["/api_accounts/utils.py"], "/api_projects/tasks.py": ["/api_projects/models.py"]}
65,426
kamils224/STXNext_training_program
refs/heads/main
/api_accounts/apps.py
from django.apps import AppConfig class ApiAccountsConfig(AppConfig): name = "api_accounts"
{"/api_projects/models.py": ["/stx_training_program/celery.py", "/api_projects/tasks.py"], "/api_projects/serializers.py": ["/api_projects/models.py"], "/api_projects/urls.py": ["/api_projects/views.py"], "/api_accounts/views.py": ["/api_accounts/serializers.py", "/api_accounts/utils.py"], "/api_projects/views.py": ["/api_projects/models.py", "/api_projects/serializers.py", "/api_projects/permissions.py"], "/api_projects/admin.py": ["/api_projects/models.py"], "/api_accounts/urls.py": ["/api_accounts/views.py"], "/api_projects/tests.py": ["/api_projects/models.py"], "/api_projects/permissions.py": ["/api_projects/models.py"], "/api_accounts/serializers.py": ["/api_accounts/utils.py"], "/api_projects/tasks.py": ["/api_projects/models.py"]}
65,427
kamils224/STXNext_training_program
refs/heads/main
/api_accounts/utils.py
from typing import Optional from django.utils.http import urlsafe_base64_encode from django.utils.encoding import force_bytes from django.conf import settings from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.contrib.auth import get_user_model from django.core.mail import send_mail from rest_framework.request import Request from rest_framework.reverse import reverse __all__ = ["VerificationTokenGenerator", "send_verification_email"] User = get_user_model() class VerificationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return str(user.pk) + str(timestamp) + str(user.is_active) def send_verification_email( user: User, request: Request, subject: str = "Verify your email", message: str = "", sender: Optional[str] = None, ) -> None: token_generator = VerificationTokenGenerator() token = token_generator.make_token(user) uid = urlsafe_base64_encode(force_bytes(user.pk)) message += create_activation_url(uid, token, request) # The sender is set in DEFAULT_FROM_EMAIL in settings.py send_mail(subject, message, None, recipient_list=[user.email], fail_silently=False) def _create_activation_url(uid: str, token: str, request: Request) -> str: endpoint = reverse("api_accounts:activate") protocol = "https" if request.is_secure() else "http" host = request.get_host() return f"{protocol}://{host}{endpoint}?uid={uid}&token={token}"
{"/api_projects/models.py": ["/stx_training_program/celery.py", "/api_projects/tasks.py"], "/api_projects/serializers.py": ["/api_projects/models.py"], "/api_projects/urls.py": ["/api_projects/views.py"], "/api_accounts/views.py": ["/api_accounts/serializers.py", "/api_accounts/utils.py"], "/api_projects/views.py": ["/api_projects/models.py", "/api_projects/serializers.py", "/api_projects/permissions.py"], "/api_projects/admin.py": ["/api_projects/models.py"], "/api_accounts/urls.py": ["/api_accounts/views.py"], "/api_projects/tests.py": ["/api_projects/models.py"], "/api_projects/permissions.py": ["/api_projects/models.py"], "/api_accounts/serializers.py": ["/api_accounts/utils.py"], "/api_projects/tasks.py": ["/api_projects/models.py"]}
65,428
kamils224/STXNext_training_program
refs/heads/main
/api_accounts/tests.py
from typing import Dict from django.contrib.auth import get_user_model from django.core import mail from rest_framework import status from rest_framework.reverse import reverse_lazy from rest_framework.test import APITestCase from rest_framework.response import Response User = get_user_model() class UserAccountTest(APITestCase): REGISTER_URL = reverse_lazy("api_accounts:register") OBTAIN_TOKEN_URL = reverse_lazy("api_accounts:token_obtain_pair") USER_DETAILS_URL = reverse_lazy("api_accounts:user_details") ACCOUNT_ACTIVATE_URL = reverse_lazy("api_accounts:activate") def setUp(self): self.user_data = { "email": "user@example.com", "password": "password123", } self.bad_email_data = { "email": "bad_email.com", "password": "password123", } def _register_user(self, user_data: Dict[str, str]) -> Response: return self.client.post(self.REGISTER_URL, user_data, format="json") def test_register(self): response = self._register_user(self.user_data) expected_obj_count = 1 self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(User.objects.count(), expected_obj_count) self.assertEqual(User.objects.get().email, self.user_data["email"]) # try to create the same user again response = self._register_user(self.user_data) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(User.objects.count(), expected_obj_count) # there should be a new message self.assertEqual(len(mail.outbox), expected_obj_count) def test_short_password(self): expected_users_count = User.objects.count() user_data = self.user_data user_data["password"] = "123" response = self._register_user(self.user_data) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(User.objects.count(), expected_users_count) def test_bad_email_register(self): expected_users_count = User.objects.count() response = self._register_user(self.bad_email_data) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(User.objects.count(), expected_users_count) def test_login(self): self._register_user(self.user_data) # set user as active user = User.objects.first() user.is_active = True user.save(update_fields=["is_active"]) response = self.client.post( self.OBTAIN_TOKEN_URL, self.user_data, format="json" ) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTrue("access" in response.data and "refresh" in response.data) def test_login_inactive(self): self._register_user(self.user_data) response = self.client.post( self.OBTAIN_TOKEN_URL, self.user_data, format="json" ) # user should be inactive after registration self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) def test_user_details(self): self._register_user(self.user_data) # set user as active user = User.objects.first() user.is_active = True user.save() response = self.client.post( self.OBTAIN_TOKEN_URL, self.user_data, format="json" ) access_token = response.data["access"] self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token}") response = self.client.get(self.USER_DETAILS_URL) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data["email"], user.email) def test_user_details_fail(self): response = self.client.get(self.USER_DETAILS_URL) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) def test_account_activate_fail(self): response = self.client.get( self.ACCOUNT_ACTIVATE_URL, {"uid": "1", "token": "anytoken"} ) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
{"/api_projects/models.py": ["/stx_training_program/celery.py", "/api_projects/tasks.py"], "/api_projects/serializers.py": ["/api_projects/models.py"], "/api_projects/urls.py": ["/api_projects/views.py"], "/api_accounts/views.py": ["/api_accounts/serializers.py", "/api_accounts/utils.py"], "/api_projects/views.py": ["/api_projects/models.py", "/api_projects/serializers.py", "/api_projects/permissions.py"], "/api_projects/admin.py": ["/api_projects/models.py"], "/api_accounts/urls.py": ["/api_accounts/views.py"], "/api_projects/tests.py": ["/api_projects/models.py"], "/api_projects/permissions.py": ["/api_projects/models.py"], "/api_accounts/serializers.py": ["/api_accounts/utils.py"], "/api_projects/tasks.py": ["/api_projects/models.py"]}
65,429
kamils224/STXNext_training_program
refs/heads/main
/api_projects/urls.py
from django.urls import path, include from rest_framework.routers import DefaultRouter from api_projects.views import ( ProjectViewSet, IssueViewSet, IssueAttachmentDelete, IssueAttachmentCreate, ) app_name = "api_projects" # Create a router and register our viewsets with it. router = DefaultRouter() router.register(r"project", ProjectViewSet) router.register(r"issue", IssueViewSet) # The API URLs are now determined automatically by the router. urlpatterns = [ path("", include(router.urls)), path( "attachment/", IssueAttachmentCreate.as_view(), name="issue_attachment_create" ), path( "attachment/<int:pk>/", IssueAttachmentDelete.as_view(), name="issue_attachment_delete", ), ]
{"/api_projects/models.py": ["/stx_training_program/celery.py", "/api_projects/tasks.py"], "/api_projects/serializers.py": ["/api_projects/models.py"], "/api_projects/urls.py": ["/api_projects/views.py"], "/api_accounts/views.py": ["/api_accounts/serializers.py", "/api_accounts/utils.py"], "/api_projects/views.py": ["/api_projects/models.py", "/api_projects/serializers.py", "/api_projects/permissions.py"], "/api_projects/admin.py": ["/api_projects/models.py"], "/api_accounts/urls.py": ["/api_accounts/views.py"], "/api_projects/tests.py": ["/api_projects/models.py"], "/api_projects/permissions.py": ["/api_projects/models.py"], "/api_accounts/serializers.py": ["/api_accounts/utils.py"], "/api_projects/tasks.py": ["/api_projects/models.py"]}
65,430
kamils224/STXNext_training_program
refs/heads/main
/api_accounts/views.py
from django.contrib.auth import get_user_model from django.db import transaction from rest_framework import status from rest_framework.generics import CreateAPIView, RetrieveAPIView from rest_framework.permissions import AllowAny from rest_framework.response import Response from smtplib import SMTPException from api_accounts.models import User from api_accounts.serializers import ( UserRegistrationSerializer, UserSerializer, ActivateAccountSerializer, ) from api_accounts.utils import send_verification_email class UserRegistrationView(CreateAPIView): """ An endpoint for creating user. """ queryset = User.objects.all() serializer_class = UserRegistrationSerializer permission_classes = [AllowAny] @transaction.atomic def create(self, request, *args, **kwargs): serializer = UserRegistrationSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() try: send_verification_email( user, request, subject="Training course", message="Hello! Activate your account here:\n", ) except (SMTPException): return Response(status=status.HTTP_400_BAD_REQUEST) return Response( {"message": f"Registration successful, check your email: {user}"}, status=status.HTTP_201_CREATED, ) class UserDetailsView(RetrieveAPIView): """ An endpoint for user details. Returns data based on the currently logged user, without providing his id/pk in URL. """ serializer_class = UserSerializer def get_object(self): serializer = UserSerializer(self.request.user) return serializer.data class ActivateAccountView(RetrieveAPIView): serializer_class = ActivateAccountSerializer permission_classes = [AllowAny] def get(self, request, format=None): serializer = ActivateAccountSerializer(data=request.query_params) serializer.is_valid(raise_exception=True) user = serializer.validated_data user.is_active = True user.save(update_fields=["is_active"]) return Response( {"message": "Email successfully verified!"}, status=status.HTTP_200_OK )
{"/api_projects/models.py": ["/stx_training_program/celery.py", "/api_projects/tasks.py"], "/api_projects/serializers.py": ["/api_projects/models.py"], "/api_projects/urls.py": ["/api_projects/views.py"], "/api_accounts/views.py": ["/api_accounts/serializers.py", "/api_accounts/utils.py"], "/api_projects/views.py": ["/api_projects/models.py", "/api_projects/serializers.py", "/api_projects/permissions.py"], "/api_projects/admin.py": ["/api_projects/models.py"], "/api_accounts/urls.py": ["/api_accounts/views.py"], "/api_projects/tests.py": ["/api_projects/models.py"], "/api_projects/permissions.py": ["/api_projects/models.py"], "/api_accounts/serializers.py": ["/api_accounts/utils.py"], "/api_projects/tasks.py": ["/api_projects/models.py"]}
65,431
kamils224/STXNext_training_program
refs/heads/main
/api_projects/views.py
from django.db.models import Q from django.shortcuts import get_object_or_404 from rest_framework.response import Response from rest_framework import status from rest_framework.viewsets import ModelViewSet from rest_framework.generics import DestroyAPIView, CreateAPIView from rest_framework.parsers import MultiPartParser from rest_framework.permissions import IsAuthenticated from rest_framework.decorators import action from api_projects.models import Project, Issue, IssueAttachment from api_projects.serializers import ( ProjectSerializer, IssueSerializer, IssueAttachmentSerializer, ) from api_projects.permissions import ( IsOwner, MemberReadOnly, IsProjectMember, ) class ProjectViewSet(ModelViewSet): queryset = Project.objects.all() serializer_class = ProjectSerializer permission_classes = [IsAuthenticated, IsOwner | MemberReadOnly] def get_queryset(self): user = self.request.user query = Q(owner=user) | Q(members=user) return Project.objects.filter(query).distinct() def perform_create(self, serializer): serializer.save(owner=self.request.user) class IssueViewSet(ModelViewSet): queryset = Issue.objects.all() serializer_class = IssueSerializer permission_classes = [IsProjectMember] def get_queryset(self): user = self.request.user query = Q(project__in=user.projects.all()) | Q( project__in=user.own_projects.all() ) return Issue.objects.filter(query) def perform_create(self, serializer): serializer.save(owner=self.request.user) class IssueAttachmentDelete(DestroyAPIView): queryset = IssueAttachment.objects.all() serializer_class = IssueAttachmentSerializer permission_classes = [IsProjectMember | IsOwner] class IssueAttachmentCreate(CreateAPIView): queryset = IssueAttachment.objects.all() serializer_class = IssueAttachmentSerializer permission_classes = [IsProjectMember | IsOwner] parser_classes = [MultiPartParser]
{"/api_projects/models.py": ["/stx_training_program/celery.py", "/api_projects/tasks.py"], "/api_projects/serializers.py": ["/api_projects/models.py"], "/api_projects/urls.py": ["/api_projects/views.py"], "/api_accounts/views.py": ["/api_accounts/serializers.py", "/api_accounts/utils.py"], "/api_projects/views.py": ["/api_projects/models.py", "/api_projects/serializers.py", "/api_projects/permissions.py"], "/api_projects/admin.py": ["/api_projects/models.py"], "/api_accounts/urls.py": ["/api_accounts/views.py"], "/api_projects/tests.py": ["/api_projects/models.py"], "/api_projects/permissions.py": ["/api_projects/models.py"], "/api_accounts/serializers.py": ["/api_accounts/utils.py"], "/api_projects/tasks.py": ["/api_projects/models.py"]}
65,432
kamils224/STXNext_training_program
refs/heads/main
/api_projects/admin.py
from django.contrib import admin from api_projects.models import Project, Issue, DateUpdateTask, IssueAttachment admin.site.register(Project) admin.site.register(Issue) admin.site.register(IssueAttachment) admin.site.register(DateUpdateTask)
{"/api_projects/models.py": ["/stx_training_program/celery.py", "/api_projects/tasks.py"], "/api_projects/serializers.py": ["/api_projects/models.py"], "/api_projects/urls.py": ["/api_projects/views.py"], "/api_accounts/views.py": ["/api_accounts/serializers.py", "/api_accounts/utils.py"], "/api_projects/views.py": ["/api_projects/models.py", "/api_projects/serializers.py", "/api_projects/permissions.py"], "/api_projects/admin.py": ["/api_projects/models.py"], "/api_accounts/urls.py": ["/api_accounts/views.py"], "/api_projects/tests.py": ["/api_projects/models.py"], "/api_projects/permissions.py": ["/api_projects/models.py"], "/api_accounts/serializers.py": ["/api_accounts/utils.py"], "/api_projects/tasks.py": ["/api_projects/models.py"]}
65,433
kamils224/STXNext_training_program
refs/heads/main
/api_accounts/urls.py
from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) from api_accounts.views import ( UserRegistrationView, UserDetailsView, ActivateAccountView, ) app_name = "api_accounts" urlpatterns = [ path("register/", UserRegistrationView.as_view(), name="register"), path("register/activate/", ActivateAccountView.as_view(), name="activate"), path("user/", UserDetailsView.as_view(), name="user_details"), path("token/", TokenObtainPairView.as_view(), name="token_obtain_pair"), path("token/refresh/", TokenRefreshView.as_view(), name="token_refresh"), ] urlpatterns = format_suffix_patterns(urlpatterns)
{"/api_projects/models.py": ["/stx_training_program/celery.py", "/api_projects/tasks.py"], "/api_projects/serializers.py": ["/api_projects/models.py"], "/api_projects/urls.py": ["/api_projects/views.py"], "/api_accounts/views.py": ["/api_accounts/serializers.py", "/api_accounts/utils.py"], "/api_projects/views.py": ["/api_projects/models.py", "/api_projects/serializers.py", "/api_projects/permissions.py"], "/api_projects/admin.py": ["/api_projects/models.py"], "/api_accounts/urls.py": ["/api_accounts/views.py"], "/api_projects/tests.py": ["/api_projects/models.py"], "/api_projects/permissions.py": ["/api_projects/models.py"], "/api_accounts/serializers.py": ["/api_accounts/utils.py"], "/api_projects/tasks.py": ["/api_projects/models.py"]}