-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparcel.h
More file actions
4752 lines (4058 loc) · 155 KB
/
parcel.h
File metadata and controls
4752 lines (4058 loc) · 155 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* =========================================================================
Parcel - A C library for reading OpenPMD particle and mesh data
Copyright (c) 2025 Christopher M. Pierce
SPDX-License-Identifier: BSD-3-Clause
========================================================================= */
#ifndef PARCEL_H
#define PARCEL_H
#include <stddef.h>
#include <stdint.h>
#include <time.h>
#include <hdf5.h>
#ifdef __cplusplus
extern "C" {
#endif
/* =========================================================================
* Library Version
* ========================================================================= */
/* Parcel library version */
#define PARCEL_VERSION_STRING "1.0.0"
/* OpenPMD version that this library writes */
#define OPENPMD_VERSION_STRING "2.0.0"
/* =========================================================================
* Status Codes
* ========================================================================= */
/**
* pmd_status - Return status codes for Parcel API functions
*/
typedef enum {
PMD_SUCCESS = 0, /* Operation succeeded */
PMD_ERROR = -1, /* General error */
PMD_ERROR_NULL_POINTER = -2, /* Null pointer argument */
PMD_ERROR_INVALID_ITERATION = -3,/* Invalid iteration index */
PMD_ERROR_INVALID_SPECIES = -4, /* Species not found */
PMD_ERROR_OUT_OF_MEMORY = -5, /* Memory allocation failed */
PMD_ERROR_FILE_NOT_FOUND = -6, /* File doesn't exist */
PMD_ERROR_FILE_FORMAT = -7, /* Invalid/malformed file format */
PMD_ERROR_HDF5 = -8 /* HDF5 library error */
} pmd_status;
/* =========================================================================
* Iteration Encoding Types
* ========================================================================= */
/**
* pmd_iteration_encoding - How iterations are stored in the series
*/
typedef enum {
PMD_FILE_BASED, /* Multiple files (one per iteration) */
PMD_GROUP_BASED /* Single file with group per iteration */
} pmd_iteration_encoding;
/**
* pmd_access_mode - File access mode for opening series
*/
typedef enum {
PMD_RDONLY, /* Read-only access */
PMD_RDWR, /* Read-write access to existing file */
PMD_TRUNC, /* Create new file, truncate if exists */
PMD_EXCL /* Create new file, fail if exists */
} pmd_access_mode;
/* =========================================================================
* Logging
* ========================================================================= */
/**
* pmd_log_level - Log level for controlling message verbosity
*/
typedef enum {
PMD_LOG_NONE = -1, /* Suppress all messages */
PMD_LOG_ERROR = 0, /* Error messages only */
PMD_LOG_WARNING = 1, /* Errors and warnings */
PMD_LOG_INFO = 2, /* Errors, warnings, and info */
PMD_LOG_DEBUG = 3 /* All messages including debug */
} pmd_log_level;
/* =========================================================================
* Particle Data Structures
* ========================================================================= */
/**
* pmd_unit_dimension - Physical dimensionality of a record in SI base units
*
* Represents the powers of the 7 SI base dimensions:
* - length (L): meter
* - mass (M): kilogram
* - time (T): second
* - current (I): ampere
* - temperature (theta): kelvin
* - amount (N): mole
* - intensity (J): candela
*
* Example: For velocity (m/s), use: {1.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0}
* Example: For force (N = kg*m/s^2), use: {1.0, 1.0, -2.0, 0.0, 0.0, 0.0, 0.0}
*/
typedef struct {
double length; /* L - meter */
double mass; /* M - kilogram */
double time; /* T - second */
double current; /* I - ampere */
double temperature; /* theta - kelvin */
double amount; /* N - mole */
double intensity; /* J - candela */
} pmd_unit_dimension;
/**
* pmd_particle_group - Represents a collection of particles, either allocated with
* pmd_allocate_particle_group or array pointers are set by user to existing
* arrays in beam physics code being intergrated with.
*/
typedef struct {
int64_t num_particles; /* Number of particles in group */
char *species_type; /* Species name (e.g., "electron") */
/* Position arrays */
double *x; /* x positions (m) */
double *y; /* y positions (m) */
double *z; /* z positions (m) */
double *t; /* Time (s) */
/* Position offset */
double *x_offset; /* x position offset (m) */
double *y_offset; /* y position offset (m) */
double *z_offset; /* z position offset (m) */
/* Momentum arrays */
double *px; /* x momentum (eV/c) */
double *py; /* y momentum (eV/c) */
double *pz; /* z momentum (eV/c) */
/* Optional per-particle data */
double *weight; /* Macro-particle weights */
int64_t *status; /* Particle status (1=alive) */
int64_t *id; /* Particle IDs */
} pmd_particle_group;
/**
* pmd_particle_group_read_info - Information about how particle data was read
*
* Used to report which optional fields were present in the file and other
* read operation metadata.
*/
typedef struct {
bool t_present; /* true if time dataset exists */
bool px_present; /* true if momentum/x dataset exists */
bool py_present; /* true if momentum/y dataset exists */
bool pz_present; /* true if momentum/z dataset exists */
bool weight_present; /* true if weight dataset exists */
bool status_present; /* true if particleStatus dataset exists */
bool id_present; /* true if id dataset exists */
} pmd_particle_group_read_info;
/* =========================================================================
* Series and Iteration Handles
* ========================================================================= */
/* Forward declaration for circular reference */
typedef struct pmd_iteration pmd_iteration;
/**
* pmd_series - Handle for an OpenPMD data series
*
* Represents a collection of iterations that may be stored in:
* - A single file with multiple groups (GROUP_BASED)
* - Multiple files with one iteration each (FILE_BASED)
*/
typedef struct {
/* File handle (for GROUP_BASED only, -1 for FILE_BASED) */
hid_t file_id;
/* Access mode used to open this series */
pmd_access_mode access_mode;
/* Required OpenPMD metadata */
char *base_path; /* e.g., "/data/%T/" */
char *iteration_format; /* e.g., "sim_%T.h5" or "/data/%T/" */
/* Iteration encoding type */
pmd_iteration_encoding iteration_encoding;
/* Optional paths (private - use accessor functions) */
char *_particles_path; /* e.g., "particles/" */
char *_meshes_path; /* e.g., "meshes/" */
/* For FILE_BASED: directory containing files */
char *directory; /* Directory containing files */
/* Metadata attributes (private - use accessor functions) */
char *_author;
char *_software;
char *_software_version;
char *_software_dependencies;
char *_machine;
char *_comment;
char *_date;
char *_extensions;
/* Cached metadata */
int num_iterations; /* -1 if not enumerated yet */
int64_t *iteration_indices; /* Array of available iterations */
/* Track open iterations (for FILE_BASED to prevent multiple file handles) */
pmd_iteration **open_iterations; /* Array of pointers to open iteration handles */
int num_open_iterations; /* Number of currently open iterations */
int open_iterations_capacity; /* Allocated capacity for open_iterations array */
} pmd_series;
/**
* pmd_iteration - Handle for a single iteration in an OpenPMD series
*
* Represents a specific timestep with its metadata and particle data
*/
struct pmd_iteration {
pmd_series *series; /* Parent series */
int64_t iteration_index; /* Current iteration number */
/* Handle to data */
hid_t file_id; /* For FILE_BASED only. -1 if not used */
hid_t iteration_group_id;
};
/* =========================================================================
* API Function Declarations
* ========================================================================= */
/* --- Logging Configuration --- */
/**
* Set the minimum log level for messages
*
* Messages with a level below this threshold will be suppressed.
* Default level is PMD_LOG_WARNING (shows errors and warnings).
*
* @param level Minimum log level to display
*/
void pmd_set_log_level(pmd_log_level level);
/* --- Series Operations --- */
/**
* Open an OpenPMD series from a file
*
* @param filename Path to OpenPMD file (may contain %T pattern for FILE_BASED)
* @param series_out Output pointer to created series handle
* @param mode Access mode (PMD_RDONLY, PMD_RDWR, PMD_TRUNC, PMD_EXCL)
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_open_series(const char *filename, pmd_series **series_out, pmd_access_mode mode);
/**
* Close an OpenPMD series and free resources
*
* @param series Series handle to close
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_close_series(pmd_series *series);
/**
* Get list of available iterations in the series
*
* @param series Series handle
* @param iterations Output pointer to array of iteration indices
* @param count Output pointer to number of iterations
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_list_iterations(pmd_series *series, int64_t **iterations, int *count);
/* --- Iteration Operations --- */
/**
* Open a specific iteration within a series
*
* @param series Parent series handle
* @param index Iteration index to open
* @param iter_out Output pointer to created iteration handle
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_open_iteration(pmd_series *series, int64_t index, pmd_iteration **iter_out);
/**
* Close an iteration and free resources
*
* @param iter Iteration handle to close
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_close_iteration(pmd_iteration *iter);
/**
* Get list of particle species in the iteration
*
* @param iter Iteration handle
* @param species_names Output pointer to array of species name strings
* @param count Output pointer to number of species
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_list_species(pmd_iteration *iter, char ***species_names, int *count);
/**
* Get number of particles for a species in the iteration
*
* @param iter Iteration handle
* @param species Species name
* @param count Output pointer to particle count
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_get_num_particles(pmd_iteration *iter, const char *species, int64_t *count);
/* --- Iteration Metadata Operations --- */
/**
* Get the time attribute from an iteration
*
* @param iter Iteration handle
* @param time Output pointer to time value
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_iter_get_time(pmd_iteration *iter, double *time);
/**
* Get the dt (time step) attribute from an iteration
*
* @param iter Iteration handle
* @param dt Output pointer to dt value
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_iter_get_dt(pmd_iteration *iter, double *dt);
/**
* Get the timeUnitSI attribute from an iteration
*
* @param iter Iteration handle
* @param time_unit_si Output pointer to timeUnitSI value
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_iter_get_time_unit_si(pmd_iteration *iter, double *time_unit_si);
/**
* Set the time attribute for an iteration
*
* @param iter Iteration handle
* @param time Time value to set
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_iter_set_time(pmd_iteration *iter, double time);
/**
* Set the dt (time step) attribute for an iteration
*
* @param iter Iteration handle
* @param dt Time step value to set
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_iter_set_dt(pmd_iteration *iter, double dt);
/**
* Set the timeUnitSI attribute for an iteration
*
* @param iter Iteration handle
* @param time_unit_si TimeUnitSI value to set
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_iter_set_time_unit_si(pmd_iteration *iter, double time_unit_si);
/* --- Series Metadata Operations --- */
/**
* Get particlesPath (returns copy of cached value from series)
*
* @param series Series handle
* @param value_out Output pointer to particles path string (caller must free)
* @return PMD_SUCCESS or PMD_ERROR if not set
*/
pmd_status pmd_get_particles_path(pmd_series *series, char **value_out);
/**
* Get meshesPath (returns copy of cached value from series)
*
* @param series Series handle
* @param value_out Output pointer to meshes path string (caller must free)
* @return PMD_SUCCESS or PMD_ERROR if not set
*/
pmd_status pmd_get_meshes_path(pmd_series *series, char **value_out);
/**
* Get the openPMD version from the series
*
* @param series Series handle
* @param major Output pointer to major version
* @param minor Output pointer to minor version
* @param revision Output pointer to revision version
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_get_openpmd_version(pmd_series *series, int *major, int *minor, int *revision);
/**
* Get author attribute (reads from file on-demand)
*
* @param series Series handle
* @param value_out Output pointer to author string (caller must free)
* @return PMD_SUCCESS or error code (PMD_ERROR if attribute doesn't exist)
*/
pmd_status pmd_get_author(pmd_series *series, char **value_out);
/**
* Get software attribute (reads from file on-demand)
*
* @param series Series handle
* @param value_out Output pointer to software string (caller must free)
* @return PMD_SUCCESS or error code (PMD_ERROR if attribute doesn't exist)
*/
pmd_status pmd_get_software(pmd_series *series, char **value_out);
/**
* Get softwareVersion attribute (reads from file on-demand)
*
* @param series Series handle
* @param value_out Output pointer to version string (caller must free)
* @return PMD_SUCCESS or error code (PMD_ERROR if attribute doesn't exist)
*/
pmd_status pmd_get_software_version(pmd_series *series, char **value_out);
/**
* Get date attribute (reads from file on-demand)
*
* @param series Series handle
* @param value_out Output pointer to date string (caller must free)
* @return PMD_SUCCESS or error code (PMD_ERROR if attribute doesn't exist)
*/
pmd_status pmd_get_date(pmd_series *series, char **value_out);
/**
* Get softwareDependencies attribute (reads from file on-demand)
*
* @param series Series handle
* @param value_out Output pointer to dependencies string (caller must free)
* @return PMD_SUCCESS or error code (PMD_ERROR if attribute doesn't exist)
*/
pmd_status pmd_get_software_dependencies(pmd_series *series, char **value_out);
/**
* Get machine attribute (reads from file on-demand)
*
* @param series Series handle
* @param value_out Output pointer to machine string (caller must free)
* @return PMD_SUCCESS or error code (PMD_ERROR if attribute doesn't exist)
*/
pmd_status pmd_get_machine(pmd_series *series, char **value_out);
/**
* Get comment attribute (reads from file on-demand)
*
* @param series Series handle
* @param value_out Output pointer to comment string (caller must free)
* @return PMD_SUCCESS or error code (PMD_ERROR if attribute doesn't exist)
*/
pmd_status pmd_get_comment(pmd_series *series, char **value_out);
/**
* Set author attribute
*
* @param series Series handle
* @param value Author string to write
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_set_author(pmd_series *series, const char *value);
/**
* Set software attribute
*
* @param series Series handle
* @param value Software name to write
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_set_software(pmd_series *series, const char *value);
/**
* Set softwareVersion attribute
*
* @param series Series handle
* @param value Software version to write
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_set_software_version(pmd_series *series, const char *value);
/**
* Set softwareDependencies attribute
*
* @param series Series handle
* @param value Dependencies string to write
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_set_software_dependencies(pmd_series *series, const char *value);
/**
* Set machine attribute
*
* @param series Series handle
* @param value Machine description to write
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_set_machine(pmd_series *series, const char *value);
/**
* Set comment attribute
*
* @param series Series handle
* @param value Comment string to write
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_set_comment(pmd_series *series, const char *value);
/**
* Get openPMDextension attribute (reads from file on-demand)
*
* @param series Series handle
* @param value_out Output pointer to extensions string (caller must free)
* @return PMD_SUCCESS or error code (PMD_ERROR if attribute doesn't exist)
*/
pmd_status pmd_get_extensions_string(pmd_series *series, char **value_out);
/* --- Particle Data Operations --- */
/**
* Allocate memory for a pmd_particle_group
*
* Allocates all arrays based on the number of particles for the species.
* User must call pmd_free_particle_group() when done.
*
* @param iter Iteration handle
* @param species Species name
* @param pg_out Output pointer to allocated pmd_particle_group
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_allocate_particle_group(pmd_iteration *iter, const char *species,
pmd_particle_group **pg_out);
/**
* Read particle group data
*
* Reads particle data into a pre-allocated pmd_particle_group.
* The pmd_particle_group arrays must be allocated before calling (e.g., via pmd_allocate_particle_group).
*
* @param iter Iteration handle
* @param species Species name
* @param pg Pre-allocated pmd_particle_group to fill
* @param read_info Optional output for read metadata (can be NULL)
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_read_particle_group(pmd_iteration *iter, const char *species,
pmd_particle_group *pg, pmd_particle_group_read_info *read_info);
/**
* Free a pmd_particle_group and its arrays
*
* @param pg pmd_particle_group to free
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_free_particle_group(pmd_particle_group *pg);
/**
* Write particle group to iteration
*
* @param iter Iteration handle
* @param pg pmd_particle_group to write
* @return PMD_SUCCESS or error code
*/
pmd_status pmd_write_particle_group(pmd_iteration *iter, const pmd_particle_group *pg);
/* --- Utility Functions --- */
#ifdef __cplusplus
}
#endif
/* =========================================================================
* Implementation
* ========================================================================= */
#ifdef PARCEL_IMPLEMENTATION
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <ctype.h> /* For isdigit() */
#include <stdarg.h> /* For variadic arguments */
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wuse-after-free"
/* =========================================================================
* Constants
* ========================================================================= */
/* Exact speed of light (m/s) */
#define CLIGHT 299792456
/* Conversion from eV/c^2 to kg (CODATA recommended value 2022) */
#define EV_C2_TO_SI 1.782661921e-36
/* Conversion factor from eV/c to SI (kg⋅m/s) */
#define EV_C_TO_SI (EV_C2_TO_SI*CLIGHT)
/* =========================================================================
* Platform-Specific Includes and Definitions
* ========================================================================= */
#if defined(_WIN32) || defined(_WIN64)
/* Windows platform */
#define PMD_PLATFORM_WINDOWS
#include <windows.h>
#include <io.h>
#define PMD_PATH_MAX MAX_PATH
#define PMD_PATH_SEP "\\"
#define PMD_PATH_SEP_CHAR '\\'
#else
/* POSIX platform (Linux, macOS, etc.) */
#define PMD_PLATFORM_POSIX
#include <limits.h> /* For PATH_MAX */
#include <libgen.h> /* For dirname() */
#include <dirent.h> /* For directory scanning */
#include <sys/stat.h> /* For stat() and S_ISDIR() */
#include <errno.h> /* For errno and EEXIST */
/* PATH_MAX is not guaranteed by POSIX, provide fallback */
#ifndef PATH_MAX
#define PATH_MAX 4096
#endif
#define PMD_PATH_MAX PATH_MAX
#define PMD_PATH_SEP "/"
#define PMD_PATH_SEP_CHAR '/'
#endif
/* =========================================================================
* Logging
* ========================================================================= */
/**
* Global log level threshold - messages below this level are suppressed
* Default: PMD_LOG_WARNING (shows errors and warnings)
*/
static pmd_log_level pmd_log_threshold = PMD_LOG_WARNING;
/**
* Set the log level threshold (implementation)
*/
void pmd_set_log_level(pmd_log_level level) {
pmd_log_threshold = level;
}
/**
* Log a message with the specified log level
*
* @param level Log level
* @param format Printf-style format string
* @param ... Variable arguments for format string
*/
static void pmd_log(pmd_log_level level, const char *format, ...) {
int status;
const char *level_str;
va_list args;
if (level > pmd_log_threshold) {
return; /* Message level below threshold, suppress */
}
switch (level) {
case PMD_LOG_ERROR: level_str = "Error"; break;
case PMD_LOG_WARNING: level_str = "Warning"; break;
case PMD_LOG_INFO: level_str = "Info"; break;
case PMD_LOG_DEBUG: level_str = "Debug"; break;
default: level_str = "Unknown"; break;
}
va_start(args, format);
/* Construct start of log line */
status = fprintf(stderr, "%s: ", level_str);
if ((status < 0) && (pmd_log_threshold > PMD_LOG_NONE)) {
printf("pmd_log - failed to construct log level message.\n");
return;
}
/* Perform user formatting */
status = vfprintf(stderr, format, args);
if ((status < 0) && (pmd_log_threshold > PMD_LOG_NONE)) {
printf("pmd_log - failed to apply user formatting to log message.\n");
return;
}
/* Append newline to each message*/
status = fprintf(stderr, "\n");
if ((status < 0) && (pmd_log_threshold > PMD_LOG_NONE)) {
printf("pmd_log - failed to add newline to log message.\n");
return;
}
va_end(args);
}
/* =========================================================================
* Forward Declarations
* ========================================================================= */
static int record_exists(hid_t group_id, const char *name);
static pmd_status validate_attribute_type(hid_t attr_id, H5T_class_t expected_class);
static pmd_status read_record_generic(hid_t group_id, const char *name,
void *array, hid_t h5_type, size_t elem_size,
int64_t num_particles, double *unit_si_out);
static pmd_status read_double_record(hid_t group_id, const char *name, double *array,
int64_t num_particles, double unit_multiplier);
static pmd_status read_int64_record(hid_t group_id, const char *name, int64_t *array,
int64_t num_particles);
static pmd_status read_double_attribute(hid_t loc_id, const char *attr_name, double *value_out);
static pmd_status write_string_attribute(hid_t loc_id, const char *attr_name, const char *value);
static pmd_status write_double_attribute(hid_t loc_id, const char *attr_name, double value);
static unsigned int pmd_access_mode_to_hdf5(pmd_access_mode mode);
static pmd_status write_root_attributes(hid_t file_id, pmd_series *series);
static pmd_status write_iteration_attributes(hid_t group_id);
static pmd_status ensure_parent_groups(hid_t file_id, const char *path);
static pmd_status write_series_root_attributes(pmd_series *series);
static pmd_status write_double_record(hid_t group_id, const char *name, const double *data,
int64_t num_particles, double unit_si,
const pmd_unit_dimension *unit_dim, double time_offset);
static pmd_status write_int64_dataset(hid_t group_id, const char *name, const int64_t *data,
int64_t num_particles,
const pmd_unit_dimension *unit_dim, double time_offset);
static pmd_status write_int64_attribute(hid_t loc_id, const char *attr_name, int64_t value);
static void pmd_invalidate_iterations_cache(pmd_series *series);
/* Pattern matching forward declarations */
typedef struct {
char *scan_parent;
char *first_segment;
const char *full_pattern;
} iteration_pattern;
static pmd_status parse_iteration_pattern(const char *pattern, iteration_pattern *info);
static void free_iteration_pattern(iteration_pattern *info);
static pmd_status extract_iteration_from_name(const char *name, const char *pattern,
int64_t *iteration_out);
static char* replace_iteration(const char *pattern, int64_t iteration);
/* =========================================================================
* C99-Compliant String Utilities
* ========================================================================= */
/**
* C99-compliant string duplication
* Replacement for POSIX pmd_strdup which is not part of C99
*/
static char* pmd_strdup(const char *s) {
if (!s) return NULL;
size_t len = strlen(s) + 1;
char *dup = (char *)malloc(len);
if (dup) {
memcpy(dup, s, len);
}
return dup;
}
/* =========================================================================
* Platform-Specific Directory and Path Utilities
* ========================================================================= */
#ifdef PMD_PLATFORM_WINDOWS
/* Windows directory iteration structure */
typedef struct {
HANDLE handle;
WIN32_FIND_DATAA find_data;
int first_call;
} pmd_dir;
/* Windows directory entry structure */
typedef struct {
char d_name[MAX_PATH];
} pmd_dirent;
/**
* Open directory for reading (Windows implementation)
*/
static pmd_dir* pmd_opendir(const char *path) {
pmd_dir *dir = (pmd_dir*)malloc(sizeof(pmd_dir));
if (!dir) return NULL;
char search_path[MAX_PATH];
snprintf(search_path, sizeof(search_path), "%s\\*", path);
dir->handle = FindFirstFileA(search_path, &dir->find_data);
if (dir->handle == INVALID_HANDLE_VALUE) {
free(dir);
return NULL;
}
dir->first_call = 1;
return dir;
}
/**
* Read next directory entry (Windows implementation)
*/
static pmd_dirent* pmd_readdir(pmd_dir *dir) {
static pmd_dirent entry;
if (!dir) return NULL;
if (dir->first_call) {
dir->first_call = 0;
strncpy(entry.d_name, dir->find_data.cFileName, MAX_PATH - 1);
entry.d_name[MAX_PATH - 1] = '\0';
return &entry;
}
if (FindNextFileA(dir->handle, &dir->find_data)) {
strncpy(entry.d_name, dir->find_data.cFileName, MAX_PATH - 1);
entry.d_name[MAX_PATH - 1] = '\0';
return &entry;
}
return NULL;
}
/**
* Close directory (Windows implementation)
*/
static int pmd_closedir(pmd_dir *dir) {
if (!dir) return -1;
FindClose(dir->handle);
free(dir);
return 0;
}
/**
* Extract directory path from filename (Windows implementation)
* Caller must free the returned string
*/
static char* pmd_dirname(const char *path) {
char *dir = pmd_strdup(path);
if (!dir) return NULL;
/* Find last backslash or forward slash */
char *last_sep = NULL;
char *p = dir;
while (*p) {
if (*p == '\\' || *p == '/') {
last_sep = p;
}
p++;
}
if (last_sep) {
*last_sep = '\0';
} else {
/* No separator found, return "." */
free(dir);
dir = pmd_strdup(".");
}
return dir;
}
#else /* PMD_PLATFORM_POSIX */
/* POSIX: use standard types and functions */
typedef DIR pmd_dir;
typedef struct dirent pmd_dirent;
#define pmd_opendir opendir
#define pmd_readdir readdir
#define pmd_closedir closedir
/**
* Extract directory path from filename (POSIX implementation)
* Caller must free the returned string
*/
static char* pmd_dirname(const char *path) {
char *path_copy = pmd_strdup(path);
if (!path_copy) return NULL;
char *result = pmd_strdup(dirname(path_copy));
free(path_copy);
return result;
}
#endif /* PMD_PLATFORM_WINDOWS */
/* =========================================================================
* Helper Functions
* ========================================================================= */
/**
* Check if an attribute exists on an HDF5 object
* Returns 1 if exists, 0 if not, -1 on error
*/
static int attribute_exists(hid_t loc_id, const char *attr_name) {
htri_t exists = H5Aexists(loc_id, attr_name);
return (int)exists;
}
/**
* Read a string attribute from an HDF5 object
* Returns PMD_SUCCESS on success, error code on failure
*/
static pmd_status read_string_attribute(hid_t loc_id, const char *attr_name, char **value_out) {
hid_t attr_id;
hid_t atype_id;
char *str_value = NULL;
htri_t is_variable;
pmd_status status;
/* Check if attribute exists */
if (attribute_exists(loc_id, attr_name) <= 0) {
pmd_log(PMD_LOG_ERROR, "Missing '%s' attribute", attr_name);
return PMD_ERROR_FILE_FORMAT;
}
/* Open attribute */
attr_id = H5Aopen(loc_id, attr_name, H5P_DEFAULT);
if (attr_id < 0) {
return PMD_ERROR_HDF5;
}
/* Check that attribute is right type */
status = validate_attribute_type(attr_id, H5T_STRING);
if (status != PMD_SUCCESS) {
H5Aclose(attr_id);
return status;
}
/* Get attribute type */
atype_id = H5Aget_type(attr_id);
/* Check if variable-length string */
is_variable = H5Tis_variable_str(atype_id);
if (is_variable > 0) {
/* Variable-length string - HDF5 allocates memory */
char *vlen_str = NULL;
if (H5Aread(attr_id, atype_id, &vlen_str) < 0) {
H5Tclose(atype_id);
H5Aclose(attr_id);
return PMD_ERROR_HDF5;
}
/* Copy to our own allocated memory */
str_value = pmd_strdup(vlen_str);
if (!str_value) {
H5free_memory(vlen_str);
H5Tclose(atype_id);
H5Aclose(attr_id);
return PMD_ERROR_OUT_OF_MEMORY;
}
/* Free HDF5-allocated memory */
H5free_memory(vlen_str);
} else {
/* Fixed-length string */
size_t size = H5Tget_size(atype_id);
/* Allocate buffer */
str_value = (char *)malloc(size + 1);
if (!str_value) {
H5Tclose(atype_id);
H5Aclose(attr_id);
return PMD_ERROR_OUT_OF_MEMORY;
}
/* Read attribute */
if (H5Aread(attr_id, atype_id, str_value) < 0) {
free(str_value);
H5Tclose(atype_id);
H5Aclose(attr_id);
return PMD_ERROR_HDF5;
}
str_value[size] = '\0'; /* Null terminate */
}
*value_out = str_value;
H5Tclose(atype_id);
H5Aclose(attr_id);
return PMD_SUCCESS;
}
/**
* Recursively create all parent directories of a file path
*
* @param dirpath Directory path to create
* @return PMD_SUCCESS on success, error code otherwise
*/