monitor.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 import sys
4 import rospy
5 
6 from sensor_msgs.msg import JointState
7 import matplotlib.pyplot as plt
8 from sklearn.externals import joblib
9 import numpy as np
10 from mpl_toolkits.mplot3d import Axes3D
11 from mpl_toolkits.mplot3d.art3d import Poly3DCollection
12 import subprocess
13 import os
14 
15 SCALER = None
16 REDUCE = None
17 MODEL = None
18 THRESHOLD = None
19 
20 PREV = None
21 GOOD = 0
22 BAD = 0
23 
24 POINTS = []
25 PREDS = []
26 POSITIONS_LIST = []
27 
28 
29 def load_modules(load_file, th):
30  '''
31  This function NEEDS to get called first, so that global variables can
32  be set.
33  Once set, they can be used to classify incoming data.
34  Sets global variables, so they can be used later.
35  '''
36 
37  global SCALER
38  global REDUCE
39  global MODEL
40  global THRESHOLD
41 
42  THRESHOLD = th
43 
44  # FIXME: TODO: Fix relative paths
45  SCALER = joblib.load("../data/scale.pkl")
46  REDUCE = joblib.load("../data/reduce.pkl")
47 
48  load_file = '../data/'+load_file
49  MODEL = joblib.load(load_file)
50 
51  # print 'Unsupervised models - ', rospy.get_param('unsupervised_model')
52  # print 'Supervised models - ', rospy.get_param('supervised_model')
53 
54  # if load_file in rospy.get_param('unsupervised_model'):
55  # MODEL_TYPE = 'unsupervised_model'
56  # print 'Loaded an unsupervised model'
57 
58  # elif load_file in rospy.get_param('supervised_model'):
59  # MODEL_TYPE = 'supervised_model'
60  # print 'Loaded a supervised model'
61  # else:
62  # rospy.logwarn("WARNING: Model might not exist. Going to exit.")
63  # rospy.signal_shutdown("Model type not known.")
64 
65  print 'Modules loaded. Over.'
66 
67 
68 
69 def command(val):
70  '''
71  Callback function for when specified message is published.
72  Adds data to global list to be processed later.
73  '''
74  global PREV
75  poses = list(val.position)
76 
77  if PREV != poses:
78  POSITIONS_LIST.append(poses)
79  PREV = poses
80 
81 
82 def check():
83 
84  global SCALER
85  global REDUCE
86  global MODEL
87  global THRESHOLD
88 
89  global GOOD
90  global BAD
91 
92  global POINTS
93  global PREDS
94 
95  while POSITIONS_LIST:
96 
97 
98  data = np.array([POSITIONS_LIST[0]])
99  POSITIONS_LIST.pop(0)
100 
101  scaled = SCALER.transform(data)
102  # print 'scale done'
103 
104  pca_ed = REDUCE.transform(scaled)
105  POINTS.append(pca_ed.tolist()[0])
106  # print 'reduce done'
107 
108  prediction = MODEL.predict(pca_ed)
109  PREDS.append(prediction[0])
110  # print 'got prediction', prediction[0]
111 
112  if prediction == 1:
113  GOOD += 1
114  print 'Good: ', GOOD/float(GOOD+BAD), 'Bad: ', BAD/float(GOOD+BAD), 'Count: ', GOOD+BAD
115  else:
116  BAD += 1
117  print 'Good: ', GOOD/float(GOOD+BAD), 'Bad: ', BAD/float(GOOD+BAD), 'Count: ', GOOD+BAD
118  rospy.logwarn("WARNING: Robot state classified as an \
119  anomaly.\n" + str(data))
120 
121  # FIXME: This logic is going to have to change.
122  # Currently, this method does not take into account when an
123  # a single task is complete, but keeps a running tally.
124  if (BAD/float(BAD+GOOD) > float(THRESHOLD)) and (BAD+GOOD > 60):
125  rospy.logerr("ERR: Robot state classified as an \
126  anomaly.\n" + str(data))
127 
128 
129 def graph_3d():
130 
131  global POINTS
132  global PREDS
133  global GOOD
134  global BAD
135 
136  percentgood = GOOD/float(GOOD+BAD)
137  percentbad = BAD/float(GOOD+BAD)
138  print GOOD, BAD, percentgood, percentbad
139 
140 
141  pts0 = [row[0] for row in POINTS]
142  pts1 = [row[1] for row in POINTS]
143  pts2 = [row[2] for row in POINTS]
144 
145  fig = plt.figure()
146  ax = fig.gca(projection='3d')
147  ax.scatter(pts0, pts1, pts2, c=PREDS, cmap='bwr', s=10)
148 
149  plt.show()
150 
151 
152 if __name__ == '__main__':
153 
154  rospy.init_node('monitor', anonymous=True)
155 
156  load_modules(sys.argv[2], sys.argv[3])
157 
158  # Subscribe to the appropriate topic
159  rospy.Subscriber(sys.argv[1],
160  JointState,
161  command)
162 
163  rospy.on_shutdown(graph_3d)
164 
165  while not rospy.is_shutdown():
166  check()
def command(val)
Definition: monitor.py:69
def load_modules(load_file, th)
Definition: monitor.py:29
def check()
Definition: monitor.py:82
def graph_3d()
Definition: monitor.py:129


mh5_anomaly_detector
Author(s): Vedanth Narayanan
autogenerated on Mon Jun 10 2019 13:49:20