-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbaselib.py
executable file
·1719 lines (1505 loc) · 71.3 KB
/
baselib.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
# --------------------------------------------------------------------------
# Blendyn -- file baselib.py
# Copyright (C) 2015 -- 2021 Andrea Zanoni -- [email protected]
# --------------------------------------------------------------------------
# ***** BEGIN GPL LICENSE BLOCK *****
#
# This file is part of Blendyn, add-on script for Blender.
#
# Blendyn is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Blendyn is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Blendyn. If not, see <http://www.gnu.org/licenses/>.
#
# ***** END GPL LICENCE BLOCK *****
# --------------------------------------------------------------------------
from mathutils import *
from math import *
import bpy
from bpy.props import *
import logging
import numpy as np
import os, csv, atexit, re
from .nodelib import *
from .elementlib import *
from .rfmlib import *
from .componentlib import DEFORMABLE_ELEMENTS
from .logwatcher import *
from .stresslib import *
HAVE_PSUTIL = False
try:
import psutil
HAVE_PSUTIL = True
except ImportError:
pass
try:
from netCDF4 import Dataset
except ImportError:
message = "BLENDYN: could not find netCDF4 module. NetCDF import "\
+ "will be disabled."
print(message)
logging.warning(message)
pass
def parse_input_file(context):
mbs = context.scene.mbdyn
out_file = mbs.input_path
with open(out_file) as of:
reader = csv.reader(of, delimiter=' ', skipinitialspace=True)
while True:
rw = next(reader)
print(rw)
if rw:
first = rw[0].strip()
if first == 'final':
time = rw[2]
try:
time = float(time[:-1])
except ValueError:
mbs.final_time = mbs.ui_time
break
mbs.final_time = time
mbs.ui_time = time
break
if HAVE_PSUTIL:
def kill_mbdyn():
mbdynProc = [var for var in psutil.process_iter() if var.name() == 'mbdyn']
if mbdynProc:
mbdynProc[0].kill()
def get_plot_vars_glob(context):
mbs = context.scene.mbdyn
if mbs.use_netcdf:
ncfile = os.path.join(os.path.dirname(mbs.file_path), \
mbs.file_basename + '.nc')
nc = Dataset(ncfile, 'r')
N = len(nc.variables["time"])
var_list = list()
for var in nc.variables:
m = nc.variables[var].shape
if (m[0] == N) and (var not in mbs.plot_vars.keys()):
plotvar = mbs.plot_vars.add()
plotvar.name = var
def get_plot_engine():
HAVE_MATPLOTLIB = True
HAVE_PYGAL = True
HAVE_BOKEH = True
try:
import matplotlib
except ImportError:
HAVE_MATPLOTLIB = False
try:
import pygal
except ImportError:
HAVE_PYGAL = False
try:
import bokeh
except ImportError:
HAVE_BOKEH = False
is_have_engine = [HAVE_PYGAL, HAVE_MATPLOTLIB, HAVE_BOKEH]
plot_engines = [("PYGAL", "Pygal", "Pygal", '', 2), \
("MATPLOTLIB", "Matplotlib", "Matplotlib", '', 1), \
("BOKEH", "Bokeh", "bokeh", '', 3)]
return [plot_engines[i] for i in range(len(is_have_engine)) if is_have_engine[i]]
def update_driver_variables(self, context):
mbs = bpy.context.scene.mbdyn
pvar = mbs.plot_vars[mbs.plot_var_index]
if pvar.as_driver:
dvar = mbs.driver_vars.add()
dvar.name = pvar.name
dvar.variable = pvar.name
dvar.components = pvar.plot_comps
else:
idx = [idx for idx in range(len(mbs.driver_vars)) if mbs.driver_vars[idx].name == pvar.name]
mbs.driver_vars.remove(idx[0])
## Function that sets up the data for the import process
def setup_import(filepath, context):
mbs = context.scene.mbdyn
mbs.file_path, mbs.file_basename = path_leaf(filepath)
if filepath[-2:] == 'nc':
nc = Dataset(filepath, "r")
mbs.use_netcdf = True
mbs.num_rows = 0
mbs.num_nodes = nc.dimensions['struct_node_labels_dim'].size
mbs.num_timesteps = nc.dimensions['time'].size
try:
NVecs = [dim for dim in nc.dimensions if 'iNVec_out' in dim]
for ii in range(0, len(NVecs)):
eigsol = mbs.eigensolutions.add()
eigsol.index = int(NVecs[ii][4:-10])
try:
eigsol.step = nc.variables['eig.' + str(ii) + '.step'][0]
eigsol.time = nc.variables['eig.' + str(ii) + '.time'][0]
eigsol.dCoef = nc.variables['eig.' + str(ii) + '.dCoef'][0]
except KeyError:
# Maybe we are dealing with old output?
eigsol.step = nc.variables['eig.step'][eigsol.index]
eigsol.time = nc.variables['eig.time'][eigsol.index]
eigsol.dCoef = nc.variables['eig.dCoef'][eigsol.index]
eigsol.iNVec = nc.dimensions[NVecs[ii]].size
eigsol.curr_eigmode = 1
except KeyError as err:
message = 'BLENDYN::setup_import(): ' + \
'no valid eigenanalysis results found'
print(message)
logging.info(message)
pass
# by default, we remove the log files on exit
atexit.register(delete_log)
get_plot_vars_glob(context)
else:
mbs.use_netcdf = False
mbs.num_rows = file_len(filepath)
if mbs.num_rows < 0:
return {'FILE_ERROR'}
return {'FINISHED'}
# -----------------------------------------------------------
# end of setup_import() function
def number_modal_modes(context):
"""Check for total modal modes in .mod file"""
mbs = context.scene.mbdyn
if os.path.isfile(os.path.join(os.path.dirname(mbs.file_path), mbs.file_basename + '.mod')):
mod_file = os.path.join(os.path.dirname(mbs.file_path), mbs.file_basename + '.mod')
with open(mod_file) as mdf:
reader_mod = csv.reader(mdf, delimiter = ' ', skipinitialspace = True)
rw_mod = next(reader_mod)
first_mode = rw_mod[0]
num_modal_modes = 0
while True:
num_modal_modes += 1
try:
rw_mod = next(reader_mod)
except StopIteration:
break
mode = rw_mod[0]
if mode == first_mode:
break
mbs.num_modal_modes = num_modal_modes
else:
mbs.num_modal_modes = 0
pass
#---------------------------------------------------------------
# end of number_modal_modes() function
def no_output(context):
"""Check for nodes with no output"""
mbs = context.scene.mbdyn
nd = mbs.nodes
if mbs.use_netcdf:
ncfile = os.path.join(os.path.dirname(mbs.file_path), \
mbs.file_basename + '.nc')
nc = Dataset(ncfile, "r")
log_nodes = list(map(lambda x: int(x[5:]), nd.keys()))
for node in log_nodes:
try:
X = nc.variables['node.struct.' + str(node) + '.X']
nd['node_' + str(node)].output = True
except KeyError:
# output disabled for this node
pass
else:
# .mov filename
mov_file = os.path.join(os.path.dirname(mbs.file_path), \
mbs.file_basename + '.mov')
try:
with open(mov_file) as mf:
reader = csv.reader(mf, delimiter = ' ', skipinitialspace = True)
rw = next(reader)
first_node = int(rw[0])
num_nodes = 0
while True:
node = [node for node in nd if node.int_label == int(rw[0])]
num_nodes += 1
if node:
node[0].output = True
rw = next(reader)
if int(rw[0]) == first_node:
break
mbs.num_nodes = num_nodes
except StopIteration: # EOF
pass
# -----------------------------------------------------------
# end of no_output() function
def parse_log_file(context):
""" Parses the .log file and calls parse_elements() to add elements
to the elements dictionary and parse_node() to add nodes to
the nodes dictionary """
# utility rename
mbs = context.scene.mbdyn
nd = mbs.nodes
ed = mbs.elems
rd = mbs.references
is_init_nd = len(nd) == 0
is_init_ed = len(ed) == 0
for node_name in nd.keys():
nd[node_name].is_imported = False
for elem_name in ed.keys():
ed[elem_name].is_imported = False
log_file = os.path.join(os.path.dirname(mbs.file_path), \
mbs.file_basename + '.log')
out_file = os.path.join(os.path.dirname(mbs.file_path), \
mbs.file_basename + '.out')
rfm_file = os.path.join(os.path.dirname(mbs.file_path), \
mbs.file_basename + '.rfm')
# Debug message to console
print("Blendyn::parse_log_file(): Trying to read nodes and elements from file: "\
+ log_file)
ret_val = {''}
# Check if collections are already present (not the first import).
# if not, create them
try:
ncol = bpy.data.collections['mbdyn.nodes']
except KeyError:
ncol = bpy.data.collections.new(name = 'mbdyn.nodes')
bpy.context.scene.collection.children.link(ncol)
try:
ecol = bpy.data.collections['mbdyn.elements']
except KeyError:
ecol = bpy.data.collections.new(name = 'mbdyn.elements')
bpy.context.scene.collection.children.link(ecol)
# create elements children collections if they are not already there
try:
aecol = ecol.children['aerodynamic']
except KeyError:
aecol = bpy.data.collections.new(name = 'aerodynamic')
ecol.children.link(aecol)
try:
becol = ecol.children['beams']
except KeyError:
becol = bpy.data.collections.new(name = 'beams')
ecol.children.link(becol)
# elements sections sub-collection
try:
scol = ecol.children['sections']
except KeyError:
scol = bpy.data.collections.new(name = 'sections')
ecol.children.link(scol)
try:
bocol = ecol.children['bodies']
except KeyError:
bocol = bpy.data.collections.new(name = 'bodies')
ecol.children.link(bocol)
try:
fcol = ecol.children['forces']
except KeyError:
fcol = bpy.data.collections.new(name = 'forces')
ecol.children.link(fcol)
try:
jcol = ecol.children['joints']
except KeyError:
jcol = bpy.data.collections.new(name = 'joints')
ecol.children.link(jcol)
try:
pcol = ecol.children['plates']
except KeyError:
pcol = bpy.data.collections.new(name = 'plates')
ecol.children.link(pcol)
try:
with open(log_file) as lf:
# open the reader, skipping initial whitespaces
b_nodes_consistent = True
b_elems_consistent = True
reader = csv.reader(lf, delimiter=' ', skipinitialspace=True)
entry = ""
while entry[:-1] != "Symbol table":
# get the next row
rw = next(reader)
entry = rw[0]
ii = 0
while (rw[ii][-1] != ':') and (ii < min(3, (len(rw) - 1))):
ii = ii + 1
entry = entry + " " + rw[ii]
if ii == min(3, (len(rw) - 1)):
print("Blendyn::parse_log_file(): row does not contain an element definition. Skipping...")
elif entry == "structural node:":
print("Blendyn::parse_log_file(): Found a structural node.")
b_nodes_consistent = b_nodes_consistent * (parse_node(context, rw))
else:
print("Blendyn::parse_log_file(): Found " + entry[:-1] + " element.")
b_elems_consistent = b_elems_consistent * parse_elements(context, entry[:-1], rw)
if (is_init_nd and is_init_ed) or (b_nodes_consistent*b_elems_consistent):
ret_val = {'FINISHED'}
elif (not(b_nodes_consistent) and not(is_init_nd)) and (not(b_elems_consistent) and not(is_init_ed)):
ret_val = {'MODEL_INCONSISTENT'}
elif (not(b_nodes_consistent) and not(is_init_nd)) and (b_elems_consistent):
ret_val = {'NODES_INCONSISTENT'}
elif (b_nodes_consistent) and (not(b_elems_consistent) and not(is_init_ed)):
ret_val = {'ELEMS_INCONSISTENT'}
else:
ret_val = {'FINISHED'}
except IOError:
print("Blendyn::parse_log_file(): Could not locate the file " + log_file + ".")
ret_val = {'LOG_NOT_FOUND'}
pass
except StopIteration:
print("Blendyn::parse_log_file() Reached the end of .log file")
pass
except TypeError:
# TypeError will be thrown if parse node exits with a {}, indicating an
# unsupported rotation parametrization (e.g. euler313)
ret_val = {'ROTATION_ERROR'}
pass
del_nodes = [var for var in nd.keys() if nd[var].is_imported == False]
del_elems = [var for var in ed.keys() if ed[var].is_imported == False]
obj_names = [nd[var].blender_object for var in del_nodes]
obj_names += [ed[var].blender_object for var in del_elems]
obj_names = list(filter(None, obj_names))
nn = len(nd)
# Account for nodes with no output
if nn:
no_output(context)
mbs.min_node_import = nd[0].int_label
mbs.max_node_import = nd[0].int_label
for ndx in range(1, len(nd)):
if nd[ndx].int_label < mbs.min_node_import:
mbs.min_node_import = nd[ndx].int_label
elif nd[ndx].int_label > mbs.max_node_import:
mbs.max_node_import = nd[ndx].int_label
if mbs.use_netcdf:
ncfile = os.path.join(os.path.dirname(mbs.file_path), \
mbs.file_basename + '.nc')
nc = Dataset(ncfile, "r")
mbs.num_timesteps = len(nc.variables["time"])
else:
mbs.num_nodes = nn
mbs.num_timesteps = int(mbs.num_rows/mbs.num_nodes)
mbs.is_ready = True
ret_val = {'FINISHED'}
else:
ret_val = {'NODES_NOT_FOUND'}
pass
en = len(ed)
if en:
mbs.min_elem_import = ed[0].int_label
mbs.max_elem_import = ed[0].int_label
for edx in range(1, len(ed)):
if ed[edx].int_label < mbs.min_elem_import:
mbs.min_elem_import = ed[edx].int_label
elif ed[edx].int_label > mbs.max_elem_import:
mbs.max_elem_import = ed[edx].int_label
try:
with open(out_file) as of:
reader = csv.reader(of, delimiter = ' ', skipinitialspace = True)
while True:
if next(reader)[0] == 'Step':
mbs.time_step = float(next(reader)[3])
if (mbs.use_netcdf):
mbs.end_time = nc.variables["time"][-1]
mbs.start_time = nc.variables["time"][0]
break
except FileNotFoundError:
print("Blendyn::parse_log_file(): Could not locate the file " + out_file)
ret_val = {'OUT_NOT_FOUND'}
pass
except StopIteration:
print("Blendyn::parse_log_file(): Reached the end of .out file")
pass
except IOError:
print("Blendyn::parse_log_file(): Could not read the file " + out_file)
pass
try:
with open(rfm_file) as rfm:
reader = csv.reader(rfm, delimiter = ' ', skipinitialspace = True)
for rfm_row in reader:
if len(rfm_row) and rfm_row[0].strip() != '#':
parse_reference_frame(rfm_row, rd)
# create the reference frames collection if it is not already there
try:
rcol = bpy.data.collections['mbdyn.references']
except KeyError:
rcol = bpy.data.collections.new(name = 'mbdyn.references')
bpy.context.scene.collection.children.link(rcol)
except StopIteration:
pass
except FileNotFoundError:
print("Blendyn::parse_out_file(): Could not locate the file " + rfm_file)
pass
except IOError:
print("Blendyn::parse_out_file(): Could not read the file " + rfm_file)
pass
if not(mbs.use_netcdf):
mbs.end_time = (mbs.num_timesteps - 1) * mbs.time_step
return ret_val, obj_names
# -----------------------------------------------------------
# end of parse_log_file() function
def path_leaf(path, keep_extension = False):
""" Helper function to strip filename of path """
head, tail = ntpath.split(path)
tail1 = (tail or ntpath.basename(head))
if keep_extension:
return path.replace(tail1, ''), tail1
else:
return path.replace(tail1, ''), os.path.splitext(tail1)[0]
# -----------------------------------------------------------
# end of path_leaf() function
def file_len(filepath):
""" Function to count the number of rows in a file """
try:
with open(filepath) as f:
for kk, ll in enumerate(f):
pass
return kk + 1
except UnboundLocalError:
return 0
except IsADirectoryError:
return 0
# -----------------------------------------------------------
# end of file_len() function
def assign_labels(context):
""" Function that parses the .log file and assigns \
the string labels it can find to the respective MBDyn objects
--
'standard' labels: assigns only the labels that match a
specific pattern
'free' labels: assigns the labels directly.
contributed by Louis Gagnon
-- see Github Issue #39
--
"""
mbs = context.scene.mbdyn
nd = mbs.nodes
ed = mbs.elems
rd = mbs.references
labels_changed = False
log_file = os.path.join(os.path.dirname(mbs.file_path), \
mbs.file_basename + '.log')
if mbs.free_labels:
obj_list = [nd, ed, rd]
set_strings_any = [" const integer", \
" integer"]
else:
set_strings_node = [" const integer Node_", \
" integer Node_", \
" const integer node_", \
" integer node_", \
" const integer NODE_", \
" integer NODE_"]
set_strings_joint = [" const integer Joint_", \
" integer Joint_"
" const integer joint_", \
" integer joint_", \
" const integer JOINT_", \
" integer JOINT_"]
set_strings_beam = [" const integer Beam_", \
" integer Beam_", \
" const integer beam_", \
" integer beam_", \
" const integer BEAM_", \
" integer BEAM_"]
set_strings_refs = [" const integer Ref_", \
" integer Ref_", \
" const integer ref_", \
" integer ref_", \
" const integer REF_", \
" integer REF_", \
" const integer Reference_", \
" integer Reference_", \
" const integer reference_", \
" integer reference_", \
" const integer REFERENCE_", \
" integer REFERENCE_"]
def assign_label(line, entity_type, set_string, the_dict):
line_str = line.rstrip()
eq_idx = line_str.find('=') + 1
label_int = int(line_str[eq_idx:].strip())
if mbs.free_labels:
label_str = line_str[len(set_string):(eq_idx -1)].strip()
else:
label_str = line_str[(len(set_string) - len(entity_type) - 1):(eq_idx-1)].strip()
for item in the_dict:
if item.int_label == label_int:
if item.string_label != label_str:
item.string_label = label_str
message = "BLENDYN::assign_label(): \nset_string:{}\nline_str:{}\nlabel_str:{}".format(set_string, line_str, label_str)
print(message)
baseLogger.info(message)
return True
break
return False
try:
if mbs.free_labels:
with open(log_file) as lf:
for line in lf:
found = False
for set_string in set_strings_any:
if set_string in line:
for the_obj in obj_list:
labels_changed += (assign_label(line, '', set_string, the_obj))
found = True
break
else:
with open(log_file) as lf:
for line in lf:
found = False
for set_string in set_strings_node:
if set_string in line:
labels_changed += (assign_label(line, 'node', set_string, nd))
found = True
break
if not(found):
for set_string in set_strings_joint:
if set_string in line:
labels_changed += (assign_label(line, 'joint', set_string, ed))
found = True
break
if not(found):
for set_string in set_strings_beam:
if set_string in line:
labels_changed += (assign_label(line, 'beam', set_string, ed))
found = True
break
if not (found):
for set_string in set_strings_refs:
if set_string in line:
labels_changed += (assign_label(line, 'ref', set_string, rd))
found = True
break
except IOError:
print("Blendyn::assign_labels(): can't read from file {}, \
sticking with default labeling...".format(log_file))
return {'FILE_NOT_FOUND'}
if labels_changed:
return {'LABELS_UPDATED'}
else:
return {'NOTHING_DONE'}
# -----------------------------------------------------------
# end of assign_labels() function
def update_label(self, context):
# utility renaming
obj = context.view_layer.objects.active
nd = context.scene.mbdyn.nodes
# Search for int label and assign corresponding string label, if found.
# If not, signal it by assign the "not found" label
node_string_label = "not_found"
obj.mbdyn.is_assigned = False
if obj.mbdyn.type == 'node.struct':
try:
key = 'node_' + str(obj.mbdyn.int_label)
node_string_label = nd[key].string_label
nd[key].blender_object = obj.name
obj.mbdyn.is_assigned = True
obj.mbdyn.string_label = node_string_label
ret_val = {}
if obj.mbdyn.is_assigned:
ret_val = update_parametrization(obj)
if ret_val == 'ROT_NOT_SUPPORTED':
message = type(self).__name__ + "::update_label(): "\
+ "Rotation parametrization not supported, node " \
+ obj.mbdyn.string_label
self.report({'ERROR'}, message)
logging.error(message)
elif ret_val == 'LOG_NOT_FOUND':
message = type(self).__name__ + "::update_label(): "\
+ "MBDyn .log file not found"
self.report({'ERROR'}, message)
logging.error(message)
except KeyError:
message = type(self).__name__ + "::update_label(): "\
+ "Node not found"
self.report({'ERROR'}, message)
logging.error(message)
pass
return
# -----------------------------------------------------------
# end of update_label() function
def update_end_time(self, context):
mbs = context.scene.mbdyn
if mbs.use_netcdf:
ncfile = os.path.join(os.path.dirname(mbs.file_path), \
mbs.file_basename + '.nc')
nc = Dataset(ncfile, "r")
if (mbs.end_time - nc.variables["time"][-1]) > mbs.time_step:
mbs.end_time = nc.variables["time"][-1]
elif mbs.end_time > mbs.num_timesteps * mbs.time_step:
mbs.end_time = mbs.num_timesteps * mbs.time_step
# -----------------------------------------------------------
# end of update_end_time() function
def update_start_time(self, context):
mbs = context.scene.mbdyn
if mbs.use_netcdf:
ncfile = os.path.join(os.path.dirname(mbs.file_path), \
mbs.file_basename + '.nc')
nc = Dataset(ncfile, "r")
if mbs.start_time < nc.variables["time"][0]:
mbs.start_time = nc.variables["time"][0]
elif mbs.start_time >= mbs.num_timesteps * mbs.time_step:
mbs.start_time = (mbs.num_timesteps - 1) * mbs.time_step
# -----------------------------------------------------------
# end of update_start_time() function
def remove_oldframes(context):
""" Clears the scene of keyframes of current simulation """
mbs = context.scene.mbdyn
node_names = mbs.nodes.keys()
obj_names = [bpy.context.scene.mbdyn.nodes[var].blender_object for var in node_names]
obj_names = list(filter(lambda v: v != 'none', obj_names))
obj_names = list(filter(lambda v: v in bpy.data.objects.keys(), obj_names))
if len(obj_names) > 0:
obj_list = [bpy.data.objects[var] for var in obj_names]
for obj in obj_list:
obj.animation_data_clear()
# -----------------------------------------------------------
# end of remove_oldframes() function
def hide_or_delete(obj_names, missing):
obj_names = list(filter(lambda v: v != 'none', obj_names))
obj_list = [bpy.data.objects[var] for var in obj_names]
if missing == "HIDE":
obj_list = [bpy.data.objects[var] for var in obj_names]
for obj in obj_list:
obj.hide_set(state = True)
if missing == "DELETE":
bpy.ops.object.select_all(action='DESELECT')
for obj in obj_list:
obj.select_set(state = True)
bpy.ops.object.delete()
def set_motion_paths_mov(context):
""" Parses the .mov file and .mod file then sets the nodes motion paths """
# Debug message
print("Blendyn::set_motion_paths_mov(): Setting Motion Paths using .mov output...")
# utility renaming
scene = context.scene
mbs = scene.mbdyn
nd = mbs.nodes
ed = mbs.elems
wm = context.window_manager
if not(mbs.is_ready):
return {'CANCELLED'}
# .mov filename
mov_file = os.path.join(os.path.dirname(mbs.file_path), \
mbs.file_basename + '.mov')
have_mod_file = True
if os.path.isfile(os.path.join(os.path.dirname(mbs.file_path), \
mbs.file_basename + '.mod')):
mod_file = os.path.join(os.path.dirname(mbs.file_path), \
mbs.file_basename + '.mod')
else:
have_mod_file = False
# Debug message
if have_mod_file:
print("Blendyn::set_motion_paths_mov(): Reading from file: {0} and {1}".format(mov_file, mod_file))
else:
print("Blendyn::set_motion_paths_mov(): Reading from file: {0}".format(mov_file))
# total number of frames to be animated
scene.frame_start = int(mbs.start_time/(mbs.time_step * mbs.load_frequency))
scene.frame_end = int(mbs.end_time/(mbs.time_step * mbs.load_frequency)) + 1
loop_start = int(scene.frame_start * mbs.load_frequency)
loop_end = int(scene.frame_end * mbs.load_frequency)
# list of animatable Blender object types
anim_types = ['MESH', 'ARMATURE', 'EMPTY']
# Cycle to establish which objects to animate
anim_objs = dict()
wm.progress_begin(scene.frame_start, scene.frame_end)
if have_mod_file:
try:
with open(mod_file) as mdf:
with open(mov_file) as mvf :
reader_mov = csv.reader(mvf, delimiter=' ', skipinitialspace=True)
reader_mod = csv.reader(mdf, delimiter=' ', skipinitialspace=True)
# first loop: we establish which object to animate
scene.frame_current = scene.frame_start
# skip to the first timestep to import
for ndx in range(int(mbs.start_time * mbs.num_nodes / mbs.time_step)):
next(reader_mov)
for ndx in range(int(mbs.start_time * mbs.num_modal_modes / mbs.time_step)):
next(reader_mod)
first_mov = []
second_mov = []
for ndx in range(mbs.num_nodes):
rw_mov = np.array(next(reader_mov)).astype(float)
first_mov.append(rw_mov)
second_mov.append(rw_mov)
try:
obj_name = nd['node_' + str(int(rw_mov[0]))].blender_object
if obj_name != 'none' and nd['node_' + str(int(rw_mov[0]))].output:
anim_objs[rw_mov[0]] = obj_name
obj = bpy.data.objects[obj_name]
obj.select_set(state = True)
set_obj_locrot_mov(obj, rw_mov)
except KeyError:
pass
dg = bpy.context.evaluated_depsgraph_get()
dg.update()
# Initial position of modal nodes
first_mod = []
second_mod = []
flag = False # Whether we set up the node positions in the space
mode_counter = 0
for mdx in range(mbs.num_modal_modes):
mode_counter += 1
rw_mod = np.array(next(reader_mod)).astype(float)
first_mod.append(rw_mod)
second_mod.append(rw_mod)
elem_int_label, mode_int_label = str(rw_mod[0]).split('.')
elem = ed['modal_'+ elem_int_label]
elem_node = nd['node_'+ str(elem.nodes[0].int_label)]
elem_nodeOJB = bpy.data.objects[elem_node.blender_object]
for node in elem.modal_node:
try:
obj_name = node.blender_object
if obj_name != 'none':
obj = bpy.data.objects[obj_name]
obj.select_set(state=True)
if not flag:
obj.location = elem_nodeOJB.matrix_world @ Vector(
(node.relative_pos[0] + rw_mod[1] * node.mode[mode_int_label].mode_shape[0],
node.relative_pos[1] + rw_mod[1] * node.mode[mode_int_label].mode_shape[1],
node.relative_pos[2] + rw_mod[1] * node.mode[mode_int_label].mode_shape[2],
1)).to_3d()
else:
obj.location += elem_nodeOJB.matrix_world @ Vector(
(rw_mod[1] * node.mode[mode_int_label].mode_shape[0],
rw_mod[1] * node.mode[mode_int_label].mode_shape[1],
rw_mod[1] * node.mode[mode_int_label].mode_shape[2],
1)).to_3d() - elem_nodeOJB.location
try:
if mode_counter == len(elem.modal_node[0].mode):
obj.keyframe_insert(data_path="location")
obj.rotation_euler = elem_nodeOJB.rotation_euler
obj.keyframe_insert(data_path="rotation_euler")
except KeyError:
pass
except KeyError:
pass
if not flag:
flag = True
try:
if mode_counter == len(elem.modal_node[0].mode):
mode_counter = 0
flag = False
except KeyError:
pass
# main for loop, from second frame to last
freq = mbs.load_frequency
Nskip_mov = 0
Nskip_mod = 0
for idx, frame in enumerate(np.arange(loop_start + freq, loop_end, freq)):
scene.frame_current += 1
message = "BLENDYN::set_motion_paths_mov(): Animating frame {}".format(scene.frame_current)
print(message)
logging.info(message)
# skip (freq - 1)*N lines
if freq > 1:
Nskip_mov = (int(frame) - int(frame - freq) - 2) * mbs.num_nodes
Nskip_mod = (int(frame) - int(frame - freq) - 2) * mbs.num_modal_modes
if Nskip_mov >= 0:
for ii in range(Nskip_mov):
next(reader_mov)
for ndx in range(mbs.num_nodes):
first_mov[ndx] = np.array(next(reader_mov)).astype(float)
if Nskip_mod >= 0:
for ii in range(Nskip_mod):
next(reader_mod)
for ndx in range(mbs.num_modal_modes):
first_mod[ndx] = np.array(next(reader_mod)).astype(float)
if freq > 1:
frac = np.ceil(frame) - frame
for ndx in range(mbs.num_nodes):
second_mov[ndx] = np.array(next(reader_mov)).astype(float)
for ndx in range(mbs.num_modal_modes):
second_mod[ndx] = np.array(next(reader_mod)).astype(float)
for ndx in range(mbs.num_nodes):
try:
answer = frac*first_mov[ndx] + (1 - frac)*second_mov[ndx]
obj = bpy.data.objects[anim_objs[round(answer[0])]]
obj.select_set(state = True)
set_obj_locrot_mov(obj, answer)
except KeyError:
pass
dg = bpy.context.evaluated_depsgraph_get()
dg.update()
flag = False # Whether we set up the node positions in the space
mode_counter = 0
for mdx in range(mbs.num_modal_modes):
mode_counter += 1
elem_int_label, mode_int_label = str(first_mod[mdx][0]).split('.')
elem = ed['modal_' + elem_int_label]
elem_node = nd['node_' + str(elem.nodes[0].int_label)]
elem_nodeOJB = bpy.data.objects[elem_node.blender_object]
answer = frac * first_mod[mdx] + (1 - frac) * second_mod[mdx]
for node in elem.modal_node:
try:
obj_name = node.blender_object
if obj_name != 'none':
obj = bpy.data.objects[obj_name]
obj.select_set(state=True)
if not flag:
obj.location = elem_nodeOJB.matrix_world @ Vector(
(node.relative_pos[0] + answer[1] *
node.mode[mode_int_label].mode_shape[0],
node.relative_pos[1] + answer[1] *
node.mode[mode_int_label].mode_shape[1],
node.relative_pos[2] + answer[1] *
node.mode[mode_int_label].mode_shape[2], 1)).to_3d()
else:
obj.location += elem_nodeOJB.matrix_world @ Vector(
(answer[1] * node.mode[mode_int_label].mode_shape[0],
answer[1] * node.mode[mode_int_label].mode_shape[1],
answer[1] * node.mode[mode_int_label].mode_shape[2],
1)).to_3d() - elem_nodeOJB.location
try:
if mode_counter == len(elem.modal_node[0].mode):
obj.keyframe_insert(data_path="location")
obj.rotation_euler = elem_nodeOJB.rotation_euler
obj.keyframe_insert(data_path="rotation_euler")
except KeyError:
pass
except KeyError:
pass
if not flag:
flag = True
try:
if mode_counter == len(elem.modal_node[0].mode):
mode_counter = 0
flag = False
except KeyError:
pass
first_mod = second_mod
first_mov = second_mov
else:
for ndx in range(mbs.num_nodes):
rw_mov = first_mov[ndx]
obj = bpy.data.objects[anim_objs[round(rw_mov[0])]]
obj.select_set(state = True)