316 Commits

Author SHA1 Message Date
0115745433 Add initial changelog for v1.0.0 2025-06-26 10:10:22 +02:00
eb853ee948 Fix bug instruments/readers/g5505_text_reader.py. The fallback format does not contain desired_format key, leading to a key error 2025-06-25 16:54:03 +02:00
6c908e6686 Update src/hdf5_writer.py to record unflattened path from original folder 2025-06-25 14:11:56 +02:00
dacafb6234 Update src/hdf5_ops.py to allow for replicates after flattening directory structures. 2025-06-25 14:11:02 +02:00
ee8540e04e Fix typos in instruments/readers/g5505_text_reader.py 2025-06-25 14:09:13 +02:00
e6df345578 Modify instruments/readers/g5505_text_reader.py to include new instrument CEDOAS, which produces multi-format files. The updated file dependencies. 2025-06-25 12:00:55 +02:00
334335387e Update to notebooks/demo_data_integration.ipynb. Step description now includes information about set up with network_mount env variable 2025-06-22 12:16:26 +02:00
cbcebd998a Fix typos in README.md and commplemtned some information about network drives. 2025-06-22 12:15:34 +02:00
e851131269 Append new functions to utils/g5505_utils.py. This search for .env file in root directory 2025-06-22 12:13:14 +02:00
f3ff32e049 Update to pipelines/data_integration.py. Added feature to use environment variable MOUNT_DRIVE defined in .env file. 2025-06-22 12:11:48 +02:00
be7cf0ba12 Re-add sanitized config files
- Replaced sensitive server paths with placeholders
- Ensure .env is used to provide values
2025-06-22 10:45:44 +02:00
630189c5d7 Update input_files/campaignDescriptor3_NG.yaml input directory due changes in source directory 2025-06-22 10:42:20 +02:00
e6b8b60258 update gitignore 2025-06-21 20:28:49 +02:00
a70b012da5 Simplify output dir and file naming 2025-06-20 11:47:19 +02:00
cc702ee17d Change output directory to data/ for all descriptors 2025-06-20 11:45:25 +02:00
177bcee400 Refactor step 1 in notebook to facilitate usage of campaign descriptors 2025-06-20 10:37:01 +02:00
b610b4e337 Rename yaml files in input_files/ as campaign descriptors for consistency with idear project. 2025-06-20 10:24:53 +02:00
f4ddd36ef2 Clean import statements 2025-06-19 20:49:36 +02:00
8e6ee49188 Modify utils/g5505_utils.py. Implement handling unicode character errors. 2025-06-19 20:49:14 +02:00
617a923fb6 Add processing_Script and processing_data and actris_level to output metadata 2025-06-19 20:41:17 +02:00
b96c04fc01 Refactor instruments/readers/g5505_text_reader.py, some code abstracted as functions to improve readabilitity. 2025-06-19 20:40:14 +02:00
f555f7f199 Implement skipping in convert_attrdict_to_np_structured_array(attr_value: dict) when dictionary values are not scalar. This ensures compatible values are transfered while the rest simply dicarded. 2025-06-10 16:03:01 +02:00
7d710c1e62 Fix bug while reading yaml file from utils/g5505_utils.py 2025-06-10 14:38:29 +02:00
ab897018d9 Add exclude paths set through yaml file 2025-06-10 11:08:14 +02:00
83cec97e83 Fix bug instruments/readers/structured_file_reader.py. pd.to_dict return a list of dicts so we need to handle each item seprately using a loop. 2025-06-07 19:14:53 +02:00
f640205b12 Add new file reader instruments/readers/structured_file_reader.py, and update registry.py and yaml 2025-06-07 18:15:41 +02:00
e80c19ef61 Update src/hdf5_writer.py to consider data lineage metadata in data ingestion process 2025-06-07 15:31:13 +02:00
a95fc1fc6a Modified output_file_directory attribute in yaml files as ../output_files/ 2025-06-07 15:30:19 +02:00
87462211a9 Update instruments/readers/nasa_ames_reader.py to handle dirty text entries. Dirty entries of time variables that cannot be properly processed are sent to nat 2025-05-27 10:12:20 +02:00
6851f03dbd Restore instruments/readers/nasa_ames_reader.py to previous version. 2025-05-26 19:39:21 +02:00
bd74f8310c Record missing values for each variable according to EBAS value convention 2025-05-21 13:53:18 +02:00
e4b2a4cd5a Split header in three parts and detect variables and variable descriptions added to attribute dictionary 2025-05-21 09:19:16 +02:00
a22532d08d Register new file reader in the reader registry system. 2025-05-14 13:51:28 +02:00
ad4339a76b Added new filereader dictionary pair for nasames files. This is a first version that may change. 2025-05-14 13:50:08 +02:00
773b6a6fbe Fix import statement in pipelines.data_integration.py 2025-03-14 10:12:57 +01:00
9276f060b0 WIP: Update contributing and acknowledgement sections. 2025-03-11 14:03:22 +01:00
32abd4cd56 Implemented hdf5_file_reader.py and updated register.yaml and hdf5_writer.py. This replaces previous function __copy_file_in_group(). 2025-02-25 12:25:15 +01:00
5f9f09d288 Merge branch 'feature/DB_for_FileReader_Repo' into 'main'
Restructuring of file reader system to process multi-instrument data folders.

