frameit 1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. frameit-1.0/PKG-INFO +4 -0
  2. frameit-1.0/README.md +93 -0
  3. frameit-1.0/pyproject.toml +45 -0
  4. frameit-1.0/setup.cfg +4 -0
  5. frameit-1.0/src/frameit/__init__.py +5 -0
  6. frameit-1.0/src/frameit/__main__.py +4 -0
  7. frameit-1.0/src/frameit/_version.py +13 -0
  8. frameit-1.0/src/frameit/check/__init__.py +3 -0
  9. frameit-1.0/src/frameit/check/check_functions.py +157 -0
  10. frameit-1.0/src/frameit/cli.py +271 -0
  11. frameit-1.0/src/frameit/core/__init__.py +0 -0
  12. frameit-1.0/src/frameit/core/runner.py +210 -0
  13. frameit-1.0/src/frameit/core/settings_class.py +283 -0
  14. frameit-1.0/src/frameit/io/__init__.py +0 -0
  15. frameit-1.0/src/frameit/io/grib_utils.py +255 -0
  16. frameit-1.0/src/frameit/io/grib_utils_old.py +256 -0
  17. frameit-1.0/src/frameit/io/loader.py +96 -0
  18. frameit-1.0/src/frameit/io/netcdf_export.py +485 -0
  19. frameit-1.0/src/frameit/io/netcdf_utils.py +202 -0
  20. frameit-1.0/src/frameit/io/netcdf_utils_old.py +198 -0
  21. frameit-1.0/src/frameit/processing/__init__.py +6 -0
  22. frameit-1.0/src/frameit/processing/derived/wind.py +119 -0
  23. frameit-1.0/src/frameit/processing/dims_utils.py +128 -0
  24. frameit-1.0/src/frameit/processing/extraction.py +703 -0
  25. frameit-1.0/src/frameit/processing/polar/__init__.py +3 -0
  26. frameit-1.0/src/frameit/processing/polar/polar_grid.py +339 -0
  27. frameit-1.0/src/frameit/processing/polar/polar_proj.py +507 -0
  28. frameit-1.0/src/frameit/processing/polar/polar_proj_diag.py +462 -0
  29. frameit-1.0/src/frameit/processing/polar/polar_utils.py +179 -0
  30. frameit-1.0/src/frameit/processing/requests.py +258 -0
  31. frameit-1.0/src/frameit/processing/tracking/postprocess.py +213 -0
  32. frameit-1.0/src/frameit/processing/tracking/postprocess_old.py +185 -0
  33. frameit-1.0/src/frameit/processing/wind_collocation.py +368 -0
  34. frameit-1.0/src/frameit/tracking/FixedBox_Tracker.py +192 -0
  35. frameit-1.0/src/frameit/tracking/PrescribedTrack_Tracker.py +244 -0
  36. frameit-1.0/src/frameit/tracking/PressureWind_Tracker.py +204 -0
  37. frameit-1.0/src/frameit/tracking/Utrack_Tracker.py +78 -0
  38. frameit-1.0/src/frameit/tracking/__init__.py +9 -0
  39. frameit-1.0/src/frameit/tracking/tracker_core.py +184 -0
  40. frameit-1.0/src/frameit/utils/__init__.py +13 -0
  41. frameit-1.0/src/frameit/utils/logging.py +87 -0
  42. frameit-1.0/src/frameit/utils/logging_helpers.py +74 -0
  43. frameit-1.0/src/frameit/utils/timing.py +49 -0
  44. frameit-1.0/src/frameit/viz/__init__.py +0 -0
  45. frameit-1.0/src/frameit/viz/polar_axes.py +16 -0
  46. frameit-1.0/src/frameit.egg-info/PKG-INFO +4 -0
  47. frameit-1.0/src/frameit.egg-info/SOURCES.txt +50 -0
  48. frameit-1.0/src/frameit.egg-info/dependency_links.txt +1 -0
  49. frameit-1.0/src/frameit.egg-info/entry_points.txt +2 -0
  50. frameit-1.0/src/frameit.egg-info/top_level.txt +1 -0
  51. frameit-1.0/tests/test_integration_runner_multi_configs.py +165 -0
  52. frameit-1.0/tests/test_units_config.py +9 -0
