Skip to content

Commit 4691f8f

Browse files
committed
feat: pid_tunner
1 parent b0878ac commit 4691f8f

24 files changed

+3275
-46
lines changed

docs/pid_tuner_guide.md

Lines changed: 397 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,397 @@
1+
# PID Tuner Binary - Comprehensive Guide
2+
3+
## Overview
4+
5+
The PID Tuner is a specialized binary tool designed for automatic tuning of PID (Proportional-Integral-Derivative) controllers in thermal regulation systems. It uses classical control theory algorithms to analyze system step responses and calculate optimal PID parameters for stable and responsive temperature control.
6+
7+
### Key Features
8+
9+
- **Automated PID Parameter Calculation**: Uses proven algorithms (Ziegler-Nichols, Cohen-Coon)
10+
- **Step Response Analysis**: Performs controlled step tests to characterize system dynamics
11+
- **Safety-First Design**: Only works with mock drivers to prevent damage to real hardware
12+
- **Comprehensive Reporting**: Generates HTML reports with SVG charts and performance metrics
13+
- **Multiple Tuning Algorithms**: Choose the best method for your specific application
14+
15+
### Target Audience
16+
17+
This guide is intended for:
18+
- **Rust Developers**: Working on thermal control systems and PID implementations
19+
- **System Integrators**: Configuring photoacoustic equipment for production use
20+
- **Control Engineers**: Tuning PID parameters for optimal thermal regulation performance
21+
22+
## Quick Start
23+
24+
### Basic Usage
25+
26+
```bash
27+
# Tune a regulator using default Ziegler-Nichols method
28+
cargo run --bin pid_tuner -- --regulator-id dev_cell_temperature
29+
30+
# Tune with Cohen-Coon method and generate HTML report
31+
cargo run --bin pid_tuner -- \
32+
--regulator-id dev_cell_temperature \
33+
--method cohen-coon \
34+
--output tuning_report.html
35+
36+
# Custom step amplitude and duration
37+
cargo run --bin pid_tuner -- \
38+
--regulator-id dev_cell_temperature \
39+
--step-amplitude 8.0 \
40+
--duration 600 \
41+
--output detailed_report.html
42+
```
43+
44+
### Prerequisites
45+
46+
1. **Configuration File**: Ensure your `config.yaml` contains:
47+
- Thermal regulation enabled
48+
- Mock I2C bus configuration
49+
- Regulator definition with proper sensor and actuator mappings
50+
51+
2. **Safety Check**: The tuner will only work with mock drivers to prevent hardware damage during testing.
52+
53+
## Command Line Interface
54+
55+
### Arguments
56+
57+
| Argument | Short | Default | Description |
58+
|----------|-------|---------|-------------|
59+
| `--config` | `-c` | `config.yaml` | Path to configuration file |
60+
| `--regulator-id` | `-r` | *required* | ID of the thermal regulator to tune |
61+
| `--method` | `-m` | `ziegler-nichols` | Tuning algorithm to use |
62+
| `--output` | `-o` | *none* | Output HTML report file path |
63+
| `--step-amplitude` | `-s` | `5.0` | Step input amplitude (°C) |
64+
| `--duration` | `-d` | `300` | Test duration in seconds |
65+
| `--interactive` | `-i` | `false` | Enable interactive mode (future feature) |
66+
| `--verbose` | `-v` | `false` | Enable verbose logging |
67+
68+
### Tuning Methods
69+
70+
The tuner supports three algorithms:
71+
72+
- `ziegler-nichols`: Classical Ziegler-Nichols step response method
73+
- `cohen-coon`: Cohen-Coon method for processes with significant dead time
74+
- `manual`: Interactive manual tuning (not yet implemented)
75+
76+
## Tuning Algorithms
77+
78+
### Ziegler-Nichols Method
79+
80+
**Best for**: General-purpose applications with moderate dynamics.
81+
82+
The Ziegler-Nichols step response method is based on analyzing the system's reaction to a step input. It characterizes the process using three key parameters:
83+
84+
- **Process Gain (K)**: Ratio of output change to input change at steady state
85+
- **Time Constant (τ)**: Time for the system to reach 63.2% of its final value
86+
- **Dead Time (L)**: Time delay before the system begins to respond
87+
88+
#### Calculation Formulas
89+
90+
```
91+
Kp = 1.2 × (τ / (K × L))
92+
Ki = Kp / (2 × L)
93+
Kd = Kp × L / 2
94+
```
95+
96+
#### Characteristics
97+
98+
- **Pros**:
99+
- Simple and well-established
100+
- Good general-purpose performance
101+
- Works well for first-order plus dead time systems
102+
- **Cons**:
103+
- Can be aggressive (high overshoot)
104+
- May not be optimal for processes with large dead times
105+
- Limited performance for complex dynamics
106+
107+
#### Typical Applications
108+
109+
- Temperature control with moderate time constants
110+
- Systems with dead time < 25% of time constant
111+
- General industrial process control
112+
113+
### Cohen-Coon Method
114+
115+
**Best for**: Processes with significant dead time relative to time constant.
116+
117+
The Cohen-Coon method provides improved performance for processes where dead time is a significant portion of the total response time. It uses more sophisticated formulas that account for the dead time to time constant ratio.
118+
119+
#### Calculation Formulas
120+
121+
```
122+
L/τ ratio = Dead Time / Time Constant
123+
124+
Kp = (1/K) × (τ/L) × (16 + 3×(L/τ)) / (13 + 8×(L/τ))
125+
Ki = Kp / (L × (32 + 6×(L/τ)) / (13 + 8×(L/τ)))
126+
Kd = Kp × L × 4 / (11 + 2×(L/τ))
127+
```
128+
129+
#### Characteristics
130+
131+
- **Pros**:
132+
- Better performance for high dead time processes
133+
- More conservative than Ziegler-Nichols
134+
- Reduced overshoot and oscillation
135+
- **Cons**:
136+
- More complex calculations
137+
- May be slower responding than Ziegler-Nichols
138+
- Requires accurate dead time identification
139+
140+
#### Typical Applications
141+
142+
- Thermal systems with significant thermal mass
143+
- Processes with dead time > 25% of time constant
144+
- Systems requiring stable, non-oscillatory response
145+
146+
### Method Selection Guidelines
147+
148+
| Process Characteristics | Recommended Method | Reasoning |
149+
|------------------------|-------------------|-----------|
150+
| Fast thermal response, low dead time | Ziegler-Nichols | Simple, effective for responsive systems |
151+
| Slow thermal response, high thermal mass | Cohen-Coon | Better handling of dead time effects |
152+
| Critical stability requirements | Cohen-Coon | More conservative tuning |
153+
| General-purpose applications | Ziegler-Nichols | Well-established, good starting point |
154+
155+
## Step Response Analysis
156+
157+
### Process Identification
158+
159+
The tuner performs a step response test to identify system characteristics:
160+
161+
1. **Pre-stabilization**: 10 seconds at initial conditions
162+
2. **Step Application**: Sudden change in control output
163+
3. **Response Recording**: 1 Hz sampling of temperature response
164+
4. **Analysis**: Mathematical extraction of process parameters
165+
166+
### Key Metrics Extracted
167+
168+
| Metric | Description | Control Impact |
169+
|--------|-------------|----------------|
170+
| **Process Gain** | Steady-state output/input ratio | Determines proportional gain magnitude |
171+
| **Time Constant** | Time to reach 63.2% of final value | Affects integral and derivative timing |
172+
| **Dead Time** | Initial response delay | Critical for stability margins |
173+
| **Rise Time** | Time from 10% to 90% of final value | Indicates system responsiveness |
174+
| **Settling Time** | Time to reach ±2% of final value | Shows control effectiveness |
175+
| **Overshoot** | Maximum excursion beyond final value | Indicates stability margins |
176+
177+
### Performance Evaluation
178+
179+
The tuner automatically evaluates controller performance:
180+
181+
- **Overshoot > 20%**: Warning about potential instability
182+
- **Settling Time > 180s**: Suggestion to increase integral gain
183+
- **Steady-State Error > 5%**: Recommendation to increase integral action
184+
- **Good Balance**: Overshoot < 5% and settling time < 120s
185+
186+
## Configuration Requirements
187+
188+
### I2C Bus Configuration
189+
190+
```yaml
191+
thermal_regulation:
192+
enabled: true
193+
i2c_buses:
194+
mock_bus:
195+
bus_type: Mock
196+
device: "mock"
197+
pwm_controllers:
198+
- address: 0x40
199+
channels: 16
200+
frequency_hz: 1000
201+
adc_controllers:
202+
- address: 0x48
203+
channels: 4
204+
resolution: 16
205+
voltage_ref: 5.0
206+
```
207+
208+
### Regulator Configuration
209+
210+
```yaml
211+
regulators:
212+
- id: "dev_cell_temperature"
213+
name: "Development Cell Temperature"
214+
i2c_bus: "mock_bus"
215+
temperature_sensor:
216+
sensor_type: Ntc
217+
adc_address: 0x48
218+
adc_channel: 0
219+
# NTC thermistor parameters (10kΩ at 25°C, β=3977)
220+
ntc_beta: 3977.0
221+
ntc_r0: 10000.0
222+
ntc_t0: 25.0
223+
series_resistor: 10000.0
224+
supply_voltage: 5.0
225+
actuators:
226+
thermal_control:
227+
actuator_type: Resistive
228+
pwm_controller:
229+
address: 0x40
230+
channel: 0
231+
power_rating: 60.0 # DBK HPG-1/10-60x35-12-24V
232+
```
233+
234+
## Output and Reporting
235+
236+
### Console Output
237+
238+
The tuner provides comprehensive console output:
239+
240+
```
241+
🎯 PID Tuning Results (Ziegler-Nichols):
242+
╭─────────────────────────────────────────╮
243+
│ Kp = 2.458620 │
244+
│ Ki = 0.245862 │
245+
│ Kd = 6.146551 │
246+
╰─────────────────────────────────────────╯
247+
248+
📊 Performance Metrics:
249+
• Process Gain: 0.850
250+
• Time Constant: 90.0 s
251+
• Dead Time: 5.0 s
252+
• Rise Time: 45.2 s
253+
• Settling Time: 120.8 s
254+
• Overshoot: 12.3 %
255+
• Steady-State Error: 1.45 %
256+
257+
💡 Recommendations:
258+
✅ Good balance between stability and response time.
259+
```
260+
261+
### HTML Report Generation
262+
263+
When `--output` is specified, the tuner generates a comprehensive HTML report:
264+
265+
- **Executive Summary**: Tuning parameters and method used
266+
- **Step Response Chart**: SVG plot of temperature vs. time
267+
- **Performance Metrics**: Detailed analysis of system characteristics
268+
- **Parameter Comparison**: Side-by-side comparison if multiple methods are used
269+
- **Recommendations**: Specific guidance for parameter adjustment
270+
271+
## Implementation for Developers
272+
273+
### Mock Driver Integration
274+
275+
The PID tuner integrates with the mock thermal driver to provide realistic simulation:
276+
277+
```rust
278+
// Thermal properties for 1016g stainless steel 316 cell
279+
mass_g: 1016.0,
280+
specific_heat: 501.0, // J/kg·K for stainless steel 316
281+
thermal_conductivity: 16.2, // W/m·K
282+
heat_transfer_coefficient: 25.0, // W/m²·K
283+
```
284+
285+
### NTC Thermistor Simulation
286+
287+
The mock driver simulates a 10kΩ NTC thermistor (β=3977) with voltage divider:
288+
289+
```rust
290+
let r_ntc = r0 * ((beta * (1.0 / temp_k - 1.0 / t0)).exp());
291+
let v_adc = 5.0 * r_ntc / (10000.0 + r_ntc);
292+
let adc_raw = ((v_adc / 5.0) * 65535.0) as u16;
293+
```
294+
295+
### Heating Element Modeling
296+
297+
60W DBK HPG-1/10-60x35-12-24V resistive heater simulation:
298+
299+
```rust
300+
let heater_heat = self.heater_power / 100.0 * 60.0; // Watts
301+
let temp_change = total_heat_rate * dt / thermal_mass; // K
302+
```
303+
304+
## Best Practices
305+
306+
### For Rust Developers
307+
308+
1. **Test with Mock First**: Always use mock drivers for initial tuning
309+
2. **Validate Parameters**: Check that calculated parameters are within reasonable ranges
310+
3. **Monitor Performance**: Use the HTML reports to verify tuning effectiveness
311+
4. **Iterative Approach**: Start with conservative parameters and refine as needed
312+
313+
### For System Integrators
314+
315+
1. **Characterize Your System**: Understand your thermal mass, dead times, and response characteristics
316+
2. **Choose Appropriate Method**: Use Cohen-Coon for high dead time systems, Ziegler-Nichols for general use
317+
3. **Validate in Practice**: Test tuned parameters with real hardware under controlled conditions
318+
4. **Document Settings**: Keep records of tuning parameters and system characteristics
319+
320+
### Safety Considerations
321+
322+
- **Mock Driver Only**: Never run tuning on real hardware without proper safety measures
323+
- **Parameter Limits**: The tuner applies reasonable limits to prevent extreme values
324+
- **Gradual Implementation**: When applying tuned parameters to real hardware, start with reduced gains
325+
- **Monitor Stability**: Watch for oscillations or instability when implementing new parameters
326+
327+
## Troubleshooting
328+
329+
### Common Issues
330+
331+
| Problem | Cause | Solution |
332+
|---------|-------|----------|
333+
| "Regulator not found" | Incorrect regulator ID | Verify ID matches config.yaml |
334+
| "Not using mock driver" | Safety check failed | Ensure I2C bus is configured as Mock type |
335+
| "Process gain too small" | Insufficient step response | Increase step amplitude or check sensor |
336+
| "Invalid time constant" | Poor step response data | Increase test duration or check system |
337+
338+
### Debug Mode
339+
340+
Use `--verbose` flag for detailed logging:
341+
342+
```bash
343+
cargo run --bin pid_tuner -- \
344+
--regulator-id dev_cell_temperature \
345+
--verbose
346+
```
347+
348+
This provides detailed information about:
349+
- Step response data collection
350+
- Parameter calculation steps
351+
- Internal algorithm decisions
352+
- Thermal simulation updates
353+
354+
## Future Enhancements
355+
356+
### Planned Features
357+
358+
- **Interactive Manual Tuning**: Real-time parameter adjustment with live feedback
359+
- **Multiple Algorithm Comparison**: Automatic testing of all methods with comparison
360+
- **Advanced Algorithms**: Implementation of Lambda tuning, IMC, and other modern methods
361+
- **Closed-Loop Tuning**: Relay feedback and ultimate cycle methods
362+
- **Real Hardware Support**: Safe tuning procedures for production systems
363+
364+
### Extending the Tuner
365+
366+
The modular design allows easy extension:
367+
368+
```rust
369+
// Add new tuning algorithm
370+
pub struct MyCustomCalculator;
371+
372+
impl MyCustomCalculator {
373+
pub fn calculate_pid_parameters(metrics: &PerformanceMetrics) -> Result<PidParameters> {
374+
// Implement your algorithm
375+
}
376+
}
377+
```
378+
379+
## References
380+
381+
### Technical References
382+
383+
- Ziegler, J.G. and Nichols, N.B. (1942). "Optimum Settings for Automatic Controllers"
384+
- Cohen, G.H. and Coon, G.A. (1953). "Theoretical Consideration of Retarded Control"
385+
- Åström, Karl J. and Hägglund, Tore (2006). "Advanced PID Control"
386+
387+
### Related Documentation
388+
389+
- [Thermal Regulation Guide](regulation_thermique.md)
390+
- [Mock Driver Documentation](mock_driver_guide.md)
391+
- [Configuration Reference](config_reference.md)
392+
393+
## License
394+
395+
Copyright (c) 2025 Ronan LE MEILLAT, SCTG Development
396+
397+
This documentation is part of the rust-photoacoustic project and is licensed under the SCTG Development Non-Commercial License v1.0.

0 commit comments

Comments
 (0)