corr-vars 2.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. corr_vars/__init__.py +174 -0
  2. corr_vars/concepts/__init__.py +100 -0
  3. corr_vars/concepts/client.py +1138 -0
  4. corr_vars/concepts/compile.py +339 -0
  5. corr_vars/concepts/files.py +280 -0
  6. corr_vars/concepts/resolver.py +650 -0
  7. corr_vars/concepts/routing.py +242 -0
  8. corr_vars/concepts/routing.toml +49 -0
  9. corr_vars/concepts/spec.py +313 -0
  10. corr_vars/concepts/standards.py +428 -0
  11. corr_vars/core/__init__.py +12 -0
  12. corr_vars/core/change_tracker.py +496 -0
  13. corr_vars/core/cohort.py +2347 -0
  14. corr_vars/core/file_manager.py +137 -0
  15. corr_vars/core/steps.py +310 -0
  16. corr_vars/core/variable/__init__.py +13 -0
  17. corr_vars/core/variable/base.py +333 -0
  18. corr_vars/core/variable/free_days.py +168 -0
  19. corr_vars/definitions/__init__.py +4 -0
  20. corr_vars/definitions/constants.py +26 -0
  21. corr_vars/definitions/exceptions.py +119 -0
  22. corr_vars/definitions/typing.py +371 -0
  23. corr_vars/plot/__init__.py +0 -0
  24. corr_vars/plot/movement.py +73 -0
  25. corr_vars/sources/__init__.py +51 -0
  26. corr_vars/sources/charite_demo/__init__.py +43 -0
  27. corr_vars/sources/charite_demo/classify/__init__.py +10 -0
  28. corr_vars/sources/charite_demo/classify/airway.py +492 -0
  29. corr_vars/sources/charite_demo/cohort.py +601 -0
  30. corr_vars/sources/charite_demo/config.py +111 -0
  31. corr_vars/sources/charite_demo/connector.py +640 -0
  32. corr_vars/sources/charite_demo/dataset.py +395 -0
  33. corr_vars/sources/charite_demo/extract.py +356 -0
  34. corr_vars/sources/charite_demo/helpers.py +1136 -0
  35. corr_vars/sources/charite_demo/mapping/__init__.py +59 -0
  36. corr_vars/sources/charite_demo/mapping/defaults.json +6 -0
  37. corr_vars/sources/charite_demo/mapping/globals.json +23 -0
  38. corr_vars/sources/charite_demo/mapping/loader.py +142 -0
  39. corr_vars/sources/charite_demo/mapping/tables.json +104 -0
  40. corr_vars/sources/charite_demo/py_env.py +203 -0
  41. corr_vars/sources/charite_demo/py_namespace.py +211 -0
  42. corr_vars/sources/cohort_loader.py +44 -0
  43. corr_vars/sources/config_loader.py +84 -0
  44. corr_vars/sources/local_datasource/__init__.py +24 -0
  45. corr_vars/sources/local_datasource/cohort.py +41 -0
  46. corr_vars/sources/local_datasource/config.py +51 -0
  47. corr_vars/sources/local_datasource/extract.py +1373 -0
  48. corr_vars/sources/local_datasource/helpers.py +98 -0
  49. corr_vars/sources/local_datasource/mapping/__init__.py +17 -0
  50. corr_vars/sources/local_datasource/mapping/loader.py +38 -0
  51. corr_vars/sources/local_datasource/mapping/variables.py +12 -0
  52. corr_vars/sources/local_datasource/mapping/vars.json +12 -0
  53. corr_vars/sources/reprodicu/__init__.py +4 -0
  54. corr_vars/sources/reprodicu/cohort.py +212 -0
  55. corr_vars/sources/reprodicu/config.py +20 -0
  56. corr_vars/sources/reprodicu/extract.py +191 -0
  57. corr_vars/sources/reprodicu/helpers.py +331 -0
  58. corr_vars/sources/reprodicu/mapping/__init__.py +7 -0
  59. corr_vars/sources/reprodicu/mapping/loader.py +21 -0
  60. corr_vars/sources/reprodicu/mapping/units.json +122 -0
  61. corr_vars/sources/reprodicu/mapping/variables.py +0 -0
  62. corr_vars/sources/var_loader.py +1051 -0
  63. corr_vars/style/matplotlibrc +1 -0
  64. corr_vars/utils/__init__.py +9 -0
  65. corr_vars/utils/base.py +84 -0
  66. corr_vars/utils/debug.py +98 -0
  67. corr_vars/utils/frames.py +1163 -0
  68. corr_vars/utils/helpers.py +522 -0
  69. corr_vars/utils/logging.py +338 -0
  70. corr_vars/utils/outcomes.py +569 -0
  71. corr_vars/utils/tableone.py +189 -0
  72. corr_vars/utils/time.py +579 -0
  73. corr_vars-2.1.0.dist-info/METADATA +289 -0
  74. corr_vars-2.1.0.dist-info/RECORD +76 -0
  75. corr_vars-2.1.0.dist-info/WHEEL +4 -0
  76. corr_vars-2.1.0.dist-info/licenses/LICENSE.md +21 -0
