prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>F57.py<|end_file_name|><|fim▁begin|>import fechbase class Records(fechbase.RecordsBase): def <|fim_middle|>(self): fechbase.RecordsBase.__init__(self) self.fields = [ {'name': 'FORM TYPE', 'number': '1'}, {'name': 'FILER FEC CMTE ID', 'number': '2'}, {'name': 'ENTITY TYPE', 'number': '3'}, {'name': 'NAME (Payee)', 'number': '4'}, {'name': 'STREET 1', 'number': '5'}, {'name': 'STREET 2', 'number': '6'}, {'name': 'CITY', 'number': '7'}, {'name': 'STATE', 'number': '8'}, {'name': 'ZIP', 'number': '9'}, {'name': 'TRANSDESC', 'number': '10'}, {'name': 'Of Expenditure', 'number': '11-'}, {'name': 'AMOUNT', 'number': '12'}, {'name': 'SUPPORT/OPPOSE', 'number': '13'}, {'name': 'S/O FEC CAN ID NUMBER', 'number': '14'}, {'name': 'S/O CAN/NAME', 'number': '15'}, {'name': 'S/O CAN/OFFICE', 'number': '16'}, {'name': 'S/O CAN/STATE', 'number': '17'}, {'name': 'S/O CAN/DIST', 'number': '18'}, {'name': 'FEC COMMITTEE ID NUMBER', 'number': '19'}, {'name': 'Unused field', 'number': '20'}, {'name': 'Unused field', 'number': '21'}, {'name': 'Unused field', 'number': '22'}, {'name': 'Unused field', 'number': '23'}, {'name': 'Unused field', 'number': '24'}, {'name': 'CONDUIT NAME', 'number': '25'}, {'name': 'CONDUIT STREET 1', 'number': '26'}, {'name': 'CONDUIT STREET 2', 'number': '27'}, {'name': 'CONDUIT CITY', 'number': '28'}, {'name': 'CONDUIT STATE', 'number': '29'}, {'name': 'CONDUIT ZIP', 'number': '30'}, {'name': 'AMENDED CD', 'number': '31'}, {'name': 'TRAN ID', 'number': '32'}, ] self.fields_names = self.hash_names(self.fields) <|fim▁end|>
__init__
<|file_name|>loggingFunctions.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """ Set up the logging """<|fim▁hole|>import logging import tempfile import os def initialize_logging(): """ Set up the screen and file logging. :return: The log filename """ # set up DEBUG logging to file, INFO logging to STDERR log_file = os.path.join(tempfile.gettempdir(), 'spfy.log') formatter = logging.Formatter( '%(asctime)s %(name)-12s %(levelname)-8s %(message)s') # set up logging to file - see previous section for more details logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename=log_file, filemode='w') # define a Handler which writes INFO messages or higher to the sys.stderr console = logging.StreamHandler() console.setFormatter(formatter) console.setLevel(logging.INFO) # add the handler to the root logger logging.getLogger('').addHandler(console) return log_file<|fim▁end|>
<|file_name|>loggingFunctions.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """ Set up the logging """ import logging import tempfile import os def initialize_logging(): <|fim_middle|> <|fim▁end|>
""" Set up the screen and file logging. :return: The log filename """ # set up DEBUG logging to file, INFO logging to STDERR log_file = os.path.join(tempfile.gettempdir(), 'spfy.log') formatter = logging.Formatter( '%(asctime)s %(name)-12s %(levelname)-8s %(message)s') # set up logging to file - see previous section for more details logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename=log_file, filemode='w') # define a Handler which writes INFO messages or higher to the sys.stderr console = logging.StreamHandler() console.setFormatter(formatter) console.setLevel(logging.INFO) # add the handler to the root logger logging.getLogger('').addHandler(console) return log_file
<|file_name|>loggingFunctions.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """ Set up the logging """ import logging import tempfile import os def <|fim_middle|>(): """ Set up the screen and file logging. :return: The log filename """ # set up DEBUG logging to file, INFO logging to STDERR log_file = os.path.join(tempfile.gettempdir(), 'spfy.log') formatter = logging.Formatter( '%(asctime)s %(name)-12s %(levelname)-8s %(message)s') # set up logging to file - see previous section for more details logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename=log_file, filemode='w') # define a Handler which writes INFO messages or higher to the sys.stderr console = logging.StreamHandler() console.setFormatter(formatter) console.setLevel(logging.INFO) # add the handler to the root logger logging.getLogger('').addHandler(console) return log_file <|fim▁end|>
initialize_logging
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import<|fim▁hole|> from .base import WhiteNoise __version__ = '2.0.3' __all__ = ['WhiteNoise']<|fim▁end|>
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. '''<|fim▁hole|><|fim▁end|>
if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold)
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): <|fim_middle|> #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
'''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1'])
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): <|fim_middle|> def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
'''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2)
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): <|fim_middle|> #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
'''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']);
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): <|fim_middle|> def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
'''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1'])
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): <|fim_middle|> def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
'''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold)
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): <|fim_middle|> #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
'''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold)
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): <|fim_middle|> def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1'])
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): <|fim_middle|> def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
'''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold)
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): <|fim_middle|> #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
'''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold)
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): <|fim_middle|> def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1'])
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): <|fim_middle|> def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold)
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): <|fim_middle|> #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold)
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): <|fim_middle|> def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
'''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1'])
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): <|fim_middle|> def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold)
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): <|fim_middle|> <|fim▁end|>
''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold)
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: <|fim_middle|> unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
print('No unflooded training domain provided.') return None
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. <|fim_middle|> return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
threshold = float(domain.algorithm_params['modis_diff_threshold'])
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: <|fim_middle|> unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
print('No unflooded training domain provided.') return None
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: <|fim_middle|> return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
threshold = float(domain.algorithm_params['dartmouth_threshold'])
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: <|fim_middle|> unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
print('No unflooded training domain provided.') return None
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: <|fim_middle|> return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
threshold = float(domain.algorithm_params['mod_ndwi_threshold'])
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: <|fim_middle|> unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
print('No unflooded training domain provided.') return None
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: <|fim_middle|> return get_fai(b).lte(threshold) <|fim▁end|>
threshold = float(domain.algorithm_params['fai_threshold'])
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def <|fim_middle|>(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
dem_threshold
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def <|fim_middle|>(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
evi
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def <|fim_middle|>(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
xiao
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def <|fim_middle|>(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
get_diff
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def <|fim_middle|>(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
diff_learned
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def <|fim_middle|>(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
modis_diff
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def <|fim_middle|>(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
get_dartmouth
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def <|fim_middle|>(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
dart_learned
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def <|fim_middle|>(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
dartmouth
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def <|fim_middle|>(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
get_mod_ndwi
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def <|fim_middle|>(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
mod_ndwi_learned
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def <|fim_middle|>(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
mod_ndwi
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def <|fim_middle|>(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
get_fai
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def <|fim_middle|>(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
fai_learned
<|file_name|>simple_modis_algorithms.py<|end_file_name|><|fim▁begin|># ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache # License, Version 2.0 (the "License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # ----------------------------------------------------------------------------- import ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def <|fim_middle|>(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) <|fim▁end|>
fai
<|file_name|>__manifest__.py<|end_file_name|><|fim▁begin|>##############################################################################<|fim▁hole|># # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Products Management Group', 'version': '13.0.1.0.0', 'category': 'base.module_category_knowledge_management', 'author': 'ADHOC SA', 'website': 'www.adhoc.com.ar', 'license': 'AGPL-3', 'depends': [ 'sale', ], 'data': [ 'security/product_management_security.xml', ], 'installable': False, }<|fim▁end|>
# # Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar) # All Rights Reserved.
<|file_name|>gd.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2016, Jianfeng Chen <[email protected]> # vim: set ts=4 sts=4 sw=4 expandtab smartindent: # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights<|fim▁hole|># to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from __future__ import division def dist(a, b): return sum((i-j)**2 for i, j in zip(a, b)) def GD(PF0, PFc): up = 0 for i in PFc: up += min([dist(i, j) for j in PF0]) return up**0.5 / (len(PFc))<|fim▁end|>
<|file_name|>gd.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2016, Jianfeng Chen <[email protected]> # vim: set ts=4 sts=4 sw=4 expandtab smartindent: # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from __future__ import division def dist(a, b): <|fim_middle|> def GD(PF0, PFc): up = 0 for i in PFc: up += min([dist(i, j) for j in PF0]) return up**0.5 / (len(PFc)) <|fim▁end|>
return sum((i-j)**2 for i, j in zip(a, b))
<|file_name|>gd.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2016, Jianfeng Chen <[email protected]> # vim: set ts=4 sts=4 sw=4 expandtab smartindent: # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from __future__ import division def dist(a, b): return sum((i-j)**2 for i, j in zip(a, b)) def GD(PF0, PFc): <|fim_middle|> <|fim▁end|>
up = 0 for i in PFc: up += min([dist(i, j) for j in PF0]) return up**0.5 / (len(PFc))
<|file_name|>gd.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2016, Jianfeng Chen <[email protected]> # vim: set ts=4 sts=4 sw=4 expandtab smartindent: # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from __future__ import division def <|fim_middle|>(a, b): return sum((i-j)**2 for i, j in zip(a, b)) def GD(PF0, PFc): up = 0 for i in PFc: up += min([dist(i, j) for j in PF0]) return up**0.5 / (len(PFc)) <|fim▁end|>
dist
<|file_name|>gd.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2016, Jianfeng Chen <[email protected]> # vim: set ts=4 sts=4 sw=4 expandtab smartindent: # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from __future__ import division def dist(a, b): return sum((i-j)**2 for i, j in zip(a, b)) def <|fim_middle|>(PF0, PFc): up = 0 for i in PFc: up += min([dist(i, j) for j in PF0]) return up**0.5 / (len(PFc)) <|fim▁end|>
GD
<|file_name|>hashivault_approle_role_get.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python from ansible.module_utils.hashivault import hashivault_argspec from ansible.module_utils.hashivault import hashivault_auth_client from ansible.module_utils.hashivault import hashivault_init from ansible.module_utils.hashivault import hashiwrapper ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'community', 'version': '1.1'} DOCUMENTATION = ''' --- module: hashivault_approle_role_get version_added: "3.8.0" short_description: Hashicorp Vault approle role get module description: - Module to get a approle role from Hashicorp Vault. options: name: description: - role name. mount_point: description: - mount point for role default: approle extends_documentation_fragment: hashivault ''' EXAMPLES = ''' --- - hosts: localhost tasks: - hashivault_approle_role_get: name: 'ashley' register: 'vault_approle_role_get' - debug: msg="Role is {{vault_approle_role_get.role}}" ''' def main(): argspec = hashivault_argspec()<|fim▁hole|> argspec['mount_point'] = dict(required=False, type='str', default='approle') module = hashivault_init(argspec) result = hashivault_approle_role_get(module.params) if result.get('failed'): module.fail_json(**result) else: module.exit_json(**result) @hashiwrapper def hashivault_approle_role_get(params): name = params.get('name') client = hashivault_auth_client(params) result = client.get_role(name, mount_point=params.get('mount_point')) return {'role': result} if __name__ == '__main__': main()<|fim▁end|>
argspec['name'] = dict(required=True, type='str')
<|file_name|>hashivault_approle_role_get.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python from ansible.module_utils.hashivault import hashivault_argspec from ansible.module_utils.hashivault import hashivault_auth_client from ansible.module_utils.hashivault import hashivault_init from ansible.module_utils.hashivault import hashiwrapper ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'community', 'version': '1.1'} DOCUMENTATION = ''' --- module: hashivault_approle_role_get version_added: "3.8.0" short_description: Hashicorp Vault approle role get module description: - Module to get a approle role from Hashicorp Vault. options: name: description: - role name. mount_point: description: - mount point for role default: approle extends_documentation_fragment: hashivault ''' EXAMPLES = ''' --- - hosts: localhost tasks: - hashivault_approle_role_get: name: 'ashley' register: 'vault_approle_role_get' - debug: msg="Role is {{vault_approle_role_get.role}}" ''' def main(): <|fim_middle|> @hashiwrapper def hashivault_approle_role_get(params): name = params.get('name') client = hashivault_auth_client(params) result = client.get_role(name, mount_point=params.get('mount_point')) return {'role': result} if __name__ == '__main__': main() <|fim▁end|>
argspec = hashivault_argspec() argspec['name'] = dict(required=True, type='str') argspec['mount_point'] = dict(required=False, type='str', default='approle') module = hashivault_init(argspec) result = hashivault_approle_role_get(module.params) if result.get('failed'): module.fail_json(**result) else: module.exit_json(**result)
<|file_name|>hashivault_approle_role_get.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python from ansible.module_utils.hashivault import hashivault_argspec from ansible.module_utils.hashivault import hashivault_auth_client from ansible.module_utils.hashivault import hashivault_init from ansible.module_utils.hashivault import hashiwrapper ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'community', 'version': '1.1'} DOCUMENTATION = ''' --- module: hashivault_approle_role_get version_added: "3.8.0" short_description: Hashicorp Vault approle role get module description: - Module to get a approle role from Hashicorp Vault. options: name: description: - role name. mount_point: description: - mount point for role default: approle extends_documentation_fragment: hashivault ''' EXAMPLES = ''' --- - hosts: localhost tasks: - hashivault_approle_role_get: name: 'ashley' register: 'vault_approle_role_get' - debug: msg="Role is {{vault_approle_role_get.role}}" ''' def main(): argspec = hashivault_argspec() argspec['name'] = dict(required=True, type='str') argspec['mount_point'] = dict(required=False, type='str', default='approle') module = hashivault_init(argspec) result = hashivault_approle_role_get(module.params) if result.get('failed'): module.fail_json(**result) else: module.exit_json(**result) @hashiwrapper def hashivault_approle_role_get(params): <|fim_middle|> if __name__ == '__main__': main() <|fim▁end|>
name = params.get('name') client = hashivault_auth_client(params) result = client.get_role(name, mount_point=params.get('mount_point')) return {'role': result}
<|file_name|>hashivault_approle_role_get.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python from ansible.module_utils.hashivault import hashivault_argspec from ansible.module_utils.hashivault import hashivault_auth_client from ansible.module_utils.hashivault import hashivault_init from ansible.module_utils.hashivault import hashiwrapper ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'community', 'version': '1.1'} DOCUMENTATION = ''' --- module: hashivault_approle_role_get version_added: "3.8.0" short_description: Hashicorp Vault approle role get module description: - Module to get a approle role from Hashicorp Vault. options: name: description: - role name. mount_point: description: - mount point for role default: approle extends_documentation_fragment: hashivault ''' EXAMPLES = ''' --- - hosts: localhost tasks: - hashivault_approle_role_get: name: 'ashley' register: 'vault_approle_role_get' - debug: msg="Role is {{vault_approle_role_get.role}}" ''' def main(): argspec = hashivault_argspec() argspec['name'] = dict(required=True, type='str') argspec['mount_point'] = dict(required=False, type='str', default='approle') module = hashivault_init(argspec) result = hashivault_approle_role_get(module.params) if result.get('failed'): <|fim_middle|> else: module.exit_json(**result) @hashiwrapper def hashivault_approle_role_get(params): name = params.get('name') client = hashivault_auth_client(params) result = client.get_role(name, mount_point=params.get('mount_point')) return {'role': result} if __name__ == '__main__': main() <|fim▁end|>
module.fail_json(**result)
<|file_name|>hashivault_approle_role_get.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python from ansible.module_utils.hashivault import hashivault_argspec from ansible.module_utils.hashivault import hashivault_auth_client from ansible.module_utils.hashivault import hashivault_init from ansible.module_utils.hashivault import hashiwrapper ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'community', 'version': '1.1'} DOCUMENTATION = ''' --- module: hashivault_approle_role_get version_added: "3.8.0" short_description: Hashicorp Vault approle role get module description: - Module to get a approle role from Hashicorp Vault. options: name: description: - role name. mount_point: description: - mount point for role default: approle extends_documentation_fragment: hashivault ''' EXAMPLES = ''' --- - hosts: localhost tasks: - hashivault_approle_role_get: name: 'ashley' register: 'vault_approle_role_get' - debug: msg="Role is {{vault_approle_role_get.role}}" ''' def main(): argspec = hashivault_argspec() argspec['name'] = dict(required=True, type='str') argspec['mount_point'] = dict(required=False, type='str', default='approle') module = hashivault_init(argspec) result = hashivault_approle_role_get(module.params) if result.get('failed'): module.fail_json(**result) else: <|fim_middle|> @hashiwrapper def hashivault_approle_role_get(params): name = params.get('name') client = hashivault_auth_client(params) result = client.get_role(name, mount_point=params.get('mount_point')) return {'role': result} if __name__ == '__main__': main() <|fim▁end|>
module.exit_json(**result)
<|file_name|>hashivault_approle_role_get.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python from ansible.module_utils.hashivault import hashivault_argspec from ansible.module_utils.hashivault import hashivault_auth_client from ansible.module_utils.hashivault import hashivault_init from ansible.module_utils.hashivault import hashiwrapper ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'community', 'version': '1.1'} DOCUMENTATION = ''' --- module: hashivault_approle_role_get version_added: "3.8.0" short_description: Hashicorp Vault approle role get module description: - Module to get a approle role from Hashicorp Vault. options: name: description: - role name. mount_point: description: - mount point for role default: approle extends_documentation_fragment: hashivault ''' EXAMPLES = ''' --- - hosts: localhost tasks: - hashivault_approle_role_get: name: 'ashley' register: 'vault_approle_role_get' - debug: msg="Role is {{vault_approle_role_get.role}}" ''' def main(): argspec = hashivault_argspec() argspec['name'] = dict(required=True, type='str') argspec['mount_point'] = dict(required=False, type='str', default='approle') module = hashivault_init(argspec) result = hashivault_approle_role_get(module.params) if result.get('failed'): module.fail_json(**result) else: module.exit_json(**result) @hashiwrapper def hashivault_approle_role_get(params): name = params.get('name') client = hashivault_auth_client(params) result = client.get_role(name, mount_point=params.get('mount_point')) return {'role': result} if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
main()
<|file_name|>hashivault_approle_role_get.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python from ansible.module_utils.hashivault import hashivault_argspec from ansible.module_utils.hashivault import hashivault_auth_client from ansible.module_utils.hashivault import hashivault_init from ansible.module_utils.hashivault import hashiwrapper ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'community', 'version': '1.1'} DOCUMENTATION = ''' --- module: hashivault_approle_role_get version_added: "3.8.0" short_description: Hashicorp Vault approle role get module description: - Module to get a approle role from Hashicorp Vault. options: name: description: - role name. mount_point: description: - mount point for role default: approle extends_documentation_fragment: hashivault ''' EXAMPLES = ''' --- - hosts: localhost tasks: - hashivault_approle_role_get: name: 'ashley' register: 'vault_approle_role_get' - debug: msg="Role is {{vault_approle_role_get.role}}" ''' def <|fim_middle|>(): argspec = hashivault_argspec() argspec['name'] = dict(required=True, type='str') argspec['mount_point'] = dict(required=False, type='str', default='approle') module = hashivault_init(argspec) result = hashivault_approle_role_get(module.params) if result.get('failed'): module.fail_json(**result) else: module.exit_json(**result) @hashiwrapper def hashivault_approle_role_get(params): name = params.get('name') client = hashivault_auth_client(params) result = client.get_role(name, mount_point=params.get('mount_point')) return {'role': result} if __name__ == '__main__': main() <|fim▁end|>
main
<|file_name|>hashivault_approle_role_get.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python from ansible.module_utils.hashivault import hashivault_argspec from ansible.module_utils.hashivault import hashivault_auth_client from ansible.module_utils.hashivault import hashivault_init from ansible.module_utils.hashivault import hashiwrapper ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'community', 'version': '1.1'} DOCUMENTATION = ''' --- module: hashivault_approle_role_get version_added: "3.8.0" short_description: Hashicorp Vault approle role get module description: - Module to get a approle role from Hashicorp Vault. options: name: description: - role name. mount_point: description: - mount point for role default: approle extends_documentation_fragment: hashivault ''' EXAMPLES = ''' --- - hosts: localhost tasks: - hashivault_approle_role_get: name: 'ashley' register: 'vault_approle_role_get' - debug: msg="Role is {{vault_approle_role_get.role}}" ''' def main(): argspec = hashivault_argspec() argspec['name'] = dict(required=True, type='str') argspec['mount_point'] = dict(required=False, type='str', default='approle') module = hashivault_init(argspec) result = hashivault_approle_role_get(module.params) if result.get('failed'): module.fail_json(**result) else: module.exit_json(**result) @hashiwrapper def <|fim_middle|>(params): name = params.get('name') client = hashivault_auth_client(params) result = client.get_role(name, mount_point=params.get('mount_point')) return {'role': result} if __name__ == '__main__': main() <|fim▁end|>
hashivault_approle_role_get
<|file_name|>A_evolve_outer_star_to_giant.py<|end_file_name|><|fim▁begin|>import os import os.path from amuse.units import units from amuse.datamodel import Particle from amuse.ext.star_to_sph import pickle_stellar_model from amuse.community.mesa.interface import MESA as stellar_evolution_code from xiTau_parameters import triple_parameters def evolve_giant(giant, stop_radius): stellar_evolution = stellar_evolution_code() giant_in_code = stellar_evolution.particles.add_particle(giant) while (giant_in_code.radius < 0.7 | units.AU): giant_in_code.evolve_one_step() print "Giant starts to ascend the giant branch, now saving model every step..." print giant_in_code.as_set() i = 0 while (giant_in_code.radius < stop_radius): giant_in_code.evolve_one_step() print giant_in_code.radius, giant_in_code.age pickle_file_name = "./model_{0:=04}_".format(i) + "%0.1f"%(giant_in_code.radius.value_in(units.AU)) pickle_stellar_model(giant_in_code, pickle_file_name) i += 1 if __name__ == "__main__": model_directory = os.path.join("../../../../../BIGDATA/code/amuse-10.0", "giant_models") if not os.path.exists(model_directory): os.mkdir(model_directory)<|fim▁hole|> os.chdir(model_directory) giant = Particle(mass = triple_parameters["mass_out"]) print "\nEvolving with", stellar_evolution_code.__name__ evolve_giant(giant, 1.0 | units.AU) print "Done"<|fim▁end|>
<|file_name|>A_evolve_outer_star_to_giant.py<|end_file_name|><|fim▁begin|>import os import os.path from amuse.units import units from amuse.datamodel import Particle from amuse.ext.star_to_sph import pickle_stellar_model from amuse.community.mesa.interface import MESA as stellar_evolution_code from xiTau_parameters import triple_parameters def evolve_giant(giant, stop_radius): <|fim_middle|> if __name__ == "__main__": model_directory = os.path.join("../../../../../BIGDATA/code/amuse-10.0", "giant_models") if not os.path.exists(model_directory): os.mkdir(model_directory) os.chdir(model_directory) giant = Particle(mass = triple_parameters["mass_out"]) print "\nEvolving with", stellar_evolution_code.__name__ evolve_giant(giant, 1.0 | units.AU) print "Done" <|fim▁end|>
stellar_evolution = stellar_evolution_code() giant_in_code = stellar_evolution.particles.add_particle(giant) while (giant_in_code.radius < 0.7 | units.AU): giant_in_code.evolve_one_step() print "Giant starts to ascend the giant branch, now saving model every step..." print giant_in_code.as_set() i = 0 while (giant_in_code.radius < stop_radius): giant_in_code.evolve_one_step() print giant_in_code.radius, giant_in_code.age pickle_file_name = "./model_{0:=04}_".format(i) + "%0.1f"%(giant_in_code.radius.value_in(units.AU)) pickle_stellar_model(giant_in_code, pickle_file_name) i += 1
<|file_name|>A_evolve_outer_star_to_giant.py<|end_file_name|><|fim▁begin|>import os import os.path from amuse.units import units from amuse.datamodel import Particle from amuse.ext.star_to_sph import pickle_stellar_model from amuse.community.mesa.interface import MESA as stellar_evolution_code from xiTau_parameters import triple_parameters def evolve_giant(giant, stop_radius): stellar_evolution = stellar_evolution_code() giant_in_code = stellar_evolution.particles.add_particle(giant) while (giant_in_code.radius < 0.7 | units.AU): giant_in_code.evolve_one_step() print "Giant starts to ascend the giant branch, now saving model every step..." print giant_in_code.as_set() i = 0 while (giant_in_code.radius < stop_radius): giant_in_code.evolve_one_step() print giant_in_code.radius, giant_in_code.age pickle_file_name = "./model_{0:=04}_".format(i) + "%0.1f"%(giant_in_code.radius.value_in(units.AU)) pickle_stellar_model(giant_in_code, pickle_file_name) i += 1 if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
model_directory = os.path.join("../../../../../BIGDATA/code/amuse-10.0", "giant_models") if not os.path.exists(model_directory): os.mkdir(model_directory) os.chdir(model_directory) giant = Particle(mass = triple_parameters["mass_out"]) print "\nEvolving with", stellar_evolution_code.__name__ evolve_giant(giant, 1.0 | units.AU) print "Done"
<|file_name|>A_evolve_outer_star_to_giant.py<|end_file_name|><|fim▁begin|>import os import os.path from amuse.units import units from amuse.datamodel import Particle from amuse.ext.star_to_sph import pickle_stellar_model from amuse.community.mesa.interface import MESA as stellar_evolution_code from xiTau_parameters import triple_parameters def evolve_giant(giant, stop_radius): stellar_evolution = stellar_evolution_code() giant_in_code = stellar_evolution.particles.add_particle(giant) while (giant_in_code.radius < 0.7 | units.AU): giant_in_code.evolve_one_step() print "Giant starts to ascend the giant branch, now saving model every step..." print giant_in_code.as_set() i = 0 while (giant_in_code.radius < stop_radius): giant_in_code.evolve_one_step() print giant_in_code.radius, giant_in_code.age pickle_file_name = "./model_{0:=04}_".format(i) + "%0.1f"%(giant_in_code.radius.value_in(units.AU)) pickle_stellar_model(giant_in_code, pickle_file_name) i += 1 if __name__ == "__main__": model_directory = os.path.join("../../../../../BIGDATA/code/amuse-10.0", "giant_models") if not os.path.exists(model_directory): <|fim_middle|> os.chdir(model_directory) giant = Particle(mass = triple_parameters["mass_out"]) print "\nEvolving with", stellar_evolution_code.__name__ evolve_giant(giant, 1.0 | units.AU) print "Done" <|fim▁end|>
os.mkdir(model_directory)
<|file_name|>A_evolve_outer_star_to_giant.py<|end_file_name|><|fim▁begin|>import os import os.path from amuse.units import units from amuse.datamodel import Particle from amuse.ext.star_to_sph import pickle_stellar_model from amuse.community.mesa.interface import MESA as stellar_evolution_code from xiTau_parameters import triple_parameters def <|fim_middle|>(giant, stop_radius): stellar_evolution = stellar_evolution_code() giant_in_code = stellar_evolution.particles.add_particle(giant) while (giant_in_code.radius < 0.7 | units.AU): giant_in_code.evolve_one_step() print "Giant starts to ascend the giant branch, now saving model every step..." print giant_in_code.as_set() i = 0 while (giant_in_code.radius < stop_radius): giant_in_code.evolve_one_step() print giant_in_code.radius, giant_in_code.age pickle_file_name = "./model_{0:=04}_".format(i) + "%0.1f"%(giant_in_code.radius.value_in(units.AU)) pickle_stellar_model(giant_in_code, pickle_file_name) i += 1 if __name__ == "__main__": model_directory = os.path.join("../../../../../BIGDATA/code/amuse-10.0", "giant_models") if not os.path.exists(model_directory): os.mkdir(model_directory) os.chdir(model_directory) giant = Particle(mass = triple_parameters["mass_out"]) print "\nEvolving with", stellar_evolution_code.__name__ evolve_giant(giant, 1.0 | units.AU) print "Done" <|fim▁end|>
evolve_giant
<|file_name|>0063_auto_20210511_2343.py<|end_file_name|><|fim▁begin|># Generated by Django 3.2 on 2021-05-11 13:43 from django.db import migrations<|fim▁hole|> dependencies = [ ('stock', '0062_auto_20210511_2151'), ] operations = [ migrations.RemoveField( model_name='stockitemtracking', name='link', ), migrations.RemoveField( model_name='stockitemtracking', name='quantity', ), migrations.RemoveField( model_name='stockitemtracking', name='system', ), migrations.RemoveField( model_name='stockitemtracking', name='title', ), ]<|fim▁end|>
class Migration(migrations.Migration):
<|file_name|>0063_auto_20210511_2343.py<|end_file_name|><|fim▁begin|># Generated by Django 3.2 on 2021-05-11 13:43 from django.db import migrations class Migration(migrations.Migration): <|fim_middle|> <|fim▁end|>
dependencies = [ ('stock', '0062_auto_20210511_2151'), ] operations = [ migrations.RemoveField( model_name='stockitemtracking', name='link', ), migrations.RemoveField( model_name='stockitemtracking', name='quantity', ), migrations.RemoveField( model_name='stockitemtracking', name='system', ), migrations.RemoveField( model_name='stockitemtracking', name='title', ), ]
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """<|fim▁hole|> self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event)<|fim▁end|>
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): <|fim_middle|> class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
""" The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): <|fim_middle|> ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent)
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): <|fim_middle|> def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
""" Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): <|fim_middle|> def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
""" Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): <|fim_middle|> ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
""" Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor)
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): <|fim_middle|> def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
self._changed_path()
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): <|fim_middle|> ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width()
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): <|fim_middle|> def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
""" Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): <|fim_middle|> def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
""" Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): <|fim_middle|> class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
""" Called whenever a change is made to the text of the document. """ self.changed = True
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): <|fim_middle|> <|fim▁end|>
""" A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event)
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): <|fim_middle|> def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): <|fim_middle|> <|fim▁end|>
""" Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event)
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: <|fim_middle|> # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
path = self.path
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: <|fim_middle|> else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
f = open(self.path, 'r') text = f.read() f.close()
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: <|fim_middle|> self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
text = ''
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: <|fim_middle|> f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
path = self.path
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: <|fim_middle|> ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width()
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. <|fim_middle|> elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
self.__editor.control.emit(QtCore.SIGNAL('lostFocus'))
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. <|fim_middle|> return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event)
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def <|fim_middle|>(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
__init__
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def <|fim_middle|>(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
load
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def <|fim_middle|>(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
save
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def <|fim_middle|>(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
select_line
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def <|fim_middle|>(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
_path_changed
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def <|fim_middle|>(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
_show_line_numbers_changed
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def <|fim_middle|>(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
_create_control
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def <|fim_middle|>(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
_on_dirty_changed
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def <|fim_middle|>(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
_on_text_changed
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def <|fim_middle|>(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def eventFilter(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
__init__
<|file_name|>python_editor.py<|end_file_name|><|fim▁begin|>#------------------------------------------------------------------------------ # Copyright (c) 2007, Riverbank Computing Limited # All rights reserved. # # This software is provided without warranty under the terms of the BSD license. # However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply # # Author: Riverbank Computing Limited # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ # Standard library imports. import sys # Major package imports. from pyface.qt import QtCore, QtGui # Enthought library imports. from traits.api import Bool, Event, provides, Unicode # Local imports. from pyface.i_python_editor import IPythonEditor, MPythonEditor from pyface.key_pressed_event import KeyPressedEvent from pyface.widget import Widget from pyface.ui.qt4.code_editor.code_widget import AdvancedCodeWidget @provides(IPythonEditor) class PythonEditor(MPythonEditor, Widget): """ The toolkit specific implementation of a PythonEditor. See the IPythonEditor interface for the API documentation. """ #### 'IPythonEditor' interface ############################################ dirty = Bool(False) path = Unicode show_line_numbers = Bool(True) #### Events #### changed = Event key_pressed = Event(KeyPressedEvent) ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent, **traits): super(PythonEditor, self).__init__(**traits) self.control = self._create_control(parent) ########################################################################### # 'PythonEditor' interface. ########################################################################### def load(self, path=None): """ Loads the contents of the editor. """ if path is None: path = self.path # We will have no path for a new script. if len(path) > 0: f = open(self.path, 'r') text = f.read() f.close() else: text = '' self.control.code.setPlainText(text) self.dirty = False def save(self, path=None): """ Saves the contents of the editor. """ if path is None: path = self.path f = open(path, 'w') f.write(self.control.code.toPlainText()) f.close() self.dirty = False def select_line(self, lineno): """ Selects the specified line. """ self.control.code.set_line_column(lineno, 0) self.control.code.moveCursor(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor) ########################################################################### # Trait handlers. ########################################################################### def _path_changed(self): self._changed_path() def _show_line_numbers_changed(self): if self.control is not None: self.control.code.line_number_widget.setVisible( self.show_line_numbers) self.control.code.update_line_number_width() ########################################################################### # Private interface. ########################################################################### def _create_control(self, parent): """ Creates the toolkit-specific control for the widget. """ self.control = control = AdvancedCodeWidget(parent) self._show_line_numbers_changed() # Install event filter to trap key presses. event_filter = PythonEditorEventFilter(self, self.control) self.control.installEventFilter(event_filter) self.control.code.installEventFilter(event_filter) # Connect signals for text changes. control.code.modificationChanged.connect(self._on_dirty_changed) control.code.textChanged.connect(self._on_text_changed) # Load the editor's contents. self.load() return control def _on_dirty_changed(self, dirty): """ Called whenever a change is made to the dirty state of the document. """ self.dirty = dirty def _on_text_changed(self): """ Called whenever a change is made to the text of the document. """ self.changed = True class PythonEditorEventFilter(QtCore.QObject): """ A thin wrapper around the advanced code widget to handle the key_pressed Event. """ def __init__(self, editor, parent): super(PythonEditorEventFilter, self).__init__(parent) self.__editor = editor def <|fim_middle|>(self, obj, event): """ Reimplemented to trap key presses. """ if self.__editor.control and obj == self.__editor.control and \ event.type() == QtCore.QEvent.FocusOut: # Hack for Traits UI compatibility. self.__editor.control.emit(QtCore.SIGNAL('lostFocus')) elif self.__editor.control and obj == self.__editor.control.code and \ event.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = event.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = event.modifiers() self.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = event) return super(PythonEditorEventFilter, self).eventFilter(obj, event) <|fim▁end|>
eventFilter
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory Hacked together by / Copyright 2021 Ross Wightman """ import torch from functools import partial from .bottleneck_attn import BottleneckAttn from .cbam import CbamModule, LightCbamModule from .eca import EcaModule, CecaModule from .gather_excite import GatherExcite from .global_context import GlobalContext from .halo_attn import HaloAttn from .lambda_layer import LambdaLayer from .non_local_attn import NonLocalAttn, BatNonLocalAttn from .selective_kernel import SelectiveKernel from .split_attn import SplitAttn from .squeeze_excite import SEModule, EffectiveSEModule def get_attn(attn_type): if isinstance(attn_type, torch.nn.Module): return attn_type module_cls = None if attn_type is not None: if isinstance(attn_type, str): attn_type = attn_type.lower() # Lightweight attention modules (channel and/or coarse spatial). # Typically added to existing network architecture blocks in addition to existing convolutions. if attn_type == 'se': module_cls = SEModule elif attn_type == 'ese': module_cls = EffectiveSEModule elif attn_type == 'eca': module_cls = EcaModule elif attn_type == 'ecam': module_cls = partial(EcaModule, use_mlp=True) elif attn_type == 'ceca': module_cls = CecaModule elif attn_type == 'ge': module_cls = GatherExcite elif attn_type == 'gc': module_cls = GlobalContext elif attn_type == 'gca': module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False) elif attn_type == 'cbam': module_cls = CbamModule elif attn_type == 'lcbam': module_cls = LightCbamModule # Attention / attention-like modules w/ significant params # Typically replace some of the existing workhorse convs in a network architecture. # All of these accept a stride argument and can spatially downsample the input. elif attn_type == 'sk': module_cls = SelectiveKernel elif attn_type == 'splat': module_cls = SplitAttn # Self-attention / attention-like modules w/ significant compute and/or params # Typically replace some of the existing workhorse convs in a network architecture. # All of these accept a stride argument and can spatially downsample the input. elif attn_type == 'lambda': return LambdaLayer elif attn_type == 'bottleneck': return BottleneckAttn elif attn_type == 'halo':<|fim▁hole|> return HaloAttn elif attn_type == 'nl': module_cls = NonLocalAttn elif attn_type == 'bat': module_cls = BatNonLocalAttn # Woops! else: assert False, "Invalid attn module (%s)" % attn_type elif isinstance(attn_type, bool): if attn_type: module_cls = SEModule else: module_cls = attn_type return module_cls def create_attn(attn_type, channels, **kwargs): module_cls = get_attn(attn_type) if module_cls is not None: # NOTE: it's expected the first (positional) argument of all attention layers is the # input channels return module_cls(channels, **kwargs) return None<|fim▁end|>
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory Hacked together by / Copyright 2021 Ross Wightman """ import torch from functools import partial from .bottleneck_attn import BottleneckAttn from .cbam import CbamModule, LightCbamModule from .eca import EcaModule, CecaModule from .gather_excite import GatherExcite from .global_context import GlobalContext from .halo_attn import HaloAttn from .lambda_layer import LambdaLayer from .non_local_attn import NonLocalAttn, BatNonLocalAttn from .selective_kernel import SelectiveKernel from .split_attn import SplitAttn from .squeeze_excite import SEModule, EffectiveSEModule def get_attn(attn_type): <|fim_middle|> def create_attn(attn_type, channels, **kwargs): module_cls = get_attn(attn_type) if module_cls is not None: # NOTE: it's expected the first (positional) argument of all attention layers is the # input channels return module_cls(channels, **kwargs) return None <|fim▁end|>
if isinstance(attn_type, torch.nn.Module): return attn_type module_cls = None if attn_type is not None: if isinstance(attn_type, str): attn_type = attn_type.lower() # Lightweight attention modules (channel and/or coarse spatial). # Typically added to existing network architecture blocks in addition to existing convolutions. if attn_type == 'se': module_cls = SEModule elif attn_type == 'ese': module_cls = EffectiveSEModule elif attn_type == 'eca': module_cls = EcaModule elif attn_type == 'ecam': module_cls = partial(EcaModule, use_mlp=True) elif attn_type == 'ceca': module_cls = CecaModule elif attn_type == 'ge': module_cls = GatherExcite elif attn_type == 'gc': module_cls = GlobalContext elif attn_type == 'gca': module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False) elif attn_type == 'cbam': module_cls = CbamModule elif attn_type == 'lcbam': module_cls = LightCbamModule # Attention / attention-like modules w/ significant params # Typically replace some of the existing workhorse convs in a network architecture. # All of these accept a stride argument and can spatially downsample the input. elif attn_type == 'sk': module_cls = SelectiveKernel elif attn_type == 'splat': module_cls = SplitAttn # Self-attention / attention-like modules w/ significant compute and/or params # Typically replace some of the existing workhorse convs in a network architecture. # All of these accept a stride argument and can spatially downsample the input. elif attn_type == 'lambda': return LambdaLayer elif attn_type == 'bottleneck': return BottleneckAttn elif attn_type == 'halo': return HaloAttn elif attn_type == 'nl': module_cls = NonLocalAttn elif attn_type == 'bat': module_cls = BatNonLocalAttn # Woops! else: assert False, "Invalid attn module (%s)" % attn_type elif isinstance(attn_type, bool): if attn_type: module_cls = SEModule else: module_cls = attn_type return module_cls
<|file_name|>create_attn.py<|end_file_name|><|fim▁begin|>""" Attention Factory Hacked together by / Copyright 2021 Ross Wightman """ import torch from functools import partial from .bottleneck_attn import BottleneckAttn from .cbam import CbamModule, LightCbamModule from .eca import EcaModule, CecaModule from .gather_excite import GatherExcite from .global_context import GlobalContext from .halo_attn import HaloAttn from .lambda_layer import LambdaLayer from .non_local_attn import NonLocalAttn, BatNonLocalAttn from .selective_kernel import SelectiveKernel from .split_attn import SplitAttn from .squeeze_excite import SEModule, EffectiveSEModule def get_attn(attn_type): if isinstance(attn_type, torch.nn.Module): return attn_type module_cls = None if attn_type is not None: if isinstance(attn_type, str): attn_type = attn_type.lower() # Lightweight attention modules (channel and/or coarse spatial). # Typically added to existing network architecture blocks in addition to existing convolutions. if attn_type == 'se': module_cls = SEModule elif attn_type == 'ese': module_cls = EffectiveSEModule elif attn_type == 'eca': module_cls = EcaModule elif attn_type == 'ecam': module_cls = partial(EcaModule, use_mlp=True) elif attn_type == 'ceca': module_cls = CecaModule elif attn_type == 'ge': module_cls = GatherExcite elif attn_type == 'gc': module_cls = GlobalContext elif attn_type == 'gca': module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False) elif attn_type == 'cbam': module_cls = CbamModule elif attn_type == 'lcbam': module_cls = LightCbamModule # Attention / attention-like modules w/ significant params # Typically replace some of the existing workhorse convs in a network architecture. # All of these accept a stride argument and can spatially downsample the input. elif attn_type == 'sk': module_cls = SelectiveKernel elif attn_type == 'splat': module_cls = SplitAttn # Self-attention / attention-like modules w/ significant compute and/or params # Typically replace some of the existing workhorse convs in a network architecture. # All of these accept a stride argument and can spatially downsample the input. elif attn_type == 'lambda': return LambdaLayer elif attn_type == 'bottleneck': return BottleneckAttn elif attn_type == 'halo': return HaloAttn elif attn_type == 'nl': module_cls = NonLocalAttn elif attn_type == 'bat': module_cls = BatNonLocalAttn # Woops! else: assert False, "Invalid attn module (%s)" % attn_type elif isinstance(attn_type, bool): if attn_type: module_cls = SEModule else: module_cls = attn_type return module_cls def create_attn(attn_type, channels, **kwargs): <|fim_middle|> <|fim▁end|>
module_cls = get_attn(attn_type) if module_cls is not None: # NOTE: it's expected the first (positional) argument of all attention layers is the # input channels return module_cls(channels, **kwargs) return None