disdrodb 0.2.0__py3-none-any.whl → 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. disdrodb/_version.py +2 -2
  2. disdrodb/accessor/methods.py +10 -3
  3. disdrodb/api/checks.py +1 -1
  4. disdrodb/api/io.py +6 -1
  5. disdrodb/constants.py +1 -1
  6. disdrodb/etc/products/L1/LPM_V0/1MIN.yaml +13 -0
  7. disdrodb/etc/products/L1/global.yaml +1 -1
  8. disdrodb/etc/products/L2E/global.yaml +1 -1
  9. disdrodb/etc/products/L2M/global.yaml +1 -1
  10. disdrodb/issue/checks.py +2 -2
  11. disdrodb/l0/check_configs.py +1 -1
  12. disdrodb/l0/configs/LPM/l0a_encodings.yml +0 -1
  13. disdrodb/l0/configs/LPM/l0b_cf_attrs.yml +0 -4
  14. disdrodb/l0/configs/LPM/l0b_encodings.yml +9 -9
  15. disdrodb/l0/configs/LPM/raw_data_format.yml +11 -11
  16. disdrodb/l0/configs/LPM_V0/bins_diameter.yml +103 -0
  17. disdrodb/l0/configs/LPM_V0/bins_velocity.yml +103 -0
  18. disdrodb/l0/configs/LPM_V0/l0a_encodings.yml +45 -0
  19. disdrodb/l0/configs/LPM_V0/l0b_cf_attrs.yml +180 -0
  20. disdrodb/l0/configs/LPM_V0/l0b_encodings.yml +410 -0
  21. disdrodb/l0/configs/LPM_V0/raw_data_format.yml +474 -0
  22. disdrodb/l0/configs/PARSIVEL/raw_data_format.yml +8 -8
  23. disdrodb/l0/configs/PARSIVEL2/raw_data_format.yml +9 -9
  24. disdrodb/l0/l0a_processing.py +6 -2
  25. disdrodb/l0/l0b_processing.py +26 -19
  26. disdrodb/l0/l0c_processing.py +10 -0
  27. disdrodb/l0/manuals/LPM_V0.pdf +0 -0
  28. disdrodb/l0/readers/LPM/ITALY/GID_LPM.py +15 -7
  29. disdrodb/l0/readers/LPM/ITALY/GID_LPM_PI.py +279 -0
  30. disdrodb/l0/readers/LPM/ITALY/GID_LPM_T.py +276 -0
  31. disdrodb/l0/readers/LPM/ITALY/GID_LPM_W.py +2 -2
  32. disdrodb/l0/readers/LPM/NETHERLANDS/DELFT_RWANDA_LPM_NC.py +103 -0
  33. disdrodb/l0/readers/LPM/NORWAY/HAUKELISETER_LPM.py +216 -0
  34. disdrodb/l0/readers/LPM/NORWAY/NMBU_LPM.py +208 -0
  35. disdrodb/l0/readers/LPM/UK/WITHWORTH_LPM.py +219 -0
  36. disdrodb/l0/readers/LPM/USA/CHARLESTON.py +229 -0
  37. disdrodb/l0/readers/{LPM → LPM_V0}/BELGIUM/ULIEGE.py +33 -49
  38. disdrodb/l0/readers/LPM_V0/ITALY/GID_LPM_V0.py +240 -0
  39. disdrodb/l0/readers/PARSIVEL/NASA/LPVEX.py +25 -13
  40. disdrodb/l0/readers/PARSIVEL/NASA/MC3E.py +1 -1
  41. disdrodb/l0/readers/PARSIVEL2/BASQUECOUNTRY/EUSKALMET_OTT2.py +1 -1
  42. disdrodb/l0/readers/PARSIVEL2/JAPAN/PRECIP.py +155 -0
  43. disdrodb/l0/readers/PARSIVEL2/MPI/BCO_PARSIVEL2.py +14 -7
  44. disdrodb/l0/readers/PARSIVEL2/MPI/BOWTIE.py +8 -3
  45. disdrodb/l0/readers/PARSIVEL2/NASA/APU.py +28 -5
  46. disdrodb/l0/readers/PARSIVEL2/NCAR/RELAMPAGO_PARSIVEL2.py +1 -1
  47. disdrodb/l0/readers/PARSIVEL2/{NASA/GCPEX.py → NORWAY/UIB.py} +54 -29
  48. disdrodb/l0/readers/PARSIVEL2/PHILIPPINES/PAGASA.py +6 -3
  49. disdrodb/l0/readers/{PARSIVEL/NASA/PIERS.py → PARSIVEL2/USA/CSU.py} +62 -29
  50. disdrodb/l0/readers/PARSIVEL2/USA/CW3E.py +48 -21
  51. disdrodb/l0/readers/{PARSIVEL/NASA/IFLOODS.py → RD80/BRAZIL/ATTO_RD80.py} +50 -34
  52. disdrodb/l0/readers/{SW250 → SWS250}/BELGIUM/KMI.py +1 -1
  53. disdrodb/l1/beard_model.py +45 -1
  54. disdrodb/l1/fall_velocity.py +1 -6
  55. disdrodb/l1/filters.py +2 -0
  56. disdrodb/l2/empirical_dsd.py +12 -8
  57. disdrodb/routines/l0.py +2 -2
  58. disdrodb/routines/options.py +2 -0
  59. disdrodb/scattering/axis_ratio.py +3 -0
  60. disdrodb/scattering/routines.py +1 -1
  61. disdrodb/summary/routines.py +63 -61
  62. disdrodb/utils/compression.py +4 -2
  63. disdrodb/utils/dask.py +31 -11
  64. disdrodb/utils/manipulations.py +7 -1
  65. disdrodb/viz/plots.py +5 -3
  66. {disdrodb-0.2.0.dist-info → disdrodb-0.2.1.dist-info}/METADATA +1 -1
  67. {disdrodb-0.2.0.dist-info → disdrodb-0.2.1.dist-info}/RECORD +71 -54
  68. {disdrodb-0.2.0.dist-info → disdrodb-0.2.1.dist-info}/WHEEL +0 -0
  69. {disdrodb-0.2.0.dist-info → disdrodb-0.2.1.dist-info}/entry_points.txt +0 -0
  70. {disdrodb-0.2.0.dist-info → disdrodb-0.2.1.dist-info}/licenses/LICENSE +0 -0
  71. {disdrodb-0.2.0.dist-info → disdrodb-0.2.1.dist-info}/top_level.txt +0 -0
