pyfsda 0.4.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.
pyfsda/__init__.py ADDED
@@ -0,0 +1,162 @@
1
+ """pyfsda — call FSDA (MATLAB robust-statistics toolbox) routines from Python.
2
+
3
+ Two ways to call, over the same generic engine and numpy <-> MATLAB marshalling.
4
+
5
+ Functional (MATLAB-like) — call any FSDA routine as ``pyfsda.<name>(...)``; the shared
6
+ MATLAB session starts on first use and is reused::
7
+
8
+ import pyfsda
9
+
10
+ d = pyfsda.mahalFS(Y, MU, SIGMA) # numeric array -> ndarray
11
+ out = pyfsda.Score(y, X, la=la, intercept=True) # struct -> dict
12
+ RAW, REW = pyfsda.mcd(Y, nargout=2) # two outputs -> tuple
13
+ pyfsda.stop() # optional; also runs at exit
14
+
15
+ Explicit session (advanced) — manage the engine yourself::
16
+
17
+ from pyfsda import FsdaEngine
18
+ eng = FsdaEngine.start("mahalFS")
19
+ d = eng.call("mahalFS", Y, MU, SIGMA)
20
+ eng.stop()
21
+
22
+ Requires MATLAB with the FSDA Add-On and a ``matlabengine`` release matching that
23
+ MATLAB (see the README).
24
+
25
+ On the first call, pyfsda prints (once, best-effort) the latest FSDA release available
26
+ on GitHub, so you can check your install is current. Silence it with
27
+ ``pyfsda.start(check_version=False)`` before the first call.
28
+
29
+ Optional pandas view (``pip install pyfsda[pandas]``): pass ``frames=True`` to receive
30
+ table/timetable outputs as a ``pandas.DataFrame`` (``out = pyfsda.univariatems(y, X,
31
+ frames=True)``), and pass a ``pandas.DataFrame`` argument to send a MATLAB ``table`` in.
32
+ The default return is still the neutral dict -- the cross-language contract is unchanged.
33
+ """
34
+ from __future__ import annotations
35
+
36
+ import atexit
37
+ import sys
38
+
39
+ from .engine import FsdaEngine, from_matlab, to_matlab
40
+ from .frames import is_table_dict, to_dataframe
41
+
42
+ __version__ = "0.4.0"
43
+
44
+ __all__ = [
45
+ "FsdaEngine", "to_matlab", "from_matlab",
46
+ "to_dataframe", "is_table_dict",
47
+ "start", "stop", "engine", "__version__",
48
+ ]
49
+
50
+ # --- shared lazily-started engine (backs the functional pyfsda.<name>(...) surface) ----
51
+ _ENGINE: FsdaEngine | None = None
52
+ _WRAPPERS: dict = {}
53
+ _VALIDATED: set = set() # FSDA names confirmed on-path for the current engine
54
+ _CHECK_VERSION: bool = True # set by start(); gates the first-call GitHub version notice
55
+ _LATEST_CHECKED: bool = False # run-once latch for _notify_latest_fsda
56
+
57
+ _FSDA_RELEASES_API = "https://api.github.com/repos/UniprJRC/FSDA/releases/latest"
58
+
59
+ # A few common FSDA routines advertised by __dir__ for REPL discoverability. The
60
+ # __getattr__ mechanism accepts ANY FSDA function name, not just these.
61
+ _COMMON = (
62
+ "mahalFS", "Score", "FSR", "FSRaddt", "FSM", "mcd", "pcaFS",
63
+ "corrNominal", "tabulateFS", "TBwei", "bc", "combsFS",
64
+ )
65
+
66
+
67
+ def start(routine: str | None = None, fsda_root: str | None = None,
68
+ check_version: bool = True) -> FsdaEngine:
69
+ """Start (once) and return the shared FSDA engine used by ``pyfsda.<name>(...)``.
70
+
71
+ Idempotent: returns the already-running engine on later calls. Call this before the
72
+ first routine only if you need to set ``fsda_root`` or disable ``check_version``.
73
+ """
74
+ global _ENGINE, _CHECK_VERSION
75
+ _CHECK_VERSION = check_version # also gates the first-call GitHub version notice
76
+ if _ENGINE is None:
77
+ _ENGINE = FsdaEngine.start(routine=routine, fsda_root=fsda_root,
78
+ check_version=check_version)
79
+ return _ENGINE
80
+
81
+
82
+ def engine() -> FsdaEngine:
83
+ """Return the shared engine, starting it with defaults if needed."""
84
+ return start()
85
+
86
+
87
+ def stop() -> None:
88
+ """Shut the shared engine down (safe to call when it was never started)."""
89
+ global _ENGINE, _LATEST_CHECKED
90
+ if _ENGINE is not None:
91
+ try:
92
+ _ENGINE.stop()
93
+ finally:
94
+ _ENGINE = None
95
+ _VALIDATED.clear()
96
+ _LATEST_CHECKED = False # a fresh session re-checks the latest release
97
+
98
+
99
+ atexit.register(stop)
100
+
101
+
102
+ def _notify_latest_fsda() -> None:
103
+ """Once per session, print the latest FSDA release available on GitHub (stderr).
104
+
105
+ Purely informational and best-effort: it reports the latest `tag_name` from the FSDA
106
+ GitHub releases API using only the standard library, and stays silent on any failure
107
+ (offline, rate-limited, blocked). It does NOT compare against the installed version.
108
+ Runs on the first `pyfsda.<name>(...)` call and is gated by `check_version` (disable
109
+ with `pyfsda.start(check_version=False)`). Separate from `engine.py`'s `tuna` check.
110
+ """
111
+ global _LATEST_CHECKED
112
+ if _LATEST_CHECKED or not _CHECK_VERSION:
113
+ return
114
+ _LATEST_CHECKED = True # latch up front: never retry on failure
115
+ try:
116
+ import json
117
+ import urllib.request
118
+
119
+ with urllib.request.urlopen(_FSDA_RELEASES_API, timeout=4.0) as resp:
120
+ tag = json.load(resp).get("tag_name")
121
+ if tag:
122
+ sys.stderr.write(
123
+ f"pyfsda: latest FSDA release on GitHub is {tag} "
124
+ f"(https://github.com/UniprJRC/FSDA/releases/tag/{tag}). "
125
+ f"Ensure your installed FSDA is current.\n"
126
+ )
127
+ sys.stderr.flush()
128
+ except Exception:
129
+ pass # never let a courtesy check break a call
130
+
131
+
132
+ def _make_wrapper(name: str):
133
+ """Build (and cache) a callable that runs FSDA `name` on the shared engine."""
134
+ def _fsda_call(*args, **kwargs):
135
+ eng = engine()
136
+ _notify_latest_fsda() # once: latest FSDA release on GitHub
137
+ if name not in _VALIDATED: # verify once per name (typo guard)
138
+ if not eng.which(name):
139
+ raise AttributeError(
140
+ f"FSDA function {name!r} not found on the MATLAB path."
141
+ )
142
+ _VALIDATED.add(name)
143
+ return eng.call(name, *args, **kwargs)
144
+ _fsda_call.__name__ = name
145
+ _fsda_call.__qualname__ = name
146
+ _fsda_call.__doc__ = (f"Call FSDA `{name}` on the shared pyfsda engine: "
147
+ f"pyfsda.{name}(*args, **name_value_options).")
148
+ return _fsda_call
149
+
150
+
151
+ def __getattr__(name: str): # PEP 562 module-level hook
152
+ """Expose any FSDA routine as ``pyfsda.<name>`` (e.g. ``pyfsda.Score``)."""
153
+ if name.startswith("_"): # don't hijack dunders/privates
154
+ raise AttributeError(f"module 'pyfsda' has no attribute {name!r}")
155
+ wrapper = _WRAPPERS.get(name)
156
+ if wrapper is None:
157
+ wrapper = _WRAPPERS[name] = _make_wrapper(name)
158
+ return wrapper
159
+
160
+
161
+ def __dir__() -> list:
162
+ return sorted(set(__all__) | set(_COMMON))
pyfsda/engine.py ADDED
@@ -0,0 +1,514 @@
1
+ """pyfsda — a generic Python bridge for calling FSDA routines via the MATLAB Engine.
2
+
3
+ Python -> matlab.engine -> MATLAB + FSDA
4
+
5
+ Every per-routine `code/<target>/bridge.py` repeats the same engine/plumbing:
6
+ start the engine, check the routine is on the path, marshal numpy <-> matlab.double,
7
+ route MATLAB messages, handle figures, shut down. This module factors that plumbing
8
+ into ONE place so a new FSDA routine usually needs no wrapper at all -- you call
9
+
10
+ eng = FsdaEngine.start("mahalFS")
11
+ d = eng.call("mahalFS", Y, MU, SIGMA) # numeric array -> ndarray
12
+ out = eng.call("Score", y, X, la=la, intercept=True) # struct -> dict
13
+
14
+ and the generic converters handle the crossing. It covers these MATLAB return
15
+ shapes (see spec 016):
16
+
17
+ numeric array matlab.double -> ndarray
18
+ struct dict -> dict (recursed)
19
+ nested struct of arrays dict of dicts -> dict of dicts of ndarrays
20
+ char/string scalar char -> str
21
+ table / timetable (cannot return) -> dict {VariableNames, RowNames
22
+ / RowTimes, data} (decomposed
23
+ MATLAB-side; see _table_to_dict)
24
+ 2-D cell (M x N) (cannot return) -> nested list (see _marshal_cell2d)
25
+ struct holding any of (cannot return) -> dict, decomposed field-by-field
26
+ the above (see _marshal_struct)
27
+
28
+ A table/timetable, a 2-D cell, or a struct *containing* one cannot be returned to Python
29
+ by the engine at all, so `call` runs through the MATLAB workspace and decomposes them
30
+ there (the approach `code/getYahoo/bridge.py` uses for its timetable). The struct/cell
31
+ field-by-field path is a *fallback*: the fast whole-value read is tried first, so ordinary
32
+ structs/numerics are untouched. STILL OUT OF SCOPE: struct-ARRAYS and datetime/duration
33
+ scalars (getYahoo keeps its own bespoke bridge for those).
34
+
35
+ Marshalling rules (CONSTITUTION sec 4):
36
+ * Output is returned in MATLAB's natural shape -- NO silent reshape. A column
37
+ vector stays (n, 1); callers squeeze if they want (n,).
38
+ * Input has ONE documented convention: a 1-D ndarray/list crosses as a MATLAB
39
+ *row* (1 x n). Pass an (n, 1) array when a routine wants a column (e.g. y).
40
+ * NaN / Inf are preserved; MATLAB indices stay 1-based -- interpretation is the
41
+ caller's.
42
+
43
+ Dependencies: numpy + matlab + matlab.engine + stdlib only.
44
+
45
+ See the pyfsda README for the full marshalling rules and usage.
46
+ """
47
+ from __future__ import annotations
48
+
49
+ import io
50
+ import re
51
+ import sys
52
+
53
+ import numpy as np
54
+ import matlab
55
+ import matlab.engine
56
+
57
+ from .frames import apply_frames, is_dataframe
58
+
59
+ # call() reserves these keyword names for its own control; every OTHER keyword is
60
+ # forwarded to MATLAB as a name/value pair. Notably `msg` is NOT reserved -- it
61
+ # passes straight through to FSDA (FSR/FSRaddt/getYahoo each have their own `msg`
62
+ # option). The bridge's stdout/stderr tee is `echo_output`, deliberately named so
63
+ # it cannot collide with an FSDA option. `frames` is the opt-in pandas view (see
64
+ # call()). The rare case where an FSDA option's name does collide with one of these
65
+ # reserved words is handled via the `options` dict:
66
+ # eng.call("FSR", y, X, options={"nargout": ...})
67
+ _RESERVED_CALL_KWARGS = ("nargout", "echo_output", "options", "frames")
68
+
69
+ # call()/eval() execute through the MATLAB workspace (so table/timetable outputs --
70
+ # which the engine cannot return directly -- can be decomposed MATLAB-side). The
71
+ # function name and option names are interpolated into an eval command, so they are
72
+ # validated against this allow-list first (an injection guard, like getYahoo).
73
+ _IDENT_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$")
74
+
75
+
76
+ def _cellstr_list(raw) -> list:
77
+ """MATLAB cellstr -> Python list[str]. The engine returns a 1-element cell as a
78
+ bare str and a multi-element cell as a list; an empty cell as an empty value.
79
+ Collapse all of these to a list[str]."""
80
+ if raw is None:
81
+ return []
82
+ if isinstance(raw, str):
83
+ return [raw]
84
+ try:
85
+ return [str(x) for x in raw]
86
+ except TypeError:
87
+ return [str(raw)]
88
+
89
+
90
+ def to_matlab(x):
91
+ """Marshal a Python value to a MATLAB-engine input type.
92
+
93
+ ndarray : 0-D -> float; 1-D -> MATLAB row (1 x n); 2-D -> matlab.double as-is.
94
+ (1-D -> row is a *convention*; pass an (n, 1) array for a column.)
95
+ bool -> bool (MATLAB logical) -- checked before int (bool is an int subclass).
96
+ int/float -> float. str -> str (char). list/tuple of numbers -> row matlab.double.
97
+ Anything else is passed through untouched (already a matlab.* type, etc.).
98
+ """
99
+ if is_dataframe(x):
100
+ raise TypeError(
101
+ "pandas.DataFrame inputs are marshalled to a MATLAB table by call() -- "
102
+ "pass a DataFrame as a positional/option argument to call(), not to to_matlab().")
103
+ if isinstance(x, np.ndarray):
104
+ a = np.asarray(x, dtype=float)
105
+ if a.ndim == 0:
106
+ return float(a)
107
+ if a.ndim == 1:
108
+ a = a.reshape(1, -1) # documented: 1-D -> MATLAB row
109
+ return matlab.double(a.tolist())
110
+ if isinstance(x, bool):
111
+ return x
112
+ if isinstance(x, (int, float)):
113
+ return float(x)
114
+ if isinstance(x, str):
115
+ return x
116
+ if isinstance(x, (list, tuple)):
117
+ return matlab.double([float(v) for v in x])
118
+ return x
119
+
120
+
121
+ def from_matlab(x):
122
+ """Marshal a MATLAB-engine return value to plain Python, recursively.
123
+
124
+ None -> None (e.g. an nargout=0 call).
125
+ dict -> {k: from_matlab(v)} (struct / nested struct).
126
+ str/bool/int/float -> passed through (char scalar, logical scalar).
127
+ list/tuple -> [from_matlab(v) ...] (cell array / nargout > 1).
128
+ matlab.* -> np.asarray(x) (numeric/logical array; shape & NaN/Inf preserved,
129
+ NO reshape).
130
+ """
131
+ if x is None:
132
+ return None
133
+ if isinstance(x, dict):
134
+ return {k: from_matlab(v) for k, v in x.items()}
135
+ if isinstance(x, str):
136
+ return x
137
+ if isinstance(x, (bool, int, float)):
138
+ return x
139
+ if isinstance(x, (list, tuple)):
140
+ return [from_matlab(v) for v in x]
141
+ # matlab.double / matlab.logical / matlab.int* and anything array-like.
142
+ try:
143
+ return np.asarray(x)
144
+ except Exception:
145
+ return x
146
+
147
+
148
+ class FsdaEngine:
149
+ """A reusable MATLAB engine session with a generic, routine-agnostic `call`."""
150
+
151
+ def __init__(self, eng):
152
+ self.eng = eng
153
+
154
+ # --- lifecycle -----------------------------------------------------------
155
+ @classmethod
156
+ def start(cls, routine: str | None = None, fsda_root: str | None = None,
157
+ check_version: bool = True) -> "FsdaEngine":
158
+ """Start a MATLAB engine; optionally verify one FSDA `routine` resolves.
159
+
160
+ FSDA is normally a MATLAB Add-On (already on the path), so `fsda_root` can
161
+ be None; pass the FSDA install dir only as a fallback (added with
162
+ addpath(genpath(...))). When `routine` is given and cannot be found, the
163
+ engine is closed and RuntimeError is raised.
164
+
165
+ When `check_version` is True (default), a one-off, non-fatal FSDA
166
+ up-to-date check runs once the session is up (see `_check_fsda_version`):
167
+ it is silent when FSDA is current and prints a notice otherwise. Pass
168
+ `check_version=False` for a network-free / hermetic session.
169
+ """
170
+ eng = matlab.engine.start_matlab()
171
+ if fsda_root:
172
+ eng.addpath(eng.genpath(fsda_root), nargout=0)
173
+ if routine and not eng.which(routine):
174
+ eng.quit()
175
+ raise RuntimeError(
176
+ f"FSDA `{routine}` not found on the MATLAB path. Install the FSDA "
177
+ f"Add-On in MATLAB, or pass fsda_root=<FSDA install dir>."
178
+ )
179
+ self = cls(eng)
180
+ if check_version:
181
+ self._check_fsda_version()
182
+ return self
183
+
184
+ def stop(self) -> None:
185
+ """Shut the engine session down (startup is slow -- callers control this)."""
186
+ self.eng.quit()
187
+
188
+ def _check_fsda_version(self) -> None:
189
+ """Notify, once at session start, if the installed FSDA is not the latest.
190
+
191
+ Uses FSDA's own `tuna` utility in its quiet, no-GUI mode
192
+ (`tuna('FSDA','uniprJRC','FSDA','gui',false)`): tuna compares the installed
193
+ version (from the Add-On manager) against the latest GitHub release and
194
+ writes a message to the MATLAB Command Window ONLY when an update is
195
+ available -- so this prints nothing when FSDA is current. No modal dialog
196
+ is shown; a failure to reach GitHub is non-fatal MATLAB-side.
197
+
198
+ `tuna` is a recent FSDA utility, so `exist('tuna','file')==0` means FSDA is
199
+ either not installed or too old to self-check -- reported as such. The whole
200
+ check is best-effort: any Python-side failure is swallowed so it can never
201
+ break a session (disable it entirely with `start(check_version=False)`).
202
+ """
203
+ try:
204
+ has_tuna = int(self.eng.eval("double(exist('tuna','file')>0)", nargout=1))
205
+ except Exception:
206
+ return
207
+ if not has_tuna:
208
+ sys.stderr.write("FSDA not found on the MATLAB path, or too old to include "
209
+ "'tuna' -- FSDA version check skipped.\n")
210
+ sys.stderr.flush()
211
+ return
212
+ out, err = io.StringIO(), io.StringIO()
213
+ try:
214
+ self.eng.eval("tuna('FSDA','uniprJRC','FSDA','gui',false)",
215
+ nargout=0, stdout=out, stderr=err)
216
+ except Exception:
217
+ return # tuna raised -> stay silent
218
+ msg = out.getvalue() + err.getvalue()
219
+ if msg.strip(): # current FSDA -> tuna is silent
220
+ sys.stderr.write(msg)
221
+ sys.stderr.flush()
222
+
223
+ # --- the generic call ----------------------------------------------------
224
+ def call(self, name: str, *args, nargout: int = 1, echo_output: bool = False,
225
+ options: dict | None = None, frames: bool = False, **kwargs):
226
+ """Call FSDA function `name` generically and return plain Python.
227
+
228
+ Positional `args` are marshalled with `to_matlab` and passed in order.
229
+ Keyword args (and any `options` dict) become MATLAB name/value pairs, in
230
+ the given order -- e.g. ``call("Score", y, X, la=la, intercept=True)``
231
+ sends ``Score(y, X, 'la', la, 'intercept', true)``. FSDA's own ``msg``
232
+ option is just such a kwarg -- ``call("FSR", y, X, msg=0)`` forwards it to
233
+ MATLAB (it is NOT consumed by the bridge).
234
+
235
+ nargout : number of outputs to request (default 1).
236
+ echo_output : when True, route MATLAB's stdout/stderr to this terminal (the
237
+ engine needs io.StringIO buffers, so capture then echo). This
238
+ is the bridge's OWN tee, named so it cannot clash with an FSDA
239
+ option; it does not change what FSDA prints, only whether an
240
+ embedded host (reticulate / PythonCall) surfaces it.
241
+ frames : when True, table/timetable outputs (the dict returned by
242
+ `_table_to_dict`) are returned as a `pandas.DataFrame` instead
243
+ -- an opt-in Python-only view; the dict is still the default and
244
+ the cross-language contract (needs `pip install pyfsda[pandas]`).
245
+
246
+ A `pandas.DataFrame` passed as a positional/option argument is marshalled to a
247
+ MATLAB `table` (see `_df_to_table_var`), independent of the `frames` flag.
248
+
249
+ Execution runs through the MATLAB workspace so outputs the engine cannot
250
+ return directly -- a **table / timetable** -- can be decomposed MATLAB-side
251
+ into a Python dict (see `_table_to_dict`); numeric/struct/char outputs cross
252
+ exactly as before. A returned table -> dict has keys ``VariableNames``,
253
+ ``RowNames`` (or ISO ``RowTimes`` for a timetable), and ``data`` (column ->
254
+ ndarray / list[str]).
255
+ """
256
+ if not _IDENT_RE.match(name):
257
+ raise ValueError(f"unsafe / malformed function name: {name!r}")
258
+ pairs = dict(options or {})
259
+ pairs.update(kwargs)
260
+ for key in pairs:
261
+ if not _IDENT_RE.match(str(key)):
262
+ raise ValueError(f"unsafe / malformed option name: {key!r}")
263
+
264
+ ws = self.eng.workspace
265
+ in_names, opt_tokens, temp = [], [], []
266
+ for i, a in enumerate(args):
267
+ vn = f"fe_in{i}"
268
+ if is_dataframe(a):
269
+ self._df_to_table_var(a, vn) # DataFrame -> MATLAB table
270
+ else:
271
+ ws[vn] = to_matlab(a)
272
+ in_names.append(vn)
273
+ temp.append(vn)
274
+ for key, value in pairs.items():
275
+ vn = f"fe_opt_{key}"
276
+ if is_dataframe(value):
277
+ self._df_to_table_var(value, vn) # DataFrame option value -> MATLAB table
278
+ else:
279
+ ws[vn] = to_matlab(value)
280
+ opt_tokens.append(f"'{key}',{vn}") # 'name', tempvar
281
+ temp.append(vn)
282
+
283
+ out_names = [f"fe_out{j}" for j in range(nargout)]
284
+ temp.extend(out_names)
285
+ rhs = ",".join(in_names + opt_tokens)
286
+ if nargout == 0:
287
+ cmd = f"{name}({rhs});"
288
+ elif nargout == 1:
289
+ cmd = f"{out_names[0]} = {name}({rhs});"
290
+ else:
291
+ cmd = f"[{','.join(out_names)}] = {name}({rhs});"
292
+
293
+ try:
294
+ self._eval_cmd(cmd, echo_output)
295
+ if nargout == 0:
296
+ return None
297
+ results = [self._marshal_var(vn) for vn in out_names]
298
+ finally:
299
+ self._clear(temp)
300
+ if frames: # opt-in: table-dicts -> DataFrames
301
+ results = [apply_frames(r) for r in results]
302
+ return results[0] if nargout == 1 else tuple(results)
303
+
304
+ def eval(self, expr: str, nargout: int = 1):
305
+ """Evaluate a MATLAB expression and marshal the result back generically.
306
+
307
+ Handy for building/reading values the function `call` surface does not cover
308
+ (e.g. a constructed nested struct, or a table). nargout=0 returns None. For
309
+ nargout==1 the value is bound to a workspace temp first, so a table/timetable
310
+ expression decomposes through the same path as `call`.
311
+ """
312
+ if nargout == 0:
313
+ self.eng.eval(expr, nargout=0)
314
+ return None
315
+ if nargout == 1:
316
+ vn = "fe_eval0"
317
+ try:
318
+ self.eng.eval(f"{vn} = ({expr});", nargout=0)
319
+ return self._marshal_var(vn)
320
+ finally:
321
+ self._clear([vn])
322
+ return from_matlab(self.eng.eval(expr, nargout=nargout))
323
+
324
+ # --- workspace execution helpers -----------------------------------------
325
+ def _eval_cmd(self, cmd: str, echo_output: bool = False) -> None:
326
+ """Run a MATLAB statement, optionally tee-ing its stdout/stderr (see call())."""
327
+ if echo_output:
328
+ out_buf, err_buf = io.StringIO(), io.StringIO()
329
+ self.eng.eval(cmd, nargout=0, stdout=out_buf, stderr=err_buf)
330
+ if out_buf.getvalue():
331
+ sys.stdout.write(out_buf.getvalue())
332
+ sys.stdout.flush() # surface under reticulate / PythonCall too
333
+ if err_buf.getvalue():
334
+ sys.stderr.write(err_buf.getvalue())
335
+ sys.stderr.flush()
336
+ else:
337
+ self.eng.eval(cmd, nargout=0)
338
+
339
+ def _clear(self, names: list) -> None:
340
+ """Remove the bridge's `fe_*` temp variables from the MATLAB workspace."""
341
+ if names:
342
+ self.eng.eval("clear " + " ".join(names), nargout=0)
343
+
344
+ def _marshal_var(self, vn: str):
345
+ """Marshal one workspace variable. table/timetable -> dict (decomposed
346
+ MATLAB-side); a 2-D cell -> nested list (the engine only returns 1-D cells);
347
+ otherwise read it out and pass through `from_matlab`. If that direct read
348
+ fails (e.g. a struct containing a field the engine cannot convert), fall back
349
+ to decomposing the struct/cell field-by-field MATLAB-side."""
350
+ if int(self.eng.eval(f"double(istable({vn})||istimetable({vn}))", nargout=1)):
351
+ return self._table_to_dict(vn)
352
+ if int(self.eng.eval(
353
+ f"double(iscell({vn}) && ~isrow({vn}) && ~iscolumn({vn}))", nargout=1)):
354
+ return self._marshal_cell2d(vn) # M x N cell: engine can't return it
355
+ try:
356
+ return from_matlab(self.eng.workspace[vn])
357
+ except Exception:
358
+ if int(self.eng.eval(f"double(isstruct({vn}))", nargout=1)):
359
+ return self._marshal_struct(vn)
360
+ if int(self.eng.eval(f"double(iscell({vn}))", nargout=1)):
361
+ return self._marshal_cell2d(vn)
362
+ raise
363
+
364
+ def _marshal_struct(self, vn: str) -> dict:
365
+ """Decompose a struct field-by-field MATLAB-side (used when the engine cannot
366
+ eagerly convert the whole struct -- e.g. it holds a 2-D cell or table field).
367
+ Each field is routed back through `_marshal_var`, so tables/2-D cells/nested
368
+ structs are handled recursively. The function ran once already; this only
369
+ re-reads its result carefully."""
370
+ fields = _cellstr_list(self.eng.eval(f"fieldnames({vn})", nargout=1))
371
+ out = {}
372
+ for f in fields:
373
+ if not _IDENT_RE.match(f): # fieldnames are valid idents; guard anyway
374
+ raise ValueError(f"unsafe struct field name: {f!r}")
375
+ self.eng.eval(f"fe_fld = {vn}.{f};", nargout=0)
376
+ try:
377
+ out[f] = self._marshal_var("fe_fld")
378
+ finally:
379
+ self._clear(["fe_fld"])
380
+ return out
381
+
382
+ def _marshal_cell2d(self, vn: str) -> list:
383
+ """Decompose an M x N MATLAB cell into a nested Python list (the engine only
384
+ returns 1-by-N / M-by-1 cells). Each element is read by index and routed
385
+ through `_marshal_var`, so cells of matrices / structs / tables all cross."""
386
+ m = int(self.eng.eval(f"double(size({vn},1))", nargout=1))
387
+ n = int(self.eng.eval(f"double(size({vn},2))", nargout=1))
388
+ rows = []
389
+ for i in range(1, m + 1):
390
+ row = []
391
+ for j in range(1, n + 1):
392
+ self.eng.eval(f"fe_cel = {vn}{{{i},{j}}};", nargout=0)
393
+ try:
394
+ row.append(self._marshal_var("fe_cel"))
395
+ finally:
396
+ self._clear(["fe_cel"])
397
+ rows.append(row)
398
+ return rows
399
+
400
+ def _table_to_dict(self, vn: str) -> dict:
401
+ """Decompose a MATLAB table/timetable workspace var into a Python dict.
402
+
403
+ Columns are read by **index** (`T{:,j}`), never by interpolating their names,
404
+ so a column name can be anything without risk. Numeric/logical columns become
405
+ ndarrays (single columns flattened to 1-D); other columns (categorical /
406
+ string / cellstr) become list[str].
407
+ """
408
+ is_tt = int(self.eng.eval(f"double(istimetable({vn}))", nargout=1))
409
+ varnames = _cellstr_list(self.eng.eval(f"{vn}.Properties.VariableNames", nargout=1))
410
+ height = int(self.eng.eval(f"double(height({vn}))", nargout=1))
411
+
412
+ data = {}
413
+ for j, col in enumerate(varnames, start=1):
414
+ is_num = int(self.eng.eval(
415
+ f"double(isnumeric({vn}{{:,{j}}})||islogical({vn}{{:,{j}}}))", nargout=1))
416
+ if is_num:
417
+ arr = np.asarray(self.eng.eval(f"{vn}{{:,{j}}}", nargout=1), dtype=float)
418
+ data[col] = arr.reshape(-1) if (arr.ndim == 1 or arr.shape[1] == 1) else arr
419
+ else:
420
+ data[col] = _cellstr_list(
421
+ self.eng.eval(f"cellstr(string({vn}{{:,{j}}}))", nargout=1))
422
+
423
+ result = {"VariableNames": varnames, "data": data, "height": height}
424
+ if is_tt:
425
+ result["RowTimes"] = _cellstr_list(
426
+ self.eng.eval(f"cellstr(string({vn}.Properties.RowTimes))", nargout=1))
427
+ else:
428
+ result["RowNames"] = _cellstr_list(
429
+ self.eng.eval(f"{vn}.Properties.RowNames", nargout=1))
430
+ return result
431
+
432
+ def _cellstr_to_var(self, values, vn: str) -> None:
433
+ """Build a MATLAB cellstr in workspace var `vn` from a Python list[str].
434
+
435
+ Each element crosses as a char scalar (a supported engine input); the cell is then
436
+ assembled MATLAB-side. Only the bridge's own temp names (`{vn}_e0`, ...) are ever
437
+ interpolated -- never the string CONTENTS -- so column/row labels are injection-safe.
438
+ """
439
+ ws = self.eng.workspace
440
+ elem_vars = []
441
+ try:
442
+ for k, v in enumerate(values):
443
+ ev = f"{vn}_e{k}"
444
+ ws[ev] = str(v)
445
+ elem_vars.append(ev)
446
+ self.eng.eval(f"{vn} = {{{','.join(elem_vars)}}};", nargout=0)
447
+ finally:
448
+ self._clear(elem_vars)
449
+
450
+ def _df_to_table_var(self, df, vn: str) -> None:
451
+ """Assemble a MATLAB `table` in workspace variable `vn` from a pandas DataFrame.
452
+
453
+ The inverse of `_table_to_dict`. Column names cross as a MATLAB cell (`fe_varnames`,
454
+ built by `_cellstr_to_var`) and feed `array2table(...,'VariableNames',fe_varnames)`
455
+ -- never string-interpolated. Explicit `VariableNames` are used verbatim (modern
456
+ MATLAB tables allow arbitrary variable-name text). A non-default row index becomes
457
+ the table's `RowNames`.
458
+
459
+ v1 supports **numeric / logical** columns only (the common FSDA design-matrix case);
460
+ string / categorical / datetime columns and a MultiIndex raise NotImplementedError,
461
+ consistent with the engine's existing struct-array / datetime limits.
462
+ """
463
+ raw = np.asarray(df.to_numpy())
464
+ if raw.dtype != bool and not np.issubdtype(raw.dtype, np.number):
465
+ raise NotImplementedError(
466
+ "pyfsda: DataFrame -> MATLAB table supports numeric/logical columns only in "
467
+ "v1; string / categorical / datetime columns are not yet marshalled.")
468
+ block = np.asarray(raw, dtype=float)
469
+ if block.ndim != 2:
470
+ block = block.reshape(len(df), -1)
471
+
472
+ ws = self.eng.workspace
473
+ ws["fe_block"] = matlab.double(block.tolist())
474
+ temp = ["fe_block", "fe_varnames"]
475
+ try:
476
+ self._cellstr_to_var([str(c) for c in df.columns], "fe_varnames")
477
+ self.eng.eval(
478
+ f"{vn} = array2table(fe_block,'VariableNames',fe_varnames);", nargout=0)
479
+ index = list(df.index)
480
+ if index != list(range(len(df))): # non-default index -> RowNames
481
+ self._cellstr_to_var([str(i) for i in index], "fe_rownames")
482
+ temp.append("fe_rownames")
483
+ self.eng.eval(f"{vn}.Properties.RowNames = fe_rownames;", nargout=0)
484
+ finally:
485
+ self._clear(temp)
486
+
487
+ # --- diagnostics ---------------------------------------------------------
488
+ def which(self, name: str) -> str:
489
+ """Resolved path of FSDA function `name` (empty str if not found)."""
490
+ return str(self.eng.which(name))
491
+
492
+ def version(self) -> str:
493
+ """MATLAB version string."""
494
+ return str(self.eng.version())
495
+
496
+ # --- figures (parity with the per-routine bridges) -----------------------
497
+ def render_figures(self) -> None:
498
+ """Force any open MATLAB figures to paint."""
499
+ self.eng.eval("drawnow", nargout=0)
500
+
501
+ def wait_for_figures(self) -> None:
502
+ """Block until the user closes all open MATLAB figures.
503
+
504
+ Driven entirely MATLAB-side (uiwait), so it is immune to the terminal-stdin
505
+ interference seen when the engine is embedded via reticulate / PythonCall.
506
+ Returns immediately if no figures are open.
507
+ """
508
+ self.eng.eval(
509
+ "drawnow; "
510
+ "fh = findall(groot, 'Type', 'figure'); "
511
+ "while ~isempty(fh); uiwait(fh(1)); "
512
+ "fh = findall(groot, 'Type', 'figure'); end",
513
+ nargout=0,
514
+ )
pyfsda/frames.py ADDED
@@ -0,0 +1,91 @@
1
+ """Optional pandas view over FSDA table/timetable results -- Python codepath only.
2
+
3
+ The generic engine returns a MATLAB ``table``/``timetable`` as a neutral dict
4
+ ``{VariableNames, RowNames/RowTimes, data, height}`` (see ``engine._table_to_dict``). That
5
+ dict is the cross-language interchange format (R / Julia rely on it) and stays the default.
6
+ This module layers an *opt-in* pandas view on the Python side:
7
+
8
+ * ``to_dataframe(table_dict)`` -- build a ``pandas.DataFrame`` from the dict.
9
+ * ``apply_frames(obj)`` -- recurse through a result, converting every table-dict.
10
+ * ``is_table_dict(obj)`` -- recognise the dict shape.
11
+ * ``is_dataframe(x)`` -- recognise a pandas DataFrame WITHOUT importing pandas.
12
+
13
+ pandas is an optional dependency: it is imported lazily, only when a table actually crosses
14
+ (``to_dataframe``). ``is_dataframe`` is duck-typed so the input path never imports pandas.
15
+ Install the extra with ``pip install pyfsda[pandas]``.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ _PANDAS_HINT = (
20
+ "pandas is required for this feature; install it with `pip install pyfsda[pandas]` "
21
+ "(or `pip install pandas`)."
22
+ )
23
+
24
+
25
+ def _require_pandas():
26
+ """Import pandas lazily, raising a clear, actionable error if it is missing."""
27
+ try:
28
+ import pandas as pd
29
+ except ImportError as exc: # pragma: no cover - trivial guard
30
+ raise ImportError(_PANDAS_HINT) from exc
31
+ return pd
32
+
33
+
34
+ def is_table_dict(obj) -> bool:
35
+ """True if ``obj`` is a table/timetable dict emitted by ``engine._table_to_dict``."""
36
+ return (
37
+ isinstance(obj, dict)
38
+ and "VariableNames" in obj
39
+ and "data" in obj
40
+ and ("RowNames" in obj or "RowTimes" in obj)
41
+ )
42
+
43
+
44
+ def is_dataframe(x) -> bool:
45
+ """True if ``x`` is a pandas DataFrame -- duck-typed, so pandas is never imported here."""
46
+ cls = type(x)
47
+ return cls.__name__ == "DataFrame" and cls.__module__.split(".", 1)[0] == "pandas"
48
+
49
+
50
+ def to_dataframe(table_dict):
51
+ """Build a ``pandas.DataFrame`` from a table/timetable dict.
52
+
53
+ Columns follow ``VariableNames`` order; the index comes from ``RowTimes`` (parsed to a
54
+ DatetimeIndex when possible, else kept as strings) for a timetable, or from non-empty
55
+ ``RowNames`` for a table; otherwise the default RangeIndex is used.
56
+ """
57
+ if not is_table_dict(table_dict):
58
+ raise TypeError("to_dataframe expects a table/timetable dict "
59
+ "{VariableNames, data, RowNames/RowTimes, ...}.")
60
+ pd = _require_pandas()
61
+ names = list(table_dict["VariableNames"])
62
+ data = table_dict["data"]
63
+ df = pd.DataFrame({col: data[col] for col in names}, columns=names)
64
+
65
+ row_times = table_dict.get("RowTimes")
66
+ row_names = table_dict.get("RowNames")
67
+ if row_times:
68
+ try:
69
+ df.index = pd.to_datetime(list(row_times))
70
+ except (ValueError, TypeError):
71
+ df.index = list(row_times)
72
+ elif row_names:
73
+ df.index = list(row_names)
74
+ return df
75
+
76
+
77
+ def apply_frames(obj):
78
+ """Recurse through a marshalled result, converting every table-dict to a DataFrame.
79
+
80
+ Handles a bare table-dict, a ``nargout > 1`` tuple/list, and a struct dict that holds
81
+ table-dict fields. Non-table values are returned unchanged.
82
+ """
83
+ if is_table_dict(obj):
84
+ return to_dataframe(obj)
85
+ if isinstance(obj, dict):
86
+ return {k: apply_frames(v) for k, v in obj.items()}
87
+ if isinstance(obj, tuple):
88
+ return tuple(apply_frames(v) for v in obj)
89
+ if isinstance(obj, list):
90
+ return [apply_frames(v) for v in obj]
91
+ return obj
pyfsda/py.typed ADDED
File without changes
@@ -0,0 +1,158 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyfsda
3
+ Version: 0.4.0
4
+ Summary: Call FSDA (MATLAB robust-statistics toolbox) routines from Python via the MATLAB Engine.
5
+ Project-URL: Homepage, https://github.com/UniprJRC/FSDA-bridge
6
+ Project-URL: Repository, https://github.com/UniprJRC/FSDA-bridge
7
+ Project-URL: Issues, https://github.com/UniprJRC/FSDA-bridge/issues
8
+ Project-URL: FSDA toolbox, https://github.com/UniprJRC/FSDA
9
+ Author: FSDA team
10
+ Author-email: Aldo Corbellini <aldo.corbellini@gmail.com>
11
+ Maintainer-email: Aldo Corbellini <aldo.corbellini@gmail.com>
12
+ License-Expression: EUPL-1.2
13
+ License-File: LICENSE
14
+ Keywords: forward search,fsda,matlab,matlab engine,outlier detection,robust statistics
15
+ Classifier: Development Status :: 4 - Beta
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Topic :: Scientific/Engineering
25
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
26
+ Classifier: Typing :: Typed
27
+ Requires-Python: >=3.9
28
+ Requires-Dist: matlabengine
29
+ Requires-Dist: numpy>=1.22
30
+ Provides-Extra: dev
31
+ Requires-Dist: build; extra == 'dev'
32
+ Requires-Dist: pandas>=1.5; extra == 'dev'
33
+ Requires-Dist: pytest>=7; extra == 'dev'
34
+ Requires-Dist: twine; extra == 'dev'
35
+ Provides-Extra: pandas
36
+ Requires-Dist: pandas>=1.5; extra == 'pandas'
37
+ Description-Content-Type: text/markdown
38
+
39
+ # pyfsda
40
+
41
+ Call [**FSDA**](https://github.com/UniprJRC/FSDA) — the MATLAB *Flexible Statistics and Data
42
+ Analysis* toolbox for robust statistics — from **Python**, using the MATLAB Engine as the
43
+ computational backend. FSDA runs unmodified in MATLAB; `pyfsda` is a thin, routine-agnostic bridge
44
+ that marshals data across the boundary.
45
+
46
+ Call any FSDA routine as a plain Python function — the MATLAB session starts on first use and is
47
+ reused:
48
+
49
+ ```python
50
+ import pyfsda
51
+
52
+ d = pyfsda.mahalFS(Y, MU, SIGMA) # numeric array -> numpy ndarray
53
+ out = pyfsda.Score(y, X, la=la, intercept=True) # struct -> dict (MATLAB-style options)
54
+ RAW, REW = pyfsda.mcd(Y, nargout=2) # two outputs -> tuple
55
+ pyfsda.stop() # optional; also runs automatically at exit
56
+ ```
57
+
58
+ `pyfsda.<name>` works for **any** FSDA function (`from pyfsda import Score` works too). Prefer managing
59
+ the session yourself? Use the explicit engine:
60
+
61
+ ```python
62
+ from pyfsda import FsdaEngine
63
+
64
+ eng = FsdaEngine.start("mahalFS")
65
+ d = eng.call("mahalFS", Y, MU, SIGMA)
66
+ eng.stop()
67
+ ```
68
+
69
+ ## Requirements
70
+
71
+ `pyfsda` does not bundle MATLAB or FSDA — it drives your local install. You need:
72
+
73
+ 1. **MATLAB** with the **FSDA Add-On** installed and on the MATLAB path (verify `which mahalFS`
74
+ inside MATLAB).
75
+ 2. **`matlabengine`** matching your MATLAB release. This is the one version constraint that matters:
76
+ the `matlabengine` package on PyPI is release-locked, so install the one that pairs with your
77
+ MATLAB — e.g. `pip install "matlabengine==26.1.*"` for **R2026a**. `pyfsda` lists `matlabengine`
78
+ as a dependency but deliberately does **not** pin it, so it will not clobber a matching version you
79
+ already have.
80
+ 3. **Python 3.9–3.13** (whatever your MATLAB release's engine supports).
81
+
82
+ ## Install
83
+
84
+ ```bash
85
+ pip install pyfsda
86
+ # then, if not already present, the matlabengine that matches YOUR MATLAB:
87
+ pip install "matlabengine==26.1.*" # example: MATLAB R2026a
88
+ ```
89
+
90
+ ## Verify your install
91
+
92
+ Run [`examples/smoke_test.py`](examples/smoke_test.py) — it starts MATLAB and checks a few real FSDA
93
+ routines against numpy oracles, printing `RESULT: PASS` when your MATLAB + FSDA + `matlabengine` setup
94
+ is good:
95
+
96
+ ```bash
97
+ python smoke_test.py # or: python smoke_test.py /path/to/FSDA
98
+ ```
99
+
100
+ For a worked, MATLAB-style example, see [`examples/score_example.py`](examples/score_example.py) — the
101
+ Box-Cox `Score` test on the wool dataset, calling `Score(y, X, 'la', ..., 'intercept', true)` the same
102
+ way you would in MATLAB.
103
+
104
+ ## What crosses the boundary
105
+
106
+ `call(name, *args, nargout=1, echo_output=False, options=None, **kwargs)` marshals positional
107
+ arguments in order and keyword arguments (and any `options` dict) as MATLAB name/value pairs. It runs
108
+ through the MATLAB workspace so outputs the engine cannot return directly (tables, 2-D cells) are
109
+ decoded MATLAB-side.
110
+
111
+ | MATLAB value | crosses as |
112
+ |---|---|
113
+ | numeric / logical array | `numpy.ndarray` (natural shape, `NaN`/`Inf` preserved) |
114
+ | `struct` | `dict` (recursed) |
115
+ | `char` / `string` scalar | `str` |
116
+ | `cell` | `list` |
117
+ | `table` / `timetable` | `dict` `{VariableNames, RowNames`/`RowTimes, data, height}` |
118
+ | 2-D `cell` | nested `list` |
119
+ | `nargout > 1` | `tuple` of the above |
120
+ | graphics handle (`matlab.graphics.*`) | **not marshalled** — request only data outputs |
121
+
122
+ Conventions: a 1-D input crosses as a MATLAB **row** (pass an `(n, 1)` array for a column); outputs
123
+ keep MATLAB's natural shape (no silent reshape); MATLAB indices stay **1-based**.
124
+
125
+ Reserved keywords consumed by the bridge are only `nargout`, `echo_output`, `options`, and `frames`;
126
+ every other keyword is forwarded to MATLAB (so FSDA's own `msg` option passes straight through).
127
+ `echo_output=True` tees MATLAB's stdout/stderr to your terminal.
128
+
129
+ ### Optional pandas view (`pip install pyfsda[pandas]`)
130
+
131
+ pandas is an **optional** dependency — `import pyfsda` works without it. When it is installed you get a
132
+ DataFrame view over MATLAB tables, on the Python side only (the neutral dict stays the default and
133
+ remains the cross-language contract):
134
+
135
+ - **Output:** pass `frames=True` to receive `table`/`timetable` outputs as a `pandas.DataFrame`
136
+ (index from `RowNames`/`RowTimes`) — e.g. `out = pyfsda.univariatems(y, X, frames=True)`. The public
137
+ helper `pyfsda.to_dataframe(table_dict)` converts a dict you already have.
138
+ - **Input:** pass a `pandas.DataFrame` argument and it is marshalled to a MATLAB `table`
139
+ (`array2table`, column names and any non-default index preserved). v1 covers numeric/logical columns;
140
+ string/categorical/datetime columns raise a clear `NotImplementedError`.
141
+
142
+ Requesting `frames=True` (or passing a DataFrame) without pandas installed raises a clear
143
+ `pip install pyfsda[pandas]` error.
144
+
145
+ On the **first `pyfsda.<name>(...)` call**, pyfsda also prints (once, best-effort) the **latest FSDA
146
+ release available on GitHub**, so you can check your install is current. `FsdaEngine.start()`
147
+ additionally runs a MATLAB-side FSDA up-to-date check via FSDA's `tuna` utility (quiet unless an update
148
+ is available). Both are gated by `check_version` — silence them with
149
+ `pyfsda.start(check_version=False)` (or `FsdaEngine.start(check_version=False)`) before the first call.
150
+
151
+ ## Notes
152
+
153
+ - **MATLAB engine startup is slow** — start one `FsdaEngine` and reuse it; always `stop()` explicitly.
154
+ - Struct-arrays and `datetime`/`duration` scalars are out of scope for the generic converters.
155
+
156
+ ## License
157
+
158
+ [EUPL-1.2](LICENSE) — consistent with FSDA's own licensing.
@@ -0,0 +1,8 @@
1
+ pyfsda/__init__.py,sha256=RQjt5_8mqDYDN90IOp6QEWjBqQYYzpjSVUH1Aj-epjg,6560
2
+ pyfsda/engine.py,sha256=WOeQm58_NC2ohzNPwA1yAWmnC8htUMaTPPLSd3JCW6s,24242
3
+ pyfsda/frames.py,sha256=WN46KjphgjY-73eCl-BBiqT5vbsPGosr0NnmyZdeMQE,3609
4
+ pyfsda/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ pyfsda-0.4.0.dist-info/METADATA,sha256=keYhCk-lZ7nYEpGsH62EGRyHetxUFnGLao14ky1W5Kc,7183
6
+ pyfsda-0.4.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
7
+ pyfsda-0.4.0.dist-info/licenses/LICENSE,sha256=V_tC-80LA3zlKO2PcvHsCV1nvGgl7PFEj_Ob4f5opLQ,13792
8
+ pyfsda-0.4.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,190 @@
1
+ EUROPEAN UNION PUBLIC LICENCE v. 1.2
2
+ EUPL © the European Union 2007, 2016
3
+
4
+ This European Union Public Licence (the ‘EUPL’) applies to the Work (as defined below) which is provided under the
5
+ terms of this Licence. Any use of the Work, other than as authorised under this Licence is prohibited (to the extent such
6
+ use is covered by a right of the copyright holder of the Work).
7
+ The Work is provided under the terms of this Licence when the Licensor (as defined below) has placed the following
8
+ notice immediately following the copyright notice for the Work:
9
+ Licensed under the EUPL
10
+ or has expressed by any other means his willingness to license under the EUPL.
11
+
12
+ 1.Definitions
13
+ In this Licence, the following terms have the following meaning:
14
+ — ‘The Licence’:this Licence.
15
+ — ‘The Original Work’:the work or software distributed or communicated by the Licensor under this Licence, available
16
+ as Source Code and also as Executable Code as the case may be.
17
+ — ‘Derivative Works’:the works or software that could be created by the Licensee, based upon the Original Work or
18
+ modifications thereof. This Licence does not define the extent of modification or dependence on the Original Work
19
+ required in order to classify a work as a Derivative Work; this extent is determined by copyright law applicable in
20
+ the country mentioned in Article 15.
21
+ — ‘The Work’:the Original Work or its Derivative Works.
22
+ — ‘The Source Code’:the human-readable form of the Work which is the most convenient for people to study and
23
+ modify.
24
+ — ‘The Executable Code’:any code which has generally been compiled and which is meant to be interpreted by
25
+ a computer as a program.
26
+ — ‘The Licensor’:the natural or legal person that distributes or communicates the Work under the Licence.
27
+ — ‘Contributor(s)’:any natural or legal person who modifies the Work under the Licence, or otherwise contributes to
28
+ the creation of a Derivative Work.
29
+ — ‘The Licensee’ or ‘You’:any natural or legal person who makes any usage of the Work under the terms of the
30
+ Licence.
31
+ — ‘Distribution’ or ‘Communication’:any act of selling, giving, lending, renting, distributing, communicating,
32
+ transmitting, or otherwise making available, online or offline, copies of the Work or providing access to its essential
33
+ functionalities at the disposal of any other natural or legal person.
34
+
35
+ 2.Scope of the rights granted by the Licence
36
+ The Licensor hereby grants You a worldwide, royalty-free, non-exclusive, sublicensable licence to do the following, for
37
+ the duration of copyright vested in the Original Work:
38
+ — use the Work in any circumstance and for all usage,
39
+ — reproduce the Work,
40
+ — modify the Work, and make Derivative Works based upon the Work,
41
+ — communicate to the public, including the right to make available or display the Work or copies thereof to the public
42
+ and perform publicly, as the case may be, the Work,
43
+ — distribute the Work or copies thereof,
44
+ — lend and rent the Work or copies thereof,
45
+ — sublicense rights in the Work or copies thereof.
46
+ Those rights can be exercised on any media, supports and formats, whether now known or later invented, as far as the
47
+ applicable law permits so.
48
+ In the countries where moral rights apply, the Licensor waives his right to exercise his moral right to the extent allowed
49
+ by law in order to make effective the licence of the economic rights here above listed.
50
+ The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to any patents held by the Licensor, to the
51
+ extent necessary to make use of the rights granted on the Work under this Licence.
52
+
53
+ 3.Communication of the Source Code
54
+ The Licensor may provide the Work either in its Source Code form, or as Executable Code. If the Work is provided as
55
+ Executable Code, the Licensor provides in addition a machine-readable copy of the Source Code of the Work along with
56
+ each copy of the Work that the Licensor distributes or indicates, in a notice following the copyright notice attached to
57
+ the Work, a repository where the Source Code is easily and freely accessible for as long as the Licensor continues to
58
+ distribute or communicate the Work.
59
+
60
+ 4.Limitations on copyright
61
+ Nothing in this Licence is intended to deprive the Licensee of the benefits from any exception or limitation to the
62
+ exclusive rights of the rights owners in the Work, of the exhaustion of those rights or of other applicable limitations
63
+ thereto.
64
+
65
+ 5.Obligations of the Licensee
66
+ The grant of the rights mentioned above is subject to some restrictions and obligations imposed on the Licensee. Those
67
+ obligations are the following:
68
+
69
+ Attribution right: The Licensee shall keep intact all copyright, patent or trademarks notices and all notices that refer to
70
+ the Licence and to the disclaimer of warranties. The Licensee must include a copy of such notices and a copy of the
71
+ Licence with every copy of the Work he/she distributes or communicates. The Licensee must cause any Derivative Work
72
+ to carry prominent notices stating that the Work has been modified and the date of modification.
73
+
74
+ Copyleft clause: If the Licensee distributes or communicates copies of the Original Works or Derivative Works, this
75
+ Distribution or Communication will be done under the terms of this Licence or of a later version of this Licence unless
76
+ the Original Work is expressly distributed only under this version of the Licence — for example by communicating
77
+ ‘EUPL v. 1.2 only’. The Licensee (becoming Licensor) cannot offer or impose any additional terms or conditions on the
78
+ Work or Derivative Work that alter or restrict the terms of the Licence.
79
+
80
+ Compatibility clause: If the Licensee Distributes or Communicates Derivative Works or copies thereof based upon both
81
+ the Work and another work licensed under a Compatible Licence, this Distribution or Communication can be done
82
+ under the terms of this Compatible Licence. For the sake of this clause, ‘Compatible Licence’ refers to the licences listed
83
+ in the appendix attached to this Licence. Should the Licensee's obligations under the Compatible Licence conflict with
84
+ his/her obligations under this Licence, the obligations of the Compatible Licence shall prevail.
85
+
86
+ Provision of Source Code: When distributing or communicating copies of the Work, the Licensee will provide
87
+ a machine-readable copy of the Source Code or indicate a repository where this Source will be easily and freely available
88
+ for as long as the Licensee continues to distribute or communicate the Work.
89
+ Legal Protection: This Licence does not grant permission to use the trade names, trademarks, service marks, or names
90
+ of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and
91
+ reproducing the content of the copyright notice.
92
+
93
+ 6.Chain of Authorship
94
+ The original Licensor warrants that the copyright in the Original Work granted hereunder is owned by him/her or
95
+ licensed to him/her and that he/she has the power and authority to grant the Licence.
96
+ Each Contributor warrants that the copyright in the modifications he/she brings to the Work are owned by him/her or
97
+ licensed to him/her and that he/she has the power and authority to grant the Licence.
98
+ Each time You accept the Licence, the original Licensor and subsequent Contributors grant You a licence to their contributions
99
+ to the Work, under the terms of this Licence.
100
+
101
+ 7.Disclaimer of Warranty
102
+ The Work is a work in progress, which is continuously improved by numerous Contributors. It is not a finished work
103
+ and may therefore contain defects or ‘bugs’ inherent to this type of development.
104
+ For the above reason, the Work is provided under the Licence on an ‘as is’ basis and without warranties of any kind
105
+ concerning the Work, including without limitation merchantability, fitness for a particular purpose, absence of defects or
106
+ errors, accuracy, non-infringement of intellectual property rights other than copyright as stated in Article 6 of this
107
+ Licence.
108
+ This disclaimer of warranty is an essential part of the Licence and a condition for the grant of any rights to the Work.
109
+
110
+ 8.Disclaimer of Liability
111
+ Except in the cases of wilful misconduct or damages directly caused to natural persons, the Licensor will in no event be
112
+ liable for any direct or indirect, material or moral, damages of any kind, arising out of the Licence or of the use of the
113
+ Work, including without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, loss
114
+ of data or any commercial damage, even if the Licensor has been advised of the possibility of such damage. However,
115
+ the Licensor will be liable under statutory product liability laws as far such laws apply to the Work.
116
+
117
+ 9.Additional agreements
118
+ While distributing the Work, You may choose to conclude an additional agreement, defining obligations or services
119
+ consistent with this Licence. However, if accepting obligations, You may act only on your own behalf and on your sole
120
+ responsibility, not on behalf of the original Licensor or any other Contributor, and only if You agree to indemnify,
121
+ defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against such Contributor by
122
+ the fact You have accepted any warranty or additional liability.
123
+
124
+ 10.Acceptance of the Licence
125
+ The provisions of this Licence can be accepted by clicking on an icon ‘I agree’ placed under the bottom of a window
126
+ displaying the text of this Licence or by affirming consent in any other similar way, in accordance with the rules of
127
+ applicable law. Clicking on that icon indicates your clear and irrevocable acceptance of this Licence and all of its terms
128
+ and conditions.
129
+ Similarly, you irrevocably accept this Licence and all of its terms and conditions by exercising any rights granted to You
130
+ by Article 2 of this Licence, such as the use of the Work, the creation by You of a Derivative Work or the Distribution
131
+ or Communication by You of the Work or copies thereof.
132
+
133
+ 11.Information to the public
134
+ In case of any Distribution or Communication of the Work by means of electronic communication by You (for example,
135
+ by offering to download the Work from a remote location) the distribution channel or media (for example, a website)
136
+ must at least provide to the public the information requested by the applicable law regarding the Licensor, the Licence
137
+ and the way it may be accessible, concluded, stored and reproduced by the Licensee.
138
+
139
+ 12.Termination of the Licence
140
+ The Licence and the rights granted hereunder will terminate automatically upon any breach by the Licensee of the terms
141
+ of the Licence.
142
+ Such a termination will not terminate the licences of any person who has received the Work from the Licensee under
143
+ the Licence, provided such persons remain in full compliance with the Licence.
144
+
145
+ 13.Miscellaneous
146
+ Without prejudice of Article 9 above, the Licence represents the complete agreement between the Parties as to the
147
+ Work.
148
+ If any provision of the Licence is invalid or unenforceable under applicable law, this will not affect the validity or
149
+ enforceability of the Licence as a whole. Such provision will be construed or reformed so as necessary to make it valid
150
+ and enforceable.
151
+ The European Commission may publish other linguistic versions or new versions of this Licence or updated versions of
152
+ the Appendix, so far this is required and reasonable, without reducing the scope of the rights granted by the Licence.
153
+ New versions of the Licence will be published with a unique version number.
154
+ All linguistic versions of this Licence, approved by the European Commission, have identical value. Parties can take
155
+ advantage of the linguistic version of their choice.
156
+
157
+ 14.Jurisdiction
158
+ Without prejudice to specific agreement between parties,
159
+ — any litigation resulting from the interpretation of this License, arising between the European Union institutions,
160
+ bodies, offices or agencies, as a Licensor, and any Licensee, will be subject to the jurisdiction of the Court of Justice
161
+ of the European Union, as laid down in article 272 of the Treaty on the Functioning of the European Union,
162
+ — any litigation arising between other parties and resulting from the interpretation of this License, will be subject to
163
+ the exclusive jurisdiction of the competent court where the Licensor resides or conducts its primary business.
164
+
165
+ 15.Applicable Law
166
+ Without prejudice to specific agreement between parties,
167
+ — this Licence shall be governed by the law of the European Union Member State where the Licensor has his seat,
168
+ resides or has his registered office,
169
+ — this licence shall be governed by Belgian law if the Licensor has no seat, residence or registered office inside
170
+ a European Union Member State.
171
+
172
+
173
+ Appendix
174
+
175
+ ‘Compatible Licences’ according to Article 5 EUPL are:
176
+ — GNU General Public License (GPL) v. 2, v. 3
177
+ — GNU Affero General Public License (AGPL) v. 3
178
+ — Open Software License (OSL) v. 2.1, v. 3.0
179
+ — Eclipse Public License (EPL) v. 1.0
180
+ — CeCILL v. 2.0, v. 2.1
181
+ — Mozilla Public Licence (MPL) v. 2
182
+ — GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3
183
+ — Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for works other than software
184
+ — European Union Public Licence (EUPL) v. 1.1, v. 1.2
185
+ — Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong Reciprocity (LiLiQ-R+).
186
+
187
+ The European Commission may update this Appendix to later versions of the above licences without producing
188
+ a new version of the EUPL, as long as they provide the rights granted in Article 2 of this Licence and protect the
189
+ covered Source Code from exclusive appropriation.
190
+ All other changes or additions to this Appendix require the production of a new EUPL version.