Skip to content

Commit 8708ebf

Browse files
committed
refact: replace sys.exit by raise
1 parent bb44297 commit 8708ebf

File tree

6 files changed

+83
-115
lines changed

6 files changed

+83
-115
lines changed

.pylintrc

-1
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,6 @@ max-nested-blocks=6
103103
# inconsistent-return-statements if a never returning function is called then
104104
# it will be considered as an explicit return statement and no message will be
105105
# printed.
106-
never-returning-functions=sys.exit
107106

108107

109108
[SPELLING]

pandora/check_configuration.py

+32-45
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@
2828
import copy
2929
import json
3030
import logging
31-
import sys
3231
from collections.abc import Mapping
3332
from os import PathLike
3433
from typing import Dict, Union, List, Tuple
@@ -83,15 +82,15 @@ def check_shape(dataset: xr.Dataset, ref: str, test: str) -> None:
8382
8483
:param dataset: dataset
8584
:type dataset: xr.Dataset
86-
:param ref: the reference image
87-
:type str: name of image
85+
:param ref: name of the reference image
86+
:type ref: str
8887
:param test: the tested image
89-
:type str: name of image
88+
:type test: str
89+
:return: None
9090
"""
9191
# check only the rows and columns, the last two elements of the shape
9292
if dataset[ref].data.shape[-2:] != dataset[test].data.shape[-2:]:
93-
logging.error("%s and %s must have the same shape", ref, test)
94-
sys.exit(1)
93+
raise ValueError(f" {ref} and {test} must have the same shape")
9594

9695

9796
def check_attributes(dataset: xr.Dataset, attribute_list: set) -> None:
@@ -100,13 +99,13 @@ def check_attributes(dataset: xr.Dataset, attribute_list: set) -> None:
10099
101100
:param dataset: dataset
102101
:type dataset: xr.Dataset
103-
:param attribute: the atribute to test
104-
:type set: list of attribute names
102+
:param attribute_list: the attribute to test
103+
:type attribute_list: list
104+
:return: None
105105
"""
106106
attribute = attribute_list - set(dataset.attrs)
107107
if attribute:
108-
logging.error("User must provide the % attribute(s)", attribute)
109-
sys.exit(1)
108+
raise AttributeError(f"User must provide the {attribute} attribute(s)")
110109

111110

112111
def check_dataset(dataset: xr.Dataset) -> None:
@@ -115,20 +114,19 @@ def check_dataset(dataset: xr.Dataset) -> None:
115114
116115
:param dataset: dataset
117116
:type dataset: xr.Dataset
117+
:return: None
118118
"""
119119

120120
# Check image
121121
if "im" not in dataset:
122-
logging.error("User must provide an image im")
123-
sys.exit(1)
122+
raise AttributeError("User must provide an image im")
124123

125124
# Check band in "band_im" coordinates
126125
check_band_names(dataset)
127126

128127
# Check not empty image (all nan values)
129128
if np.isnan(dataset["im"].data).all():
130-
logging.error("Image contains only nan values")
131-
sys.exit(1)
129+
raise ValueError("Image contains only nan values")
132130

133131
# Check disparities
134132
if "disparity" in dataset:
@@ -147,26 +145,25 @@ def check_datasets(left: xr.Dataset, right: xr.Dataset) -> None:
147145
"""
148146
Check that left and right datasets are correct
149147
150-
:param left: dataset
151-
:type dataset: xr.Dataset
152-
:param right: dataset
153-
:type dataset: xr.Dataset
148+
:param left: left dataset
149+
:type left: xr.Dataset
150+
:param right: right dataset
151+
:type right: xr.Dataset
152+
:return: None
154153
"""
155154

156155
# Check the dataset content
157156
check_dataset(left)
158157
check_dataset(right)
159158

160159
# Check disparities at least on the left
161-
if not "disparity" in left:
162-
logging.error("left dataset must have disparity DataArray")
163-
sys.exit(1)
160+
if "disparity" not in left:
161+
raise AttributeError("left dataset must have disparity DataArray")
164162

165163
# Check shape
166164
# check only the rows and columns, the last two elements of the shape
167165
if left["im"].data.shape[-2:] != right["im"].data.shape[-2:]:
168-
logging.error("left and right datasets must have the same shape")
169-
sys.exit(1)
166+
raise AttributeError("left and right datasets must have the same shape")
170167

171168

172169
def check_image_dimension(img1: rasterio.io.DatasetReader, img2: rasterio.io.DatasetReader) -> None:
@@ -180,8 +177,7 @@ def check_image_dimension(img1: rasterio.io.DatasetReader, img2: rasterio.io.Dat
180177
:return: None
181178
"""
182179
if (img1.width != img2.width) or (img1.height != img2.height):
183-
logging.error("Images must have the same size")
184-
sys.exit(1)
180+
raise AttributeError("Images must have the same size")
185181

