pyfopid 0.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.
pyfopid/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ """pyfopid: fractional-order modelling and control in Python."""
2
+
3
+ from .approx import ZPK, freqresp_zpk, oustaloup
4
+ from .controller import FOPID
5
+ from .operators import caputo_derivative, fractional_integral, gl_derivative, gl_weights
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ __all__ = [
10
+ "FOPID",
11
+ "ZPK",
12
+ "caputo_derivative",
13
+ "fractional_integral",
14
+ "freqresp_zpk",
15
+ "gl_derivative",
16
+ "gl_weights",
17
+ "oustaloup",
18
+ "__version__",
19
+ ]
pyfopid/approx.py ADDED
@@ -0,0 +1,103 @@
1
+ """Rational (integer-order) approximations of fractional operators s^alpha.
2
+
3
+ Implements the Oustaloup recursive approximation
4
+
5
+ s^g ~= K * prod_{k=-N}^{N} (s + w'_k) / (s + w_k),
6
+
7
+ w'_k = wb * (wh / wb) ** ((k + N + (1 - g) / 2) / (2N + 1))
8
+ w_k = wb * (wh / wb) ** ((k + N + (1 + g) / 2) / (2N + 1))
9
+ K = wh ** g
10
+
11
+ valid inside the band [wb, wh] for |g| < 1 (Oustaloup et al., 2000,
12
+ IEEE Trans. Circuits Syst. I, 47(1), 25-39).
13
+
14
+ Orders with |alpha| >= 1 are split as alpha = n + g, with n = round(alpha) and
15
+ g in [-0.5, 0.5]; the integer part is realised exactly with zeros or poles at
16
+ the origin, and only g is approximated.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from dataclasses import dataclass
22
+
23
+ import numpy as np
24
+ from numpy.typing import ArrayLike, NDArray
25
+
26
+ __all__ = ["ZPK", "oustaloup", "freqresp_zpk"]
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class ZPK:
31
+ """Zero-pole-gain representation: H(s) = gain * prod(s - z) / prod(s - p)."""
32
+
33
+ zeros: NDArray[np.float64]
34
+ poles: NDArray[np.float64]
35
+ gain: float
36
+
37
+ def to_tf(self):
38
+ """Return a :class:`control.TransferFunction`."""
39
+ import control
40
+
41
+ num = self.gain * np.real_if_close(np.poly(self.zeros)) if self.zeros.size else np.array([self.gain])
42
+ den = np.real_if_close(np.poly(self.poles)) if self.poles.size else np.array([1.0])
43
+ return control.tf(np.atleast_1d(num).astype(float), np.atleast_1d(den).astype(float))
44
+
45
+
46
+ def oustaloup(
47
+ alpha: float,
48
+ wb: float = 1e-3,
49
+ wh: float = 1e3,
50
+ N: int = 5,
51
+ as_tf: bool = True,
52
+ ):
53
+ """Oustaloup approximation of ``s**alpha`` in the band ``[wb, wh]`` rad/s.
54
+
55
+ Parameters
56
+ ----------
57
+ alpha : float
58
+ Fractional order (any real value).
59
+ wb, wh : float
60
+ Lower and upper band limits in rad/s, ``0 < wb < wh``.
61
+ N : int
62
+ Number of zero/pole pairs is ``2N + 1``.
63
+ as_tf : bool
64
+ If True return a :class:`control.TransferFunction`; otherwise a
65
+ :class:`ZPK` object.
66
+ """
67
+ if not (wb > 0 and wh > wb):
68
+ raise ValueError("require 0 < wb < wh")
69
+ if not isinstance(N, (int, np.integer)) or N < 1:
70
+ raise ValueError("N must be a positive integer")
71
+ alpha = float(alpha)
72
+ n_int = int(np.round(alpha))
73
+ g = alpha - n_int
74
+
75
+ zeros: list[float] = []
76
+ poles: list[float] = []
77
+ gain = 1.0
78
+ if abs(g) > 1e-12:
79
+ ratio = wh / wb
80
+ k = np.arange(-N, N + 1)
81
+ wz = wb * ratio ** ((k + N + 0.5 * (1.0 - g)) / (2 * N + 1))
82
+ wp = wb * ratio ** ((k + N + 0.5 * (1.0 + g)) / (2 * N + 1))
83
+ zeros.extend(-wz)
84
+ poles.extend(-wp)
85
+ gain = wh**g
86
+ if n_int > 0:
87
+ zeros.extend([0.0] * n_int)
88
+ elif n_int < 0:
89
+ poles.extend([0.0] * (-n_int))
90
+
91
+ zpk = ZPK(np.array(zeros, dtype=float), np.array(poles, dtype=float), float(gain))
92
+ return zpk.to_tf() if as_tf else zpk
93
+
94
+
95
+ def freqresp_zpk(zpk: ZPK, omega: ArrayLike) -> NDArray[np.complex128]:
96
+ """Evaluate ``H(j*omega)`` of a :class:`ZPK` without forming polynomials."""
97
+ s = 1j * np.asarray(omega, dtype=float)
98
+ h = np.full(s.shape, zpk.gain, dtype=complex)
99
+ for z in zpk.zeros:
100
+ h *= s - z
101
+ for p in zpk.poles:
102
+ h /= s - p
103
+ return h
pyfopid/controller.py ADDED
@@ -0,0 +1,434 @@
1
+ """Discrete-time fractional-order PID controller, PI^lambda D^mu.
2
+
3
+ Continuous law:
4
+
5
+ u(t) = Kp e(t) + Ki D^(-lambda) e(t) + Kd D^(mu) e(t)
6
+
7
+ Integral term
8
+ -------------
9
+ Two Grünwald-Letnikov (GL) discretisations are provided:
10
+
11
+ ``integral="accumulated"`` (default)
12
+ Uses the factorisation s^(-lambda) = s^(-1) * s^(1 - lambda):
13
+
14
+ v_k = dt^(-(1-lambda)) * sum_{j=0}^{L} w_j(1-lambda) e_{k-j}
15
+ I_k = I_{k-1} + dt * v_k
16
+
17
+ The integer integrator keeps genuine integral action (infinite DC gain,
18
+ zero steady-state error) even with a short memory L, whereas the
19
+ fractional part is confined to the GL sum.
20
+
21
+ ``integral="gl"``
22
+ Direct GL sum of order -lambda with memory L:
23
+
24
+ I_k = dt^lambda * sum_{j=0}^{L} w_j(-lambda) e_{k-j}
25
+
26
+ With a finite memory the DC gain is finite, so a small steady-state error
27
+ remains; it is provided for comparison with the literature.
28
+
29
+ Derivative term
30
+ ---------------
31
+ D_k = dt^(-mu) * sum_{j=0}^{L} w_j(mu) d_{k-j}
32
+
33
+ where d is the error (``derivative_on="error"``) or the sign-adjusted
34
+ measurement (``derivative_on="measurement"``, no set-point kick). An optional
35
+ first-order low-pass filter with time constant ``d_filter_tau``,
36
+ 1 / (tau s + 1), discretised with backward Euler, limits noise amplification
37
+ (important for mu > 1).
38
+
39
+ With lambda = mu = 1, no filter and derivative on error, both integral modes
40
+ reduce exactly to the classical discrete PID (backward-rectangle integral,
41
+ backward-difference derivative).
42
+ """
43
+
44
+ from __future__ import annotations
45
+
46
+ import numpy as np
47
+
48
+ from .approx import oustaloup
49
+ from .operators import gl_weights
50
+
51
+ __all__ = ["FOPID"]
52
+
53
+ _INTEGRAL_MODES = ("accumulated", "gl")
54
+ _DERIVATIVE_MODES = ("error", "measurement")
55
+
56
+
57
+ class FOPID:
58
+ """Fractional-order PID controller for sampled-data loops.
59
+
60
+ Parameters
61
+ ----------
62
+ kp, ki, kd : float
63
+ Proportional, integral and derivative gains.
64
+ lam : float
65
+ Integration order lambda (> 0). For ``integral="accumulated"`` it must
66
+ satisfy 0 < lam <= 2.
67
+ mu : float
68
+ Differentiation order mu (>= 0).
69
+ dt : float
70
+ Sampling period in seconds.
71
+ memory : int
72
+ Short-memory length L (number of past samples in the GL sums). The
73
+ fractional behaviour of the integral is effective for frequencies above
74
+ roughly 1 / (L * dt) rad/s; choose L so that L * dt covers the dominant
75
+ time constants of the plant.
76
+ u_min, u_max : float, optional
77
+ Output saturation limits. Conditional-integration anti-windup is
78
+ applied: a sample is not integrated if the output is saturated and
79
+ integrating it would push further into saturation.
80
+ integral : {"accumulated", "gl"}
81
+ Discretisation of the integral term (see module docstring).
82
+ integral_limit : float, optional
83
+ Symmetric bound on the integral state ``|I| <= integral_limit``
84
+ (``accumulated`` mode only). Extra protection on top of anti-windup.
85
+ derivative_on : {"error", "measurement"}
86
+ Signal differentiated by the D term.
87
+ d_filter_tau : float, optional
88
+ Time constant (s) of the first-order derivative filter. ``None`` or 0
89
+ disables it.
90
+ error_sign : {+1, -1}
91
+ Error convention, needed only for ``derivative_on="measurement"``:
92
+ +1 for e = r - y (heating / direct loops), -1 for e = y - r (e.g.
93
+ cooling with a Peltier module where a larger u lowers y).
94
+
95
+ Examples
96
+ --------
97
+ >>> c = FOPID(kp=1.0, ki=0.5, kd=0.1, lam=0.9, mu=0.6, dt=0.01, memory=500)
98
+ >>> u = c.step(1.0)
99
+ """
100
+
101
+ def __init__(
102
+ self,
103
+ kp: float,
104
+ ki: float,
105
+ kd: float,
106
+ lam: float,
107
+ mu: float,
108
+ dt: float,
109
+ memory: int = 1000,
110
+ u_min: float | None = None,
111
+ u_max: float | None = None,
112
+ integral: str = "accumulated",
113
+ integral_limit: float | None = None,
114
+ derivative_on: str = "error",
115
+ d_filter_tau: float | None = None,
116
+ error_sign: int = 1,
117
+ ) -> None:
118
+ if lam <= 0:
119
+ raise ValueError("lam must be > 0")
120
+ if integral not in _INTEGRAL_MODES:
121
+ raise ValueError(f"integral must be one of {_INTEGRAL_MODES}")
122
+ if integral == "accumulated" and lam > 2:
123
+ raise ValueError("integral='accumulated' requires 0 < lam <= 2")
124
+ if mu < 0:
125
+ raise ValueError("mu must be >= 0")
126
+ if dt <= 0:
127
+ raise ValueError("dt must be > 0")
128
+ if memory < 1:
129
+ raise ValueError("memory must be >= 1")
130
+ if u_min is not None and u_max is not None and u_min >= u_max:
131
+ raise ValueError("u_min must be < u_max")
132
+ if derivative_on not in _DERIVATIVE_MODES:
133
+ raise ValueError(f"derivative_on must be one of {_DERIVATIVE_MODES}")
134
+ if d_filter_tau is not None and d_filter_tau < 0:
135
+ raise ValueError("d_filter_tau must be >= 0")
136
+ if error_sign not in (1, -1):
137
+ raise ValueError("error_sign must be +1 or -1")
138
+ if integral_limit is not None and integral_limit <= 0:
139
+ raise ValueError("integral_limit must be > 0")
140
+
141
+ self.kp, self.ki, self.kd = float(kp), float(ki), float(kd)
142
+ self.lam, self.mu, self.dt = float(lam), float(mu), float(dt)
143
+ self.memory = int(memory)
144
+ self.u_min, self.u_max = u_min, u_max
145
+ self.integral = integral
146
+ self.integral_limit = integral_limit
147
+ self.derivative_on = derivative_on
148
+ self.d_filter_tau = float(d_filter_tau) if d_filter_tau else 0.0
149
+ self.error_sign = int(error_sign)
150
+
151
+ n = self.memory + 1
152
+ if integral == "accumulated":
153
+ a = 1.0 - self.lam
154
+ # dI_k = cv . e_hist (already includes dt and dt^-(1-lambda))
155
+ self._cv = self.dt * self.dt ** (-a) * gl_weights(a, n)
156
+ else:
157
+ # I_k = ci . e_hist (gain Ki folded in)
158
+ self._ci = self.ki * self.dt**self.lam * gl_weights(-self.lam, n)
159
+ self._cd = self.kd * self.dt ** (-self.mu) * gl_weights(self.mu, n)
160
+ self._d_alpha = self.dt / (self.d_filter_tau + self.dt)
161
+ self.reset()
162
+
163
+ # ------------------------------------------------------------------ state
164
+ def reset(
165
+ self,
166
+ error: float = 0.0,
167
+ measurement: float | None = None,
168
+ keep_integral: bool = False,
169
+ ) -> None:
170
+ """Reset the controller histories.
171
+
172
+ Parameters
173
+ ----------
174
+ error : float
175
+ Value used to fill the error history. Passing the current error
176
+ (instead of 0) avoids an artificial step at the first sample.
177
+ measurement : float, optional
178
+ Value used to fill the measurement history when
179
+ ``derivative_on="measurement"``. Defaults to 0.
180
+ keep_integral : bool
181
+ Keep the integral state (``accumulated`` mode). Use it, together
182
+ with ``error``, for bumpless set-point changes.
183
+ """
184
+ n = self.memory + 1
185
+ self._hist_e = np.full(n, float(error))
186
+ if self.derivative_on == "error":
187
+ self._hist_d = np.full(n, float(error))
188
+ else:
189
+ y0 = 0.0 if measurement is None else float(measurement)
190
+ self._hist_d = np.full(n, -self.error_sign * y0)
191
+ if not keep_integral or not hasattr(self, "_I"):
192
+ self._I = 0.0
193
+ self._d_filt = 0.0
194
+ self._d_initialised = False
195
+
196
+ @property
197
+ def integral_state(self) -> float:
198
+ """Current integral state I (accumulated mode) or GL integral value."""
199
+ if self.integral == "accumulated":
200
+ return self._I
201
+ return float(self._ci @ self._hist_e) / self.ki if self.ki else 0.0
202
+
203
+ # --------------------------------------------------------------- helpers
204
+ def _saturate(self, u: float) -> float:
205
+ if self.u_max is not None and u > self.u_max:
206
+ return self.u_max
207
+ if self.u_min is not None and u < self.u_min:
208
+ return self.u_min
209
+ return u
210
+
211
+ @staticmethod
212
+ def _push(hist: np.ndarray, value: float) -> None:
213
+ hist[1:] = hist[:-1]
214
+ hist[0] = value
215
+
216
+ def _derivative(self) -> float:
217
+ d_raw = float(self._cd @ self._hist_d)
218
+ if self.d_filter_tau == 0.0:
219
+ return d_raw
220
+ if not self._d_initialised:
221
+ self._d_filt = d_raw
222
+ self._d_initialised = True
223
+ else:
224
+ self._d_filt += self._d_alpha * (d_raw - self._d_filt)
225
+ return self._d_filt
226
+
227
+ # ------------------------------------------------------------------ step
228
+ def step(self, error: float, measurement: float | None = None) -> float:
229
+ """Advance one sample and return the (saturated) control action.
230
+
231
+ Parameters
232
+ ----------
233
+ error : float
234
+ Control error at this sample (sign convention: see ``error_sign``).
235
+ measurement : float, optional
236
+ Process measurement; required when ``derivative_on="measurement"``.
237
+ """
238
+ e = float(error)
239
+ self._push(self._hist_e, e)
240
+ if self.derivative_on == "error":
241
+ self._push(self._hist_d, e)
242
+ else:
243
+ if measurement is None:
244
+ raise ValueError("derivative_on='measurement' requires `measurement`")
245
+ self._push(self._hist_d, -self.error_sign * float(measurement))
246
+
247
+ u_pd = self.kp * e + self._derivative()
248
+
249
+ if self.integral == "accumulated":
250
+ d_i = float(self._cv @ self._hist_e)
251
+ u_try = u_pd + self.ki * (self._I + d_i)
252
+ u_sat = self._saturate(u_try)
253
+ winding = u_sat != u_try and self.ki * d_i * (u_try - u_sat) > 0
254
+ if not winding:
255
+ self._I += d_i
256
+ if self.integral_limit is not None:
257
+ self._I = min(max(self._I, -self.integral_limit), self.integral_limit)
258
+ return self._saturate(u_pd + self.ki * self._I)
259
+
260
+ # integral == "gl"
261
+ u = u_pd + float(self._ci @ self._hist_e)
262
+ u_sat = self._saturate(u)
263
+ if u_sat != u and e * (u - u_sat) > 0:
264
+ self._hist_e[0] = 0.0
265
+ u_sat = self._saturate(u_pd + float(self._ci @ self._hist_e))
266
+ return u_sat
267
+
268
+ # ------------------------------------------------------------ continuous
269
+ def tf(self, wb: float = 1e-3, wh: float = 1e3, N: int = 5):
270
+ """Continuous transfer function using Oustaloup approximations.
271
+
272
+ Returns ``Kp + Ki * s^(-lam) + Kd * s^(mu) / (tau s + 1)`` as a
273
+ :class:`control.TransferFunction` (the filter factor only if
274
+ ``d_filter_tau > 0``). The integer part of each order is realised
275
+ exactly. If ``mu >= 0.5`` and no filter is used, the result is
276
+ improper, as is the ideal derivative.
277
+ """
278
+ import control
279
+
280
+ c = control.tf([self.kp], [1.0])
281
+ if self.ki != 0.0:
282
+ c = c + self.ki * oustaloup(-self.lam, wb, wh, N)
283
+ if self.kd != 0.0:
284
+ d = self.kd * oustaloup(self.mu, wb, wh, N)
285
+ if self.d_filter_tau > 0.0:
286
+ d = d * control.tf([1.0], [self.d_filter_tau, 1.0])
287
+ c = c + d
288
+ return c
289
+
290
+ # ------------------------------------------------------------- C export
291
+ def to_c_header(self, name: str = "fopid", precision: int = 9) -> str:
292
+ """Generate a self-contained C99 header implementing this controller.
293
+
294
+ Weights are pre-scaled by the gains and sampling period. The generated
295
+ step function is ``float <name>_step(<name>_state_t *s, float e, float y)``;
296
+ ``y`` (measurement) is used only when ``derivative_on="measurement"``.
297
+ On small AVR boards keep the memory short or move the arrays to flash
298
+ with PROGMEM.
299
+ """
300
+ if not name.isidentifier():
301
+ raise ValueError("name must be a valid C identifier")
302
+ up = name.upper()
303
+ n = self.memory + 1
304
+
305
+ def cf(v: float) -> str:
306
+ s = f"{float(v):.{precision}g}"
307
+ if not any(ch in s for ch in ".e"):
308
+ s += ".0"
309
+ return s + "f"
310
+
311
+ def arr(a: np.ndarray) -> str:
312
+ return "{" + ", ".join(cf(v) for v in a) + "}"
313
+
314
+ umin = "-INFINITY" if self.u_min is None else cf(self.u_min)
315
+ umax = "INFINITY" if self.u_max is None else cf(self.u_max)
316
+ acc = self.integral == "accumulated"
317
+ ilim = "INFINITY" if self.integral_limit is None else cf(self.integral_limit)
318
+ d_meas = self.derivative_on == "measurement"
319
+ filt = self.d_filter_tau > 0.0
320
+
321
+ int_array = (
322
+ f"static const float {up}_CV[{up}_N] = {arr(self._cv)};"
323
+ if acc
324
+ else f"static const float {up}_CI[{up}_N] = {arr(self._ci)};"
325
+ )
326
+ d_input = f"{-self.error_sign}.0f * y" if d_meas else "e"
327
+ d_fill = f"{-self.error_sign}.0f * y0" if d_meas else "e0"
328
+
329
+ filt_code = (
330
+ f""" if (!s->d_init) {{ s->d_filt = d; s->d_init = 1; }}
331
+ else s->d_filt += {up}_DALPHA * (d - s->d_filt);
332
+ d = s->d_filt;
333
+ """
334
+ if filt
335
+ else ""
336
+ )
337
+
338
+ if acc:
339
+ int_code = f""" float di = {name}_dot({up}_CV, s->hist_e, s->head);
340
+ float u_try = u_pd + {up}_KI * (s->integ + di);
341
+ float u_sat = {name}_clamp(u_try);
342
+ if (!(u_sat != u_try && {up}_KI * di * (u_try - u_sat) > 0.0f)) {{
343
+ s->integ += di;
344
+ if (s->integ > {up}_ILIM) s->integ = {up}_ILIM;
345
+ if (s->integ < -{up}_ILIM) s->integ = -{up}_ILIM;
346
+ }}
347
+ return {name}_clamp(u_pd + {up}_KI * s->integ);
348
+ """
349
+ else:
350
+ int_code = f""" float u = u_pd + {name}_dot({up}_CI, s->hist_e, s->head);
351
+ float u_sat = {name}_clamp(u);
352
+ if (u_sat != u && e * (u - u_sat) > 0.0f) {{
353
+ s->hist_e[s->head] = 0.0f;
354
+ u_sat = {name}_clamp(u_pd + {name}_dot({up}_CI, s->hist_e, s->head));
355
+ }}
356
+ return u_sat;
357
+ """
358
+
359
+ return f"""/* Auto-generated by pyfopid. Do not edit by hand.
360
+ * FOPID: Kp={self.kp:g}, Ki={self.ki:g}, Kd={self.kd:g},
361
+ * lambda={self.lam:g}, mu={self.mu:g}, dt={self.dt:g} s, L={self.memory}
362
+ * integral={self.integral}, derivative_on={self.derivative_on},
363
+ * d_filter_tau={self.d_filter_tau:g} s, error_sign={self.error_sign:+d}
364
+ * Usage: call {name}_reset(&s, e0, y0) once, then u = {name}_step(&s, e, y)
365
+ * every dt seconds. y is ignored unless derivative_on = measurement.
366
+ */
367
+ #ifndef {up}_H
368
+ #define {up}_H
369
+ #include <math.h>
370
+
371
+ #define {up}_N {n}
372
+ static const float {up}_KP = {cf(self.kp)};
373
+ static const float {up}_KI = {cf(self.ki)};
374
+ static const float {up}_UMIN = {umin};
375
+ static const float {up}_UMAX = {umax};
376
+ static const float {up}_ILIM = {ilim};
377
+ static const float {up}_DALPHA = {cf(self._d_alpha)};
378
+ {int_array}
379
+ static const float {up}_CD[{up}_N] = {arr(self._cd)};
380
+
381
+ typedef struct {{
382
+ float hist_e[{up}_N];
383
+ float hist_d[{up}_N];
384
+ int head;
385
+ float integ;
386
+ float d_filt;
387
+ int d_init;
388
+ }} {name}_state_t;
389
+
390
+ /* e0, y0: current error and measurement, for a bumpless start. */
391
+ static void {name}_reset({name}_state_t *s, float e0, float y0) {{
392
+ (void)y0;
393
+ for (int j = 0; j < {up}_N; ++j) {{ s->hist_e[j] = e0; s->hist_d[j] = {d_fill}; }}
394
+ s->head = 0;
395
+ s->integ = 0.0f;
396
+ s->d_filt = 0.0f;
397
+ s->d_init = 0;
398
+ }}
399
+
400
+ static float {name}_dot(const float *c, const float *h, int head) {{
401
+ float acc = 0.0f;
402
+ int idx = head;
403
+ for (int j = 0; j < {up}_N; ++j) {{
404
+ acc += c[j] * h[idx];
405
+ idx = (idx == 0) ? {up}_N - 1 : idx - 1;
406
+ }}
407
+ return acc;
408
+ }}
409
+
410
+ static float {name}_clamp(float u) {{
411
+ if (u > {up}_UMAX) return {up}_UMAX;
412
+ if (u < {up}_UMIN) return {up}_UMIN;
413
+ return u;
414
+ }}
415
+
416
+ static float {name}_step({name}_state_t *s, float e, float y) {{
417
+ (void)y;
418
+ s->head = (s->head + 1) % {up}_N;
419
+ s->hist_e[s->head] = e;
420
+ s->hist_d[s->head] = {d_input};
421
+ float d = {name}_dot({up}_CD, s->hist_d, s->head);
422
+ {filt_code} float u_pd = {up}_KP * e + d;
423
+ {int_code}}}
424
+
425
+ #endif /* {up}_H */
426
+ """
427
+
428
+ def __repr__(self) -> str:
429
+ return (
430
+ f"FOPID(kp={self.kp:g}, ki={self.ki:g}, kd={self.kd:g}, "
431
+ f"lam={self.lam:g}, mu={self.mu:g}, dt={self.dt:g}, memory={self.memory}, "
432
+ f"integral={self.integral!r}, derivative_on={self.derivative_on!r}, "
433
+ f"d_filter_tau={self.d_filter_tau:g})"
434
+ )
pyfopid/operators.py ADDED
@@ -0,0 +1,176 @@
1
+ """Fractional-order differ-integral operators on uniformly sampled signals.
2
+
3
+ All operators use the Grünwald-Letnikov (GL) definition
4
+
5
+ D^alpha f(t_k) ~= h^(-alpha) * sum_{j=0}^{k} w_j f(t_{k-j}),
6
+
7
+ with the binomial weights w_j = (-1)^j * binom(alpha, j), computed with the
8
+ numerically stable recursion
9
+
10
+ w_0 = 1, w_j = w_{j-1} * (1 - (alpha + 1) / j).
11
+
12
+ The recursion produces the alternating sign pattern of (-1)^j automatically.
13
+ Positive ``alpha`` gives a derivative, negative ``alpha`` an integral and
14
+ ``alpha = 0`` the identity.
15
+
16
+ For functions with f(0) = 0 (and sufficiently smooth), the GL, Riemann-Liouville
17
+ and Caputo derivatives coincide. The GL scheme is first-order accurate, O(h).
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import math
23
+
24
+ import numpy as np
25
+ from numpy.typing import ArrayLike, NDArray
26
+
27
+ __all__ = [
28
+ "gl_weights",
29
+ "gl_derivative",
30
+ "fractional_integral",
31
+ "caputo_derivative",
32
+ ]
33
+
34
+
35
+ def gl_weights(alpha: float, n: int) -> NDArray[np.float64]:
36
+ """Return the first ``n`` Grünwald-Letnikov weights for order ``alpha``.
37
+
38
+ Parameters
39
+ ----------
40
+ alpha : float
41
+ Order of the operator. Positive for derivatives, negative for integrals.
42
+ n : int
43
+ Number of weights (memory length + 1). Must be >= 1.
44
+
45
+ Returns
46
+ -------
47
+ numpy.ndarray
48
+ Array ``w`` with ``w[j] = (-1)**j * binom(alpha, j)``.
49
+
50
+ Examples
51
+ --------
52
+ >>> gl_weights(2.0, 3)
53
+ array([ 1., -2., 1.])
54
+ >>> gl_weights(-1.0, 3)
55
+ array([1., 1., 1.])
56
+ """
57
+ if not isinstance(n, (int, np.integer)) or n < 1:
58
+ raise ValueError("n must be a positive integer")
59
+ alpha = float(alpha)
60
+ w = np.empty(int(n), dtype=np.float64)
61
+ w[0] = 1.0
62
+ for j in range(1, int(n)):
63
+ w[j] = w[j - 1] * (1.0 - (alpha + 1.0) / j)
64
+ return w
65
+
66
+
67
+ def gl_derivative(
68
+ f: ArrayLike,
69
+ alpha: float,
70
+ h: float,
71
+ memory: int | None = None,
72
+ ) -> NDArray[np.float64]:
73
+ """Grünwald-Letnikov fractional derivative (or integral) of a sampled signal.
74
+
75
+ Parameters
76
+ ----------
77
+ f : array_like
78
+ Samples ``f(t_0), f(t_1), ...`` on a uniform grid starting at ``t_0``.
79
+ alpha : float
80
+ Order. ``alpha > 0`` derivative, ``alpha < 0`` integral.
81
+ h : float
82
+ Sampling step (> 0).
83
+ memory : int, optional
84
+ Short-memory length ``L`` (number of past samples used). ``None`` uses
85
+ the full history (exact GL sum). Truncation introduces an error that
86
+ decays as ``L**(-alpha)`` for derivatives.
87
+
88
+ Returns
89
+ -------
90
+ numpy.ndarray
91
+ ``D^alpha f`` evaluated at every sample, same length as ``f``.
92
+ """
93
+ f = np.asarray(f, dtype=np.float64)
94
+ if f.ndim != 1:
95
+ raise ValueError("f must be one-dimensional")
96
+ if h <= 0:
97
+ raise ValueError("h must be positive")
98
+ n = f.size
99
+ if n == 0:
100
+ return f.copy()
101
+ if memory is None:
102
+ n_w = n
103
+ else:
104
+ if memory < 0:
105
+ raise ValueError("memory must be >= 0")
106
+ n_w = min(int(memory) + 1, n)
107
+ w = gl_weights(alpha, n_w)
108
+ y = np.convolve(f, w)[:n]
109
+ return y * h ** (-float(alpha))
110
+
111
+
112
+ def fractional_integral(
113
+ f: ArrayLike,
114
+ order: float,
115
+ h: float,
116
+ memory: int | None = None,
117
+ ) -> NDArray[np.float64]:
118
+ """Fractional integral of order ``order > 0`` (GL / Riemann-Liouville).
119
+
120
+ Equivalent to ``gl_derivative(f, -order, h, memory)``.
121
+ """
122
+ if order < 0:
123
+ raise ValueError("order must be non-negative; use gl_derivative for derivatives")
124
+ return gl_derivative(f, -float(order), h, memory)
125
+
126
+
127
+ def caputo_derivative(
128
+ f: ArrayLike,
129
+ alpha: float,
130
+ h: float,
131
+ initial: ArrayLike | None = None,
132
+ memory: int | None = None,
133
+ ) -> NDArray[np.float64]:
134
+ """Caputo fractional derivative of order ``alpha > 0``.
135
+
136
+ Uses the identity
137
+
138
+ C D^alpha f = RL D^alpha [ f - sum_{k=0}^{m-1} f^(k)(0) t^k / k! ],
139
+
140
+ with ``m = ceil(alpha)``, and evaluates the right-hand side with the GL sum.
141
+
142
+ Parameters
143
+ ----------
144
+ f : array_like
145
+ Uniform samples starting at ``t = 0``.
146
+ alpha : float
147
+ Order (> 0).
148
+ h : float
149
+ Sampling step.
150
+ initial : array_like, optional
151
+ Initial derivatives ``(f(0), f'(0), ..., f^(m-1)(0))``. For
152
+ ``0 < alpha <= 1`` it can be omitted and ``f[0]`` is used. For
153
+ ``alpha > 1`` it is required.
154
+ memory : int, optional
155
+ Short-memory length, see :func:`gl_derivative`.
156
+ """
157
+ alpha = float(alpha)
158
+ if alpha <= 0:
159
+ raise ValueError("Caputo derivative requires alpha > 0")
160
+ f = np.asarray(f, dtype=np.float64)
161
+ m = math.ceil(alpha)
162
+ if initial is None:
163
+ if m > 1:
164
+ raise ValueError(
165
+ f"alpha={alpha} needs {m} initial derivatives; pass `initial`"
166
+ )
167
+ initial_arr = np.array([f[0]])
168
+ else:
169
+ initial_arr = np.atleast_1d(np.asarray(initial, dtype=np.float64))
170
+ if initial_arr.size != m:
171
+ raise ValueError(f"`initial` must have length ceil(alpha) = {m}")
172
+ t = np.arange(f.size) * h
173
+ taylor = np.zeros_like(f)
174
+ for k, dk in enumerate(initial_arr):
175
+ taylor += dk * t**k / math.factorial(k)
176
+ return gl_derivative(f - taylor, alpha, h, memory)
@@ -0,0 +1,151 @@
1
+ Metadata-Version: 2.5
2
+ Name: pyfopid
3
+ Version: 0.1.0
4
+ Summary: Fractional-order modelling and control in Python: Grünwald-Letnikov operators, Oustaloup approximations and FOPID controllers.
5
+ Project-URL: Homepage, https://github.com/ThermalProjects/pyfopid
6
+ Project-URL: Issues, https://github.com/ThermalProjects/pyfopid/issues
7
+ Author: Miguel F. Ferrer Pareja
8
+ License-Expression: BSD-3-Clause
9
+ License-File: LICENSE
10
+ Keywords: FOPID,Grünwald-Letnikov,Oustaloup,control systems,fractional calculus,fractional-order control
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Scientific/Engineering
15
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
16
+ Requires-Python: >=3.10
17
+ Requires-Dist: control>=0.10
18
+ Requires-Dist: numpy>=1.24
19
+ Requires-Dist: scipy>=1.10
20
+ Provides-Extra: plot
21
+ Requires-Dist: matplotlib>=3.7; extra == 'plot'
22
+ Provides-Extra: test
23
+ Requires-Dist: pytest>=7; extra == 'test'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # pyfopid
27
+
28
+ **Fractional-order modelling and control in Python.**
29
+
30
+ `pyfopid` provides tested, documented building blocks for fractional-order
31
+ control: Grünwald-Letnikov operators, Oustaloup rational approximations,
32
+ and a discrete-time FOPID (PI^λD^μ) controller that interoperates with
33
+ [python-control](https://python-control.readthedocs.io) and exports to C for
34
+ embedded targets (Arduino, ESP32, STM32).
35
+
36
+ > Status: alpha (0.1.0.dev0). API may change before 1.0.
37
+
38
+ ## Installation
39
+
40
+ ```bash
41
+ pip install pyfopid # once released on PyPI
42
+ pip install -e ".[test]" # development install from a clone
43
+ ```
44
+
45
+ Requires Python ≥ 3.10, NumPy, SciPy and python-control ≥ 0.10.
46
+
47
+ ## Quick start
48
+
49
+ ```python
50
+ import numpy as np
51
+ import pyfopid as pf
52
+
53
+ # Fractional derivative of order 0.5 of t^2 (Grünwald-Letnikov)
54
+ h = 1e-3
55
+ t = np.arange(0, 1 + h, h)
56
+ d = pf.gl_derivative(t**2, 0.5, h)
57
+
58
+ # Oustaloup approximation of s^0.5 in [0.01, 100] rad/s as a control.TransferFunction
59
+ G = pf.oustaloup(0.5, wb=1e-2, wh=1e2, N=5)
60
+
61
+ # Discrete FOPID controller (accumulated fractional integral, filtered
62
+ # derivative on the measurement, saturation with anti-windup)
63
+ c = pf.FOPID(kp=2.0, ki=1.0, kd=0.1, lam=0.9, mu=0.5, dt=0.01, memory=2000,
64
+ u_min=0.0, u_max=12.0,
65
+ derivative_on="measurement", d_filter_tau=0.05)
66
+ u = c.step(error=0.3, measurement=24.7)
67
+
68
+ # Export the same controller to a C header for a microcontroller
69
+ open("fopid.h", "w").write(c.to_c_header("fopid"))
70
+ ```
71
+
72
+ See [`examples/closed_loop.py`](examples/closed_loop.py) for a full
73
+ closed-loop simulation.
74
+
75
+ ## Features (v0.1)
76
+
77
+ | Module | Contents |
78
+ |---|---|
79
+ | `operators` | `gl_weights`, `gl_derivative` (with short-memory principle), `fractional_integral`, `caputo_derivative` |
80
+ | `approx` | `oustaloup` (any real order; integer part realised exactly), `ZPK`, `freqresp_zpk` |
81
+ | `controller` | `FOPID`: accumulated (default) or direct GL fractional integral, derivative on error or measurement, first-order derivative filter, conditional-integration anti-windup and integral clamp, bumpless `reset()`, `.tf()` (Oustaloup-based continuous model), `.to_c_header()` (C99, same options) |
82
+
83
+ ### Design notes
84
+
85
+ - **Accumulated integral (default).** `s^-λ = s^-1 · s^(1-λ)`: the fractional
86
+ operator of order `1-λ` is evaluated with a GL sum and followed by an
87
+ integer integrator. This keeps genuine integral action (zero steady-state
88
+ error) for any memory length. The direct GL integral (`integral="gl"`) has a
89
+ finite DC gain when the memory is truncated.
90
+ - **Memory length.** The fractional behaviour is effective for frequencies
91
+ above roughly `1/(L·dt)` rad/s. Choose `L·dt` comparable to the dominant
92
+ time constants of the plant.
93
+ - **Derivative.** For `μ > 1` noise amplification is severe; use
94
+ `d_filter_tau`. With non-integer `μ` the GL derivative of a constant is not
95
+ zero, so differentiating the error and differentiating the measurement are
96
+ not equivalent even for a constant set point; `derivative_on="measurement"`
97
+ also removes the set-point kick.
98
+
99
+ ## Verification
100
+
101
+ The test suite (`pytest`) checks:
102
+
103
+ - GL weights against the signed binomial coefficients `(-1)^j C(α, j)`,
104
+ including the sign pattern.
105
+ - GL derivatives and integrals against closed-form results
106
+ (`D^α t^k = Γ(k+1)/Γ(k+1−α) t^(k−α)`, `I^α 1 = t^α/Γ(1+α)`) and the
107
+ expected first-order convergence O(h).
108
+ - Caputo derivatives (constants map to zero; orders above one with initial
109
+ conditions).
110
+ - Oustaloup approximations against `(jω)^α`: with the band
111
+ `[wb, wh]` chosen at least two decades wider than the frequency range of
112
+ interest, errors are < 0.05 dB and < 0.5°. One decade from the band edges
113
+ the phase error rises to ≈ 3° for |α| = 0.5; this is dominated by band
114
+ truncation, not by `N`.
115
+ - Exact reduction of `FOPID` to the classical discrete PID for λ = μ = 1 in
116
+ both integral modes.
117
+ - Closed-loop tracking with and without saturation; zero steady-state error of
118
+ the accumulated integral with a short memory.
119
+ - Sample-by-sample agreement (rtol 1e-9) in closed loop with an independent
120
+ transcription of an FOPID firmware used on a Peltier test bench.
121
+ - Cross-validation against FOMCON 1.50.4 (MATLAB): Oustaloup approximations
122
+ identical to round-off for |α| ≤ 0.5 and more accurate for |α| > 0.5
123
+ (0.54° vs 5.09° phase error at α = −0.9); FOPID time response identical to
124
+ FOMCON `lsim` (relative difference 7.5e-12). See
125
+ [`validation/fomcon`](validation/fomcon/README.md).
126
+ - Compiled C output against Python for all integral/derivative options.
127
+
128
+ ## Citing
129
+
130
+ If you use `pyfopid` in research, please cite it using the metadata in
131
+ [`CITATION.cff`](CITATION.cff). A DOI will be issued through Zenodo with the
132
+ first release.
133
+
134
+ ## Contributing
135
+
136
+ Bug reports, questions and pull requests are welcome. See
137
+ [CONTRIBUTING.md](CONTRIBUTING.md) for the development set-up and the
138
+ [Code of Conduct](CODE_OF_CONDUCT.md).
139
+
140
+ ## Acknowledgements
141
+
142
+ pyfopid is developed at the University Institute of Intelligent Systems and
143
+ Numerical Applications in Engineering (SIANI), University of Las Palmas de
144
+ Gran Canaria. The author thanks Carlos Sánchez Morales and Federico León Zerpa
145
+ (Department of Process Engineering) and Alejandro Ramos Martín (SIANI) for
146
+ their supervision and for their review of the experimental work in which the
147
+ library was used.
148
+
149
+ ## License
150
+
151
+ BSD 3-Clause. See [LICENSE](LICENSE).
@@ -0,0 +1,8 @@
1
+ pyfopid/__init__.py,sha256=h4EXkbv_CV2lWfY6kVl_X0j9N_gXrI1lqLdxJx3bAxo,443
2
+ pyfopid/approx.py,sha256=pMMK7JPtIA3NxA7AjtwER3Rc4wPPA5UI3gN9rVxkJD0,3213
3
+ pyfopid/controller.py,sha256=81_2nZk_6kIEmIFf-XoOWgn_7UiwHK-tLucAHb2flFs,16330
4
+ pyfopid/operators.py,sha256=ABzTpxsGwu8rs5k1JBU45RJ7eVMYM-9SOHZ8B2XKq0k,5224
5
+ pyfopid-0.1.0.dist-info/METADATA,sha256=QWV5L0nqijV768YQkJpg8BUSUOUqAyA5k2KC5EWgXBs,6460
6
+ pyfopid-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ pyfopid-0.1.0.dist-info/licenses/LICENSE,sha256=AkMwYgV98YqOrY9luzGySjtu8l8fpeb1VlI5U7zJgNc,1510
8
+ pyfopid-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, Miguel F. Ferrer Pareja
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.