sm-riti16 commited on
Commit
8ea3190
·
verified ·
1 Parent(s): 46c4d40

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +355 -0
app.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """natural_language_gradio.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/135ewhMpX2YZA9ysE_QNN0yFQVWYaeW34
8
+ """
9
+
10
+ !pip install gradio transformers sentencepiece pandas
11
+
12
+ import json, pandas as pd
13
+ from dataclasses import dataclass, asdict
14
+
15
+ import math
16
+ from dataclasses import dataclass, asdict
17
+ from typing import Dict, Any
18
+
19
+ @dataclass
20
+ class PIDInputs:
21
+ tau_s: float # plant time constant [s], tau > 0
22
+ Kp: float # proportional gain
23
+ Ki: float # integral gain (>0 for step tracking)
24
+ Kd: float # derivative gain
25
+ step_amplitude: float = 1.0 # unit step default
26
+ settling_pct: float = 0.02 # 2% criterion for settling time
27
+
28
+ def validate_inputs(x: PIDInputs) -> Dict[str, Any]:
29
+ issues = []
30
+ # Reasonable ranges for a compact, safe demo. Adjust as needed.
31
+ if not (0.01 <= x.tau_s <= 10.0):
32
+ issues.append(f"tau must be in [0.01, 10] s, got {x.tau_s:.4g}")
33
+ if not (-0.9 <= x.Kp <= 200.0):
34
+ issues.append(f"Kp should be in [-0.9, 200], got {x.Kp:.4g}")
35
+ if not (1e-6 <= x.Ki <= 1e4):
36
+ issues.append(f"Ki should be in [1e-6, 1e4], got {x.Ki:.4g}")
37
+ if not (-0.009 <= x.Kd <= 100.0):
38
+ issues.append(f"Kd should be in [-0.009, 100], got {x.Kd:.4g}")
39
+ if x.tau_s + x.Kd <= 0:
40
+ issues.append("tau + Kd must be > 0 for a proper 2nd-order form.")
41
+ if x.step_amplitude == 0:
42
+ issues.append("step amplitude should be non-zero for meaningful metrics.")
43
+ if not (0.005 <= x.settling_pct <= 0.1):
44
+ issues.append("settling_pct should be within [0.005, 0.1] (i.e., 0.5% to 10%).")
45
+ return {"ok": len(issues) == 0, "issues": issues}
46
+
47
+ def compute_pid(x: PIDInputs) -> Dict[str, Any]:
48
+ val = validate_inputs(x)
49
+ status = "ok" if val["ok"] else "invalid"
50
+
51
+ wn = None
52
+ zeta = None
53
+ if (x.tau_s + x.Kd) > 0 and x.Ki > 0:
54
+ wn = math.sqrt(x.Ki / (x.tau_s + x.Kd))
55
+ denom = 2.0 * math.sqrt(x.Ki * (x.tau_s + x.Kd))
56
+ zeta = (x.Kp + 1.0) / denom
57
+
58
+ # --- NEW: poles & damping classification ---
59
+ poles = None
60
+ damping_class = None
61
+ if wn is not None and wn > 0 and zeta is not None:
62
+ # Standard 2nd-order characteristic: s^2 + 2ζωn s + ωn^2 = 0
63
+ # Poles: s = -ζωn ± ωn*sqrt(ζ^2 - 1)
64
+ re = -zeta * wn
65
+ disc = zeta**2 - 1.0
66
+ if disc < 0:
67
+ # complex-conjugate poles
68
+ im = wn * math.sqrt(1.0 - zeta**2)
69
+ poles = [complex(re, im), complex(re, -im)]
70
+ damping_class = "underdamped (ζ<1): complex-conjugate poles"
71
+ elif abs(disc) < 1e-12:
72
+ poles = [complex(re, 0.0), complex(re, 0.0)]
73
+ damping_class = "critically damped (ζ≈1): repeated real pole"
74
+ else:
75
+ # distinct real poles
76
+ root = wn * math.sqrt(disc)
77
+ poles = [complex(re + root, 0.0), complex(re - root, 0.0)]
78
+ damping_class = "overdamped (ζ>1): two distinct real poles"
79
+
80
+ metrics = {}
81
+ if wn is not None and zeta is not None and wn > 0 and zeta > 0:
82
+ if zeta < 1.0:
83
+ wd = wn * math.sqrt(1.0 - zeta**2)
84
+ Tp = math.pi / wd
85
+ Mp = math.exp(-math.pi * zeta / math.sqrt(1.0 - zeta**2)) # ratio
86
+ else:
87
+ wd = None
88
+ Tp = None
89
+ Mp = 0.0
90
+ Ts = 4.0 / (zeta * wn) * (0.02 / x.settling_pct)
91
+ if zeta < 1.0:
92
+ theta = math.acos(zeta)
93
+ Tr = (math.pi - theta) / (wn * math.sqrt(1.0 - zeta**2))
94
+ else:
95
+ Tr = 2.0 / wn
96
+ ess = 0.0
97
+
98
+ metrics = {
99
+ "wn_rad_s": wn,
100
+ "zeta": zeta,
101
+ "wd_rad_s": wd,
102
+ "Mp_pct": 100.0 * Mp,
103
+ "Tp_s": Tp,
104
+ "Ts_s": Ts,
105
+ "Tr_s": Tr,
106
+ "ess": ess,
107
+ }
108
+
109
+ structured = {
110
+ "meta": {
111
+ "model": "PID_on_1stOrder_v1",
112
+ "deterministic": True,
113
+ "assumptions": [
114
+ "Unity feedback.",
115
+ "1st-order plant G(s) = 1/(tau s + 1).",
116
+ "Linear time-invariant dynamics.",
117
+ "PID controller C(s) = Kp + Ki/s + Kd s.",
118
+ "Small-signal step response analysis."
119
+ ],
120
+ "units": {
121
+ "tau_s": "s",
122
+ "wn_rad_s": "rad/s",
123
+ "wd_rad_s": "rad/s",
124
+ "Tp_s": "s",
125
+ "Ts_s": "s",
126
+ "Tr_s": "s",
127
+ "Mp_pct": "%"
128
+ },
129
+ "valid_ranges": {
130
+ "tau_s": "[0.01, 10] s",
131
+ "Kp": "[-0.9, 200]",
132
+ "Ki": "[1e-6, 1e4]",
133
+ "Kd": "[-0.009, 100]",
134
+ "tau+Kd": "> 0",
135
+ "Ki_positive": "> 0",
136
+ "settling_pct": "[0.005, 0.1]"
137
+ }
138
+ },
139
+ "inputs": asdict(x),
140
+ "validation": val,
141
+ "normalized_second_order": {
142
+ "a2": x.tau_s + x.Kd,
143
+ "a1": 1.0 + x.Kp,
144
+ "a0": x.Ki,
145
+ "wn": wn,
146
+ "zeta": zeta
147
+ },
148
+ # --- NEW: add poles & classification in the payload ---
149
+ "poles": [complex(p).real if abs(p.imag) < 1e-15 else p for p in (poles or [])],
150
+ "damping_class": damping_class,
151
+ "metrics": metrics,
152
+ "status": status
153
+ }
154
+ return structured
155
+
156
+ import gradio as gr
157
+ import pandas as pd
158
+ from transformers import pipeline
159
+ from typing import Dict, Any
160
+
161
+ # from core import PIDInputs, compute_pid
162
+
163
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
164
+ MODEL_ID = "HuggingFaceTB/SmolLM2-135M-Instruct"
165
+ _tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
166
+ _model = AutoModelForCausalLM.from_pretrained(MODEL_ID, device_map="auto")
167
+ explainer = pipeline(task="text-generation", model=_model, tokenizer=_tokenizer)
168
+
169
+ def explain_structured(d: dict) -> str:
170
+ """
171
+ Explain what the OUTPUT means (stability class, ωn, ζ, poles, overshoot, Tr/Tp/Ts, ess).
172
+ Uses the SmolLM explainer with deterministic decoding, then falls back to a
173
+ deterministic Markdown explanation if the model returns too little text.
174
+ """
175
+ meta = d.get("meta", {})
176
+ m = d.get("metrics", {})
177
+ norm = d.get("normalized_second_order", {})
178
+ poles = d.get("poles", [])
179
+ dampc = d.get("damping_class", None)
180
+ val = d.get("validation", {})
181
+ status = d.get("status")
182
+ issues = val.get("issues", [])
183
+
184
+ # ---------- helpers ----------
185
+ def r(v, n=4, na="N/A"):
186
+ try:
187
+ return f"{float(v):.{n}g}"
188
+ except Exception:
189
+ return na if v is None else str(v)
190
+
191
+ def pstr(p):
192
+ try:
193
+ # p may already be complex or a float
194
+ if isinstance(p, complex) or (hasattr(p, "imag") and p.imag != 0):
195
+ return f"{p.real:+.4g} {'+' if p.imag>=0 else '-'} j{abs(p.imag):.4g}"
196
+ return f"{float(p):+.4g}"
197
+ except Exception:
198
+ return str(p)
199
+
200
+ def dedup_lines(md: str) -> str:
201
+ seen, out = set(), []
202
+ for line in md.splitlines():
203
+ key = line.strip()
204
+ # never dedup headers; only de-dup plain bullet/paragraph lines
205
+ if key and not key.startswith("#") and key in seen:
206
+ continue
207
+ seen.add(key)
208
+ out.append(line)
209
+ return "\n".join(out)
210
+
211
+ # ---------- invalid → deterministic, no LLM ----------
212
+ if status != "ok" or issues:
213
+ bullets = "\n".join([f"- {iss}" for iss in issues]) if issues else "- Check inputs."
214
+ return f"""# Results Explanation
215
+
216
+ **Status:** ❌ Invalid inputs
217
+
218
+ Fix these first:
219
+ {bullets}
220
+
221
+ **Why it matters**
222
+ - τ+Kd must be > 0 to form a valid 2nd-order model.
223
+ - Ki > 0 (type-1) gives zero steady-state error to a step.
224
+ """
225
+
226
+ # ---------- numeric snapshot for prompt & fallback ----------
227
+ wn = norm.get("wn")
228
+ zeta = norm.get("zeta")
229
+ Mp = m.get("Mp_pct")
230
+ Tp = m.get("Tp_s")
231
+ Ts = m.get("Ts_s")
232
+ Tr = m.get("Tr_s")
233
+ ess = m.get("ess")
234
+ poles_text = ", ".join(pstr(p) for p in poles) if poles else "N/A"
235
+
236
+ snapshot = (
237
+ f"- ωₙ (natural frequency): {r(wn)} rad/s\n"
238
+ f"- ζ (damping ratio): {r(zeta)} → {dampc or 'N/A'}\n"
239
+ f"- Poles: {poles_text}\n"
240
+ f"- Overshoot: ≈ {r(Mp,3)} %\n"
241
+ f"- Rise time Tr: ≈ {r(Tr)} s\n"
242
+ f"- Peak time Tp: ≈ {r(Tp)} s\n"
243
+ f"- Settling time Ts: ≈ {r(Ts)} s\n"
244
+ f"- Steady-state error (step): {r(ess)}"
245
+ )
246
+
247
+ # ---------- LLM prompt (deterministic, stability-focused) ----------
248
+ prompt = (
249
+ "You are a controls engineer. Explain what the OUTPUT VALUES MEAN.\n"
250
+ "Write CLEAR MARKDOWN with short, specific bullets. No repetition.\n\n"
251
+ "## Stability classification (what ζ and the poles tell you)\n"
252
+ "- State whether the system is underdamped, critically damped, or overdamped based on ζ and the pole pattern.\n"
253
+ "- Explain what complex vs real poles imply for oscillations and smoothness.\n\n"
254
+ "## What ωₙ means (speed)\n"
255
+ "- Explain that ωₙ sets the overall speed scale of the response (larger ωₙ → shorter Tr and Ts).\n\n"
256
+ "## What ζ means (smoothness vs overshoot)\n"
257
+ "- Interpret ζ ranges (<1, ≈1, >1) in terms of oscillation and overshoot.\n\n"
258
+ "## What each time/percent metric means\n"
259
+ "- Overshoot: how much the peak exceeds final value.\n"
260
+ "- Tr: time to go from low to near-final (e.g., 10–90%).\n"
261
+ "- Tp: time to first peak.\n"
262
+ "- Ts: time to settle within the chosen band.\n"
263
+ "- ess: final error for a step; with Ki>0 it is 0.\n\n"
264
+ "## How the poles relate to that behavior\n"
265
+ "- Connect pole real part to decay speed; imaginary part to oscillation frequency.\n\n"
266
+ "## Numeric snapshot\n"
267
+ f"{snapshot}\n"
268
+ )
269
+
270
+ # ---------- deterministic generation with anti-repetition ----------
271
+ gen = explainer(
272
+ prompt,
273
+ max_new_tokens=220,
274
+ do_sample=False,
275
+ temperature=0.0,
276
+ top_p=1.0,
277
+ top_k=0,
278
+ repetition_penalty=1.15,
279
+ no_repeat_ngram_size=4,
280
+ eos_token_id=_tokenizer.eos_token_id,
281
+ pad_token_id=_tokenizer.eos_token_id,
282
+ return_full_text=False
283
+ )[0]["generated_text"]
284
+
285
+ # ---------- SHORT-OUTPUT FALLBACK (your requested addition) ----------
286
+ MIN_WORDS = 30
287
+ if not gen or len(gen.split()) < MIN_WORDS:
288
+ gen = f"""## Stability classification
289
+ - ζ = {r(zeta)} → {dampc or 'N/A'}.
290
+
291
+ ## Meaning of ωₙ and ζ
292
+ - ωₙ = {r(wn)} rad/s sets the speed scale (larger ωₙ → faster rise/settle).
293
+ - ζ controls smoothness/overshoot: ζ<1 underdamped; ζ≈1 critically damped; ζ>1 overdamped.
294
+
295
+ ## Poles and behavior
296
+ - Poles: {poles_text}
297
+ - More negative real part → faster decay; nonzero imaginary part → oscillations.
298
+
299
+ ## Time-domain metrics
300
+ - Overshoot ≈ {r(Mp,3)} % | Tr ≈ {r(Tr)} s | Tp ≈ {r(Tp)} s | Ts ≈ {r(Ts)} s | ess = {r(ess)}
301
+
302
+ ## Tuning tip
303
+ - Raise Ki to increase ωₙ (speed). If overshoot or oscillation appears (ζ too low), add Kd or increase Kp to raise damping.
304
+ """
305
+
306
+ return dedup_lines(gen)
307
+
308
+ def run_calc(tau_s, Kp, Ki, Kd, step_amp, settling_pct):
309
+ x = PIDInputs(
310
+ tau_s=float(tau_s), Kp=float(Kp), Ki=float(Ki), Kd=float(Kd),
311
+ step_amplitude=float(step_amp), settling_pct=float(settling_pct) / 100.0 # slider in %, convert to fraction
312
+ )
313
+ structured = compute_pid(x)
314
+
315
+ # Display normalized form + metrics in a compact table
316
+ rows = []
317
+ for k, v in structured.get("normalized_second_order", {}).items():
318
+ rows.append(["2nd-order", k, v])
319
+ for k, v in structured.get("metrics", {}).items():
320
+ rows.append(["metrics", k, v])
321
+ df = pd.DataFrame(rows, columns=["section", "key", "value"])
322
+
323
+ explanation = explain_structured(structured)
324
+ return df, explanation, structured
325
+
326
+ with gr.Blocks(title="PID Controls Calculator (1st-Order Plant)", theme=gr.themes.Soft()) as demo:
327
+ gr.Markdown("# PID Feedback Controls — Deterministic Calculator")
328
+ gr.Markdown(
329
+ "Unity-feedback PID on a first-order plant G(s)=1/(τs+1). "
330
+ "We derive the equivalent 2nd-order parameters (ωₙ, ζ) and step-response metrics (overshoot, rise, peak, settling)."
331
+ )
332
+
333
+ with gr.Row():
334
+ with gr.Column():
335
+ tau_s = gr.Slider(0.01, 10.0, value=0.5, step=0.01, label="Plant time constant τ [s]")
336
+ Kp = gr.Slider(-0.9, 200.0, value=1.0, step=0.1, label="Kp")
337
+ Ki = gr.Slider(1e-6, 1e4, value=1.0, step=0.1, label="Ki")
338
+ Kd = gr.Slider(-0.009, 100.0, value=0.0, step=0.001, label="Kd")
339
+ step_amp = gr.Slider(0.1, 10.0, value=1.0, step=0.1, label="Step amplitude")
340
+ settling_pct = gr.Slider(0.5, 10.0, value=2.0, step=0.1, label="Settling band [%]")
341
+ go = gr.Button("Compute", variant="primary")
342
+
343
+ with gr.Column():
344
+ gr.Markdown("### Numerical Results")
345
+ table = gr.Dataframe(headers=["section", "key", "value"], interactive=False)
346
+ gr.Markdown("### Explain the Results")
347
+ explanation = gr.Markdown()
348
+ gr.Markdown("### Raw Structured Output")
349
+ json_out = gr.JSON(label="Structured JSON")
350
+
351
+ go.click(run_calc, inputs=[tau_s, Kp, Ki, Kd, step_amp, settling_pct],
352
+ outputs=[table, explanation, json_out])
353
+
354
+ if __name__ == "__main__":
355
+ demo.launch()