186182

187183
def check_images(user_cfg: Dict[str, dict]) -> None:
@@ -218,8 +214,7 @@ def check_band_names(dataset: xr.Dataset) -> None:
218214
"""
219215

220216
if "band_im" in dataset.coords and not all(isinstance(band, str) for band in dataset.coords["band_im"].data):
221-
logging.error("Band value must be str")
222-
sys.exit(1)
217+
raise TypeError("Band value must be str")
223218

224219

225220
def check_disparities_from_input(
@@ -229,18 +224,17 @@ def check_disparities_from_input(
229224
"""
230225
Check disparities from user configuration
231226
232-
:param disparity: disparity to check if list it is a list of two values: min and max.
227+
:param disparity: disparity to check if disparity is a list of two values: min and max.
233228
:type disparity: list[int] | str | None
234229
:param img_left: path to the left image
235230
:type img_left: str
236231
:return: None
237232
"""
238233
# disparities are integers
239234
if isinstance(disparity, list) and disparity[1] < disparity[0]:
240-
logging.error("Disp_max must be bigger than Disp_min")
241-
sys.exit(1)
235+
raise ValueError("disp_max must be bigger than disp_min")
242236

243-
# disparites are grids
237+
# disparities are grids
244238
if isinstance(disparity, str):
245239
# Load an image to compare the grid size
246240
img_left_ = rasterio_open(img_left)
@@ -249,17 +243,14 @@ def check_disparities_from_input(
249243

250244
# check that disparity grids is a 2-channel grid
251245
if disparity_reader.count != 2:
252-
logging.error("Disparity grids must be a 2-channel grid")
253-
sys.exit(1)
246+
raise AttributeError("Disparity grids must be a 2-channel grid")
254247

255248
# check that disp_min has the same size as the image
256249
if (disparity_reader.width != img_left_.width) or (disparity_reader.height != img_left_.height):
257-
logging.error("Disparity grids and image must have the same size")
258-
sys.exit(1)
250+
raise AttributeError("Disparity grids and image must have the same size")
259251

260252
if (disparity_reader.read(1) > disparity_reader.read(2)).any():
261-
logging.error("Disp_max must be bigger than Disp_min")
262-
sys.exit(1)
253+
raise ValueError("disp_max must be bigger than disp_min")
263254

264255

265256
def check_disparities_from_dataset(disparity: xr.DataArray) -> None:
@@ -274,15 +265,12 @@ def check_disparities_from_dataset(disparity: xr.DataArray) -> None:
274265
:return: None
275266
"""
276267
if "band_disp" not in disparity.coords:
277-
logging.error("Disparity xr.Dataset must have a band_disp coordinate")
278-
sys.exit(1)
268+
raise AttributeError("Disparity xr.Dataset must have a band_disp coordinate")
279269
band_disp = disparity.coords["band_disp"].data
280270
if not {"min", "max"}.issubset(band_disp):
281-
logging.error("Disparity xr.Dataset must have a band_disp coordinate with min and max band")
282-
sys.exit(1)
271+
raise AttributeError("Disparity xr.Dataset must have a band_disp coordinate with min and max band")
283272
if (disparity.sel(band_disp="min").data > disparity.sel(band_disp="max").data).any():
284-
logging.error("Disp_max grid must be bigger than Disp_min grid for each pixel")
285-
sys.exit(1)
273+
raise AttributeError("Disp_max grid must be bigger than Disp_min grid for each pixel")
286274

287275

