Python ee.EEException() Examples

The following are 30 code examples of ee.EEException(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ee , or try the search function .
Example #1
Source File: geometry_test.py    From earthengine with MIT License 6 votes vote down vote up
def assertInvalid(self, ctor, msg, *coords):
    """Verifies that geometry is invalid.

    Calls the given constructor with whatever arguments have been passed,
    and verifies that the given error message is thrown.

    Args:
      ctor: The geometry constructor function, e.g. ee.Geometry.MultiPoint.
      msg: The expected error message in the thrown exception.
      *coords: The coordinates of the geometry.
    """
    try:
      ctor(*coords)
    except ee.EEException as e:
      self.assertTrue(msg in str(e))
    else:
      self.fail('Expected an exception.') 
Example #2
Source File: commands.py    From aqua-monitor with GNU Lesser General Public License v3.0 6 votes vote down vote up
def run(self, args, config):
    config.ee_init()
    cancel_all = args.task_ids == ['all']
    if cancel_all:
      statuses = ee.data.getTaskList()
    else:
      statuses = ee.data.getTaskStatus(args.task_ids)
    for status in statuses:
      state = status['state']
      task_id = status['id']
      if state == 'UNKNOWN':
        raise ee.EEException('Unknown task id "%s"' % task_id)
      elif state == 'READY' or state == 'RUNNING':
        print('Canceling task "%s"' % task_id)
        ee.data.cancelTask(task_id)
      elif not cancel_all:
        print('Task "%s" already in state "%s".' % (status['id'], state)) 
Example #3
Source File: commands.py    From aqua-monitor with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _delete_asset(self, asset_id, recursive, verbose, dry_run):
    """Attempts to delete the specified asset or asset collection."""
    info = ee.data.getInfo(asset_id)
    if info is None:
      print('Asset does not exist or is not accessible: %s' % asset_id)
      return
    if recursive:
      if info['type'] in (ee.data.ASSET_TYPE_FOLDER,
                          ee.data.ASSET_TYPE_IMAGE_COLL):
        children = ee.data.getList({'id': asset_id})
        for child in children:
          self._delete_asset(child['id'], True, verbose, dry_run)
    if dry_run:
      print('[dry-run] Deleting asset: %s' % asset_id)
    else:
      if verbose:
        print('Deleting asset: %s' % asset_id)
      try:
        ee.data.deleteAsset(asset_id)
      except ee.EEException as e:
        print('Failed to delete %s. %s' % (asset_id, e)) 
Example #4
Source File: geometry_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 6 votes vote down vote up
def assertInvalid(self, ctor, msg, *coords):
    """Verifies that geometry is invalid.

    Calls the given constructor with whatever arguments have been passed,
    and verifies that the given error message is thrown.

    Args:
      ctor: The geometry constructor function, e.g. ee.Geometry.MultiPoint.
      msg: The expected error message in the thrown exception.
      *coords: The coordinates of the geometry.
    """
    try:
      ctor(*coords)
    except ee.EEException as e:
      self.assertTrue(msg in str(e))
    else:
      self.fail('Expected an exception.') 
Example #5
Source File: commands.py    From earthengine with MIT License 6 votes vote down vote up
def run(self, args, config):
    config.ee_init()
    cancel_all = args.task_ids == ['all']
    if cancel_all:
      statuses = ee.data.getTaskList()
    else:
      statuses = ee.data.getTaskStatus(args.task_ids)
    for status in statuses:
      state = status['state']
      task_id = status['id']
      if state == 'UNKNOWN':
        raise ee.EEException('Unknown task id "%s"' % task_id)
      elif state == 'READY' or state == 'RUNNING':
        print('Canceling task "%s"' % task_id)
        ee.data.cancelTask(task_id)
      elif not cancel_all:
        print('Task "%s" already in state "%s".' % (status['id'], state)) 
Example #6
Source File: commands.py    From earthengine with MIT License 6 votes vote down vote up
def _delete_asset(self, asset_id, recursive, verbose, dry_run):
    """Attempts to delete the specified asset or asset collection."""
    info = ee.data.getInfo(asset_id)
    if info is None:
      print('Asset does not exist or is not accessible: %s' % asset_id)
      return
    if recursive:
      if info['type'] in (ee.data.ASSET_TYPE_FOLDER,
                          ee.data.ASSET_TYPE_IMAGE_COLL):
        children = ee.data.getList({'id': asset_id})
        for child in children:
          self._delete_asset(child['id'], True, verbose, dry_run)
    if dry_run:
      print('[dry-run] Deleting asset: %s' % asset_id)
    else:
      if verbose:
        print('Deleting asset: %s' % asset_id)
      try:
        ee.data.deleteAsset(asset_id)
      except ee.EEException as e:
        print('Failed to delete %s. %s' % (asset_id, e)) 
Example #7
Source File: commands.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _decode_property_flags(args):
  """Decodes metadata properties from args as a list of (name,value) pairs."""
  property_list = list(args.property or [])
  if args.time_start:
    property_list.append((SYSTEM_TIME_START, args.time_start))
  if args.time_end:
    property_list.append((SYSTEM_TIME_END, args.time_end))
  names = [name for name, _ in property_list]
  duplicates = [name for name, count in Counter(names).items() if count > 1]
  if duplicates:
    raise ee.EEException('Duplicate property name(s): %s.' % duplicates)
  return dict(property_list) 
Example #8
Source File: oauth.py    From gee_tools with MIT License 5 votes vote down vote up
def Initialize(filename, credential_path='default'):
    """
    Authenticate to GEE with the specified credentials

    If credential_path is set to 'defualt', it searches for the 'filename' in
    the same folder in which credentials are stored locally
    """
    if credential_path == 'default':
        credential_path = os.path.split(ee.oauth.get_credentials_path())[0]

    path = os.path.join(credential_path, filename)

    def get_credentials():
        try:
            tokens = json.load(open(path))
            refresh_token = tokens['refresh_token']
            return Credentials(
                None,
                refresh_token=refresh_token,
                token_uri=ee.oauth.TOKEN_URI,
                client_id=ee.oauth.CLIENT_ID,
                client_secret=ee.oauth.CLIENT_SECRET,
                scopes=ee.oauth.SCOPES)
        except IOError:
            raise ee.EEException(
                'Please authorize access to your Earth Engine account by '
                'running\n\nearthengine authenticate\n\nin your command line, and then '
                'retry.')

    credentials = get_credentials()
    ee.Initialize(credentials) 
Example #9
Source File: exporting.py    From pycrop-yield-prediction with MIT License 5 votes vote down vote up
def __init__(self, locations_filepath=Path('data/yield_data.csv'),
                 collection_id='MODIS/051/MCD12Q1'):
        self.locations = load(locations_filepath)

        self.collection_id = collection_id

        try:
            ee.Initialize()
            print('The Earth Engine package initialized successfully!')
        except ee.EEException:
            print('The Earth Engine package failed to initialize! '
                  'Have you authenticated the earth engine?') 
Example #10
Source File: batch_uploader.py    From geeup with Apache License 2.0 5 votes vote down vote up
def retry_if_ee_error(exception):
    return isinstance(exception, ee.EEException) 
Example #11
Source File: metadata_ingest.py    From Planet-GEE-Pipeline-CLI with Apache License 2.0 5 votes vote down vote up
def retry_if_ee_error(exception):
    return isinstance(exception, ee.EEException) 
Example #12
Source File: eecli.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
  # Set the program name to 'earthengine' for proper help text display.
  parser = argparse.ArgumentParser(
      prog='earthengine', description='Earth Engine Command Line Interface.')
  parser.add_argument(
      '--ee_config', help='Path to the earthengine configuration file. '
      'Defaults to "~/%s".' % utils.DEFAULT_EE_CONFIG_FILE_RELATIVE)

  dispatcher = CommandDispatcher(parser)

  # Print the list of commands if the user supplied no arguments at all.
  if len(sys.argv) == 1:
    parser.print_help()
    return

  args = parser.parse_args()
  config = utils.CommandLineConfig(args.ee_config)

  # Catch EEException errors, which wrap server-side Earth Engine
  # errors, and print the error message without the irrelevant local
  # stack trace. (Individual commands may also catch EEException if
  # they want to be able to continue despite errors.)
  try:
    dispatcher.run(args, config)
  except ee.EEException as e:
    print(e)
    sys.exit(1) 
Example #13
Source File: map.py    From ipygee with MIT License 5 votes vote down vote up
def addImageCollection(self, collection, visParams=None,
                           namePattern='{id}', show=False, opacity=None,
                           datePattern='yyyyMMdd', replace=True,
                           verbose=False):
        """ Add every Image of an ImageCollection to the Map

        :param collection: the ImageCollection
        :type collection: ee.ImageCollection
        :param visParams: visualization parameter for each image. See `addImage`
        :type visParams: dict
        :param namePattern: the name pattern (uses geetools.utils.makeName)
        :type namePattern: str
        :param show: If True, adds and shows the Image, otherwise only add it
        :type show: bool
        """
        size = collection.size()
        collist = collection.toList(size)
        n = 0
        while True:
            try:
                img = ee.Image(collist.get(n))
                extra = dict(position=n)
                name = utils.makeName(img, namePattern, datePattern, extra=extra)
                self.addLayer(img, visParams, name.getInfo(), show, opacity,
                              replace=replace)
                if verbose:
                    print('Adding {} to the Map'.format(name))
                n += 1
            except ee.EEException as e:
                msg = 'List.get: List index must be between'
                if msg not in str(e):
                    raise e
                break 
Example #14
Source File: function_test.py    From earthengine with MIT License 5 votes vote down vote up
def assertRaisesWithRegexpMatch(self, msg, func, *args):
    try:
      func(*args)
    except ee.EEException as e:
      self.assertTrue(msg in str(e))
    else:
      self.fail('Expected an exception.') 
Example #15
Source File: commands.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _list_asset_content(self, asset, max_items, total_assets, long_format):
    try:
      list_req = {'id': asset}
      if max_items >= 0:
        list_req['num'] = max_items
      children = ee.data.getList(list_req)
      indent = ''
      if total_assets > 1:
        print('%s:' % asset)
        indent = '  '
      self._print_assets(children, indent, long_format)
    except ee.EEException as e:
      print(e) 
Example #16
Source File: commands.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def run(self, args, config):
    properties = _decode_property_flags(args)
    config.ee_init()
    if not properties:
      raise ee.EEException('No properties specified.')
    ee.data.setAssetProperties(args.asset_id, properties) 
Example #17
Source File: commands.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def run(self, args, config):
    config.ee_init()
    info = ee.data.getInfo(args.asset_id)
    if info:
      _pretty_print_json(info)
    else:
      raise ee.EEException(
          'Asset does not exist or is not accessible: %s' % args.asset_id) 
Example #18
Source File: commands.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _check_valid_files(filenames):
  """Returns true if the given filenames are valid upload file URIs."""
  for filename in filenames:
    if not filename.startswith('gs://'):
      raise ee.EEException('Invalid Cloud Storage URL: ' + filename) 
Example #19
Source File: commands.py    From earthengine with MIT License 5 votes vote down vote up
def run(self, args, config):
    config.ee_init()
    info = ee.data.getInfo(args.asset_id)
    if info:
      _pretty_print_json(info)
    else:
      raise ee.EEException(
          'Asset does not exist or is not accessible: %s' % args.asset_id) 
Example #20
Source File: commands.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _upload(args, request, ingestion_function):
  if 0 <= args.wait < 10:
    raise ee.EEException('Wait time should be at least 10 seconds.')
  task_id = ee.data.newTaskId()[0]
  ingestion_function(task_id, request)
  print('Started upload task with ID: %s' % task_id)
  if args.wait >= 0:
    print('Waiting for the upload task to complete...')
    utils.wait_for_task(task_id, args.wait)


# Argument types 
Example #21
Source File: function_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def assertRaisesWithRegexpMatch(self, msg, func, *args):
    try:
      func(*args)
    except ee.EEException as e:
      self.assertTrue(msg in str(e))
    else:
      self.fail('Expected an exception.') 
Example #22
Source File: commands.py    From earthengine with MIT License 5 votes vote down vote up
def _upload(args, request, ingestion_function):
  if 0 <= args.wait < 10:
    raise ee.EEException('Wait time should be at least 10 seconds.')
  task_id = ee.data.newTaskId()[0]
  ingestion_function(task_id, request)
  print('Started upload task with ID: %s' % task_id)
  if args.wait >= 0:
    print('Waiting for the upload task to complete...')
    utils.wait_for_task(task_id, args.wait)


# Argument types 
Example #23
Source File: batch_copy.py    From gee_asset_manager with Apache License 2.0 5 votes vote down vote up
def copy(source, destination):
    with open(source, 'r') as f:
        reader = csv.reader(f)
        for line in reader:
            name = line[0]
            gme_id = line[1]
            gme_path = 'GME/images/' + gme_id
            ee_path = os.path.join(destination, name)
            logging.info('Copying asset %s to %s', gme_path, ee_path)
            try:
                ee.data.copyAsset(gme_path, ee_path)
            except ee.EEException as e:
                with open('failed_batch_copy.csv', 'w') as fout:
                    fout.write('{},{},{},{}'.format(name, gme_id, ee_path,e)) 
Example #24
Source File: batch_info.py    From gee_asset_manager with Apache License 2.0 5 votes vote down vote up
def _get_size(asset):
    """Returns the size of the given asset in bytes."""
    size_parsers = {
        'Folder': _get_size_folder,
        'ImageCollection': _get_size_image_collection,
    }

    if asset['type'] not in size_parsers:
        raise ee.EEException(
            'Cannot get size for asset type "%s"' % asset['type'])

    return size_parsers[asset['type']](asset) 
Example #25
Source File: batch_uploader.py    From gee_asset_manager with Apache License 2.0 5 votes vote down vote up
def retry_if_ee_error(exception):
    return isinstance(exception, ee.EEException) 
Example #26
Source File: eecli.py    From earthengine with MIT License 5 votes vote down vote up
def main():
  # Set the program name to 'earthengine' for proper help text display.
  parser = argparse.ArgumentParser(
      prog='earthengine', description='Earth Engine Command Line Interface.')
  parser.add_argument(
      '--ee_config', help='Path to the earthengine configuration file. '
      'Defaults to "~/%s".' % utils.DEFAULT_EE_CONFIG_FILE_RELATIVE)

  dispatcher = CommandDispatcher(parser)

  # Print the list of commands if the user supplied no arguments at all.
  if len(sys.argv) == 1:
    parser.print_help()
    return

  args = parser.parse_args()
  config = utils.CommandLineConfig(args.ee_config)

  # Catch EEException errors, which wrap server-side Earth Engine
  # errors, and print the error message without the irrelevant local
  # stack trace. (Individual commands may also catch EEException if
  # they want to be able to continue despite errors.)
  try:
    dispatcher.run(args, config)
  except ee.EEException as e:
    print(e)
    sys.exit(1) 
Example #27
Source File: commands.py    From earthengine with MIT License 5 votes vote down vote up
def _decode_property_flags(args):
  """Decodes metadata properties from args as a list of (name,value) pairs."""
  property_list = list(args.property or [])
  if args.time_start:
    property_list.append((SYSTEM_TIME_START, args.time_start))
  if args.time_end:
    property_list.append((SYSTEM_TIME_END, args.time_end))
  names = [name for name, _ in property_list]
  duplicates = [name for name, count in Counter(names).items() if count > 1]
  if duplicates:
    raise ee.EEException('Duplicate property name(s): %s.' % duplicates)
  return dict(property_list) 
Example #28
Source File: commands.py    From earthengine with MIT License 5 votes vote down vote up
def _check_valid_files(filenames):
  """Returns true if the given filenames are valid upload file URIs."""
  for filename in filenames:
    if not filename.startswith('gs://'):
      raise ee.EEException('Invalid Cloud Storage URL: ' + filename) 
Example #29
Source File: commands.py    From earthengine with MIT License 5 votes vote down vote up
def _list_asset_content(self, asset, max_items, total_assets, long_format):
    try:
      list_req = {'id': asset}
      if max_items >= 0:
        list_req['num'] = max_items
      children = ee.data.getList(list_req)
      indent = ''
      if total_assets > 1:
        print('%s:' % asset)
        indent = '  '
      self._print_assets(children, indent, long_format)
    except ee.EEException as e:
      print(e) 
Example #30
Source File: commands.py    From earthengine with MIT License 5 votes vote down vote up
def run(self, args, config):
    properties = _decode_property_flags(args)
    config.ee_init()
    if not properties:
      raise ee.EEException('No properties specified.')
    ee.data.setAssetProperties(args.asset_id, properties)