forked from adaptive-cfd/python-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsect_tools.py
executable file
·3255 lines (2492 loc) · 112 KB
/
insect_tools.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
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 11 09:11:47 2017
@author: engels
"""
import numpy as np
import numpy.ma as ma
import glob
from warnings import warn
def change_color_opacity(color, alpha):
import matplotlib
color = list(matplotlib.colors.to_rgba(color))
color[-1] = alpha
return color
# I cannot learn this by heart....
def change_figure_dpi(dpi):
import matplotlib.pyplot as plt
plt.rcParams['figure.dpi'] = dpi
icolor = 0
def get_next_color(ax=None):
import matplotlib.pyplot as plt
# as of 01/2024, the method below is not available anymore, because PROP_CYCLER
# has vannished. This current version is a hack.
# if ax is None:
# ax = plt.gca()
# return next(ax._get_lines.prop_cycler)['color']
global icolor
colors = plt.rcParams["axes.prop_cycle"].by_key()["color"]
this_color = colors[icolor]
icolor += 1
if icolor>len(colors)-1:
icolor=0
return this_color
# It is often the case that I want to plot several lines with the same color, eg Fx, Fy
# from a specific run. This function gets the last used color for this purpose.
def get_last_color(ax=None):
import matplotlib.pyplot as plt
if ax is None:
ax = plt.gca()
color = ax.lines[-1].get_color()
return color
def reset_colorcycle( ax=None ):
global icolor
icolor = 0
def get_next_marker():
import itertools
marker = itertools.cycle(('o', '+', 's', '>', '*', 'd', 'p'))
return next(marker)
def statistics_stroke_time_evolution( t, y, plot_indiv_strokes=True, N=1000, tstroke=1.0, plot_raw_data=False, color='k', marker='d'):
"""
Perform statistics over periodic data.
Often, we have data for several strokes, say 0 <= t <= 10. This function assumes
a period time T=1.0, divides the data into chunks corresponding to each of the strokes,
then computes the average time evolution as well as standard deviation among all strokes.
The data is divided into cycles and (linearily) interpolated to an equidistant time
grid. Ths grid is equidistant and sampled using N=1000 data points.
Input:
------
t: vector, float
full time vector (say 0<t<10.0)
y: vector, float
The actual data to be analyzed (e.g., drag or power)
plot_indiv_strokes: logical
If true, each individual stroke is plotted in the current figure.
Output:
-------
time, y_avg, y_std
Todo:
-----
The code does not check for incomplete cycles, say 0<t<4.57 is a problem
"""
import matplotlib.pyplot as plt
# all data is interpolated to an equidistant time grid
time = np.linspace(0.0, 1.0, num=N, endpoint=False)
# start and end time of data
t0, t1 = t[0], t[-1]
# how many cycles are there?
nstrokes = int( np.round( (t1-t0) / tstroke) )
y_interp = np.zeros( (nstrokes, time.shape[0]) )
for i in range(nstrokes):
# linear interpolation
y_interp[i,:] = np.interp( time+float(i)*tstroke, t, y)
if plot_indiv_strokes:
# plot the linear interpolated data for this stroke
plt.plot(time, y_interp[i,:], color='k', linewidth=0.5)
if plot_raw_data:
# plot raw (non-interpolated) data points
# helpful if data contains holes (NAN) and isolated datapoints, because
# we need at least two non-NAN points for linear interpolation
mask = np.zeros( t.shape, dtype=bool)
mask[ t>=float(i)*tstroke ] = True
mask[ t>=float(i+1)*tstroke ] = False
plt.plot( t[mask]-float(i)*tstroke, y[mask], marker=marker, color=color, mfc='none', linewidth=0.5, linestyle='none')
y_avg = np.nanmean(y_interp, axis=0)
y_std = np.nanstd(y_interp, axis=0)
return time, y_avg, y_std
def plot_errorbar_fill_between(x, y, yerr, color=None, label="", alpha=0.25, fmt='o-', linewidth=1.0, ax=None):
"""
Plot the data y(x) with a shaded area for error (e.g., standard deviation.)
This is a generic function often used. It does only the plotting, not the computation
part.
Input:
------
x: vector, float
data location (usually time)
y: vector, float
The actual data to be plotted (e.g., drag or power)
yerr: vector_float:
The shaded area will be between y-yerr and y+yerr for all x
color: color_object
Well. guess.
alpha: float (0<=alpha<=1.0)
The degree of transparency of the shaded area.
Output:
-------
plotting to figure
"""
import matplotlib.pyplot as plt
import matplotlib
if ax is None:
ax = plt.gca()
x = np.asarray(x)
y = np.asarray(y)
yerr = np.asarray(yerr)
if color is None:
color = get_next_color()
color = np.asarray( matplotlib.colors.to_rgba(color) )
# first, draw shaded area for dev
color[3] = alpha
ax.fill_between( x, y-yerr, y+yerr, color=color, alpha=alpha )
# then, avg data
color[3] = 1.00
ax.plot( x, y, fmt, label=label, color=color, mfc='none', linewidth=linewidth )
# chunk a string, regardless of whatever delimiter, after length characters,
# return a list
def chunkstring(string, length):
return list( string[0+i:length+i] for i in range(0, len(string), length) )
def cm2inch(value):
return value/2.54
def deg2rad(value):
return value*np.pi/180.0
# construct a column-vector for math operatrions. I hate python.
def vct(x):
# use the squeeze function in case x is a [3,1] or [1,3]
v = np.matrix(x)
v = v[np.newaxis]
v = v.reshape(len(x),1)
return v
def ylim_auto(ax, x, y):
# ax: axes object handle
# x: data for entire x-axes
# y: data for entire y-axes
# assumption: you have already set the x-limit as desired
lims = ax.get_xlim()
i = np.where( (x > lims[0]) & (x < lims[1]) )[0]
ax.set_ylim( y[i].min(), y[i].max() )
# set axis spacing to equal by modifying only the axis limits, not touching the
# size of the figure
def axis_equal_keepbox( fig, ax ):
# w, h = fig.get_size_inches()
bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
w, h = bbox.width, bbox.height
x1, x2 = ax.get_xlim()
y1, y2 = ax.get_ylim()
if (x2-x1)/w > (y2-y1)/h:
# adjust y-axis
l_old = (y2-y1)
l_new = (x2-x1) * h/w
ax.set_ylim([ y1-(l_new-l_old)/2.0, y2+(l_new-l_old)/2.0])
else:
# adjust x-axis
l_old = (x2-x1)
l_new = (y2-y1) * w/h
ax.set_xlim([ x1-(l_new-l_old)/2.0, x2+(l_new-l_old)/2.0])
# read pointcloudfile
def read_pointcloud(file):
data = np.loadtxt(file, skiprows=1, delimiter=' ')
if data.shape[1] > 6:
data = np.delete( data, range(3,data.shape[1]-3) , 1)
print(data.shape)
return data
def write_pointcloud(file, data, header):
write_csv_file( file, data, header=header, sep=' ')
def load_t_file( fname, interp=False, time_out=None, return_header=False,
verbose=True, time_mask_before=None, T0=None, keep_duplicates=False, remove_outliers=False ):
"""
Read in an ascii *.t file as generated by flusi or wabbit.
Returns only unique times (if the simulation ran first until t=3.0 and then is resumed from
t=2.0, the script will return the entries 2.0<t<3.0 only one time, even though they exist twice
in the file)
Input:
------
fname: string
filename to be read
interp: bool
is interpolation used or do we just read what is in the file?
time_out: numpy array
if interp=True, ou can specify to what time vector we interpolate.
return_header: bool
If true, we return the header line of the file as list of strings
verbose: bool
be verbose or not.
keep_duplicates: bool
remove lines with non-unique time stamps or not? if True, only one is kept. The code takes care that the LAST
of non-unique time stamps is returned (i.e. if the simulation runs until t=20.0 and is then resumed from t=19.0
the values of that last resubmission are returned)
remove_outliers: bool
An ugly function to remove obvious outliers that frequently appear for wabbit data at the saving intervals, when the time
stamp dt gets very small. ugly for presentations but harmless for the data.
time_mask_before: float
if set, we return a masked array which masks data before this time. note some routines do not like masked arrays
T0: list of floats or single float
can be either one value or two values. In the former case, we extract data t>=T0
in the latter T0[0]<=t<=T0[1]
Output:
-------
data: numpy array
the actual matrix stored in the file, possibly interpolated
header: list of strings
the columns headers, if return_header=True. If we did not find a heade in the file, the list is empty.
"""
import os
if verbose:
print('reading file %s' %fname)
# does the file exists?
if not os.path.isfile(fname):
raise ValueError('load_t_file: file=%s not found!' % (fname))
# does the user want the header back?
if return_header:
# read header line
f = open(fname, 'r')
header = f.readline()
# a header is a comment that begins with % (not all files have one)
if "%" in header:
# remove comment character
header = header.replace('%',' ')
# convert header line to list of strings
header = chunkstring(header, 16)
f.close()
# format and print header
for i in range(0,len(header)):
# remove spaces (leading+trailing, conserve mid-spaces)
header[i] = header[i].strip()
# remove newlines
header[i] = header[i].replace('\n','')
if verbose:
print( 'd[:,%i] %s' % (i, header[i] ) )
else:
print('You requested a header, but we did not find one...')
# return empty list
header = []
#--------------------------------------------------------------------------
# read the data from file
#--------------------------------------------------------------------------
# 18/12/2018: we no longer directly use np.loadtxt, because it sometimes fails
# if a run has been interrupted while writing the file. In those cases, a line
# sometimes contains less elements, trip-wiring the loadtxt function
#
# old call:
#
# data_raw = np.loadtxt( fname, comments="%")
ncols = None
# initialize file as list (of lists)
dat = []
with open( fname, "r" ) as f:
# loop over all lines
for line in f:
if not '%' in line:
# turn line into list
tmp = line.split()
# did we already figure out how many cols the file has?
if ncols is None:
ncols = len(tmp)
# try if we can convert the list entries to float
# sometimes suff like '-8.28380559-104' happens and that cannot be
# converted. in this case, we set zero
for j in range(len(tmp)):
try:
dummy = float(tmp[j])
except:
print( "WARNING %s cannot be converted to float, returning zero instead" % (tmp[j]) )
tmp[j] = "0.0"
if len(tmp) == ncols:
dat.append( tmp )
else:
dat.append( tmp[0:ncols] )
# convert list of lists into an numpy array
data_raw = np.array( dat, dtype=float )
if len(data_raw.shape) == 1:
return None
nt_raw, ncols = data_raw.shape
# retain only unique values (judging by the time stamp, so if multiple rows
# have exactly the same time, only one of them is kept)
if not keep_duplicates:
time_raw = data_raw[:,0]
# old code:
# dummy, unique_indices = np.unique( time_raw, return_index=True )
# data = np.copy( data_raw[unique_indices,:] )
it_unique = np.zeros( time_raw.shape, dtype=bool )
# skip first time stamp
for it in np.arange( 1, nt_raw ):
t0, t1 = time_raw[it-1], time_raw[it]
if t1 < t0:
# we have found a jump. now, figure out the index where we duplicate time stamps began
istart = np.argmin( np.abs(time_raw[0:it-1]-t1) )
tstart = time_raw[istart]
if (abs(tstart - t1) >= 1.0e-3):
print("""Warning.
In %s we found a jump in time (duplicate values) t[%i]=%f t[%i]=%f but the nearest
time in the past is t[%i]=%f so it may not be duplicates""" % (fname, it-1, t0, it, t1, istart, tstart) )
else:
# legit jump (duplicate values)
it_unique[istart:it] = False
it_unique[it] = True
else:
# no jump, seems to be okay for now, but is maybe removed later
it_unique[it] = True
data = data_raw[ it_unique, :].copy()
else:
data = data_raw.copy()
if remove_outliers:
it_unique = np.zeros( data.shape[0], dtype=bool )
for it in np.arange(1, data.shape[0]-1): # skips first and last point
# actual data (all columns of file)
line = data[it,:]
# linear interpolation using neighbor values (all columns of file)
line_interp = (data[it-1,:] + data[it+1,:]) *0.5
# absolute and relative "errors" (difference to linear interpolation)
err_abs = np.abs(line - line_interp)
err_rel = err_abs.copy()
err_rel[ np.abs(line_interp) >= 1.0e-10 ] /= np.abs(line_interp)[ np.abs(line_interp) >= 1.0e-10 ]
# use absolute value where the magnitude is smaller than 1e-7
err = err_rel
err[ err_abs <= 1.0e-7 ] = err_abs[ err_abs <= 1.0e-7 ]
# remove time steps that are detected as 'outliers'
if (np.max(err)>0.25):
it_unique[it] = False
else:
it_unique[it] = True
# sometimes the last point is a problem....
# note we cannot assume periodicity, so we use a one-sided difference stencil.
err_abs = np.abs(data[-2,:]-data[-1,:])
err_rel = err_abs.copy()
for ic in range( data.shape[1]):
# normalize by 2nd to last point not the last one in case its super large
if np.abs(data[-2,ic]) > 1e-10:
err_rel[ic] /= np.abs(data[-2,ic])
# use absolute value where the magnitude is smaller than 1e-7
err = err_rel
err[ err_abs <= 1.0e-7 ] = err_abs[ err_abs <= 1.0e-7 ]
if (np.max(err)>1.5):
it_unique[-1] = False
else:
it_unique[-1] = True
data = data[ it_unique, :].copy()
if T0 is not None:
if type(T0) is list and len(T0)==2:
# extract time instants between T0[0] and T0[1]
i0 = np.argmin( np.abs(data[:,0]-T0[0]) )
i1 = np.argmin( np.abs(data[:,0]-T0[1]) )
# data = np.copy( data[i0:i1,:] )
data = data[i0:i1,:].copy()
else:
# extract everything after T0
i0 = np.argmin( np.abs(data[:,0]-T0) )
# data = np.copy( data[i0:,:] )
data = data[i0:,:].copy()
# info on data
nt, ncols = data.shape
if verbose:
print( 'nt_unique=%i nt_raw=%i ncols=%i' % (nt, nt_raw, ncols) )
# if desired, the data is interpolated to an equidistant time grid
if interp:
if time_out is None:
# time stamps as they are in the file, possibly nont equidistant
time_in = np.copy(data[:,0])
# start & end time
t1 = time_in[0]
t2 = time_in[-1]
# create equidistant time vector
time_out = np.linspace( start=t1, stop=t2, endpoint=True, num=nt )
# equidistant time step
dt = time_out[1]-time_out[0]
if verbose:
print('interpolating to nt=%i (dt=%e) points' % (time_out.size, dt) )
if data[0,0] > time_out[0] or data[-1,0] < time_out[-1]:
print('WARNING you want to interpolate beyond bounds of data')
print("Data: %e<=t<=%e Interp: %e<=t<=%e" % (data[0,0], data[-1,0], time_out[0], time_out[-1]))
data = interp_matrix( data, time_out )
# hide first times, if desired
if time_mask_before is not None:
data = np.ma.array( data, mask=np.repeat( data[:,0]<time_mask_before, data.shape[1]))
# return data
if return_header:
return data, header
else:
return data
def stroke_average_matrix( d, tstroke=1.0, t1=None, t2=None, force_fullstroke=True ):
"""
Return a matrix of cycle-averaged values from a array from a *.t file.
Input:
------
d: np.ndarray, float
Data. we assume d[:,0] to be time.
tstroke: scalar, float
length of a cycle
force_fullstrokes: scalar, bool
If you do not pass t1, t2 then we can round the data time: if the first
data point is at 0.01, it will rounded down to 0.0.
t1: scalar, float
first time instant to begin averaging from
t2: scalar, float
last time instant to end averaging at. This can be useful if the very last
time step is not precisely the end of a stroke (say 2.9999 instead of 3.000)
Output:
-------
D: matrix
stroke averages in a matrix
"""
# start time of data
if t1 is None:
t1 = d[0,0]
# end time of data
if t2 is None:
t2 = d[-1,0]
if force_fullstroke:
t1 = np.floor( t1/tstroke )*tstroke
t2 = np.ceil( t2/tstroke )*tstroke
# will there be any strokes at all?
if t2-t1 < tstroke:
print('warning: no complete stroke present, not returning any averages')
if t1 - np.round(t1) >= 1e-3:
print('warning: data does not start at full stroke (tstart=%f)' % t1)
# allocate stroke average matrix
nt, ncols = d.shape
navgs = int( np.round((t2-t1)/tstroke) )
D = np.zeros([navgs,ncols])
# running index of strokes
istroke = 0
# we had some trouble with float equality, so be a little tolerant
dt = np.mean( d[1:,0]-d[:-1,0] )
# go in entire strokes
while t1+tstroke <= t2 + dt:
# begin of this stroke
tbegin = t1
# end of this stroke
tend = t1+tstroke
# iterate
t1 = tend
# find index where stroke begins:
i = np.argmin( abs(d[:,0]-tbegin) )
# find index where stroke ends
j = np.argmin( abs(d[:,0]-tend) )
# extract time vector
time = d[i:j+1,0]
# replace first and last time instant with stroke begin/endpoint to avoid being just to dt close
time[0] = tbegin
time[-1] = tend
#print('t1=%f t2=%f i1 =%i i2=%i %f %f istroke=%i' % (tbegin, tend, i, j, d[i,0], d[j,0], istroke))
# actual integration. see wikipedia :)
# the integral f(x)dx over x2-x1 is the average of the function on that
# interval. note this script is more precise than the older matlab versions
# as it is, numerically, higher order. the results are however very similar
# (below 1% difference)
for col in range(0,ncols):
# use interpolation, but actually only for first and last point of a stroke
# the others are identical as saved in the data file
dat = np.interp( time, d[:,0], d[:,col] )
D[istroke,col] = np.trapz( dat, x=time) / (tend-tbegin)
istroke = istroke + 1
return D
def write_csv_file( fname, d, header=None, sep=';'):
# open file, erase existing
f = open( fname, 'w', encoding='utf-8' )
# if we specified a header ( a list of strings )
# write that
if not header == None:
# write column headers
if isinstance(header, list):
for name in header[:-1]:
f.write( name+sep )
f.write(header[-1])
else:
f.write(header)
# newline after header
f.write('\n')
# check
nt, ncols = d.shape
for it in range(nt):
for icol in range(ncols-1):
f.write( '%e%s' % (d[it,icol], sep) )
# last column
f.write( '%e' % (d[it,-1]) )
# new line
f.write('\n')
f.close()
def read_param(config, section, key):
# read value
value = config[section].get(key)
if value is not None:
# remove comments and ; delimiter, which flusi uses for reading.
value = value.split(';')[0]
return value
def read_param_vct(config, section, key):
value = read_param(config, section, key)
if "," in value:
value = np.array( value.split(",") )
else:
value = np.array( value.split() )
value = value.astype(float)
return value
def fseries(y, n):
"""
Return the coefficients ai and bi from a truncated Fourier series of signal y
with n coefficients. Used for kinematics analysis and other encoding.
The coefficients are determined efficiently using FFT, but note the hermitian
symmetry of real input data. The zeroth mode is multiplied by a factor of
two, i.e., mean = a0/2.0.
If you request N=20 modes, we return a0 and ai[0:19] so a total of 20 numbers.
Zero mode is returned separately
Input:
------
y: vector, float
The actual data to be analyzed (e.g., angle time series). Note: it is assumed
to be sampled on an equidistant grid.
n: integer
Number of Fourier modes to use.
Output:
-------
a0, ai, bi: numpy arrays containing the real (ai) and imaginary (bi) parts of the n Fourier coefficients.
"""
# perform fft
yk = np.fft.fft(y)
# data length, for normalization
N = y.shape[0]
# return first n values, normalized (note factor 2.0 from hermite symmetry)
ai = +2.0*np.real( yk[0:n+1] ) / float(N)
bi = -2.0*np.imag( yk[0:n+1] ) / float(N)
a0 = ai[0]
ai, bi = ai[1:], bi[1:]
# I was not aware the the bi coefficients need to switch signs, but it seems they
# do have to indeed. this is related to the minus sign in the basis function (exp-i....)
# see: https://pages.mtu.edu/~tbco/cm416/fft1.pdf
return( a0, ai, bi )
def Fserieseval(a0, ai, bi, time):
"""
evaluate the Fourier series given by a0, ai, bi at the time instant time
note we divide amplitude of constant by 2 (which is compatible with "fseries")
function is vectorized; pass a vector of time instants for evaluation.
Input:
------
a0: float
zero mode (constant) for historical reasons, it is divided by two.
ai: vector, float
real parts of fourier coefficients
bi: vector, float
imag parts of fourier coefficients
time: vector, float
Output time vector at which to evaluate the hermite interpolation
Output:
-------
u: vector, float
Resulting data sampled at "time"
"""
if ai.shape[0] != bi.shape[0]:
raise ValueError("ai and bi must be of the same length!")
y = a0/2.0
for k in range( ai.size ):
# note pythons tedious 0-based indexing, so wavenumber is k+1
y = y + ai[k]*np.cos(2.0*np.pi*float(k+1)*time) + bi[k]*np.sin(2.0*np.pi*float(k+1)*time)
return y
def Hserieseval(a0, ai, bi, time):
"""
evaluate hermite series, given by coefficients ai (function values)
and bi (derivative values) at the locations x. Note that x is assumed periodic;
do not include x=1.0.
a valid example is x=(0:N-1)/N
Input:
------
a0: float
UNUSED dummy argument
ai: vector, float
Function values
bi: vector, float
Derivative values
time: vector, float
Output time vector at which to evaluate the hermite interpolation
Output:
-------
u: vector, float
Resulting data sampled at "time"
"""
#
# function is vectorized; pass a vector of time instants for evaluation.
#
if len( ai.shape ) != 1:
raise ValueError("ai must be a vector")
if len( bi.shape ) != 1:
raise ValueError("bi must be a vector")
if ai.shape[0] != bi.shape[0]:
raise ValueError("length of ai and bi must be the same")
time2 = time.copy()
# time periodization
while ( np.max(time2) >= 1.0 ):
time2[ time2 >= 1.0 ] -= 1.0
n = ai.shape[0]
dt = 1.0 / n
j1 = np.floor(time2/dt) # zero-based indexing in python
j1 = np.asarray(j1, dtype=int)
j2 = j1 + 1
# periodization
j2[ j2 > n-1 ] = 0 # zero-based indexing in python
# normalized time (between two data points)
t = (time2 - j1*dt) / dt
# values of hermite interpolant
h00 = (1.0+2.0*t)*((1.0-t)**2)
h10 = t*((1.0-t)**2)
h01 = (t**2)*(3.0-2.0*t)
h11 = (t**2)*(t-1.0)
# function value
u = h00*ai[j1] + h10*dt*bi[j1] + h01*ai[j2] + h11*dt*bi[j2]
return u
def read_kinematics_file( fname, unit_out='deg' ):
import configparser
import os
import inifile_tools
if not os.path.isfile(fname):
raise ValueError("File "+fname+" not found!")
config = configparser.ConfigParser( inline_comment_prefixes=(';'), allow_no_value=True )
# read the ini-file
config.read(fname)
if config['kinematics']:
convention = read_param(config,'kinematics','convention')
series_type = read_param(config,'kinematics','type')
# input file units
unit_in = inifile_tools.get_ini_parameter(fname,'kinematics', 'units', default='deg', dtype=str)
# options tolerated by FLUSI/WABBIT
if unit_in in ["degree","DEGREE","Degree","DEG","deg"]:
# simplified to deg/rad
unit_in = 'deg'
# options tolerated by FLUSI/WABBIT
if unit_in == ["radian","RADIAN","Radian","radiant","RADIANT","Radiant","rad","RAD"]:
# simplified to deg/rad
unit_in = 'rad'
if convention != "flusi":
raise ValueError("The kinematics file %s is using a convention not supported yet" % (fname))
if series_type == "fourier":
a0_phi = float(read_param(config,'kinematics','a0_phi'))
a0_alpha = float(read_param(config,'kinematics','a0_alpha'))
a0_theta = float(read_param(config,'kinematics','a0_theta'))
else:
a0_phi, a0_theta, a0_alpha = 0.0, 0.0, 0.0
ai_alpha = read_param_vct(config,'kinematics','ai_alpha')
bi_alpha = read_param_vct(config,'kinematics','bi_alpha')
ai_theta = read_param_vct(config,'kinematics','ai_theta')
bi_theta = read_param_vct(config,'kinematics','bi_theta')
ai_phi = read_param_vct(config,'kinematics','ai_phi')
bi_phi = read_param_vct(config,'kinematics','bi_phi')
if unit_out != unit_in:
# factor1 converts input to deg
if unit_in == 'deg':
factor1 = 1.0
else:
factor1 = 180.0/np.pi
# factor2 ensures desired output
if unit_out == 'deg':
factor2 = 1.0
else:
factor2 = np.pi/180.0
a0_phi *= factor1*factor2
a0_theta *= factor1*factor2
a0_alpha *= factor1*factor2
ai_alpha *= factor1*factor2
bi_alpha *= factor1*factor2
ai_theta *= factor1*factor2
bi_theta *= factor1*factor2
ai_phi *= factor1*factor2
bi_phi *= factor1*factor2
return a0_phi, ai_phi, bi_phi, a0_alpha, ai_alpha, bi_alpha, a0_theta, ai_theta, bi_theta, series_type
else:
print('This seems to be an invalid ini file as it does not contain the kinematics section')
def visualize_kinematics_file(fname, ax=None, savePDF=True, savePNG=False):
""" Read an INI file with wingbeat kinematics and plot the 3 angles over the period. Output written to a PDF and PNG file.
"""
import matplotlib.pyplot as plt
if ax is None:
plt.figure( figsize=(cm2inch(12), cm2inch(7)) )
plt.subplots_adjust(bottom=0.16, left=0.14)
ax = plt.gca()
t, phi, alpha, theta = eval_angles_kinematics_file(fname)
# plt.rcParams["text.usetex"] = False
ax.plot(t, phi , label='$\\phi$ (flapping)')
ax.plot(t, alpha, label='$\\alpha$ (feathering)')
ax.plot(t, theta, label='$\\theta$ (deviation)')
ax.legend()
ax.set_xlim([0,1])
ax.set_xlabel('$t/T$')
# axis y in degree
from matplotlib.ticker import EngFormatter
ax.yaxis.set_major_formatter(EngFormatter(unit="°"))
ax.set_title('$\\Phi=%2.2f^\\circ$ $\\phi_m=%2.2f^\\circ$ $\\phi_\\mathrm{max}=%2.2f^\\circ$ $\\phi_\\mathrm{min}=%2.2f^\\circ$' % (np.max(phi)-np.min(phi), np.mean(phi), np.max(phi), np.min(phi)))
indicate_strokes(ax=ax)
ax.tick_params( which='both', direction='in', top=True, right=True )
if savePDF:
plt.savefig( fname.replace('.ini','.pdf'), format='pdf' )
if savePNG:
plt.savefig( fname.replace('.ini','.png'), format='png' )
def csv_kinematics_file(fname):
""" Read an INI file with wingbeat kinematics and store the 3 angles over the period in a *.csv file
"""
t, phi, alpha, theta = eval_angles_kinematics_file(fname, time=np.linspace(0,1,100, endpoint=False) )
d = np.zeros([t.shape[0], 4])
d[:,0] = t
d[:,1] = phi
d[:,2] = alpha
d[:,3] = theta
write_csv_file( fname.replace('.ini', '.csv'), d, header=['time', 'phi', 'alpha', 'theta'], sep=';')
def eval_angles_kinematics_file(fname, time=None, unit_out='deg'):
"""
Parameters
----------
fname : string
Ini file to read the kinematics from.
time : array, optional
Time arry. If none is passed, we sample [0.0, 1.0) with n=1000 samples and return this as well
unit_out : str, optional
'rad' or 'deg' output of angles. defaults to 'deg'
Returns
-------
t : array
time. A copy of the input array or the default if no input time vector is given.
phi : array
flapping angle.
alpha : array
feathering angle.
theta : array
deviation angle.
"""
# read the kinematics INI file
a0_phi, ai_phi, bi_phi, a0_alpha, ai_alpha, bi_alpha, a0_theta, ai_theta, bi_theta, kine_type = read_kinematics_file(fname, unit_out=unit_out)
if time is None:
# time vector for plotting
t = np.linspace(0.0, 1.0, 1000, endpoint=False)
else:
t = time.copy()
if kine_type == "fourier":
alpha = Fserieseval(a0_alpha, ai_alpha, bi_alpha, t)
phi = Fserieseval(a0_phi , ai_phi , bi_phi , t)
theta = Fserieseval(a0_theta, ai_theta, bi_theta, t)
elif kine_type == "hermite":
alpha = Hserieseval(a0_alpha, ai_alpha, bi_alpha, t)
phi = Hserieseval(a0_phi , ai_phi , bi_phi , t)
theta = Hserieseval(a0_theta, ai_theta, bi_theta, t)