mertisreader 0.0.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.
@@ -0,0 +1,2 @@
1
+ __version__ = "0.0.1"
2
+ from .core import *
@@ -0,0 +1,32 @@
1
+ # Autogenerated by nbdev
2
+
3
+ d = { 'settings': { 'branch': 'master',
4
+ 'doc_baseurl': '/mertisreader',
5
+ 'doc_host': '/',
6
+ 'git_url': 'https://gitlab.com/damo_ma/mertisreader/tree/master/',
7
+ 'lib_path': 'mertisreader'},
8
+ 'syms': { 'mertisreader.core': { 'mertisreader.core.MERTISDataPackReader': ('core.html#mertisdatapackreader', 'mertisreader/core.py'),
9
+ 'mertisreader.core.MERTISDataPackReader.__init__': ( 'core.html#mertisdatapackreader.__init__',
10
+ 'mertisreader/core.py'),
11
+ 'mertisreader.core.MERTISDataPackReader.data_assembler': ( 'core.html#mertisdatapackreader.data_assembler',
12
+ 'mertisreader/core.py'),
13
+ 'mertisreader.core.MERTISDataPackReader.data_collector': ( 'core.html#mertisdatapackreader.data_collector',
14
+ 'mertisreader/core.py'),
15
+ 'mertisreader.core.MERTISDataPackReader.filetypes2dict': ( 'core.html#mertisdatapackreader.filetypes2dict',
16
+ 'mertisreader/core.py'),
17
+ 'mertisreader.core.MERTISDataPackReader.get_fits_files': ( 'core.html#mertisdatapackreader.get_fits_files',
18
+ 'mertisreader/core.py'),
19
+ 'mertisreader.core.MERTISDataPackReader.get_input_path_dict': ( 'core.html#mertisdatapackreader.get_input_path_dict',
20
+ 'mertisreader/core.py'),
21
+ 'mertisreader.core.MERTISDataPackReader.listfiletypes': ( 'core.html#mertisdatapackreader.listfiletypes',
22
+ 'mertisreader/core.py'),
23
+ 'mertisreader.core.MERTISDataPackReader.save_plot': ( 'core.html#mertisdatapackreader.save_plot',
24
+ 'mertisreader/core.py'),
25
+ 'mertisreader.core.MERTISDataPackReader.set_logger': ( 'core.html#mertisdatapackreader.set_logger',
26
+ 'mertisreader/core.py'),
27
+ 'mertisreader.core.MERTISDataPackReader.set_output_dir': ( 'core.html#mertisdatapackreader.set_output_dir',
28
+ 'mertisreader/core.py'),
29
+ 'mertisreader.core.MERTISDataPackReader.show_files': ( 'core.html#mertisdatapackreader.show_files',
30
+ 'mertisreader/core.py'),
31
+ 'mertisreader.core.extract_mertis_hk_columns': ( 'core.html#extract_mertis_hk_columns',
32
+ 'mertisreader/core.py')}}}
mertisreader/_nbdev.py ADDED
@@ -0,0 +1,14 @@
1
+ # AUTOGENERATED BY NBDEV! DO NOT EDIT!
2
+
3
+ __all__ = ["index", "modules", "custom_doc_links", "git_url"]
4
+
5
+ index = {"extract_mertis_hk_columns": "00_core.ipynb",
6
+ "MERTISSessionReader": "00_core.ipynb"}
7
+
8
+ modules = ["core.py"]
9
+
10
+ doc_url = "//mertisreader"
11
+
12
+ git_url = "https://gitlab.com/damo_ma/mertisreader/tree/master/"
13
+
14
+ def custom_doc_links(name): return None
mertisreader/core.py ADDED
@@ -0,0 +1,381 @@
1
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_core.ipynb.
2
+
3
+ # %% auto 0
4
+ __all__ = ['extract_mertis_hk_columns', 'MERTISDataPackReader']
5
+
6
+ # %% ../nbs/00_core.ipynb 2
7
+ import pathlib
8
+ import re
9
+ import rich
10
+ import numpy as np
11
+ import pandas as pd
12
+ import logging
13
+ from typing import Union
14
+
15
+ # %% ../nbs/00_core.ipynb 4
16
+ def extract_mertis_hk_columns(in_path):
17
+ """
18
+ Extracts column names from an MERTIS HK XML file.
19
+
20
+ Args:
21
+ in_path (pathlib.Path): Path to the input file.
22
+
23
+ Returns:
24
+ list: List of column names.
25
+ """
26
+ import xmltodict
27
+
28
+ # Create the path to the XML file by appending '.xml' to the input path.
29
+ in_file = in_path.with_suffix('.xml')
30
+
31
+ # Open the XML file in read binary mode and parse it using xmltodict.
32
+ with open(in_file, "rb") as f:
33
+ obj = xmltodict.parse(f, xml_attribs=False)
34
+
35
+ # Extract the column names from the parsed XML object.
36
+ # The XML structure is assumed to be consistent with the provided example.
37
+ return [x['name'] for x in obj['Product_Observational']['File_Area_Observational']['Table_Delimited']['Record_Delimited']['Field_Delimited']]
38
+
39
+
40
+ class MERTISDataPackReader:
41
+ """
42
+ Class to read and process MERTIS data.
43
+
44
+ Attributes:
45
+ input_dir (pathlib.Path): Input directory.
46
+ output_dir (pathlib.Path): Output directory.
47
+ log_level (str): Log level.
48
+ fits_files (list): List of FITS files.
49
+ input_path_dict (dict): Dictionary of input paths.
50
+ collect_data (dict): Dictionary of collected data.
51
+ """
52
+ def __init__(self, input_dir, output_dir='', log_level=''):
53
+ """
54
+ Initialize the MERTISDataPackReader.
55
+
56
+ Args:
57
+ input_dir (str or pathlib.Path): Input directory.
58
+ output_dir (str or pathlib.Path, optional): Output directory. Defaults to ''.
59
+ log_level (str, optional): Log level. Defaults to ''.
60
+ """
61
+ self.input_dir = pathlib.Path(input_dir)
62
+ self.output_dir = self.set_output_dir(output_dir)
63
+ self.log_level = log_level
64
+ self.log = self.set_logger()
65
+ logging.info(f'{input_dir=}')
66
+ self.fits_files = self.get_fits_files()
67
+ self.input_path_dict = self.get_input_path_dict()
68
+
69
+ def set_output_dir(self, output_dir):
70
+ """
71
+ Set the output directory.
72
+
73
+ Args:
74
+ output_dir (str or pathlib.Path): Output directory.
75
+
76
+ Returns:
77
+ pathlib.Path: Output directory.
78
+ """
79
+ if output_dir:
80
+ return pathlib.Path(output_dir)
81
+ else:
82
+ return self.input_dir.parent / f'{self.input_dir.name}-analysis_products'
83
+
84
+ def set_logger(self):
85
+ """
86
+ Set the logger.
87
+ """
88
+ log_level = 'WARNING' if not self.log_level else self.log_level
89
+ logging.basicConfig(format='%(asctime)s|%(process)d|%(levelname)s|%(message)s',
90
+ level=logging.getLevelName(log_level))
91
+ logger = logging.getLogger()
92
+ return logger
93
+
94
+ def get_fits_files(self):
95
+ """
96
+ Get the list of FITS files.
97
+
98
+ Returns:
99
+ list: List of FITS files.
100
+ """
101
+ return list(self.input_dir.glob('**/*tis*.fits')) + \
102
+ [i for i in self.input_dir.glob('**/*_hk_*.dat') if 'tis' not in i.stem and 'tir' not in i.stem]
103
+
104
+ def get_input_path_dict(self):
105
+ """
106
+ Get the dictionary of input paths.
107
+
108
+ Returns:
109
+ dict: Dictionary of input paths.
110
+ """
111
+ files_type = ['hk_default', 'hk_extended', 'sc_tis', 'sc_tir', 'sc_tis_ql', 'sc_tir_ql']
112
+ return {
113
+ ft: list(
114
+ sorted(
115
+ filter(lambda x: ft in str(x.stem), self.fits_files),
116
+ key=lambda x: int(x.stem.split('_')[-1])
117
+ )
118
+ )
119
+ for ft in files_type
120
+ }
121
+
122
+ def show_files(self):
123
+ """
124
+ Print statistics about the files in the input directory.
125
+
126
+ Prints the number of files in the input directory and the number of files
127
+ in the input directory that match the pattern '\d{8}_\d{8}'.
128
+ """
129
+ # Import the Counter class from the collections module.
130
+ from collections import Counter
131
+ # Compile a regular expression that matches the pattern '\d{8}_\d{8}'.
132
+ regex = re.compile('\d{8}_\d{8}')
133
+
134
+ # Print the number of files in the input directory.
135
+ print('All files in input_dir :')
136
+ # Count the number of files in the input directory.
137
+ # The Counter class is used to count the occurrences of each file extension.
138
+ rich.print(Counter([p.suffix for p in self.input_dir.rglob('*')]))
139
+
140
+ # Print the number of files in the input directory matching the pattern '\d{8}_\d{8}'.
141
+ print('All files in input_dir matching \d{8}:')
142
+ # Count the number of files in the input directory that match the pattern '\d{8}_\d{8}'.
143
+ # The regular expression is used to search for the pattern in the stem of each file path.
144
+ # The Counter class is used to count the occurrences of each prefix before the pattern.
145
+ rich.print(Counter([re.findall('^([^\d]*)_',p.stem)[0] for p in self.input_dir.rglob('*') if regex.search(p.stem)]))
146
+
147
+ def filetypes2dict(self):
148
+ """
149
+ Convert the input files into a dictionary, where the keys are the file types and the values are lists of file paths.
150
+
151
+ Returns:
152
+ dict: A dictionary where the keys are the file types and the values are lists of file paths.
153
+ """
154
+ # Define the file types.
155
+ files_type = ['hk_default', 'hk_extended', 'sc_tis', 'sc_tir', 'sc_tis_ql', 'sc_tir_ql']
156
+
157
+ # Create a dictionary to store the file paths.
158
+ input_path_dict = {}
159
+
160
+ # Iterate over each file type.
161
+ for ft in files_type:
162
+ # Filter the fits files based on the file type.
163
+ # Sort the filtered files based on the numeric part in the file name.
164
+ # Convert the result to a list.
165
+ input_path_dict[ft] = list(
166
+ sorted(
167
+ filter(lambda x: ft in str(x.stem), self.fits_files),
168
+ key=lambda x: int(x.stem.split('_')[-1])
169
+ )
170
+ )
171
+
172
+ # Return the dictionary.
173
+ return input_path_dict
174
+
175
+ def listfiletypes(self) :
176
+ """
177
+ Print the list of file types and the number of files for each file type.
178
+
179
+ This function iterates over the input_path_dict dictionary and prints the file types and the number
180
+ of files for each file type. The file types and the number of files are printed using the rich.print
181
+ function.
182
+
183
+ Returns:
184
+ None
185
+ """
186
+ # Iterate over the input_path_dict dictionary and print the file types and the number of files for each file type.
187
+ rich.print({k: [f.name for f in v] for k, v in self.input_path_dict.items()})
188
+
189
+ # Print the number of files for each file type.
190
+ rich.print({filetype:len(files_paths) for filetype,files_paths in self.input_path_dict.items()})
191
+
192
+ def save_plot(self,
193
+ out_file,
194
+ dpi=150,
195
+ out_format='jpg'):
196
+ """
197
+ Save a plot to the output directory.
198
+
199
+ Args:
200
+ out_file (str): The name of the output file.
201
+ dpi (int): The resolution of the saved image in dots per inch. Default is 150.
202
+ out_format (str): The format of the saved image. Default is 'jpg'.
203
+
204
+ Returns:
205
+ None
206
+ """
207
+ # Construct the output file path by joining the output directory and the output file name.
208
+ out_path = self.output_dir / (out_file +f'.{out_format}' )
209
+
210
+ # Save the plot to the output file path with the specified resolution and format.
211
+ plt.savefig(out_path,dpi=dpi)
212
+
213
+ # Print a message indicating that the plot is being saved.
214
+ print(f'Saving {out_path}')
215
+
216
+ def data_collector(self):
217
+ """
218
+ Collect data from the input files and store it in the collect_data attribute.
219
+
220
+ This function iterates over the input_path_dict dictionary, which contains the file paths for each file type.
221
+ For each file type, it checks if there are files available and reads the data from the files.
222
+ The collected data is stored in the collect_data attribute.
223
+
224
+ Returns:
225
+ None
226
+ """
227
+ from astropy.io import fits
228
+
229
+ # Create an empty dictionary to store the collected data
230
+ collect_data = {}
231
+
232
+ # Iterate over the input_path_dict dictionary
233
+ for filetype, files_paths in self.input_path_dict.items():
234
+
235
+ # Check if the file type contains 'hk'
236
+ if 'hk' in filetype:
237
+ # Skip if there are no files
238
+ if len(files_paths) == 0:
239
+ continue
240
+
241
+ # Iterate over the files for the current file type
242
+ for in_file in files_paths:
243
+ # Read the data from the file
244
+ data = pd.read_csv(in_file, names=extract_mertis_hk_columns(in_file))
245
+ print(f'Reading filetype: {filetype} from {in_file.stem}')
246
+
247
+ # Add the data to the collect_data dictionary
248
+ if filetype not in collect_data:
249
+ collect_data[filetype] = []
250
+ collect_data[filetype].append({
251
+ 'data': data,
252
+ 'path': in_file
253
+ })
254
+
255
+ # Check if the file type contains 'sc_tis' or 'sc_tir'
256
+ elif ('sc_tis' in filetype) or ('sc_tir' in filetype):
257
+ # Remove the 'sc_' prefix from the file type
258
+ filetype = re.sub('^sc_', '', filetype)
259
+
260
+ # Skip if there are no files
261
+ if len(files_paths) == 0:
262
+ continue
263
+
264
+ # Iterate over the files for the current file type
265
+ for in_file in files_paths:
266
+ # Read the data from the FITS file
267
+ hdulist = fits.open(str(in_file))
268
+ print(f'Reading filetype: {filetype} from {in_file.stem}')
269
+
270
+ # Add the data to the collect_data dictionary
271
+ if filetype not in collect_data:
272
+ collect_data[filetype] = []
273
+ collect_data[filetype].append({
274
+ 'fits_data': hdulist,
275
+ 'path': in_file
276
+ })
277
+
278
+ # Store the collected data in the collect_data attribute
279
+ self.collect_data = collect_data
280
+
281
+
282
+ def data_assembler(self, verbose=False):
283
+ """
284
+ Assembles the collected data into convenient data structures.
285
+
286
+ This function processes the collected data and stores it in convenient data structures. The processed data includes:
287
+ - ``geom_ls``: a dictionary of dictionaries, where each dictionary contains the data for a specific file, and each inner dictionary contains the data for a specific parameter.
288
+ - ``frames``: a dictionary of numpy arrays, where each array contains the data for a specific file.
289
+ - ``wavelengths``: a dictionary of numpy arrays, where each array contains the wavelength data for a specific file.
290
+ - ``mertis_tis_metadata``: a dictionary of pandas DataFrames, where each DataFrame contains the metadata for a specific file.
291
+ - ``space_index``: a pandas Index object containing the indices of the space measurements.
292
+ - ``bb7_index``: a pandas Index object containing the indices of the BB7 measurements.
293
+ - ``bb3_index``: a pandas Index object containing the indices of the BB3 measurements.
294
+ - ``planet_index``: a pandas Index object containing the indices of the planet measurements.
295
+ """
296
+ from astropy.table import Table, vstack
297
+ from astropy.time import Time
298
+ from rich.progress import track
299
+
300
+ # call data_collector if no data loaded
301
+ if not hasattr(self, 'collect_data'):
302
+ self.data_collector()
303
+
304
+ NODATA_GEOMETRY = -1.7976931348623157e+308 # min double, this is new
305
+
306
+ # Initialize the data structures
307
+ geom_ls = {}
308
+ frames = {}
309
+ wavelengths = {}
310
+ mertis_tis_metadata = {}
311
+ output_str = []
312
+
313
+ # Iterate over the collected tis data
314
+ for tis_data in track(self.collect_data["tis"],
315
+ total=len(self.collect_data["tis"]),
316
+ description="Loading files..."):
317
+ if "table" not in tis_data["path"].name:
318
+ # Read the data from the FITS file and convert it to a pandas DataFrame
319
+ tmp_table = Table(tis_data["fits_data"][1].data).to_pandas()
320
+ tmp_table['file'] = tis_data["path"].stem
321
+ mertis_tis_metadata[tis_data["path"].stem] = tmp_table
322
+
323
+ print(f'Reading filetype: tis from {tis_data["path"]}')
324
+ # Convert the data to float64 to keep the native byteorder
325
+ frames[tis_data["path"].stem] = tis_data["fits_data"]['MERTIS_TIS_CALIB_SCIENCE_DATA'].data.astype(np.float64)
326
+ wavelengths[tis_data["path"].stem] = tis_data["fits_data"]['MERTIS_TIS_CALIB_SCIENCE_DATA_WAVELENGTH'].data.astype(np.float64) #-wav_correction_factor
327
+
328
+ # Process the geometry data
329
+ geom_ls[tis_data["path"].stem] = {k.name: k.data.astype(np.float64) for k in tis_data["fits_data"] if 'GEOM' in k.name}
330
+ for geo_k, geo_v in geom_ls[tis_data["path"].stem].items():
331
+ geo_v[geo_v == NODATA_GEOMETRY] = np.nan
332
+ geo_k = 'MERTIS_TIS_GEOMETRY_TARGET_LONGITUDE'
333
+ output_str.append([tis_data["path"].stem, np.sum(np.isfinite(geo_v)), geo_v.size])
334
+
335
+ # Preserve the original index in the source file
336
+ mertis_tis_metadata_df = pd.concat(mertis_tis_metadata).reset_index(drop=False).drop(columns=['level_0']).rename(columns={"level_1": "file_index"})
337
+
338
+ # Sort the metadata DataFrame by the TIME_UTC column
339
+ mertis_tis_metadata_df_time_utc_sort_index = mertis_tis_metadata_df.sort_values('TIME_UTC').index.values
340
+ mertis_tis_metadata_df = mertis_tis_metadata_df.sort_values('TIME_UTC').reset_index(drop=True)
341
+ mertis_tis_metadata_df['TIME_UTC'] = pd.to_datetime(mertis_tis_metadata_df['TIME_UTC'], utc=True)
342
+
343
+
344
+ # Identify the indices of the space, BB7, BB3, and planet measurements
345
+ space_index = mertis_tis_metadata_df[mertis_tis_metadata_df['HK_STAT_TIS_DATA_ACQ_TARGET'].str.contains('Space')].index
346
+ bb7_index = mertis_tis_metadata_df[mertis_tis_metadata_df['HK_STAT_TIS_DATA_ACQ_TARGET'].str.contains('BB7')].index
347
+ bb3_index = mertis_tis_metadata_df[mertis_tis_metadata_df['HK_STAT_TIS_DATA_ACQ_TARGET'].str.contains('BB3')].index
348
+ planet_index = mertis_tis_metadata_df[mertis_tis_metadata_df['HK_STAT_TIS_DATA_ACQ_TARGET'].str.contains('Planet')].index
349
+
350
+ ########################################################################
351
+ # generic wavelengths : not precise enough for scientific analysis!
352
+ wav = wavelengths[list(wavelengths.keys())[-1]].mean(axis=1)
353
+ n_wav = len(wav)
354
+ n_corners = geom_ls[list(geom_ls.keys())[0]]['MERTIS_TIS_GEOMETRY_TARGET_LONGITUDE'].shape[0]
355
+
356
+ # Print the output statistics
357
+ if verbose:
358
+ print(f'{n_wav=} # generic wavelengths : not precise enough for scientific analysis!')
359
+ print(pd.DataFrame(columns=["tis_stem", "finite(geo)", "geo.size"], data=output_str).to_markdown())
360
+ print("Indices of measurements targets (HK_STAT_TIS_DATA_ACQ_TARGET):")
361
+ print(f'{space_index.shape=}')
362
+ print(f'{bb7_index.shape=}')
363
+ print(f'{bb3_index.shape=}')
364
+ print(f'{planet_index.shape=}')
365
+ # Print the collected data statistics
366
+ print(f'Collected data statistics:')
367
+ print(f'Number of TIS files: {len(self.collect_data.get("tis", []))}')
368
+ print(f'Number of HK files: {len(self.collect_data.get("hk_default", [])) + len(self.collect_data.get("hk_extended", []))}')
369
+ print(f'Number of TIR files: {len(self.collect_data.get("tir", []))}')
370
+ print(f'Number of TIS QL files: {len(self.collect_data.get("tis_ql", []))}')
371
+ print(f'Number of TIR QL files: {len(self.collect_data.get("tir_ql", []))}')
372
+ # Store the processed data in the corresponding attributes
373
+ self.geom_ls = geom_ls
374
+ self.frames = frames
375
+ self.wavelengths = wavelengths
376
+ self.mertis_tis_metadata = mertis_tis_metadata
377
+ self.space_index = space_index
378
+ self.bb7_index = bb7_index
379
+ self.bb3_index = bb3_index
380
+ self.planet_index = planet_index
381
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) DLR
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,190 @@
1
+ Metadata-Version: 2.1
2
+ Name: mertisreader
3
+ Version: 0.0.1
4
+ Summary: helper routines to read ESA/Bepicolombo space mission - DLR MERTIS instrument data
5
+ Home-page: https://gitlab.com/damo_ma/mertisreader/tree/master/
6
+ Author: Mario D Amore
7
+ Author-email: mario.damore@dlr.de
8
+ License: MIT License
9
+ Keywords: planetary,instrument,data
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Natural Language :: English
14
+ Classifier: Programming Language :: Python :: 3.7
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Requires-Python: >=3.7
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: rich
22
+ Requires-Dist: numpy
23
+ Requires-Dist: pandas
24
+ Requires-Dist: astropy
25
+ Requires-Dist: matplotlib
26
+ Requires-Dist: xmltodict
27
+
28
+
29
+
30
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
31
+
32
+ ## Quick Install
33
+
34
+ To install the `mertisreader` package, you can clone the repository from
35
+ GitLab and install it using pip:
36
+
37
+ The code is under active development, this enable to pull the last code
38
+ with `git pull` and have this directly enabled in your environment.
39
+
40
+ I advise to use a pytohn virtual environment /conda environment.
41
+
42
+ ``` bash
43
+ git clone https://gitlab.dlr.de/psl/mertisreader.git
44
+ cd mertisreader
45
+ python -m pip install -e .
46
+ ```
47
+
48
+ ## mertisreader - Quick cheatsheet
49
+
50
+ Import Required Libraries
51
+
52
+ ``` python
53
+ import pathlib
54
+ import rich
55
+ import mertisreader as mr
56
+
57
+ print("Libraries imported successfully.")
58
+ ```
59
+
60
+ Libraries imported successfully.
61
+
62
+ Initialize MERTISDataPackReader
63
+
64
+ ``` python
65
+ input_path = pathlib.Path('../data/bcmer_tm_all_START-20200409T000000_END-20200410T000000_CRE-20240717T132010-ParamEventBootSciHK-short/cal')
66
+ output_path = pathlib.Path('/tmp/')
67
+ log_level = 'INFO'
68
+
69
+ if not input_path.exists():
70
+ print(f"Input path {input_path} does not exist.")
71
+ else:
72
+ print(f"Reading path {input_path}")
73
+
74
+ ms_reader = mr.MERTISDataPackReader(input_dir=input_path, output_dir=output_path, log_level=log_level)
75
+
76
+ print(f'MERTISDataPackReader initialized with input directory: {ms_reader.input_dir}')
77
+ print(f'Output directory: {ms_reader.output_dir}')
78
+ print(f'Log level: {ms_reader.log_level}')
79
+ ```
80
+
81
+ 2024-11-25 16:00:21,499|1472475|INFO|input_dir=PosixPath('../data/bcmer_tm_all_START-20200409T000000_END-20200410T000000_CRE-20240717T132010-ParamEventBootSciHK-short/cal')
82
+
83
+ Reading path ../data/bcmer_tm_all_START-20200409T000000_END-20200410T000000_CRE-20240717T132010-ParamEventBootSciHK-short/cal
84
+ MERTISDataPackReader initialized with input directory: ../data/bcmer_tm_all_START-20200409T000000_END-20200410T000000_CRE-20240717T132010-ParamEventBootSciHK-short/cal
85
+ Output directory: /tmp
86
+ Log level: INFO
87
+
88
+ Show Files in Input Directory
89
+
90
+ ``` python
91
+ ms_reader.show_files()
92
+ ```
93
+
94
+ All files in input_dir :
95
+ All files in input_dir matching \d{8}:
96
+
97
+ <pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #800080; text-decoration-color: #800080; font-weight: bold">Counter</span><span style="font-weight: bold">({</span><span style="color: #008000; text-decoration-color: #008000">'.tdat'</span>: <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">1</span>, <span style="color: #008000; text-decoration-color: #008000">'.dat'</span>: <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">2</span>, <span style="color: #008000; text-decoration-color: #008000">'.fits'</span>: <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">1</span>, <span style="color: #008000; text-decoration-color: #008000">'.xml'</span>: <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">3</span><span style="font-weight: bold">})</span>
98
+ </pre>
99
+ <pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #800080; text-decoration-color: #800080; font-weight: bold">Counter</span><span style="font-weight: bold">({</span><span style="color: #008000; text-decoration-color: #008000">'mer_cal_sc_tis'</span>: <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">3</span>, <span style="color: #008000; text-decoration-color: #008000">'mer_cal_hk_extended'</span>: <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">2</span>, <span style="color: #008000; text-decoration-color: #008000">'mer_cal_hk_default'</span>: <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">2</span><span style="font-weight: bold">})</span>
100
+ </pre>
101
+
102
+ List File Types
103
+
104
+ ``` python
105
+ ms_reader.listfiletypes()
106
+ ```
107
+
108
+ <pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="font-weight: bold">{</span>
109
+ <span style="color: #008000; text-decoration-color: #008000">'hk_default'</span>: <span style="font-weight: bold">[</span><span style="color: #008000; text-decoration-color: #008000">'mer_cal_hk_default_20200409_20200409.dat'</span><span style="font-weight: bold">]</span>,
110
+ <span style="color: #008000; text-decoration-color: #008000">'hk_extended'</span>: <span style="font-weight: bold">[</span><span style="color: #008000; text-decoration-color: #008000">'mer_cal_hk_extended_20200409_20200409.dat'</span><span style="font-weight: bold">]</span>,
111
+ <span style="color: #008000; text-decoration-color: #008000">'sc_tis'</span>: <span style="font-weight: bold">[</span><span style="color: #008000; text-decoration-color: #008000">'mer_cal_sc_tis_20200409_20200409_1.fits'</span><span style="font-weight: bold">]</span>,
112
+ <span style="color: #008000; text-decoration-color: #008000">'sc_tir'</span>: <span style="font-weight: bold">[]</span>,
113
+ <span style="color: #008000; text-decoration-color: #008000">'sc_tis_ql'</span>: <span style="font-weight: bold">[]</span>,
114
+ <span style="color: #008000; text-decoration-color: #008000">'sc_tir_ql'</span>: <span style="font-weight: bold">[]</span>
115
+ <span style="font-weight: bold">}</span>
116
+ </pre>
117
+ <pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="font-weight: bold">{</span><span style="color: #008000; text-decoration-color: #008000">'hk_default'</span>: <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">1</span>, <span style="color: #008000; text-decoration-color: #008000">'hk_extended'</span>: <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">1</span>, <span style="color: #008000; text-decoration-color: #008000">'sc_tis'</span>: <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">1</span>, <span style="color: #008000; text-decoration-color: #008000">'sc_tir'</span>: <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">0</span>, <span style="color: #008000; text-decoration-color: #008000">'sc_tis_ql'</span>: <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">0</span>, <span style="color: #008000; text-decoration-color: #008000">'sc_tir_ql'</span>: <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">0</span><span style="font-weight: bold">}</span>
118
+ </pre>
119
+
120
+ Collect Data
121
+
122
+ ``` python
123
+ ms_reader.data_collector()
124
+
125
+ print(f'Collected data keys: {ms_reader.collect_data.keys()}')
126
+ for key, value in ms_reader.collect_data.items():
127
+ print(f'{key}: {len(value)} files collected')
128
+ ```
129
+
130
+ Reading filetype: hk_default from mer_cal_hk_default_20200409_20200409
131
+ Reading filetype: hk_extended from mer_cal_hk_extended_20200409_20200409
132
+ Reading filetype: tis from mer_cal_sc_tis_20200409_20200409_1
133
+ Collected data keys: dict_keys(['hk_default', 'hk_extended', 'tis'])
134
+ hk_default: 1 files collected
135
+ hk_extended: 1 files collected
136
+ tis: 1 files collected
137
+
138
+ Assemble Data
139
+
140
+ ``` python
141
+ ms_reader.data_assembler(verbose=True)
142
+ ```
143
+
144
+ Output()
145
+
146
+ <pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace">Reading filetype: tis from
147
+ ../data/bcmer_tm_all_START-20200409T000000_END-20200410T000000_CRE-20240717T132010-ParamEventBootSciHK-short/cal/me
148
+ r_cal_sc_tis_20200409_20200409_1.fits
149
+ </pre>
150
+ <pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"></pre>
151
+ <pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace">
152
+ </pre>
153
+
154
+ n_wav=40 # generic wavelengths : not precise enough for scientific analysis!
155
+ | | tis_stem | finite(geo) | geo.size |
156
+ |---:|:-----------------------------------|--------------:|-----------:|
157
+ | 0 | mer_cal_sc_tis_20200409_20200409_1 | 672 | 11000 |
158
+ Indices of measurements targets (HK_STAT_TIS_DATA_ACQ_TARGET):
159
+ space_index.shape=(21,)
160
+ bb7_index.shape=(0,)
161
+ bb3_index.shape=(1,)
162
+ planet_index.shape=(0,)
163
+ Collected data statistics:
164
+ Number of TIS files: 1
165
+ Number of HK files: 2
166
+ Number of TIR files: 0
167
+ Number of TIS QL files: 0
168
+ Number of TIR QL files: 0
169
+
170
+ Verify the Assembled Data
171
+
172
+ ``` python
173
+ print(f'Geometry data keys: {ms_reader.geom_ls.keys()}')
174
+ print(f'Frames data keys: {ms_reader.frames.keys()}')
175
+ print(f'Wavelengths data keys: {ms_reader.wavelengths.keys()}')
176
+ print(f'MERTIS TIS metadata keys: {ms_reader.mertis_tis_metadata.keys()}')
177
+ print(f'Space index shape: {ms_reader.space_index.shape}')
178
+ print(f'BB7 index shape: {ms_reader.bb7_index.shape}')
179
+ print(f'BB3 index shape: {ms_reader.bb3_index.shape}')
180
+ print(f'Planet index shape: {ms_reader.planet_index.shape}')
181
+ ```
182
+
183
+ Geometry data keys: dict_keys(['mer_cal_sc_tis_20200409_20200409_1'])
184
+ Frames data keys: dict_keys(['mer_cal_sc_tis_20200409_20200409_1'])
185
+ Wavelengths data keys: dict_keys(['mer_cal_sc_tis_20200409_20200409_1'])
186
+ MERTIS TIS metadata keys: dict_keys(['mer_cal_sc_tis_20200409_20200409_1'])
187
+ Space index shape: (21,)
188
+ BB7 index shape: (0,)
189
+ BB3 index shape: (1,)
190
+ Planet index shape: (0,)
@@ -0,0 +1,12 @@
1
+ mertisreader/__init__.py,sha256=XoppFCWM_8XsGAbynKKKg7C3Mca0Kzf_ueJ_7U-l9SE,42
2
+ mertisreader/_modidx.py,sha256=X9EfkRqB-6J1sYwhxGSKibfawpC7w3MDDgHRPi2vnV0,3483
3
+ mertisreader/_nbdev.py,sha256=HTrynMhNZjmSrTfgx3-dYoYCNCC-jJC-J_o-Fsk8EWc,365
4
+ mertisreader/core.py,sha256=W5WMhBao0HBskuVl5oPDg-vSnMtxmZW7AjtwWPySEc8,16968
5
+ nbdev_template/__init__.py,sha256=sXLh7g3KC4QCFxcZGBTpG2scR7hmmBsMjq6LqRptkRg,22
6
+ nbdev_template/_nbdev.py,sha256=_KydeHfComfGuszwZK6SbKVX0wvnIX-DwqKzBIbOYJs,303
7
+ nbdev_template/core.py,sha256=5KMNsQWwe1-tLVCf9J3qhyy5GnaHlMd6REotCr_3_gg,131
8
+ mertisreader-0.0.1.dist-info/LICENSE,sha256=VcZMZr4QHc45W9SnDKs0AMYMmCEObzWwZ4bllIfF3xM,1055
9
+ mertisreader-0.0.1.dist-info/METADATA,sha256=hD6iiuId3nrlCwcvWoywvtPPOZ7axJOZv9HkWlhQ2sY,10445
10
+ mertisreader-0.0.1.dist-info/WHEEL,sha256=Z4pYXqR_rTB7OWNDYFOm1qRk0RX6GFP2o8LgvP453Hk,91
11
+ mertisreader-0.0.1.dist-info/top_level.txt,sha256=Wo0u-oLpHsWBaYj6wifiDjaG0ToY-8xO3CPuceTDL2M,28
12
+ mertisreader-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (70.3.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ mertisreader
2
+ nbdev_template
@@ -0,0 +1 @@
1
+ __version__ = "0.0.1"
@@ -0,0 +1,13 @@
1
+ # AUTOGENERATED BY NBDEV! DO NOT EDIT!
2
+
3
+ __all__ = ["index", "modules", "custom_doc_links", "git_url"]
4
+
5
+ index = {"f": "00_core.ipynb"}
6
+
7
+ modules = ["core.py"]
8
+
9
+ doc_url = "//nbdev_template"
10
+
11
+ git_url = "https://gitlab.com/thomas.capelle/nbdev_template/tree/master/"
12
+
13
+ def custom_doc_links(name): return None
nbdev_template/core.py ADDED
@@ -0,0 +1,6 @@
1
+ # AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified).
2
+
3
+ __all__ = ['f']
4
+
5
+ # Cell
6
+ def f(x): return x