Skip to content

Commit bb37511

Browse files
committed
refactor: fix all the mypy and linting issues
1 parent 9bb3d8d commit bb37511

16 files changed

Lines changed: 65 additions & 152 deletions

geetools/_deprecated_algorithms.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,7 @@ def distanceToMask(
1919
normalize=False,
2020
):
2121
"""Compute the distance to the mask in meters."""
22-
return (
23-
ee.Image(image)
24-
.geetools.distanceToMask(mask, radius=radius, band_name=band_name)
25-
.select(band_name)
26-
)
22+
return ee.Image(image).geetools.distanceToMask(mask, radius=radius, band_name=band_name).select(band_name)
2723

2824

2925
@deprecated(version="1.5.0", reason="Use ee.Image.geetools.maskCover instead.")

geetools/_deprecated_composite.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,7 @@ def compositeRegularIntervals(
4444

4545

4646
@deprecated(version="1.5.0", reason="Use ee.ImageCollection.geetools.reduceInterval instead")
47-
def compositeByMonth(
48-
collection, composite_function=None, composite_args=None, composite_kwargs=None
49-
):
47+
def compositeByMonth(collection, composite_function=None, composite_args=None, composite_kwargs=None):
5048
"""Make a composite at regular intervals parsing a composite."""
5149
return ee.ImageCollection(collection).geetools.reduceInterval(unit="month")
5250

geetools/ee_asset.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -463,9 +463,7 @@ def iterdir(self, recursive: bool = False) -> list:
463463
"""
464464
# sanity check on variables
465465
if not (self.is_project() or self.is_folder() or self.is_image_collection()):
466-
raise ValueError(
467-
f"Asset {self.as_posix()} is not a container and cannot contain other assets."
468-
)
466+
raise ValueError(f"Asset {self.as_posix()} is not a container and cannot contain other assets.")
469467

470468
# no need for recursion if recursive is false we directly return the result of th API call
471469
if recursive is False:

geetools/ee_dictionary.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,7 @@ def getMany(self, list: list | ee.List) -> ee.List:
8787
"""
8888
return ee.List(list).map(lambda key: self._obj.get(key))
8989

90-
def toTable(
91-
self, valueType: Literal["dict", "list", "value"] = "value"
92-
) -> ee.FeatureCollection:
90+
def toTable(self, valueType: Literal["dict", "list", "value"] = "value") -> ee.FeatureCollection:
9391
"""Convert a :py:class:`ee.Dictionary` to a :py:class:`ee.FeatureCollection` with no geometries (table).
9492
9593
There are 3 different type of values handled by this method:

geetools/ee_feature_collection.py

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -127,19 +127,15 @@ def toDictionary(
127127
print(json.dumps(countries.getInfo(), indent=2))
128128
"""
129129
uniqueIds = self._obj.aggregate_array(keyColumn)
130-
selectors = (
131-
ee.List(selectors) if selectors is not None else self._obj.first().propertyNames()
132-
)
130+
selectors = ee.List(selectors) if selectors is not None else self._obj.first().propertyNames()
133131
keyColumn = ee.String(keyColumn)
134132

135133
features = self._obj.toList(self._obj.size())
136134
values = features.map(lambda feat: ee.Feature(feat).toDictionary(selectors))
137135
keys = uniqueIds.map(lambda uid: ee.String(ee.Algorithms.String(uid)))
138136
return ee.Dictionary.fromLists(keys, values)
139137

140-
def addId(
141-
self, name: str | ee.String = "id", start: int | ee.Number = 1
142-
) -> ee.FeatureCollection:
138+
def addId(self, name: str | ee.String = "id", start: int | ee.Number = 1) -> ee.FeatureCollection:
143139
"""Add a unique numeric identifier, starting from parameter ``start``.
144140
145141
Args:
@@ -318,18 +314,14 @@ def byProperties(
318314
"""
319315
# get all the id values, they must be string so we are forced to cast them manually
320316
# the default casting is broken from Python side: https://issuetracker.google.com/issues/329106322
321-
features = self._obj.aggregate_array(featureId)
317+
feats = self._obj.aggregate_array(featureId)
322318
isString = lambda i: ee.Algorithms.ObjectType(i).compareTo("String").eq(0) # noqa: E731
323-
features = features.map(lambda i: ee.Algorithms.If(isString(i), i, ee.Number(i).format()))
319+
feats = feats.map(lambda i: ee.Algorithms.If(isString(i), i, ee.Number(i).format()))
324320

325321
# retrieve properties for each feature
326-
properties = (
327-
ee.List(properties) if properties is not None else self._obj.first().propertyNames()
328-
)
329-
properties = properties.remove(featureId)
330-
values = properties.map(
331-
lambda p: ee.Dictionary.fromLists(features, self._obj.aggregate_array(p))
332-
)
322+
eeProps = self._obj.first().propertyNames() if properties is None else ee.List(properties)
323+
eeProps = eeProps.remove(featureId)
324+
values = eeProps.map(lambda p: ee.Dictionary.fromLists(feats, self._obj.aggregate_array(p)))
333325

334326
# get the label to use in the dictionary if requested
335327
labels = ee.List(labels) if labels is not None else properties
@@ -459,11 +451,7 @@ def plot_by_features(
459451
label.set_rotation(45)
460452
"""
461453
# Get the features and properties
462-
props = (
463-
ee.List(properties)
464-
if properties is not None
465-
else self._obj.first().propertyNames().getInfo()
466-
)
454+
props = ee.List(properties) if properties is not None else self._obj.first().propertyNames().getInfo()
467455
props = props.remove(featureId)
468456

469457
# get the data from server

geetools/ee_image.py

Lines changed: 23 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,7 @@ def addDate(self, format: str | ee.String = "") -> ee.Image:
7171

7272
return self._obj.addBands(dateBand)
7373

74-
def addSuffix(
75-
self, suffix: str | ee.String, bands: list[str] | ee.List | None = None
76-
) -> ee.Image:
74+
def addSuffix(self, suffix: str | ee.String, bands: list[str] | ee.List | None = None) -> ee.Image:
7775
"""Add a suffix to the image selected band.
7876
7977
Add a suffix to the selected band. If no band is specified, the suffix is added to all bands.
@@ -97,16 +95,12 @@ def addSuffix(
9795
print(image.bandNames().getInfo())
9896
"""
9997
suffix = ee.String(suffix)
100-
bands = ee.List(bands) if bands is not None else self._obj.bandNames()
101-
bandNames = bands.iterate(
102-
lambda b, n: ee.List(n).replace(b, ee.String(b).cat(suffix)),
103-
self._obj.bandNames(),
104-
)
98+
srcBands = self._obj.bandNames()
99+
eeBands = srcBands if bands is None else ee.List(bands)
100+
bandNames = eeBands.iterate(lambda b, n: ee.List(n).replace(b, ee.String(b).cat(suffix)), srcBands)
105101
return self._obj.rename(bandNames)
106102

107-
def addPrefix(
108-
self, prefix: str | ee.String, bands: list[str] | ee.List | None = None
109-
) -> ee.Image:
103+
def addPrefix(self, prefix: str | ee.String, bands: list[str] | ee.List | None = None) -> ee.Image:
110104
"""Add a prefix to the image selected band.
111105
112106
Add a prefix to the selected band. If no band is specified, the prefix is added to all bands.
@@ -130,11 +124,9 @@ def addPrefix(
130124
print(image.bandNames().getInfo())
131125
"""
132126
prefix = ee.String(prefix)
133-
bands = ee.List(bands) if bands is not None else self._obj.bandNames()
134-
bandNames = bands.iterate(
135-
lambda b, n: ee.List(n).replace(b, prefix.cat(ee.String(b))),
136-
self._obj.bandNames(),
137-
)
127+
srcBands = self._obj.bandNames()
128+
eeBands = srcBands if bands is None else ee.List(bands)
129+
bandNames = eeBands.iterate(lambda b, n: ee.List(n).replace(b, prefix.cat(ee.String(b))), srcBands)
138130
return self._obj.rename(bandNames)
139131

140132
def rename(self, names: dict | ee.Dictionary) -> ee.Image:
@@ -162,9 +154,7 @@ def rename(self, names: dict | ee.Dictionary) -> ee.Image:
162154
print(image.bandNames().getInfo())
163155
"""
164156
names = ee.Dictionary(names)
165-
bands = names.keys().iterate(
166-
lambda b, n: ee.List(n).replace(b, names.get(b)), self._obj.bandNames()
167-
)
157+
bands = names.keys().iterate(lambda b, n: ee.List(n).replace(b, names.get(b)), self._obj.bandNames())
168158
return self._obj.rename(bands)
169159

170160
def remove(self, bands: list[str] | ee.List) -> ee.Image:
@@ -228,9 +218,7 @@ def doyToDate(
228218

229219
doyList = ee.List.sequence(0, 365)
230220
remapList = doyList.map(
231-
lambda d: ee.Number.parse(
232-
ee.Date.fromYMD(year, 1, 1).advance(d, "day").format(dateFormat)
233-
)
221+
lambda d: ee.Number.parse(ee.Date.fromYMD(year, 1, 1).advance(d, "day").format(dateFormat))
234222
)
235223
return self._obj.remap(doyList, remapList, bandName=band).rename(band)
236224

@@ -361,9 +349,7 @@ def toGrid(
361349
index = ee.List.sequence(0, lat.size().subtract(2))
362350
squares = index.map(
363351
lambda i: (
364-
ee.Geometry.Point([lon.get(i), lat.get(i)])
365-
.buffer(size.divide(2))
366-
.bounds(0.01, projection)
352+
ee.Geometry.Point([lon.get(i), lat.get(i)]).buffer(size.divide(2)).bounds(0.01, projection)
367353
)
368354
)
369355

@@ -402,9 +388,7 @@ def clipOnCollection(
402388

403389
def fcClip(feat):
404390
image = self._obj.clip(feat.geometry())
405-
return ee.Algorithms.If(
406-
ee.Number(keepProperties).toInt(), image.copyProperties(feat), image
407-
)
391+
return ee.Algorithms.If(ee.Number(keepProperties).toInt(), image.copyProperties(feat), image)
408392

409393
return ee.ImageCollection(fc.map(fcClip))
410394

@@ -469,18 +453,18 @@ def full(
469453
image = ee.Image.geetools.full([1, 2, 3], ['a', 'b', 'c'])
470454
print(image.bandNames().getInfo())
471455
"""
472-
values = ee.List(values) if values is not None else ee.List([0])
473-
names = ee.List(names) if names is not None else ee.List(["constant"])
456+
eeValues = ee.List([0]) if values is None else ee.List(values)
457+
eeNames = ee.List(["constant"]) if names is None else ee.List(names)
474458

475459
# resize value to the same length as names
476-
values = ee.List(
460+
eeValues = ee.List(
477461
ee.Algorithms.If(
478-
values.size().eq(1),
479-
ee.List.repeat(ee.Number(values.get(0)), names.size()),
480-
values,
462+
eeValues.size().eq(1),
463+
ee.List.repeat(ee.Number(eeValues.get(0)), eeNames.size()),
464+
eeValues,
481465
)
482466
)
483-
return ee.Image.constant(values).rename(names)
467+
return ee.Image.constant(eeValues).rename(eeNames)
484468

485469
def fullLike(
486470
self,
@@ -574,12 +558,12 @@ def reduceBands(
574558
if not isinstance(reducer, str):
575559
raise TypeError("reducer must be a Python string")
576560

577-
bands = ee.List(bands) if bands is not None else ee.List([])
561+
eeBands = ee.List(bands) if bands is not None else ee.List([])
578562
name = ee.String(name)
579-
bands = ee.Algorithms.If(bands.size().eq(0), self._obj.bandNames(), bands)
563+
eeBands = ee.Algorithms.If(eeBands.size().eq(0), self._obj.bandNames(), eeBands)
580564
name = ee.Algorithms.If(name.equals(ee.String("")), reducer, name)
581565
red = getattr(ee.Reducer, reducer)() if isinstance(reducer, str) else reducer
582-
reduceImage = self._obj.select(ee.List(bands)).reduce(red).rename([name])
566+
reduceImage = self._obj.select(ee.List(eeBands)).reduce(red).rename([name])
583567
return self._obj.addBands(reduceImage)
584568

585569
def negativeClip(self, geometry: ee.Geometry | ee.Feature | ee.FeatureCollection) -> ee.Image:
@@ -827,9 +811,7 @@ def isletMask(self, offset: float | int | ee.Number) -> ee.Image:
827811
scale = self._obj.projection().nominalScale()
828812
pixelsLimit = offset.multiply(2).sqrt().divide(scale).max(ee.Number(2)).toInt()
829813
area = ee.Image.pixelArea().rename("area")
830-
isletArea = (
831-
self._obj.select(0).mask().toInt().connectedPixelCount(pixelsLimit).multiply(area)
832-
)
814+
isletArea = self._obj.select(0).mask().toInt().connectedPixelCount(pixelsLimit).multiply(area)
833815
return isletArea.lt(offset).rename("mask").selfMask()
834816

835817
# -- ee-extra wrapper ------------------------------------------------------

geetools/ee_image_collection.py

Lines changed: 13 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -107,9 +107,7 @@ def maskClouds(
107107
# cdi,
108108
# )
109109

110-
def closest(
111-
self, date: ee.Date | str, tolerance: int = 1, unit: str = "month"
112-
) -> ee.ImageCollection:
110+
def closest(self, date: ee.Date | str, tolerance: int = 1, unit: str = "month") -> ee.ImageCollection:
113111
"""Gets the closest image (or set of images if the collection intersects a region that requires multiple scenes) to the specified date.
114112
115113
Parameters:
@@ -403,7 +401,9 @@ def getDOI(self) -> str:
403401
ee.ImageCollection('NASA/GPM_L3/IMERG_V06').geetools.getDOI()
404402
"""
405403
stac = self.getSTAC()
406-
error_msg = "The DOI is not available for this collection. Please check the STAC for more information."
404+
error_msg = (
405+
"The DOI is not available for this collection. Please check the STAC for more information."
406+
)
407407
return stac.get("sci:doi", error_msg)
408408

409409
def getCitation(self) -> str:
@@ -885,9 +885,7 @@ def containsBandNames(
885885
# apply this filter and remove the temporary property. Exclude parameter is additive so
886886
# we do a blank multiplication to remove all the properties beforehand
887887
ic = ee.ImageCollection(self._obj.filter(filterCombination))
888-
ic = ic.map(
889-
lambda i: ee.Image(i.multiply(1).copyProperties(i, exclude=[bandNamesProperty]))
890-
)
888+
ic = ic.map(lambda i: ee.Image(i.multiply(1).copyProperties(i, exclude=[bandNamesProperty])))
891889

892890
return ee.ImageCollection(ic)
893891

@@ -1040,9 +1038,7 @@ def delete_size_property(ic):
10401038
return ee.ImageCollection(ic.copyProperties(ic, properties=toCopy))
10411039

10421040
imageCollectionList = (
1043-
imageCollectionList.map(add_size)
1044-
.filter(ee.Filter.gt(sizeName, 0))
1045-
.map(delete_size_property)
1041+
imageCollectionList.map(add_size).filter(ee.Filter.gt(sizeName, 0)).map(delete_size_property)
10461042
)
10471043

10481044
return ee.List(imageCollectionList)
@@ -1242,8 +1238,8 @@ def sortMany(
12421238
ascending: the list of order. If not passed all properties will be sorted ascending
12431239
"""
12441240
properties = ee.List(properties)
1245-
ascending = ee.List(ascending or properties.map(lambda p: True))
1246-
order_dict = ee.Dictionary.fromLists(properties.slice(0, ascending.size()), ascending)
1241+
asc = ee.List(ascending or properties.map(lambda p: True))
1242+
order_dict = ee.Dictionary.fromLists(properties.slice(0, asc.size()), asc)
12471243
# position order of each prop will be converted to string using this format
12481244
length = self._obj.size().toInt().format().length()
12491245
format = ee.String("%0").cat(length.format()).cat("d")
@@ -1546,9 +1542,7 @@ def filter_doy(d: ee.Number) -> ee.ImageCollection:
15461542

15471543
# reduce every sub ImageCollection in the list into images (it's the temporal reduction)
15481544
# and aggregate the result as a single ImageCollection
1549-
timeRed = (
1550-
getattr(ee.Reducer, timeReducer)() if isinstance(timeReducer, str) else timeReducer
1551-
)
1545+
timeRed = getattr(ee.Reducer, timeReducer)() if isinstance(timeReducer, str) else timeReducer
15521546

15531547
def timeReduce(c: ee.ImageCollection) -> ee.image:
15541548
c = ee.ImageCollection(c)
@@ -1561,9 +1555,7 @@ def timeReduce(c: ee.ImageCollection) -> ee.image:
15611555
# spatially reduce the generated imagecollection over the region for each band
15621556
doyList = ic.aggregate_array(doy_metadata).map(lambda d: ee.Number(d).int().format())
15631557
spatialRed = (
1564-
getattr(ee.Reducer, spatialReducer)()
1565-
if isinstance(spatialReducer, str)
1566-
else spatialReducer
1558+
getattr(ee.Reducer, spatialReducer)() if isinstance(spatialReducer, str) else spatialReducer
15671559
)
15681560

15691561
def spatialReduce(label: ee.String) -> ee.Dictionary:
@@ -1652,9 +1644,7 @@ def filter_doy(d: ee.Number) -> ee.ImageCollection:
16521644

16531645
# reduce every sub ImageCollection in the list into images (it's the temporal reduction)
16541646
# and aggregate the result as a single ImageCollection
1655-
timeRed = (
1656-
getattr(ee.Reducer, timeReducer)() if isinstance(timeReducer, str) else timeReducer
1657-
)
1647+
timeRed = getattr(ee.Reducer, timeReducer)() if isinstance(timeReducer, str) else timeReducer
16581648

16591649
def timeReduce(c: ee.ImageCollection) -> ee.image:
16601650
c = ee.ImageCollection(c)
@@ -1667,9 +1657,7 @@ def timeReduce(c: ee.ImageCollection) -> ee.image:
16671657
# reduce the data for each region
16681658
doyList = ic.aggregate_array(doy_metadata).map(lambda d: ee.Number(d).int().format())
16691659
spatialRed = (
1670-
getattr(ee.Reducer, spatialReducer)()
1671-
if isinstance(spatialReducer, str)
1672-
else spatialReducer
1660+
getattr(ee.Reducer, spatialReducer)() if isinstance(spatialReducer, str) else spatialReducer
16731661
)
16741662
image = ic.toBands().rename(doyList)
16751663
reduced = image.reduceRegions(
@@ -2769,9 +2757,7 @@ def splitFeatures(f: ee.Feature) -> ee.List:
27692757
def splitId(loc_id: ee.String) -> ee.Feature:
27702758
loc_id = ee.String(loc_id)
27712759
loc_f = ee.Feature(f).select([loc_id.cat("_.*")])
2772-
oldNames = loc_f.propertyNames().filter(
2773-
ee.Filter.stringStartsWith("item", "system:").Not()
2774-
)
2760+
oldNames = loc_f.propertyNames().filter(ee.Filter.stringStartsWith("item", "system:").Not())
27752761
newNames = oldNames.map(lambda n: ee.String(n).replace(loc_id.cat("_"), ""))
27762762
loc_f = ee.Feature(ee.Feature(loc_f).select(oldNames, newNames))
27772763
loc_f = ee.Feature(loc_f.copyProperties(f, properties=originalProps))

geetools/ee_list.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,7 @@ def product(self, other: list | ee.List) -> ee.List:
4040
"""
4141
l1 = ee.List(self._obj).map(lambda e: ee.String(e))
4242
l2 = ee.List(other).map(lambda e: ee.String(e))
43-
product = l1.map(
44-
lambda e: l2.map(lambda f: ee.Algorithms.String(e).cat(ee.Algorithms.String(f)))
45-
)
43+
product = l1.map(lambda e: l2.map(lambda f: ee.Algorithms.String(e).cat(ee.Algorithms.String(f))))
4644
return product.flatten()
4745

4846
def complement(self, other: list | ee.List) -> ee.List:

geetools/ee_number.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,7 @@ def truncate(self, nbDecimals: int | ee.Number = 2) -> ee.Number:
3838
factor = ee.Number(10).pow(nbDecimals)
3939
return self._obj.multiply(factor).toInt().divide(factor)
4040

41-
def isClose(
42-
self, other: int | float | ee.Number, tol: int | float | ee.Number = 1e-9
43-
) -> ee.Number:
41+
def isClose(self, other: int | float | ee.Number, tol: int | float | ee.Number = 1e-9) -> ee.Number:
4442
"""Check if a number is close to another number.
4543
4644
Args:

geetools/tools/_deprecated_imagecollection.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,7 @@ def mosaicSameDay(collection, qualityBand=""):
2020

2121

2222
@deprecated(version="1.5.0", reason="Use ee.ImageCollection.geetools.reduceInterval instead.")
23-
def reduceEqualInterval(
24-
collection, interval=30, unit="day", reducer=None, start_date=None, end_date=None
25-
):
23+
def reduceEqualInterval(collection, interval=30, unit="day", reducer=None, start_date=None, end_date=None):
2624
"""Reduce an ImageCollection into a new one that has one image per reduced interval."""
2725
return ee.ImageCollection(collection).geetools.reduceInterval(reducer, unit, interval)
2826

0 commit comments

Comments
 (0)