See merge request 5505-public/dima!3
2025-02-25 10:48:59 +01:00
295b43a89a Merge branch 'main' into 'feature/DB_for_FileReader_Repo'
# Conflicts:
#   instruments/filereader_registry.py
#   pipelines/data_integration.py
#   src/hdf5_writer.py
2025-02-25 10:41:02 +01:00
064b8b3a62 Update import statements in pipelines/data_integration.py. from instruments.readers import ... -> from instruments import ... 2025-02-25 09:21:52 +01:00
db4bb0ef03 Implemented create_hdf5_from_filesystem_new() using new instrument readers cml interface and subprocesses. This facilitates extension of file reading capabilities by collaborators without requiring changes to file_registry.py. Only additions in folders and registry.yaml. 2025-02-24 18:48:03 +01:00
92a2560ed7 Update all file readers with command line interface so we can run them as a subprocess. Added also registry.yaml to decouple code from user-based instrument adaptations or extensions. 2025-02-24 17:27:12 +01:00
9511377883 Merge branch 'main' of https://gitlab.psi.ch/5505-public/dima 2025-02-22 18:02:45 +01:00
1e67745fa4 Fix import for filereader_registry.py after moving it from intruments/readers/ one level above. 2025-02-22 17:59:00 +01:00
6ebc699a43 Moved filereader_registry.py outside readers folder. 2025-02-22 17:53:19 +01:00
bb48cfa0cd Moved filereader_registry.py outside readers folder. 2025-02-22 17:51:56 +01:00
821d314cb6 Change import statements with try except to enable explicit import of submodules from import to avoid conflicts with parent project. 2025-02-22 17:10:53 +01:00
8ce6f588dc Implement data_lineage_metadata.json detection and then use it to annotate associated file. 2025-02-10 15:56:34 +01:00
68a9928c39 Enable boolean type columns from pandas DataFrame to be suitably converted into numpy structured array 2025-02-10 15:52:17 +01:00
c28286a626 Make file reader selection case insensitive by using ext.lower() and update config_text_reader.py to point to renamed dictionary. 2025-02-08 19:45:16 +01:00
0b29e2ec68 remove instruments/dictionaries/ICAD_NO2.yaml. Its dict terms are now in ICAD.yaml. 2025-02-08 19:23:37 +01:00
609bb0b859 Add dict terms from ICAD_NO2.yaml 2025-02-08 19:22:27 +01:00
ef7fe70bf0 Combine dictionaries of ICAD_HONO.yaml and ICAD_NO2.yaml into ICAD.yaml 2025-02-08 19:21:17 +01:00
b58e205f9f Remove skip directory condition when directory keywords are empty. Here, all paths to files should be considered. 2025-02-07 16:37:01 +01:00
f986edd4a5 Fix reader txt/csv default behavior. 2025-02-07 16:25:45 +01:00
0d26777732 Enable instrumentFolder of form <instFolder>/<category>/ to be trasfered without flatenning 2025-02-07 16:24:21 +01:00
b374de60f3 Add try except block to trigger errors for invalid group names. 2025-02-06 16:07:45 +01:00
2f72177410 Add constraint to match only path/to/keyword1/keyword2/files containing a composite keyword keyword1/keyword2. 2025-02-06 15:34:38 +01:00
5d0ab4603f Add property to extracted dataset as dataframe. Now time column is of datetime type to facilitate downstream procesing. 2025-02-04 17:23:32 +01:00
6fae139360 Implement method in hdf5 manager to infer datetime column in dataset 2025-02-04 17:13:01 +01:00
32bba4239a Synch with remote repo 2025-02-03 10:31:48 +01:00
a3ccff4079 Fix typo in html text. 2025-01-27 13:53:59 +01:00
6653add80c Update readme.md and set_up_env.sh 2025-01-27 13:29:29 +01:00
ef66d8f1c2 Update unload operation to remove reference and fix logic error to dataset metadata extraction. 2025-01-24 10:28:43 +01:00
1ae607f73b Add validation step to yaml file validation to ensure list type and a minimun length for the 'instrument_datafolder' keyword. 2025-01-22 15:55:21 +01:00
5b06548d88 Fix typo on extension items, extensions need to include a dot .json and .yaml. 2025-01-21 09:30:49 +01:00
45132b42ce Add json and yaml extensions to admissible file extension lists. 2025-01-21 08:57:38 +01:00
dd3ebcfe6d Updated to cleared jupyter notebooks 2025-01-14 14:46:43 +01:00
4f85ca1ad6 Added comments to explain configuration parameters/or variables. 2025-01-14 14:25:53 +01:00
2bd2e89134 Add directory tree structure description. 2024-12-04 17:20:35 +01:00
600899dca2 Update .gitignore with output_files/ 2024-12-04 16:53:57 +01:00
4a91785efb Add .gitkeep and keep this folder empty. it is only to be used for local processing 2024-12-04 16:52:50 +01:00
49dff5b87b Update readme with getting started section 2024-12-04 16:24:14 +01:00
3e37854445 Solved binary incompatibility issue of generated environment by conda installing h5py and numpy from conda-forge or default channels. 2024-12-04 16:15:42 +01:00
112b88e31f Updated bash script and yml env file to set up python interpreter. 2024-12-04 13:52:35 +01:00
d422067223 Update to readme.md 2024-12-03 13:55:45 +01:00
47c9bd8e3d Update readme with key features of the repo. 2024-12-03 13:50:53 +01:00
31d8af6aef Updated README.md with software arquitecture figure 2024-12-02 17:28:22 +01:00
b2455b2456 Updated README.md with software arquitecture figure 2024-12-02 17:24:48 +01:00
6bc89ebff0 Updated README 2024-12-02 17:22:52 +01:00
1a941bbb6e Updated figure name. 2024-12-02 17:08:36 +01:00
c57bb62ebd Updated ci runner pipeline fot gitlab page 2024-12-02 16:31:49 +01:00
f3bb82a937 Updated documentation and built doc website 2024-12-02 16:31:03 +01:00
23e0ced190 Relocated to visualization module 2024-12-02 15:39:41 +01:00
fc561a6068 Add __init__.py 2024-12-02 15:36:03 +01:00
c373c18062 Moved hdf5_lib.py to visualization folder 2024-12-02 15:34:44 +01:00
f2df2ced66 Removed no longer useful notebook 2024-12-02 15:32:57 +01:00
4797c8e894 Added env file specification and bash script for env setup 2024-12-02 15:10:21 +01:00
2e52109bee removed review folder. This is now supposed to be create for review of experimental campaign data objects metadata. 2024-12-02 14:32:34 +01:00
dccf64ef30 Configure GitLab Pages 2024-11-26 13:43:09 +01:00
f4f27b7084 Add draft of dima documentation 2024-11-26 13:40:43 +01:00
11ca454b94 Removed bacause some of the functionalities have been outsourced to other modules src/hdf5_ops.py and src/hdf5_writer.py 2024-11-26 11:55:06 +01:00
22298f643a Merge branch 'main' of https://gitlab.psi.ch/5505/dima 2024-11-25 15:50:25 +01:00
31a129694c Updated instrument dictionaries with variable descriptor names aligned with CF metadata conventions. 2024-11-25 15:49:49 +01:00
5c61e2391a Update to DIMA package path resolution from file. 2024-11-24 19:45:18 +01:00
1b2b319295 Attempt to dynamically resolve path to dima package, when excecuted from command line. 2024-11-24 17:37:38 +01:00
1174ffc8b8 Commented out metadata info about group members for a given group. This is to simplify yaml or json representation of the metadata. 2024-11-24 15:57:54 +01:00
d7f6e52068 Reimplemented code snippet using hdf5_Writer module 2024-11-24 11:32:26 +01:00
967be876d1 Moved func create_hdf5_file_from_dataframe() from hdf5_lib_part2 into hdf5_write.py 2024-11-24 11:30:08 +01:00
0330773f08 Moved read_mtable_as_dataframe(filename) to src/hdf5_ops.py 2024-11-24 11:03:44 +01:00
3122c4482f Removed logs/ folder. This is usually created locally to trace certain file copying, transfer and conversion processes. 2024-11-24 10:51:05 +01:00
c257ab6072 Rerun jupyternotebooks to check their functionality after relocating them to notebooks. OpenBis related python scripts still need to be tested. 2024-11-24 10:45:40 +01:00
02ded9c11a Add hidden.py to the list. This file may contain sensitive information is only to be accessed locally or from a secure location. 2024-11-24 10:41:32 +01:00
b24d33ab15 Check whether h5 file being written exists. If so, we do not overwrite it because it may be underdoing refinement, changes or updates, for archiving, sharing, or publishing. 2024-11-24 10:38:13 +01:00
ca314f971d Add utility functions add_project_path_to_sys_path() to set up path to DIMA's modules dynamically. 2024-11-24 10:08:19 +01:00
a928c4ef4c Moved demos .py to notebooks. Note: Maybe turn them to jupyternotebooks for consistency 2024-11-24 07:49:50 +01:00
6701bc06ad Added read_mtable_as_dataframe(filename) back so that jupyter notebook can use it to demonstrate some functionality 2024-11-23 16:31:29 +01:00
fd92bce802 Implemented sanitize dataframe function to deal with 'O' which may have numbers or strings detected as string types. Then we use it prior to convert dataframe into structured numpy array. 2024-11-23 16:28:49 +01:00
8ab2cb3bdb Moved to notebooks/ 2024-11-23 12:29:55 +01:00
33ad4b8509 Moved to notebooks/ 2024-11-23 12:16:13 +01:00
c30bdab41a Moved to notebooks/ to improve repo organization 2024-11-23 12:06:27 +01:00
3535fd0cc2 Moved data integration ipynb to notebooks folder to improve readability 2024-11-23 11:24:28 +01:00
e486b4659c Added .pkl extension in the list of admissible file extensions 2024-11-21 11:47:41 +01:00
d13e10e44f Modified logger setup to create monthly logs 2024-11-21 11:46:11 +01:00
4632554af1 Added a logs/ and envs/ folder to gitignore. 2024-11-21 11:44:38 +01:00
1be4b8493a Improved progress description stdout 2024-11-10 18:21:00 +01:00
ca2c98eebc Fixed command line interface bug 2024-11-10 18:19:59 +01:00
8d17bf267c Major code refactoring and simplifications to enhance modularity. Included a command line interface. 2024-11-01 09:52:41 +01:00
510683a50d Renamed the input argument yaml_review_file as review_yaml_file. 2024-11-01 09:51:12 +01:00
e2fec03d4a Included cli commands update and serialize to simplify running metadata revision pipeline. 2024-10-29 07:56:43 +01:00
3f7a089a28 Fixed bug: to_serializable_dtype() did not identify correctly dtype of array's entries with object dtype 2024-10-28 18:49:22 +01:00
74633adf7f Removed unused import statements 2024-10-28 16:37:32 +01:00
cc96672245 Moved git related operations from pipelines/ to src/git_ops.py 2024-10-28 16:30:34 +01:00
15b0ff3cc4 Added function to validate review yaml file, and updated update_hdf5_with_review function 2024-10-28 16:20:28 +01:00
69b73c26b0 Corrected import statements due to dependency name changes 2024-10-17 16:52:42 +02:00
7c60193aa6 Renamed module: src/hdf5_lib.py -> src/hdf5_writer.py 2024-10-17 10:53:51 +02:00
44073e3816 Replaced read_dataset_from_hdf5file(hdf5_file_path, dataset_path) with HDF5DataOpsManager.extract_dataset_as_dataframe(self,dataset_name) 2024-10-17 10:46:19 +02:00
f1b2c64f66 Fixed bug when file reader not available. File reader registry now returns a reade that maps input to None. 2024-10-14 16:03:03 +02:00
2a330fcf92 Added 'filename_format' attribute to YAML schema. It takes as value a string of comma separated keys from available attributes in YAML file. 2024-10-14 16:01:24 +02:00
1954542031 Fixed bug introduce in logger due to invalid date naming replace : with - 2024-10-10 14:29:36 +02:00
ea82af2cd5 Cleaned up import statements and comment out path append operations 2024-10-10 14:27:50 +02:00
7d94ce29dd Attempt to initialize dima/utils as a module 2024-10-10 11:53:27 +02:00
1c2588d85f Attemp to initialize dima as a module 2024-10-10 11:43:02 +02:00
2a9d69c757 Robustified metadata and dataset extraction methods by requiring explicit load of file obj before their use. Renamed a few functions and fixed types in print statements. 2024-10-10 11:28:23 +02:00
7653e982a4 Updated function dependencies to reflect changes made to hdf5_ops.py 2024-10-10 11:02:05 +02:00
6be3b31247 Renamed open_file() --> load_file_obj() and close_file() --> unload_file_obj() to focus more on the management operations on the files that actual file handling operations. 2024-10-10 10:47:44 +02:00
568f747a69 Robustifed metadata revision methods with error detection conditions and try-except statements. Metadata revision methods now do not have the capability of opening the file. 2024-10-10 10:39:10 +02:00
31c9db98ca Changed datetime format output of created_at() function as '%Y-%m-%d %H:%M:%S.%f' 2024-10-09 16:07:40 +02:00
fe96134383 Fixed bug in HDF5DataOpsManager.append_dataset() and added 'creation_date' metadata attribute when instrument (groups) are created. 2024-10-09 16:06:44 +02:00
7c683f96a1 Merge branch 'main' of https://gitlab.psi.ch/5505/dima 2024-10-07 16:19:10 +02:00
9a3bf77f37 Created file reader for acsm tofware files, updated registry and updated yaml file with instrument specific terms and reader config params. 2024-10-07 16:18:14 +02:00
c321a17943 Fixed bug, causing input_path normalization operation to damage Windows network drive paths. Basically, os.path.normpath(path_to_input_directory).strip(os.sep) replaced by os.path.normpath(path_to_input_directory).rstrip(os.sep) 2024-10-07 16:16:12 +02:00
dc7f156367 Updated README.md with guide for intrument dependent file reader extensions and updated TODO.md with pending tasks. 2024-10-03 11:31:51 +02:00
89e9dd9ab1 Fixed bugs in update_file() method and create_hdf5_file_from_filesystem_path() 2024-10-03 09:32:25 +02:00
098a79531c Added new instrument (flagging app) file reading capabilities. It includes two files a flag_reader.py that takes flag.json files produced by the app into a standard intermidiate representation, and a yaml file with instrument dependent description terms. Last, we modified the filereader_registry.py to find the new instrument file reader. 2024-10-03 09:07:06 +02:00
01b39b4c02 Added __init__.py inside intrument folders 2024-10-02 15:51:02 +02:00
9b5d777a5b Added .update_file() method, which enables complementary data structure updates to existing file with same name as append_dir's head. 2024-10-02 14:38:35 +02:00
aad0a7c3fb Added file openning mode as input parameter. Now, mode can only take values in ['w','r+'] 2024-10-02 13:54:59 +02:00
4420f81642 Removed construct_attributes_dict(attrs_obj) and replaced by {key: utils.to_serializable_dtype(val) for key, val in obj.attrs.items()} 2024-10-01 10:42:20 +02:00
4d48e84e50 Made two helper functions private by adding the prefix __ 2024-10-01 09:31:41 +02:00
8cd4b7d925 Deleted annotate_root_dir(filename,annotation_dict: dict), and outsourced functionality to HDF5DataOpsManager.append_metadata() or .update_metadata() at obj_name = '/' 2024-10-01 09:19:14 +02:00
6f5d4adcee Implemented metadata append, rename, delete, and update operations on the hdf5 manager object and refactored metadata update script based on yaml file to use said operations. 2024-09-30 16:32:39 +02:00
afe31288a0 Refactored a few function calls due to ranming changes in utils module 2024-09-27 08:58:35 +02:00
96dad0bfb1 Renamed to_yaml() as serialize_metadata() and introduce input parameter output_format, which allows yaml or json. 2024-09-26 16:23:09 +02:00
85b0e5ab74 Performed a few function relocations and deletions from src/hdf5_lib.py into src/hdf5_ops.py and made a copy of previous version as src/hdf5_lib_part2.py 2024-09-26 15:13:31 +02:00
a92660049f Moved is_structured_array() and to_serializable_dtype() to utils, ranamed a few functions and propagated changes to dependent modules. 2024-09-26 14:03:11 +02:00
a57e46d89c Renamed take_yml_snapshot_of_hdf5_file func as to_yaml func 2024-09-25 16:49:44 +02:00
7b221599d8 Moved take_yml_snapshot_of_hdf5_file func and associted helper functions from hdf5_vis.py into hdf5_ops.py 2024-09-25 16:42:44 +02:00
1e93a2c552 Moved take_yml_snapshot_of_hdf5_file func and associted helper functions from hdf5_vis.py into hdf5_ops.py 2024-09-25 16:40:16 +02:00
10554fc41e Renamed make_dtype_yaml_compatible func as to_serializable_dtype func 2024-09-25 16:36:50 +02:00
df2f7b3de6 Abstracted reusable steps in integration_sources as dima_pipeline.py and added functionality to make a collection of hdf5 files, where each represents an single experiment of campaign. 2024-09-25 15:23:23 +02:00
1e1499c28a Robustified definition of path_to_input_dir arg or parameter by ensuring is always defined using forward slashes and then is normalized to the os specification. Improved dry run = True of copy directory func. 2024-09-25 15:12:19 +02:00
0dbec94374 Fixed instrument_dir estimation to be bottom up, ie, based on path to file. Otherwise, it does not work when dima used as submodule 2024-09-19 15:47:11 +02:00
9eeb9d6380 Moved src/metadata_review_lib.py pipelines/metadata_revision.py 2024-09-17 16:55:22 +02:00
07401c895f Moved src/data_integration_lib.py -> pipelines/data_integration.py 2024-09-17 15:32:23 +02:00
2dd033bcb3 Refactored code into functions to parse and validate yaml condif file and to perform specified data integration task using a pipeline like software structure. 2024-09-17 15:28:11 +02:00
d63f522588 Major update. Remove file filtering option and outputname input arg. The output name is now the same as the path_to_input_dir + .h5. By default, the hdf5 writer preserves second level subdirectories and the rest are flattend. dir filtering is outsource to copy_dir_with_constraints from utils- 2024-09-16 16:35:09 +02:00
9c641c0dae Restructured a bit to include the default case of copying an imnput directory without any constraints. Also, added dry_run input argument that returns a path to files dict representation of output directory without making an actual copy. Useful when input directory is already safe to work with directly 2024-09-16 15:38:30 +02:00
7a9f7a8c59 Renamed parameter 'input_file_system_path' to 'path_to_input_directory' for clarity. 2024-09-16 14:24:55 +02:00
cc0adfca62 Fixed import statement 2024-09-13 15:11:25 +02:00
4974246522 move def get_parent_child_relationships(file: h5py.File) from ..._vis.py to ..._ops.py 2024-09-13 14:59:11 +02:00
b42482069c src/hdf5_data_extraction.py -> src/hdf5_ops.py 2024-09-13 14:55:12 +02:00
e8e2473ebe Added new method to retreive metadata from h5file at a given obj path 2024-09-13 14:52:07 +02:00
96a2e96b6a Fixed import statement after module's relocation 2024-08-23 16:23:57 +02:00
e4b04b4484 Modified to use filereader_registry.py. 2024-08-23 16:10:23 +02:00
9789d312f9 Removed and splitted into instruments/readers/filereader_registry.py instruments/readers/g5505_text_reader.py instruments/readers/xps_ibw_reader.py 2024-08-23 16:09:04 +02:00
d866c8f9f9 Split instruments/readers/g5505_file_reader.py into a fileregistry.py and independent file readers. This is to improve instrument modularity and additions 2024-08-23 16:06:44 +02:00
aad51fb1b8 Renamed to reflect better the functionality of the file 2024-08-23 15:50:14 +02:00
d985115125 Integrated copy h5 file into group functionality, imported from g5505_file_reader 2024-08-23 15:47:04 +02:00
a4b7c6a8b0 Moved copy_file_in_group() into hdf5_lib.py because it is not really doing the same role of all filereaders 2024-08-23 15:45:32 +02:00
b5c200d588 Moved all yaml files with dictionary terms for each instrument to dictionaries folder 2024-08-23 14:32:23 +02:00
0be48f8a21 Added ACSM_TOFWARE metadata descriptions 2024-08-23 14:23:32 +02:00
18165eca1a Modified import statements to account for reader module's relocation. 2024-08-23 13:27:26 +02:00
15b76f7704 Fixed a few import dependencies after relocating this file. 2024-08-23 10:57:13 +02:00
a0f44a1f4b Moved src/g5505_file_reader.py -> instruments/readers/g5505_file_reader.py to increase modularity with respect to new intrument additions. 2024-08-23 10:11:29 +02:00
1112a214e9 Moved src/g5505_utils.py to utils/g5505_utils.py 2024-08-23 07:27:39 +02:00
d7fc38abd9 Moved get_parent_relationships func into hdf5_vis.py and cleaned up unused import statements 2024-08-22 09:50:26 +02:00
05d1133e32 Moved get_parent_child_relationships() funct from hdf5_lib.py tinto hdf5_vis.py to avoid circular dependency between the lower level and higher level module. Thus removed also src.hdf5_lib.py import statement. 2024-08-22 09:47:57 +02:00
d7c7808400 Implemented method for appending new attributes to an specific object. 2024-08-16 09:32:58 +02:00
bb250e9940 Implemented method to reformat a given column in a datatable holding datetime info into a desired datetime format. During data integration this will serve to normalize datatime formats across data tables 2024-08-16 08:08:28 +02:00
062a688f47 Added method to reformat columns containing datetime byte strings into a desired datetime formated object 2024-08-14 16:22:28 +02:00
5124df14d8 Changed link to descriptions according to new instrument folder location. 2024-08-12 13:40:43 +02:00
c876e925a7 Modified code to point to new instrument folders location. Also, upgrated code to accept either a user specified location or the default location 2024-08-12 13:40:01 +02:00
7f0e5384ea Moved instruments folder outside src/. 2024-08-12 10:09:21 +02:00
18aba8d0d3 Implemented dataset append method in HDF5DatOpsAPI 2024-08-09 15:25:09 +02:00
5fe7fc4b70 Developed a class to manage data operations on a given hdf5 file 2024-08-09 13:23:54 +02:00
8f7f14ab68 Removed time stamp configuration attributes from ACSM_TOFWARE, because it can be messy for a configuration file. 2024-08-08 11:24:41 +02:00
74db800e01 Updated file with new instrument configuration ACSM. 2024-08-07 16:38:52 +02:00
ae1e3bfc23 Moved ext_to_reader_dict to g5505_file_reader.py and replaced redear selection based on g5505_reader.select_file_reader(hdf5_file_path). 2024-08-07 16:30:36 +02:00
4e669b3eee Moved hdf5_file_path to file reader mapping and extension definitions to g5505_file_reader_module.py. Created functions to compute file_reader key from path to file in the hdf5 file and select the reader based on the key. This should enable more modular file reader selection. 2024-08-07 16:21:22 +02:00
3430627494 Modified reader to output table_preamble as a dataset as opposed to attributes of the file. I believe this is better for readability of the metadata given that those preambles can sometimes contain large ammounts of text. 2024-08-02 14:37:06 +02:00
4e584b9d90 Modified .yaml config files to satisty metadata naming expectations. 2024-07-17 08:50:24 +02:00
938e8e50a1 Changed names of expected root level metadata attributes. 2024-07-17 08:48:47 +02:00
a06e28291c Added attribution insertion order tracking at the root level and reorganized a few import statements. 2024-07-17 08:41:40 +02:00
2ebe5f3220 Made edits to documentation 2024-07-11 13:42:38 +02:00
f04f5eaaf9 Robustified column name to description assigment, however it may be a bit slower than before. 2024-07-10 13:31:47 +02:00
5c6fcabf91 Updated the yaml instrument descriptions. 2024-07-10 13:29:14 +02:00
73beb83278 Moved parse_attribute() from ..review_lib.py into ...utils.py and backpropagate (refactored) changes to respective modules. 2024-07-10 11:32:00 +02:00
2ce925735d Modified return datetime output to a format without colons, which could be problematic for filenaming. 2024-07-10 09:47:56 +02:00
0a0b4ac41d Moved a few functions from ...reader.py and hdf5_lib.py into ..utils.py, and refactored accordingly. 2024-07-10 09:19:30 +02:00
0c74c52e09 Removed smogchamber reader because its funtionality is now integrated into g5505_file_reader.py. 2024-07-09 16:13:01 +02:00
afc6c93823 Removed non utilized code. 2024-07-08 15:29:13 +02:00
cb7d914908 Cleaned code and modified def create_hdf5_file_from_dataframe to create group hierichy implicitly from path rather than recursively. 2024-07-08 15:24:48 +02:00
92eca4d79e Moved remaining git operations in metadata_review_lib.py to git_ops.py and refactored accoringly 2024-07-05 15:46:20 +02:00
77386432f8 Merge branch 'main' of https://gitlab.psi.ch/5505/dima 2024-07-02 16:50:08 +02:00
177a5aa2a1 Updated documentation. 2024-07-02 16:49:48 +02:00
ca8570b3b0 Merge branch 'main' of https://gitlab.psi.ch/5505/dima 2024-07-01 16:20:06 +02:00
ba6d89d8e1 Modified created at function to output date time and time zone 2024-07-01 16:19:28 +02:00
c074e45892 Renamed script_name to processing_file. 2024-07-01 16:17:25 +02:00
b816e62f3b Made a few edits. 2024-06-21 15:55:44 +02:00
db199f81e0 Merge branch 'main' of https://gitlab.psi.ch/5505/dima 2024-06-21 15:42:46 +02:00
6d6caf96db Cleared out outputs. 2024-06-21 15:42:23 +02:00
5ab775ecac Added a few root level metadata names and definitions 2024-06-21 15:40:38 +02:00
cedfe614e7 Implemented input argument to enable append information to exisintg attributes, which must take the values of either strings or lists. 2024-06-20 15:32:33 +02:00
106795ae59 Added a few lines to detect the existence of the file and change the file mode from 'w' to 'a' based on that information. 2024-06-20 09:03:47 +02:00
498a51cbc6 Updated function to add project level metadata at the root group of the hdf5 file. 2024-06-19 18:31:11 +02:00
06c5c6d84b Incorporated method to MetadataHarvester class to collect project level metadata. 2024-06-19 18:30:02 +02:00
04558e7785 Added code to parse dict attributes. 2024-06-18 14:42:51 +02:00
a6868d985d Fixed bug regarding datetime to str column conversion in dataframe by using .map(srt) (element wise operation) as opposed to .apply(str) 2024-06-18 09:21:46 +02:00
b66dc11a62 Replaced applymap to .apply because the former is being depricated 2024-06-17 13:47:54 +02:00
ed1641af55 Created function to save dataframes with annotations in hdf5 format 2024-06-17 13:36:05 +02:00
0eba80db41 Added metadata printer method and rewrote slightly a few class terms. 2024-06-17 08:44:44 +02:00
c68e800967 Incorporated dataframe_to_np_structured_array(df: pd.DataFrame) from another module. 2024-06-16 18:39:30 +02:00
e4de4edf28 Incorporated dataframe_to_np_structured_array(df: pd.DataFrame) from another module. 2024-06-16 18:26:12 +02:00
2d4ecec806 Moved dataframe_to_np_structured_array(df: pd.DataFrame) to src/g5505_utils.py. This is a more generic function that can be used more broadly accross modules. 2024-06-16 18:25:08 +02:00
6f5c49dc64 Removed lenthy example. 2024-06-13 16:03:04 +02:00
a301d42ad5 Replaced add_data_level_info to add_dataset. 2024-06-13 16:01:27 +02:00
0fb14b7c6c Developed a metadata harvesting object to facilitate metadata collection throught the code. 2024-06-13 15:47:02 +02:00
f43d86e729 Modified a few variable values in yaml files so that they are within expected values. 2024-06-13 15:45:39 +02:00
9ab9aa49c4 Abstracted a code snippet from def create_hdf5_file_from_filesystem_path(..) as transfer_file_dict_to_hdf5() so that it can be reusable. 2024-06-13 15:44:01 +02:00
cbca94390f Modified hardcoded paths to adapt with respect to the parent directory 2024-06-11 17:30:58 +02:00
e7ed6145f0 Implemented a data extraction module to access data from an hdf5 file in the form of dataframes. 2024-06-11 10:38:04 +02:00
a410bde23e Removed data table split into categorical and numerical variables and numering is only introduce to disambiguate repeated columns. 2024-06-10 16:18:51 +02:00
1ec7ad76ff Removed additional numbering from some intrument specifications. These are now only added if the column names are ambigous. 2024-06-10 16:14:13 +02:00
726e9b3503 Fixed bug in the case where data_integration_mode = 'collection'. 2024-06-07 16:45:00 +02:00
dba5bc9ea7 Updated instrument names from ICAD/HONO and ICAD/NO2 to HONO and NO2. 2024-06-07 16:41:41 +02:00
197ad0288a Updated file reader and data integration with datastart and dataend properties. 2024-06-04 13:37:20 +02:00
9dcc757acc renamed folder src/instrument_descriptions/ to src/intruments/ and moved text_data_sources.yaml in there. 2024-06-04 10:54:09 +02:00
a6ddb24eeb Added .strip to column names to remove unwanted characters (\r|\t|\n) and included units description to timestamps. 2024-06-04 09:57:37 +02:00
fa2990527e Simplified and documented parse_attribute function. 2024-06-04 09:51:12 +02:00
014bd14fcd Modified temperature units from °C to Celcius for simpler string encoding. It seems ascii codec cannot encode such a character 2024-06-04 09:44:09 +02:00
385267a98f Updated treemap visualization to select only root metadata, which is of string type. 2024-06-03 14:17:42 +02:00
560481610c Updated root metadata display in treemaps 2024-06-02 16:43:54 +02:00
c74b6c1a91 Updated instrument attributes with datetime_format and desired_format. 2024-06-02 16:14:30 +02:00
1054367f12 Modified annotate_root_dir function. 2024-06-02 16:02:48 +02:00
d335836a7d Updated reader to standardize timestamps to a desired format when possible. The desired format is set in text_data_sources.yaml. 2024-06-02 15:59:01 +02:00
69f3857936 Implemented functions for data extraction from hdf5 files. 2024-05-31 12:39:10 +02:00
e6de1ff55d Incorporated jupyter notebook of simple example metadata annotation workflow. 2024-05-30 12:24:12 +02:00
4de7834a91 Updated readme file 2024-05-30 12:21:17 +02:00
76bffc6afe Updated notebook documentation and included an example metadata annotation notebook. 2024-05-30 12:20:34 +02:00
a0318681be Removed html file no longer useful. 2024-05-30 12:18:28 +02:00
922bb3ca64 Updated YAML config file parsing logic to account for changes in config file description. 2024-05-30 12:16:54 +02:00
7f423ccc6f Decomposed experiment_data into experiment_startdate and experiment_enddate. 2024-05-30 12:15:49 +02:00
3a9aede909 Made def third_update_hdf5_file_with_review more modular by separating data update and git operations, resulting new functions that can be reused in less restrictive matadata annotation contexts. 2024-05-29 15:26:48 +02:00
ef7c6c9efb Implemented a git operations module for automated git ops, based on subprocess. 2024-05-29 15:17:09 +02:00
146981379f Updated readme file. 2024-05-29 11:24:46 +02:00
71f284f709 Updated readme file 2024-05-29 11:23:33 +02:00
4ffd790059 Updated project name in configuration file 2024-05-28 15:06:25 +02:00
dad5e082f1 Changed ordering of data integration config files so that they align with our experimental campaign hierarchy. 2024-05-28 14:43:32 +02:00
a86fc97605 Refactored due to updates in the file reader function. 2024-05-28 14:41:34 +02:00
3de6abce50 added the feature to activate or deactivate data copying before reading the input file. This is to avoid redundant copying when we are already working on file copies. 2024-05-28 14:40:14 +02:00
fd1c6461bb Updated some of the raname_as metadata for all instruments so that it is much machine readable and perhpas be used as an alternative to the original name in future releases. 2024-05-28 14:37:43 +02:00
804ea52583 Modified function to return list of paths when config_file.yaml integration mode = experimental step. 2024-05-28 11:29:32 +02:00
f6a46168ec Improved parsing from HDF5 attr dict to yaml compatible dict. Now we can parse HDF5 compound attributes (structured np arrays). 2024-05-28 11:27:44 +02:00
41c7660be3 Enhanced data transfer progress visualization and logging 2024-05-28 08:59:29 +02:00
08d58557df Fixed bug that didnot allowed analythical_methods composite keywords (e.g., ICAD/HONO) to be matched in intrument configurations. 2024-05-28 08:57:57 +02:00
3270ce5ed7 Implemented reader file compatibility check. 2024-05-27 18:22:16 +02:00
2911416431 Improved modularity of hdf5_file creation by creating a function that copies the intput directory file and applies directory, files, and extensions constraints before regular directory to hdf5 transfer. See [200~def copy_directory_with_contraints(input_dir_path, output_dir_path, select_dir_keywords, select_file_keywords, allowed_file_extensions): 2024-05-27 18:15:08 +02:00
24a2d5d37e Refactored list to array conversion using metadata_rewiew_lib 2024-05-26 15:04:07 +02:00
77afbbbf8f Added function to convert list of strings into a np.array of bytes. This is useful to create list-valued attributes in HDF5. 2024-05-26 14:56:36 +02:00
88572b44b1 Fixed buggy statement. import datetime ... followed by datetime.now() was fixed as datetime.datetime.now(). 2024-05-26 12:26:54 +02:00
37071945f5 Removed hdf5 file creation redundancy by creating a helper function create_HDF5_file(date_str,select_file_keywords), which handles variations in date_str and keywords. 2024-05-26 12:24:15 +02:00
4dc09339b5 Replaced lambda function with regular function and fstring for better readability and debugging 2024-05-26 11:39:40 +02:00
b7f9bfe149 Replaced print statement with logging and raise exception for better error handling and managment 2024-05-26 11:34:20 +02:00
ac37235072 Added function setup_logging to configure logger to record logs in specified output directory. 2024-05-26 11:19:54 +02:00
8f1a82c00d updated env file 2024-05-24 15:55:49 +02:00
c7051bfe69 updated readme and reader to handle ignore ascii character errors 2024-05-24 15:55:15 +02:00
9329f39deb Deleted output no longer returned in data integration pipeline 2024-05-24 14:55:08 +02:00
b5ed1cb826 Updated readme file 2024-05-24 11:56:30 +02:00
005e855e48 Updated configuration file organization and workflow description. 2024-05-24 11:15:05 +02:00
784cb1eb62 Commented out openia python module. 2024-05-24 10:54:15 +02:00
d000a8348f Added bottom level instrument metadata descriptions such as units and description. 2024-05-24 09:50:25 +02:00
8d4f4e68c7 Removed yaml file output from data integration file. The creation of this file is being outsource to data store repo 2024-05-24 09:32:30 +02:00
88de88c316 Removed creation of yaml file subsequent to data integration. This can cause misalignment with data store. I think the yaml snapshot of a hdf5 file should therefore be outsourced there. 2024-05-24 09:30:24 +02:00
1537633b1a Made a few optimizations to code and documentation. Expressions relying on list comprehensions were simplified with generator expressions. ex,: any([keyword in filename for keyword in select_file_keywords]) was simplified to any(keyword in filename for keyword in select_file_keywords). 2024-05-24 09:06:07 +02:00
d574ac382d Replaced attribute table_header in Lopap configuration file with a shorter version which is consistent accross more files. Some of the headers might change. 2024-05-24 08:55:36 +02:00
63b683e4aa Optimzed and included df to np structured array conversion. \n-Replaced loop plus append with list comprehension. \n-Replaced pd df column concatenation based on row-wise concatenation with df.aggr() method that uses column wise concatenation. 2024-05-23 22:20:19 +02:00
bd458c6cd0 Optimzed and included df to np structured array conversion. \n-Replaced loop plus append with list comprehension. \n-Replaced pd df column concatenation based on row-wise concatenation with df.aggr() method that uses column wise concatenation. 2024-05-23 22:18:37 +02:00
a45fb4476b Replaced commented lines by accurate comments 2024-05-22 20:15:17 +02:00
7367da84b9 Simplified code by updating HDF5 attributes using .update() dict method (inherited from dict type). 2024-05-22 20:11:54 +02:00
1729cd40fa Added feature to interpret links to description in the yaml intrument configuration file and added them at the dataset level as attributes. 2024-05-09 19:17:08 +02:00
1429c56916 Added link to descriptions and units of table variables/or columns. These can be used as attributes of datasets from tabular data 2024-05-09 19:15:20 +02:00
f49120102d Included timestamp specification, which indicates column names in a list that contain datetime information. 2024-04-30 14:51:58 +02:00
553c3fe946 Incorparated feature to merge data and time data which may originally be in separate columns in text source files. This is specified in the text source specification yaml file 2024-04-30 14:50:33 +02:00
f3c2777bb0 Performed edits to README.md 2024-04-26 14:33:41 +02:00
4fd3bb1957 Updated readme file with instructions on how to set compound attributes and delete them. 2024-04-26 14:27:01 +02:00
493be88f49 Removed unecessary pygit depenedency and associated function that relied on it. 2024-04-26 13:15:33 +02:00
f25fc67fc1 Cleared out jupyter notebook. 2024-04-26 13:09:41 +02:00
4d91e59279 Included new delete attribute and restart review features. 2024-04-26 13:08:27 +02:00
14ae29bf3c Corrected parsing problem from hdf5 to yaml attribute. Single element arrays are now represented as a scalar as opposed to a list with a single element. 2024-04-26 12:54:41 +02:00
cefa2219e1 Submitted metadata review. 2024-04-26 11:30:05 +02:00
2ef171c6d0 Updated hdf5 file with yaml review file. 2024-04-26 11:28:58 +02:00
05dc90d8af Submitted metadata review. 2024-04-26 11:07:42 +02:00
7469003524 Initialized metadata review. 2024-04-26 10:56:32 +02:00
6c73fbb695 Submitted metadata review. 2024-04-25 16:56:06 +02:00
70b0c10316 Submitted metadata review. 2024-04-25 16:47:44 +02:00
21 changed files with 1021 additions and 8166 deletions

1
.gitignore vendored
View File

@@ -7,3 +7,4 @@ logs/
envs/ envs/
hidden.py hidden.py
output_files/ output_files/
.env

22
CHANGELOG.md Normal file
View File

@@ -0,0 +1,22 @@
# Changelog
All notable changes to this project will be documented in this file, which is a **cumulative record**.
Each version entry follows a consistent structure with the following optional sections:
- **Added** New features
- **Changed** Modifications to existing functionality
- **Deprecated** Features marked for future removal
- **Removed** Features removed in this version
- **Fixed** Bug fixes
- **Security** Vulnerability fixes
Format based on [Keep a Changelog](https://keepachangelog.com) and [Semantic Versioning](https://semver.org).
## [1.0.0] - 2025-06-26
### Added
- Multi-format, multi-instrument file reading system for FAIR data processing
- Data integration pipeline with YAML-based configuration for cross-project adaptability
- Metadata revision and normalization pipeline
- HDF5 manager object for data extraction, handling, and visualization

View File

@@ -32,7 +32,10 @@ For **Windows** users, the following are required:
2. **Conda**: Install [Anaconda](https://www.anaconda.com/products/individual) or [Miniconda](https://docs.conda.io/en/latest/miniconda.html). 2. **Conda**: Install [Anaconda](https://www.anaconda.com/products/individual) or [Miniconda](https://docs.conda.io/en/latest/miniconda.html).
3. **PSI Network Access**: Ensure access to PSIs network and access rights to source drives for retrieving campaign data from YAML files in the `input_files/` folder. 3. **PSI Network Access**
Ensure you have access to the PSI internal network and the necessary permissions to access the source directories. See [notebooks/demo_data_integration.ipynb](notebooks/demo_data_integration.ipynb) for details on how to set up data integration from network drives.
:bulb: **Tip**: Editing your systems PATH variable ensures both Conda and Git are available in the terminal environment used by Git Bash. :bulb: **Tip**: Editing your systems PATH variable ensures both Conda and Git are available in the terminal environment used by Git Bash.
@@ -43,11 +46,11 @@ For **Windows** users, the following are required:
Open a **Git Bash** terminal. Open a **Git Bash** terminal.
Navigate to your `GitLab` folder, clone the repository, and navigate to the `dima` folder as follows: Navigate to your `Gitea` folder, clone the repository, and navigate to the `dima` folder as follows:
```bash ```bash
cd path/to/GitLab cd path/to/Gitea
git clone --recurse-submodules https://gitlab.psi.ch/5505/dima.git git clone --recurse-submodules https://gitea.psi.ch/5505-public/dima.git
cd dima cd dima
``` ```
@@ -206,7 +209,7 @@ This section is in progress!
| actris_level | - | Indicates the processing level of the data within the ACTRIS (Aerosol, Clouds and Trace Gases Research Infrastructure) framework. | | actris_level | - | Indicates the processing level of the data within the ACTRIS (Aerosol, Clouds and Trace Gases Research Infrastructure) framework. |
| dataset_startdate | - | Denotes the start datetime of the dataset collection. | | dataset_startdate | - | Denotes the start datetime of the dataset collection. |
| dataset_enddate | - | Denotes the end datetime of the dataset collection. | | dataset_enddate | - | Denotes the end datetime of the dataset collection. |
| processing_file | - | Denotes the name of the file used to process an initial version (e.g, original version) of the dataset into a processed dataset. | | processing_script | - | Denotes the name of the file used to process an initial version (e.g, original version) of the dataset into a processed dataset. |
| processing_date | - | The date when the data processing was completed. | | | processing_date | - | The date when the data processing was completed. | |
## Adaptability to Experimental Campaign Needs ## Adaptability to Experimental Campaign Needs

View File

@@ -1,8 +1,8 @@
# Path to the directory where raw data is stored # Path to the directory where raw data is stored
input_file_directory: '//fs101/5505/Data' input_file_directory: '${NETWORK_MOUNT}/Data'
# Path to directory where raw data is copied and converted to HDF5 format for local analysis. # Path to directory where raw data is copied and converted to HDF5 format for local analysis.
output_file_directory: '../output_files/' output_file_directory: '../data/'
# Project metadata for data lineage and provenance # Project metadata for data lineage and provenance
project: 'Photoenhanced uptake of NO2 driven by Fe(III)-carboxylate' project: 'Photoenhanced uptake of NO2 driven by Fe(III)-carboxylate'

View File

@@ -1,8 +1,8 @@
# Path to the directory where raw data is stored # Path to the directory where raw data is stored
input_file_directory: '//fs101/5505/People/Juan/TypicalBeamTime' input_file_directory: '${NETWORK_MOUNT}/People/Juan/TypicalBeamTime'
# Path to directory where raw data is copied and converted to HDF5 format for local analysis. # Path to directory where raw data is copied and converted to HDF5 format for local analysis.
output_file_directory: 'output_files/' output_file_directory: '../data/'
# Project metadata for data lineage and provenance # Project metadata for data lineage and provenance
project: 'Beamtime May 2024, Ice Napp' project: 'Beamtime May 2024, Ice Napp'

View File

@@ -1,8 +1,8 @@
# Path to the directory where raw data is stored # Path to the directory where raw data is stored
input_file_directory: '//fs03/Iron_Sulphate' input_file_directory: '${NETWORK_MOUNT}/Chamber Data/L0 -raw data'
# Path to directory where raw data is copied and converted to HDF5 format for local analysis. # Path to directory where raw data is copied and converted to HDF5 format for local analysis.
output_file_directory: 'output_files/' output_file_directory: '../data/'
# Project metadata for data lineage and provenance # Project metadata for data lineage and provenance
project: 'Fe SOA project' project: 'Fe SOA project'

View File

@@ -0,0 +1,42 @@
table_header:
w_CenterTime:
description: time between start and stop of the measurement
units: YYYY/MM/DD HH:MM:SS
rename_as: center_time
w_StartTime:
description: Start time of the measurement
units: YYYY/MM/DD HH:MM:SS
rename_as: start_time
w_StopTime:
description: Stop time of the measurement
units: YYYY/MM/DD HH:MM:SS
rename_as: stop_time
w_I2_molec_cm3:
description: I2 concentration
units: cm^-1
rename_as: i2_concentration
w_I2_SlCol:
description: I2 concentration sl #?
units: ppb #?
rename_as: i2_sl
w_I2_SlErr:
description: Uncertainty in I2 concentration sl #?
units: ppb #?
rename_as: i2_sl_uncertainty
w_I2_VMR:
description: I2 concentration vmr #?
units: ppb #?
rename_as: i2_vmr
w_I2_VMRErr:
description: Uncertainty in I2 concentration vmr
units: ppb #?
rename_as: i2_vmr_uncertainty
w_Rho:
description: Rho #?
units: ppb #?
rename_as: rho
w_RMS:
description: RMS #?
units: ppb #?
rename_as: rms

View File

@@ -16,8 +16,9 @@ from instruments.readers.g5505_text_reader import read_txt_files_as_dict
from instruments.readers.acsm_tofware_reader import read_acsm_files_as_dict from instruments.readers.acsm_tofware_reader import read_acsm_files_as_dict
from instruments.readers.acsm_flag_reader import read_jsonflag_as_dict from instruments.readers.acsm_flag_reader import read_jsonflag_as_dict
from instruments.readers.nasa_ames_reader import read_nasa_ames_as_dict from instruments.readers.nasa_ames_reader import read_nasa_ames_as_dict
from instruments.readers.structured_file_reader import read_structured_file_as_dict
file_extensions = ['.ibw','.txt','.dat','.h5','.TXT','.csv','.pkl','.json','.yaml','.nas'] file_extensions = ['.ibw','.txt','.dat','.h5','.TXT','.csv','.pkl','.json','.yaml','yml','.nas']
# Define the instruments directory (modify this as needed or set to None) # Define the instruments directory (modify this as needed or set to None)
default_instruments_dir = None # or provide an absolute path default_instruments_dir = None # or provide an absolute path
@@ -27,11 +28,16 @@ file_readers = {
'txt': lambda a1: read_txt_files_as_dict(a1, instruments_dir=default_instruments_dir, work_with_copy=False), 'txt': lambda a1: read_txt_files_as_dict(a1, instruments_dir=default_instruments_dir, work_with_copy=False),
'dat': lambda a1: read_txt_files_as_dict(a1, instruments_dir=default_instruments_dir, work_with_copy=False), 'dat': lambda a1: read_txt_files_as_dict(a1, instruments_dir=default_instruments_dir, work_with_copy=False),
'csv': lambda a1: read_txt_files_as_dict(a1, instruments_dir=default_instruments_dir, work_with_copy=False), 'csv': lambda a1: read_txt_files_as_dict(a1, instruments_dir=default_instruments_dir, work_with_copy=False),
'yaml': lambda a1: read_structured_file_as_dict(a1),
'yml': lambda a1: read_structured_file_as_dict(a1),
'json': lambda a1: read_structured_file_as_dict(a1),
'ACSM_TOFWARE_txt' : lambda x: read_acsm_files_as_dict(x, instruments_dir=default_instruments_dir, work_with_copy=False), 'ACSM_TOFWARE_txt' : lambda x: read_acsm_files_as_dict(x, instruments_dir=default_instruments_dir, work_with_copy=False),
'ACSM_TOFWARE_csv' : lambda x: read_acsm_files_as_dict(x, instruments_dir=default_instruments_dir, work_with_copy=False), 'ACSM_TOFWARE_csv' : lambda x: read_acsm_files_as_dict(x, instruments_dir=default_instruments_dir, work_with_copy=False),
'ACSM_TOFWARE_flags_json' : lambda x: read_jsonflag_as_dict(x), 'ACSM_TOFWARE_flags_json' : lambda x: read_jsonflag_as_dict(x),
'ACSM_TOFWARE_nas' : lambda x: read_nasa_ames_as_dict(x)} 'ACSM_TOFWARE_nas' : lambda x: read_nasa_ames_as_dict(x)}
file_readers.update({'CEDOAS_txt' : lambda x: read_txt_files_as_dict(x, instruments_dir=default_instruments_dir, work_with_copy=False)})
REGISTRY_FILE = "registry.yaml" #os.path.join(os.path.dirname(__file__), "registry.yaml") REGISTRY_FILE = "registry.yaml" #os.path.join(os.path.dirname(__file__), "registry.yaml")
def load_registry(): def load_registry():
@@ -52,7 +58,7 @@ def find_reader(instrument_folder, file_extension):
registry = load_registry() registry = load_registry()
for entry in registry: for entry in registry:
if entry["instrumentFolderName"] == instrument_folder and entry["fileExtension"] == file_extension: if entry["instrumentFolderName"] == instrument_folder and (file_extension in entry["fileExtension"].split(sep=',')):
return entry["fileReaderPath"], entry["InstrumentDictionaryPath"] return entry["fileReaderPath"], entry["InstrumentDictionaryPath"]
return None, None # Not found return None, None # Not found

View File

@@ -81,32 +81,18 @@ gas:
datetime_format: '%Y.%m.%d %H:%M:%S' datetime_format: '%Y.%m.%d %H:%M:%S'
link_to_description: 'dictionaries/gas.yaml' link_to_description: 'dictionaries/gas.yaml'
ACSM_TOFWARE: CEDOAS: #CE-DOAS/I2:
table_header: formats:
#txt: - table_header: 'w_CenterTime w_StartTime w_StopTime w_I2_molec_cm3 w_I2_SlCol w_I2_SlErr w_I2_VMR w_I2_VMRErr w_Rho w_RMS'
- 't_base VaporizerTemp_C HeaterBias_V FlowRefWave FlowRate_mb FlowRate_ccs FilamentEmission_mA Detector_V AnalogInput06_V ABRefWave ABsamp ABCorrFact' separator: '\t'
- 't_start_Buf,Chl_11000,NH4_11000,SO4_11000,NO3_11000,Org_11000,SO4_48_11000,SO4_62_11000,SO4_82_11000,SO4_81_11000,SO4_98_11000,NO3_30_11000,Org_60_11000,Org_43_11000,Org_44_11000' file_encoding: 'utf-8'
#csv: timestamp: ['w_CenterTime']
- "X4 X5 X6 X7 X8 X9 X10 X11 X12 X13 X14 X15 X16 X17 X18 X19 X20 X21 X22 X23 X24 X25 X26 X27 X28 X29 X30 X31 X32 X33 X34 X35 X36 X37 X38 X39 X40 X41 X42 X43 X44 X45 X46 X47 X48 X49 X50 X51 X52 X53 X54 X55 X56 X57 X58 X59 X60 X61 X62 X63 X64 X65 X66 X67 X68 X69 X70 X71 X72 X73 X74 X75 X76 X77 X78 X79 X80 X81 X82 X83 X84 X85 X86 X87 X88 X89 X90 X91 X92 X93 X94 X95 X96 X97 X98 X99 X100 X101 X102 X103 X104 X105 X106 X107 X108 X109 X110 X111 X112 X113 X114 X115 X116 X117 X118 X119 X120 X121 X122 X123 X124 X125 X126 X127 X128 X129 X130 X131 X132 X133 X134 X135 X136 X137 X138 X139 X140 X141 X142 X143 X144 X145 X146 X147 X148 X149 X150 X151 X152 X153 X154 X155 X156 X157 X158 X159 X160 X161 X162 X163 X164 X165 X166 X167 X168 X169 X170 X171 X172 X173 X174 X175 X176 X177 X178 X179 X180 X181 X182 X183 X184 X185 X186 X187 X188 X189 X190 X191 X192 X193 X194 X195 X196 X197 X198 X199 X200 X201 X202 X203 X204 X205 X206 X207 X208 X209 X210 X211 X212 X213 X214 X215 X216 X217 X218 X219" datetime_format: '%Y/%m/%d %H:%M:%S'
- "X4 X5 X6 X7 X8 X9 X10 X11 X12 X13 X14 X15 X16 X17 X18 X19 X20 X21 X22 X23 X24 X25 X26 X27 X28 X29 X30 X31 X32 X33 X34 X35 X36 X37 X38 X39 X40 X41 X42 X43 X44 X45 X46 X47 X48 X49 X50 X51 X52 X53 X54 X55 X56 X57 X58 X59 X60 X61 X62 X63 X64 X65 X66 X67 X68 X69 X70 X71 X72 X73 X74 X75 X76 X77 X78 X79 X80 X81 X82 X83 X84 X85 X86 X87 X88 X89 X90 X91 X92 X93 X94 X95 X96 X97 X98 X99 X100 X101 X102 X103 X104 X105 X106 X107 X108 X109 X110 X111 X112 X113 X114 X115 X116 X117 X118 X119 X120 X121 X122 X123 X124 X125 X126 X127 X128 X129 X130 X131 X132 X133 X134 X135 X136 X137 X138 X139 X140 X141 X142 X143 X144 X145 X146 X147 X148 X149 X150 X151 X152 X153 X154 X155 X156 X157 X158 X159 X160 X161 X162 X163 X164 X165 X166 X167 X168 X169 X170 X171 X172 X173 X174 X175 X176 X177 X178 X179 X180 X181 X182 X183 X184 X185 X186 X187 X188 X189 X190 X191 X192 X193 X194 X195 X196 X197 X198 X199 X200 X201 X202 X203 X204 X205 X206 X207 X208 X209 X210 X211 X212 X213 X214 X215 X216 X217 X218 X219"
- 'MSS_base'
- 'tseries'
separator:
#txt:
- "\t"
- ","
#csv:
- "\t"
- "\t"
- "None"
- "None"
file_encoding:
#txt:
- "utf-8"
- "utf-8"
#csv:
- "utf-8"
- "utf-8"
- "utf-8"
- "utf-8"
- table_header: 'TimeStamp,Seconds_Midnight,Year,Month,Day,Hour,Minute,Second,HK0,HK1,HK2,HK3,HK4,HK5,HK6,HK7,HK8,HK9,HK10,HK11,HK12,HK13,HK14,HK15,RTD0_OO1,RTD1_LED,RTD2,RTD3_CBox,RTD4_Gas1,RTD5,RTD6,RTD7,Temp0,Temp1,Temp2,Temp3,DutyCycle0,DutyCycle1,DutyCycle2,DutyCycle3,Relay4,Relay5,Shutter0,Shutter1,Diode0Threshold,Diode0Hysteresis,Diode1Threshold,Diode1Hysteresis,SWTargetPosition,SWCurrentPosition,ELTargetPosition'
separator: ','
file_encoding: 'utf-8'
#timestamp: []
#datetime_format:
link_to_description: 'dictionaries/CEDOAS.yaml'

View File

@@ -19,16 +19,7 @@ import yaml
import h5py import h5py
import argparse import argparse
import logging import logging
# Import project modules import warnings
#root_dir = os.path.abspath(os.curdir)
#sys.path.append(root_dir)
#try:
# from dima.utils import g5505_utils as utils
#except ModuleNotFoundError:
# import utils.g5505_utils as utils
# import src.hdf5_ops as hdf5_ops
import utils.g5505_utils as utils import utils.g5505_utils as utils
@@ -41,56 +32,19 @@ def read_txt_files_as_dict(filename: str, instruments_dir: str = None, work_with
module_dir = os.path.dirname(__file__) module_dir = os.path.dirname(__file__)
instruments_dir = os.path.join(module_dir, '..') instruments_dir = os.path.join(module_dir, '..')
# Normalize the path (resolves any '..' in the path) #(config_dict,
instrument_configs_path = os.path.abspath(os.path.join(instruments_dir,'readers','config_text_reader.yaml')) #file_encoding,
#separator,
#table_header,
#timestamp_variables,
#datetime_format,
#description_dict) = load_file_reader_parameters(filename, instruments_dir)
print(instrument_configs_path) format_variants, description_dict = load_file_reader_parameters(filename, instruments_dir)
with open(instrument_configs_path,'r') as stream:
try:
config_dict = yaml.load(stream, Loader=yaml.FullLoader)
except yaml.YAMLError as exc:
print(exc)
# Verify if file can be read by available intrument configurations.
#if not any(key in filename.replace(os.sep,'/') for key in config_dict.keys()):
# return {}
#TODO: this may be prone to error if assumed folder structure is non compliant
file_encoding = config_dict['default']['file_encoding'] #'utf-8'
separator = config_dict['default']['separator']
table_header = config_dict['default']['table_header']
timestamp_variables = []
datetime_format = []
tb_idx = 0
column_names = ''
description_dict = {}
for instFolder in config_dict.keys():
if instFolder in filename.split(os.sep):
file_encoding = config_dict[instFolder].get('file_encoding',file_encoding)
separator = config_dict[instFolder].get('separator',separator)
table_header = config_dict[instFolder].get('table_header',table_header)
timestamp_variables = config_dict[instFolder].get('timestamp',[])
datetime_format = config_dict[instFolder].get('datetime_format',[])
link_to_description = config_dict[instFolder].get('link_to_description', '').replace('/', os.sep)
if link_to_description:
path = os.path.join(instruments_dir, link_to_description)
try:
with open(path, 'r') as stream:
description_dict = yaml.load(stream, Loader=yaml.FullLoader)
except (FileNotFoundError, yaml.YAMLError) as exc:
print(exc)
#if 'None' in table_header:
# return {}
# Read header as a dictionary and detect where data table starts # Read header as a dictionary and detect where data table starts
header_dict = {} header_dict = {'actris_level': 0, 'processing_date':utils.created_at(), 'processing_script' : os.path.relpath(thisFilePath,dimaPath)}
data_start = False data_start = False
# Work with copy of the file for safety # Work with copy of the file for safety
if work_with_copy: if work_with_copy:
@@ -98,77 +52,35 @@ def read_txt_files_as_dict(filename: str, instruments_dir: str = None, work_with
else: else:
tmp_filename = filename tmp_filename = filename
#with open(tmp_filename,'rb',encoding=file_encoding,errors='ignore') as f: # Run header detection
header_line_number, column_names, fmt_dict, table_preamble = detect_table_header_line(tmp_filename, format_variants)
if not isinstance(table_header, list): # Unpack validated format info
table_header = fmt_dict['table_header']
separator = fmt_dict['separator']
file_encoding = fmt_dict['file_encoding']
timestamp_variables = fmt_dict.get('timestamp', [])
datetime_format = fmt_dict.get('datetime_format', None)
desired_datetime_fmt = fmt_dict.get('desired_datetime_format', None)
table_header = [table_header] # Ensure separator is valid
file_encoding = [file_encoding] if not isinstance(separator, str) or not separator.strip():
separator = [separator] raise ValueError(f"Invalid separator found in format: {repr(separator)}")
table_preamble = []
line_number = 0
if 'infer' not in table_header:
with open(tmp_filename,'rb') as f:
for line_number, line in enumerate(f):
decoded_line = line.decode(file_encoding[tb_idx])
for tb_idx, tb in enumerate(table_header):
print(tb)
if tb in decoded_line:
break
if tb in decoded_line:
list_of_substrings = decoded_line.split(separator[tb_idx].replace('\\t','\t'))
# Count occurrences of each substring
substring_counts = collections.Counter(list_of_substrings)
data_start = True
# Generate column names with appended index only for repeated substrings
column_names = [f"{i}_{name.strip()}" if substring_counts[name] > 1 else name.strip() for i, name in enumerate(list_of_substrings)]
#column_names = [str(i)+'_'+name.strip() for i, name in enumerate(list_of_substrings)]
#column_names = []
#for i, name in enumerate(list_of_substrings):
# column_names.append(str(i)+'_'+name)
#print(line_number, len(column_names ),'\n')
break
else:
print('Table header was not detected.')
# Subdivide line into words, and join them by single space.
# I asumme this can produce a cleaner line that contains no weird separator characters \t \r or extra spaces and so on.
list_of_substrings = decoded_line.split()
# TODO: ideally we should use a multilinear string but the yalm parser is not recognizing \n as special character
#line = ' '.join(list_of_substrings+['\n'])
#line = ' '.join(list_of_substrings)
table_preamble.append(' '.join([item for item in list_of_substrings]))# += new_line
# TODO: it does not work with separator as none :(. fix for RGA
# Load DataFrame
try: try:
print(column_names) if 'infer' not in table_header:
if not 'infer' in table_header:
#print(table_header)
#print(file_encoding[tb_idx])
df = pd.read_csv(tmp_filename, df = pd.read_csv(tmp_filename,
delimiter = separator[tb_idx].replace('\\t','\t'), delimiter=separator,
header=line_number, header=header_line_number,
#encoding='latin-1', encoding=file_encoding,
encoding = file_encoding[tb_idx],
names=column_names, names=column_names,
skip_blank_lines=True) skip_blank_lines=True)
else: else:
df = pd.read_csv(tmp_filename, df = pd.read_csv(tmp_filename,
delimiter = separator[tb_idx].replace('\\t','\t'), delimiter=separator,
header=line_number, header=header_line_number,
encoding = file_encoding[tb_idx], encoding=file_encoding,
skip_blank_lines=True) skip_blank_lines=True)
df_numerical_attrs = df.select_dtypes(include ='number') df_numerical_attrs = df.select_dtypes(include ='number')
@@ -177,6 +89,10 @@ def read_txt_files_as_dict(filename: str, instruments_dir: str = None, work_with
# Consolidate into single timestamp column the separate columns 'date' 'time' specified in text_data_source.yaml # Consolidate into single timestamp column the separate columns 'date' 'time' specified in text_data_source.yaml
if timestamp_variables: if timestamp_variables:
if not all(col in df_categorical_attrs.columns for col in timestamp_variables):
raise ValueError(f"Invalid timestamp columns: {[col for col in timestamp_variables if col not in df_categorical_attrs.columns]}.")
#df_categorical_attrs['timestamps'] = [' '.join(df_categorical_attrs.loc[i,timestamp_variables].to_numpy()) for i in df.index] #df_categorical_attrs['timestamps'] = [' '.join(df_categorical_attrs.loc[i,timestamp_variables].to_numpy()) for i in df.index]
#df_categorical_attrs['timestamps'] = [ df_categorical_attrs.loc[i,'0_Date']+' '+df_categorical_attrs.loc[i,'1_Time'] for i in df.index] #df_categorical_attrs['timestamps'] = [ df_categorical_attrs.loc[i,'0_Date']+' '+df_categorical_attrs.loc[i,'1_Time'] for i in df.index]
@@ -192,7 +108,7 @@ def read_txt_files_as_dict(filename: str, instruments_dir: str = None, work_with
df_categorical_attrs = df_categorical_attrs.loc[valid_indices,:] df_categorical_attrs = df_categorical_attrs.loc[valid_indices,:]
df_numerical_attrs = df_numerical_attrs.loc[valid_indices,:] df_numerical_attrs = df_numerical_attrs.loc[valid_indices,:]
df_categorical_attrs[timestamps_name] = df_categorical_attrs[timestamps_name].dt.strftime(config_dict['default']['desired_format']) df_categorical_attrs[timestamps_name] = df_categorical_attrs[timestamps_name].dt.strftime(desired_datetime_fmt)
startdate = df_categorical_attrs[timestamps_name].min() startdate = df_categorical_attrs[timestamps_name].min()
enddate = df_categorical_attrs[timestamps_name].max() enddate = df_categorical_attrs[timestamps_name].max()
@@ -205,12 +121,6 @@ def read_txt_files_as_dict(filename: str, instruments_dir: str = None, work_with
df_categorical_attrs = df_categorical_attrs.drop(columns = timestamp_variables) df_categorical_attrs = df_categorical_attrs.drop(columns = timestamp_variables)
#df_categorical_attrs.reindex(drop=True)
#df_numerical_attrs.reindex(drop=True)
categorical_variables = [item for item in df_categorical_attrs.columns]
#### ####
#elif 'RGA' in filename: #elif 'RGA' in filename:
# df_categorical_attrs = df_categorical_attrs.rename(columns={'0_Time(s)' : 'timestamps'}) # df_categorical_attrs = df_categorical_attrs.rename(columns={'0_Time(s)' : 'timestamps'})
@@ -285,13 +195,169 @@ def read_txt_files_as_dict(filename: str, instruments_dir: str = None, work_with
# if timestamps_name in categorical_variables: # if timestamps_name in categorical_variables:
# dataset['attributes'] = {timestamps_name: utils.parse_attribute({'unit':'YYYY-MM-DD HH:MM:SS.ffffff'})} # dataset['attributes'] = {timestamps_name: utils.parse_attribute({'unit':'YYYY-MM-DD HH:MM:SS.ffffff'})}
# file_dict['datasets'].append(dataset) # file_dict['datasets'].append(dataset)
#except Exception as e:
except Exception as e: except Exception as e:
#raise RuntimeError(f"Failed to read file with detected format: {e}")
print(e) print(e)
return {} return {}
return file_dict return file_dict
## Supporting functions
def detect_table_header_line(filepath, format_variants, verbose=False):
"""
Tries multiple format variants to detect the table header line in the file.
Args:
filepath (str): Path to file.
format_variants (List[Dict]): Each must contain:
- 'file_encoding' (str)
- 'separator' (str)
- 'table_header' (str or list of str)
verbose (bool): If True, prints debug info.
Returns:
Tuple:
- header_line_idx (int)
- column_names (List[str])
- matched_format (Dict[str, Any]) # full format dict (validated)
- preamble_lines (List[str])
"""
import collections
import warnings
for idx, fmt in enumerate(format_variants):
# Validate format dict
if 'file_encoding' not in fmt or not isinstance(fmt['file_encoding'], str):
raise ValueError(f"[Format {idx}] 'file_encoding' must be a string.")
if 'separator' not in fmt or not isinstance(fmt['separator'], str):
raise ValueError(f"[Format {idx}] 'separator' must be a string.")
if 'table_header' not in fmt or not isinstance(fmt['table_header'], (str, list)):
raise ValueError(f"[Format {idx}] 'table_header' must be a string or list of strings.")
encoding = fmt['file_encoding']
separator = fmt['separator']
header_patterns = fmt['table_header']
if isinstance(header_patterns, str):
header_patterns = [header_patterns]
preamble_lines = []
try:
with open(filepath, 'rb') as f:
for line_number, line in enumerate(f):
try:
decoded_line = line.decode(encoding)
except UnicodeDecodeError:
break # Try next format
for pattern in header_patterns:
if pattern in decoded_line:
substrings = decoded_line.split(separator.replace('\\t', '\t'))
counts = collections.Counter(substrings)
column_names = [
f"{i}_{name.strip()}" if counts[name] > 1 else name.strip()
for i, name in enumerate(substrings)
]
if verbose:
print(f"[Detected header] Line {line_number}: {column_names}")
return line_number, column_names, fmt, preamble_lines
preamble_lines.append(' '.join(decoded_line.split()))
except Exception as e:
if verbose:
print(f"[Format {idx}] Attempt failed: {e}")
continue
warnings.warn("Table header was not detected using known patterns. Will attempt inference mode.")
# Return fallback format with 'infer' but retain encoding/separator from first variant
fallback_fmt = {
'file_encoding': 'utf-8',
'separator': ',',
'table_header': ['infer']
}
return -1, [], fallback_fmt, []
def load_file_reader_parameters(filename: str, instruments_dir: str) -> tuple:
"""
Load file reader configuration parameters based on the file and instrument directory.
Returns:
- format_variants: List of dicts with keys:
'file_encoding', 'separator', 'table_header', 'timestamp', 'datetime_format', 'desired_datetime_format'
- description_dict: Dict loaded from instrument's description YAML
"""
config_path = os.path.abspath(os.path.join(instruments_dir, 'readers', 'config_text_reader.yaml'))
if not os.path.exists(config_path):
config_path = os.path.join(dimaPath,'instruments','readers', 'config_text_reader.yaml')
try:
with open(config_path, 'r') as stream:
config_dict = yaml.load(stream, Loader=yaml.FullLoader)
except yaml.YAMLError as exc:
print(f"[YAML Load Error] {exc}")
return {}, [], {}
default_config = config_dict.get('default', {})
default_format = {
'file_encoding': default_config.get('file_encoding', 'utf-8'),
'separator': default_config.get('separator', ',').replace('\\t','\t'),
'table_header': default_config.get('table_header', 'infer'),
'timestamp': [],
'datetime_format': default_config.get('datetime_format', '%Y-%m-%d %H:%M:%S.%f'),
'desired_datetime_format' : default_config.get('desired_format', '%Y-%m-%d %H:%M:%S.%f')
}
format_variants = []
description_dict = {}
# Match instrument key by folder name in file path
filename = os.path.normpath(filename)
for instFolder in config_dict.keys():
if instFolder in filename.split(os.sep):
inst_config = config_dict[instFolder]
# New style: has 'formats' block
if 'formats' in inst_config:
for fmt in inst_config['formats']:
format_variants.append({
'file_encoding': fmt.get('file_encoding', default_format['file_encoding']),
'separator': fmt.get('separator', default_format['separator']),
'table_header': fmt.get('table_header', default_format['table_header']),
'timestamp': fmt.get('timestamp', []),
'datetime_format': fmt.get('datetime_format', default_format['desired_datetime_format']),
'desired_datetime_format' :default_format['desired_datetime_format']
})
else:
# Old style: flat format
format_variants.append({
'file_encoding': inst_config.get('file_encoding', default_format['file_encoding']),
'separator': inst_config.get('separator', default_format['separator']),
'table_header': inst_config.get('table_header', default_format['table_header']),
'timestamp': inst_config.get('timestamp', []),
'datetime_format': inst_config.get('datetime_format', default_format['desired_datetime_format']),
'desired_datetime_format' : default_format['desired_datetime_format']
})
# Description loading
link_to_description = inst_config.get('link_to_description', '').replace('/', os.sep)
if link_to_description:
desc_path = os.path.join(instruments_dir, link_to_description)
try:
with open(desc_path, 'r') as desc_stream:
description_dict = yaml.load(desc_stream, Loader=yaml.FullLoader)
except (FileNotFoundError, yaml.YAMLError) as exc:
print(f"[Description Load Error] {exc}")
break # Stop after first match
# Always return config_dict + list of formats + description
return format_variants, description_dict
if __name__ == "__main__": if __name__ == "__main__":

View File

@@ -152,10 +152,22 @@ def read_nasa_ames_as_dict(filename, instruments_dir: str = None, work_with_copy
sep="\s+", sep="\s+",
header=header_length - 1, header=header_length - 1,
skip_blank_lines=True) skip_blank_lines=True)
df['start_time'] = df['start_time'].astype(str).str.strip()
df['end_time'] = df['end_time'].astype(str).str.strip()
df['start_time'] = pd.to_numeric(df['start_time'], errors='coerce')
df['end_time'] = pd.to_numeric(df['end_time'], errors='coerce')
# Compute actual datetime from start_time and (if present) end_time # Compute actual datetime from start_time and (if present) end_time
df['start_time'] = df['start_time'].apply(lambda x: start_date + timedelta(days=x)) df['start_time'] = df['start_time'].apply(
lambda x: start_date + timedelta(days=x) if pd.notna(x) else pd.NaT
)
if 'end_time' in df.columns: if 'end_time' in df.columns:
df['end_time'] = df['end_time'].apply(lambda x: start_date + timedelta(days=x)) df['end_time'] = df['end_time'].apply(
lambda x: start_date + timedelta(days=x) if pd.notna(x) else pd.NaT
)
# Create header metadata dictionary # Create header metadata dictionary
header_metadata_dict = { header_metadata_dict = {

View File

@@ -0,0 +1,115 @@
import sys
import os
try:
thisFilePath = os.path.abspath(__file__)
except NameError:
print("Error: __file__ is not available. Ensure the script is being run from a file.")
print("[Notice] Path to DIMA package may not be resolved properly.")
thisFilePath = os.getcwd() # Use current directory or specify a default
dimaPath = os.path.normpath(os.path.join(thisFilePath, "..",'..','..')) # Move up to project root
if dimaPath not in sys.path: # Avoid duplicate entries
sys.path.insert(0,dimaPath)
import pandas as pd
import json, yaml
import h5py
import argparse
import logging
import utils.g5505_utils as utils
def read_structured_file_as_dict(path_to_file):
"""
Reads a JSON or YAML file, flattens nested structures using pandas.json_normalize,
converts to a NumPy structured array via utils.convert_attrdict_to_np_structured_array,
and returns a standardized dictionary.
"""
file_dict = {}
_, path_head = os.path.split(path_to_file)
file_dict['name'] = path_head
file_dict['attributes_dict'] = {'actris_level': 0, 'processing_date': utils.created_at(), 'processing_script' : os.path.relpath(thisFilePath,dimaPath)}
file_dict['datasets'] = []
try:
with open(path_to_file, 'r') as stream:
if path_to_file.endswith(('.yaml', '.yml')):
raw_data = yaml.safe_load(stream)
elif path_to_file.endswith('.json'):
raw_data = json.load(stream)
else:
raise ValueError(f"Unsupported file type: {path_to_file}")
except Exception as exc:
logging.error("Failed to load input file %s: %s", path_to_file, exc)
raise
try:
df = pd.json_normalize(raw_data)
except Exception as exc:
logging.error("Failed to normalize data structure: %s", exc)
raise
for item_idx, item in enumerate(df.to_dict(orient='records')):
try:
structured_array = utils.convert_attrdict_to_np_structured_array(item)
except Exception as exc:
logging.error("Failed to convert to structured array: %s", exc)
raise
dataset = {
'name': f'data_table_{item_idx}',
'data': structured_array,
'shape': structured_array.shape,
'dtype': type(structured_array)
}
file_dict['datasets'].append(dataset)
return file_dict
if __name__ == "__main__":
from src.hdf5_ops import save_file_dict_to_hdf5
from utils.g5505_utils import created_at
parser = argparse.ArgumentParser(description="Data ingestion process to HDF5 files.")
parser.add_argument('dst_file_path', type=str, help="Path to the target HDF5 file.")
parser.add_argument('src_file_path', type=str, help="Relative path to source file to be saved to target HDF5 file.")
parser.add_argument('dst_group_name', type=str, help="Group name '/instFolder/[category]/fileName' in the target HDF5 file.")
args = parser.parse_args()
hdf5_file_path = args.dst_file_path
src_file_path = args.src_file_path
dst_group_name = args.dst_group_name
default_mode = 'r+'
try:
idr_dict = read_structured_file_as_dict(src_file_path)
if not os.path.exists(hdf5_file_path):
default_mode = 'w'
print(f'Opening HDF5 file: {hdf5_file_path} in mode {default_mode}')
with h5py.File(hdf5_file_path, mode=default_mode, track_order=True) as hdf5_file_obj:
try:
if dst_group_name not in hdf5_file_obj:
hdf5_file_obj.create_group(dst_group_name)
hdf5_file_obj[dst_group_name].attrs['creation_date'] = created_at().encode('utf-8')
print(f'Created new group: {dst_group_name}')
else:
print(f'Group {dst_group_name} already exists. Proceeding with data transfer...')
except Exception as inst:
logging.error('Failed to create group %s in HDF5: %s', dst_group_name, inst)
save_file_dict_to_hdf5(hdf5_file_obj, dst_group_name, idr_dict)
print(f'Completed saving file dict with keys: {idr_dict.keys()}')
except Exception as e:
logging.error('File reader failed to process %s: %s', src_file_path, e)
print(f'File reader failed to process {src_file_path}. See logs for details.')

View File

@@ -1,10 +1,27 @@
import os
import sys import sys
import os
try:
thisFilePath = os.path.abspath(__file__)
except NameError:
print("Error: __file__ is not available. Ensure the script is being run from a file.")
print("[Notice] Path to DIMA package may not be resolved properly.")
thisFilePath = os.getcwd() # Use current directory or specify a default
dimaPath = os.path.normpath(os.path.join(thisFilePath, "..",'..','..')) # Move up to project root
if dimaPath not in sys.path: # Avoid duplicate entries
sys.path.insert(0,dimaPath)
import h5py import h5py
from igor2.binarywave import load as loadibw from igor2.binarywave import load as loadibw
import logging import logging
import argparse import argparse
import utils.g5505_utils as utils
def read_xps_ibw_file_as_dict(filename): def read_xps_ibw_file_as_dict(filename):
""" """
@@ -49,7 +66,7 @@ def read_xps_ibw_file_as_dict(filename):
# Group name and attributes # Group name and attributes
file_dict['name'] = path_head file_dict['name'] = path_head
file_dict['attributes_dict'] = {} file_dict['attributes_dict'] = {'actris_level': 0, 'processing_date':utils.created_at(), 'processing_script' : os.path.relpath(thisFilePath,dimaPath)}
# Convert notes of bytes class to string class and split string into a list of elements separated by '\r'. # Convert notes of bytes class to string class and split string into a list of elements separated by '\r'.
notes_list = file_obj['wave']['note'].decode("utf-8").split('\r') notes_list = file_obj['wave']['note'].decode("utf-8").split('\r')
@@ -85,22 +102,11 @@ def read_xps_ibw_file_as_dict(filename):
if __name__ == "__main__": if __name__ == "__main__":
try:
thisFilePath = os.path.abspath(__file__)
except NameError:
print("Error: __file__ is not available. Ensure the script is being run from a file.")
print("[Notice] Path to DIMA package may not be resolved properly.")
thisFilePath = os.getcwd() # Use current directory or specify a default
dimaPath = os.path.normpath(os.path.join(thisFilePath, "..",'..','..')) # Move up to project root
if dimaPath not in sys.path: # Avoid duplicate entries
sys.path.insert(0,dimaPath)
from src.hdf5_ops import save_file_dict_to_hdf5 from src.hdf5_ops import save_file_dict_to_hdf5
from utils.g5505_utils import created_at from utils.g5505_utils import created_at
# Set up argument parsing # Set up argument parsing
parser = argparse.ArgumentParser(description="Data ingestion process to HDF5 files.") parser = argparse.ArgumentParser(description="Data ingestion process to HDF5 files.")
parser.add_argument('dst_file_path', type=str, help="Path to the target HDF5 file.") parser.add_argument('dst_file_path', type=str, help="Path to the target HDF5 file.")

View File

@@ -78,3 +78,13 @@ instruments:
fileExtension: nas fileExtension: nas
fileReaderPath: instruments/readers/nasa_ames_reader.py fileReaderPath: instruments/readers/nasa_ames_reader.py
InstrumentDictionaryPath: instruments/dictionaries/EBAS.yaml InstrumentDictionaryPath: instruments/dictionaries/EBAS.yaml
- instrumentFolderName: ACSM_TOFWARE
fileExtension: yaml,yml,json
fileReaderPath: instruments/readers/read_structured_file_as_dict.py
InstrumentDictionaryPath: instruments/dictionaries/EBAS.yaml
- instrumentFolderName: CEDOAS
fileExtension: txt
fileReaderPath: instruments/readers/g5505_text_reader.py
InstrumentDictionaryPath: instruments/dictionaries/CEDOAS.yaml

View File

@@ -40,24 +40,32 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"## Step 1: Specify data integration task through YAML configuration file\n", "## Step 1: Configure Your Data Integration Task\n",
"\n",
"1. Based on one of the example `.yaml` files found in the `input_files/` folder, define the input and output directory paths inside the file.\n",
"\n",
"2. When working with network drives, create `.env` file in the root of the `dima/` project with the following line:\n",
"\n",
" ```dotenv\n",
" NETWORK_MOUNT=//your-server/your-share\n",
" ```\n",
"3. Excecute Cell.\n",
"\n",
"**Note:** Ensure `.env` is listed in `.gitignore` and `.dockerignore`.\n",
"\n", "\n",
"* Create your configuration file (i.e., *.yaml file) adhering to the example yaml file in the input folder.\n",
"* Set up input directory and output directory paths and Excecute Cell.\n",
"\n" "\n"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 2, "execution_count": null,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"#output_filename_path = 'output_files/unified_file_smog_chamber_2024-04-07_UTC-OFST_+0200_NG.h5'\n", "number, initials = 2, 'TBR' # Set as either 2, 'TBR' or 3, 'NG'\n",
"yaml_config_file_path = '../input_files/data_integr_config_file_TBR.yaml'\n", "campaign_descriptor_path = f'../input_files/campaignDescriptor{number}_{initials}.yaml'\n",
"\n", "\n",
"#path_to_input_directory = 'output_files/kinetic_flowtube_study_2022-01-31_LuciaI'\n", "print(campaign_descriptor_path)\n"
"#path_to_hdf5_file = hdf5_lib.create_hdf5_file_from_filesystem_path(path_to_input_directory)\n"
] ]
}, },
{ {
@@ -66,7 +74,9 @@
"source": [ "source": [
"## Step 2: Create an integrated HDF5 file of experimental campaign.\n", "## Step 2: Create an integrated HDF5 file of experimental campaign.\n",
"\n", "\n",
"* Excecute Cell. Here we run the function `integrate_data_sources` with input argument as the previously specified YAML config file." "* Excecute Cell. Here we run the function `integrate_data_sources` with input argument as the previously specified YAML config file.\n",
"\n",
" "
] ]
}, },
{ {
@@ -76,7 +86,7 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"\n", "\n",
"hdf5_file_path = data_integration.run_pipeline(yaml_config_file_path)" "hdf5_file_path = data_integration.run_pipeline(campaign_descriptor_path)"
] ]
}, },
{ {
@@ -146,7 +156,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 5, "execution_count": null,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [

File diff suppressed because it is too large Load Diff

View File

@@ -38,12 +38,19 @@ def _generate_datetime_dict(datetime_steps):
""" Generate the datetime augment dictionary from datetime steps. """ """ Generate the datetime augment dictionary from datetime steps. """
datetime_augment_dict = {} datetime_augment_dict = {}
for datetime_step in datetime_steps: for datetime_step in datetime_steps:
#tmp = datetime.strptime(datetime_step, '%Y-%m-%d %H-%M-%S')
datetime_augment_dict[datetime_step] = [ datetime_augment_dict[datetime_step] = [
datetime_step.strftime('%Y-%m-%d'), datetime_step.strftime('%Y_%m_%d'), datetime_step.strftime('%Y.%m.%d'), datetime_step.strftime('%Y%m%d') datetime_step.strftime('%Y-%m-%d'), datetime_step.strftime('%Y_%m_%d'),
datetime_step.strftime('%Y.%m.%d'), datetime_step.strftime('%Y%m%d')
] ]
return datetime_augment_dict return datetime_augment_dict
def _generate_output_path_fragment(filename_prefix, integration_mode, dataset_startdate, dataset_enddate, index=None):
"""Generate consistent directory or file name fragment based on mode."""
if integration_mode == 'collection':
return f'collection_{index}_{filename_prefix}_{dataset_enddate}'
else:
return f'{filename_prefix}_{dataset_enddate}'
def load_config_and_setup_logging(yaml_config_file_path, log_dir): def load_config_and_setup_logging(yaml_config_file_path, log_dir):
"""Load YAML configuration file, set up logging, and validate required keys and datetime_steps.""" """Load YAML configuration file, set up logging, and validate required keys and datetime_steps."""
@@ -74,6 +81,22 @@ def load_config_and_setup_logging(yaml_config_file_path, log_dir):
if missing_keys: if missing_keys:
raise KeyError(f"Missing required keys in YAML configuration: {missing_keys}") raise KeyError(f"Missing required keys in YAML configuration: {missing_keys}")
# Look for all placeholders like ${VAR_NAME}
input_dir = config_dict['input_file_directory']
placeholders = re.findall(r'\$\{([^}^{]+)\}', input_dir)
success = utils.load_env_from_root()
print(f'Success : {success}')
for var in placeholders:
env_value = os.environ.get(var)
if env_value is None:
raise ValueError(f"Environment variable '{var}' is not set but used in the config.")
input_dir = input_dir.replace(f"${{{var}}}", env_value)
config_dict['input_file_directory'] = input_dir
# Check the instrument_datafolder required type and ensure the list is of at least length one. # Check the instrument_datafolder required type and ensure the list is of at least length one.
if isinstance(config_dict['instrument_datafolder'], list) and not len(config_dict['instrument_datafolder'])>=1: if isinstance(config_dict['instrument_datafolder'], list) and not len(config_dict['instrument_datafolder'])>=1:
raise ValueError('Invalid value for key "instrument_datafolder". Expected a list of strings with at least one item.' raise ValueError('Invalid value for key "instrument_datafolder". Expected a list of strings with at least one item.'
@@ -189,17 +212,6 @@ def copy_subtree_and_create_hdf5(src, dst, select_dir_keywords, select_file_keyw
def run_pipeline(path_to_config_yamlFile, log_dir='logs/'): def run_pipeline(path_to_config_yamlFile, log_dir='logs/'):
"""Integrates data sources specified by the input configuration file into HDF5 files.
Parameters:
yaml_config_file_path (str): Path to the YAML configuration file.
log_dir (str): Directory to save the log file.
Returns:
list: List of Paths to the created HDF5 file(s).
"""
config_dict = load_config_and_setup_logging(path_to_config_yamlFile, log_dir) config_dict = load_config_and_setup_logging(path_to_config_yamlFile, log_dir)
path_to_input_dir = config_dict['input_file_directory'] path_to_input_dir = config_dict['input_file_directory']
@@ -213,22 +225,27 @@ def run_pipeline(path_to_config_yamlFile, log_dir='logs/'):
dataset_startdate = config_dict['dataset_startdate'] dataset_startdate = config_dict['dataset_startdate']
dataset_enddate = config_dict['dataset_enddate'] dataset_enddate = config_dict['dataset_enddate']
# Determine mode and process accordingly integration_mode = config_dict.get('integration_mode', 'single_experiment')
output_filename_path = [] filename_prefix = config_dict['filename_prefix']
campaign_name_template = lambda filename_prefix, suffix: '_'.join([filename_prefix, suffix])
date_str = f'{dataset_startdate}_{dataset_enddate}' output_filename_path = []
# Determine top-level campaign folder path
top_level_foldername = _generate_output_path_fragment(
filename_prefix, integration_mode, dataset_startdate, dataset_enddate, index=1
)
# Create path to new raw datafolder and standardize with forward slashes
path_to_rawdata_folder = os.path.join( path_to_rawdata_folder = os.path.join(
path_to_output_dir, 'collection_' + campaign_name_template(config_dict['filename_prefix'], date_str), "").replace(os.sep, '/') path_to_output_dir, top_level_foldername, ""
).replace(os.sep, '/')
# Process individual datetime steps if available, regardless of mode # Process individual datetime steps if available, regardless of mode
if config_dict.get('datetime_steps_dict', {}): if config_dict.get('datetime_steps_dict', {}):
# Single experiment mode
for datetime_step, file_keywords in config_dict['datetime_steps_dict'].items(): for datetime_step, file_keywords in config_dict['datetime_steps_dict'].items():
date_str = datetime_step.strftime('%Y-%m-%d') single_date_str = datetime_step.strftime('%Y%m%d')
single_campaign_name = campaign_name_template(config_dict['filename_prefix'], date_str) subfolder_name = f"{filename_prefix}_{single_date_str}"
path_to_rawdata_subfolder = os.path.join(path_to_rawdata_folder, single_campaign_name, "") subfolder_name = f"experimental_step_{single_date_str}"
path_to_rawdata_subfolder = os.path.join(path_to_rawdata_folder, subfolder_name, "")
path_to_integrated_stepwise_hdf5_file = copy_subtree_and_create_hdf5( path_to_integrated_stepwise_hdf5_file = copy_subtree_and_create_hdf5(
path_to_input_dir, path_to_rawdata_subfolder, select_dir_keywords, path_to_input_dir, path_to_rawdata_subfolder, select_dir_keywords,
@@ -236,11 +253,12 @@ def run_pipeline(path_to_config_yamlFile, log_dir='logs/'):
output_filename_path.append(path_to_integrated_stepwise_hdf5_file) output_filename_path.append(path_to_integrated_stepwise_hdf5_file)
# Collection mode processing if specified # Collection mode post-processing
if 'collection' in config_dict.get('integration_mode', 'single_experiment'): if integration_mode == 'collection':
path_to_filenames_dict = {path_to_rawdata_folder: [os.path.basename(path) for path in output_filename_path]} if output_filename_path else {} path_to_filenames_dict = {path_to_rawdata_folder: [os.path.basename(path) for path in output_filename_path]} if output_filename_path else {}
#hdf5_path = hdf5_lib.create_hdf5_file_from_filesystem_path_new(path_to_rawdata_folder, path_to_filenames_dict, [], root_metadata_dict) hdf5_path = hdf5_lib.create_hdf5_file_from_filesystem_path(
hdf5_path = hdf5_lib.create_hdf5_file_from_filesystem_path(path_to_rawdata_folder, path_to_filenames_dict, [], root_metadata_dict) path_to_rawdata_folder, path_to_filenames_dict, [], root_metadata_dict
)
output_filename_path.append(hdf5_path) output_filename_path.append(hdf5_path)
else: else:
path_to_integrated_stepwise_hdf5_file = copy_subtree_and_create_hdf5( path_to_integrated_stepwise_hdf5_file = copy_subtree_and_create_hdf5(
@@ -250,24 +268,16 @@ def run_pipeline(path_to_config_yamlFile, log_dir='logs/'):
return output_filename_path return output_filename_path
if __name__ == "__main__": if __name__ == "__main__":
if len(sys.argv) < 2: if len(sys.argv) < 2:
print("Usage: python data_integration.py <function_name> <function_args>") print("Usage: python data_integration.py <function_name> <function_args>")
sys.exit(1) sys.exit(1)
# Extract the function name from the command line arguments
function_name = sys.argv[1] function_name = sys.argv[1]
# Handle function execution based on the provided function name
if function_name == 'run': if function_name == 'run':
if len(sys.argv) != 3: if len(sys.argv) != 3:
print("Usage: python data_integration.py run <path_to_config_yamlFile>") print("Usage: python data_integration.py run <path_to_config_yamlFile>")
sys.exit(1) sys.exit(1)
# Extract path to configuration file, specifying the data integration task
path_to_config_yamlFile = sys.argv[2] path_to_config_yamlFile = sys.argv[2]
run_pipeline(path_to_config_yamlFile) run_pipeline(path_to_config_yamlFile)

View File

@@ -19,17 +19,10 @@ import pandas as pd
import numpy as np import numpy as np
import logging import logging
import datetime import datetime
import h5py
import yaml import yaml
import json import json
import copy import copy
#try:
# from dima.utils import g5505_utils as utils
# from dima.src import hdf5_writer as hdf5_lib
#except ModuleNotFoundError:
import utils.g5505_utils as utils import utils.g5505_utils as utils
import src.hdf5_writer as hdf5_lib import src.hdf5_writer as hdf5_lib
@@ -744,10 +737,30 @@ def save_file_dict_to_hdf5(h5file, group_name, file_dict):
try: try:
# Create group and add their attributes # Create group and add their attributes
filename = file_dict['name'] filename = file_dict['name']
group = h5file[group_name].create_group(name=filename)
# Base filename to use as group name
base_filename = file_dict['name']
candidate_name = base_filename
replicate_index = 0
# Check for existing group and find a free name
parent_group = h5file.require_group(group_name)
while candidate_name in parent_group:
replicate_index += 1
candidate_name = f"{base_filename}_{replicate_index}"
group = h5file[group_name].create_group(name=candidate_name )
# Add group attributes # Add group attributes
group.attrs.update(file_dict['attributes_dict']) group.attrs.update(file_dict['attributes_dict'])
# Annotate replicate if renamed
if replicate_index > 0:
group.attrs['replicate_of'] = base_filename
group.attrs['replicate_info'] = (
f"Renamed due to existing group with same name. "
f"This is replicate #{replicate_index}."
)
# Add datasets to the just created group # Add datasets to the just created group
for dataset in file_dict['datasets']: for dataset in file_dict['datasets']:
dataset_obj = group.create_dataset( dataset_obj = group.create_dataset(

View File

@@ -100,6 +100,20 @@ def create_hdf5_file_from_filesystem_path(path_to_input_directory: str,
print(message) print(message)
logging.error(message) logging.error(message)
else: else:
# Step 1: Preprocess all metadata.json files into a lookup dict
all_metadata_dict = {}
for dirpath, filenames in path_to_filenames_dict.items():
metadata_file = next((f for f in filenames if f.endswith('metadata.json')), None)
if metadata_file:
metadata_path = os.path.join(dirpath, metadata_file)
try:
with open(metadata_path, 'r') as metafile:
all_metadata_dict[dirpath] = json.load(metafile)
except json.JSONDecodeError:
logging.warning(f"Invalid JSON in metadata file: {metadata_path}")
all_metadata_dict[dirpath] = {}
with h5py.File(path_to_output_file, mode=mode, track_order=True) as h5file: with h5py.File(path_to_output_file, mode=mode, track_order=True) as h5file:
number_of_dirs = len(path_to_filenames_dict.keys()) number_of_dirs = len(path_to_filenames_dict.keys())
@@ -138,22 +152,15 @@ def create_hdf5_file_from_filesystem_path(path_to_input_directory: str,
stdout = inst stdout = inst
logging.error('Failed to create group %s into HDF5: %s', group_name, inst) logging.error('Failed to create group %s into HDF5: %s', group_name, inst)
if 'data_lineage_metadata.json' in filtered_filenames_list: # Step 3: During ingestion, attach metadata per file
idx = filtered_filenames_list.index('data_lineage_metadata.json') metadata_dict = all_metadata_dict.get(dirpath, {})
data_lineage_file = filtered_filenames_list[idx]
try:
with open('/'.join([dirpath,data_lineage_file]),'r') as dlf:
data_lineage_dict = json.load(dlf)
filtered_filenames_list.pop(idx)
except json.JSONDecodeError:
data_lineage_dict = {} # Start fresh if file is invalid
else:
data_lineage_dict = {}
for filenumber, filename in enumerate(filtered_filenames_list): for filenumber, filename in enumerate(filtered_filenames_list):
# Skip any file that itself ends in metadata.json
if filename.endswith('metadata.json'):
continue
# hdf5 path to filename group # hdf5 path to filename group
dest_group_name = f'{group_name}/{filename}' dest_group_name = f'{group_name}/{filename}'
source_file_path = os.path.join(dirpath,filename) source_file_path = os.path.join(dirpath,filename)
@@ -163,6 +170,10 @@ def create_hdf5_file_from_filesystem_path(path_to_input_directory: str,
#file_dict = ext_to_reader_dict[file_ext](os.path.join(dirpath,filename)) #file_dict = ext_to_reader_dict[file_ext](os.path.join(dirpath,filename))
file_dict = filereader_registry.select_file_reader(dest_group_name)(source_file_path) file_dict = filereader_registry.select_file_reader(dest_group_name)(source_file_path)
# Attach per-file metadata if available
if filename in metadata_dict:
file_dict.get("attributes_dict",{}).update(metadata_dict[filename])
file_dict.get("attributes_dict",{}).update({'original_path' : dirpath})
stdout = hdf5_ops.save_file_dict_to_hdf5(dest_file_obj, group_name, file_dict) stdout = hdf5_ops.save_file_dict_to_hdf5(dest_file_obj, group_name, file_dict)
else: else:
@@ -270,6 +281,21 @@ def create_hdf5_file_from_filesystem_path_new(path_to_input_directory: str,
print(message) print(message)
logging.error(message) logging.error(message)
else: else:
# Step 1: Preprocess all metadata.json files into a lookup dict
all_metadata_dict = {}
for dirpath, filenames in path_to_filenames_dict.items():
metadata_file = next((f for f in filenames if f.endswith('metadata.json')), None)
if metadata_file:
metadata_path = os.path.join(dirpath, metadata_file)
try:
with open(metadata_path, 'r') as metafile:
all_metadata_dict[dirpath] = json.load(metafile)
except json.JSONDecodeError:
logging.warning(f"Invalid JSON in metadata file: {metadata_path}")
all_metadata_dict[dirpath] = {}
with h5py.File(path_to_output_file, mode=mode, track_order=True) as h5file: with h5py.File(path_to_output_file, mode=mode, track_order=True) as h5file:
print('Created file') print('Created file')
@@ -309,8 +335,15 @@ def create_hdf5_file_from_filesystem_path_new(path_to_input_directory: str,
# stdout = inst # stdout = inst
# logging.error('Failed to create group %s into HDF5: %s', group_name, inst) # logging.error('Failed to create group %s into HDF5: %s', group_name, inst)
# Step 3: During ingestion, attach metadata per file
# TODO: pass this metadata fict to run_file_reader line 363
metadata_dict = all_metadata_dict.get(dirpath, {})
for filenumber, filename in enumerate(filtered_filenames_list): for filenumber, filename in enumerate(filtered_filenames_list):
if filename.endswith('metadata.json'):
continue
#file_ext = os.path.splitext(filename)[1] #file_ext = os.path.splitext(filename)[1]
#try: #try:

View File

@@ -0,0 +1,7 @@
exclude_paths:
containing :
- .ipynb_checkpoints
- .renku
- .git
# - params
- .Trash

View File

@@ -1,3 +1,18 @@
import sys
import os
try:
thisFilePath = os.path.abspath(__file__)
except NameError:
print("Error: __file__ is not available. Ensure the script is being run from a file.")
print("[Notice] Path to DIMA package may not be resolved properly.")
thisFilePath = os.getcwd() # Use current directory or specify a default
dimaPath = os.path.normpath(os.path.join(thisFilePath, "..",'..','..')) # Move up to project root
if dimaPath not in sys.path: # Avoid duplicate entries
sys.path.insert(0,dimaPath)
import pandas as pd import pandas as pd
import os import os
import sys import sys
@@ -7,7 +22,7 @@ import logging
import numpy as np import numpy as np
import h5py import h5py
import re import re
import yaml
def setup_logging(log_dir, log_filename): def setup_logging(log_dir, log_filename):
"""Sets up logging to a specified directory and file. """Sets up logging to a specified directory and file.
@@ -202,43 +217,49 @@ def convert_string_to_bytes(input_list: list):
def convert_attrdict_to_np_structured_array(attr_value: dict): def convert_attrdict_to_np_structured_array(attr_value: dict):
""" """
Converts a dictionary of attributes into a numpy structured array for HDF5 Converts a dictionary of attributes into a NumPy structured array with byte-encoded fields.
compound type compatibility. Handles UTF-8 encoding to avoid UnicodeEncodeError with non-ASCII characters.
Each dictionary key is mapped to a field in the structured array, with the
data type (S) determined by the longest string representation of the values.
If the dictionary is empty, the function returns 'missing'.
Parameters Parameters
---------- ----------
attr_value : dict attr_value : dict
Dictionary containing the attributes to be converted. Example: Dictionary with scalar values (int, float, str).
attr_value = {
'name': 'Temperature',
'unit': 'Celsius',
'value': 23.5,
'timestamp': '2023-09-26 10:00'
}
Returns Returns
------- -------
new_attr_value : ndarray or str new_attr_value : ndarray
Numpy structured array with UTF-8 encoded fields. Returns 'missing' if 1-row structured array with fixed-size byte fields (dtype='S').
the input dictionary is empty.
""" """
if not isinstance(attr_value, dict):
raise ValueError(f"Input must be a dictionary, got {type(attr_value)}")
if not attr_value:
return np.array(['missing'], dtype=[('value', 'S16')]) # placeholder
dtype = [] dtype = []
values_list = [] values_list = []
max_length = max(len(str(attr_value[key])) for key in attr_value.keys())
for key in attr_value.keys():
if key != 'rename_as':
dtype.append((key, f'S{max_length}'))
values_list.append(attr_value[key])
if values_list:
new_attr_value = np.array([tuple(values_list)], dtype=dtype)
else:
new_attr_value = 'missing'
return new_attr_value max_str_len = max(len(str(v)) for v in attr_value.values())
byte_len = max_str_len * 4 # UTF-8 worst-case
for key, val in attr_value.items():
if key == 'rename_as':
continue
if isinstance(val, (int, float, str)):
dtype.append((key, f'S{byte_len}'))
try:
encoded_val = str(val).encode('utf-8') # explicit UTF-8
values_list.append(encoded_val)
except UnicodeEncodeError as e:
logging.error(f"Failed to encode {key}={val}: {e}")
raise
else:
logging.warning(f"Skipping unsupported type for key {key}: {type(val)}")
if values_list:
return np.array([tuple(values_list)], dtype=dtype)
else:
return np.array(['missing'], dtype=[('value', 'S16')])
def infer_units(column_name): def infer_units(column_name):
@@ -292,6 +313,19 @@ def copy_directory_with_contraints(input_dir_path, output_dir_path,
output_dir_path = os.path.normpath(output_dir_path) output_dir_path = os.path.normpath(output_dir_path)
select_dir_keywords = [keyword.replace('/',os.sep) for keyword in select_dir_keywords] select_dir_keywords = [keyword.replace('/',os.sep) for keyword in select_dir_keywords]
try:
with open(os.path.join(dimaPath, 'dima/utils/exclude_path_keywords.yaml'), 'r') as stream:
exclude_path_dict = yaml.safe_load(stream)
if isinstance(exclude_path_dict, dict):
exclude_path_keywords = exclude_path_dict.get('exclude_paths',{}).get('containing', [])
if not all(isinstance(keyword, str) for keyword in exclude_path_keywords):
exclude_path_keywords = []
else:
exclude_path_keywords = []
except (FileNotFoundError, yaml.YAMLError) as e:
print(f"Warning. Unable to load YAML file: {e}")
exclude_path_keywords = []
date = created_at('%Y_%m').replace(":", "-") date = created_at('%Y_%m').replace(":", "-")
log_dir='logs/' log_dir='logs/'
setup_logging(log_dir, f"copy_directory_with_contraints_{date}.log") setup_logging(log_dir, f"copy_directory_with_contraints_{date}.log")
@@ -302,6 +336,7 @@ def copy_directory_with_contraints(input_dir_path, output_dir_path,
def file_is_selected(filename): def file_is_selected(filename):
return not select_file_keywords or any(keyword in filename for keyword in select_file_keywords) return not select_file_keywords or any(keyword in filename for keyword in select_file_keywords)
# Exclude path keywords
# Collect paths of directories, which are directly connected to the root dir and match select_dir_keywords # Collect paths of directories, which are directly connected to the root dir and match select_dir_keywords
@@ -320,6 +355,10 @@ def copy_directory_with_contraints(input_dir_path, output_dir_path,
for dirpath, _, filenames in os.walk(subpath,topdown=False): for dirpath, _, filenames in os.walk(subpath,topdown=False):
# Exclude any dirpath containing a keyword in exclude_path_keywords
if any(excluded in dirpath for excluded in exclude_path_keywords):
continue
# Ensure composite keywords e.g., <keyword>/<keyword> are contained in the path # Ensure composite keywords e.g., <keyword>/<keyword> are contained in the path
if select_dir_keywords and not any([keyword in dirpath for keyword in select_dir_keywords]): if select_dir_keywords and not any([keyword in dirpath for keyword in select_dir_keywords]):
continue continue
@@ -412,3 +451,56 @@ def is_structured_array(attr_val):
return True if attr_val.dtype.names is not None else False return True if attr_val.dtype.names is not None else False
else: else:
return False return False
import os
from pathlib import Path
def find_env_file(start_path=None):
"""
Find .env file by walking up the directory tree.
Looks for .env in current dir, then parent dirs up to filesystem root.
Args:
start_path: Starting directory (defaults to current working directory)
Returns:
Path to .env file or None if not found
"""
if start_path is None:
start_path = os.getcwd()
current_path = Path(start_path).resolve()
# Walk up the directory tree
for path in [current_path] + list(current_path.parents):
env_file = path / '.env'
if env_file.exists():
return str(env_file)
return None
import os
def load_env_from_root():
"""Load environment variables from .env file found in project root or parent."""
env_file = find_env_file()
if env_file:
try:
from dotenv import load_dotenv
load_dotenv(env_file, override=True) # override existing values
print(f"Loaded .env from: {env_file}")
return True
except ImportError:
with open(env_file, 'r') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#') and '=' in line:
key, value = line.split('=', 1)
os.environ[key.strip()] = value.strip()
print(f"Manually loaded .env from: {env_file}")
return True
else:
print("No .env file found in project hierarchy")
return False