summaryrefslogtreecommitdiff
path: root/ui/code_templates.py
blob: 0863e6277a1f28250aa5602de2e29b078beeeb79 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""
ui/code_templates.py

Python code templates for built-in derived channel kinds.
Shown as read-only previews in the UI; clicking "Edit as Custom Script"
converts the channel to custom_script kind with the template pre-filled.

Templates use the enhanced expression namespace:
  x      — list of source values in order
  <name> — each source's channel_id as a named variable
  t      — elapsed time (seconds)
  math   — Python math module
  vars   — shared SignalProcessor._script_vars dict (read/write)
  state  — per-channel persistent dict (survives between evaluations)
  result — assign the computed value here (expression-style exec)
"""

BUILTIN_TEMPLATES: dict = {

    "derivative": """\
# dy/dt — backward finite difference
prev_v = state.get("v", x[0])
prev_t = state.get("t", t)
state["v"] = x[0]
state["t"] = t
result = (x[0] - prev_v) / (t - prev_t) if t != prev_t else 0.0
""",

    "second_derivative": """\
# d²y/dt² — two-pass finite difference
prev_v   = state.get("v", x[0])
prev_t   = state.get("t", t)
prev_vel = state.get("vel", 0.0)

cur_vel = (x[0] - prev_v) / (t - prev_t) if t != prev_t else 0.0
result  = (cur_vel - prev_vel) / (t - prev_t) if t != prev_t else 0.0

state["v"]   = x[0]
state["t"]   = t
state["vel"] = cur_vel
""",

    "rms": """\
# Rolling RMS over a sliding window
import math as _math
buf = state.setdefault("buf", [])
buf.append(x[0])
window = 20          # adjust window size (samples) here
if len(buf) > window:
    buf.pop(0)
result = _math.sqrt(sum(v * v for v in buf) / len(buf))
""",

    "power": """\
# Electrical power  P = V × I
# source 0 = voltage,  source 1 = current
result = x[0] * x[1]
""",

    "difference": """\
# Difference  A − B
# source 0 = A,  source 1 = B
result = x[0] - x[1]
""",

    "sum": """\
# Sum of all sources
result = sum(x)
""",
}