Variable & Instance

Variable

Bases: _ProxyVariable

from geocube import Client client = Client('127.0.0.1:8080') vs = client.list_variables("test") for v in vs: ... v.delete() profile = {'dformat': ('f8', -1, 0, 1), 'bands': ['R', 'G', 'B']} v = client.create_variable('test/vegetation/NDVI', **profile) v2 = client.variable('test/vegetation/NDVI') v.id==v2.id True vi = v.instance('master') v.description = "normalize difference vegetation index " vi.instance_metadata = {'version': 'v1'} vi2 = client.variable('test/vegetation/NDVI').instance('master') vi.id == vi2.id True

Source code in geocube/entities/variable.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
class Variable(_ProxyVariable):
    """
    >>> from geocube import Client
    >>> client = Client('127.0.0.1:8080')
    >>> vs = client.list_variables("test")
    >>> for v in vs:
    ...    v.delete()
    >>> profile = {'dformat': ('f8', -1, 0, 1), \
                   'bands': ['R', 'G', 'B']}
    >>> v = client.create_variable('test/vegetation/NDVI', **profile)
    >>> v2 = client.variable('test/vegetation/NDVI')
    >>> v.id==v2.id
    True
    >>> vi = v.instance('master')
    >>> v.description = "normalize difference vegetation index "
    >>> vi.instance_metadata = {'version': 'v1'}
    >>> vi2 = client.variable('test/vegetation/NDVI').instance('master')
    >>> vi.id == vi2.id
    True
    """
    @classmethod
    def from_pb(cls, stub: Stub, pb: variables_pb2.Variable):
        return cls(_BaseVariable(
            stub=stub,
            id=pb.id,
            name=pb.name,
            unit=pb.unit,
            description=pb.description,
            dformat=entities.DataFormat.from_pb(pb.dformat),
            bands=[b for b in pb.bands],
            palette=pb.palette,
            resampling_alg=entities.pb_resampling[pb.resampling_alg],
        ), {pbi.name: Instance.from_pb(pbi) for pbi in pb.instances})

    def __init__(self, base_variable, instances=None):
        super().__init__(base_variable)
        self.instances = instances if instances is not None else {}

    @property
    def id(self) -> str:
        return self.variable_id

    @property
    def name(self) -> str:
        return self.variable_name

    @utils.catch_rpc_error
    def instance(self, name: Union[None, str] = None) -> VariableInstance:
        """ Load the given instance

        Args:
            name: of the instance (or if None: the default instance if exists)

        Returns:
            Specialization of the variable
        """
        if name is None:
            if len(self.instances) != 1:
                raise utils.GeocubeError("instance", grpc.StatusCode.NOT_FOUND.name,
                                         f"Default instance does not exist for variable {self.variable_name}"
                                         f" (or more than one instance is defined).")
            return VariableInstance(self, next(iter(self.instances.values())))

        if name not in self.instances:
            raise utils.GeocubeError("instance", grpc.StatusCode.NOT_FOUND.name,
                                     f"Instance {name} does not exist for variable {self.variable_name}. "
                                     f"To instantiate a variable, use instantiate()")

        return VariableInstance(self, self.instances[name])

    @utils.catch_rpc_error
    def instantiate(self, name: str, metadata: Dict[str, str]) -> VariableInstance:
        """
        Instantiate the variable (create a specialization)
        Args:
            name: of the instance
            metadata: of the instance (e.g. processing parameters, version...) can be empty

        Returns:
            The specialization of this variable
        """
        if name in self.instances:
            if metadata is not None and self.instances[name].metadata != metadata:
                raise utils.GeocubeError("instantiate", "ALREADY EXISTS",
                                         "Use instance({}).add_metadata(key, value) and del_metadata(key) "
                                         "to update the metadata".format(name))
        else:
            req = variables_pb2.InstantiateVariableRequest(
                variable_id=self.id, instance_name=name, instance_metadata=metadata)
            self.instances[name] = Instance.from_pb(self.client.InstantiateVariable(req).instance)

        return VariableInstance(self, self.instances[name])

    @utils.catch_rpc_error
    def delete_instances(self, pattern=''):
        """ delete empty instances whose name match pattern (only * and ? are supported) """
        pattern = re.escape(pattern).replace("\*", ".*").replace("\?", ".")
        for instance in self.instances.values():
            if re.match(pattern, instance.name):
                req = variables_pb2.DeleteInstanceRequest(id=instance.id)
                self.client.DeleteInstance(req)

    @utils.catch_rpc_error
    def delete(self):
        self.delete_instances('')
        req = variables_pb2.DeleteVariableRequest(id=self.id)
        self.client.DeleteVariable(req)

    def config_consolidation(self, dformat: entities.DataFormat, exponent=1.,
                             compression: entities.Compression = entities.Compression.LOSSLESS,
                             creation_params: Dict[str, str] = None,
                             resampling_alg: entities.Resampling = entities.Resampling.near):
        """ See entities.ConsolidationParams """
        self.consolidation_params = entities.ConsolidationParams(
            dformat=entities.DataFormat.from_user(dformat), exponent=exponent,
            compression=compression, creation_params={} if creation_params is None else creation_params,
            resampling_alg=resampling_alg)

    def __str__(self):
        return "{}\n" \
               "Instances: {}\n"\
            .format(_ProxyVariable.__str__(self), self.instances)

config_consolidation(dformat, exponent=1.0, compression=entities.Compression.LOSSLESS, creation_params=None, resampling_alg=entities.Resampling.near)

See entities.ConsolidationParams

