disdrodb 0.1.5__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 (125) hide show
  1. disdrodb/__init__.py +1 -5
  2. disdrodb/_version.py +2 -2
  3. disdrodb/accessor/methods.py +22 -4
  4. disdrodb/api/checks.py +10 -0
  5. disdrodb/api/io.py +20 -18
  6. disdrodb/api/path.py +42 -77
  7. disdrodb/api/search.py +89 -23
  8. disdrodb/cli/disdrodb_create_summary.py +1 -1
  9. disdrodb/cli/disdrodb_run_l0.py +1 -1
  10. disdrodb/cli/disdrodb_run_l0a.py +1 -1
  11. disdrodb/cli/disdrodb_run_l0b.py +1 -1
  12. disdrodb/cli/disdrodb_run_l0c.py +1 -1
  13. disdrodb/cli/disdrodb_run_l1.py +1 -1
  14. disdrodb/cli/disdrodb_run_l2e.py +1 -1
  15. disdrodb/cli/disdrodb_run_l2m.py +1 -1
  16. disdrodb/configs.py +30 -83
  17. disdrodb/constants.py +4 -3
  18. disdrodb/data_transfer/download_data.py +4 -2
  19. disdrodb/docs.py +2 -2
  20. disdrodb/etc/products/L1/1MIN.yaml +13 -0
  21. disdrodb/etc/products/L1/LPM/1MIN.yaml +13 -0
  22. disdrodb/etc/products/L1/LPM_V0/1MIN.yaml +13 -0
  23. disdrodb/etc/products/L1/PARSIVEL/1MIN.yaml +13 -0
  24. disdrodb/etc/products/L1/PARSIVEL2/1MIN.yaml +13 -0
  25. disdrodb/etc/products/L1/PWS100/1MIN.yaml +13 -0
  26. disdrodb/etc/products/L1/RD80/1MIN.yaml +13 -0
  27. disdrodb/etc/products/L1/SWS250/1MIN.yaml +13 -0
  28. disdrodb/etc/products/L1/global.yaml +6 -0
  29. disdrodb/etc/products/L2E/10MIN.yaml +1 -12
  30. disdrodb/etc/products/L2E/global.yaml +1 -1
  31. disdrodb/etc/products/L2M/MODELS/NGAMMA_GS_R_MAE.yaml +6 -0
  32. disdrodb/etc/products/L2M/global.yaml +1 -1
  33. disdrodb/issue/checks.py +2 -2
  34. disdrodb/l0/check_configs.py +1 -1
  35. disdrodb/l0/configs/LPM/l0a_encodings.yml +0 -1
  36. disdrodb/l0/configs/LPM/l0b_cf_attrs.yml +0 -4
  37. disdrodb/l0/configs/LPM/l0b_encodings.yml +9 -9
  38. disdrodb/l0/configs/LPM/raw_data_format.yml +11 -11
  39. disdrodb/l0/configs/LPM_V0/bins_diameter.yml +103 -0
  40. disdrodb/l0/configs/LPM_V0/bins_velocity.yml +103 -0
  41. disdrodb/l0/configs/LPM_V0/l0a_encodings.yml +45 -0
  42. disdrodb/l0/configs/LPM_V0/l0b_cf_attrs.yml +180 -0
  43. disdrodb/l0/configs/LPM_V0/l0b_encodings.yml +410 -0
  44. disdrodb/l0/configs/LPM_V0/raw_data_format.yml +474 -0
  45. disdrodb/l0/configs/PARSIVEL/l0b_encodings.yml +1 -1
  46. disdrodb/l0/configs/PARSIVEL/raw_data_format.yml +8 -8
  47. disdrodb/l0/configs/PARSIVEL2/raw_data_format.yml +9 -9
  48. disdrodb/l0/l0_reader.py +2 -2
  49. disdrodb/l0/l0a_processing.py +6 -2
  50. disdrodb/l0/l0b_processing.py +26 -19
  51. disdrodb/l0/l0c_processing.py +17 -3
  52. disdrodb/l0/manuals/LPM_V0.pdf +0 -0
  53. disdrodb/l0/readers/LPM/ITALY/GID_LPM.py +15 -7
  54. disdrodb/l0/readers/LPM/ITALY/GID_LPM_PI.py +279 -0
  55. disdrodb/l0/readers/LPM/ITALY/GID_LPM_T.py +276 -0
  56. disdrodb/l0/readers/LPM/ITALY/GID_LPM_W.py +2 -2
  57. disdrodb/l0/readers/LPM/NETHERLANDS/DELFT_RWANDA_LPM_NC.py +103 -0
  58. disdrodb/l0/readers/LPM/NORWAY/HAUKELISETER_LPM.py +216 -0
  59. disdrodb/l0/readers/LPM/NORWAY/NMBU_LPM.py +208 -0
  60. disdrodb/l0/readers/LPM/UK/WITHWORTH_LPM.py +219 -0
  61. disdrodb/l0/readers/LPM/USA/CHARLESTON.py +229 -0
  62. disdrodb/l0/readers/{LPM → LPM_V0}/BELGIUM/ULIEGE.py +33 -49
  63. disdrodb/l0/readers/LPM_V0/ITALY/GID_LPM_V0.py +240 -0
  64. disdrodb/l0/readers/PARSIVEL/BASQUECOUNTRY/EUSKALMET_OTT.py +227 -0
  65. disdrodb/l0/readers/{PARSIVEL2 → PARSIVEL}/NASA/LPVEX.py +16 -28
  66. disdrodb/l0/readers/PARSIVEL/{GPM → NASA}/MC3E.py +1 -1
  67. disdrodb/l0/readers/PARSIVEL/NCAR/VORTEX2_2010_UF.py +3 -3
  68. disdrodb/l0/readers/PARSIVEL2/BASQUECOUNTRY/EUSKALMET_OTT2.py +232 -0
  69. disdrodb/l0/readers/PARSIVEL2/DENMARK/EROSION_raw.py +1 -1
  70. disdrodb/l0/readers/PARSIVEL2/JAPAN/PRECIP.py +155 -0
  71. disdrodb/l0/readers/PARSIVEL2/MPI/BCO_PARSIVEL2.py +14 -7
  72. disdrodb/l0/readers/PARSIVEL2/MPI/BOWTIE.py +8 -3
  73. disdrodb/l0/readers/PARSIVEL2/NASA/APU.py +28 -5
  74. disdrodb/l0/readers/PARSIVEL2/NCAR/RELAMPAGO_PARSIVEL2.py +1 -1
  75. disdrodb/l0/readers/PARSIVEL2/{GPM/GCPEX.py → NORWAY/UIB.py} +54 -29
  76. disdrodb/l0/readers/PARSIVEL2/PHILIPPINES/{PANGASA.py → PAGASA.py} +6 -3
  77. disdrodb/l0/readers/PARSIVEL2/SPAIN/GRANADA.py +1 -1
  78. disdrodb/l0/readers/PARSIVEL2/SWEDEN/SMHI.py +189 -0
  79. disdrodb/l0/readers/{PARSIVEL/GPM/PIERS.py → PARSIVEL2/USA/CSU.py} +62 -29
  80. disdrodb/l0/readers/PARSIVEL2/USA/{C3WE.py → CW3E.py} +51 -24
  81. disdrodb/l0/readers/{PARSIVEL/GPM/IFLOODS.py → RD80/BRAZIL/ATTO_RD80.py} +50 -34
  82. disdrodb/l0/readers/{SW250 → SWS250}/BELGIUM/KMI.py +1 -1
  83. disdrodb/l1/beard_model.py +45 -1
  84. disdrodb/l1/fall_velocity.py +1 -6
  85. disdrodb/l1/filters.py +2 -0
  86. disdrodb/l1/processing.py +6 -5
  87. disdrodb/l1/resampling.py +101 -38
  88. disdrodb/l2/empirical_dsd.py +12 -8
  89. disdrodb/l2/processing.py +4 -3
  90. disdrodb/metadata/search.py +3 -4
  91. disdrodb/routines/l0.py +4 -4
  92. disdrodb/routines/l1.py +173 -60
  93. disdrodb/routines/l2.py +121 -269
  94. disdrodb/routines/options.py +347 -0
  95. disdrodb/routines/wrappers.py +9 -1
  96. disdrodb/scattering/axis_ratio.py +3 -0
  97. disdrodb/scattering/routines.py +1 -1
  98. disdrodb/summary/routines.py +765 -724
  99. disdrodb/utils/archiving.py +51 -44
  100. disdrodb/utils/attrs.py +1 -1
  101. disdrodb/utils/compression.py +4 -2
  102. disdrodb/utils/dask.py +35 -15
  103. disdrodb/utils/dict.py +33 -0
  104. disdrodb/utils/encoding.py +1 -1
  105. disdrodb/utils/manipulations.py +7 -1
  106. disdrodb/utils/routines.py +9 -8
  107. disdrodb/utils/time.py +9 -1
  108. disdrodb/viz/__init__.py +0 -13
  109. disdrodb/viz/plots.py +209 -0
  110. {disdrodb-0.1.5.dist-info → disdrodb-0.2.1.dist-info}/METADATA +1 -1
  111. {disdrodb-0.1.5.dist-info → disdrodb-0.2.1.dist-info}/RECORD +124 -95
  112. disdrodb/l0/readers/PARSIVEL/GPM/LPVEX.py +0 -85
  113. /disdrodb/etc/products/L2M/{GAMMA_GS_ND_MAE.yaml → MODELS/GAMMA_GS_ND_MAE.yaml} +0 -0
  114. /disdrodb/etc/products/L2M/{GAMMA_ML.yaml → MODELS/GAMMA_ML.yaml} +0 -0
  115. /disdrodb/etc/products/L2M/{LOGNORMAL_GS_LOG_ND_MAE.yaml → MODELS/LOGNORMAL_GS_LOG_ND_MAE.yaml} +0 -0
  116. /disdrodb/etc/products/L2M/{LOGNORMAL_GS_ND_MAE.yaml → MODELS/LOGNORMAL_GS_ND_MAE.yaml} +0 -0
  117. /disdrodb/etc/products/L2M/{LOGNORMAL_ML.yaml → MODELS/LOGNORMAL_ML.yaml} +0 -0
  118. /disdrodb/etc/products/L2M/{NGAMMA_GS_LOG_ND_MAE.yaml → MODELS/NGAMMA_GS_LOG_ND_MAE.yaml} +0 -0
  119. /disdrodb/etc/products/L2M/{NGAMMA_GS_ND_MAE.yaml → MODELS/NGAMMA_GS_ND_MAE.yaml} +0 -0
  120. /disdrodb/etc/products/L2M/{NGAMMA_GS_Z_MAE.yaml → MODELS/NGAMMA_GS_Z_MAE.yaml} +0 -0
  121. /disdrodb/l0/readers/PARSIVEL2/{GPM → NASA}/NSSTC.py +0 -0
  122. {disdrodb-0.1.5.dist-info → disdrodb-0.2.1.dist-info}/WHEEL +0 -0
  123. {disdrodb-0.1.5.dist-info → disdrodb-0.2.1.dist-info}/entry_points.txt +0 -0
  124. {disdrodb-0.1.5.dist-info → disdrodb-0.2.1.dist-info}/licenses/LICENSE +0 -0
  125. {disdrodb-0.1.5.dist-info → disdrodb-0.2.1.dist-info}/top_level.txt +0 -0
