-
Notifications
You must be signed in to change notification settings - Fork 0
/
HawcPy.py
executable file
·2329 lines (1919 loc) · 83.6 KB
/
HawcPy.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
# -*- coding: utf-8 -*-
"""
Author: David Verelst
"""
from __future__ import division # always devide as floats
__author__ = 'David Verelst'
__license__ = 'GPL'
__version__ = '0.5'
from time import time
import scipy
import array
import numpy as np
import os
import logging
import copy
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.ticker import FormatStrFormatter
import wafo
import misc
PRECISION = np.float64
def linspace_around(start, stop, points=None, num=50, verbose=False):
"""
Create a linspace between an interval while considering some points
start < points < stop
"""
# data checks
if start > stop:
raise ValueError, 'start should be smaller than stop!'
# ordinary linspace of points is not defined
if type(points).__name__ == 'NoneType':
return np.linspace(start, stop, num=num)
res = np.array([start])
res = np.append(res, points)
res = np.append(res, stop)
# define the fractions and fill the linspace
# num-2 because we exclude start and stop points
num_missing = num - 2 - len(points)
if num_missing < 1:
raise ValueError, 'num has to be at least +3 longer than nr of points'
fractions = num_missing*(res[1:]-res[:-1])/res[-1]
# and see how that would translete to nr of points
distribution = np.around(fractions, decimals=0)
# missing points
deltas = distribution - fractions
# if we miss points, missing will be negative, too much points it will be
# possitive. This number is always either 1 or -1!!
missing = np.sum(deltas)
# add/remove missing point to largest delta interval
if missing < 0:
# we are missing a point, add one to the largest deficit
fractions[np.argmin(deltas)] -= missing
else:
# we have too many points, remove on the largest surplus
fractions[np.argmax(deltas)] -= missing
# convert to int
distribution = np.int32(np.around(fractions, decimals=0))
# fill up the gaps, start with the starting point, because we will allways
# ignore the first element of the linspace, to avoid double entries
res_fill= res[0]
for k in range(len(res)-1):
fill = np.linspace(res[k], res[k+1], num=(2+distribution[k]))
res_fill = np.append(res_fill, fill[1:])
if verbose:
print 'fractions', fractions
print 'distribution', distribution
print 'missing', missing
print 'res_fill', res_fill
print 'points', points
print len(res_fill), num
# and make sure we have the same number of elements as num and
if not len(res_fill) == num:
msg = 'result does not have the specified number of items'
raise ValueError, msg
# make sure we have an increasing set of numbers
if (res_fill[1:]-res_fill[:-1]).min() < 0:
raise ValueError, 'result is not strictly increasing'
return res_fill
def unique(s):
"""
SOURCE: http://code.activestate.com/recipes/52560/
AUTHOR: Tim Peters
Return a list of the elements in s, but without duplicates.
For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3],
unique("abcabc") some permutation of ["a", "b", "c"], and
unique(([1, 2], [2, 3], [1, 2])) some permutation of
[[2, 3], [1, 2]].
For best speed, all sequence elements should be hashable. Then
unique() will usually work in linear time.
If not possible, the sequence elements should enjoy a total
ordering, and if list(s).sort() doesn't raise TypeError it's
assumed that they do enjoy a total ordering. Then unique() will
usually work in O(N*log2(N)) time.
If that's not possible either, the sequence elements must support
equality-testing. Then unique() will usually work in quadratic
time.
"""
n = len(s)
if n == 0:
return []
# Try using a dict first, as that's the fastest and will usually
# work. If it doesn't work, it will usually fail quickly, so it
# usually doesn't cost much to *try* it. It requires that all the
# sequence elements be hashable, and support equality comparison.
u = {}
try:
for x in s:
u[x] = 1
except TypeError:
del u # move on to the next method
else:
return u.keys()
# We can't hash all the elements. Second fastest is to sort,
# which brings the equal elements together; then duplicates are
# easy to weed out in a single pass.
# NOTE: Python's list.sort() was designed to be efficient in the
# presence of many duplicate elements. This isn't true of all
# sort functions in all languages or libraries, so this approach
# is more effective in Python than it may be elsewhere.
try:
t = list(s)
t.sort()
except TypeError:
del t # move on to the next method
else:
assert n > 0
last = t[0]
lasti = i = 1
while i < n:
if t[i] != last:
t[lasti] = last = t[i]
lasti += 1
i += 1
return t[:lasti]
# Brute force is all that's left.
u = []
for x in s:
if x not in u:
u.append(x)
return u
def remove_items(list, value):
"""Remove items from list
The given list wil be returned withouth the items equal to value.
Empty ('') is allowed. So this is een extension on list.remove()
"""
# remove list entries who are equal to value
ind_del = []
for i in xrange(len(list)):
if list[i] == value:
# add item at the beginning of the list
ind_del.insert(0, i)
# remove only when there is something to remove
if len(ind_del) > 0:
for k in ind_del:
del list[k]
return list
def SignalStatisticsNew(sig, start=0, stop=-1, dtype='Float64'):
"""
Statistical properties of a HAWC2 result file
=============================================
Input:
sig as outputted by the class LoadResults: sig[timeStep,channel]
start, stop: indices (not the time!!) of starting and stopping point
in the signal matrix. This option allows you to skip a period at the
beginning or the end of the time series
Default start and stop are for the entire signal range. Note that
np.array[0:-1] will exclude the last element! You should use
np.array[0:len(array)]
Output:
np array:
sig_stat = [(0=value,1=index),statistic parameter, channel]
statistic parameter = 0 max, 1 min, 2 mean, 3 std, 4 range, 5 abs max
Or just input a time series.
"""
# convert index -1 to also inlcude the last element:
if stop == -1:
stop = len(sig)
nr_statistics = 6
sig_stats = scipy.zeros([2,nr_statistics, sig.shape[1]], dtype=dtype)
# calculate the statistics values:
sig_stats[0,0,:] = sig[start:stop,:].max(axis=0)
sig_stats[0,1,:] = sig[start:stop,:].min(axis=0)
sig_stats[0,2,:] = sig[start:stop,:].mean(axis=0)
sig_stats[0,3,:] = sig[start:stop,:].std(axis=0)
sig_stats[0,4,:] = sig_stats[0,0,:] - sig_stats[0,1,:] # range
sig_stats[0,5,:] = np.absolute(sig[start:stop,:]).max(axis=0)
# and the corresponding indices:
sig_stats[1,0,:] = sig[start:stop,:].argmax(axis=0)
sig_stats[1,1,:] = sig[start:stop,:].argmin(axis=0)
# not relevant for mean, std and range
sig_stats[1,2,:] = 0
sig_stats[1,3,:] = 0
sig_stats[1,4,:] = 0 # range
sig_stats[1,5,:] = np.absolute(sig[start:stop,:]).argmax(axis=0)
return sig_stats
class ModelData:
# DEPRICATED, use Simulations.ModelData instead!!
"""
DEPRICATED, use Simulations.ModelData instead!!
Make plots of defined HAWC2 model:
* aerodynamic coeficients in the .pc file
* chord and twist distributions in the .ae file
* structural properties in the .st file
"""
class st_headers:
"""
Indices to the respective parameters in the HAWC2 st data file
"""
r = 0
m = 1
x_cg = 2
y_cg = 3
ri_x = 4
ri_y = 5
x_sh = 6
y_sh = 7
E = 8
G = 9
Ixx = 10
Iyy = 11
I_p = 12
k_x = 13
k_y = 14
A = 15
pitch = 16
x_e = 17
y_e = 18
def __init__(self):
"""
"""
self.data_path = None
# saving plots in the same directory
self.save_path = None
self.ae_file = 'somefile.ae'
self.pc_file = 'somefile.pc'
self.st_file = 'somefile.st'
self.debug = False
# relevant for write_st2
self.st_file2 = 'somefile2.st'
self.st2_filemode = 'w'
# define the column width for printing
self.col_width = 13
# formatting and precision
self.float_hi = 999.9999
self.float_lo = 0.01
self.prec_float = ' 8.04f'
self.prec_exp = ' 8.04e'
#0 1 2 3 4 5 6 7 8 9 10 11
#r m x_cg y_cg ri_x ri_y x_sh y_sh E G I_x I_y
#12 13 14 15 16 17 18
#I_p/K k_x k_y A pitch x_e y_e
# 19 cols
self.st_column_header_list = ['r', 'm', 'x_cg', 'y_cg', 'ri_x', \
'ri_y', 'x_sh', 'y_sh', 'E', 'G', 'I_x', 'I_y', 'I_p/K', 'k_x', \
'k_y', 'A', 'pitch', 'x_e', 'y_e']
self.st_column_header_list_latex = ['r','m','x_{cg}','y_{cg}','ri_x',\
'ri_y', 'x_{sh}','y_{sh}','E', 'G', 'I_x', 'I_y', 'J', 'k_x', \
'k_y', 'A', 'pitch', 'x_e', 'y_e']
self.column_header_line = ''
for k in self.st_column_header_list:
self.column_header_line += k.rjust(self.col_width)
def _data_checks(self):
"""
Data Checks on self
===================
"""
if self.data_path is None:
raise UserWarning, 'specify data_path first'
def fromline(self, line, separator=' '):
# TODO: move this to the global function space (dav-general-module)
"""
split a line, but ignore any blank spaces and return a list with only
the values, not empty places
"""
# remove all tabs, new lines, etc? (\t, \r, \n)
line = line.replace('\t',' ').replace('\n','').replace('\r','')
line = line.split(separator)
values = []
for k in range(len(line)):
if len(line[k]) > 0: #and k == item_nr:
values.append(line[k])
# break
return values
def load_pc(self):
"""
Load the Profile coeficients file (pc)
======================================
DEPRICATED, use Simulations.ModelData instead!!
Members
-------
pc_dict : dict
pc_dict[pc_set] = [label,tc_ratio,data]
data = array[AoA [deg], C_L, C_D, C_M]
"""
self._data_checks()
FILE = open(self.data_path + self.pc_file)
lines = FILE.readlines()
FILE.close()
self.pc_dict = dict()
# dummy values for
nr_points, start, point = -10, -10, -10
# go through all the lines
n = 0
for line in lines:
# create a list with all words on the line
line_list = self.fromline(line)
if self.debug:
# print n, ' -- ', line
print n, start, start+nr_points, \
line_list[0:4],
# ignore empty lines
if len(line_list) < 2:
if self.debug:
print 'empty line ignored'
# first two lines are not relevant in this context
elif n == 0 or n == 1:
# number of data sets
# nr_sets = int(line_list[0])
pass
# the first set, label line
elif n == 2:
set_nr = int(line_list[0])
# nr of points in set
nr_points = int(line_list[1])
tc_ratio = line_list[2]
start = n
# back to a string and skip the first 2 elements
label = ''
for m in range(len(line_list)-2):
label += line_list[m+2]
label += ' '
label = label.rstrip()
data = scipy.zeros((nr_points,4),dtype=PRECISION)
if self.debug:
print ' -> first set'
# the other sets, label line
elif (n - nr_points-1) == start:
# save the previous data set
self.pc_dict[set_nr] = [label,tc_ratio,data]
set_nr = int(line_list[0])
# number of data points in this set
nr_points = int(line_list[1])
tc_ratio = line_list[2]
# mark start line of data set
start = n
# new data array for the dataset
data = scipy.zeros((nr_points,4),dtype=PRECISION)
# back to a string and skip the first element ()
label = ''
for m in range(len(line_list)-2):
label += line_list[m+2]
label += ' '
label = label.rstrip()
if self.debug:
print ' -> other sets, label line'
# if in between, save the data
elif n > start and n <= (start + nr_points):
# only take the first 4 elements, rest of line can be comments
data[n-start-1,:] = line_list[0:4]
if self.debug:
print ' -> data line',
print n-start-1, '/', nr_points
else:
msg = 'ERROR in ae file, the contents is not correctly defined'
raise UserWarning, msg
n += 1
# save the last label and data array to the dictionary
self.pc_dict[set_nr] = [label,tc_ratio,data]
# TODO: implement aspect ratio determination
def load_ae(self):
"""
Load the aerodynamic layout file (.ae)
======================================
DEPRICATED, use Simulations.ModelData instead!!
Members
-------
ae_dict : dict
ae_dict[ae_set] = [label, data_array]
data_array = [Radius [m], Chord[m], T/C[%], Set no. of pc file]
"""
self._data_checks()
FILE = open(self.data_path + self.ae_file)
lines = FILE.readlines()
FILE.close()
self.ae_dict = dict()
# dummy values for
nr_points, start, point = -10, -10, -10
# go through all the lines
n = 0
for line in lines:
# create a list with all words on the line
line_list = self.fromline(line)
if self.debug:
# print n, ' -- ', line
print n, start, start+nr_points, \
line_list[0:4],
# ignore empty lines
if len(line_list) < 2:
if self.debug:
print 'empty line ignored'
# first line is the header stating how many sets
elif n == 0:
# number of data sets
# nr_sets = int(line_list[0])
pass
# the first set, label line
elif n == 1:
# nr of points in set
set_nr = int(line_list[0])
nr_points = int(line_list[1])
start = n
# back to a string and skip the first 2 elements
label = ''
for m in range(len(line_list)-2):
label += line_list[m+2]
label += ' '
label = label.rstrip()
data = scipy.zeros((nr_points,4),dtype=PRECISION)
if self.debug:
print ' -> first set'
# the other sets, label line
elif (n - nr_points-1) == start:
# save the previous data set
self.ae_dict[set_nr] = [label,data]
set_nr = int(line_list[0])
# number of data points in this set
nr_points = int(line_list[1])
# mark start line of data set
start = n
# new data array for the dataset
data = scipy.zeros((nr_points,4),dtype=PRECISION)
# back to a string and skip the first element ()
label = ''
for m in range(len(line_list)-2):
label += line_list[m+2]
label += ' '
label = label.rstrip()
if self.debug:
print ' -> other sets, label line'
# if in between, save the data
elif n > start and n <= (start + nr_points):
# only take the first 4 elements, rest of line can be comments
data[n-start-1,:] = line_list[0:4]
if self.debug:
print ' -> data line',
print n-start-1, '/', nr_points
else:
msg = 'ERROR in ae file, the contents is not correctly defined'
raise UserWarning, msg
n += 1
# save the last label and data array to the dictionary
self.ae_dict[set_nr] = [label,data]
def load_st(self):
"""
Load the structural data file (.st)
===================================
DEPRICATED, use Simulations.ModelData instead!!
Load a given st file into st_dict
This could actually be taken care of by pyparsing....
Members
-------
st_dict : dict
st_dict[tag] = [data]
possible tag/data combinations:
st_dict[tag + set_nr + '-' + sub_set_nr + '-data'] = sub_set_arr
sub_set_arr has following columns:
0 1 2 3 4 5 6 7 8 9 10 11 12
r m x_cg y_cg ri_x ri_y x_sh y_sh E G I_x I_y J
13 14 15 16 17 18
k_x k_y A pitch x_e y_e
each row is a new data point
The sorted st_dict.keys() key/value pairs looks as follows
00-00-header_comments : list
00-00-nset : list
01-00-setcomments : list
01-01-comments : list
01-01-data : ndarray
02-00-setcomments : list
02-01-comments : list
02-01-data : ndarray
A new set is created if a setcomments tags is present
Comments are placed in an iterable (list, tuple,...). Each element
gets a space placed in between.
"""
self._data_checks()
# TODO: store this in an HDF5 format! This is perfect for that.
# the structural file saved in a structured way
# keep track of how many subsets there are in each set
self.subsets_per_set = []
# also remember how many sets and how many subsets in each set.
# this to faciliate to add more sets later
if self.debug:
print 'loading st file from:'
print self.data_path + self.st_file
# read all the lines of the file into memory
FILE = open(self.data_path + self.st_file)
lines = FILE.readlines()
FILE.close()
# all flags to false
start_sets, set_comments, sub_set = False, False, False
self.st_dict = dict()
for nr in range(len(lines)):
# first, read all the items in the line, loose all spaces, which
# can vary over the document
items = self.fromline(lines[nr])
# nr_items = len(items)
# if we have an empty line, items will be an empty list.
# Because we investigate the first item of items, append an empty
# string, otherwise we get an index error
if len(items) == 0:
items.append('')
# for sorting the keys back in the right order, based on line number
tag = format(nr+1, '04.0f') + '-'
# or just emtpy
tag = ''
if self.debug == True:
if nr == 0:
print 'start_sets, startwith #, set_comments, ',
print 'startswith $, sub_set, len(items)'
print nr+1, start_sets, items[0].startswith('#'),
print set_comments, items[0].startswith('$'), len(items)
print items
# first line: number of sets is the first item
if nr == 0:
# nset = int(items[0])
# and save to dict
self.st_dict[tag + '00-00-nset'] = items
# prepare the header comments
header_comments = []
# after the first line, you can have all kind of crap lines, holding
# any comments you like
# the "and not..." will trigger to go the next type of line
elif not start_sets and not items[0].startswith('#'):
header_comments.append(items)
# each set starts with #1, followed by comments/name/whatever
elif items[0].startswith('#'):
# when we just leave the header comments, save it first
if not start_sets:
self.st_dict[tag +'00-00-header_comments'] = header_comments
start_sets = True
# read the set number, attached to # withouth space
set_nr = int(items[0][1:len(items[0])])
# make a big comments list, where each line is a new list
comments = []
comments.append(items)
set_comments = True
self.subsets_per_set.append([])
# more comments are allowed to follow until the start of a
# subset, marked with $
elif set_comments and not items[0].startswith('$'):
comments.append(items)
# if we have a subset (starting with $)
elif items[0].startswith('$') and not sub_set:
# next time we can start with the subset
sub_set = True
# sub set number
sub_set_nr = int(items[0][1:len(items[0])])
# attach the sub_set_nr to the current set
self.subsets_per_set[-1].append(sub_set_nr)
# also store the set comments
if set_comments:
tmp = format(set_nr, '02.0f')
self.st_dict[tag + str(tmp) + '-00-setcomments']=comments
# stop the set comments
set_comments = False
# read the number of data points
nr_points = int(items[1])
point = 0
# store the sub set comments included on this line
tmp1 = format(set_nr, '02.0f')
tmp2 = format(sub_set_nr, '02.0f')
self.st_dict[tag+str(tmp1)+'-'+str(tmp2)+'-comments'] \
= items
# create array to store all the data points:
sub_set_arr = scipy.zeros((nr_points,19), dtype = np.float128)
# if the we have the data points
elif len(items) == 19 and sub_set:
if point < nr_points-1:
# we can store it in the array
sub_set_arr[point,:] = items
point += 1
# on the last entry:
elif point == nr_points-1:
sub_set_arr[point,:] = items
tmp1 = format(set_nr, '02.0f')
tmp2 = format(sub_set_nr, '02.0f')
# save to the dict:
self.st_dict[tag + str(tmp1)+'-'+str(tmp2)+'-data']\
= sub_set_arr
# and prepare for the next loop
sub_set = False
# save the last data points to st_dict
tmp1 = format(set_nr, '02.0f')
tmp2 = format(sub_set_nr, '02.0f')
self.st_dict[tag + str(tmp1)+'-'+str(tmp2)+'-data'] = sub_set_arr
def plot_pc(self, ylim=None, xlim=None):
"""
Plot given pc set
=================
DEPRICATED, use Simulations.ModelData instead!!
pc_dict[pc_set] = [label,tc_ratio,data]
data = array[AoA [deg], C_L, C_D, C_M]
WARNING: only one aero set is supported for the moment!
"""
# load the pc file
self.load_pc()
if self.debug:
print 'saving pc plots in:',self.data_path
# plot all aero data
# pc_sets = self.pc_dict.keys()
# nr_sets = len(pc_sets)
for k in self.pc_dict.iteritems():
# k is now a key, value pair of the dictionary
pc_set = k[0]
label = k[1][0]
tc_ratio = k[1][1]
data = k[1][2]
x = data[:,0]
# add_subplot(nr rows nr cols plot_number)
# initialize the plot object
fig = Figure(figsize=(16, 9), dpi=200)
canvas = FigureCanvas(fig)
fig.set_canvas(canvas)
ax = fig.add_subplot(1,2,1)
ax.plot(x,data[:,1], 'bo-', label=r'$C_L$')
ax.plot(x,data[:,2], 'rx-', label=r'$C_D$')
ax.plot(x,data[:,3], 'g*-', label=r'$C_M$')
ax.set_xlim([-180,180])
if type(ylim).__name__ == 'list':
ax.set_ylim(ylim)
if type(xlim).__name__ == 'list':
ax.set_xlim(xlim)
ax.set_xlabel('Angle of Attack [deg]')
ax.legend()
ax.grid(True)
ax = fig.add_subplot(1,2,2)
ax.plot(data[:,2],data[:,1], 'bo-')
ax.set_xlabel(r'$C_D$')
ax.set_ylabel(r'$C_L$')
ax.grid(True)
fig.suptitle(label)
figpath = self.save_path + self.pc_file + '_set' + str(pc_set) + \
'_tc_' + str(tc_ratio)
fig.savefig(figpath + '.eps')
print 'saved:', figpath + '.eps'
fig.savefig(figpath + '.png')
print 'saved:', figpath + '.png'
# canvas.close()
fig.clear()
def plot_ae(self, ae_set):
"""
Plot given ae set
=================
"""
# load the ae file
self.load_ae()
if self.debug:
print 'saving ae plots in:',self.data_path
# print 'ae_dict.keys', self.ae_dict.keys()
label = self.ae_dict[ae_set][0]
data = self.ae_dict[ae_set][1]
x = data[:,0]
x_label = 'blade radius [m]'
# self.numStepsY = 10
# self.numStepsX = 10
# add_subplot(nr rows nr cols plot_number)
fig = Figure(figsize=(8, 4), dpi=200)
canvas = FigureCanvas(fig)
fig.set_canvas(canvas)
ax = fig.add_subplot(1,1,1)
ax.plot(x,data[:,1], 'bo-', label='chord')
ax.set_xlabel(x_label)
# ax.set_yticks(plt.linspace(plt.ylim()[0],plt.ylim()[1],self.numStepsY))
# ax.set_xticks(plt.linspace(plt.xlim()[0],plt.xlim()[1],self.numStepsX))
ax.plot(x,data[:,2]/100.0, 'rx-', label='T/C')
# set the ticks the same way as on the left axes
# ax2.set_yticks(plt.linspace(plt.ylim()[0],plt.ylim()[1],self.numStepsY))
# ax2.set_xticks(plt.linspace(plt.xlim()[0],plt.xlim()[1],self.numStepsX))
ax.legend(loc='upper right')
ax.grid(True)
fig.suptitle(label)
figpath = self.save_path+self.ae_file +'_set' + str(ae_set)
fig.savefig(figpath + '.png')
# canvas.close()
fig.clear()
if self.debug:
print 'saved;',figpath+'.png'
def plot_st(self, sets):
"""
Plot a list of set-subset pairs
===============================
Parameters
----------
sets : list
[ [set, subset], [set, subset], ... ]
"""
# load the structure file
self.load_st()
# number of sets in the file
# nr_sets = int(st_dict['0-0-nset'][0])
if self.debug:
print 'saving st plots in:',self.save_path
print self.st_dict.keys()
# # plot all subsets
# for k in range(nr_sets):
# define the label precision
majorFormatter = FormatStrFormatter('%1.1e')
set_labels = self.st_column_header_list_latex
# plot given set-subsets
for x in sets:
# define the set-subset numbers
k = x[0] -1
i = x[1] -1
# get the set name, the set_comments object looks like
# [['#1', 'Blade', 'data'], ['r', 'm', 'x_cg', 'y_cg', 'ri_x',
# 'ri_y', 'x_sh', 'y_sh', 'E', 'G', 'I_x', 'I_y', 'I_p/K', 'k_x',
# 'k_y', 'A', 'pitch', 'x_e', 'y_e']]
set_comment=self.st_dict[format(k+1,'02.0f')+'-00-setcomments'][0]
# set_labels =self.st_dict[format(k+1,'02.0f')+'-00-setcomments'][1]
set_comment_str = ''
# back to a string and skip the first element ()
for m in range(len(set_comment)-1):
set_comment_str += set_comment[m+1]
set_comment_str += ' '
set_comment_str = set_comment_str.rstrip()
# color-label for left and right axis plots
left = 'bo-'
right = 'rx-'
ax2_left = 'ko-'
ax2_right = 'gx-'
label_size = 'large'
legend_ax1 = 'upper right'
legend_ax2 = ''
# # cycle through all subsets
# # assume there are maximum 20 subsets
# for i in range(20):
# see if the subset exists
try:
data = self.st_dict[format(k+1,'02.0f') \
+ '-' + format(i+1,'02.0f') + '-data']
# if the subset does not exist, go to the next set
except KeyError:
print 'Can\'t find set in st_dict:'
print format(k+1,'02.0f')+'-'+format(i+1,'02.0f')+'-data'
continue
if self.debug:
print 'set ' + format(k+1, '02.0f'),
print 'subset ' + format(i+1, '02.0f')
# and plot some items of the structural data
fig = Figure(figsize=(16, 9), dpi=200)
canvas = FigureCanvas(fig)
fig.set_canvas(canvas)
ax = fig.add_subplot(2, 3, 1)
fig.subplots_adjust(left= 0.1, bottom=0.1, right=0.9,
top=0.95, wspace=0.35, hspace=0.2)
# x-axis is always the radius
x = data[:,0]
# mass
ax.plot(x,data[:,1], left, label=r'$'+set_labels[1]+'$')
ax.legend()
ax.set_xlabel(r'$' + set_labels[0] + '$', size=label_size)
ax.yaxis.set_major_formatter(majorFormatter)
ax.grid(True)
# x_cg and y_cg and pitch
ax = fig.add_subplot(2, 3, 2)
ax.plot(x,data[:,2], left, label=r'$'+set_labels[2]+'$')
ax.plot(x,data[:,3], right, label=r'$'+set_labels[3]+'$')
ax.plot(x,data[:,16], ax2_left, label=r'$'+set_labels[16]+'$')
ax.legend(loc=legend_ax1)
# plt.grid(True)
# ax2 = ax.twinx()
# ax2.legend(loc='upper right')
ax.set_xlabel(r'$' + set_labels[0] + '$', size=label_size)
ax.yaxis.set_major_formatter(majorFormatter)
ax.grid(True)
# x_sh and y_sh, x_e and y_e
ax = fig.add_subplot(2, 3, 3)
ax.plot(x,data[:,6], left,label=r'$'+set_labels[6]+'$')
ax.plot(x,data[:,7], right, label=r'$'+set_labels[7]+'$')
ax.yaxis.set_major_formatter(majorFormatter)
ax.grid(True)
ax2 = ax.twinx()
ax2.plot(x,data[:,17], ax2_left, label=r'$'+set_labels[17]+'$')
ax2.plot(x,data[:,18], ax2_right, label=r'$'+set_labels[18]+'$')
ax.legend(loc='upper left')
ax2.legend(loc='upper right')
ax.set_xlabel(r'$' + set_labels[0] + '$', size=label_size)
ax.yaxis.set_major_formatter(majorFormatter)
ax2.yaxis.set_major_formatter(majorFormatter)
ax.grid(True)
# second row of plots
# EI_x and EI_y
ax = fig.add_subplot(2, 3, 4)
label = set_labels[8] + '*' + set_labels[10]
ax.plot(x,data[:,8]*data[:,10], left, label=r'$'+label+'$')
# ax2 = ax.twinx()
label = set_labels[8] + '*' + set_labels[11]
ax.plot(x,data[:,8]*data[:,11], right, label=r'$'+label+'$')
ax.legend(loc=legend_ax1)
# ax2.legend(loc='upper right')
ax.set_xlabel(r'$' + set_labels[0] + '$', size=label_size)
ax.yaxis.set_major_formatter(majorFormatter)
ax.grid(True)
# m*ri_x and m*ri_y
ax = fig.add_subplot(2, 3, 5)
label = set_labels[1] + '*' + set_labels[4] + '^2'
ax.plot(x,data[:,1]*np.power(data[:,4],2),
left, label=r'$'+label+'$')
# ax2 = ax.twinx()
label = set_labels[1] + '*' + set_labels[5] + '^2'
ax.plot(x,data[:,1]*np.power(data[:,5],2),