File: createGRIB2inputProcessIdentifiersConceptsFromYaml.py

package info (click to toggle)
eccodes 2.46.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 154,956 kB
  • sloc: cpp: 163,970; ansic: 26,310; sh: 22,006; f90: 6,854; perl: 6,361; python: 5,352; java: 2,226; javascript: 1,427; yacc: 854; fortran: 543; lex: 359; makefile: 279; xml: 183; awk: 66
file content (251 lines) | stat: -rwxr-xr-x 7,766 bytes parent folder | download
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
#!/usr/bin/env python3

import yaml
import shutil
import os
import sys
import argparse
from jsonschema import validate, ValidationError

# =========================================================
# User settings
# =========================================================
INPUT_YAML = "grib2/localConcepts/ecmf/inputProcessIdentifierList.yaml"

# Output files in sub-folder
NAME_OUTPUT = "grib2/localConcepts/ecmf/inputModelNameConcept.def"
VERSION_OUTPUT = "grib2/localConcepts/ecmf/inputModelVersionConcept.def"

# Formatting toggles
ADD_BLANK_LINE_BEFORE_MODEL = True
INCLUDE_ID_RANGE_IN_COMMENT = True

# Copy settings
ENABLE_COPY = True
DEST_FOLDERS = [
    "grib2/localConcepts/hydro",
]

# =========================================================
# CLI
# =========================================================
parser = argparse.ArgumentParser(
    description=f"Generate {NAME_OUTPUT} and {VERSION_OUTPUT} from YAML"
)

parser.add_argument(
    "--dry-run",
    action="store_true",
    help="Process YAML but do not write files"
)

parser.add_argument(
    "--validate-only",
    action="store_true",
    help="Only validate YAML and exit"
)

args = parser.parse_args()

# =========================================================
# YAML Schema
# =========================================================
SCHEMA = {
    "type": "object",
    "required": ["models"],
    "properties": {
        "models": {
            "type": "array",
            "items": {
                "type": "object",
                "required": ["name", "start"],
                "additionalProperties": False,
                "properties": {
                    "name": {"type": "string"},
                    "start": {"type": "integer"},
                    "extra_keys": {
                        "type": "object",
                        "additionalProperties": {
                            "type": ["string", "number", "boolean"]
                        }
                    },
                    "versions": {
                        "type": "array",
                        "items": {
                            "oneOf": [
                                {"type": ["string", "null"]},
                                {
                                    "type": "object",
                                    "additionalProperties": False,
                                    "properties": {
                                        "version": {"type": ["string", "null"]},
                                        "skip": {"type": "boolean"},
                                        "override_id": {"type": "integer"},
                                        "extra_keys": {
                                            "type": "object",
                                            "additionalProperties": {
                                                "type": ["string", "number", "boolean"]
                                            }
                                        }
                                    }
                                }
                            ]
                        }
                    }
                }
            }
        }
    }
}

# =========================================================
# Ensure output folders exist (if needed)
# =========================================================
for path in (NAME_OUTPUT, VERSION_OUTPUT):
    d = os.path.dirname(path)
    if d:
        os.makedirs(d, exist_ok=True)

# =========================================================
# Read & validate YAML
# =========================================================
try:
    with open(INPUT_YAML, "r") as f:
        data = yaml.safe_load(f)
except Exception as e:
    sys.exit(f"ERROR reading YAML: {e}")

try:
    validate(instance=data, schema=SCHEMA)
except ValidationError as e:
    sys.exit(f"YAML SCHEMA VALIDATION ERROR:\n{e.message}")

if args.validate_only:
    print("YAML validation successful.")
    sys.exit(0)

# =========================================================
# Build blocks
# =========================================================
blocks = []
used_ids = {}  # id -> "MODEL VERSION"

for model in data["models"]:
    model_name = model["name"]
    start_id = int(model["start"])
    versions = model.get("versions", [])
    block_extra = model.get("extra_keys", {})

    entries = []
    current_id = start_id

    for v in versions:
        if isinstance(v, dict):
            version = v.get("version") or model_name
            version_extra = v.get("extra_keys", {})
            skip = v.get("skip", False)
            override_id = v.get("override_id")
        else:
            version = v if v else model_name
            version_extra = {}
            skip = False
            override_id = None

        if override_id is not None:
            id_val = override_id
        else:
            id_val = current_id

        combined_extra = {**block_extra, **version_extra}

        if not skip:
            if id_val in used_ids:
                sys.exit(
                    "ID COLLISION DETECTED:\n"
                    f"  ID {id_val} used by:\n"
                    f"    - {used_ids[id_val]}\n"
                    f"    - {model_name} {version}"
                )

            used_ids[id_val] = f"{model_name} {version}"
            entries.append((model_name, version, id_val, combined_extra))

        if override_id is None:
            current_id += 1

    blocks.append({
        "model": model_name,
        "entries": entries
    })

# =========================================================
# Sort blocks
# =========================================================
blocks.sort(key=lambda b: b["entries"][0][2] if b["entries"] else float("inf"))

# =========================================================
# Generate output
# =========================================================
name_lines = []
version_lines = []

for block in blocks:
    if not block["entries"]:
        continue

    model = block["model"]
    ids = [e[2] for e in block["entries"]]
    start_id = min(ids)
    end_id = max(ids)

    prefix = "\n" if ADD_BLANK_LINE_BEFORE_MODEL else ""
    #header = f"{prefix}# MODEL {model}"
    header = f"{prefix}# {model}"
    if INCLUDE_ID_RANGE_IN_COMMENT:
        header += f" (ID range: {start_id}-{end_id})"
    header += "\n"

    name_lines.append(header)
    version_lines.append(header)

    for model_name, version, id_val, extra in block["entries"]:
        extra_str = "".join(f"{k}={v};" for k, v in extra.items())

        name_lines.append(
            f"'{model_name}' = {{inputProcessIdentifier={id_val};{extra_str}}}\n"
        )

        if version == model_name:
            version_lines.append(
                f"'{model_name}' = {{inputProcessIdentifier={id_val};{extra_str}}}\n"
            )
        else:
            version_lines.append(
                f"'{model_name}-{version}' = {{inputProcessIdentifier={id_val};{extra_str}}}\n"
            )

# =========================================================
# Write files
# =========================================================
if args.dry_run:
    print("Dry run enabled — no files written.")
else:
    for path in (NAME_OUTPUT, VERSION_OUTPUT):
        d = os.path.dirname(path)
        if d:
            os.makedirs(d, exist_ok=True)

    with open(NAME_OUTPUT, "w") as f:
        f.writelines(name_lines)
    print(f"Created file: {NAME_OUTPUT}")

    with open(VERSION_OUTPUT, "w") as f:
        f.writelines(version_lines)
    print(f"Created file: {VERSION_OUTPUT}")

    if ENABLE_COPY:
        for folder in DEST_FOLDERS:
            os.makedirs(folder, exist_ok=True)
            shutil.copy(NAME_OUTPUT, folder)
            shutil.copy(VERSION_OUTPUT, folder)