Changeset 911

Show
Ignore:
Timestamp:
02/16/12 12:28:34 (15 months ago)
Author:
jjr8
Message:

Fixed/implemented:
* #517: Interpolate OSCAR Currents At Points tool fails with AttributeError?: 'NoneType?' object has no attribute 'lower'
* #518: MGET tools should utilize the ArcGIS progress bar (ArcGIS 9.3 and higher)
* #519: Ocean currents tools (Aviso, OSCAR, HYCOM, ROMS-CoSiNE) should calculate eddy kinetic energy, current direction, and current magnitude grids
* #520: Add tools for Chelton et al. (2011) study "Global observations of nonlinear mesoscale eddies"
Some are not completely done.

Location:
MGET/Branches/Jason/PythonPackage/src/GeoEco
Files:
8 modified

Legend:

Unmodified
Added
Removed
  • MGET/Branches/Jason/PythonPackage/src/GeoEco/DataProducts/Aviso.py

    r906 r911  
    194194         
    195195        if rotationOffset is not None: 
    196             if u'-global-' not in grid.ParentCollection.URL: 
     196            if grid.ParentCollection is not None and u'-global-' not in grid.ParentCollection.URL: 
    197197                raise ValueError(_(u'The Rotate Raster parameter may only be used with global products. Please omit the Rotate Raster parameter and try again.')) 
    198198 
     
    504504 
    505505    @classmethod 
    506     def CreateArcGISRasters(cls, username, password, productName, vectorComponent, temporalResolution, 
     506    def _ConstructGridForParameter(cls, productName, parameter, temporalResolution, username, password, timeout, maxRetryTime, cacheDirectory): 
     507 
     508        # If the caller just wants u or v, construct and return a 
     509        # AvisoGriddedGeostrophicCurrents instance. 
     510         
     511        if parameter in [u'u', u'v']: 
     512            AvisoGriddedGeostrophicCurrents(productName, parameter, temporalResolution, username, password, timeout, maxRetryTime, cacheDirectory) 
     513 
     514        # The caller wants something derived from both u and v. First 
     515        # create u and v component grids. 
     516         
     517        uGrid = AvisoGriddedGeostrophicCurrents(productName, u'u', temporalResolution, username, password, timeout, maxRetryTime, cacheDirectory) 
     518        vGrid = AvisoGriddedGeostrophicCurrents(productName, u'v', temporalResolution, username, password, timeout, maxRetryTime, cacheDirectory) 
     519 
     520        # Now construct and return the appropriate DerivedGrid 
     521        # instance. 
     522 
     523        qav = {} 
     524        for qa in uGrid.GetAllQueryableAttributes(): 
     525            qav[qa.Name] = uGrid.GetQueryableAttributeValue(qa.Name) 
     526 
     527        from GeoEco.Datasets.Virtual import DerivedGrid 
     528 
     529        if parameter == u'dir': 
     530            qav[u'Variable'] = qav[u'Variable'].split(u'_')[0] + u'_dir' 
     531             
     532            return DerivedGrid([uGrid, vGrid], 
     533                               'numpy.arctan2(0 - self._Grids[0].Data.__getitem__(tuple(sliceList)), 0 - self._Grids[1].Data.__getitem__(tuple(sliceList))) / numpy.pi * 180 + 180',    # north = 0, east = 90, south = 180, west = 270 
     534                               _(u'Aviso %(product)s geostrophic current magnitude') % {u'product': productName}, 
     535                               u'float32', 
     536                               noDataValue=uGrid.NoDataValue, 
     537                               queryableAttributes=tuple(uGrid.GetAllQueryableAttributes()), 
     538                               queryableAttributeValues=qav) 
     539 
     540        if parameter == u'eke': 
     541            if not productName.lower().endswith('madt'): 
     542                raise ValueError(_(u'In order to compute eddy kinetic energy, an MADT product must be used.')) 
     543             
     544            qav[u'Variable'] = qav[u'Variable'].split(u'_')[0] + u'_eke' 
     545             
     546            return DerivedGrid([uGrid, vGrid], 
     547                               '0.5 * (self._Grids[0].Data.__getitem__(tuple(sliceList))**2 + self._Grids[1].Data.__getitem__(tuple(sliceList))**2)', 
     548                               _(u'Aviso %(product)s eddy kinetic energy') % {u'product': productName}, 
     549                               u'float32', 
     550                               noDataValue=uGrid.NoDataValue, 
     551                               queryableAttributes=tuple(uGrid.GetAllQueryableAttributes()), 
     552                               queryableAttributeValues=qav) 
     553 
     554        if parameter == u'mag': 
     555            qav[u'Variable'] = qav[u'Variable'].split(u'_')[0] + u'_mag' 
     556             
     557            return DerivedGrid([uGrid, vGrid], 
     558                               '(self._Grids[0].Data.__getitem__(tuple(sliceList))**2 + self._Grids[1].Data.__getitem__(tuple(sliceList))**2) ** 0.5', 
     559                               _(u'Aviso %(product)s geostrophic current magnitude') % {u'product': productName}, 
     560                               u'float32', 
     561                               noDataValue=uGrid.NoDataValue, 
     562                               queryableAttributes=tuple(uGrid.GetAllQueryableAttributes()), 
     563                               queryableAttributeValues=qav) 
     564             
     565        raise RuntimeError(_(u'Programming error in this tool: AvisoGriddedGeostrophicCurrents._ConstructGridForParameter() does not recognize parameter "%(parameter)s". Please contact the author of this tool for assistance.') % {u'parameter': parameter}) 
     566 
     567    @classmethod 
     568    def CreateArcGISRasters(cls, username, password, productName, parameter, temporalResolution, 
    507569                            outputWorkspace, mode=u'add', rasterNameExpressions=['%(Region)s', '%(DataSeries)s', '%(Satellites)s', '%(TemporalResolution)s', '%(Variable)s', '%%Y', '%(DataSeries)s_%(Satellites)s_%(Variable)s_%%Y%%j.img'], 
    508570                            rotationOffset=None, spatialExtent=None, linearUnit=u'Degrees', startDate=None, endDate=None, 
     
    510572                            calculateStatistics=True, buildPyramids=False): 
    511573        cls.__doc__.Obj.ValidateMethodInvocation() 
    512         grid = AvisoGriddedGeostrophicCurrents(productName, vectorComponent, temporalResolution, username, password, timeout, maxRetryTime, cacheDirectory) 
     574        grid = cls._ConstructGridForParameter(productName, parameter, temporalResolution, username, password, timeout, maxRetryTime, cacheDirectory) 
    513575        _AvisoGriddedProduct.CreateArcGISRasters(grid, outputWorkspace, mode, rasterNameExpressions, rotationOffset, spatialExtent, linearUnit, startDate, endDate, calculateStatistics, buildPyramids) 
    514576        return outputWorkspace 
    515577 
    516578    @classmethod 
    517     def CreateClimatologicalArcGISRasters(cls, username, password, productName, vectorComponent, temporalResolution, 
     579    def CreateClimatologicalArcGISRasters(cls, username, password, productName, parameter, temporalResolution, 
    518580                                          statistic, binType, 
    519581                                          outputWorkspace, mode=u'add', rasterNameExpressions=['%(Region)s', '%(DataSeries)s', '%(Satellites)s', '%(TemporalResolution)s', '%(Variable)s', u'%(ClimatologyBinType)s_Climatology', u'%(DataSeries)s_%(Satellites)s_%(Variable)s_%(ClimatologyBinName)s_%(Statistic)s.img'], 
     
    523585                                          calculateStatistics=True, buildPyramids=False): 
    524586        cls.__doc__.Obj.ValidateMethodInvocation() 
    525         grid = AvisoGriddedGeostrophicCurrents(productName, vectorComponent, temporalResolution, username, password, timeout, maxRetryTime, cacheDirectory) 
     587        grid = cls._ConstructGridForParameter(productName, parameter, temporalResolution, username, password, timeout, maxRetryTime, cacheDirectory) 
    526588        _AvisoGriddedProduct.CreateClimatologicalArcGISRasters(grid, statistic, binType, outputWorkspace, mode, rasterNameExpressions, binDuration, startDayOfYear, rotationOffset, spatialExtent, linearUnit, startDate, endDate, calculateStatistics, buildPyramids) 
    527589        return outputWorkspace 
    528590 
    529591    @classmethod 
    530     def InterpolateAtArcGISPoints(cls, username, password, productName, vectorComponent, temporalResolution, 
     592    def InterpolateAtArcGISPoints(cls, username, password, productName, parameter, temporalResolution, 
    531593                                   points, valueField, tField, method=u'Nearest', where=None, noDataValue=None, 
    532594                                   timeout=60, maxRetryTime=120, cacheDirectory=None, 
    533595                                   orderByFields=None, numBlocksToCacheInMemory=128, xBlockSize=16, yBlockSize=16, tBlockSize=3): 
    534596        cls.__doc__.Obj.ValidateMethodInvocation() 
    535         grid = AvisoGriddedGeostrophicCurrents(productName, vectorComponent, temporalResolution, username, password, timeout, maxRetryTime, cacheDirectory) 
     597        grid = cls._ConstructGridForParameter(productName, parameter, temporalResolution, username, password, timeout, maxRetryTime, cacheDirectory) 
    536598        _AvisoGriddedProduct.InterpolateAtArcGISPoints(grid, points, valueField, tField, method, where, noDataValue, orderByFields, numBlocksToCacheInMemory, xBlockSize, yBlockSize, tBlockSize) 
    537599        return points 
     
    19442006CopyArgumentMetadata(AvisoGriddedGeostrophicCurrents.__init__, u'password', AvisoGriddedGeostrophicCurrents.CreateArcGISRasters, u'password') 
    19452007CopyArgumentMetadata(AvisoGriddedGeostrophicCurrents.__init__, u'productName', AvisoGriddedGeostrophicCurrents.CreateArcGISRasters, u'productName') 
    1946 CopyArgumentMetadata(AvisoGriddedGeostrophicCurrents.__init__, u'vectorComponent', AvisoGriddedGeostrophicCurrents.CreateArcGISRasters, u'vectorComponent') 
     2008 
     2009AddArgumentMetadata(AvisoGriddedGeostrophicCurrents.CreateArcGISRasters, u'parameter', 
     2010    typeMetadata=UnicodeStringTypeMetadata(allowedValues=[u'dir', u'eke', u'mag', u'u', u'v'], makeLowercase=True), 
     2011    description=_( 
     2012u"""Geophysical parameter to use, one of: 
     2013 
     2014* dir - Direction of geostrophic water flow, in degrees. Due north is 
     2015  0, due east is 90, due south is 180, due west is 270. 
     2016 
     2017* eke - Eddy kinetic energy, in cm^2/s^2, computed as 0.5*(u^2 + v^2). 
     2018 
     2019* mag - Absolute magnitude (or modulus) of the geostrophic water 
     2020  velocity vector, in cm/s. 
     2021 
     2022* u - Eastward geostrophic water velocity, in cm/s. 
     2023 
     2024* v - Northward geostrophic water velocity, in cm/s. 
     2025"""), 
     2026    arcGISDisplayName=_(u'Geophysical parameter')) 
     2027 
    19472028CopyArgumentMetadata(AvisoGriddedGeostrophicCurrents.__init__, u'temporalResolution', AvisoGriddedGeostrophicCurrents.CreateArcGISRasters, u'temporalResolution') 
    19482029CopyArgumentMetadata(AvisoGriddedSSH.CreateArcGISRasters, u'outputWorkspace', AvisoGriddedGeostrophicCurrents.CreateArcGISRasters, u'outputWorkspace') 
     
    19782059CopyArgumentMetadata(AvisoGriddedGeostrophicCurrents.CreateArcGISRasters, u'password', AvisoGriddedGeostrophicCurrents.CreateClimatologicalArcGISRasters, u'password') 
    19792060CopyArgumentMetadata(AvisoGriddedGeostrophicCurrents.CreateArcGISRasters, u'productName', AvisoGriddedGeostrophicCurrents.CreateClimatologicalArcGISRasters, u'productName') 
    1980 CopyArgumentMetadata(AvisoGriddedGeostrophicCurrents.CreateArcGISRasters, u'vectorComponent', AvisoGriddedGeostrophicCurrents.CreateClimatologicalArcGISRasters, u'vectorComponent') 
     2061CopyArgumentMetadata(AvisoGriddedGeostrophicCurrents.CreateArcGISRasters, u'parameter', AvisoGriddedGeostrophicCurrents.CreateClimatologicalArcGISRasters, u'parameter') 
    19812062CopyArgumentMetadata(AvisoGriddedGeostrophicCurrents.CreateArcGISRasters, u'temporalResolution', AvisoGriddedGeostrophicCurrents.CreateClimatologicalArcGISRasters, u'temporalResolution') 
    19822063CopyArgumentMetadata(AvisoGriddedSSH.CreateClimatologicalArcGISRasters, u'statistic', AvisoGriddedGeostrophicCurrents.CreateClimatologicalArcGISRasters, u'statistic') 
     
    21732254CopyArgumentMetadata(AvisoGriddedGeostrophicCurrents.CreateArcGISRasters, u'password', AvisoGriddedGeostrophicCurrents.InterpolateAtArcGISPoints, u'password') 
    21742255CopyArgumentMetadata(AvisoGriddedGeostrophicCurrents.CreateArcGISRasters, u'productName', AvisoGriddedGeostrophicCurrents.InterpolateAtArcGISPoints, u'productName') 
    2175 CopyArgumentMetadata(AvisoGriddedGeostrophicCurrents.CreateArcGISRasters, u'vectorComponent', AvisoGriddedGeostrophicCurrents.InterpolateAtArcGISPoints, u'vectorComponent') 
     2256CopyArgumentMetadata(AvisoGriddedGeostrophicCurrents.CreateArcGISRasters, u'parameter', AvisoGriddedGeostrophicCurrents.InterpolateAtArcGISPoints, u'parameter') 
    21762257CopyArgumentMetadata(AvisoGriddedGeostrophicCurrents.CreateArcGISRasters, u'temporalResolution', AvisoGriddedGeostrophicCurrents.InterpolateAtArcGISPoints, u'temporalResolution') 
    21772258CopyArgumentMetadata(AvisoGriddedSSH.InterpolateAtArcGISPoints, u'points', AvisoGriddedGeostrophicCurrents.InterpolateAtArcGISPoints, u'points') 
  • MGET/Branches/Jason/PythonPackage/src/GeoEco/DataProducts/NOAA/OSCAR.py

    r906 r911  
    7979            self.ParentCollection._Open() 
    8080            self._CachedTCenterCoords = numpy.array(map(lambda days: datetime.timedelta(int(days)) + datetime.datetime(1992, 10, 5), list(self.ParentCollection._PydapDataset['time'][:])), dtype='object') 
     81            self._CachedTMinCoords = numpy.array([self._CachedTCenterCoords[0] - (self._CachedTCenterCoords[1] - self._CachedTCenterCoords[0])/2] + map(lambda a, b: a + (b-a)/2, self._CachedTCenterCoords[:-1], self._CachedTCenterCoords[1:])) 
     82            self._CachedTMaxCoords = numpy.array(map(lambda a, b: a + (b-a)/2, self._CachedTCenterCoords[:-1], self._CachedTCenterCoords[1:]) + [self._CachedTCenterCoords[-1] + (self._CachedTCenterCoords[-1] - self._CachedTCenterCoords[-2])/2]) 
     83 
    8184        if slices is None: 
    82             result = self._CachedTCenterCoords.copy() 
    83         else: 
    84             result = self._CachedTCenterCoords.__getitem__(*slices) 
    85         if fixedIncrementOffset != 0: 
    86             result += datetime.timedelta(fixedIncrementOffset) 
    87  
    88         return result 
     85            if fixedIncrementOffset < 0: 
     86                return self._CachedTMinCoords.copy() 
     87            if fixedIncrementOffset == 0: 
     88                return self._CachedTCenterCoords.copy() 
     89            return self._CachedTMaxCoords.copy() 
     90             
     91        if fixedIncrementOffset < 0: 
     92            return self._CachedTMinCoords.__getitem__(*slices) 
     93        if fixedIncrementOffset == 0: 
     94            return self._CachedTCenterCoords.__getitem__(*slices) 
     95        return self._CachedTMaxCoords.__getitem__(*slices) 
    8996 
    9097    def _ReadNumpyArray(self, sliceList): 
     
    103110    __doc__ = DynamicDocString() 
    104111 
    105     def _GetVariableName(self): 
    106         return self._VectorComponent 
    107  
    108     VectorComponent = property(_GetVariableName, doc=DynamicDocString()) 
    109  
    110     def __init__(self, vectorComponent, timeout=60, maxRetryTime=120, cacheDirectory=None): 
     112    def _GetParameter(self): 
     113        return self._Parameter 
     114 
     115    Parameter = property(_GetParameter, doc=DynamicDocString()) 
     116 
     117    def __init__(self, parameter, timeout=60, maxRetryTime=120, cacheDirectory=None): 
    111118        self.__doc__.Obj.ValidateMethodInvocation() 
    112119 
    113120        # Initialize our properties. 
    114121 
    115         self._VectorComponent = vectorComponent 
    116         self._DisplayName = _(u'%(name)s component of the OSCAR 5-day unfiltered 1/3 degree ocean surface currents') % {u'name': vectorComponent} 
     122        self._Parameter = parameter 
    117123        self._Timeout = timeout 
    118124        self._MaxRetryTime = maxRetryTime 
     
    120126        self._Grid = None 
    121127 
     128        if parameter == u'eke': 
     129            self._DisplayName = _(u'eddy kinetic energy calcuated from the OSCAR 5-day unfiltered 1/3 degree ocean surface currents') 
     130        elif parameter == u'dir': 
     131            self._DisplayName = _(u'direction of the OSCAR 5-day unfiltered 1/3 degree ocean surface currents') 
     132        elif parameter == u'mag': 
     133            self._DisplayName = _(u'magnitude of the OSCAR 5-day unfiltered 1/3 degree ocean surface currents') 
     134        else: 
     135            self._DisplayName = _(u'%(name)s component of the OSCAR 5-day unfiltered 1/3 degree ocean surface currents') % {u'name': parameter} 
     136 
    122137        # Initialize the base class. 
    123138 
    124         super(OSCAR5DayThirdDegreeCurrents, self).__init__(queryableAttributes=(QueryableAttribute(u'VectorComponent', _(u'Vector component'), UnicodeStringTypeMetadata(allowedValues=[u'u', u'v', u'u_anom', u'v_anom'], makeLowercase=True)),), 
    125                                                            queryableAttributeValues={u'VectorComponent': vectorComponent}, 
     139        super(OSCAR5DayThirdDegreeCurrents, self).__init__(queryableAttributes=(QueryableAttribute(u'Parameter', _(u'Geophysical parameter'), UnicodeStringTypeMetadata(allowedValues=[u'dir', u'dir_anom', u'eke', u'mag', u'mag_anom', u'u', u'v', u'u_anom', u'v_anom'], makeLowercase=True)),), 
     140                                                           queryableAttributeValues={u'Parameter': parameter}, 
    126141                                                           lazyPropertyValues={'SpatialReference': Dataset.ConvertSpatialReference('proj4', '+proj=latlong +ellps=WGS84 +datum=WGS84 +no_defs', 'obj'), 
    127142                                                                               'Dimensions': u'tyx', 
     
    154169        if name in ['CornerCoords', 'Shape']: 
    155170            if self._Grid is None: 
    156                 self._Grid = _OSCAR5DayThirdDegreeCurrents4D(self._VectorComponent, self._Timeout, self._MaxRetryTime, self._CacheDirectory) 
     171                self._Grid = cls._ConstructGridForParameter(self._Parameter, self._Timeout, self._MaxRetryTime, self._CacheDirectory) 
    157172 
    158173            if name == 'CornerCoords': 
     
    174189 
    175190        if self._Grid is None: 
    176             self._Grid = _OSCAR5DayThirdDegreeCurrents4D(self._VectorComponent, self._Timeout, self._MaxRetryTime, self._CacheDirectory) 
     191            self._Grid = cls._ConstructGridForParameter(self._Parameter, self._Timeout, self._MaxRetryTime, self._CacheDirectory) 
    177192         
    178193        return self._Grid._GetCoords(coord, coordNum, slices, sliceDims, fixedIncrementOffset) 
     
    190205 
    191206        if self._Grid is None: 
    192             self._Grid = _OSCAR5DayThirdDegreeCurrents4D(self._VectorComponent, self._Timeout, self._MaxRetryTime, self._CacheDirectory) 
     207            self._Grid = cls._ConstructGridForParameter(self._Parameter, self._Timeout, self._MaxRetryTime, self._CacheDirectory) 
    193208 
    194209        sliceList = [sliceList[0], slice(0, 1), sliceList[1], sliceList[2]] 
    195210        data, noDataValue = self._Grid._ReadNumpyArray(sliceList) 
    196211        return data.reshape(data.shape[0], data.shape[2], data.shape[3]), noDataValue 
     212 
     213    @classmethod 
     214    def _ConstructGridForParameter(cls, parameter, timeout, maxRetryTime, cacheDirectory): 
     215 
     216        # If the caller just wants u, v, u_anom, or v_anom, construct 
     217        # and return a OSCAR5DayThirdDegreeCurrents instance. 
     218         
     219        if parameter in [u'u', u'v', u'u_anom', u'v_anom']: 
     220            OSCAR5DayThirdDegreeCurrents(parameter, timeout, maxRetryTime, cacheDirectory) 
     221 
     222        # The caller wants something derived from both u and v. First 
     223        # create u and v component grids. 
     224 
     225        if parameter.endswith('_anom'): 
     226            uGrid = OSCAR5DayThirdDegreeCurrents(u'u_anom', timeout, maxRetryTime, cacheDirectory) 
     227            vGrid = OSCAR5DayThirdDegreeCurrents(u'v_anom', timeout, maxRetryTime, cacheDirectory) 
     228        else: 
     229            uGrid = OSCAR5DayThirdDegreeCurrents(u'u', timeout, maxRetryTime, cacheDirectory) 
     230            vGrid = OSCAR5DayThirdDegreeCurrents(u'v', timeout, maxRetryTime, cacheDirectory) 
     231 
     232        # Now construct and return the appropriate DerivedGrid 
     233        # instance. 
     234 
     235        qav = {} 
     236        for qa in uGrid.GetAllQueryableAttributes(): 
     237            qav[qa.Name] = uGrid.GetQueryableAttributeValue(qa.Name) 
     238        qav[u'Parameter'] = parameter 
     239 
     240        from GeoEco.Datasets.Virtual import DerivedGrid 
     241 
     242        if parameter in [u'dir', u'dir_anom']: 
     243            return DerivedGrid([uGrid, vGrid], 
     244                               'numpy.arctan2(0 - self._Grids[0].Data.__getitem__(tuple(sliceList)), 0 - self._Grids[1].Data.__getitem__(tuple(sliceList))) / numpy.pi * 180 + 180',    # north = 0, east = 90, south = 180, west = 270 
     245                               _(u'OSCAR %(parameter)s') % {u'parameter': parameter}, 
     246                               u'float32', 
     247                               noDataValue=uGrid.NoDataValue, 
     248                               queryableAttributes=tuple(uGrid.GetAllQueryableAttributes()), 
     249                               queryableAttributeValues=qav) 
     250 
     251        if parameter == u'eke': 
     252            return DerivedGrid([uGrid, vGrid], 
     253                               '0.5 * (self._Grids[0].Data.__getitem__(tuple(sliceList))**2 + self._Grids[1].Data.__getitem__(tuple(sliceList))**2)', 
     254                               _(u'OSCAR %(parameter)s') % {u'parameter': parameter}, 
     255                               u'float32', 
     256                               noDataValue=uGrid.NoDataValue, 
     257                               queryableAttributes=tuple(uGrid.GetAllQueryableAttributes()), 
     258                               queryableAttributeValues=qav) 
     259 
     260        if parameter in [u'mag', u'mag_anom']: 
     261            return DerivedGrid([uGrid, vGrid], 
     262                               '(self._Grids[0].Data.__getitem__(tuple(sliceList))**2 + self._Grids[1].Data.__getitem__(tuple(sliceList))**2) ** 0.5', 
     263                               _(u'OSCAR %(parameter)s') % {u'parameter': parameter}, 
     264                               u'float32', 
     265                               noDataValue=uGrid.NoDataValue, 
     266                               queryableAttributes=tuple(uGrid.GetAllQueryableAttributes()), 
     267                               queryableAttributeValues=qav) 
     268             
     269        raise RuntimeError(_(u'Programming error in this tool: OSCAR5DayThirdDegreeCurrents._ConstructGridForParameter() does not recognize parameter "%(parameter)s". Please contact the author of this tool for assistance.') % {u'parameter': parameter}) 
    197270 
    198271    @classmethod 
     
    226299 
    227300    @classmethod 
    228     def CreateArcGISRasters(cls, vectorComponent, 
    229                             outputWorkspace, mode=u'add', rasterNameExpressions=['%(VectorComponent)s', '%%Y', '%(VectorComponent)s_%%Y%%j.img'], 
     301    def CreateArcGISRasters(cls, parameter, 
     302                            outputWorkspace, mode=u'add', rasterNameExpressions=['%(Parameter)s', '%%Y', '%(Parameter)s_%%Y%%j.img'], 
    230303                            rotationOffset=None, spatialExtent=None, startDate=None, endDate=None, 
    231304                            timeout=60, maxRetryTime=120, cacheDirectory=None, 
    232305                            calculateStatistics=True, buildPyramids=False): 
    233306        cls.__doc__.Obj.ValidateMethodInvocation() 
    234         grid = OSCAR5DayThirdDegreeCurrents(vectorComponent, timeout, maxRetryTime, cacheDirectory) 
     307        grid = OSCAR5DayThirdDegreeCurrents(parameter, timeout, maxRetryTime, cacheDirectory) 
    235308        try: 
    236309            from GeoEco.Datasets.ArcGIS import ArcGISWorkspace, ArcGISRaster 
     
    244317 
    245318    @classmethod 
    246     def CreateClimatologicalArcGISRasters(cls, vectorComponent, 
     319    def CreateClimatologicalArcGISRasters(cls, parameter, 
    247320                                          statistic, binType, 
    248                                           outputWorkspace, mode=u'add', rasterNameExpressions=['%(VectorComponent)s', u'%(ClimatologyBinType)s_Climatology', u'%(VectorComponent)s_%(ClimatologyBinName)s_%(Statistic)s.img'], 
     321                                          outputWorkspace, mode=u'add', rasterNameExpressions=['%(Parameter)s', u'%(ClimatologyBinType)s_Climatology', u'%(Parameter)s_%(ClimatologyBinName)s_%(Statistic)s.img'], 
    249322                                          binDuration=1, startDayOfYear=1, 
    250323                                          rotationOffset=None, spatialExtent=None, startDate=None, endDate=None, 
     
    252325                                          calculateStatistics=True, buildPyramids=False): 
    253326        cls.__doc__.Obj.ValidateMethodInvocation() 
    254         grid = OSCAR5DayThirdDegreeCurrents(vectorComponent, timeout, maxRetryTime, cacheDirectory) 
     327        grid = OSCAR5DayThirdDegreeCurrents(parameter, timeout, maxRetryTime, cacheDirectory) 
    255328        try: 
    256329            from GeoEco.Datasets.ArcGIS import ArcGISWorkspace, ArcGISRaster 
     
    320393 
    321394    @classmethod 
    322     def InterpolateAtArcGISPoints(cls, vectorComponent, 
     395    def InterpolateAtArcGISPoints(cls, parameter, 
    323396                                   points, valueField, tField, method=u'Nearest', where=None, noDataValue=None, 
    324397                                   timeout=60, maxRetryTime=120, cacheDirectory=None, 
    325398                                   orderByFields=None, numBlocksToCacheInMemory=128, xBlockSize=16, yBlockSize=16, tBlockSize=3): 
    326399        cls.__doc__.Obj.ValidateMethodInvocation() 
    327         grid = OSCAR5DayThirdDegreeCurrents(vectorComponent, timeout, maxRetryTime, cacheDirectory) 
     400        grid = OSCAR5DayThirdDegreeCurrents(parameter, timeout, maxRetryTime, cacheDirectory) 
    328401        try: 
    329402            if orderByFields is not None: 
     
    429502    description=_(u'OSCAR5DayThirdDegreeCurrents instance.')) 
    430503 
    431 AddArgumentMetadata(OSCAR5DayThirdDegreeCurrents.__init__, u'vectorComponent', 
    432     typeMetadata=UnicodeStringTypeMetadata(allowedValues=[u'u', u'v', u'u_anom', u'v_anom'], makeLowercase=True), 
    433     description=_( 
    434 u"""OSCAR currents vector component, one of: 
     504AddArgumentMetadata(OSCAR5DayThirdDegreeCurrents.__init__, u'parameter', 
     505    typeMetadata=UnicodeStringTypeMetadata(allowedValues=[u'dir', u'dir_anom', u'eke', u'mag', u'mag_anom', u'u', u'v', u'u_anom', u'v_anom'], makeLowercase=True), 
     506    description=_( 
     507u"""Geophysical parameter to use, one of: 
     508 
     509* dir - Direction of water flow, in degrees. Due north is 0, due east 
     510  is 90, due south is 180, due west is 270. 
     511 
     512* dir_anom - Direction of water flow (from u_anom and v_anom). 
     513 
     514* eke - Eddy kinetic energy, in cm^2/s^2, computed as 0.5*(u^2 + v^2). 
     515 
     516* mag - Absolute magnitude (or modulus) of the water velocity vector, 
     517  in cm/s. 
     518 
     519* mag_anom - Absolute magnitude of water velocity (from u_anom and 
     520  v_anom). 
    435521 
    436522* u - Eastward sea water velocity, in m/s. 
     
    451537Please see the OSCAR documentation for more information about these 
    452538variables."""), 
    453     arcGISDisplayName=_(u'Vector component')) 
     539    arcGISDisplayName=_(u'Geophysical parameter')) 
    454540 
    455541CopyArgumentMetadata(THREDDSCatalog.__init__, u'timeout', OSCAR5DayThirdDegreeCurrents.__init__, u'timeout') 
     
    477563    description=_(u'OSCAR5DayThirdDegreeCurrents class or instance.')) 
    478564 
    479 CopyArgumentMetadata(OSCAR5DayThirdDegreeCurrents.__init__, u'vectorComponent', OSCAR5DayThirdDegreeCurrents.CreateArcGISRasters, u'vectorComponent') 
     565CopyArgumentMetadata(OSCAR5DayThirdDegreeCurrents.__init__, u'parameter', OSCAR5DayThirdDegreeCurrents.CreateArcGISRasters, u'parameter') 
    480566 
    481567AddArgumentMetadata(OSCAR5DayThirdDegreeCurrents.CreateArcGISRasters, u'outputWorkspace', 
     
    516602The default expression assumes you are storing rasters in a file 
    517603system directory and creates them in a tree structure with levels for 
    518 the vector component and year. When storing rasters in a directory, 
    519 the final expression specifies the file name of the raster and any 
    520 preceding expressions specify subdirectories. The extension of the 
    521 final expression determines the output raster format: .asc for ArcInfo 
    522 ASCII Grid, .bmp for BMP, .gif for GIF, .img for an ERDAS IMAGINE 
    523 file, .jpg for JPEG, .jp2 for JPEG 2000, .png for PNG, .tif for 
    524 GeoTIFF, or no extension for ArcInfo Binary Grid. The default 
     604the geophysical parameter and year. When storing rasters in a 
     605directory, the final expression specifies the file name of the raster 
     606and any preceding expressions specify subdirectories. The extension of 
     607the final expression determines the output raster format: .asc for 
     608ArcInfo ASCII Grid, .bmp for BMP, .gif for GIF, .img for an ERDAS 
     609IMAGINE file, .jpg for JPEG, .jp2 for JPEG 2000, .png for PNG, .tif 
     610for GeoTIFF, or no extension for ArcInfo Binary Grid. The default 
    525611expression uses .img. 
    526612 
     
    533619codes with appropriate values when creating each raster: 
    534620 
    535 * %(VectorComponent)s - Vector component represented by the the output 
    536   raster, either "u", "v", "u_anom", or "v_anom". 
     621* %(Parameter)s - Geophysical parameter represented by the the output 
     622  raster, either "dir", "dir_anom", "eke", "mag", "mag_anom", "u", 
     623  "v", "u_anom", or "v_anom". 
    537624 
    538625* %%Y - four-digit year of the raster. 
     
    645732 
    646733CopyArgumentMetadata(OSCAR5DayThirdDegreeCurrents.CreateArcGISRasters, u'cls', OSCAR5DayThirdDegreeCurrents.CreateClimatologicalArcGISRasters, u'cls') 
    647 CopyArgumentMetadata(OSCAR5DayThirdDegreeCurrents.CreateArcGISRasters, u'vectorComponent', OSCAR5DayThirdDegreeCurrents.CreateClimatologicalArcGISRasters, u'vectorComponent') 
     734CopyArgumentMetadata(OSCAR5DayThirdDegreeCurrents.CreateArcGISRasters, u'parameter', OSCAR5DayThirdDegreeCurrents.CreateClimatologicalArcGISRasters, u'parameter') 
    648735 
    649736AddArgumentMetadata(OSCAR5DayThirdDegreeCurrents.CreateClimatologicalArcGISRasters, u'statistic', 
     
    741828The default expression assumes you are storing rasters in a file 
    742829system directory and creates them in a tree structure with levels for 
    743 the vector component and climatology type. When storing rasters in a 
    744 directory, the final expression specifies the file name of the raster 
    745 and any preceding expressions specify subdirectories. The extension of 
    746 the final expression determines the output raster format: .asc for 
    747 ArcInfo ASCII Grid, .bmp for BMP, .gif for GIF, .img for an ERDAS 
    748 IMAGINE file, .jpg for JPEG, .jp2 for JPEG 2000, .png for PNG, .tif 
    749 for GeoTIFF, or no extension for ArcInfo Binary Grid. The default 
     830the geophysical parameter and climatology type. When storing rasters 
     831in a directory, the final expression specifies the file name of the 
     832raster and any preceding expressions specify subdirectories. The 
     833extension of the final expression determines the output raster format: 
     834.asc for ArcInfo ASCII Grid, .bmp for BMP, .gif for GIF, .img for an 
     835ERDAS IMAGINE file, .jpg for JPEG, .jp2 for JPEG 2000, .png for PNG, 
     836.tif for GeoTIFF, or no extension for ArcInfo Binary Grid. The default 
    750837expression uses .img. 
    751838 
     
    758845codes with appropriate values when creating each raster: 
    759846 
    760 * %(VectorComponent)s - Vector component represented by the the output 
    761   raster, either "u", "v", "u_anom", or "v_anom". 
     847* %(Parameter)s - Geophysical parameter represented by the the output 
     848  raster, either "dir", "dir_anom", "eke", "mag", "mag_anom", "u", 
     849  "v", "u_anom", or "v_anom". 
    762850 
    763851* %(ClimatologyBinType)s - type of the climatology bin, either "Daily" 
     
    10181106 
    10191107CopyArgumentMetadata(OSCAR5DayThirdDegreeCurrents.CreateArcGISRasters, u'cls', OSCAR5DayThirdDegreeCurrents.InterpolateAtArcGISPoints, u'cls') 
    1020 CopyArgumentMetadata(OSCAR5DayThirdDegreeCurrents.CreateArcGISRasters, u'vectorComponent', OSCAR5DayThirdDegreeCurrents.InterpolateAtArcGISPoints, u'vectorComponent') 
     1108CopyArgumentMetadata(OSCAR5DayThirdDegreeCurrents.CreateArcGISRasters, u'parameter', OSCAR5DayThirdDegreeCurrents.InterpolateAtArcGISPoints, u'parameter') 
    10211109 
    10221110AddArgumentMetadata(OSCAR5DayThirdDegreeCurrents.InterpolateAtArcGISPoints, u'points', 
  • MGET/Branches/Jason/PythonPackage/src/GeoEco/DataProducts/OSU/MesoscaleEddies.py

    r909 r911  
    172172                progressReporter = ProgressReporter(progressMessage1=_(u'Still copying points: %(elapsed)s elapsed, %(opsCompleted)i points copied, %(perOp)s per point, %(opsRemaining)i remaining, estimated completion time: %(etc)s.'), 
    173173                                                    completionMessage=_(u'Finished copying points: %(elapsed)s elapsed, %(opsCompleted)i points copied, %(perOp)s per point.'), 
    174                                                     abortedMessage=_(u'Insert operation stopped before all points were copied: %(elapsed)s elapsed, %(opsCompleted)i points copied, %(perOp)s per point, %(opsIncomplete)i points not copied.')) 
     174                                                    abortedMessage=_(u'Insert operation stopped before all points were copied: %(elapsed)s elapsed, %(opsCompleted)i points copied, %(perOp)s per point, %(opsIncomplete)i points not copied.'), 
     175                                                    arcGISProgressorLabel=_(u'Copying %(count)i points') % {u'count': len(track)}) 
    175176                progressReporter.Start(len(track)) 
    176177            else: 
     
    212213            # desired). 
    213214 
     215            indexes = ['track', 'obsdate', 'lon', 'lat'] 
     216 
    214217            if reportProgress: 
    215                 self._LogInfo(_(u'Creating indexes.')) 
     218                self._LogInfo(_(u'Creating %(count)i indexes.') % {u'count': len(indexes)}) 
     219                progressReporter = ProgressReporter(progressMessage1=_(u'Still creating indexes: %(elapsed)s elapsed, %(opsCompleted)i indexes created, %(perOp)s per index, %(opsRemaining)i remaining, estimated completion time: %(etc)s.'), 
     220                                                    completionMessage=_(u'Finished creating indexes: %(elapsed)s elapsed, %(opsCompleted)i indexes created, %(perOp)s per index.'), 
     221                                                    abortedMessage=_(u'Stopped before all indexes were created: %(elapsed)s elapsed, %(opsCompleted)i indexes created, %(perOp)s per index, %(opsIncomplete)i indexes not created.'), 
     222                                                    arcGISProgressorLabel=_(u'Creating %(count)i indexes') % {u'count': len(indexes)}) 
     223                progressReporter.Start(len(indexes)) 
    216224            else: 
    217                 self._LogDebug(_(u'Creating indexes.')) 
    218  
    219             table.CreateIndex(['track'], 'idx_%s_track' % tableName) 
    220             table.CreateIndex(['obsdate'], 'idx_%s_obsdate' % tableName) 
    221             table.CreateIndex(['lon'], 'idx_%s_lon' % tableName) 
    222             table.CreateIndex(['lat'], 'idx_%s_lat' % tableName) 
    223  
    224             if reportProgress: 
    225                 self._LogInfo(_(u'Indexes created.')) 
    226             else: 
     225                self._LogDebug(_(u'Creating %(count)i indexes.') % {u'count': len(indexes)}) 
     226 
     227            for indexName in indexes: 
     228                table.CreateIndex([indexName], 'idx_%s_%s' % (tableName, indexName)) 
     229                if reportProgress: 
     230                    progressReporter.ReportProgress() 
     231 
     232            if not reportProgress: 
    227233                self._LogDebug(_(u'Indexes created.')) 
    228234 
     
    335341    def ExtractArcGISPointsFromSpatiaLite(cls, spatiaLiteDB, outputFeatureClass, tableName=u'EddyPoints', where=None, overwriteExisting=False): 
    336342        cls.__doc__.Obj.ValidateMethodInvocation() 
     343 
    337344        from GeoEco.Datasets.SpatiaLite import SpatiaLiteDatabase 
    338345        from GeoEco.Datasets.ArcGIS import ArcGISWorkspace, ArcGISTable 
     346 
    339347        db = SpatiaLiteDatabase(spatiaLiteDB) 
    340348        try: 
     349            if where is not None: 
     350                cls._LogInfo(_(u'Querying for eddy centroids that match the expression: %(where)s') % {u'where': where}) 
     351                selectCursor = db.Connection.execute('SELECT COUNT(*) FROM %s WHERE %s;' % (tableName, where)) 
     352            else: 
     353                selectCursor = db.Connection.execute('SELECT COUNT(*) FROM %s;' % tableName) 
     354            try: 
     355                pointCount = selectCursor.fetchone()[0] 
     356            finally: 
     357                selectCursor.close() 
     358             
    341359            table = db.QueryDatasets("TableName = '%s'" % tableName, False)[0] 
    342360            workspace = ArcGISWorkspace(os.path.dirname(outputFeatureClass), ArcGISTable, pathCreationExpressions=['%(TableName)s'], queryableAttributes=(QueryableAttribute('TableName', 'Table name', UnicodeStringTypeMetadata()),)) 
    343             workspace.ImportTable(os.path.basename(outputFeatureClass), table, where=where) 
     361            workspace.ImportTable(os.path.basename(outputFeatureClass), table, where=where, rowCount=pointCount) 
    344362        finally: 
    345363            db.Close() 
     
    371389        table.AddField('meanU', 'float32') 
    372390 
    373         # Open an insert cursor on the output feature class. 
    374  
    375         insertCursor = table.OpenInsertCursor() 
     391        # Open a SQLite cursor on the SpatiaLite database. We use 
     392        # a SQLite cursor rather than our own SelectCursor 
     393        # interface because if the caller specified a where 
     394        # clause, we want to extract complete tracks (all points) 
     395        # for eddies that have any points (even just one) that 
     396        # satisfy that expression. To do that, we have to join the 
     397        # eddy points table to itself, which is not possible using 
     398        # our SelectCursor interface. 
     399 
     400        from GeoEco.Datasets.SpatiaLite import SpatiaLiteDatabase 
     401 
     402        db = SpatiaLiteDatabase(spatiaLiteDB) 
    376403        try: 
    377  
    378             # Open a SQLite cursor on the SpatiaLite database. We use 
    379             # a SQLite cursor rather than our own SelectCursor 
    380             # interface because if the caller specified a where 
    381             # clause, we want to extract complete tracks (all points) 
    382             # for eddies that have any points (even just one) that 
    383             # satisfy that expression. To do that, we have to join the 
    384             # eddy points table to itself, which is not possible using 
    385             # our SelectCursor interface. 
    386  
    387             from GeoEco.Datasets.SpatiaLite import SpatiaLiteDatabase 
    388  
    389             db = SpatiaLiteDatabase(spatiaLiteDB) 
     404            if where is None: 
     405                selectCursor = db.Connection.execute('SELECT COUNT(DISTINCT track) FROM %s;' % tableName) 
     406                try: 
     407                    trackCount = selectCursor.fetchone()[0] 
     408                finally: 
     409                    selectCursor.close() 
     410 
     411                selectCursor = db.Connection.execute('SELECT * FROM %s ORDER BY track ASC, n ASC;' % tableName) 
     412 
     413            else: 
     414                db.Connection.execute('CREATE TABLE temp.MatchingEddies AS SELECT DISTINCT track FROM %s WHERE %s;' % (tableName, where)) 
     415 
     416                selectCursor = db.Connection.execute('SELECT COUNT(DISTINCT track) FROM temp.MatchingEddies;') 
     417                try: 
     418                    trackCount = selectCursor.fetchone()[0] 
     419                finally: 
     420                    selectCursor.close() 
     421 
     422                selectCursor = db.Connection.execute('SELECT t1.* FROM %s AS t1 INNER JOIN temp.MatchingEddies ON t1.track = temp.MatchingEddies.track ORDER BY t1.track ASC, t1.n ASC;' % (tableName,)) 
     423 
    390424            try: 
    391                 if where is None: 
    392                     selectCursor = db.Connection.execute('SELECT * FROM %s ORDER BY track ASC, n ASC;' % tableName) 
    393                 else: 
    394                     db.Connection.execute('CREATE TABLE temp.MatchingEddies AS SELECT DISTINCT track FROM %s WHERE %s;' % (tableName, where)) 
    395                     selectCursor = db.Connection.execute('SELECT t1.* FROM %s AS t1 INNER JOIN temp.MatchingEddies ON t1.track = temp.MatchingEddies.track ORDER BY t1.track ASC, t1.n ASC;' % (tableName,)) 
    396  
     425                # Open an insert cursor on the output feature class. 
     426 
     427                cls._LogInfo(_(u'Inserting %(count)i lines into %(fc)s.') % {u'count': trackCount, u'fc': outputFeatureClass}) 
     428 
     429                insertCursor = table.OpenInsertCursor(trackCount) 
    397430                try: 
    398431                    ogr = cls._ogr() 
     
    496529                        point = selectCursor.fetchone() 
    497530                finally: 
    498                     selectCursor.close() 
    499                     del selectCursor 
     531                    del insertCursor 
    500532            finally: 
    501                 db.Close() 
     533                selectCursor.close() 
     534                del selectCursor 
    502535        finally: 
    503             del insertCursor 
     536            db.Close() 
    504537 
    505538 
     
    524557**References** 
    525558 
    526 Chelton, D.B., M.G. Schlax, and R.M. Samelson (2011) Global 
     559Chelton, D.B., M.G. Schlax, and R.M. Samelson (2011). Global 
    527560observations of nonlinear mesoscale eddies. Progress in Oceanography 
    52856191: 167-216.""") 
     
    581614about how these parameters were calculated. 
    582615 
    583 This tool typically requires 5 to 10 minutes to complete on a reasonably 
    584 fast computer.""") + _CheltonMesocaleEddies_References, 
     616This tool typically requires 10-15 minutes to complete on a reasonably 
     617fast computer. The SpatiaLite database typically requires about 650 MB 
     618of disk space.""") + _CheltonMesocaleEddies_References, 
    585619    isExposedToPythonCallers=True, 
    586620    isExposedByCOM=True, 
     
    684718 
    685719Because the database includes over 200,000 eddies with nearly 2.5 
    686 million total centroids, we recommend that you use the Where Clause 
     720million centroids in total, we recommend that you use the Where Clause 
    687721parameter to limit the extraction to the eddies that occured in your 
    688722region and time period of interest. If you do not specify the Where 
     
    821855eddies that occured in your region and time period of interest. If you 
    822856do not specify the Where Clause, all 200,000 tracks will be extracted, 
    823 which can take quite a long time and produce an output feature class 
    824 that requires several hundred megabytes of disk space.""") + 
    825 _CheltonMesocaleEddies_References, 
     857which may take 30-45 minutes on a relatively fast computer and 
     858produce an output feature class that requires 50-100 MB of disk 
     859space.""") + _CheltonMesocaleEddies_References, 
    826860    isExposedToPythonCallers=True, 
    827861    isExposedByCOM=True, 
  • MGET/Branches/Jason/PythonPackage/src/GeoEco/Datasets/Collections.py

    r903 r911  
    632632                                                    completionMessage=_(u'Finished checking: %(elapsed)s elapsed, %(opsCompleted)i datasets checked, %(perOp)s per dataset.'), 
    633633                                                    abortedMessage=_(u'Processing stopped before all datasets were checked: %(elapsed)s elapsed, %(opsCompleted)i datasets checked, %(perOp)s per dataset, %(opsIncomplete)i datasets not checked.'), 
    634                                                     loggingChannel=DatasetCollection._LoggingChannel) 
     634                                                    loggingChannel=DatasetCollection._LoggingChannel, 
     635                                                    arcGISProgressorLabel=_(u'Checking for existing datasets')) 
    635636                progressReporter.Start(len(datasets)) 
    636637            else: 
     
    673674                                                completionMessage=_(u'Import complete: %(elapsed)s elapsed, %(opsCompleted)i datasets imported, %(perOp)s per dataset.'), 
    674675                                                abortedMessage=_(u'Import stopped before all datasets were imported: %(elapsed)s elapsed, %(opsCompleted)i datasets imported, %(perOp)s per dataset, %(opsIncomplete)i datasets not imported.'), 
    675                                                 loggingChannel=DatasetCollection._LoggingChannel) 
     676                                                loggingChannel=DatasetCollection._LoggingChannel, 
     677                                                arcGISProgressorLabel=_(u'Importing %(count)i datasets') % {u'count': datasetsToAdd}) 
    676678            progressReporter.Start(datasetsToAdd) 
    677679        else: 
  • MGET/Branches/Jason/PythonPackage/src/GeoEco/Datasets/Virtual.py

    r903 r911  
    13551355 
    13561356 
     1357class DerivedGrid(Grid): 
     1358    __doc__ = DynamicDocString() 
     1359 
     1360    def __init__(self, grids, expression, displayName, dataType, noDataValue=None, queryableAttributes=None, queryableAttributeValues=None): 
     1361        # TODO: self.__class__.__doc__.Obj.ValidateMethodInvocation() 
     1362 
     1363        # Initialize our properties. 
     1364 
     1365        self._Grids = grids 
     1366        self._Expression = expression 
     1367        self._DisplayName = displayName 
     1368        self._ValidatedGrids = False 
     1369 
     1370        # Initialize the base class. 
     1371         
     1372        super(DerivedGrid, self).__init__(queryableAttributes=queryableAttributes, queryableAttributeValues=queryableAttributeValues) 
     1373 
     1374        # Set lazy properties that override those of the contained 
     1375        # grids. 
     1376 
     1377        self.SetLazyPropertyValue('UnscaledDataType', dataType) 
     1378        self.SetLazyPropertyValue('ScaledDataType', None) 
     1379        self.SetLazyPropertyValue('UnscaledNoDataValue', noDataValue) 
     1380        self.SetLazyPropertyValue('ScaledNoDataValue', None) 
     1381        self.SetLazyPropertyValue('ScalingFunction', None) 
     1382        self.SetLazyPropertyValue('UnscalingFunction', None) 
     1383 
     1384    def _Close(self): 
     1385        if hasattr(self, '_Grids') and self._Grids is not None: 
     1386            for grid in self._Grids: 
     1387                grid.Close() 
     1388        super(DerivedGrid, self)._Close() 
     1389 
     1390    def _GetDisplayName(self): 
     1391        return self._DisplayName 
     1392 
     1393    def _GetLazyPropertyPhysicalValue(self, name): 
     1394 
     1395        # If the requested property is PhysicalDimensions or 
     1396        # PhysicalDimensionsFlipped, return values indicating the 
     1397        # dimensions in the ideal order. The contained grids take care 
     1398        # of reordering, if needed. 
     1399 
     1400        if name == 'PhysicalDimensions': 
     1401            return self.Dimensions 
     1402 
     1403        if name == 'PhysicalDimensionsFlipped': 
     1404            return tuple([False] * len(self.Dimensions)) 
     1405 
     1406        # Otherwise just get the unaltered value from the first 
     1407        # contained grid. 
     1408 
     1409        return self._Grids[0].GetLazyPropertyValue(name) 
     1410 
     1411    @classmethod 
     1412    def _TestCapability(cls, capability): 
     1413        if capability == 'SetSpatialReference': 
     1414            return NotImplementedError(_(u'DerivedGrid does not support setting the spatial reference.')) 
     1415        return cls._Grids[0]._TestCapability(capability) 
     1416 
     1417    def _GetCoords(self, coord, coordNum, slices, sliceDims, fixedIncrementOffset): 
     1418        return self._Grids[0]._GetCoords(coord, coordNum, slices, sliceDims, fixedIncrementOffset) 
     1419 
     1420    def _ReadNumpyArray(self, sliceList): 
     1421 
     1422        # If we have not yet validated the grids, do so now. 
     1423 
     1424        if not self._ValidatedGrids: 
     1425            if len(self._Grids) > 1: 
     1426                for grid in self._Grids[1:]: 
     1427                    if grid.Shape != self._Grids[0].Shape: 
     1428                        raise ValueError(_(u'%(dn1)s does not have the same shape as %(dn2)s.') % {u'dn1': grid.DisplayName, u'dn1': self._Grids[0].DisplayName}) 
     1429                     
     1430                    # TODO: More validation? 
     1431 
     1432            self._ValidatedGrids = True 
     1433 
     1434        # Evaluate the expression. 
     1435 
     1436        import numpy 
     1437 
     1438        data = eval(self._Expression) 
     1439 
     1440        # If a no data value was provided, mask any cells that have no 
     1441        # data in any of the grids. 
     1442 
     1443        if self.NoDataValue is not None: 
     1444            for grid in self._Grids: 
     1445                if grid.NoDataValue is not None: 
     1446                    data[grid.Data.__getitem__(tuple(sliceList)) == grid.NoDataValue] = self.NoDataValue 
     1447 
     1448        # Return the data and no data value. 
     1449 
     1450        return data, self.NoDataValue 
     1451 
     1452 
    13571453class RotatedGlobalGrid(Grid): 
    13581454    __doc__ = DynamicDocString() 
     
    33023398 
    33033399############################################################################### 
     3400# Metadata: DerivedGrid class 
     3401############################################################################### 
     3402 
     3403AddClassMetadata(DerivedGrid, 
     3404    shortDescription=_(u'TODO: Add description.')) 
     3405 
     3406# TODO: Add metadata 
     3407 
     3408############################################################################### 
    33043409# Metadata: RotatedGlobalGrid class 
    33053410############################################################################### 
     
    34873592           'ClippedGrid', 
    34883593           'MaskedGrid', 
     3594           'DerivedGrid', 
    34893595           'RotatedGlobalGrid', 
    34903596           'MemoryCachedGrid', 
  • MGET/Branches/Jason/PythonPackage/src/GeoEco/Datasets/__init__.py

    r903 r911  
    21352135 
    21362136        if reportProgress: 
     2137            if rowCount is not None: 
     2138                arcGISProgressorLabel = _(u'Retrieving %(rowCount)i %(plural)s') % {u'rowCount': rowCount, u'plural': self._RowDescriptionPlural} 
     2139            else: 
     2140                arcGISProgressorLabel = None 
     2141 
    21372142            self._ProgressReporter = ProgressReporter(progressMessage1=_(u'Still retrieving %(plural)s: %%(elapsed)s elapsed, %%(opsCompleted)i %(plural)s retrieved, %%(perOp)s per %(singular)s, %%(opsRemaining)i remaining, estimated completion time: %%(etc)s.') % {u'singular': self._RowDescriptionSingular, u'plural': self._RowDescriptionPlural}, 
    21382143                                                      progressMessage2=_(u'Still retrieving %(plural)s: %%(elapsed)s elapsed, %%(opsCompleted)i %(plural)s retrieved, %%(perOp)s per %(singular)s.') % {u'singular': self._RowDescriptionSingular, u'plural': self._RowDescriptionPlural}, 
    21392144                                                      completionMessage=_(u'Finished retrieving %(plural)s: %%(elapsed)s elapsed, %%(opsCompleted)i %(plural)s retrieved, %%(perOp)s per %(singular)s.') % {u'singular': self._RowDescriptionSingular, u'plural': self._RowDescriptionPlural}, 
    2140                                                       abortedMessage=_(u'Query operation stopped before all %(plural)s were retrieved: %%(elapsed)s elapsed, %%(opsCompleted)i %(plural)s retrieved, %%(perOp)s per %(singular)s, %%(opsIncomplete)i %(plural)s not retrieved.') % {u'singular': self._RowDescriptionSingular, u'plural': self._RowDescriptionPlural}) 
     2145                                                      abortedMessage=_(u'Query operation stopped before all %(plural)s were retrieved: %%(elapsed)s elapsed, %%(opsCompleted)i %(plural)s retrieved, %%(perOp)s per %(singular)s, %%(opsIncomplete)i %(plural)s not retrieved.') % {u'singular': self._RowDescriptionSingular, u'plural': self._RowDescriptionPlural}, 
     2146                                                      arcGISProgressorLabel=arcGISProgressorLabel) 
    21412147            self._ProgressReporter.Start(rowCount) 
    21422148        else: 
     
    23622368 
    23632369        if reportProgress: 
    2364             self._ProgressReporter = _UpdateCursorProgressReporter(self._RowDescriptionSingular, self._RowDescriptionPlural) 
     2370            if rowCount is not None: 
     2371                arcGISProgressorLabel = _(u'Updating %(rowCount)i %(plural)s') % {u'rowCount': rowCount, u'plural': self._RowDescriptionPlural} 
     2372            else: 
     2373                arcGISProgressorLabel = None 
     2374 
     2375            self._ProgressReporter = _UpdateCursorProgressReporter(self._RowDescriptionSingular, self._RowDescriptionPlural, arcGISProgressorLabel) 
    23652376            self._ProgressReporter.Start(rowCount) 
    23662377 
     
    23922403class _UpdateCursorProgressReporter(ProgressReporter): 
    23932404 
    2394     def __init__(self, rowDescriptionSingular, rowDescriptionPlural): 
     2405    def __init__(self, rowDescriptionSingular, rowDescriptionPlural, arcGISProgressorLabel): 
    23952406        self.RowsUpdated = 0 
    23962407        self.RowsDeleted = 0 
     
    23992410            progressMessage2=_(u'Update in progress: %%(elapsed)s elapsed, %%(updated)i %(plural)s updated, %%(deleted)i deleted, %%(unchanged)i unchanged, %%(perOp)s per %(singular)s.') % {u'singular': rowDescriptionSingular, u'plural': rowDescriptionPlural}, 
    24002411            completionMessage=_(u'Update complete: %%(elapsed)s elapsed, %%(updated)i %(plural)s updated, %%(deleted)i deleted, %%(unchanged)i unchanged, %%(perOp)s per %(singular)s.') % {u'singular': rowDescriptionSingular, u'plural': rowDescriptionPlural}, 
    2401             abortedMessage=_(u'Update stopped before all %(plural)s were processed: %%(elapsed)s elapsed, %%(updated)i %(plural)s updated, %%(deleted)i deleted, %%(unchanged)i unchanged, %%(perOp)s per %(singular)s, %%(opsIncomplete)i %(plural)s not processed.') % {u'singular': rowDescriptionSingular, u'plural': rowDescriptionPlural}) 
     2412            abortedMessage=_(u'Update stopped before all %(plural)s were processed: %%(elapsed)s elapsed, %%(updated)i %(plural)s updated, %%(deleted)i deleted, %%(unchanged)i unchanged, %%(perOp)s per %(singular)s, %%(opsIncomplete)i %(plural)s not processed.') % {u'singular': rowDescriptionSingular, u'plural': rowDescriptionPlural}, 
     2413            arcGISProgressorLabel=arcGISProgressorLabel) 
    24022414 
    24032415    def _FormatProgressMessage1(self, timeElapsed, opsCompleted, timePerOp, opsRemaining, estimatedTimeOfCompletionString): 
     
    25012513 
    25022514        if reportProgress: 
     2515            if rowCount is not None: 
     2516                arcGISProgressorLabel = _(u'Inserting %(rowCount)i %(plural)s') % {u'rowCount': rowCount, u'plural': self._RowDescriptionPlural} 
     2517            else: 
     2518                arcGISProgressorLabel = None 
     2519                 
    25032520            self._ProgressReporter = ProgressReporter(progressMessage1=_(u'Still inserting %(plural)s: %%(elapsed)s elapsed, %%(opsCompleted)i %(plural)s inserted, %%(perOp)s per %(singular)s, %%(opsRemaining)i remaining, estimated completion time: %%(etc)s.') % {u'singular': self._RowDescriptionSingular, u'plural': self._RowDescriptionPlural}, 
    25042521                                                      progressMessage2=_(u'Still inserting %(plural)s: %%(elapsed)s elapsed, %%(opsCompleted)i %(plural)s inserted, %%(perOp)s per %(singular)s.') % {u'singular': self._RowDescriptionSingular, u'plural': self._RowDescriptionPlural}, 
    25052522                                                      completionMessage=_(u'Finished inserting %(plural)s: %%(elapsed)s elapsed, %%(opsCompleted)i %(plural)s inserted, %%(perOp)s per %(singular)s.') % {u'singular': self._RowDescriptionSingular, u'plural': self._RowDescriptionPlural}, 
    2506                                                       abortedMessage=_(u'Insert operation stopped before all %(plural)s were inserted: %%(elapsed)s elapsed, %%(opsCompleted)i %(plural)s inserted, %%(perOp)s per %(singular)s, %%(opsIncomplete)i %(plural)s not inserted.') % {u'singular': self._RowDescriptionSingular, u'plural': self._RowDescriptionPlural}) 
     2523                                                      abortedMessage=_(u'Insert operation stopped before all %(plural)s were inserted: %%(elapsed)s elapsed, %%(opsCompleted)i %(plural)s inserted, %%(perOp)s per %(singular)s, %%(opsIncomplete)i %(plural)s not inserted.') % {u'singular': self._RowDescriptionSingular, u'plural': self._RowDescriptionPlural}, 
     2524                                                      arcGISProgressorLabel=arcGISProgressorLabel) 
    25072525            self._ProgressReporter.Start(rowCount) 
    25082526        else: 
  • MGET/Branches/Jason/PythonPackage/src/GeoEco/Logging.py

    r772 r911  
    2222import logging 
    2323import logging.config       # Do not remove this statement, even though it seems redundant after importing the logging module above. Removing it will break something. 
     24import math 
    2425import os 
    2526import sys 
     
    441442                 completionMessage=_(u'Processing complete: %(elapsed)s elapsed, %(opsCompleted)i operations completed, %(perOp)s per operation.'), 
    442443                 abortedMessage=_(u'Processing stopped before all operations were completed: %(elapsed)s elapsed, %(opsCompleted)i operations completed, %(perOp)s per operation, %(opsIncomplete)i operations not completed.'), 
    443                  loggingChannel=u'GeoEco'): 
     444                 loggingChannel=u'GeoEco', 
     445                 arcGISProgressorLabel=None): 
    444446 
    445447        self.ProgressMessage1 = progressMessage1 
     
    448450        self.AbortedMessage = abortedMessage 
    449451        self.LoggingChannel = loggingChannel 
     452        self._ArcGISProgressorLabel = arcGISProgressorLabel 
    450453        self._TotalOperations = None 
    451454        self._OperationsCompleted = 0 
     
    492495    AbortedMessage = property(_GetAbortedMessage, _SetAbortedMessage, doc=DynamicDocString()) 
    493496 
     497    def _GetArcGISProgressorLabel(self): 
     498        return self._ArcGISProgressorLabel 
     499     
     500    ArcGISProgressorLabel = property(_GetArcGISProgressorLabel, None, doc=DynamicDocString()) 
     501 
     502    def _UseArcGISProgressor(self): 
     503        from GeoEco.ArcGIS import GeoprocessorManager 
     504        return self._TotalOperations is not None and self.ArcGISProgressorLabel is not None and GeoprocessorManager.GetGeoprocessor() is not None and (GeoprocessorManager.GetArcGISMajorVersion() > 9 or GeoprocessorManager.GetArcGISMajorVersion() == 9 and GeoprocessorManager.GetArcGISMinorVersion() >= 3) and not GeoprocessorManager.GetGeoprocessorIsCOMObject() 
     505 
    494506    def _GetLoggingChannel(self): 
    495507        return self._LoggingChannel 
     
    506518    def _SetTotalOperations(self, value): 
    507519        assert value is None or (isinstance(value, types.IntType) and value >= 0), u'totalOperations must be a non-negative integer, or None' 
     520         
    508521        self._TotalOperations = value 
     522 
     523        if self._UseArcGISProgressor(): 
     524            from GeoEco.ArcGIS import GeoprocessorManager 
     525            gp = GeoprocessorManager.GetWrappedGeoprocessor() 
     526            if self.HasStarted: 
     527                try: 
     528                    gp.ResetProgressor() 
     529                except: 
     530                    pass 
     531            try: 
     532                gp.SetProgressor('step', self.ArcGISProgressorLabel, 0, 1000, 1) 
     533                if self.HasStarted: 
     534                    gp.SetProgressorPosition(min(1000, int(math.floor(float(self._OperationsCompleted) / float(self._TotalOperations) * 1000.)))) 
     535            except: 
     536                pass 
     537         
    509538        if self._TotalOperations is not None and self.HasStarted and self._OperationsCompleted >= self._TotalOperations: 
    510539            self.Stop() 
     
    616645            else: 
    617646                self._ClockNextReportTime = clockNow + 60.0 
     647 
     648        if self._UseArcGISProgressor() and int(math.floor(float(self._OperationsCompleted) / float(self._TotalOperations) * 1000.)) > int(math.floor(float(self._OperationsCompleted - 1) / float(self._TotalOperations) * 1000.)): 
     649            from GeoEco.ArcGIS import GeoprocessorManager 
     650            gp = GeoprocessorManager.GetWrappedGeoprocessor() 
     651            try: 
     652                gp.SetProgressorPosition(min(1000, int(math.floor(float(self._OperationsCompleted) / float(self._TotalOperations) * 1000.)))) 
     653            except: 
     654                pass 
    618655 
    619656    def Stop(self): 
     
    633670        elif self._AbortedMessage is not None: 
    634671            self._Log(self._FormatAbortedMessage(timeElapsed, self._OperationsCompleted, timePerOp, self._TotalOperations - self._OperationsCompleted)) 
     672 
     673        if self._UseArcGISProgressor(): 
     674            from GeoEco.ArcGIS import GeoprocessorManager 
     675            gp = GeoprocessorManager.GetWrappedGeoprocessor() 
     676            try: 
     677                gp.ResetProgressor() 
     678            except: 
     679                pass 
    635680 
    636681    def _Log(self, message): 
     
    12641309    isExposedToPythonCallers=True) 
    12651310 
     1311AddPropertyMetadata(ProgressReporter.ArcGISProgressorLabel, 
     1312    typeMetadata=UnicodeStringTypeMetadata(canBeNone=True), 
     1313    shortDescription=_(u'Label to use for the ArcGIS geoprocessor progressor.'), 
     1314    longDescription=_( 
     1315u"""Starting in ArcGIS 9.3, the geoprocessor allows scripts to control 
     1316the geoprocessing progress bar. If this property is not None and Start 
     1317is called with a total number of operations, the value of this 
     1318property will be used as the progressor label (the text that appears 
     1319above the progress bar) and the ProgressReporter instance will 
     1320automatically call the geoprocessor's SetProgressorPosition method 
     1321when ProgressReporter.ReportProgress is called. 
     1322 
     1323If this property is None or Start is called without a total number of 
     1324operations, the ProgressReporter instance will not manipulate the 
     1325geoprocessor's progress bar."""), 
     1326    isExposedToPythonCallers=True) 
     1327 
    12661328AddPropertyMetadata(ProgressReporter.TotalOperations, 
    12671329    typeMetadata=IntegerTypeMetadata(canBeNone=True), 
     
    13481410    description=ProgressReporter.LoggingChannel.__doc__.Obj.ShortDescription + u'\n\n' + ProgressReporter.LoggingChannel.__doc__.Obj.LongDescription) 
    13491411 
     1412AddArgumentMetadata(ProgressReporter.__init__, u'arcGISProgressorLabel', 
     1413    typeMetadata=ProgressReporter.ArcGISProgressorLabel.__doc__.Obj.Type, 
     1414    description=ProgressReporter.ArcGISProgressorLabel.__doc__.Obj.ShortDescription + u'\n\n' + ProgressReporter.ArcGISProgressorLabel.__doc__.Obj.LongDescription) 
     1415 
    13501416AddResultMetadata(ProgressReporter.__init__, u'progressReporter', 
    13511417    typeMetadata=ClassInstanceTypeMetadata(cls=ProgressReporter), 
  • MGET/Branches/Jason/PythonPackage/src/GeoEco/SpatialAnalysis/Interpolation.py

    r877 r911  
    364364                 
    365365                gridCoordIncrements.append(list(grids[i].CoordIncrements)) 
    366                 if grids[i].Dimensions[0] == u't': 
     366                if grids[i].Dimensions[0] == u't' and grids[i].CoordIncrements[0] is not None: 
    367367                    if grids[i].TSemiRegularity is not None: 
    368368                        gridCoordIncrements[i][0] = None