Source code in geocube/entities/variable.py
302
303
304
305
306
307
308
309
310
def config_consolidation(self, dformat: entities.DataFormat, exponent=1.,
                         compression: entities.Compression = entities.Compression.LOSSLESS,
                         creation_params: Dict[str, str] = None,
                         resampling_alg: entities.Resampling = entities.Resampling.near):
    """ See entities.ConsolidationParams """
    self.consolidation_params = entities.ConsolidationParams(
        dformat=entities.DataFormat.from_user(dformat), exponent=exponent,
        compression=compression, creation_params={} if creation_params is None else creation_params,
        resampling_alg=resampling_alg)

delete_instances(pattern='')

delete empty instances whose name match pattern (only * and ? are supported)

Source code in geocube/entities/variable.py
287
288
289
290
291
292
293
294
@utils.catch_rpc_error
def delete_instances(self, pattern=''):
    """ delete empty instances whose name match pattern (only * and ? are supported) """
    pattern = re.escape(pattern).replace("\*", ".*").replace("\?", ".")
    for instance in self.instances.values():
        if re.match(pattern, instance.name):
            req = variables_pb2.DeleteInstanceRequest(id=instance.id)
            self.client.DeleteInstance(req)

instance(name=None)

Load the given instance

Parameters:
  • name (Union[None, str], default: None ) –

    of the instance (or if None: the default instance if exists)

Returns:
Source code in geocube/entities/variable.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
@utils.catch_rpc_error
def instance(self, name: Union[None, str] = None) -> VariableInstance:
    """ Load the given instance

    Args:
        name: of the instance (or if None: the default instance if exists)

    Returns:
        Specialization of the variable
    """
    if name is None:
        if len(self.instances) != 1:
            raise utils.GeocubeError("instance", grpc.StatusCode.NOT_FOUND.name,
                                     f"Default instance does not exist for variable {self.variable_name}"
                                     f" (or more than one instance is defined).")
        return VariableInstance(self, next(iter(self.instances.values())))

    if name not in self.instances:
        raise utils.GeocubeError("instance", grpc.StatusCode.NOT_FOUND.name,
                                 f"Instance {name} does not exist for variable {self.variable_name}. "
                                 f"To instantiate a variable, use instantiate()")

    return VariableInstance(self, self.instances[name])

instantiate(name, metadata)

Instantiate the variable (create a specialization) Args: name: of the instance metadata: of the instance (e.g. processing parameters, version...) can be empty

Returns:
Source code in geocube/entities/variable.py
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
@utils.catch_rpc_error
def instantiate(self, name: str, metadata: Dict[str, str]) -> VariableInstance:
    """
    Instantiate the variable (create a specialization)
    Args:
        name: of the instance
        metadata: of the instance (e.g. processing parameters, version...) can be empty

    Returns:
        The specialization of this variable
    """
    if name in self.instances:
        if metadata is not None and self.instances[name].metadata != metadata:
            raise utils.GeocubeError("instantiate", "ALREADY EXISTS",
                                     "Use instance({}).add_metadata(key, value) and del_metadata(key) "
                                     "to update the metadata".format(name))
    else:
        req = variables_pb2.InstantiateVariableRequest(
            variable_id=self.id, instance_name=name, instance_metadata=metadata)
        self.instances[name] = Instance.from_pb(self.client.InstantiateVariable(req).instance)

    return VariableInstance(self, self.instances[name])

Instance

Bases: _ProxyVariable, Instance

VariableInstance is an instantiation of a Variable.

It inherits from Variable (except for id() and name() that are replaced by variable_id() and variable_name() to prevent confusion with id and name of the instance) and from Instance (except for id() and name() that are replaced by instance_id() and instance_name())

Source code in geocube/entities/variable.py
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
class VariableInstance(_ProxyVariable, Instance):
    """ VariableInstance is an instantiation of a Variable.

    It inherits from Variable (except for id() and name() that are replaced by variable_id() and variable_name()
    to prevent confusion with id and name of the instance) and from Instance (except for id() and name() that are
    replaced by instance_id() and instance_name())
    """
    def __init__(self, variable: Variable,
                 instance: Instance):
        _ProxyVariable.__init__(self, variable._variable)
        self._instance = instance

    @property
    def instance_id(self) -> str:
        return self._instance.id

    @property
    def instance_name(self) -> str:
        return self._instance.name

    @property
    def metadata(self) -> Dict[str, str]:
        return self._instance.metadata

    @instance_name.setter
    @utils.catch_rpc_error
    def instance_name(self, name):
        if self.instance_name != name:
            req = variables_pb2.UpdateInstanceRequest(id=self.instance_id, name=utils.pb_string(name))
            self.client.UpdateInstance(req)
            self._instance.name = name

    @utils.catch_rpc_error
    def add_metadata(self, key: str, value: str):
        if key not in self.metadata or self.metadata[key] != value:
            req = variables_pb2.UpdateInstanceRequest(id=self.instance_id, add_metadata={key: value})
            self.client.UpdateInstance(req)
            self._instance.metadata[key] = value

    @utils.catch_rpc_error
    def del_metadata(self, key: str):
        if key in self.metadata:
            req = variables_pb2.UpdateInstanceRequest(id=self.instance_id, del_metadata_keys=[key])
            self.client.UpdateInstance(req)
            del self._instance.metadata[key]
        else:
            raise ValueError(f"{self.__repr__()}: {key} does not exist in metadata")

    def __repr__(self):
        return "VariableInstance {}:{} ({})".format(self.variable_name, self.instance_name, self.instance_id)

    def __str__(self):
        return "{}  {}".format(_ProxyVariable.__str__(self), self._instance.__str__())