magfit_compassmot.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 '''
4 estimate COMPASS_MOT_* parameters for throttle based compensation
5 '''
6 from __future__ import print_function
7 from builtins import range
8 import math
9 
10 from argparse import ArgumentParser
11 parser = ArgumentParser(description=__doc__)
12 parser.add_argument("--condition",dest="condition", default=None, help="select packets by condition")
13 parser.add_argument("logs", metavar="LOG", nargs="+")
14 
15 args = parser.parse_args()
16 
17 from pymavlink import mavutil
18 from pymavlink.rotmat import Vector3
19 
20 def mag_error(p, data):
21  cx,cy,cz,r = p
22  errout = 0
23  # cruse bounds mechanism
24  if r < 0.3:
25  errout = (0.3 - r) * 100
26  r = 0.3
27  if r > 2.0:
28  errout = (r - 2.0) * 100
29  r = 2.0
30  corr = Vector3(cx,cy,cz)
31  (baseline_field,baseline_throttle) = data[0]
32  ret = []
33  for d in data:
34  (mag,throttle) = d
35  cmag = mag + corr * math.pow(throttle,r)
36  err = (cmag - baseline_field).length()
37  err += errout
38  ret.append(err)
39  return ret
40 
41 def fit_data(data):
42  from scipy import optimize
43 
44  p0 = [0.0, 0.0, 0.0, 1.0]
45  p1, ier = optimize.leastsq(mag_error, p0[:], args=(data))
46  if not ier in [1, 2, 3, 4]:
47  raise RuntimeError("Unable to find solution")
48  return (Vector3(p1[0], p1[1], p1[2]), p1[3])
49 
50 def magfit(logfile):
51  '''find best magnetometer offset fit to a log file'''
52 
53  print("Processing log %s" % filename)
54  mlog = mavutil.mavlink_connection(filename)
55 
56  data = []
57  throttle = 0
58 
59  # now gather all the data
60  while True:
61  m = mlog.recv_match(condition=args.condition)
62  if m is None:
63  break
64  if m.get_type() == "MAG":
65  mag = Vector3(m.MagX, m.MagY, m.MagZ)
66  data.append((mag, throttle))
67  #if m.get_type() == "RCOU":
68  # throttle = math.sqrt(m.C1/500.0)
69  if m.get_type() == "CTUN":
70  throttle = m.ThO
71 
72  print("Extracted %u data points" % len(data))
73 
74  (cmot,r) = fit_data(data)
75  print("Fit : %s r: %s" % (cmot,r))
76 
77  x = range(len(data))
78  errors = mag_error((cmot.x,cmot.y,cmot.z,r), data)
79 
80  import matplotlib.pyplot as plt
81  plt.plot(x, errors, 'bo-')
82  x1,x2,y1,y2 = plt.axis()
83  plt.axis((x1,x2,0,y2))
84  plt.ylabel('Error')
85  plt.xlabel('Sample')
86  plt.show()
87 
88 for filename in args.logs:
89  magfit(filename)


mavlink
Author(s): Lorenz Meier
autogenerated on Sun Apr 7 2019 02:06:02