-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdrone_precision.py
More file actions
2101 lines (1885 loc) · 81.1 KB
/
Copy pathdrone_precision.py
File metadata and controls
2101 lines (1885 loc) · 81.1 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import argparse
import json
import logging
import math
import sys
import time
from dataclasses import asdict, dataclass
from pathlib import Path
from statistics import fmean, median
DOCS_URL = "https://docs.robolink.com/docs/CoDroneEDU/Python/Drone-Function-Documentation"
LOG_DIR = Path(__file__).resolve().parent / "flight_logs"
LOG_DIR.mkdir(parents=True, exist_ok=True)
PID_PROFILE_PATH = LOG_DIR / "last_pid_profile.json"
HISTORY_ANALYSIS_PATH = LOG_DIR / "last_history_analysis.json"
FIXED_CONTROL_SIGNS = {"pitch": 1.0, "roll": -1.0, "throttle": 1.0, "yaw": -1.0}
DEFAULT_MAX_PITCH = 100
DEFAULT_BRAKE_PITCH = 100
DEFAULT_MAX_ROLL = 100
DEFAULT_BRAKE_ROLL = 100
DEFAULT_MAX_THROTTLE = 80
DEFAULT_BRAKE_THROTTLE = 80
DEFAULT_BRAKE_ACCEL_MM_S2 = 90.0
DEFAULT_TIMEOUT_SEC = 35.0
BRAKE_MARGIN_MM = 35.0
BRAKE_RELEASE_SPEED_MM_S = 25.0
def _clamp(value: float, lower: float, upper: float) -> float:
return max(lower, min(upper, value))
def _signed_limit(value: float, limit: float) -> float:
return _clamp(value, -abs(limit), abs(limit))
def _sign(value: float) -> float:
if value > 0.0:
return 1.0
if value < 0.0:
return -1.0
return 0.0
def _wrap_angle_deg(angle_deg: float) -> float:
return (angle_deg + 180.0) % 360.0 - 180.0
def rotate_world_to_body(x_value: float, y_value: float, yaw_deg: float) -> tuple[float, float]:
yaw_rad = math.radians(yaw_deg)
cos_yaw = math.cos(yaw_rad)
sin_yaw = math.sin(yaw_rad)
forward_value = (x_value * cos_yaw) + (y_value * sin_yaw)
right_value = (-x_value * sin_yaw) + (y_value * cos_yaw)
return forward_value, right_value
def rotate_body_to_world(forward_value: float, right_value: float, yaw_deg: float) -> tuple[float, float]:
yaw_rad = math.radians(yaw_deg)
cos_yaw = math.cos(yaw_rad)
sin_yaw = math.sin(yaw_rad)
x_value = (forward_value * cos_yaw) - (right_value * sin_yaw)
y_value = (forward_value * sin_yaw) + (right_value * cos_yaw)
return x_value, y_value
def calculate_stopping_distance_mm(
speed_mm_s: float,
brake_accel_mm_s2: float,
sensor_latency_sec: float,
margin_mm: float = BRAKE_MARGIN_MM,
) -> float:
speed = max(0.0, speed_mm_s)
acceleration = max(brake_accel_mm_s2, 1.0)
latency = max(sensor_latency_sec, 0.0)
return (speed * speed) / (2.0 * acceleration) + (speed * latency) + margin_mm
def _import_drone_class():
try:
from codrone_edu.drone import Drone as drone_class
return drone_class
except ModuleNotFoundError as exc:
raise ModuleNotFoundError(
"codrone_edu が見つかりません。.venv を有効化してから実行するか、"
"CoDrone EDU の Python ライブラリをインストールしてください。"
) from exc
def profile_key_for_distance(target_distance_mm: float) -> str:
rounded_mm = max(0, int(round(abs(target_distance_mm))))
return f"{rounded_mm}mm"
def pid_profile_path_for_key(profile_key: str) -> Path:
return LOG_DIR / f"last_pid_profile_{profile_key}.json"
def _list_distance_profile_paths() -> list[Path]:
return sorted(
path
for path in LOG_DIR.glob("last_pid_profile_*mm.json")
if path.name not in {"last_pid_profile.json"}
)
def _distance_from_profile_path(path: Path) -> float | None:
stem = path.stem.removeprefix("last_pid_profile_").removesuffix("mm")
try:
return float(stem)
except ValueError:
return None
def is_settled_state(
*,
error_x_mm: float,
error_y_mm: float,
error_z_mm: float,
error_yaw_deg: float,
x_velocity_mm_s: float,
y_velocity_mm_s: float,
z_velocity_mm_s: float,
) -> bool:
return (
abs(error_x_mm) <= 8.0
and abs(error_y_mm) <= 12.0
and abs(error_z_mm) <= 12.0
and abs(error_yaw_deg) <= 5.0
and abs(x_velocity_mm_s) <= 25.0
and abs(y_velocity_mm_s) <= 25.0
and abs(z_velocity_mm_s) <= 20.0
)
def default_pid_profile() -> dict:
return {
"pitch": {
"kp": 0.110,
"ki": 0.00030,
"kd": 0.010,
"kv": 0.080,
"output_limit": 68.0,
"integral_limit": 600.0,
"min_output": 6.0,
"min_output_error": 30.0,
},
"roll": {
"kp": 0.150,
"ki": 0.00055,
"kd": 0.012,
"kv": 0.120,
"output_limit": 42.0,
"integral_limit": 500.0,
"min_output": 6.0,
"min_output_error": 28.0,
},
"throttle": {
"kp": 0.205,
"ki": 0.00520,
"kd": 0.014,
"kv": 0.180,
"output_limit": 42.0,
"integral_limit": 450.0,
"min_output": 5.0,
"min_output_error": 18.0,
},
"yaw": {
"kp": 0.760,
"ki": 0.00020,
"kd": 0.030,
"kv": 0.070,
"output_limit": 28.0,
"integral_limit": 60.0,
"min_output": 0.0,
"min_output_error": 0.0,
},
"signs": dict(FIXED_CONTROL_SIGNS),
}
def load_pid_profile(target_distance_mm: float) -> dict:
profile = default_pid_profile()
target_magnitude = abs(target_distance_mm)
exact_path = pid_profile_path_for_key(profile_key_for_distance(target_distance_mm))
candidate_paths: list[Path] = []
if exact_path.exists():
candidate_paths.append(exact_path)
nearest_paths = sorted(
(
(abs(distance_mm - target_magnitude), path)
for path in _list_distance_profile_paths()
for distance_mm in [_distance_from_profile_path(path)]
if distance_mm is not None and path != exact_path
),
key=lambda item: item[0],
)
candidate_paths.extend(path for _, path in nearest_paths[:3])
candidate_paths.append(PID_PROFILE_PATH)
raw = None
for path in candidate_paths:
if not path.exists():
continue
try:
raw = json.loads(path.read_text(encoding="utf-8"))
break
except Exception:
continue
if raw is None:
return profile
for axis_name, config in profile.items():
if axis_name == "signs":
continue
raw_config = raw.get(axis_name)
if not isinstance(raw_config, dict):
continue
for key in config:
if key in raw_config:
try:
config[key] = float(raw_config[key])
except (TypeError, ValueError):
pass
# Control-axis polarity is fixed for this hardware and should not drift by profile.
profile["signs"] = dict(FIXED_CONTROL_SIGNS)
# Old learned profiles can contain limits that permit severe wind-up. Keep
# learned gains, but normalize safety-critical bounds on every load.
profile["pitch"]["integral_limit"] = min(profile["pitch"]["integral_limit"], 600.0)
profile["roll"]["integral_limit"] = min(profile["roll"]["integral_limit"], 500.0)
profile["throttle"]["integral_limit"] = min(profile["throttle"]["integral_limit"], 450.0)
profile["yaw"]["integral_limit"] = min(profile["yaw"]["integral_limit"], 60.0)
profile["pitch"]["kp"] = _clamp(profile["pitch"]["kp"], 0.100, 0.150)
profile["pitch"]["output_limit"] = _clamp(profile["pitch"]["output_limit"], 42.0, 50.0)
profile["roll"]["kp"] = _clamp(profile["roll"]["kp"], 0.145, 0.160)
profile["roll"]["ki"] = _clamp(profile["roll"]["ki"], 0.00045, 0.00070)
profile["roll"]["output_limit"] = _clamp(profile["roll"]["output_limit"], 40.0, 44.0)
profile["roll"]["min_output"] = _clamp(profile["roll"]["min_output"], 6.0, 8.0)
profile["roll"]["min_output_error"] = max(profile["roll"].get("min_output_error", 0.0), 28.0)
profile["throttle"]["kp"] = max(profile["throttle"]["kp"], 0.205)
profile["throttle"]["ki"] = max(profile["throttle"]["ki"], 0.00520)
profile["throttle"]["output_limit"] = max(profile["throttle"]["output_limit"], 42.0)
profile["throttle"]["min_output"] = max(profile["throttle"]["min_output"], 5.0)
profile["throttle"]["min_output_error"] = max(profile["throttle"].get("min_output_error", 0.0), 18.0)
profile["throttle"]["kd"] = min(profile["throttle"]["kd"], 0.025)
profile["throttle"]["kv"] = min(profile["throttle"]["kv"], 0.18)
profile["yaw"]["kp"] = _clamp(profile["yaw"]["kp"], 0.70, 0.95)
profile["yaw"]["kv"] = _clamp(profile["yaw"]["kv"], 0.06, 0.12)
profile["yaw"]["output_limit"] = max(profile["yaw"]["output_limit"], 28.0)
return profile
def save_pid_profile(profile: dict) -> None:
PID_PROFILE_PATH.write_text(json.dumps(profile, ensure_ascii=False, indent=2), encoding="utf-8")
def save_pid_profile_for_distance(profile: dict, target_distance_mm: float) -> None:
profile_key = profile_key_for_distance(target_distance_mm)
pid_profile_path_for_key(profile_key).write_text(json.dumps(profile, ensure_ascii=False, indent=2), encoding="utf-8")
save_pid_profile(profile)
@dataclass
class SensorSnapshot:
wall_time: float
pos_age_sec: float
motion_age_sec: float
pos_sensor_time: float
motion_sensor_time: float
x_mm: float
y_mm: float
z_mm: float
roll_deg: float
pitch_deg: float
yaw_deg: float
accel_x: float
accel_y: float
accel_z: float
gyro_roll: float
gyro_pitch: float
gyro_yaw: float
@dataclass
class StateEstimate:
x_mm: float
y_mm: float
z_mm: float
yaw_deg: float
x_velocity_mm_s: float
y_velocity_mm_s: float
z_velocity_mm_s: float
yaw_rate_deg_s: float
pos_fresh: bool
motion_fresh: bool
stale_cycles: int
stale_duration_sec: float
last_position_update_wall_time: float
@dataclass
class ControlSample:
step: int
wall_time: float
elapsed_sec: float
dt_sec: float
pos_fresh: bool
motion_fresh: bool
stale_cycles: int
stale_duration_sec: float
target_x_mm: float
target_y_mm: float
target_z_mm: float
target_yaw_deg: float
x_mm: float
y_mm: float
z_mm: float
yaw_deg: float
error_x_mm: float
error_y_mm: float
error_z_mm: float
error_yaw_deg: float
x_velocity_mm_s: float
y_velocity_mm_s: float
z_velocity_mm_s: float
yaw_rate_deg_s: float
pitch_cmd: int
roll_cmd: int
throttle_cmd: int
yaw_cmd: int
pitch_limit: float
roll_limit: float
throttle_limit: float
yaw_limit: float
pitch_integral: float
roll_integral: float
throttle_integral: float
yaw_integral: float
control_phase: str
predicted_remaining_x_mm: float
stopping_distance_x_mm: float
control_phase_y: str = "settle"
control_phase_z: str = "settle"
body_error_x_mm: float = 0.0
body_error_y_mm: float = 0.0
body_velocity_x_mm_s: float = 0.0
body_velocity_y_mm_s: float = 0.0
predicted_remaining_y_mm: float = 0.0
predicted_remaining_z_mm: float = 0.0
stopping_distance_y_mm: float = BRAKE_MARGIN_MM
stopping_distance_z_mm: float = BRAKE_MARGIN_MM
@dataclass
class FlightSummary:
samples: int
duration_sec: float
target_x_mm: float
target_y_mm: float
target_z_mm: float
final_error_x_mm: float
final_error_y_mm: float
final_error_z_mm: float
final_error_yaw_deg: float
max_abs_error_x_mm: float
max_abs_error_y_mm: float
max_abs_error_z_mm: float
mean_abs_error_x_mm: float
mean_abs_error_y_mm: float
mean_abs_error_z_mm: float
peak_speed_x_mm_s: float
peak_speed_y_mm_s: float
peak_speed_z_mm_s: float
stale_ratio: float
oscillation_count_x: int
oscillation_count_y: int
oscillation_count_z: int
settling_time_sec: float | None
termination_reason: str
brake_start_error_x_mm: float | None
brake_start_speed_x_mm_s: float | None
peak_abs_pitch_cmd: int
@dataclass
class HistoryAnalysis:
runs_analyzed: int
median_final_error_x_mm: float
median_final_error_y_mm: float
median_final_error_z_mm: float
median_duration_sec: float
median_stale_ratio: float
@dataclass
class FlightCommand:
target_x_mm: float = 0.0
target_y_mm: float = 0.0
target_z_mm: float = 0.0
target_yaw_deg: float = 0.0
timeout_sec: float = DEFAULT_TIMEOUT_SEC
loop_period_sec: float = 0.06
settle_time_sec: float = 0.5
history_limit: int = 8
auto_tune: bool = True
profile_distance_mm: float | None = None
max_pitch: int = DEFAULT_MAX_PITCH
brake_pitch: int = DEFAULT_BRAKE_PITCH
max_roll: int = DEFAULT_MAX_ROLL
brake_roll: int = DEFAULT_BRAKE_ROLL
max_throttle: int = DEFAULT_MAX_THROTTLE
brake_throttle: int = DEFAULT_BRAKE_THROTTLE
brake_accel_mm_s2: float = DEFAULT_BRAKE_ACCEL_MM_S2
@property
def profile_target_distance_mm(self) -> float:
if self.profile_distance_mm is not None:
return self.profile_distance_mm
return self.target_x_mm
@dataclass
class AxisRapidState:
axis_name: str
command_name: str
direction: float
initial_abs_error: float
min_rapid_distance_mm: float
phase: str
last_fresh_speed_toward: float = 0.0
predicted_remaining_mm: float = 0.0
stopping_distance_mm: float = BRAKE_MARGIN_MM
best_abs_error_mm: float = 0.0
runaway_count: int = 0
reverse_fresh_count: int = 0
rapid_passes: int = 1
guard_grace_cycles: int = 0
class PIDController:
def __init__(
self,
*,
kp: float,
ki: float,
kd: float,
kv: float,
output_limit: float,
integral_limit: float,
min_output: float,
) -> None:
self.base_kp = kp
self.base_ki = ki
self.base_kd = kd
self.base_kv = kv
self.output_limit = output_limit
self.integral_limit = integral_limit
self.min_output = min_output
self.integral = 0.0
self.prev_error = 0.0
self.prev_measurement = 0.0
self.prev_measurement_rate = 0.0
self._has_prev = False
def reset(self) -> None:
self.integral = 0.0
self.prev_error = 0.0
self.prev_measurement = 0.0
self.prev_measurement_rate = 0.0
self._has_prev = False
def compute(
self,
*,
error: float,
measurement: float,
measurement_rate: float,
dt: float,
output_limit: float,
min_output: float,
min_output_error: float = 0.0,
gain_scale: float = 1.0,
allow_integral: bool = True,
) -> float:
if dt <= 0.0:
return 0.0
kp = self.base_kp * gain_scale
ki = self.base_ki * gain_scale
kd = self.base_kd * gain_scale
kv = self.base_kv * gain_scale
error_rate = 0.0 if not self._has_prev else (error - self.prev_error) / dt
measurement_accel = 0.0 if not self._has_prev else (measurement_rate - self.prev_measurement_rate) / dt
derivative_term = (0.60 * error_rate) - (0.40 * measurement_accel)
if allow_integral:
candidate_integral = _clamp(self.integral + error * dt, -self.integral_limit, self.integral_limit)
candidate_output = (
(kp * error)
+ (ki * candidate_integral)
+ (kd * derivative_term)
- (kv * measurement_rate)
)
# Integrate while unsaturated, or when the error would pull a
# saturated command back toward the controllable range.
if abs(candidate_output) <= output_limit or candidate_output * error < 0.0:
self.integral = candidate_integral
else:
self.integral *= 0.92
output = (kp * error) + (ki * self.integral) + (kd * derivative_term) - (kv * measurement_rate)
output = _signed_limit(output, output_limit)
if min_output > 0.0 and abs(error) >= min_output_error and abs(output) < min_output:
output = _sign(error) * min_output
self.prev_error = error
self.prev_measurement = measurement
self.prev_measurement_rate = measurement_rate
self._has_prev = True
self.output_limit = output_limit
self.min_output = min_output
return _signed_limit(output, output_limit)
class FlightLogWriter:
def __init__(self, log_dir: Path) -> None:
stamp = time.strftime("%Y%m%d_%H%M%S")
self.log_path = log_dir / f"pid_flight_{stamp}.jsonl"
self._fh = self.log_path.open("w", encoding="utf-8")
def write(self, event: str, payload: dict) -> None:
self._fh.write(json.dumps({"event": event, "logged_at": time.time(), **payload}, ensure_ascii=False) + "\n")
self._fh.flush()
def close(self) -> None:
if not self._fh.closed:
self._fh.close()
def __enter__(self) -> "FlightLogWriter":
return self
def __exit__(self, exc_type, exc, tb) -> bool:
self.close()
return False
class FlightLogAnalyzer:
@staticmethod
def summarize(
samples: list[ControlSample],
termination_reason: str = "unknown",
) -> FlightSummary | None:
if not samples:
return None
last = samples[-1]
brake_sample = next((sample for sample in samples if sample.control_phase == "brake"), None)
return FlightSummary(
samples=len(samples),
duration_sec=last.elapsed_sec,
target_x_mm=last.target_x_mm - samples[0].x_mm,
target_y_mm=last.target_y_mm - samples[0].y_mm,
target_z_mm=last.target_z_mm - samples[0].z_mm,
final_error_x_mm=last.error_x_mm,
final_error_y_mm=last.error_y_mm,
final_error_z_mm=last.error_z_mm,
final_error_yaw_deg=last.error_yaw_deg,
max_abs_error_x_mm=max(abs(s.error_x_mm) for s in samples),
max_abs_error_y_mm=max(abs(s.error_y_mm) for s in samples),
max_abs_error_z_mm=max(abs(s.error_z_mm) for s in samples),
mean_abs_error_x_mm=fmean(abs(s.error_x_mm) for s in samples),
mean_abs_error_y_mm=fmean(abs(s.error_y_mm) for s in samples),
mean_abs_error_z_mm=fmean(abs(s.error_z_mm) for s in samples),
peak_speed_x_mm_s=max(abs(s.x_velocity_mm_s) for s in samples),
peak_speed_y_mm_s=max(abs(s.y_velocity_mm_s) for s in samples),
peak_speed_z_mm_s=max(abs(s.z_velocity_mm_s) for s in samples),
stale_ratio=sum(1 for s in samples if not s.pos_fresh) / len(samples),
oscillation_count_x=FlightLogAnalyzer._count_sign_changes([s.error_x_mm for s in samples]),
oscillation_count_y=FlightLogAnalyzer._count_sign_changes([s.error_y_mm for s in samples]),
oscillation_count_z=FlightLogAnalyzer._count_sign_changes([s.error_z_mm for s in samples]),
settling_time_sec=FlightLogAnalyzer._estimate_settling_time(samples),
termination_reason=termination_reason,
brake_start_error_x_mm=None if brake_sample is None else brake_sample.error_x_mm,
brake_start_speed_x_mm_s=None if brake_sample is None else brake_sample.x_velocity_mm_s,
peak_abs_pitch_cmd=max(abs(sample.pitch_cmd) for sample in samples),
)
@staticmethod
def _count_sign_changes(values: list[float]) -> int:
sign_changes = 0
previous = _sign(values[0])
for value in values[1:]:
current = _sign(value)
if previous != 0.0 and current != 0.0 and previous != current:
sign_changes += 1
if current != 0.0:
previous = current
return sign_changes
@staticmethod
def _estimate_settling_time(samples: list[ControlSample]) -> float | None:
stable_since = None
for sample in samples:
stable = is_settled_state(
error_x_mm=sample.error_x_mm,
error_y_mm=sample.error_y_mm,
error_z_mm=sample.error_z_mm,
error_yaw_deg=sample.error_yaw_deg,
x_velocity_mm_s=sample.x_velocity_mm_s,
y_velocity_mm_s=sample.y_velocity_mm_s,
z_velocity_mm_s=sample.z_velocity_mm_s,
)
if stable:
if stable_since is None:
stable_since = sample.elapsed_sec
elif sample.elapsed_sec - stable_since >= 0.5:
return stable_since
else:
stable_since = None
return None
@staticmethod
def analyze_history(
log_dir: Path,
limit: int = 8,
target_distance_mm: float | None = None,
) -> HistoryAnalysis | None:
summaries: list[dict] = []
for path in reversed(sorted(log_dir.glob("pid_flight_*.jsonl"))):
summary = None
with path.open(encoding="utf-8") as fh:
for line in fh:
record = json.loads(line)
if record.get("event") == "summary":
summary = record
if summary is not None:
if target_distance_mm is not None:
logged_target = abs(float(summary.get("target_x_mm", 0.0)))
match_tolerance = max(25.0, abs(target_distance_mm) * 0.10)
if abs(logged_target - abs(target_distance_mm)) > match_tolerance:
continue
summaries.append(summary)
if len(summaries) >= limit:
break
if not summaries:
return None
return HistoryAnalysis(
runs_analyzed=len(summaries),
median_final_error_x_mm=median(float(item["final_error_x_mm"]) for item in summaries),
median_final_error_y_mm=median(float(item["final_error_y_mm"]) for item in summaries),
median_final_error_z_mm=median(float(item["final_error_z_mm"]) for item in summaries),
median_duration_sec=median(float(item["duration_sec"]) for item in summaries),
median_stale_ratio=median(float(item.get("stale_ratio", 0.0)) for item in summaries),
)
def adjust_pid_profile(profile: dict, summary: FlightSummary | None) -> dict:
if summary is None:
return profile
tuned = json.loads(json.dumps(profile))
pitch = tuned["pitch"]
roll = tuned["roll"]
throttle = tuned["throttle"]
yaw = tuned["yaw"]
if abs(summary.final_error_x_mm) > 25.0:
pitch["kp"] *= 1.05
pitch["kv"] *= 0.98
if summary.oscillation_count_x >= 3:
pitch["kp"] *= 0.94
pitch["kd"] *= 1.08
pitch["kv"] *= 1.06
if abs(summary.final_error_y_mm) > 18.0:
roll["kp"] *= 1.04
roll["ki"] *= 1.03
if summary.oscillation_count_y >= 3:
roll["kp"] *= 0.95
roll["kd"] *= 1.07
roll["kv"] *= 1.06
if abs(summary.final_error_z_mm) > 15.0:
if summary.peak_speed_z_mm_s > 55.0:
# CoDrone altitude feedback has enough delay that stronger D/velocity
# feedback causes command reversal and sustained hunting.
throttle["kp"] *= 0.96
throttle["ki"] *= 0.85
throttle["kv"] *= 0.94
throttle["kd"] *= 0.90
else:
throttle["kp"] *= 1.02
throttle["ki"] *= 1.01
if summary.oscillation_count_z >= 3:
throttle["kp"] *= 0.95
throttle["kd"] *= 1.08
throttle["kv"] *= 1.06
if abs(summary.final_error_yaw_deg) > 5.0:
yaw["kp"] *= 1.03
yaw["kd"] *= 1.03
for axis_name, kp_range, ki_range, kd_range, kv_range in (
("pitch", (0.05, 0.22), (0.0, 0.004), (0.0, 0.08), (0.02, 0.25)),
("roll", (0.06, 0.24), (0.0, 0.006), (0.0, 0.08), (0.03, 0.30)),
("throttle", (0.08, 0.28), (0.0, 0.012), (0.0, 0.025), (0.04, 0.18)),
("yaw", (0.20, 0.90), (0.0, 0.01), (0.0, 0.12), (0.01, 0.20)),
):
config = tuned[axis_name]
config["kp"] = _clamp(config["kp"], *kp_range)
config["ki"] = _clamp(config["ki"], *ki_range)
config["kd"] = _clamp(config["kd"], *kd_range)
config["kv"] = _clamp(config["kv"], *kv_range)
return tuned
class PrecisionDroneController:
def __init__(
self,
logger: logging.Logger | None = None,
pid_profile: dict | None = None,
) -> None:
self.logger = logger or logging.getLogger("precision_drone")
self.drone = _import_drone_class()()
self.is_flying = False
self.log_writer: FlightLogWriter | None = None
self.profile = pid_profile or default_pid_profile()
self.pitch_pid = self._make_pid(self.profile["pitch"])
self.roll_pid = self._make_pid(self.profile["roll"])
self.throttle_pid = self._make_pid(self.profile["throttle"])
self.yaw_pid = self._make_pid(self.profile["yaw"])
self.pitch_sign = float(FIXED_CONTROL_SIGNS["pitch"])
self.roll_sign = float(FIXED_CONTROL_SIGNS["roll"])
self.throttle_sign = float(FIXED_CONTROL_SIGNS["throttle"])
self.yaw_sign = float(FIXED_CONTROL_SIGNS["yaw"])
@staticmethod
def _make_pid(config: dict) -> PIDController:
return PIDController(
kp=float(config["kp"]),
ki=float(config["ki"]),
kd=float(config.get("kd", 0.0)),
kv=float(config.get("kv", 0.0)),
output_limit=float(config["output_limit"]),
integral_limit=float(config["integral_limit"]),
min_output=float(config.get("min_output", 0.0)),
)
def open_log(self) -> FlightLogWriter:
self.log_writer = FlightLogWriter(LOG_DIR)
self.log_writer.write("metadata", {"docs_url": DOCS_URL, "profile": self.profile})
return self.log_writer
def initialize_and_takeoff(self) -> None:
self.logger.info("ドローンに接続します")
self.drone.pair()
battery_level = self.drone.get_battery()
self.logger.info("バッテリー残量: %s%%", battery_level)
if battery_level < 20:
raise RuntimeError(f"バッテリー残量が不足しています: {battery_level}%")
self.logger.info("ジャイロを再初期化します")
self.drone.reset_gyro()
self.logger.info("離陸します")
self.drone.reset_move_values()
self.drone.takeoff()
self.is_flying = True
self.drone.hover(1.0)
self.drone.reset_move_values()
self.logger.info("使用ドキュメント: %s", DOCS_URL)
def read_snapshot(self, delay: float = 0.01) -> SensorSnapshot:
position = self.drone.get_position_data(delay=delay)
motion = self.drone.get_motion_data(delay=delay)
now = time.time()
return SensorSnapshot(
wall_time=now,
pos_age_sec=max(0.0, float(position[0])),
motion_age_sec=max(0.0, float(motion[0])),
pos_sensor_time=float(position[0]),
motion_sensor_time=float(motion[0]),
x_mm=float(position[1]) * 1000.0,
y_mm=float(position[2]) * 1000.0,
z_mm=float(position[3]) * 1000.0,
roll_deg=float(motion[7]),
pitch_deg=float(motion[8]),
yaw_deg=float(motion[9]),
accel_x=float(motion[1]),
accel_y=float(motion[2]),
accel_z=float(motion[3]),
gyro_roll=float(motion[4]),
gyro_pitch=float(motion[5]),
gyro_yaw=float(motion[6]),
)
def acquire_reference_snapshot(
self,
*,
minimum_altitude_mm: float = 150.0,
timeout_sec: float = 3.0,
required_fresh_samples: int = 3,
) -> SensorSnapshot:
deadline = time.perf_counter() + timeout_sec
fresh_snapshots: list[SensorSnapshot] = []
latest_snapshot = self.read_snapshot()
while time.perf_counter() < deadline:
snapshot = self.read_snapshot()
latest_snapshot = snapshot
position_looks_valid = snapshot.z_mm >= minimum_altitude_mm or (
abs(snapshot.x_mm) > 1.0 or abs(snapshot.y_mm) > 1.0
)
if position_looks_valid:
fresh_snapshots.append(snapshot)
if len(fresh_snapshots) >= required_fresh_samples:
break
time.sleep(0.03)
if not fresh_snapshots:
self.logger.warning(
"基準位置の新鮮な取得に失敗したため、最後のスナップショットを使います x=%.1f y=%.1f z=%.1f",
latest_snapshot.x_mm,
latest_snapshot.y_mm,
latest_snapshot.z_mm,
)
return latest_snapshot
return SensorSnapshot(
wall_time=fresh_snapshots[-1].wall_time,
pos_age_sec=fmean(item.pos_age_sec for item in fresh_snapshots),
motion_age_sec=fmean(item.motion_age_sec for item in fresh_snapshots),
pos_sensor_time=fresh_snapshots[-1].pos_sensor_time,
motion_sensor_time=fresh_snapshots[-1].motion_sensor_time,
x_mm=fmean(item.x_mm for item in fresh_snapshots),
y_mm=fmean(item.y_mm for item in fresh_snapshots),
z_mm=fmean(item.z_mm for item in fresh_snapshots),
roll_deg=fmean(item.roll_deg for item in fresh_snapshots),
pitch_deg=fmean(item.pitch_deg for item in fresh_snapshots),
yaw_deg=fmean(item.yaw_deg for item in fresh_snapshots),
accel_x=fmean(item.accel_x for item in fresh_snapshots),
accel_y=fmean(item.accel_y for item in fresh_snapshots),
accel_z=fmean(item.accel_z for item in fresh_snapshots),
gyro_roll=fmean(item.gyro_roll for item in fresh_snapshots),
gyro_pitch=fmean(item.gyro_pitch for item in fresh_snapshots),
gyro_yaw=fmean(item.gyro_yaw for item in fresh_snapshots),
)
def stop_and_hover(self, duration: float = 0.25) -> None:
self.drone.reset_move_values()
self.drone.hover(duration)
def _compute_state_estimate(
self,
snapshot: SensorSnapshot,
previous_snapshot: SensorSnapshot | None,
previous_state: StateEstimate | None,
) -> StateEstimate:
pos_fresh = previous_snapshot is None or snapshot.pos_sensor_time != previous_snapshot.pos_sensor_time
motion_fresh = previous_snapshot is None or snapshot.motion_sensor_time != previous_snapshot.motion_sensor_time
if previous_state is None or previous_snapshot is None:
return StateEstimate(
x_mm=snapshot.x_mm,
y_mm=snapshot.y_mm,
z_mm=snapshot.z_mm,
yaw_deg=snapshot.yaw_deg,
x_velocity_mm_s=0.0,
y_velocity_mm_s=0.0,
z_velocity_mm_s=0.0,
yaw_rate_deg_s=snapshot.gyro_yaw,
pos_fresh=pos_fresh,
motion_fresh=motion_fresh,
stale_cycles=0,
stale_duration_sec=0.0,
last_position_update_wall_time=snapshot.wall_time,
)
if pos_fresh:
# Position packets often arrive slower than the control loop. Use
# the interval since the last fresh packet, otherwise velocity is
# exaggerated after every stale sequence.
dt = max(snapshot.wall_time - previous_state.last_position_update_wall_time, 0.001)
raw_vx = (snapshot.x_mm - previous_state.x_mm) / dt
raw_vy = (snapshot.y_mm - previous_state.y_mm) / dt
raw_vz = (snapshot.z_mm - previous_state.z_mm) / dt
alpha = 0.40
x_velocity = (alpha * raw_vx) + ((1.0 - alpha) * previous_state.x_velocity_mm_s)
y_velocity = (alpha * raw_vy) + ((1.0 - alpha) * previous_state.y_velocity_mm_s)
z_velocity = (alpha * raw_vz) + ((1.0 - alpha) * previous_state.z_velocity_mm_s)
stale_cycles = 0
stale_duration_sec = 0.0
last_position_update_wall_time = snapshot.wall_time
else:
x_velocity = previous_state.x_velocity_mm_s * 0.92
y_velocity = previous_state.y_velocity_mm_s * 0.92
z_velocity = previous_state.z_velocity_mm_s * 0.92
stale_cycles = previous_state.stale_cycles + 1
last_position_update_wall_time = previous_state.last_position_update_wall_time
stale_duration_sec = max(snapshot.wall_time - last_position_update_wall_time, 0.0)
return StateEstimate(
x_mm=snapshot.x_mm,
y_mm=snapshot.y_mm,
z_mm=snapshot.z_mm,
yaw_deg=snapshot.yaw_deg,
x_velocity_mm_s=x_velocity,
y_velocity_mm_s=y_velocity,
z_velocity_mm_s=z_velocity,
yaw_rate_deg_s=snapshot.gyro_yaw,
pos_fresh=pos_fresh,
motion_fresh=motion_fresh,
stale_cycles=stale_cycles,
stale_duration_sec=stale_duration_sec,
last_position_update_wall_time=last_position_update_wall_time,
)
@staticmethod
def _command_limit(error_mm: float, base_limit: float, near_limit: float, near_band_mm: float) -> float:
magnitude = abs(error_mm)
if magnitude >= near_band_mm:
return base_limit
ratio = magnitude / max(near_band_mm, 1.0)
return near_limit + ((base_limit - near_limit) * math.sqrt(max(ratio, 0.0)))
def _axis_command(
self,
*,
pid: PIDController,
config: dict,
error: float,
measurement: float,
measurement_rate: float,
dt: float,
sign: float,
output_limit: float,
gain_scale: float,
allow_integral: bool,
) -> int:
output = pid.compute(
error=error,
measurement=measurement,
measurement_rate=measurement_rate,
dt=dt,
output_limit=output_limit,
min_output=float(config.get("min_output", 0.0)),
min_output_error=float(config.get("min_output_error", 0.0)),
gain_scale=gain_scale,
allow_integral=allow_integral,
)
return int(round(output * sign))
def _build_rapid_state(
self,
*,
axis_name: str,
command_name: str,
target_mm: float,
min_rapid_distance_mm: float,
) -> AxisRapidState:
initial_abs_error = abs(target_mm)
phase = "acquire" if initial_abs_error >= min_rapid_distance_mm else "settle"
if _sign(target_mm) == 0.0:
phase = "settle"
return AxisRapidState(
axis_name=axis_name,
command_name=command_name,
direction=_sign(target_mm),
initial_abs_error=initial_abs_error,
min_rapid_distance_mm=min_rapid_distance_mm,
phase=phase,
predicted_remaining_mm=initial_abs_error,
best_abs_error_mm=initial_abs_error,
)
def _apply_rapid_axis(
self,
*,
rapid: AxisRapidState,
pid: PIDController,
error_mm: float,
velocity_mm_s: float,
pos_fresh: bool,