@@ -130,8 +130,8 @@ def reader(
130
130
  # "23": "station_number",
131
131
  "24": "rainfall_amount_absolute_32bit",
132
132
  # "25": "error_code",
133
- # "30": "rainfall_rate_16_bit_30",
134
- # "31": "rainfall_rate_16_bit_1200",
133
+ # "30": "rainfall_rate_16bit",
134
+ # "31": "rainfall_rate_12bit",
135
135
  "32": "rainfall_accumulated_16bit",
136
136
  # "90": "raw_drop_concentration",
137
137
  # "91": "raw_drop_average_velocity",
@@ -168,7 +168,7 @@ def reader(
168
168
  df = df.drop(columns=columns_to_drop)
169
169
 
170
170
  # Stations UF4-7 have NAN at the end of the raw drop number
171
- df["raw_drop_number"] = df["raw_drop_number"].str.replace("NaN;", "").iloc[0]
171
+ df["raw_drop_number"] = df["raw_drop_number"].str.replace("NaN;", "")
172
172
 
173
173
  # Return the dataframe adhering to DISDRODB L0 standards
174
174
  return df
@@ -0,0 +1,232 @@
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 EUSKALMET OTT Parsivel 2 raw data."""
18
+ # import os
19
+ # import tempfile
20
+ # from disdrodb.utils.compression import unzip_file_on_terminal
21
+
22
+ import numpy as np
23
+ import pandas as pd
24
+
25
+ from disdrodb.l0.l0_reader import is_documented_by, reader_generic_docstring
26
+ from disdrodb.l0.l0a_processing import read_raw_text_file
27
+ from disdrodb.utils.logger import log_error
28
+
29
+ COLUMN_DICT = {
30
+ "01": "rainfall_rate_32bit",
31
+ "02": "rainfall_accumulated_32bit",
32
+ "03": "weather_code_synop_4680",
33
+ "04": "weather_code_synop_4677",
34
+ "05": "weather_code_metar_4678", # empty
35
+ "06": "weather_code_nws", # empty
36
+ "07": "reflectivity_32bit",
37
+ "08": "mor_visibility",
38
+ "09": "sample_interval",
39
+ "10": "laser_amplitude",
40
+ "11": "number_particles",
41
+ "12": "sensor_temperature",
42
+ # "13": "sensor_serial_number",
43
+ # "14": "firmware_iop",
44
+ # "15": "firmware_dsp",
45
+ "16": "sensor_heating_current",
46
+ "17": "sensor_battery_voltage",
47
+ "18": "sensor_status",
48
+ # "19": "start_time",
49
+ # "20": "sensor_time",
50
+ # "21": "sensor_date",
51
+ # "22": "station_name",
52
+ # "23": "station_number",
53
+ "24": "rainfall_amount_absolute_32bit",
54
+ "25": "error_code",
55
+ "26": "sensor_temperature_pcb",
56
+ "27": "sensor_temperature_receiver",
57
+ "28": "sensor_temperature_trasmitter",
58
+ "30": "rainfall_rate_16_bit_30",
59
+ "31": "rainfall_rate_16_bit_1200",
60
+ "32": "rainfall_accumulated_16bit",
61
+ "34": "rain_kinetic_energy",
62
+ "35": "snowfall_rate",
63
+ "90": "raw_drop_concentration",
64
+ "91": "raw_drop_average_velocity",
65
+ "93": "raw_drop_number",
66
+ }
67
+
68
+
69
+ def infill_missing_columns(df):
70
+ """Infill with NaN missing columns."""
71
+ columns = set(COLUMN_DICT.values())
72
+ for c in columns:
73
+ if c not in df.columns:
74
+ df[c] = "NaN"
75
+ return df
76
+
77
+
78
+ def read_txt_file(file, filename, logger):
79
+ """Parse a single txt file within the daily zip file."""
80
+ ##------------------------------------------------------------------------.
81
+ #### Define column names
82
+ column_names = ["TO_PARSE"]
83
+
84
+ ##------------------------------------------------------------------------.
85
+ #### Define reader options
86
+ reader_kwargs = {}
87
+ # - Define delimiter
88
+ reader_kwargs["delimiter"] = "\\n"
89
+ # - Skip first row as columns names
90
+ # - Define encoding
91
+ reader_kwargs["encoding"] = "latin" # "ISO-8859-1"
92
+ # - Avoid first column to become df index !!!
93
+ reader_kwargs["index_col"] = False
94
+ # - Define behaviour when encountering bad lines
95
+ reader_kwargs["on_bad_lines"] = "skip"
96
+ # - Define reader engine
97
+ # - C engine is faster
98
+ # - Python engine is more feature-complete
99
+ reader_kwargs["engine"] = "python"
100
+ # - Define on-the-fly decompression of on-disk data
101
+ # - Available: gzip, bz2, zip
102
+ reader_kwargs["compression"] = "infer"
103
+ # - Strings to recognize as NA/NaN and replace with standard NA flags
104
+ # - Already included: '#N/A', '#N/A N/A', '#NA', '-1.#IND', '-1.#QNAN',
105
+ # '-NaN', '-nan', '1.#IND', '1.#QNAN', '<NA>', 'N/A',
106
+ # 'NA', 'NULL', 'NaN', 'n/a', 'nan', 'null'
107
+ reader_kwargs["na_values"] = ["na", "", "error"]
108
+
109
+ ##------------------------------------------------------------------------.
110
+ #### Read the data
111
+ df = read_raw_text_file(
112
+ filepath=file,
113
+ column_names=column_names,
114
+ reader_kwargs=reader_kwargs,
115
+ logger=logger,
116
+ )
117
+
118
+ ##--------------------------------\----------------------------------------.
119
+ #### Adapt the dataframe to adhere to DISDRODB L0 standards
120
+ # Empty file, raise error
121
+ if len(df) == 0:
122
+ raise ValueError(f"{filename} is empty.")
123
+
124
+ # Select rows with valid spectrum
125
+ # df = df[df["TO_PARSE"].str.count(";") == 1191] # 1112
126
+
127
+ # Raise error if corrupted file
128
+ if len(df) == 4:
129
+ raise ValueError(f"{filename} is corrupted.")
130
+
131
+ # Extract string
132
+ string = df["TO_PARSE"].iloc[4]
133
+
134
+ # Split into lines
135
+ decoded_text = string.encode().decode("unicode_escape")
136
+ decoded_text = decoded_text.replace("'", "").replace('"', "")
137
+ lines = decoded_text.split()
138
+
139
+ # Extract time
140
+ time_str = lines[0].split(",")[1]
141
+
142
+ # Split each line at the first colon
143
+ data = [line.split(":", 1) for line in lines if ":" in line]
144
+
145
+ # Create the DataFrame
146
+ df = pd.DataFrame(data, columns=["ID", "Value"])
147
+
148
+ # Drop rows with invalid IDs
149
+ valid_id_str = np.char.rjust(np.arange(0, 94).astype(str), width=2, fillchar="0")
150
+ df = df[df["ID"].astype(str).isin(valid_id_str)]
151
+
152
+ # Select only rows with values
153
+ df = df[df["Value"].apply(lambda x: x is not None)]
154
+
155
+ # Reshape dataframe
156
+ df = df.set_index("ID").T
157
+
158
+ # Assign column names
159
+ df = df.rename(COLUMN_DICT, axis=1)
160
+
161
+ # Keep only columns defined in the dictionary
162
+ df = df.filter(items=list(COLUMN_DICT.values()))
163
+
164
+ # Infill missing columns
165
+ df = infill_missing_columns(df)
166
+
167
+ # Add time column ad datetime dtype
168
+ df["time"] = pd.to_datetime(time_str, format="%Y%m%d%H%M%S", errors="coerce")
169
+
170
+ # Preprocess the raw spectrum and raw_drop_average_velocity
171
+ # - Add 0 before every ; if ; not preceded by a digit
172
+ # - Example: ';;1;;' --> '0;0;1;0;'
173
+ df["raw_drop_number"] = df["raw_drop_number"].str.replace(r"(?<!\d);", "0;", regex=True)
174
+ df["raw_drop_average_velocity"] = df["raw_drop_average_velocity"].str.replace(r"(?<!\d);", "0;", regex=True)
175
+
176
+ # Return the dataframe adhering to DISDRODB L0 standards
177
+ return df
178
+
179
+
180
+ @is_documented_by(reader_generic_docstring)
181
+ def reader(
182
+ filepath,
183
+ logger=None,
184
+ ):
185
+ """Reader."""
186
+ import zipfile
187
+
188
+ # ---------------------------------------------------------------------.
189
+ #### Iterate over all files (aka timesteps) in the daily zip archive
190
+ # - Each file contain a single timestep !
191
+ # list_df = []
192
+ # with tempfile.TemporaryDirectory() as temp_dir:
193
+ # # Extract all files
194
+ # unzip_file_on_terminal(filepath, temp_dir)
195
+
196
+ # # Walk through extracted files
197
+ # for root, _, files in os.walk(temp_dir):
198
+ # for filename in sorted(files):
199
+ # if filename.endswith(".txt"):
200
+ # full_path = os.path.join(root, filename)
201
+ # try:
202
+ # df = read_txt_file(file=full_path, filename=filename, logger=logger)
203
+ # if df is not None:
204
+ # list_df.append(df)
205
+ # except Exception as e:
206
+ # msg = f"An error occurred while reading {filename}: {e}"
207
+ # log_error(logger=logger, msg=msg, verbose=True)
208
+
209
+ list_df = []
210
+ with zipfile.ZipFile(filepath, "r") as zip_ref:
211
+ filenames = sorted(zip_ref.namelist())
212
+ for filename in filenames:
213
+ if filename.endswith(".dat"):
214
+ # Open file
215
+ with zip_ref.open(filename) as file:
216
+ try:
217
+ df = read_txt_file(file=file, filename=filename, logger=logger)
218
+ if df is not None:
219
+ list_df.append(df)
220
+ except Exception as e:
221
+ msg = f"An error occurred while reading {filename}. The error is: {e}."
222
+ log_error(logger=logger, msg=msg, verbose=True)
223
+
224
+ # Check the zip file contains at least some non.empty files
225
+ if len(list_df) == 0:
226
+ raise ValueError(f"{filepath} contains only empty files!")
227
+
228
+ # Concatenate all dataframes into a single one
229
+ df = pd.concat(list_df)
230
+
231
+ # ---------------------------------------------------------------------.
232
+ return df
@@ -184,7 +184,7 @@ def read_par_format(filepath, logger):
184
184
  # Retrieve raw array
185
185
  df_split = df["TO_SPLIT"].str.split(",", expand=True)
186
186
  df["raw_drop_concentration"] = df_split.iloc[:, :32].agg(",".join, axis=1)
187
- df["raw_drop_average_velocity"] = df_split.iloc[:, 32:].agg(",".join, axis=1)
187
+ df["raw_drop_average_velocity"] = df_split.iloc[:, 32:64].agg(",".join, axis=1)
188
188
  df["raw_drop_number"] = df_split.iloc[:, 64:].agg(",".join, axis=1)
189
189
  df["raw_drop_number"] = df["raw_drop_number"].str.replace("-9", "0")
190
190
  del df_split
@@ -0,0 +1,155 @@
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 Colorado State University PRECIP OTT Parsivel 2 raw data."""
18
+
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
+
24
+
25
+ @is_documented_by(reader_generic_docstring)
26
+ def reader(
27
+ filepath,
28
+ logger=None,
29
+ ):
30
+ """Reader."""
31
+ ##------------------------------------------------------------------------.
32
+ #### Define column names
33
+ column_names = ["TO_PARSE"]
34
+
35
+ ##------------------------------------------------------------------------.
36
+ #### Define reader options
37
+ reader_kwargs = {}
38
+
39
+ # - Define delimiter
40
+ reader_kwargs["delimiter"] = "\\n"
41
+
42
+ # - Skip first row as columns names
43
+ reader_kwargs["header"] = None
44
+
45
+ # - Skip header
46
+ reader_kwargs["skiprows"] = 0
47
+
48
+ # - Define encoding
49
+ reader_kwargs["encoding"] = "ISO-8859-1"
50
+
51
+ # - Avoid first column to become df index !!!
52
+ reader_kwargs["index_col"] = False
53
+
54
+ # - Define behaviour when encountering bad lines
55
+ reader_kwargs["on_bad_lines"] = "skip"
56
+
57
+ # - Define reader engine
58
+ # - C engine is faster
59
+ # - Python engine is more feature-complete
60
+ reader_kwargs["engine"] = "python"
61
+
62
+ # - Define on-the-fly decompression of on-disk data
63
+ # - Available: gzip, bz2, zip
64
+ # reader_kwargs['compression'] = 'xz'
65
+
66
+ # - Strings to recognize as NA/NaN and replace with standard NA flags
67
+ # - Already included: '#N/A', '#N/A N/A', '#NA', '-1.#IND', '-1.#QNAN',
68
+ # '-NaN', '-nan', '1.#IND', '1.#QNAN', '<NA>', 'N/A',
69
+ # 'NA', 'NULL', 'NaN', 'n/a', 'nan', 'null'
70
+ reader_kwargs["na_values"] = ["na", "error", "-.-", " NA"]
71
+
72
+ ##------------------------------------------------------------------------.
73
+ #### Read the data
74
+ df = read_raw_text_file(
75
+ filepath=filepath,
76
+ column_names=column_names,
77
+ reader_kwargs=reader_kwargs,
78
+ logger=logger,
79
+ )
80
+
81
+ ##------------------------------------------------------------------------.
82
+ #### Adapt the dataframe to adhere to DISDRODB L0 standards
83
+ # Raise error if empty file
84
+ if len(df) == 0:
85
+ raise ValueError(f"{filepath} is empty.")
86
+
87
+ # Select only rows with expected number of delimiters
88
+ df = df[df["TO_PARSE"].str.count(",") == 1041]
89
+
90
+ # Raise error if no data left
91
+ if len(df) == 0:
92
+ raise ValueError(f"No valid data in {filepath}.")
93
+
94
+ # Split into columns
95
+ df = df["TO_PARSE"].str.split(",", expand=True, n=17)
96
+
97
+ # Assign columns names
98
+ names = [
99
+ "date",
100
+ "time",
101
+ "rainfall_rate_32bit",
102
+ "rainfall_accumulated_32bit",
103
+ "weather_code_synop_4680",
104
+ "weather_code_metar_4678",
105
+ "weather_code_nws",
106
+ "reflectivity_32bit",
107
+ "mor_visibility",
108
+ "laser_amplitude",
109
+ "number_particles",
110
+ "sensor_temperature",
111
+ "sensor_heating_current",
112
+ "sensor_battery_voltage",
113
+ "sensor_status",
114
+ "rain_kinetic_energy",
115
+ "snowfall_rate",
116
+ "raw_drop_number",
117
+ ]
118
+ df.columns = names
119
+
120
+ # Add datetime time column
121
+ time_str = df["date"] + "-" + df["time"]
122
+ df["time"] = pd.to_datetime(time_str, format="%d.%m.%Y-%H:%M:%S", errors="coerce")
123
+
124
+ # Derive the raw spectrum
125
+ # Remove <SPECTRUM> and </SPECTRUM> prefix and suffix from the raw_drop_number field
126
+ df["raw_drop_number"] = df["raw_drop_number"].astype("string")
127
+ df["raw_drop_number"] = df["raw_drop_number"].str.replace("<SPECTRUM>", "")
128
+ df["raw_drop_number"] = df["raw_drop_number"].str.replace("</SPECTRUM>", "")
129
+
130
+ # Preprocess the raw spectrum and raw_drop_average_velocity
131
+ # - Add 0 before every ; if ; not preceded by a digit
132
+ # - Example: ';;1;;' --> '0;0;1;0;'
133
+ df["raw_drop_number"] = df["raw_drop_number"].str.replace(r"(?<!\d),", "0,", regex=True)
134
+
135
+ # Infill missing timesteps with raw_drop_number = 0 spectrum
136
+ # - Define the full time range with 30-second frequency
137
+ full_time_index = pd.date_range(start=df["time"].iloc[0], end=df["time"].iloc[-1], freq="30s")
138
+
139
+ # - Reindex the DataFrame to include all 30-second timesteps
140
+ df = df.set_index("time").reindex(full_time_index)
141
+
142
+ # - Fill missing raw_drop_number with 0
143
+ df["raw_drop_number"] = df["raw_drop_number"].fillna(0)
144
+
145
+ # - Restore 'time' as a column
146
+ df = df.rename_axis("time").reset_index()
147
+
148
+ # Drop columns not agreeing with DISDRODB L0 standards
149
+ columns_to_drop = [
150
+ "date",
151
+ ]
152
+ df = df.drop(columns=columns_to_drop)
153
+
154
+ # Return the dataframe adhering to DISDRODB L0 standards
155
+ return df
@@ -38,11 +38,14 @@ def reader(
38
38
  # - Define delimiter
39
39
  reader_kwargs["delimiter"] = "/\n"
40
40
 
41
- # Skip first row as columns names
41
+ # - Skip first row as columns names
42
42
  reader_kwargs["header"] = None
43
43
 
44
- # Skip first 2 rows
45
- reader_kwargs["skiprows"] = 1
44
+ # - Skip first 2 rows
45
+ reader_kwargs["skiprows"] = 0
46
+
47
+ # - Define encoding
48
+ reader_kwargs["encoding"] = "ISO-8859-1"
46
49
 
47
50
  # - Avoid first column to become df index !!!
48
51
  reader_kwargs["index_col"] = False
@@ -76,12 +79,17 @@ def reader(
76
79
 
77
80
  ##------------------------------------------------------------------------.
78
81
  #### Adapt the dataframe to adhere to DISDRODB L0 standards
79
- # Remove rows with invalid length
80
- # df = df[df["TO_BE_PARSED"].str.len().isin([4664])]
82
+ # Raise error if empty file
83
+ if len(df) == 0:
84
+ raise ValueError(f"{filepath} is empty.")
81
85
 
82
- # Count number of delimiters to select valid rows
86
+ # Select only rows with expected number of delimiters
83
87
  df = df[df["TO_BE_PARSED"].str.count(";") == 1107]
84
88
 
89
+ # Raise error if no data left
90
+ if len(df) == 0:
91
+ raise ValueError(f"No valid data in {filepath}.")
92
+
85
93
  # Split by ; delimiter
86
94
  df = df["TO_BE_PARSED"].str.split(";", expand=True, n=19)
87
95
 
@@ -132,5 +140,4 @@ def reader(
132
140
  "sample_interval",
133
141
  ]
134
142
  df = df.drop(columns=columns_to_drop)
135
-
136
143
  return df
@@ -157,12 +157,17 @@ def reader(
157
157
 
158
158
  ##------------------------------------------------------------------------.
159
159
  #### Adapt the dataframe to adhere to DISDRODB L0 standards
160
- # Remove rows with invalid length
161
- # df = df[df["TO_BE_PARSED"].str.len().isin([4664])]
160
+ # Raise error if empty file
161
+ if len(df) == 0:
162
+ raise ValueError(f"{filepath} is empty.")
162
163
 
163
- # Count number of delimiters to select valid rows
164
+ # Select only rows with expected number of delimiters
164
165
  df = df[df["TO_BE_PARSED"].str.count(";") == 1107]
165
166
 
167
+ # Raise error if no data left
168
+ if len(df) == 0:
169
+ raise ValueError(f"No valid data in {filepath}.")
170
+
166
171
  # Split by ; delimiter
167
172
  df = df["TO_BE_PARSED"].str.split(";", expand=True, n=19)
168
173
 
@@ -44,13 +44,13 @@ def reader(
44
44
  """Reader."""
45
45
  ##------------------------------------------------------------------------.
46
46
  #### Define column names
47
- column_names = ["time", "TO_BE_SPLITTED"]
47
+ column_names = ["TO_PARSE"]
48
48
 
49
49
  ##------------------------------------------------------------------------.
50
50
  #### Define reader options
51
51
  reader_kwargs = {}
52
52
  # - Define delimiter
53
- reader_kwargs["delimiter"] = ";"
53
+ reader_kwargs["delimiter"] = "//n"
54
54
  # - Skip first row as columns names
55
55
  reader_kwargs["header"] = None
56
56
  reader_kwargs["skiprows"] = 0
@@ -84,6 +84,20 @@ def reader(
84
84
 
85
85
  ##------------------------------------------------------------------------.
86
86
  #### Adapt the dataframe to adhere to DISDRODB L0 standards
87
+ # Remove rows with invalid number of separators
88
+ df = df[df["TO_PARSE"].str.count(";") == 1]
89
+ if len(df) == 0:
90
+ raise ValueError(f"No valid data in {filepath}")
91
+
92
+ # Retrieve time and telegram field
93
+ df = df["TO_PARSE"].str.split(";", expand=True)
94
+ df.columns = ["time", "TO_BE_SPLITTED"]
95
+
96
+ # Remove rows with invalid number of separators
97
+ df = df[df["TO_BE_SPLITTED"].str.count(",") == 1033]
98
+ if len(df) == 0:
99
+ raise ValueError(f"No valid data in {filepath}")
100
+
87
101
  # Convert time column to datetime
88
102
  df_time = pd.to_datetime(df["time"], format="%Y%m%d%H%M%S", errors="coerce")
89
103
 
@@ -91,7 +105,7 @@ def reader(
91
105
  df = df["TO_BE_SPLITTED"].str.split(",", n=9, expand=True)
92
106
 
93
107
  # Assign column names
94
- names = [
108
+ columns_names = [
95
109
  "station_name",
96
110
  "sensor_status",
97
111
  "sensor_temperature",
@@ -103,7 +117,7 @@ def reader(
103
117
  "weather_code_synop_4677",
104
118
  "raw_drop_number",
105
119
  ]
106
- df.columns = names
120
+ df.columns = columns_names
107
121
 
108
122
  # Add the time column
109
123
  df["time"] = df_time
@@ -111,10 +125,19 @@ def reader(
111
125
  # Drop columns not agreeing with DISDRODB L0 standards
112
126
  df = df.drop(columns=["station_name"])
113
127
 
128
+ # Remove rows with invalid raw drop number
129
+ # --> Occurs e.g. in UCONN apu28
130
+ # def mask_invalid_raw_drop_number(df)
131
+ # df_split = df["raw_drop_number"].str.split(",", expand=True)
132
+ # idx = np.where(np.any(df_split.astype(float) > 998, axis=1))[0]
133
+ # df.loc[idx, "raw_drop_number"] = "NaN"
134
+ # return df
135
+ df = df[df["raw_drop_number"].str.len() == 4096]
136
+
114
137
  # Drop rows with invalid values
115
138
  # --> Ensure that weather_code_synop_4677 has length 2
116
139
  # --> If a previous column is missing it will have 000
117
- df = df[df["weather_code_synop_4677"].str.len() == 2]
140
+ # df = df[df["weather_code_synop_4677"].str.len() == 2]
118
141
 
119
142
  # Return the dataframe adhering to DISDRODB L0 standards
120
143
  return df
@@ -42,7 +42,7 @@ def reader(
42
42
  # - Define encoding
43
43
  reader_kwargs["encoding"] = "ISO-8859-1"
44
44
 
45
- # Skip first row as columns names
45
+ # - Skip first row as columns names
46
46
  reader_kwargs["header"] = None
47
47
 
48
48
  # - Avoid first column to become df index !!!