288276
def get_config_input(user_cfg: Dict[str, dict]) -> Dict[str, dict]:
@@ -356,8 +344,7 @@ def memory_consumption_estimation(
356344
input_cfg = {"left": {"disp": disparity_interval, "img": img_path}, "right": {"img": img_path}}
357345
user_input = {"input": input_cfg}
358346
else:
359-
logging.error("%s must be a Dict or a Tuple", user_input)
360-
sys.exit(1)
347+
raise TypeError(f"{user_input} must be a dict or a tuple")
361348

362349
# Read input image
363350
img = rasterio_open(img_path)

pandora/img_tools.py

+22-25
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,8 @@
2525

2626
from __future__ import annotations
2727

28-
import logging
2928
import warnings
3029
from typing import List, Union, Tuple, cast, Dict
31-
import sys
3230

3331
import numpy as np
3432
import rasterio
@@ -87,8 +85,7 @@ def get_window(roi: Dict, width: int, height: int) -> Window:
8785

8886
# check roi outside
8987
if col_off > width or row_off > height or (col_off + roi_width) < 0 or (row_off + roi_height) < 0:
90-
logging.error("Roi specified is outside the image")
91-
sys.exit(1)
88+
raise ValueError("Roi specified is outside the image")
9289

9390
# overlap roi and image
9491
# right side
@@ -144,7 +141,7 @@ def add_disparity(
144141

145142
def add_classif(dataset: xr.Dataset, classif: Union[str, None], window: Window) -> xr.Dataset:
146143
"""
147-
Add classification informations and image to datasaet
144+
Add classification information and image to dataset
148145
149146
:param dataset: xarray dataset without classification
150147
:type dataset: xr.Dataset
@@ -169,7 +166,7 @@ def add_classif(dataset: xr.Dataset, classif: Union[str, None], window: Window)
169166

170167
def add_segm(dataset: xr.Dataset, segm: Union[str, None], window: Window) -> xr.Dataset:
171168
"""
172-
Add Segmentation informations and image to datasaet
169+
Add Segmentation information and image to dataset
173170
174171
:param dataset: xarray dataset without segmentation
175172
:type dataset: xr.Dataset
@@ -191,9 +188,9 @@ def add_segm(dataset: xr.Dataset, segm: Union[str, None], window: Window) -> xr.
191188

192189
def add_no_data(dataset: xr.Dataset, no_data: Union[int, float], no_data_pixels: np.ndarray) -> xr.Dataset:
193190
"""
194-
Add no data informations to datasaet
191+
Add no data information to dataset
195192
196-
:param dataset: xarray dataset without no_data informations
193+
:param dataset: xarray dataset without no_data information
197194
:type dataset: xr.Dataset
198195
:param no_data: value
199196
:type no_data: int or float
@@ -216,7 +213,7 @@ def add_mask(
216213
dataset: xr.Dataset, mask: Union[str, None], no_data_pixels: np.ndarray, width: int, height: int, window: Window
217214
) -> xr.Dataset:
218215
"""
219-
Add mask informations and image to datasaet
216+
Add mask information and image to dataset
220217
221218
:param dataset: xarray dataset without mask
222219
:type dataset: xr.Dataset
@@ -228,6 +225,8 @@ def add_mask(
228225
:type width: int
229226
:param height: nb rows
230227
:type height: int
228+
:param window: information about window
229+
:type window: rasterio.window
231230
:return: dataset : updated dataset
232231
:rtype: xr.Dataset
233232
"""
@@ -273,7 +272,7 @@ def create_dataset_from_inputs(input_config: dict, roi: dict = None) -> xr.Datas
273272
274273
:param input_config: configuration used to create dataset.
275274
:type input_config: dict
276-
:param roi: dictionnary with a roi
275+
:param roi: dictionary with a roi
277276
278277
"col": {"first": <value - int>, "last": <value - int>},
279278
"row": {"first": <value - int>, "last": <value - int>},
@@ -497,9 +496,9 @@ def interpolate_nodata_sgm(img: np.ndarray, valid: np.ndarray) -> Tuple[np.ndarr
497496
IEEE Transactions on pattern analysis and machine intelligence, 2007, vol. 30, no 2, p. 328-341.
498497
499498
:param img: input image
500-
:type img: 2D np.array (row, col)
499+
:type img: 2D np.ndarray (row, col)
501500
:param valid: validity mask
502-
:type valid: 2D np.array (row, col)
501+
:type valid: 2D np.ndarray (row, col)
503502
:return: the interpolate input image, with the validity mask update :
504503
505504
- If out & PANDORA_MSK_PIXEL_FILLED_NODATA != 0 : Invalid pixel : filled nodata pixel
@@ -540,11 +539,10 @@ def masks_pyramid(msk: np.ndarray, scale_factor: int, num_scales: int) -> List[n
540539
:return: a List that contains the different scaled masks
541540
:rtype: List of np.ndarray
542541
"""
543-
msk_pyramid = []
542+
msk_pyramid = [msk]
544543
# Add the full resolution mask
545-
msk_pyramid.append(msk)
546544
tmp_msk = msk
547-
for scale in range(num_scales - 1): # pylint: disable=unused-variable
545+
for _ in range(num_scales - 1):
548546
# Decimate in the two axis
549547
tmp_msk = tmp_msk[::scale_factor, ::scale_factor]
550548
msk_pyramid.append(tmp_msk)
@@ -657,7 +655,7 @@ def check_inside_image(img: xr.Dataset, row: int, col: int) -> bool:
657655
:type row: int
658656
:param col: column coordinates
659657
:type col: int
660-
:return: a boolean
658+
:return: True if the coordinates row,col are inside the image
661659
:rtype: boolean
662660
"""
663661
ny_, nx_ = img.dims["row"], img.dims["col"]
@@ -691,7 +689,7 @@ def census_transform(image: xr.Dataset, window_size: int, band: str = None) -> x
691689

692690
# Create a sliding window of using as_strided function : this function create a new a view (by manipulating data
693691
# pointer) of the image array with a different shape. The new view pointing to the same memory block as
694-
# image so it does not consume any additional memory.
692+
# image, so it does not consume any additional memory.
695693
str_row, str_col = selected_band.strides
696694
shape_windows = (
697695
ny_ - (window_size - 1),
@@ -780,22 +778,22 @@ def find_valid_neighbors(dirs: np.ndarray, disp: np.ndarray, valid: np.ndarray,
780778
Find valid neighbors along directions
781779
782780
:param dirs: directions
783-
:type dirs: 2D np.array (row, col)
781+
:type dirs: 2D np.ndarray (row, col)
784782
:param disp: disparity map
785-
:type disp: 2D np.array (row, col)
783+
:type disp: 2D np.ndarray (row, col)
786784
:param valid: validity mask
787-
:type valid: 2D np.array (row, col)
785+
:type valid: 2D np.ndarray (row, col)
788786
:param row: row current value
789787
:type row: int
790788
:param col: col current value
791789
:type col: int
792790
:return: valid neighbors
793-
:rtype: 2D np.array
791+
:rtype: 2D np.ndarray
794792
"""
795793
ncol, nrow = disp.shape
796794
# Maximum path length
797795
max_path_length = max(nrow, ncol)
798-
# For each directions
796+
# For each direction
799797
valid_neighbors = np.zeros(8, dtype=np.float32)
800798
for direction in range(8):
801799
# Find the first valid pixel in the current path
@@ -843,8 +841,7 @@ def compute_mean_patch(img: xr.Dataset, row: int, col: int, win_size: int) -> np
843841
dtype=np.float32,
844842
)
845843

846-
logging.error("The window is outside the image")
847-
raise IndexError
844+
raise IndexError("The window is outside the image")
848845

849846

850847
def compute_std_raster(img: xr.Dataset, win_size: int, band: str = None) -> np.ndarray:
@@ -903,7 +900,7 @@ def read_disp(disparity: tuple[int, int] | list[int] | str) -> tuple[int, int] |
903900

904901
if not isinstance(disparity, str):
905902
# cast because of mypy when we give list as input while it expects a tuple as output
906-
# not sure it is the best solution
903+
# not sure if it is the best solution
907904
return cast(Tuple[int, int], tuple(disparity))
908905

909906
raster_disparity = rasterio_open(disparity)

0 commit comments

Comments
 (0)