frameit-1.0/PKG-INFO ADDED
@@ -0,0 +1,4 @@
1
+ Metadata-Version: 2.4
2
+ Name: frameit
3
+ Version: 1.0
4
+ Requires-Python: >=3.10
frameit-1.0/README.md ADDED
@@ -0,0 +1,93 @@
1
+ # CycloPyV2
2
+
3
+
4
+
5
+ ## Getting started
6
+
7
+ To make it easy for you to get started with GitLab, here's a list of recommended next steps.
8
+
9
+ Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
10
+
11
+ ## Add your files
12
+
13
+ - [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
14
+ - [ ] [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:
15
+
16
+ ```
17
+ cd existing_repo
18
+ git remote add origin https://gitlab.meteo.fr/souffletc/cyclopyv2.git
19
+ git branch -M main
20
+ git push -uf origin main
21
+ ```
22
+
23
+ ## Integrate with your tools
24
+
25
+ - [ ] [Set up project integrations](https://gitlab.meteo.fr/souffletc/cyclopyv2/-/settings/integrations)
26
+
27
+ ## Collaborate with your team
28
+
29
+ - [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
30
+ - [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
31
+ - [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
32
+ - [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
33
+ - [ ] [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)
34
+
35
+ ## Test and Deploy
36
+
37
+ Use the built-in continuous integration in GitLab.
38
+
39
+ - [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/)
40
+ - [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
41
+ - [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
42
+ - [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
43
+ - [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
44
+
45
+ ***
46
+
47
+ # Editing this README
48
+
49
+ When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
50
+
51
+ ## Suggestions for a good README
52
+
53
+ Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
54
+
55
+ ## Name
56
+ Choose a self-explaining name for your project.
57
+
58
+ ## Description
59
+ Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
60
+
61
+ ## Badges
62
+ On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
63
+
64
+ ## Visuals
65
+ Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
66
+
67
+ ## Installation
68
+ Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
69
+
70
+ ## Usage
71
+ Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
72
+
73
+ ## Support
74
+ Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
75
+
76
+ ## Roadmap
77
+ If you have ideas for releases in the future, it is a good idea to list them in the README.
78
+
79
+ ## Contributing
80
+ State if you are open to contributions and what your requirements are for accepting them.
81
+
82
+ For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
83
+
84
+ You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
85
+
86
+ ## Authors and acknowledgment
87
+ Show your appreciation to those who have contributed to the project.
88
+
89
+ ## License
90
+ For open source projects, say how it is licensed.
91
+
92
+ ## Project status
93
+ If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
@@ -0,0 +1,45 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "frameit"
7
+ version = "1.0"
8
+ requires-python = ">=3.10"
9
+
10
+ [tool.setuptools.packages.find]
11
+ where = ["src"]
12
+
13
+ [tool.pytest.ini_options]
14
+ addopts = "-ra"
15
+ testpaths = ["tests"]
16
+
17
+ [project.scripts]
18
+ frameit = "frameit.cli:main"
19
+
20
+ [tool.ruff]
21
+ line-length = 100
22
+ target-version = "py310"
23
+ extend-exclude = [
24
+ "DRAFT",
25
+ "notebooks",
26
+ "docs/build",
27
+ "src/frameit.egg-info",
28
+ ".venv",
29
+ "build",
30
+ "dist",
31
+ ]
32
+
33
+ [tool.ruff.lint]
34
+ # Ensemble volontairement conservateur, utile, peu bruyant
35
+ select = ["E", "F", "I", "UP", "B"]
36
+ fixable = ["ALL"]
37
+
38
+ [tool.ruff.lint.per-file-ignores]
39
+ # Fréquent dans les packages: imports ré-exportés dans __init__.py
40
+ "src/frameit/__init__.py" = ["F401"]
41
+
42
+ [tool.ruff.format]
43
+ quote-style = "double"
44
+
45
+
frameit-1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,5 @@
1
+ import logging
2
+
3
+ from ._version import __version__
4
+
5
+ logging.getLogger("cyclopy").addHandler(logging.NullHandler())
@@ -0,0 +1,4 @@
1
+ from frameit.cli import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1,13 @@
1
+ from __future__ import annotations
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+
6
+ def get_cyclopy_version() -> str:
7
+ try:
8
+ return version("cyclopy")
9
+ except PackageNotFoundError:
10
+ return "unknown"
11
+
12
+
13
+ __version__ = get_cyclopy_version()
@@ -0,0 +1,3 @@
1
+ from .check_functions import check_group_var # nouvelle importation
2
+
3
+ __all__ = ["check_group_var"]
@@ -0,0 +1,157 @@
1
+ import logging
2
+
3
+ import numpy as np
4
+ import xarray as xr
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+
9
+ def drop_time_dupes(ds: xr.Dataset, keep: str = "first") -> xr.Dataset:
10
+ # keep: "first" ou "last"
11
+ t = ds["time"].values
12
+ if keep == "last":
13
+ # indices des dernières occurrences
14
+ _, idx = np.unique(t[::-1], return_index=True)
15
+ keep_idx = (t.size - 1) - np.sort(idx)
16
+ else:
17
+ # indices des premières occurrences
18
+ _, idx = np.unique(t, return_index=True)
19
+ keep_idx = np.sort(idx)
20
+ return ds.isel(time=keep_idx)
21
+
22
+
23
+ def check_group_var(by_group: dict, requests: dict) -> dict:
24
+ """
25
+ Supporte:
26
+ - by_group plat: {group -> xr.Dataset}, requests: {group -> spec}
27
+ - by_group imbriqué: {method -> {group -> xr.Dataset}},
28
+ requests: {method -> {group -> spec}} OU {group -> spec}
29
+
30
+ Retour:
31
+ {
32
+ "\t\t\tignored_groups": [ "group" | "method/group", ... ],
33
+ "missing_by_group": { "group" | "method/group": [vars manquantes] }
34
+ }
35
+ """
36
+
37
+ def _is_group_spec_map(d: dict) -> bool:
38
+ if not isinstance(d, dict) or not d:
39
+ return False
40
+ return all(
41
+ isinstance(v, dict)
42
+ and any(
43
+ k in v
44
+ for k in ("variables", "level_selection", "level_indices", "level_values", "levels")
45
+ )
46
+ for v in d.values()
47
+ )
48
+
49
+ def _is_method_group_spec_map(d: dict) -> bool:
50
+ if not isinstance(d, dict) or not d:
51
+ return False
52
+ return all(_is_group_spec_map(v) for v in d.values())
53
+
54
+ def _expected_vars(spec: dict) -> set:
55
+ return set((spec or {}).get("variables") or [])
56
+
57
+ if not isinstance(by_group, dict) or not by_group:
58
+ return {"\t\t\tignored_groups": [], "missing_by_group": {}}
59
+
60
+ # Détection by_group plat vs imbriqué
61
+ is_flat = all(hasattr(v, "dims") for v in by_group.values() if v is not None)
62
+
63
+ if is_flat:
64
+ # Log dims
65
+ for g, ds in by_group.items():
66
+ dims = ", ".join(f"{k}={v}" for k, v in ds.dims.items())
67
+ logger.info("\t\t\tDataset[%s] : dimensions %s", g, dims)
68
+
69
+ # Normalisation requests -> {group -> spec}
70
+ req_map = requests or {}
71
+ if not _is_group_spec_map(req_map):
72
+ req_map = {}
73
+
74
+ requested_groups = set(req_map.keys())
75
+ loaded_groups = set(by_group.keys())
76
+
77
+ ignored = requested_groups - loaded_groups
78
+ if ignored:
79
+ logger.info(
80
+ "\t\t\tGroupes ignorés car absents dans les données: %s", ", ".join(sorted(ignored))
81
+ )
82
+
83
+ missing_by_group: dict[str, list[str]] = {}
84
+ for grp in sorted(loaded_groups & requested_groups):
85
+ exp = _expected_vars(req_map.get(grp))
86
+ if not exp:
87
+ continue
88
+ present = set(by_group[grp].data_vars)
89
+ missing = sorted(exp - present)
90
+ if missing:
91
+ logger.warning("\t\t\t[%s] Variables manquantes: %s", grp, ", ".join(missing))
92
+ missing_by_group[grp] = missing
93
+ else:
94
+ logger.info(
95
+ "\t\t\t[%s] Toutes les variables demandées sont présentes (%d).", grp, len(exp)
96
+ )
97
+
98
+ return {"\t\t\tignored_groups": sorted(ignored), "missing_by_group": missing_by_group}
99
+
100
+ # Imbriqué: {method -> {group -> xr.Dataset}}
101
+ # Log dims
102
+ for m, grp_map in by_group.items():
103
+ if not isinstance(grp_map, dict):
104
+ continue
105
+ for g, ds in grp_map.items():
106
+ if not hasattr(ds, "dims"):
107
+ continue
108
+ dims = ", ".join(f"{k}={v}" for k, v in ds.dims.items())
109
+ logger.info("\t\t\tDataset[%s/%s] : dimensions %s", m, g, dims)
110
+
111
+ # Normaliser requests
112
+ req_in = requests or {}
113
+ if _is_method_group_spec_map(req_in):
114
+ req_methods = req_in # {method -> {group -> spec}}
115
+ elif _is_group_spec_map(req_in):
116
+ # Appliquer le même bloc de groupes à toutes les méthodes présentes
117
+ req_methods = {m: req_in for m in by_group.keys() if isinstance(by_group.get(m), dict)}
118
+ else:
119
+ req_methods = {}
120
+
121
+ methods = set(k for k, v in by_group.items() if isinstance(v, dict)) | set(req_methods.keys())
122
+
123
+ ignored_flat: list[str] = []
124
+ missing_flat: dict[str, list[str]] = {}
125
+
126
+ for m in sorted(methods):
127
+ grp_map = by_group.get(m) if isinstance(by_group.get(m), dict) else {}
128
+ req_map = req_methods.get(m, {})
129
+
130
+ requested_groups = set(req_map.keys())
131
+ loaded_groups = set(grp_map.keys())
132
+
133
+ ignored = requested_groups - loaded_groups
134
+ if ignored:
135
+ logger.info(
136
+ "\t\t\tGroupes ignorés car absents dans les données pour %s: %s",
137
+ m,
138
+ ", ".join(sorted(ignored)),
139
+ )
140
+ ignored_flat.extend([f"{m}/{g}" for g in sorted(ignored)])
141
+
142
+ for g in sorted(loaded_groups & requested_groups):
143
+ exp = _expected_vars(req_map.get(g))
144
+ if not exp:
145
+ continue
146
+ present = set(grp_map[g].data_vars)
147
+ missing = sorted(exp - present)
148
+ key = f"{m}/{g}"
149
+ if missing:
150
+ logger.warning("\t\t\t[%s] Variables manquantes: %s", key, ", ".join(missing))
151
+ missing_flat[key] = missing
152
+ else:
153
+ logger.info(
154
+ "\t\t\t[%s] Toutes les variables demandées sont présentes (%d).", key, len(exp)
155
+ )
156
+
157
+ return {"\t\t\tignored_groups": ignored_flat, "missing_by_group": missing_flat}
@@ -0,0 +1,271 @@
1
+
2
+ # src/cyclopy/cli.py
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+ from pathlib import Path
8
+
9
+
10
+ def _sanitize_sys_path_user_site() -> None:
11
+ """
12
+ Ensure CycloPy CLI does not import packages from the user site-packages (e.g. ~/.local),
13
+ which can shadow the conda environment and break version consistency.
14
+ """
15
+ # Fast path: if PYTHONNOUSERSITE is set, user site is usually not injected.
16
+ # Still sanitize defensively because PYTHONPATH or .pth files may add ~/.local manually.
17
+ user_base = Path(os.path.expanduser("~/.local")).resolve()
18
+
19
+ new_path: list[str] = []
20
+ for p in sys.path:
21
+ try:
22
+ rp = Path(p).resolve()
23
+ except Exception:
24
+ new_path.append(p)
25
+ continue
26
+
27
+ # Drop typical user installs, including ~/.local and user site-packages.
28
+ if user_base in rp.parents or rp == user_base:
29
+ continue
30
+
31
+ new_path.append(p)
32
+
33
+ sys.path[:] = new_path
34
+
35
+
36
+ _sanitize_sys_path_user_site()
37
+
38
+ # Imports only after sys.path is sanitized
39
+ from frameit.core.runner import CycloPyRunner # noqa: E402
40
+ import argparse
41
+ import logging
42
+ import platform
43
+ from typing import Any
44
+
45
+ from frameit.core.runner import CycloPyRunner
46
+ from frameit.core.settings_class import SimulationConfig
47
+ from frameit.io.netcdf_export import export_outputs
48
+ from frameit.utils import setup_cyclopy_logging
49
+
50
+ _DEFAULT_INSTITUTION = "LACy, Université de La Réunion, CNRS, Météo-France"
51
+
52
+
53
+ def _package_version(pkg_name: str) -> str | None:
54
+ try:
55
+ from importlib.metadata import version
56
+
57
+ return version(pkg_name)
58
+ except Exception:
59
+ return None
60
+
61
+
62
+ def _probe_module(mod_name: str) -> dict[str, Any]:
63
+ out = {"ok": False, "version": None, "path": None, "error": None}
64
+ try:
65
+ mod = __import__(mod_name)
66
+ out["ok"] = True
67
+ out["version"] = getattr(mod, "__version__", None) or _package_version(mod_name)
68
+ out["path"] = getattr(mod, "__file__", None)
69
+ return out
70
+ except Exception as exc:
71
+ out["error"] = str(exc)
72
+ return out
73
+
74
+
75
+ def _build_parser() -> argparse.ArgumentParser:
76
+ p = argparse.ArgumentParser(prog="cyclopy", description="CycloPy CLI")
77
+ sub = p.add_subparsers(dest="command", required=True)
78
+
79
+ # run
80
+ pr = sub.add_parser("run", help="Run CycloPy from a YAML configuration file.")
81
+ pr.add_argument("config", type=Path, help="Path to the YAML configuration file")
82
+ pr.add_argument(
83
+ "--log-level",
84
+ default=None,
85
+ choices=("DEBUG", "INFO", "WARNING", "ERROR"),
86
+ help="Override log level. If not set, uses conf.DEBUG to choose DEBUG/INFO.",
87
+ )
88
+ pr.add_argument(
89
+ "--no-hdf5-debug-pop",
90
+ action="store_true",
91
+ help="Do not remove HDF5_DEBUG from the environment.",
92
+ )
93
+
94
+ # Exports enabled by default, disable with --no-*
95
+ pr.add_argument(
96
+ "--no-export-netcdf",
97
+ dest="export_netcdf",
98
+ action="store_false",
99
+ default=True,
100
+ help="Disable NetCDF export (enabled by default).",
101
+ )
102
+ pr.add_argument(
103
+ "--no-export-polar",
104
+ dest="export_polar",
105
+ action="store_false",
106
+ default=True,
107
+ help="Disable polar export (enabled by default).",
108
+ )
109
+ pr.add_argument(
110
+ "--no-export-cart",
111
+ dest="export_cart",
112
+ action="store_false",
113
+ default=True,
114
+ help="Disable cartesian export (enabled by default).",
115
+ )
116
+ pr.add_argument(
117
+ "--compress-level",
118
+ type=int,
119
+ default=1,
120
+ help="NetCDF compression level (0-9). Default: 1.",
121
+ )
122
+ pr.add_argument(
123
+ "--institution",
124
+ type=str,
125
+ default=_DEFAULT_INSTITUTION,
126
+ help="Institution string stored in exported files.",
127
+ )
128
+
129
+ # validate
130
+ pv = sub.add_parser("validate", help="Load and validate the YAML configuration (lightweight).")
131
+ pv.add_argument("config", type=Path, help="Path to the YAML configuration file")
132
+
133
+ # info (fusion of version and doctor, verbose by default)
134
+ pi = sub.add_parser(
135
+ "info", help="Print CycloPy and environment information (verbose by default)."
136
+ )
137
+ pi.add_argument("--short", action="store_true", help="Print only 'CycloPy <version>'")
138
+
139
+ return p
140
+
141
+
142
+ def _configure_logging(conf: SimulationConfig, log_level_override: str | None) -> None:
143
+ level = log_level_override
144
+ if level is None:
145
+ level = "DEBUG" if getattr(conf, "DEBUG", False) else "INFO"
146
+
147
+ log_path = setup_cyclopy_logging(
148
+ conf.cyclopy_output_dir,
149
+ level=level,
150
+ simu_name=getattr(conf, "simulation_name", None),
151
+ )
152
+ logging.getLogger("cyclopy").info("Logging initialized: %s", str(log_path))
153
+
154
+
155
+ def _cmd_validate(cfg_path: Path) -> int:
156
+ conf = SimulationConfig.from_yaml_with_model_preset(cfg_path)
157
+
158
+ out_dir = Path(conf.cyclopy_output_dir)
159
+ if not out_dir.exists():
160
+ print(f"WARNING: output directory does not exist: {out_dir}")
161
+ elif not os.access(out_dir, os.W_OK):
162
+ print(f"WARNING: no write permission on output directory: {out_dir}")
163
+
164
+ print("OK: configuration loaded successfully")
165
+ return 0
166
+
167
+
168
+
169
+ def _cmd_info(short: bool) -> int:
170
+ cyclopy_ver = _package_version("cyclopy") or "unknown"
171
+ if short:
172
+ print(f"CycloPy {cyclopy_ver}")
173
+ return 0
174
+
175
+ print(f"CycloPy: {cyclopy_ver}")
176
+ print(f"Python: {platform.python_version()} ({sys.executable})")
177
+ print(f"Platform: {platform.system()} {platform.release()} ({platform.machine()})")
178
+
179
+ env_keys = ("HDF5_DEBUG", "ECCODES_DEFINITION_PATH", "ECCODES_SAMPLES_PATH")
180
+ print("Environment:")
181
+ for k in env_keys:
182
+ print(f" {k}={os.environ.get(k, '')}")
183
+
184
+ modules = {
185
+ "numpy": _probe_module("numpy"),
186
+ "xarray": _probe_module("xarray"),
187
+ "dask": _probe_module("dask"),
188
+ "cfgrib": _probe_module("cfgrib"),
189
+ "eccodes": _probe_module("eccodes"),
190
+ "xesmf": _probe_module("xesmf"),
191
+ "netCDF4": _probe_module("netCDF4"),
192
+ "h5py": _probe_module("h5py"),
193
+ }
194
+
195
+ print("Modules:")
196
+ for name in sorted(modules):
197
+ m = modules[name]
198
+ if m["ok"]:
199
+ ver = m["version"] or ""
200
+ print(f" {name}: OK {ver}".rstrip())
201
+ else:
202
+ print(f" {name}: MISSING")
203
+ if m["error"]:
204
+ print(f" error: {m['error']}")
205
+
206
+ critical_missing = [k for k in ("numpy", "xarray") if not modules[k]["ok"]]
207
+ if critical_missing:
208
+ print(f"Overall: FAIL (missing critical modules: {', '.join(critical_missing)})")
209
+ return 1
210
+
211
+ print("Overall: OK")
212
+ return 0
213
+
214
+
215
+ def _cmd_run(args: argparse.Namespace) -> int:
216
+ if not args.no_hdf5_debug_pop:
217
+ os.environ.pop("HDF5_DEBUG", None)
218
+
219
+ if not (0 <= int(args.compress_level) <= 9):
220
+ raise ValueError("--compress-level must be in [0, 9]")
221
+
222
+ conf = SimulationConfig.from_yaml_with_model_preset(args.config)
223
+
224
+ _configure_logging(conf, args.log_level)
225
+ logger = logging.getLogger("cyclopy")
226
+
227
+ runner = CycloPyRunner(conf)
228
+ runner.run()
229
+
230
+ out_dir = Path(conf.cyclopy_output_dir).resolve()
231
+
232
+ if args.export_netcdf:
233
+ with runner.timer.section("Netcdf export"):
234
+ export_outputs(
235
+ runner,
236
+ institution=str(args.institution),
237
+ out_dir=out_dir,
238
+ export_polar=bool(args.export_polar),
239
+ export_cart=bool(args.export_cart),
240
+ compress_level=int(args.compress_level),
241
+ )
242
+ logger.info("NetCDF export done.")
243
+ else:
244
+ logger.info("NetCDF export skipped (--no-export-netcdf).")
245
+
246
+ runner.timer.log_summary(logger, title="CycloPy runtime summary")
247
+ logger.info("CycloPy ends correctly")
248
+ return 0
249
+
250
+
251
+ def main(argv: list[str] | None = None) -> None:
252
+ parser = _build_parser()
253
+ args = parser.parse_args(argv)
254
+
255
+ # Minimal fallback logging for unexpected errors before CycloPy logging is configured
256
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s:%(name)s:%(message)s")
257
+
258
+ try:
259
+ if args.command == "run":
260
+ code = _cmd_run(args)
261
+ elif args.command == "validate":
262
+ code = _cmd_validate(args.config)
263
+ elif args.command == "info":
264
+ code = _cmd_info(short=bool(args.short))
265
+ else:
266
+ code = 2
267
+ except Exception:
268
+ logging.getLogger("cyclopy").exception("CycloPy CLI failed")
269
+ code = 1
270
+
271
+ raise SystemExit(code)
File without changes