corr_vars/__init__.py ADDED
@@ -0,0 +1,174 @@
1
+ """corr_vars - Build clinical study cohorts from ICU and hospital data sources."""
2
+
3
+ __version__ = "2.1.0"
4
+ __author__ = "Moritz Thiele"
5
+
6
+ import contextlib
7
+ import logging
8
+ import os
9
+
10
+ from collections.abc import Callable
11
+ from typing import Final
12
+
13
+
14
+ # Logging setup
15
+ class FStringCallableLogMessage:
16
+ def __init__(
17
+ self,
18
+ message: str,
19
+ /,
20
+ *args: object | Callable[[], object],
21
+ **kwargs: object | Callable[[], object],
22
+ ) -> None:
23
+ self.message = message
24
+ self.args = args
25
+ self.kwargs = kwargs
26
+
27
+ def __str__(self) -> str:
28
+ args = (i() if callable(i) else i for i in self.args)
29
+ kwargs = {k: v() if callable(v) else v for k, v in self.kwargs.items()}
30
+
31
+ return self.message.format(*args, **kwargs)
32
+
33
+
34
+ __ = FStringCallableLogMessage
35
+
36
+
37
+ def setup_logging(logger: logging.Logger) -> None:
38
+ from .utils.logging import configure_logger_level_and_handlers, quiet_noisy_loggers
39
+
40
+ logging.captureWarnings(capture=True)
41
+ configure_logger_level_and_handlers(logger)
42
+ quiet_noisy_loggers()
43
+
44
+
45
+ logger = logging.getLogger(__name__)
46
+ setup_logging(logger)
47
+
48
+
49
+ # Temporary directory setup
50
+ TMP_DIR: Final[str] = os.environ.get("CORR_VARS_TMP_DIR", "")
51
+
52
+
53
+ def setup_tempdir() -> None:
54
+ import tempfile
55
+
56
+ tempfile.tempdir = TMP_DIR
57
+ os.environ["TMPDIR"] = TMP_DIR
58
+ # NOTE: STATA can also read from STATATMP in addition to TMPDIR
59
+ os.environ["STATATMP"] = TMP_DIR
60
+
61
+
62
+ if TMP_DIR and os.path.isdir(TMP_DIR):
63
+ setup_tempdir()
64
+
65
+ # STATA setup
66
+ STATA_DIR: Final[str] = os.environ.get("CORR_VARS_STATA_DIR", "")
67
+
68
+
69
+ def setup_stata() -> None:
70
+ import atexit
71
+
72
+ try:
73
+ import stata_setup
74
+
75
+ # This will register pystata.config.shutdown() to be called at exit,
76
+ # which can cause a fatal Python error in the C code.
77
+ stata_setup.config(STATA_DIR, "be", splash=False)
78
+ logger.info("STATA is ready to use with Pystata")
79
+ except Exception as e:
80
+ logger.info(f"Stata is not available due to an error:\n {e}")
81
+ return
82
+
83
+ # Catch atexit shutdown errors to prevent non-zero exit codes
84
+ # 1. Capture all hidden exit callbacks
85
+ class CallbackCapturer:
86
+ def __init__(self):
87
+ self.captured = []
88
+
89
+ def __eq__(self, other):
90
+ # atexit loops through its C-array and compares everything to this object
91
+ self.captured.append(other)
92
+ return False # Return False so we don't accidentally unregister anything
93
+
94
+ capturer = CallbackCapturer()
95
+
96
+ atexit.unregister(capturer)
97
+
98
+ # 2. Clear the registry completely
99
+ atexit._clear()
100
+
101
+ # 3. Re-register everything, replacing the Stata function with a safe wrapper
102
+ for item in reversed(capturer.captured):
103
+ func = item[0] if isinstance(item, tuple) else item
104
+ args = item[1] if isinstance(item, tuple) and len(item) > 1 else ()
105
+ kwargs = item[2] if isinstance(item, tuple) and len(item) > 2 else {}
106
+
107
+ # Check if this is the Stata shutdown function
108
+ if hasattr(func, "__name__") and func.__name__ == "shutdown":
109
+ # Define the safe wrapper that swallows the error
110
+ def safe_shutdown(*s_args, **s_kwargs):
111
+ # Silently catch the error so that a script exits with status 0
112
+ with contextlib.suppress(BaseException):
113
+ func(*s_args, **s_kwargs)
114
+
115
+ # Register our wrapper instead of the original
116
+ atexit.register(safe_shutdown, *args, **kwargs)
117
+
118
+ else:
119
+ # Re-register all other safe callbacks unmodified
120
+ atexit.register(func, *args, **kwargs)
121
+
122
+
123
+ if STATA_DIR and os.path.isdir(STATA_DIR):
124
+ setup_stata()
125
+
126
+ # Import commonly used classes and functions
127
+ from .core.cohort import Cohort # noqa: E402
128
+ from .sources import charite_demo, local_datasource, reprodicu # noqa: E402
129
+
130
+ __all__ = [
131
+ "Cohort",
132
+ ###########
133
+ # Logging #
134
+ ###########
135
+ "logger",
136
+ "__",
137
+ ###########
138
+ # Modules #
139
+ ###########
140
+ # Forgo dynamic import for now.
141
+ # Stub file was not dynamic anyway and was causing
142
+ # Cohort.obs / Cohort.obsm typechecking to not work
143
+ "charite_demo",
144
+ "local_datasource",
145
+ "reprodicu",
146
+ ]
147
+
148
+
149
+ # Import variables as [source].Variable
150
+ # import types
151
+ # import pkgutil
152
+ # import importlib
153
+ # from . import sources
154
+ # import sys
155
+
156
+ # package_name = __name__
157
+
158
+ # for finder, name, ispkg in pkgutil.iter_modules(sources.__path__):
159
+ # try:
160
+ # extract_module = importlib.import_module(
161
+ # f".sources.{name}.extract", package=package_name
162
+ # )
163
+ # Variable = getattr(extract_module, "Variable", None)
164
+ # if Variable is not None:
165
+ # # Create a submodule
166
+ # mod = types.ModuleType(name)
167
+ # mod.Variable = Variable
168
+ # # Attach submodule to current package namespace
169
+ # globals()[name] = mod
170
+ # __all__.append(name)
171
+ # # Register in sys.modules for import
172
+ # sys.modules[f"{package_name}.{name}"] = mod
173
+ # except (ImportError, AttributeError):
174
+ # continue
@@ -0,0 +1,100 @@
1
+ """Fetching variable definitions from the CORR Concepts API.
2
+
3
+ A variable definition has two halves: a declarative ``json`` config (what
4
+ ``vars.json`` holds locally) and an optional ``py`` transformation function
5
+ (what ``mapping/variables.py`` holds locally). The Concepts API serves both,
6
+ per concept and per source, together with the data files a definition needs and
7
+ the version metadata describing exactly what was served.
8
+
9
+ The package is organised as:
10
+
11
+ - :mod:`~corr_vars.concepts.routing` — the packaged ``routing.toml``, deciding
12
+ per source whether definitions come from an endpoint or stay local.
13
+ - :mod:`~corr_vars.concepts.spec` — parsing ``[taxonomy/]var_name[::version]``.
14
+ - :mod:`~corr_vars.concepts.client` — the HTTP client and response types.
15
+ - :mod:`~corr_vars.concepts.files` — the content-addressed file cache.
16
+ - :mod:`~corr_vars.concepts.compile` — executing served ``py`` snippets.
17
+ - :mod:`~corr_vars.concepts.resolver` — the per-cohort façade over all of it.
18
+
19
+ Warning:
20
+ Sources routed to an endpoint **never** fall back to the bundled
21
+ ``vars.json``. A cohort assembled from a stale local definition while
22
+ recording a remote version number would misdescribe its own data, which is
23
+ the problem the API exists to solve. Every failure is therefore fatal.
24
+
25
+ Warning:
26
+ ``reprodicu`` is routed to the API but its definitions have not been
27
+ imported there yet, so every reprodicu concept resolves to nothing until
28
+ that import lands. This is a deliberate staging decision, not a bug.
29
+ """
30
+
31
+ from corr_vars.concepts.client import (
32
+ Concept,
33
+ ConceptFile,
34
+ ConceptsApiClient,
35
+ SourceConcept,
36
+ VersionInfo,
37
+ VersionWarning,
38
+ )
39
+ from corr_vars.concepts.compile import (
40
+ CompiledVariableFunction,
41
+ compile_snippet,
42
+ get_py_compiler,
43
+ )
44
+ from corr_vars.concepts.files import cache_root, materialise_files
45
+ from corr_vars.concepts.resolver import (
46
+ ConceptResolver,
47
+ FetchedConfig,
48
+ ResolvedConcept,
49
+ )
50
+ from corr_vars.concepts.routing import (
51
+ ApiRoute,
52
+ ConceptRouting,
53
+ Endpoint,
54
+ LocalRoute,
55
+ Route,
56
+ load_routing,
57
+ )
58
+ from corr_vars.concepts.spec import (
59
+ LATEST_SELECTOR,
60
+ VariableSpec,
61
+ VersionSelector,
62
+ parse_variable_spec,
63
+ parse_version_selector,
64
+ resolve_default_version,
65
+ )
66
+
67
+ __all__ = [
68
+ # Routing
69
+ "ApiRoute",
70
+ "ConceptRouting",
71
+ "Endpoint",
72
+ "LocalRoute",
73
+ "Route",
74
+ "load_routing",
75
+ # Spec
76
+ "LATEST_SELECTOR",
77
+ "VariableSpec",
78
+ "VersionSelector",
79
+ "parse_variable_spec",
80
+ "parse_version_selector",
81
+ "resolve_default_version",
82
+ # Client
83
+ "Concept",
84
+ "ConceptFile",
85
+ "ConceptsApiClient",
86
+ "SourceConcept",
87
+ "VersionInfo",
88
+ "VersionWarning",
89
+ # Files
90
+ "cache_root",
91
+ "materialise_files",
92
+ # Compilation
93
+ "CompiledVariableFunction",
94
+ "compile_snippet",
95
+ "get_py_compiler",
96
+ # Resolver
97
+ "ConceptResolver",
98
+ "FetchedConfig",
99
+ "ResolvedConcept",
100
+ ]