-
Notifications
You must be signed in to change notification settings - Fork 5
/
fcv.py
executable file
·2285 lines (1922 loc) · 66.6 KB
/
fcv.py
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
#!/usr/bin/env python3
'''
fcv format conversion and analysis script
'''
# Copyright (C) 2016-2018 by Jacob Alexander
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# TODO
# Raw import
# FCV import
#
# FCV export
# csv export
# xls export
# graph export
# - png
# - svg
# plotly export
### Imports ###
from collections import namedtuple
from datetime import date
import argparse
import inspect
import os
import sys
# Print Decorator Variables
ERROR = '\033[5;1;31mERROR\033[0m:'
WARNING = '\033[1;33mWARNING\033[0m:'
# Python Text Formatting Fixer...
textFormatter_lookup = {
"usage: " : "Usage: ",
"optional arguments" : "Optional Arguments",
}
def textFormatter_gettext( s ):
'''
Cleans up argparse help information
'''
return textFormatter_lookup.get( s, s )
argparse._ = textFormatter_gettext
### Convenience Functions ###
def peakdet( v, delta, x=None ):
"""
https://gist.github.com/endolith/250860
Converted from MATLAB script at http://billauer.co.il/peakdet.html
Returns two arrays
function [maxtab, mintab]=peakdet(v, delta, x)
%PEAKDET Detect peaks in a vector
% [MAXTAB, MINTAB] = PEAKDET(V, DELTA) finds the local
% maxima and minima ("peaks") in the vector V.
% MAXTAB and MINTAB consists of two columns. Column 1
% contains indices in V, and column 2 the found values.
%
% With [MAXTAB, MINTAB] = PEAKDET(V, DELTA, X) the indices
% in MAXTAB and MINTAB are replaced with the corresponding
% X-values.
%
% A point is considered a maximum peak if it has the maximal
% value, and was preceded (to the left) by a value lower by
% DELTA.
% Eli Billauer, 3.4.05 (Explicitly not copyrighted).
% This function is released to the public domain; Any use is allowed.
"""
from numpy import NaN, Inf, arange, isscalar, asarray, array
maxtab = []
mintab = []
if x is None:
x = arange(len(v))
v = asarray(v)
if len(v) != len(x):
sys.exit('Input vectors v and x must have same length')
if not isscalar(delta):
sys.exit('Input argument delta must be a scalar')
if delta <= 0:
sys.exit('Input argument delta must be positive')
mn, mx = Inf, -Inf
mnpos, mxpos = NaN, NaN
lookformax = True
for i in arange(len(v)):
this = v[i]
if this > mx:
mx = this
mxpos = x[i]
if this < mn:
mn = this
mnpos = x[i]
if lookformax:
if this < mx - delta:
maxtab.append((mxpos, mx))
mn = this
mnpos = x[i]
lookformax = False
else:
if this > mn + delta:
mintab.append((mnpos, mn))
mx = this
mxpos = x[i]
lookformax = True
return array(maxtab), array(mintab)
### Classes ###
AnalysisDataPoint = namedtuple(
'AnalysisDataPoint',
'force_adc_serial_factor'
)
ForceDataPoint = namedtuple(
'ForceDataPoint',
'time distance force_adc force_serial continuity direction'
)
class ForceData:
'''
Data container class used to store force data in a standard format.
Also contains the results of any analysis done to the force data.
'''
def __init__( self ):
self.cur_test = 0
self.cur_switch = 0
self.tests = 0
self.switches = 0
# Initialize datastructure
self.data = []
def get( self, name ):
'''
Convenience get access to data
'''
return self.data[ self.cur_switch ][ name ][ self.cur_test ]
def set( self, name, value ):
'''
Convenience set access to data
'''
self.data[ self.cur_switch ][ name ][ self.cur_test ] = value
def get_var( self, name ):
'''
Convenience get access to data, single variable
'''
return self.data[ self.cur_switch ][ name ]
def set_var( self, name, value ):
'''
Convenience set access to data, single variable
'''
self.data[ self.cur_switch ][ name ] = value
def set_options( self, options ):
'''
Various options set by the command line
'''
self.options = options
def set_switch( self, num ):
'''
Sets the switch datastructure to perform operations on
'''
# Add switch storage element if needed
while len( self.data ) < num + 1:
self.data.append( {
'test' : { 0 : [] },
'analysis' : { 0 : [] },
'force_adc_serial_factor' : None,
'usable_distance_range' : None,
'usable_force_range' : None,
'extra_info' : dict(),
'rest_point' : { 0 : [] },
'actuation_point' : { 0 : [] },
'release_range' : { 0 : [] },
'bottom_out_point' : { 0 : [] },
'reset_point' : { 0 : [] },
'repeat_range' : { 0 : [] },
'total_force' : { 0 : [] },
'actuation_force' : { 0 : [] },
'total_force_avg' : None,
'actuation_force_avg' : None,
} )
self.cur_switch = num
# Update total number of switches
if num + 1 > self.switches:
self.switches = num + 1
def set_test( self, num ):
'''
Sets the current test to store/access ForceDataPoints
'''
self.cur_test = num
# Prepare list
if num not in self.data[ self.cur_switch ]['test'].keys():
self.data[ self.cur_switch ]['test'][ num ] = []
self.data[ self.cur_switch ]['analysis'][ num ] = []
# Update total number of tests
if num + 1 > self.tests:
self.tests = num + 1
def add( self, data_point ):
'''
Adds a ForceDataPoint to the list
'''
self.get('test').append( data_point )
def calibration_analysis( self ):
'''
Analysis collected from calibration data
'''
import numpy as np
import statistics
midpoint = self.mid_point()
# Calibration Alignment
# Unfortunately, press/release aren't entirely distance aligned
# This algorithm finds the 0 pivot point and the release curve offset
#
# And for double annoyance, the ADC force data is different as well
# So it has to be aligned separately :/
# Then the serial and adc curves need to be aligned
# Align Calibration Serial Force Data
print("Midpoint:", midpoint)
serial_press = self.force_serial()[ :midpoint ]
serial_release = self.force_serial()[ midpoint: ]
serial_alignment = min( max( serial_press ), max( serial_release ) )
serial_press_point = [ index for index, elem in enumerate( serial_press ) if elem >= serial_alignment ]
serial_release_point = [ index for index, elem in enumerate( serial_release ) if elem >= serial_alignment ]
self.cal_serial_press_center = self.distance_raw()[ :midpoint ][ serial_press_point[-1] ]
self.cal_serial_release_center = self.distance_raw()[ midpoint: ][ serial_release_point[-1] ]
# Align Calibration ADC Force Data
adc_press = self.force_adc()[ :midpoint ]
adc_release = self.force_adc()[ midpoint: ]
adc_alignment = min( max( adc_press ), max( adc_release ) )
adc_press_point = [ index for index, elem in enumerate( adc_press ) if elem >= adc_alignment ]
adc_release_point = [ index for index, elem in enumerate( adc_release ) if elem >= adc_alignment ]
self.cal_adc_press_center = self.distance_raw()[ :midpoint ][ adc_press_point[-1] ]
self.cal_adc_release_center = self.distance_raw()[ midpoint: ][ adc_release_point[-1] ]
# Basic force adc/serial factor calculation
# Calculate press/release separately
# Only use up until synchronization point
# Press calibration
press_difference = self.cal_adc_press_center - self.cal_serial_press_center
press_analysis = []
for index in range( abs( press_difference ), midpoint - abs( press_difference ) ):
data_adc = self.get('test')[ index ]
data_serial = self.get('test')[ index + press_difference ]
# Compute factor
try:
force_factor = data_adc.force_adc / data_serial.force_serial
# Just ignore zero values, they skew results of the average anyways
except ZeroDivisionError:
continue
point = AnalysisDataPoint(
force_factor
)
press_analysis.append( point )
# XXX Currently unused
if False:
press_force_adc_serial_factor = statistics.median_grouped(
[ elem.force_adc_serial_factor for elem in press_analysis ]
)
# Release calibration
release_difference = self.cal_adc_release_center - self.cal_serial_release_center
release_analysis = []
for index in range( midpoint - abs( release_difference ), len( self.get('test') ) - abs( release_difference ) ):
data_adc = self.get('test')[ index ]
print( index, release_difference, len( self.get('test') ) )
print( midpoint )
data_serial = self.get('test')[ index + release_difference ]
# Compute factor
try:
force_factor = data_adc.force_adc / data_serial.force_serial
# Just ignore zero values, they skew results of the average anyways
except ZeroDivisionError:
continue
point = AnalysisDataPoint(
force_factor
)
release_analysis.append( point )
release_force_adc_serial_factor = statistics.median_grouped(
[ elem.force_adc_serial_factor for elem in release_analysis ]
)
print( press_force_adc_serial_factor, release_force_adc_serial_factor )
for index, datapoint in enumerate( self.get('test') ):
try:
force_factor = datapoint.force_adc / datapoint.force_serial
except ZeroDivisionError:
force_factor = 0
point = AnalysisDataPoint(
force_factor
)
self.get('analysis').append( point )
# Use the grouped median as the conversion factor
self.set_var('force_adc_serial_factor',
statistics.median_grouped(
[ elem.force_adc_serial_factor for elem in self.get('analysis') ]
)
)
# XXX
# TODO
# Remove hard-coding of factor
#print( self.get_var('force_adc_serial_factor') )
#self.set_var('force_adc_serial_factor', ( press_force_adc_serial_factor, release_force_adc_serial_factor ) )
press_force_adc_serial_factor = 37.98400556328233
self.set_var('force_adc_serial_factor', ( press_force_adc_serial_factor, press_force_adc_serial_factor - 1.35 ) )
# Determine distance range, use raw adc values from press
adc_diff = list( np.diff( [ elem.force_adc for elem in self.get('test')[ :self.mid_point() ] ] ) )
peaks = peakdet( adc_diff, 100 )[0] # TODO configurable delta and forced range
#peaks = peakdet( adc_diff, 200 )[0] # TODO configurable delta and forced range
# XXX Use the peak_detection_index configuration in the json to tweak peak detection
# Otherwise just use the first peak
plot_data = self.get_var('extra_info')
if 'peak_detection_index' in plot_data.keys():
peak_index = plot_data['peak_detection_index']
else:
peak_index = 0
print("Peaks:", peaks)
first = adc_diff.index( peaks[ peak_index ][1] )
last = adc_diff.index( peaks[-1][1] )
# Use the max force as 2x the median grouped force over the newly calculated distance range (press)
force_data = self.force_adc_converted()[ first:last ]
print("Force Data:", force_data)
max_force_calc = statistics.median_grouped( force_data ) * 2
self.set_var('usable_force_range', ( ( 0, max_force_calc ) ) )
# XXX Override usable force range, needed if statistics from calibration are not usable
if 'max_cal_force_override' in plot_data.keys():
self.set_var('usable_force_range', ( ( 0, plot_data['max_cal_force_override'] ) ) )
# Start from beginning of press + 1/4 mm
# TODO peak detection algorith has issues with exponential force curves -Jacob
# TODO use calibration data for start of press instead of first -Jacob
dist_mm = self.distance_mm()
start_mm = dist_mm[ first ] + 0.25
print ( start_mm )
self.set_var('usable_distance_range', ( start_mm, 0 ) )
def curve_analysis( self ):
'''
Runs analysis on each recorded force curve (including calibration)
Order matters, as each analysis stage may provide the next with needed data
Analysis Computed
1. Distance Points/Ranges
2. Force Points/Ranges
'''
# Iterate over each set of test data, and do analysis
for index in self.options['curves']:
# Set datastructures for given test
self.set_test( index )
# Run analysis
self.curve_analysis_distance()
#self.curve_analysis_force() # TODO
self.area_under_curve()
self.analysis_averaging()
def curve_analysis_distance( self ):
'''
-- Distance Analysis --
Rest Point - Start of press, when force goes from noise-zero to increase
Actuation Point - Distance when switch goes from off to on state
Release Range - Distance range between acutation and bottom-out
Bottom-out Point - End of press, just before force goes to ~infinity
Reset Point - Distance when switch goes from on to off state
Repeat Range - Distance range between reset and rest
Each analysis value is accompanied by a dataset index, to easily map force vs. distance
( index, ( force, distance ) )
'''
distance = self.distance_mm()
force_adc = self.force_adc_converted()
# Rest Point
# Find the index of 0 mm, or the first non-negative value
rest_point = None
for index, elem in enumerate( distance ):
if elem >= 0:
rest_point = ( index, ( force_adc[ index ], elem ) )
break
# Actuation and Reset Points
actuation = self.actuation()
if len( actuation ) > 0:
actuation_point = ( actuation[0], ( force_adc[ actuation[0] ], distance[ actuation[0] ] ) )
reset_point = ( actuation[1], ( force_adc[ actuation[1] ], distance[ actuation[1] ] ) )
else:
actuation_point = None
reset_point = None
# Bottom-out Point
# Use the point where force crosses the max_force
# Default to max force point
plot_data = self.get_var('extra_info')
default_index = self.get_var('press_max_force_index')
bottom_out_point = ( default_index, ( force_adc[ default_index ], distance[ default_index ] ) )
for index, elem in enumerate( force_adc ):
if elem >= plot_data['max_force']:
# Since we have bottomed-out at this point, use the previous index
index -= 1
bottom_out_point = ( index, ( elem, distance[ index ] ) )
break
# Store analysis with test
self.set('rest_point', rest_point )
self.set('actuation_point', actuation_point )
self.set('release_range', ( actuation_point, bottom_out_point ) )
self.set('bottom_out_point', bottom_out_point )
self.set('reset_point', reset_point )
self.set('repeat_range', ( reset_point, rest_point ) )
def curve_analysis_force( self ):
'''
-- Force Analysis --
Acuation Force - Force when switch goes from off to on state
Reset Force - Force when switch goes from on to off state
Bottom-out Force - End of press, force just before peaking towards infinity
Pre-load Force - Beginning of press, just after the press has started
Each analysis value is accompanied by a dataset index, to easily map force vs. distance
( index, ( force, distance ) )
'''
distance = self.distance_mm()
force_adc = self.force_adc_converted()
# Pre-load Force
# TODO - Algorithm
pre_load_force = 0
# Bottom-out force
bottom_out_point = self.get('bottom_out_point')
bottom_out_force = ( bottom_out_point[0], force_adc[ bottom_out_point[0] ] )
# Store analysis with test
self.set('actuation_force', self.get('actuation_point') )
self.set('reset_force', self.get('reset_point') )
self.set('bottom_out_force', bottom_out_force )
self.set('pre_load_force', pre_load_force )
def area_under_curve( self ):
'''
-- Area Under Curve --
Uses numpy to integrate the area under the force curve
Two different calculations
1) Full area, 0 to bottom out
2) Actuation, 0 to actuation point (if available)
'''
from numpy import trapz
distance = self.distance_mm()
force_adc = self.force_adc_converted()
rest_point = self.get('rest_point')
bottom_out_point = self.get('bottom_out_point')
actuation_point = self.get('actuation_point')
print( "Rest, Bottom-out:", rest_point, bottom_out_point )
# Full Area
total_force = trapz(
force_adc[ rest_point[0]:bottom_out_point[0] ],
distance[ rest_point[0]:bottom_out_point[0] ],
)
print("total force:", total_force, "gfmm")
# Actuation
actuation_force = None
if actuation_point is not None:
actuation_force = trapz(
force_adc[ rest_point[0]:actuation_point[0] ],
distance[ rest_point[0]:actuation_point[0] ],
)
print("actuation force:", actuation_force, "gfmm")
if actuation_force <= 1:
print("{0} Less than 1 gfmm, ignoring...".format( WARNING ) )
actuation_force = None
self.set('total_force', total_force )
self.set('actuation_force', actuation_force )
def analysis_averaging( self ):
'''
Takes analysis from the set of tests and averages it
'''
total_tests = len( self.data[ self.cur_switch ]['total_force'] ) - 1
# Total Force
total = 0
for index in self.options['curves']:
# Set datastructures for given test
self.set_test( index )
# Get total_force for this test
total += self.get('total_force')
total_force_avg = total / total_tests
print("total force avg:", total_force_avg, "gfmm")
self.set_var('total_force_avg', total_force_avg )
# Actuation Force
if 'actuation_force' in self.data[ self.cur_switch ].keys():
total = 0
for index in self.options['curves']:
# Set datastructures for given test
self.set_test( index )
# Get actuation_force for this test
value = self.get('actuation_force')
# Sometimes a single test won't have an actuation...
# Bad test, or switch, ignore from average
if value is None:
total_tests -= 1
print("{0} Missing actuation from test #{1}...".format(
WARNING,
index,
) )
continue
total += value
# If 0, then just ignore this measurement
if total != 0:
actuation_force_avg = total / total_tests
print("actuation force avg:", actuation_force_avg, "gfmm")
self.set_var('actuation_force_avg', actuation_force_avg )
def max_force_points_converted( self ):
'''
Returns a tuple of the distance ticks for the max force points
These values are interpolated, so don't bother trying to look them up in the dataset
Ideally, this calculation only needs to be done on the calibration data.
Unfortunately, some datasets...are less clean, so it's recommended to run on each press/release pair
'''
# Determine the start and max distance points (using data indices)
# These points will be the same for all the curves in the dataset
# This is used in the conversion to mm needed for the usable_distance_range
# Using the approximate points, interpolate to find the point we want
# dist = dist_1 + (dist_2 - dist_1)( (force - force_1) / (force_2 - force_1) )
max_force_calc = self.get_var('usable_force_range')[1]
print( "MAX FORCE: ", max_force_calc )
# Press "wave"
conv_factor = self.get_var('force_adc_serial_factor')[0]
try:
press_max_force_index = [
index
for index, value in enumerate( self.get('test') )
if value.force_adc / conv_factor > max_force_calc
][0]
self.set_var('press_max_force_index', press_max_force_index )
except IndexError as err:
print( "{0} Check data, likely a Next Test Starting tag is missing/in the wrong spot.".format(
WARNING
) )
print( err )
# Max Detected force
press_max_force_detected = [
value.force_adc / conv_factor
for index, value in enumerate( self.get('test') )
if value.force_adc / conv_factor
]
print( "Max Detected Force:", max(press_max_force_detected ) )
print( "Max Force Calculated:", max_force_calc )
point1 = self.get('test')[ press_max_force_index - 1 ]
point2 = self.get('test')[ press_max_force_index ]
press_max = point1.distance + ( point2.distance - point1.distance ) * (
(max_force_calc - point1.force_adc / conv_factor) /
(point2.force_adc / conv_factor - point1.force_adc / conv_factor)
)
# Release "wave"
conv_factor = self.get_var('force_adc_serial_factor')[1]
release_max_force_index = [
index
for index, value in reversed( list( enumerate( self.get('test') ) ) )
if value.force_adc / conv_factor > max_force_calc
][0]
point1 = self.get('test')[ release_max_force_index - 1 ]
point2 = self.get('test')[ release_max_force_index ]
release_max = point1.distance + ( point2.distance - point1.distance ) * (
(max_force_calc - point1.force_adc / conv_factor) /
(point2.force_adc / conv_factor - point1.force_adc / conv_factor)
)
return (press_max, release_max)
def force_adc( self ):
'''
Returns a list of force adc values for the current test
'''
return [ data.force_adc for data in self.get('test') ]
def force_serial( self ):
'''
Returns a list of force serial values for the current test
'''
data = [ data.force_serial for data in self.get('test') ]
return data
def force_adc_converted( self ):
'''
Returns a list of converted force adc values for the current test
'''
midpoint = self.mid_point()
data = [ data.force_adc / self.get_var('force_adc_serial_factor')[0] for data in self.get('test')[ :midpoint ] ]
data.extend( [ data.force_adc / self.get_var('force_adc_serial_factor')[1] for data in self.get('test')[ midpoint: ] ] )
return data
def distance_raw( self ):
'''
Returns a list of distance values for the current test
'''
data = [ data.distance for data in self.get('test') ]
return data
def distance_mm( self ):
'''
Returns a list of distance values for the current test converted to mm
Convert to mm
As per http://www.shumatech.com/web/21bit_protocol?page=0,1
21 bits is 2560 CPI (counts per inch) (C/inch)
1 inch is 25.4 mm
2560 / 25.4 = 100.7874016... CPMM (C/mm)
Or
1 count is 1/2560 = 0.000390625... inches
1 count is (1/2560) * 25.4 = 0.00992187500000000 mm = 9.92187500000000 um = 9921.87500000000 nm
Since there are 21 bits (2 097 152 positions) converting to um is possible by multiplying by 1000
which is 2 097 152 000, and within 32 bits (4 294 967 295).
However, um is still not convenient, so 64 bits (18 446 744 073 709 551 615) is a more accurate alternative.
For each nm there are 2 097 152 000 000 positions.
And for shits:
mm is 2 097 152 : 0.009 921 875 000 mm : 32 bit
um is 2 097 152 000 : 9.921 875 000 um : 32 bit (ideal acc. for 32 bit)
nm is 2 097 152 000 000 : 9 921.875 000 nm : 64 bit
pm is 2 097 152 000 000 000 : 9 921 875.000 pm : 64 bit (ideal acc. for 64 bit)
XXX Apparently shumatech was sorta wrong about the 21 bits of usage
Yes there are 21 bits, but the values only go from ~338 to ~30681 which is less than 16 bits...
This means that the conversion at NM can use 32 bits :D
It's been noted that the multiplier should be 100.6 (and that it could vary from scale to scale)
'''
mm_conv = 0.009921875
plot_data = self.get_var('extra_info')
# Determine the start and max distance points (using data indices)
max_force_points = self.max_force_points_converted()
zero_point_press = max_force_points[0]
zero_point_release = max_force_points[1]
# XXX Use the release_mm_offset to deal with algorithm issues, defined in mm when necessary
plot_data = self.get_var('extra_info')
if 'release_mm_offset' in plot_data.keys():
release_offset = plot_data['release_mm_offset']
else:
release_offset = 0
# Apply mm_shift
if 'mm_shift' in plot_data.keys():
press_offset = plot_data['mm_shift']
release_offset += plot_data['mm_shift']
else:
press_offset = 0
# Compute lists with offsets
mid_point = self.mid_point()
press = [ ((data.distance - zero_point_press) * mm_conv) + press_offset for data in self.get('test')[:mid_point] ]
release = [ ((data.distance - zero_point_release) * mm_conv) + release_offset for data in self.get('test')[mid_point:] ]
press.extend( release )
# Flip the distance axis at max_distance (e.g. 4 mm)
max_mm = plot_data['max_distance']
press = [ (point - max_mm) * -1 for point in press ]
# Make sure distance points are sequential
# 3 point, 2 differences (Naive -HaaTa)
# for index, elem in enumerate( press ):
# # We need adjacent points to do check
# if index == 0 or index == len( press ) - 1:
# continue
#
# # Look for non-sequential distance points
# # These may happen due to a firmware bug, transient reading error, or mm conversion error
# before = press[index - 1]
# after = press[index + 1]
# if ( before > elem and after > elem ) or ( before < elem and after < elem ):
# avg = ( before + after ) / 2
# press[index] = avg
# # Warn the user we are modifying data
# print ( "{0} Found non-sequential point {1} mm at index '{2}' between {3} mm and {4} mm. "
# "Averaging to {5} mm.".format(
# WARNING,
# elem, index,
# before, after,
# avg,
# )
# )
# Make sure distance points are sequential
# Using 5 points to determine directional intent (curve changes direction)
for index, elem in enumerate( press ):
# We need adjacent points to do check
if index == 0 or index > len( press ) - 4:
continue
# Look for non-sequential distances points
# The algorithm is to look at the 3 differences between the 4 points
# If 3/4 differences point in one direction *and* changing the current element brings this to 4/4
# in a single direction, change, otherwise, do nothing
results = []
total_pos = 0
total_neg = 0
for pos in range( index - 1, index + 3 ):
results.append( press[pos] - press[pos + 1] )
if results[-1] > 0:
total_pos += 1
elif results[-1] < 0:
total_neg -= 1
# Adjustment condition, must have 3/4 in the same direction to make an adjustment
if (
( total_pos == 3 and ( results[0] < 0 or results[1] < 0 ) ) or
( total_neg == -3 and ( results[0] > 0 or results[1] > 0 ) )
):
before = press[index - 1]
after = press[index + 1]
avg = ( before + after ) / 2
# Ignore if after position is the 0 mm position
if after == 0.0 or elem == 0.0:
continue
press[index] = avg
# Warn the user we are modifying data
print ( "{0} Found non-sequential point {1} mm at index '{2}' between {3} mm and {4} mm. "
"Averaging to {5} mm.".format(
WARNING,
elem, index,
before, after,
avg,
)
)
return press
def mid_point( self ):
'''
Determines the direction change point of a test sequence
'''
print( min( self.get('test'), key = lambda t: t.distance ) )
return self.get('test').index( min( self.get('test'), key = lambda t: t.distance ) )
def mid_point_dir( self ):
'''
Determines the direction change point of a test sequence using the direction field (more accurate than mid_point)
Look for the transition from 2 to 1
2 - Down
1 - Up
'''
prev = ForceDataPoint( None, None, None, None, None, None )
position = None
for index, elem in enumerate( self.get('test') ):
if prev.direction == 2 and elem.direction == 1:
position = index
break
prev = elem
return position
def mid_point_peak( self ):
'''
Determines the direction change using the bottom out force peaks
Returns, a tuple
(end of press, start of release)
'''
import numpy as np
from operator import itemgetter
adc_diff = list( np.diff( [ elem.force_adc for elem in self.get('test') ] ) )
# XXX Naive version
#return ( adc_diff.index( max( adc_diff ) ), adc_diff.index( min( adc_diff ) ) )
# XXX Peak detection version (still a bit naive) -HaaTa
#peaks = peakdet( adc_diff, 200 )
#return ( int( peaks[0][0][0] ), int( peaks[1][-1][0] ) )
# Peak detection with peak analysis
# For the max (bottom out start), find the highest peak, then check the previous peak
# If it's force peak is greater than half of the current, then move the peak, and check again
# For the min (bottom out end), check forward instead
peaks = peakdet( adc_diff, 100 )
max_peaks = peaks[0].tolist()
min_peaks = peaks[1].tolist()
max_point = max_peaks.index( max( max_peaks, key=itemgetter( 1 ) ) )
min_point = min_peaks.index( min( min_peaks, key=itemgetter( 1 ) ) )
# Bottom out start approximation
for index in range( max_point - 1, -1, -1 ):
# Check if force peak is at least half as large as the previous
if max_peaks[index][1] < max_peaks[index - 1][1] / 2:
break
# Update new bottom out point
max_point = index
# Bottom out end approximation
for index in range( min_point + 1, len( min_peaks ) ):
# Check if force peak is at least half as large as the previous
if min_peaks[index][1] > min_peaks[index - 1][1] / 2:
break
# Update new bottom out point
min_point = index
peaks = ( int( max_peaks[max_point][0] ), int( min_peaks[min_point][0] ) )
return peaks
def actuation( self ):
'''
Determines press/release actuation, returns a list of change (index) points.
This can generally be assumed as (press, release).
Default state (usually 1), is set initially.
The first change is the press.
The second change is the release.
'''
prev = ForceDataPoint( None, None, None, None, None, None )
state = None
actuation = []
for index, elem in enumerate( self.get('test') ):
# Determine initial state
if state is None:
state = elem.continuity
# Determine if the state has changed
if prev.continuity == state and elem.continuity != state:
actuation.append( index )
state = elem.continuity
prev = elem
return actuation
class GenericForceData:
'''
Common function/variables used for all import/export classes
Mark contstructor variables as None if not using
force_data is required
'''
def __init__( self, force_data, input_file, output_file ):
# Input data
self.force_data = force_data
self.input_file = input_file
self.output_file = output_file
# Processing variables
self.cur_test = None
self.calibration = False
# Check if a valid input file
if input_file is not None and not self.valid_input_file():
self.valid_input_file()
def process_input( self ):
'''
Import force data from file into force_data structure
'''
raise NotImplementedError("Invalid/Not implemented yet")
def process_output( self ):
'''
Output force data from force_data structure to the output file
'''
raise NotImplementedError("Invalid/Not implemented yet")
def valid_input_file( self ):
'''
Checks if the input file is valid.
'''
raise NotImplementedError("Invalid/Not implemented yet")
class RawForceData( GenericForceData ):
'''
Class used to import and prepare force gauge data
'''
def __init__( self, force_data, input_file ):
# Store extension (used to determine if compressed)
split = os.path.splitext( input_file )
self.extension = split[1]
super( RawForceData, self ).__init__( force_data, input_file, None )