Binary file
@@ -31,7 +31,7 @@ def reader(
31
31
  """Reader."""
32
32
  ##------------------------------------------------------------------------.
33
33
  #### - Define raw data headers
34
- column_names = ["TO_BE_SPLITTED"]
34
+ column_names = ["TO_PARSE"]
35
35
 
36
36
  ##------------------------------------------------------------------------.
37
37
  #### Define reader options
@@ -79,14 +79,22 @@ def reader(
79
79
 
80
80
  ##------------------------------------------------------------------------.
81
81
  #### Adapt the dataframe to adhere to DISDRODB L0 standards
82
- # Count number of delimiters to identify valid rows
83
- df = df[df["TO_BE_SPLITTED"].str.count(";") == 519]
82
+ # Raise error if empty file
83
+ if len(df) == 0:
84
+ raise ValueError(f"{filepath} is empty.")
85
+
86
+ # Select only rows with expected number of delimiters
87
+ df = df[df["TO_PARSE"].str.count(";").isin([519, 520])]
88
+
89
+ # Check there are still valid rows
90
+ if len(df) == 0:
91
+ raise ValueError(f"No valid rows in {filepath}.")
84
92
 
85
93
  # Split by ; delimiter (before raw drop number)
86
- df = df["TO_BE_SPLITTED"].str.split(";", expand=True, n=79)
94
+ df = df["TO_PARSE"].str.split(";", expand=True, n=79)
87
95
 
88
96
  # Assign column names
89
- column_names = [
97
+ names = [
90
98
  "start_identifier",
91
99
  "device_address",
92
100
  "sensor_serial_number",
@@ -168,10 +176,10 @@ def reader(
168
176
  "number_particles_class_9_internal_data",
169
177
  "raw_drop_number",
170
178
  ]
171
- df.columns = column_names
179
+ df.columns = names
172
180
 
173
181
  # Remove checksum from raw_drop_number
174
- df["raw_drop_number"] = df["raw_drop_number"].str.rsplit(";", n=1, expand=True)[0]
182
+ df["raw_drop_number"] = df["raw_drop_number"].str.strip(";").str.rsplit(";", n=1, expand=True)[0]
175
183
 
176
184
  # Define datetime "time" column
177
185
  df["time"] = df["sensor_date"] + "-" + df["sensor_time"]
@@ -0,0 +1,279 @@
1
+ # -----------------------------------------------------------------------------.
2
+ # Copyright (c) 2021-2023 DISDRODB developers
3
+ #
4
+ # This program is free software: you can redistribute it and/or modify
5
+ # it under the terms of the GNU General Public License as published by
6
+ # the Free Software Foundation, either version 3 of the License, or
7
+ # (at your option) any later version.
8
+ #
9
+ # This program is distributed in the hope that it will be useful,
10
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ # GNU General Public License for more details.
13
+ #
14
+ # You should have received a copy of the GNU General Public License
15
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
+ # -----------------------------------------------------------------------------.
17
+ """DISDRODB reader for GID LPM sensor TC-PI with incorrect reported time."""
18
+ import pandas as pd
19
+
20
+ from disdrodb.l0.l0_reader import is_documented_by, reader_generic_docstring
21
+ from disdrodb.l0.l0a_processing import read_raw_text_file
22
+ from disdrodb.utils.logger import log_error
23
+
24
+
25
+ def read_txt_file(file, filename, logger):
26
+ """Parse for TC-PI LPM file."""
27
+ #### - Define raw data headers
28
+ column_names = ["TO_PARSE"]
29
+
30
+ ##------------------------------------------------------------------------.
31
+ #### Define reader options
32
+ # - For more info: https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html
33
+ reader_kwargs = {}
34
+
35
+ # - Define delimiter
36
+ reader_kwargs["delimiter"] = "\\n"
37
+
38
+ # - Avoid first column to become df index !!!
39
+ reader_kwargs["index_col"] = False
40
+
41
+ # Since column names are expected to be passed explicitly, header is set to None
42
+ reader_kwargs["header"] = None
43
+
44
+ # - Number of rows to be skipped at the beginning of the file
45
+ reader_kwargs["skiprows"] = 1
46
+
47
+ # - Define behaviour when encountering bad lines
48
+ reader_kwargs["on_bad_lines"] = "skip"
49
+
50
+ # - Define reader engine
51
+ # - C engine is faster
52
+ # - Python engine is more feature-complete
53
+ reader_kwargs["engine"] = "python"
54
+
55
+ # - Define on-the-fly decompression of on-disk data
56
+ # - Available: gzip, bz2, zip
57
+ reader_kwargs["compression"] = "infer"
58
+
59
+ # - Strings to recognize as NA/NaN and replace with standard NA flags
60
+ # - Already included: '#N/A', '#N/A N/A', '#NA', '-1.#IND', '-1.#QNAN',
61
+ # '-NaN', '-nan', '1.#IND', '1.#QNAN', '<NA>', 'N/A',
62
+ # 'NA', 'NULL', 'NaN', 'n/a', 'nan', 'null'
63
+ reader_kwargs["na_values"] = ["na", "", "error"]
64
+
65
+ ##------------------------------------------------------------------------.
66
+ #### Read the data
67
+ df = read_raw_text_file(
68
+ filepath=file,
69
+ column_names=column_names,
70
+ reader_kwargs=reader_kwargs,
71
+ logger=logger,
72
+ )
73
+
74
+ ##------------------------------------------------------------------------.
75
+ #### Adapt the dataframe to adhere to DISDRODB L0 standards
76
+ # Raise error if empty file
77
+ if len(df) == 0:
78
+ raise ValueError(f"{filename} is empty.")
79
+
80
+ # Select only rows with expected number of delimiters
81
+ df = df[df["TO_PARSE"].str.count(" ") == 526]
82
+
83
+ # Check there are still valid rows
84
+ if len(df) == 0:
85
+ raise ValueError(f"No valid rows in {filename}.")
86
+
87
+ # Split by ; delimiter (before raw drop number)
88
+ df = df["TO_PARSE"].str.split(" ", expand=True, n=82)
89
+
90
+ # Assign column names
91
+ names = [
92
+ "date",
93
+ "time",
94
+ "unknown",
95
+ "start_identifier",
96
+ "device_address",
97
+ "sensor_serial_number",
98
+ "sensor_date",
99
+ "sensor_time",
100
+ "weather_code_synop_4677_5min",
101
+ "weather_code_synop_4680_5min",
102
+ "weather_code_metar_4678_5min",
103
+ "precipitation_rate_5min",
104
+ "weather_code_synop_4677",
105
+ "weather_code_synop_4680",
106
+ "weather_code_metar_4678",
107
+ "precipitation_rate",
108
+ "rainfall_rate",
109
+ "snowfall_rate",
110
+ "precipitation_accumulated",
111
+ "mor_visibility",
112
+ "reflectivity",
113
+ "quality_index",
114
+ "max_hail_diameter",
115
+ "laser_status",
116
+ "static_signal_status",
117
+ "laser_temperature_analog_status",
118
+ "laser_temperature_digital_status",
119
+ "laser_current_analog_status",
120
+ "laser_current_digital_status",
121
+ "sensor_voltage_supply_status",
122
+ "current_heating_pane_transmitter_head_status",
123
+ "current_heating_pane_receiver_head_status",
124
+ "temperature_sensor_status",
125
+ "current_heating_voltage_supply_status",
126
+ "current_heating_house_status",
127
+ "current_heating_heads_status",
128
+ "current_heating_carriers_status",
129
+ "control_output_laser_power_status",
130
+ "reserved_status",
131
+ "temperature_interior",
132
+ "laser_temperature",
133
+ "laser_current_average",
134
+ "control_voltage",
135
+ "optical_control_voltage_output",
136
+ "sensor_voltage_supply",
137
+ "current_heating_pane_transmitter_head",
138
+ "current_heating_pane_receiver_head",
139
+ "temperature_ambient",
140
+ "current_heating_voltage_supply",
141
+ "current_heating_house",
142
+ "current_heating_heads",
143
+ "current_heating_carriers",
144
+ "number_particles",
145
+ "number_particles_internal_data",
146
+ "number_particles_min_speed",
147
+ "number_particles_min_speed_internal_data",
148
+ "number_particles_max_speed",
149
+ "number_particles_max_speed_internal_data",
150
+ "number_particles_min_diameter",
151
+ "number_particles_min_diameter_internal_data",
152
+ "number_particles_no_hydrometeor",
153
+ "number_particles_no_hydrometeor_internal_data",
154
+ "number_particles_unknown_classification",
155
+ "number_particles_unknown_classification_internal_data",
156
+ "number_particles_class_1",
157
+ "number_particles_class_1_internal_data",
158
+ "number_particles_class_2",
159
+ "number_particles_class_2_internal_data",
160
+ "number_particles_class_3",
161
+ "number_particles_class_3_internal_data",
162
+ "number_particles_class_4",
163
+ "number_particles_class_4_internal_data",
164
+ "number_particles_class_5",
165
+ "number_particles_class_5_internal_data",
166
+ "number_particles_class_6",
167
+ "number_particles_class_6_internal_data",
168
+ "number_particles_class_7",
169
+ "number_particles_class_7_internal_data",
170
+ "number_particles_class_8",
171
+ "number_particles_class_8_internal_data",
172
+ "number_particles_class_9",
173
+ "number_particles_class_9_internal_data",
174
+ "TO_BE_FURTHER_PROCESSED",
175
+ ]
176
+ df.columns = names
177
+
178
+ # Define datetime "time" column
179
+ df["time"] = df["date"] + " " + df["time"]
180
+ df["time"] = pd.to_datetime(df["time"], format="%Y-%m-%d %H:%M:%S", errors="coerce")
181
+
182
+ # Drop row if start_identifier different than 00
183
+ df = df[df["start_identifier"].astype(str) == "00"]
184
+
185
+ # Extract the last variables remained in raw_drop_number
186
+ df_parsed = df["TO_BE_FURTHER_PROCESSED"].str.rsplit(" ", n=5, expand=True)
187
+ df_parsed.columns = [
188
+ "raw_drop_number",
189
+ "air_temperature",
190
+ "relative_humidity",
191
+ "wind_speed",
192
+ "wind_direction",
193
+ "checksum",
194
+ ]
195
+
196
+ # Assign columns to the original dataframe
197
+ df[df_parsed.columns] = df_parsed
198
+
199
+ # Drop rows with invalid raw_drop_number
200
+ # --> 440 value # 22x20
201
+ df = df[df["raw_drop_number"].astype(str).str.len() == 1759]
202
+
203
+ # Drop columns not agreeing with DISDRODB L0 standards
204
+ columns_to_drop = [
205
+ "start_identifier",
206
+ "device_address",
207
+ "sensor_serial_number",
208
+ "sensor_date",
209
+ "sensor_time",
210
+ "date",
211
+ "unknown",
212
+ "TO_BE_FURTHER_PROCESSED",
213
+ "air_temperature",
214
+ "relative_humidity",
215
+ "wind_speed",
216
+ "wind_direction",
217
+ "checksum",
218
+ ]
219
+ df = df.drop(columns=columns_to_drop)
220
+ return df
221
+
222
+
223
+ @is_documented_by(reader_generic_docstring)
224
+ def reader(
225
+ filepath,
226
+ logger=None,
227
+ ):
228
+ """Reader."""
229
+ import zipfile
230
+
231
+ ##------------------------------------------------------------------------.
232
+ # filename = os.path.basename(filepath)
233
+ # return read_txt_file(file=filepath, filename=filename, logger=logger)
234
+
235
+ # ---------------------------------------------------------------------.
236
+ #### Iterate over all files (aka timesteps) in the daily zip archive
237
+ # - Each file contain a single timestep !
238
+ # list_df = []
239
+ # with tempfile.TemporaryDirectory() as temp_dir:
240
+ # # Extract all files
241
+ # unzip_file_on_terminal(filepath, temp_dir)
242
+
243
+ # # Walk through extracted files
244
+ # for root, _, files in os.walk(temp_dir):
245
+ # for filename in sorted(files):
246
+ # if filename.endswith(".txt"):
247
+ # full_path = os.path.join(root, filename)
248
+ # try:
249
+ # df = read_txt_file(file=full_path, filename=filename, logger=logger)
250
+ # if df is not None:
251
+ # list_df.append(df)
252
+ # except Exception as e:
253
+ # msg = f"An error occurred while reading {filename}: {e}"
254
+ # log_error(logger=logger, msg=msg, verbose=True)
255
+
256
+ list_df = []
257
+ with zipfile.ZipFile(filepath, "r") as zip_ref:
258
+ filenames = sorted(zip_ref.namelist())
259
+ for filename in filenames:
260
+ if filename.endswith(".txt"):
261
+ # Open file
262
+ with zip_ref.open(filename) as file:
263
+ try:
264
+ df = read_txt_file(file=file, filename=filename, logger=logger)
265
+ if df is not None:
266
+ list_df.append(df)
267
+ except Exception as e:
268
+ msg = f"An error occurred while reading {filename}. The error is: {e}"
269
+ log_error(logger=logger, msg=msg, verbose=True)
270
+
271
+ # Check the zip file contains at least some non.empty files
272
+ if len(list_df) == 0:
273
+ raise ValueError(f"{filepath} contains only empty files!")
274
+
275
+ # Concatenate all dataframes into a single one
276
+ df = pd.concat(list_df)
277
+
278
+ # ---------------------------------------------------------------------.
279
+ return df
@@ -0,0 +1,276 @@
1
+ # -----------------------------------------------------------------------------.
2
+ # Copyright (c) 2021-2023 DISDRODB developers
3
+ #
4
+ # This program is free software: you can redistribute it and/or modify
5
+ # it under the terms of the GNU General Public License as published by
6
+ # the Free Software Foundation, either version 3 of the License, or
7
+ # (at your option) any later version.
8
+ #
9
+ # This program is distributed in the hope that it will be useful,
10
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ # GNU General Public License for more details.
13
+ #
14
+ # You should have received a copy of the GNU General Public License
15
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
+ # -----------------------------------------------------------------------------.
17
+ """DISDRODB reader for GID LPM sensors not reporting time (TC-MI2, TC-MI3, TC-ER e TC-FI)."""
18
+ import numpy as np
19
+ import pandas as pd
20
+
21
+ from disdrodb.l0.l0_reader import is_documented_by, reader_generic_docstring
22
+ from disdrodb.l0.l0a_processing import read_raw_text_file
23
+ from disdrodb.utils.logger import log_error, log_warning
24
+
25
+
26
+ def read_txt_file(file, filename, logger):
27
+ """Parse for LPM hourly file."""
28
+ #### - Define raw data headers
29
+ column_names = ["TO_PARSE"]
30
+
31
+ ##------------------------------------------------------------------------.
32
+ #### Define reader options
33
+ # - For more info: https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html
34
+ reader_kwargs = {}
35
+
36
+ # - Define delimiter
37
+ reader_kwargs["delimiter"] = "\\n"
38
+
39
+ # - Avoid first column to become df index !!!
40
+ reader_kwargs["index_col"] = False
41
+
42
+ # Since column names are expected to be passed explicitly, header is set to None
43
+ reader_kwargs["header"] = None
44
+
45
+ # - Number of rows to be skipped at the beginning of the file
46
+ reader_kwargs["skiprows"] = None
47
+
48
+ # - Define behaviour when encountering bad lines
49
+ reader_kwargs["on_bad_lines"] = "skip"
50
+
51
+ # - Define reader engine
52
+ # - C engine is faster
53
+ # - Python engine is more feature-complete
54
+ reader_kwargs["engine"] = "python"
55
+
56
+ # - Define on-the-fly decompression of on-disk data
57
+ # - Available: gzip, bz2, zip
58
+ reader_kwargs["compression"] = "infer"
59
+
60
+ # - Strings to recognize as NA/NaN and replace with standard NA flags
61
+ # - Already included: '#N/A', '#N/A N/A', '#NA', '-1.#IND', '-1.#QNAN',
62
+ # '-NaN', '-nan', '1.#IND', '1.#QNAN', '<NA>', 'N/A',
63
+ # 'NA', 'NULL', 'NaN', 'n/a', 'nan', 'null'
64
+ reader_kwargs["na_values"] = ["na", "", "error"]
65
+
66
+ ##------------------------------------------------------------------------.
67
+ #### Read the data
68
+ df = read_raw_text_file(
69
+ filepath=file,
70
+ column_names=column_names,
71
+ reader_kwargs=reader_kwargs,
72
+ logger=logger,
73
+ )
74
+
75
+ ##------------------------------------------------------------------------.
76
+ #### Adapt the dataframe to adhere to DISDRODB L0 standards
77
+ # Count number of delimiters to identify valid rows
78
+ df = df[df["TO_PARSE"].str.count(";") == 520]
79
+
80
+ # Check there are still valid rows
81
+ if len(df) == 0:
82
+ raise ValueError(f"No valid rows in {filename}.")
83
+
84
+ # Split by ; delimiter (before raw drop number)
85
+ df = df["TO_PARSE"].str.split(";", expand=True, n=79)
86
+
87
+ # Assign column names
88
+ column_names = [
89
+ "start_identifier",
90
+ "device_address",
91
+ "sensor_serial_number",
92
+ "sensor_date",
93
+ "sensor_time",
94
+ "weather_code_synop_4677_5min",
95
+ "weather_code_synop_4680_5min",
96
+ "weather_code_metar_4678_5min",
97
+ "precipitation_rate_5min",
98
+ "weather_code_synop_4677",
99
+ "weather_code_synop_4680",
100
+ "weather_code_metar_4678",
101
+ "precipitation_rate",
102
+ "rainfall_rate",
103
+ "snowfall_rate",
104
+ "precipitation_accumulated",
105
+ "mor_visibility",
106
+ "reflectivity",
107
+ "quality_index",
108
+ "max_hail_diameter",
109
+ "laser_status",
110
+ "static_signal_status",
111
+ "laser_temperature_analog_status",
112
+ "laser_temperature_digital_status",
113
+ "laser_current_analog_status",
114
+ "laser_current_digital_status",
115
+ "sensor_voltage_supply_status",
116
+ "current_heating_pane_transmitter_head_status",
117
+ "current_heating_pane_receiver_head_status",
118
+ "temperature_sensor_status",
119
+ "current_heating_voltage_supply_status",
120
+ "current_heating_house_status",
121
+ "current_heating_heads_status",
122
+ "current_heating_carriers_status",
123
+ "control_output_laser_power_status",
124
+ "reserved_status",
125
+ "temperature_interior",
126
+ "laser_temperature",
127
+ "laser_current_average",
128
+ "control_voltage",
129
+ "optical_control_voltage_output",
130
+ "sensor_voltage_supply",
131
+ "current_heating_pane_transmitter_head",
132
+ "current_heating_pane_receiver_head",
133
+ "temperature_ambient",
134
+ "current_heating_voltage_supply",
135
+ "current_heating_house",
136
+ "current_heating_heads",
137
+ "current_heating_carriers",
138
+ "number_particles",
139
+ "number_particles_internal_data",
140
+ "number_particles_min_speed",
141
+ "number_particles_min_speed_internal_data",
142
+ "number_particles_max_speed",
143
+ "number_particles_max_speed_internal_data",
144
+ "number_particles_min_diameter",
145
+ "number_particles_min_diameter_internal_data",
146
+ "number_particles_no_hydrometeor",
147
+ "number_particles_no_hydrometeor_internal_data",
148
+ "number_particles_unknown_classification",
149
+ "number_particles_unknown_classification_internal_data",
150
+ "number_particles_class_1",
151
+ "number_particles_class_1_internal_data",
152
+ "number_particles_class_2",
153
+ "number_particles_class_2_internal_data",
154
+ "number_particles_class_3",
155
+ "number_particles_class_3_internal_data",
156
+ "number_particles_class_4",
157
+ "number_particles_class_4_internal_data",
158
+ "number_particles_class_5",
159
+ "number_particles_class_5_internal_data",
160
+ "number_particles_class_6",
161
+ "number_particles_class_6_internal_data",
162
+ "number_particles_class_7",
163
+ "number_particles_class_7_internal_data",
164
+ "number_particles_class_8",
165
+ "number_particles_class_8_internal_data",
166
+ "number_particles_class_9",
167
+ "number_particles_class_9_internal_data",
168
+ "raw_drop_number",
169
+ ]
170
+ df.columns = column_names
171
+
172
+ # Deal with case if there are 61 timesteps
173
+ # - Occurs sometimes when previous hourly file miss timesteps
174
+ if len(df) == 61:
175
+ log_warning(logger=logger, msg=f"{filename} contains 61 timesteps. Dropping the first.")
176
+ df = df.iloc[1:]
177
+
178
+ # Raise error if more than 60 timesteps/rows
179
+ n_rows = len(df)
180
+ if n_rows > 60:
181
+ raise ValueError(f"The hourly file contains {n_rows} timesteps.")
182
+
183
+ # Infer and define "time" column
184
+ start_time_str = filename.split(".")[0] # '2024020200.txt'
185
+ start_time = pd.to_datetime(start_time_str, format="%Y%m%d%H")
186
+
187
+ # - Define timedelta based on sensor_time
188
+ # --> Add +24h to subsequent times when time resets
189
+ dt = pd.to_timedelta(df["sensor_time"]).to_numpy().astype("m8[s]")
190
+ rollover_indices = np.where(np.diff(dt) < np.timedelta64(0, "s"))[0]
191
+ if rollover_indices.size > 0:
192
+ for idx in rollover_indices:
193
+ dt[idx + 1 :] += np.timedelta64(24, "h")
194
+ dt = dt - dt[0]
195
+
196
+ # - Define approximate time
197
+ df["time"] = start_time + dt
198
+
199
+ # - Keep rows where time increment is between 00 and 59 minutes
200
+ valid_rows = dt <= np.timedelta64(3540, "s")
201
+ df = df[valid_rows]
202
+
203
+ # Drop rows with invalid raw_drop_number
204
+ # --> 440 value # 22x20
205
+ # --> 400 here # 20x20
206
+ df = df[df["raw_drop_number"].astype(str).str.len() == 1763]
207
+
208
+ # Drop columns not agreeing with DISDRODB L0 standards
209
+ columns_to_drop = [
210
+ "start_identifier",
211
+ "device_address",
212
+ "sensor_serial_number",
213
+ "sensor_date",
214
+ "sensor_time",
215
+ ]
216
+ df = df.drop(columns=columns_to_drop)
217
+ return df
218
+
219
+
220
+ @is_documented_by(reader_generic_docstring)
221
+ def reader(
222
+ filepath,
223
+ logger=None,
224
+ ):
225
+ """Reader."""
226
+ import zipfile
227
+
228
+ ##------------------------------------------------------------------------.
229
+ # filename = os.path.basename(filepath)
230
+ # return read_txt_file(file=filepath, filename=filename, logger=logger)
231
+
232
+ # ---------------------------------------------------------------------.
233
+ #### Iterate over all files (aka timesteps) in the daily zip archive
234
+ # - Each file contain a single timestep !
235
+ # list_df = []
236
+ # with tempfile.TemporaryDirectory() as temp_dir:
237
+ # # Extract all files
238
+ # unzip_file_on_terminal(filepath, temp_dir)
239
+
240
+ # # Walk through extracted files
241
+ # for root, _, files in os.walk(temp_dir):
242
+ # for filename in sorted(files):
243
+ # if filename.endswith(".txt"):
244
+ # full_path = os.path.join(root, filename)
245
+ # try:
246
+ # df = read_txt_file(file=full_path, filename=filename, logger=logger)
247
+ # if df is not None:
248
+ # list_df.append(df)
249
+ # except Exception as e:
250
+ # msg = f"An error occurred while reading {filename}: {e}"
251
+ # log_error(logger=logger, msg=msg, verbose=True)
252
+
253
+ list_df = []
254
+ with zipfile.ZipFile(filepath, "r") as zip_ref:
255
+ filenames = sorted(zip_ref.namelist())
256
+ for filename in filenames:
257
+ if filename.endswith(".txt"):
258
+ # Open file
259
+ with zip_ref.open(filename) as file:
260
+ try:
261
+ df = read_txt_file(file=file, filename=filename, logger=logger)
262
+ if df is not None:
263
+ list_df.append(df)
264
+ except Exception as e:
265
+ msg = f"An error occurred while reading {filename}. The error is: {e}"
266
+ log_error(logger=logger, msg=msg, verbose=True)
267
+
268
+ # Check the zip file contains at least some non.empty files
269
+ if len(list_df) == 0:
270
+ raise ValueError(f"{filepath} contains only empty files!")
271
+
272
+ # Concatenate all dataframes into a single one
273
+ df = pd.concat(list_df)
274
+
275
+ # ---------------------------------------------------------------------.
276
+ return df
@@ -86,7 +86,7 @@ def reader(
86
86
  df = df["TO_BE_SPLITTED"].str.split(";", expand=True, n=79)
87
87
 
88
88
  # Assign column names
89
- column_names = [
89
+ names = [
90
90
  "start_identifier",
91
91
  "device_address",
92
92
  "sensor_serial_number",
@@ -168,7 +168,7 @@ def reader(
168
168
  "number_particles_class_9_internal_data",
169
169
  "TO_BE_FURTHER_PROCESSED",
170
170
  ]
171
- df.columns = column_names
171
+ df.columns = names
172
172
 
173
173
  # Extract the last variables remained in raw_drop_number
174
174
  df_parsed = df["TO_BE_FURTHER_PROCESSED"].str.rsplit(";", n=5, expand=True)