-
Notifications
You must be signed in to change notification settings - Fork 11
/
cellblender_mol_viz.py
1804 lines (1428 loc) · 73.2 KB
/
cellblender_mol_viz.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
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program 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 2
# of the License, or (at your option) any later version.#
# This program 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 this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# <pep8 compliant>
"""
This file contains the classes for CellBlender's Molecule Visualization.
"""
import cellblender
# blender imports
import bpy
from bpy.app.handlers import persistent
from bpy.props import BoolProperty, CollectionProperty, EnumProperty, \
FloatProperty, FloatVectorProperty, IntProperty, \
IntVectorProperty, PointerProperty, StringProperty
#from bpy.app.handlers import persistent
#import math
#import mathutils
# python imports
import mathutils
import array
import glob
import os
import random
import re
import json
# CellBlender imports
import cellblender
import cellblender.parameter_system as parameter_system
import cellblender.cellblender_release as cellblender_release
import cellblender.cellblender_utils as cellblender_utils
from cellblender.cellblender_utils import timeline_view_all
from cellblender.cellblender_utils import mcell_files_path
# Mol Viz Operators:
global_mol_file_list = []
def create_color_list():
""" Create a list of colors to be assigned to the glyphs. """
mcell = bpy.context.scene.mcell
mcell.mol_viz.color_index = 0
if not mcell.mol_viz.color_list:
for i in range(8):
mcell.mol_viz.color_list.add()
mcell.mol_viz.color_list[0].vec = [0.8, 0.0, 0.0]
mcell.mol_viz.color_list[1].vec = [0.0, 0.8, 0.0]
mcell.mol_viz.color_list[2].vec = [0.0, 0.0, 0.8]
mcell.mol_viz.color_list[3].vec = [0.0, 0.8, 0.8]
mcell.mol_viz.color_list[4].vec = [0.8, 0.0, 0.8]
mcell.mol_viz.color_list[5].vec = [0.8, 0.8, 0.0]
mcell.mol_viz.color_list[6].vec = [1.0, 1.0, 1.0]
mcell.mol_viz.color_list[7].vec = [0.0, 0.0, 0.0]
# Matrix Form: Assemble obj2 onto obj1 at location of obj1
def assemble_mat(obj1, obj2):
# get tform matrices of obj1 and obj2
m1 = obj1.matrix_world.copy()
m2 = obj2.matrix_world.copy()
# compute inverse of tform matrix of obj2
m2i = m2.inverted_safe()
# create rotation and translation tform matrix for binding site of assembly
r = mathutils.Matrix.Rotation(pi/8,4,'Y')
t = mathutils.Matrix.Translation((0,-2, 0))
bsm = r*t
# create complete composite tform matrix for assembly
assem = m2i*m1*bsm
# Apply the assembly tform matrix to obj2
obj2.matrix_world = obj2.matrix_world*assem
@persistent
def read_viz_data_load_post(context):
print ( "load post handler: cellblender_mol_viz.read_viz_data_load_post() called" )
bpy.ops.mcell.read_viz_data()
@persistent
def viz_data_save_post(context):
# context appears to be None
print ( "save post handler: cellblender_mol_viz.viz_data_save_post() called" )
if 'global_mol_file_list' in dir(cellblender.cellblender_mol_viz):
if len(cellblender.cellblender_mol_viz.global_mol_file_list) > 0:
# There is a non-empty file list, so check if this file path matches the current viz directory
print ( "New file name = " + str(bpy.data.filepath) )
mv = bpy.context.scene.mcell.mol_viz
if not mv.manual_select_viz_dir:
print ( "Viz not manually selected" )
bfn = os.path.abspath(str(bpy.data.filepath))
mfd = os.path.abspath(str(mv.mol_file_dir))
print ( "Blend: " + bfn )
print ( "Viz: " + mfd )
if not mfd.startswith(os.path.splitext(bfn)[0] + "_files" + os.sep + "mcell" + os.sep ):
print ( "Paths don't match, so clear mol-viz information" )
# This is being saved as a different file than was used to generate the visualization data
cellblender.cellblender_mol_viz.global_mol_file_list = []
mv.mol_file_dir = ''
# __import__('code').interact(local={k: v for ns in (globals(), locals()) for k, v in ns.items()})
# Operators can't be callbacks, so we need this function for now. This is
# temporary until we make importing viz data automatic.
def read_viz_data_callback(self, context):
# print ( "read_viz_data_callback" )
bpy.ops.mcell.read_viz_data()
class MCELL_OT_update_data_layout(bpy.types.Operator):
bl_idname = "mcell.update_data_layout"
bl_label = "Update Layout Data"
bl_description = "Update the Data Layout based on most recent run of this project."
bl_options = {'REGISTER'}
def execute(self, context):
# print ( "MCELL_OT_update_data_layout operator" )
mcell = context.scene.mcell
mcell.mol_viz.update_data_layout(context)
return {'FINISHED'}
class MCELL_OT_read_viz_data(bpy.types.Operator):
bl_idname = "mcell.read_viz_data"
bl_label = "Read Viz Data"
bl_description = "Load the molecule visualization data into Blender"
bl_options = {'REGISTER'}
def execute(self, context):
global global_mol_file_list
# Called when the molecule files are actually to be read (when the
# "Read Molecule Files" button is pushed or a seed value is selected
# from the list)
mcell = context.scene.mcell
mol_viz = mcell.mol_viz
choices_list = mol_viz.choices_list
mol_file_dir = ''
if mol_viz.manual_select_viz_dir:
# mol_file_dir comes from directory already chosen manually
mol_file_dir = mol_viz.mol_file_dir
print("manual mol_file_dir: %s" % (mol_file_dir))
else:
# mol_file_dir comes from directory associated with saved .blend file
mol_viz_top_level_dir = None
files_path = mcell_files_path() # This will be the full path from "/"
# Check to see if the data is in an output_data directory or not
if os.path.exists(files_path) and 'output_data' in os.listdir(files_path):
# New "output_data" layout
# Read the viz data from the first data path in the potential sweep
f = open ( os.path.join(files_path,"data_layout.json"), 'r' )
layout_spec = json.loads ( f.read() )
f.close()
data_layout = layout_spec['data_layout']
sub_path = ""
for level in data_layout:
if level[0] == '/DIR':
# This is typically the top level directory
sub_path = os.path.join ( sub_path, level[1][0] )
elif level[0] == '/FILE_TYPE':
# This is typically either "viz_data" or "react_data" ... force "viz_data
sub_path = os.path.join ( sub_path, 'viz_data', '' )
elif (level[0] == '/SEED'):
# Seed selection is handled in another part of the application so pass
pass
else:
# This is a parameter sweep subdirectory, use the parameter name and currently selected index
selected_index = 0
try:
selected_index = choices_list[level[0]]['enum_choice']
except:
pass
sub_path = os.path.join ( sub_path, level[0] + ("_index_%d" % selected_index) )
mol_viz_top_level_dir = os.path.join(files_path, sub_path)
else:
# Old "non-output_data" layout
# Force the top level mol_viz directory to be where the .blend file
# lives plus "viz_data". The seed directories will live underneath it.
mol_viz_top_level_dir = os.path.join(files_path, "viz_data", "")
mol_viz_top_level_dir = os.path.relpath(mol_viz_top_level_dir)
mol_viz_seed_list = glob.glob(os.path.join(mol_viz_top_level_dir, "*"))
mol_viz_seed_list.sort()
# Clear the list of seeds (e.g. seed_00001, seed_00002, etc) and the
# list of files (e.g. my_project.cellbin.0001.dat,
# my_project.cellbin.0002.dat)
mol_viz.mol_viz_seed_list.clear()
# Add all the seed directories to the mol_viz_seed_list collection
# (seed_00001, seed_00002, etc)
for mol_viz_seed in mol_viz_seed_list:
new_item = mol_viz.mol_viz_seed_list.add()
new_item.name = os.path.basename(mol_viz_seed)
if mol_viz.mol_viz_seed_list:
# If you previously had some viz data loaded, but reran the
# simulation with less seeds, you can receive an index error.
try:
active_mol_viz_seed = mol_viz.mol_viz_seed_list[
mol_viz.active_mol_viz_seed_index]
except IndexError:
mol_viz.active_mol_viz_seed_index = 0
active_mol_viz_seed = mol_viz.mol_viz_seed_list[0]
mol_file_dir = os.path.join(mol_viz_top_level_dir, active_mol_viz_seed.name)
mol_file_dir = os.path.relpath(mol_file_dir)
mol_viz.mol_file_dir = mol_file_dir
# mol_viz.mol_file_list.clear()
global_mol_file_list = []
mol_file_list = []
if mol_file_dir != '':
mol_file_list = [ f for f in glob.glob(os.path.join(mol_file_dir, "*.dat")) ]
mol_file_list.sort()
if mol_file_list:
# Add all the viz_data files to global_mol_file_list (e.g.
# my_project.cellbin.0001.dat, my_project.cellbin.0001.dat, etc)
for mol_file_name in mol_file_list:
global_mol_file_list.append(os.path.basename(mol_file_name))
# If you previously had some viz data loaded, but reran the
# simulation with less iterations, you can receive an index error.
try:
mol_file = global_mol_file_list[mol_viz.mol_file_index]
except IndexError:
mol_viz.mol_file_index = 0
mol_file = global_mol_file_list[mol_viz.mol_file_index]
create_color_list()
set_viz_boundaries(context)
# Set the mol_file_index to match the cursor as closely as possible
cursor_index = context.scene.frame_current
if len(mol_file_list) > cursor_index:
mol_viz.mol_file_index = cursor_index
elif len(mol_file_list) >= 1:
mol_viz.mol_file_index = len(mol_file_list) - 1
else:
mol_viz.mol_file_index = 0
try:
mol_viz_clear(mcell, force_clear=True)
mol_viz_update(self, context)
except:
print( "Unexpected Exception calling mol_viz_update: " + str(sys.exc_info()) )
return {'FINISHED'}
# Mol Viz callback functions
def set_viz_boundaries( context ):
global global_mol_file_list
mcell = context.scene.mcell
# mcell.mol_viz.mol_file_num = len(mcell.mol_viz.mol_file_list)
mcell.mol_viz.mol_file_num = len(global_mol_file_list)
mcell.mol_viz.mol_file_stop_index = mcell.mol_viz.mol_file_num - 1
#print("Setting frame_start to 0")
#print("Setting frame_end to ", len(mcell.mol_viz.mol_file_list)-1)
bpy.context.scene.frame_start = 0
# bpy.context.scene.frame_end = len(mcell.mol_viz.mol_file_list)-1
bpy.context.scene.frame_end = len(global_mol_file_list)-1
timeline_view_all ( context )
"""
if bpy.context.screen != None:
for area in bpy.context.screen.areas:
if area != None:
if area.type == 'TIMELINE':
for region in area.regions:
if region.type == 'WINDOW':
ctx = bpy.context.copy()
ctx['area'] = area
ctx['region'] = region
bpy.ops.time.view_all(ctx)
break # It's not clear if this should break or continue ... breaking for now
"""
class MCELL_OT_select_viz_data(bpy.types.Operator):
bl_idname = "mcell.select_viz_data"
bl_label = "Read Viz Data"
bl_description = "Read MCell Molecule Files for Visualization"
bl_options = {'REGISTER'}
filepath: StringProperty(subtype='FILE_PATH', default="")
directory: StringProperty(subtype='DIR_PATH')
def __init__(self):
self.directory = bpy.context.scene.mcell.mol_viz.mol_file_dir
def execute(self, context):
global global_mol_file_list
mcell = context.scene.mcell
if (os.path.isdir(self.filepath)):
mol_file_dir = self.filepath
else:
# Strip the file name off of the file path.
mol_file_dir = os.path.dirname(self.filepath)
mcell.mol_viz.mol_file_dir = mol_file_dir
mol_file_list = [ f for f in glob.glob(os.path.join(mol_file_dir, "*")) if not f.endswith(os.sep + "viz_bngl") ]
print ( "Select found " + str(len(mol_file_list)) + " files" )
mol_file_list.sort()
# Reset mol_file_list and mol_viz_seed_list to empty
# mcell.mol_viz.mol_file_list.clear()
global_mol_file_list = []
for mol_file_name in mol_file_list:
# new_item = mcell.mol_viz.mol_file_list.add()
# new_item.name = os.path.basename(mol_file_name)
global_mol_file_list.append(os.path.basename(mol_file_name))
create_color_list()
set_viz_boundaries(context)
mcell.mol_viz.mol_file_index = 0
mol_viz_update(self, context)
return {'FINISHED'}
def invoke(self, context, event):
# Called when the file selection panel is requested
# (when the "Set Molecule Viz Directory" button is pushed)
print("MCELL_OT_select_viz_data.invoke() called")
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class MCELL_OT_mol_viz_set_index(bpy.types.Operator):
bl_idname = "mcell.mol_viz_set_index"
bl_label = "Set Molecule File Index"
bl_description = "Set MCell Molecule File Index for Visualization"
bl_options = {'REGISTER'}
def execute(self, context):
global global_mol_file_list
mcell = context.scene.mcell
# if mcell.mol_viz.mol_file_list:
if global_mol_file_list:
i = mcell.mol_viz.mol_file_index
if (i > mcell.mol_viz.mol_file_stop_index):
i = mcell.mol_viz.mol_file_stop_index
if (i < mcell.mol_viz.mol_file_start_index):
i = mcell.mol_viz.mol_file_start_index
mcell.mol_viz.mol_file_index = i
# print ( "Set index calling update" )
mol_viz_update(self, context)
return{'FINISHED'}
#CellBlender operator helper functions:
@persistent
def frame_change_handler(scn):
""" Update the viz data every time a frame is changed. """
mcell = scn.mcell
curr_frame = mcell.mol_viz.mol_file_index
if (not curr_frame == scn.frame_current):
mcell.mol_viz.mol_file_index = scn.frame_current
bpy.ops.mcell.mol_viz_set_index()
# Is the following code necessary?
#if mcell.mol_viz.render_and_save:
# scn.render.filepath = "//stores_on/frames/frame_%05d.png" % (
# scn.frame_current)
# bpy.ops.render.render(write_still=True)
def mol_viz_toggle_manual_select(self, context):
""" Toggle the option to manually load viz data. """
global global_mol_file_list
mcell = context.scene.mcell
mcell.mol_viz.mol_file_dir = ""
mcell.mol_viz.mol_file_name = ""
# mcell.mol_viz.mol_file_list.clear()
global_mol_file_list = []
mcell.mol_viz.mol_viz_seed_list.clear()
if not mcell.mol_viz.manual_select_viz_dir:
bpy.ops.mcell.read_viz_data()
mol_viz_clear(mcell)
def get_mol_file_dir():
""" Get the viz dir """
mcell = bpy.context.scene.mcell
# If you previously had some viz data loaded, but reran the
# simulation with less seeds, you can receive an index error.
try:
active_mol_viz_seed = mcell.mol_viz.mol_viz_seed_list[
mcell.mol_viz.active_mol_viz_seed_index]
except IndexError:
mcell.mol_viz.active_mol_viz_seed_index = 0
active_mol_viz_seed = mcell.mol_viz.mol_viz_seed_list[0]
filepath = os.path.join(
mcell_files_path(), "viz_data/%s" % active_mol_viz_seed.name)
filepath = os.path.relpath(filepath)
return filepath
# Note: why is self here? This isn't a class method...
def mol_viz_update(self, context):
""" Clear the old viz data. Draw the new viz data. """
mcell = context.scene.mcell
if global_mol_file_list:
if mcell.mol_viz.mol_file_index > len(global_mol_file_list) or mcell.mol_viz.mol_file_index < 0:
mcell.mol_viz.mol_file_index = 0
filename = global_mol_file_list[mcell.mol_viz.mol_file_index]
mcell.mol_viz.mol_file_name = filename
filepath = os.path.join(mcell.mol_viz.mol_file_dir, filename)
# Save current global_undo setting. Turn undo off to save memory
global_undo = bpy.context.preferences.edit.use_global_undo
bpy.context.preferences.edit.use_global_undo = False
mol_viz_clear(mcell)
if mcell.mol_viz.mol_viz_enable:
mol_viz_file_read(mcell, filepath)
# Reset undo back to its original state
bpy.context.preferences.edit.use_global_undo = global_undo
return
def mol_viz_clear(mcell_prop, force_clear=False):
""" Clear the viz data from the previous frame. """
mcell = mcell_prop
scn = bpy.context.scene
scn_objs = bpy.context.scene.collection.children[0].objects
meshes = bpy.data.meshes
objs = bpy.data.objects
if force_clear:
mol_viz_list = [obj for obj in scn_objs if (obj.name[:4] == 'mol_') and (obj.name[-6:] != '_shape')]
else:
mol_viz_list = mcell.mol_viz.mol_viz_list
for mol_item in mol_viz_list:
mol_name = mol_item.name
mol_obj = scn_objs.get(mol_name)
if mol_obj:
hide = mol_obj.hide_viewport
mol_pos_mesh = mol_obj.data
mol_pos_mesh_name = mol_pos_mesh.name
mol_shape_obj_name = "%s_shape" % (mol_name)
mol_shape_obj = objs.get(mol_shape_obj_name)
if mol_shape_obj:
mol_shape_obj.parent = None
scn_objs.unlink(mol_obj)
objs.remove(mol_obj)
meshes.remove(mol_pos_mesh)
mol_pos_mesh = meshes.new(mol_pos_mesh_name)
mol_obj = objs.new(mol_name, mol_pos_mesh)
scn_objs.link(mol_obj)
if mol_shape_obj:
mol_shape_obj.parent = mol_obj
mol_obj.instance_type = 'VERTS'
mol_obj.use_instance_vertices_rotation = True
mols_obj = objs.get("molecules")
mol_obj.parent = mols_obj
mol_obj.hide_viewport = hide
# Reset mol_viz_list to empty
for i in range(len(mcell.mol_viz.mol_viz_list)-1, -1, -1):
mcell.mol_viz.mol_viz_list.remove(i)
"""
def old_mol_viz_file_read(mcell_prop, filepath):
mcell = mcell_prop
try:
# begin = resource.getrusage(resource.RUSAGE_SELF)[0]
# print ("Processing molecules from file: %s" % (filepath))
# Quick check for Binary or ASCII format of molecule file:
mol_file = open(filepath, "rb")
b = array.array("I")
b.fromfile(mol_file, 1)
mol_dict = {}
if b[0] == 1:
# Read Binary format molecule file:
bin_data = 1
while True:
try:
# Variable names are a little hard to follow
# Here's what I assume they mean:
# ni = Initially, array of molecule name length.
# Later, array of number of molecule positions in xyz
# (essentially, the number of molecules multiplied by 3).
# ns = Array of ascii character codes for molecule name.
# s = String of molecule name.
# mt = Surface molecule flag.
ni = array.array("B")
ni.fromfile(mol_file, 1)
ns = array.array("B")
ns.fromfile(mol_file, ni[0])
s = ns.tobytes().decode()
mol_name = "mol_%s" % (s)
mt = array.array("B")
mt.fromfile(mol_file, 1)
ni = array.array("I")
ni.fromfile(mol_file, 1)
mol_pos = array.array("f")
mol_orient = array.array("f")
mol_pos.fromfile(mol_file, ni[0])
# tot += ni[0]/3
if mt[0] == 1:
mol_orient.fromfile(mol_file, ni[0])
mol_dict[mol_name] = [mt[0], mol_pos, mol_orient]
new_item = mcell.mol_viz.mol_viz_list.add()
new_item.name = mol_name
except:
# print("Molecules read: %d" % (int(tot)))
mol_file.close()
break
else:
# Read ASCII format molecule file:
bin_data = 0
mol_file.close()
# Create a list of molecule names, positions, and orientations
# Each entry in the list is ordered like this (afaik):
# [molec_name, [x_pos, y_pos, z_pos, x_orient, y_orient, z_orient]]
# Orientations are zero in the case of volume molecules.
mol_data = [[s.split()[0], [
float(x) for x in s.split()[2:]]] for s in open(
filepath, "r").read().split("\n") if s != ""]
for mol in mol_data:
mol_name = "mol_%s" % (mol[0])
if not mol_name in mol_dict:
mol_orient = mol[1][3:]
mt = 0
# Check to see if it's a surface molecule
if ((mol_orient[0] != 0.0) | (mol_orient[1] != 0.0) |
(mol_orient[2] != 0.0)):
mt = 1
mol_dict[mol_name] = [
mt, array.array("f"), array.array("f")]
new_item = mcell.mol_viz.mol_viz_list.add()
new_item.name = mol_name
mt = mol_dict[mol_name][0]
mol_dict[mol_name][1].extend(mol[1][:3])
if mt == 1:
mol_dict[mol_name][2].extend(mol[1][3:])
# Get the parent object to all the molecule positions if it exists.
# Otherwise, create it.
mols_obj = bpy.data.objects.get("molecules")
if not mols_obj:
bpy.ops.object.add(location=[0, 0, 0])
mols_obj = bpy.context.selected_objects[0]
mols_obj.name = "molecules"
#mol_viz_list
if mol_dict:
meshes = bpy.data.meshes
mats = bpy.data.materials
objs = bpy.data.objects
scn = bpy.context.scene
scn_objs = bpy.context.scene.collection.children[0].objects
z_axis = mathutils.Vector((0.0, 0.0, 1.0))
#ident_mat = mathutils.Matrix.Translation(
# mathutils.Vector((0.0, 0.0, 0.0)))
for mol_name in mol_dict.keys():
mol_mat_name = "%s_mat" % (mol_name)
mol_type = mol_dict[mol_name][0]
mol_pos = mol_dict[mol_name][1]
mol_orient = mol_dict[mol_name][2]
# Randomly orient volume molecules
if mol_type == 0:
mol_orient.extend([random.uniform(
-1.0, 1.0) for i in range(len(mol_pos))])
# Look-up mesh shape (glyph) template and create if needed
mol_shape_mesh_name = "%s_shape" % (mol_name)
mol_shape_obj_name = mol_shape_mesh_name
mol_shape_mesh = meshes.get(mol_shape_mesh_name)
if not mol_shape_mesh:
bpy.ops.mesh.primitive_ico_sphere_add(
subdivisions=0, radius=0.005, location=[0, 0, 0])
mol_shape_obj = bpy.context.active_object
mol_shape_obj.name = mol_shape_obj_name
mol_shape_obj.track_axis = "POS_Z"
mol_shape_mesh = mol_shape_obj.data
mol_shape_mesh.name = mol_shape_mesh_name
else:
mol_shape_obj = objs.get(mol_shape_obj_name)
# Look-up material, create if needed.
# Associate material with mesh shape.
mol_mat = mats.get(mol_mat_name)
if not mol_mat:
mol_mat = mats.new(mol_mat_name)
mol_mat.diffuse_color = mcell.mol_viz.color_list[
mcell.mol_viz.color_index].vec
mcell.mol_viz.color_index = mcell.mol_viz.color_index + 1
if (mcell.mol_viz.color_index >
len(mcell.mol_viz.color_list)-1):
mcell.mol_viz.color_index = 0
if not mol_shape_mesh.materials.get(mol_mat_name):
mol_shape_mesh.materials.append(mol_mat)
# Create a "mesh" to hold instances of molecule positions
mol_pos_mesh_name = "%s_pos" % (mol_name)
mol_pos_mesh = meshes.get(mol_pos_mesh_name)
if not mol_pos_mesh:
mol_pos_mesh = meshes.new(mol_pos_mesh_name)
# Add and place vertices at positions of molecules
mol_pos_mesh.vertices.add(len(mol_pos)//3)
mol_pos_mesh.vertices.foreach_set("co", mol_pos)
mol_pos_mesh.vertices.foreach_set("normal", mol_orient)
# Create object to contain the mol_pos_mesh data
mol_obj = objs.get(mol_name)
if not mol_obj:
mol_obj = objs.new(mol_name, mol_pos_mesh)
scn_objs.link(mol_obj)
mol_shape_obj.parent = mol_obj
mol_obj.instance_type = 'VERTS'
mol_obj.use_instance_vertices_rotation = True
mol_obj.parent = mols_obj
# bpy.context.view_layer.update()
# utime = resource.getrusage(resource.RUSAGE_SELF)[0]-begin
# print (" Processed %d molecules in %g seconds\n" % (
# len(mol_data), utime))
except IOError:
print(("\n***** File not found: %s\n") % (filepath))
except ValueError:
print(("\n***** Invalid data in file: %s\n") % (filepath))
"""
import sys, traceback
def mol_viz_file_dump(filepath):
""" Read and Dump a molecule viz file. """
tot = 0
try:
# Quick check for Binary or ASCII format of molecule file:
mol_file = open(filepath, "rb")
b = array.array("I")
b.fromfile(mol_file, 1)
mol_dict = {}
if b[0] == 1:
# Read MCell/CellBlender Binary Format molecule file, version 1:
print ("Reading binary file " + filepath )
while True:
try:
# ni = Initially, byte array of molecule name length.
# Later, array of number of molecule positions in xyz
# (essentially, the number of molecules multiplied by 3).
# ns = Array of ascii character codes for molecule name.
# s = String of molecule name.
# mt = Surface molecule flag.
ni = array.array("B") # Create a binary byte ("B") array
ni.fromfile(mol_file, 1) # Read one byte which is the number of characters in the molecule name
ns = array.array("B") # Create another byte array to hold the molecule name
ns.fromfile(mol_file, ni[0]) # Read ni bytes from the file
s = ns.tobytes().decode() # Decode bytes as ASCII into a string (s)
mol_name = "mol_%s" % (s) # Construct name of blender molecule viz object
mt = array.array("B") # Create a byte array for the molecule type
mt.fromfile(mol_file, 1) # Read one byte for the molecule type
ni = array.array("I") # Re-use ni as an integer array to hold the number of molecules of this name in this frame
ni.fromfile(mol_file, 1) # Read the 4 byte integer value which is 3 times the number of molecules
mol_pos = array.array("f") # Create a floating point array to hold the positions
mol_orient = array.array("f") # Create a floating point array to hold the orientations
mol_pos.fromfile(mol_file, ni[0]) # Read the positions which should be 3 floats per molecule
mol_type_name = "Volume"
tot += ni[0]/3
if mt[0] == 1: # If mt==1, it's a surface molecule
mol_orient.fromfile(mol_file, ni[0]) # Read the surface molecule orientations
mol_type_name = "Surface"
print ( mol_type_name + " Molecule " + s + " contains " + str(tot) + " instances" )
except EOFError:
# print("Molecules read: %d" % (int(tot)))
mol_file.close()
break
except:
print( "Unexpected Exception: " + str(sys.exc_info()) )
# print("Molecules read: %d" % (int(tot)))
mol_file.close()
break
else:
print ( "Dump doesn't read text files." )
except IOError:
print(("\n***** IOError: File: %s\n") % (filepath))
except ValueError:
print(("\n***** ValueError: Invalid data in file: %s\n") % (filepath))
except RuntimeError as rte:
print(("\n***** RuntimeError reading file: %s\n") % (filepath))
print(" str(error): \n" + str(rte) + "\n")
fail_error = sys.exc_info()
print ( " Error Type: " + str(fail_error[0]) )
print ( " Error Value: " + str(fail_error[1]) )
tb = fail_error[2]
# tb.print_stack()
print ( "=== Traceback Start ===" )
traceback.print_tb(tb)
print ( "=== Traceback End ===" )
except Exception as uex:
# Catch any exception
print ( "\n***** Unexpected exception:" + str(uex) + "\n" )
raise
def remove_compartment_and_state(name):
# Remove states and compartment, e.g. @EC:Syk(a~Y,l~Y,tSH2)@CP -> Syk
split_by_colon = name.split(':')
if len(split_by_colon) == 2:
em_no_start_compartment = split_by_colon[1]
else:
em_no_start_compartment = name
em_no_compartment = em_no_start_compartment.split('@')[0]
em_no_components = em_no_compartment.split('(')[0]
return em_no_components
def get_used_molecule_names(name):
# example of input:
# '@EC:scov2(s!1,s!2,s!3,s!4,s!5).spike(v!1,a)@CP.spike(v!1,a)@CP'
# output:
# ['scov', 'spike']
res = set()
split_by_dot = name.split('.')
for em in split_by_dot:
# remove compartment and states
res.add(remove_compartment_and_state(em))
return sorted(list(res))
def mol_viz_file_read(mcell, filepath):
""" Read and Draw the molecule viz data for the current frame. """
mv = mcell.mol_viz
if (mv.viz_code in ['custom','both']):
script_text = None
if mv.internal_viz_file_name in bpy.data.texts:
# It's an internal file
script_text = bpy.data.texts[mv.internal_viz_file_name].as_string()
elif mv.internal_viz_file_name.startswith ( os.path.sep ):
# It must be an external file starting with an os.sep (typically '/')
script_file = open ( os.path.join ( os.path.dirname(bpy.data.filepath), mv.internal_viz_file_name[1:] ), 'r' )
print ( "Reading script text from " + str(script_file) )
script_text = script_file.read()
if script_text != None:
# Store the filepath for this frame in a place where it can be used by the custom code
mcell.mol_viz.frame_file_name = filepath
# Convert the text to code (this might be done earlier when the file is selected)
code = compile ( script_text, "<string>", 'exec' )
# Execute the code
exec ( code )
if mv.viz_code == 'custom':
return
# check whether the viz file is not empty (may happen for ASCII files)
if os.path.getsize(filepath) == 0:
return
dup_check = False
try:
# begin = resource.getrusage(resource.RUSAGE_SELF)[0]
# print ("Processing molecules from file: %s" % (filepath))
# Quick check for Binary or ASCII format of molecule file:
mol_file = open(filepath, "rb")
b = array.array("I")
b.fromfile(mol_file, 1)
mol_dict = {}
if b[0] == 1 or b[0] == 2:
ver = b[0]
# Read MCell/CellBlender Binary Format molecule file, version 1:
# print ("Reading binary file " + filepath )
bin_data = 1
while True:
try:
# ni = Initially, byte array of molecule name length.
# Later, array of number of molecule positions in xyz
# (essentially, the number of molecules multiplied by 3).
# ns = Array of ascii character codes for molecule name.
# s = String of molecule name.
# mt = Surface molecule flag.
if ver == 1:
ni = array.array("B") # Create a binary byte ("B") array to read one byte
else:
ni = array.array("I") # Create a binary integer ("I") array to read 4 bytes
ni.fromfile(mol_file, 1) # Read one or four bytes which is the number of characters in the molecule name
ns = array.array("B") # Create another byte array to hold the molecule name
ns.fromfile(mol_file, ni[0]) # Read ni bytes from the file
mol_name_from_file = ns.tobytes().decode() # Decode bytes as ASCII into a string (s)
mt = array.array("B") # Create a byte array for the molecule type
mt.fromfile(mol_file, 1) # Read one byte for the molecule type
ni = array.array("I") # Re-use ni as an integer array to hold the number of molecules of this name in this frame
ni.fromfile(mol_file, 1) # Read the 4 byte integer value which is the number of molecules (v2) or 3 times the number of molecules (v1)
if ver > 1:
num_mols = ni[0]
num_floats = 3*ni[0]
mol_ids = array.array("I") # Molecule ids are gnored in cellblender
mol_ids.fromfile(mol_file, num_mols)
else:
num_floats = ni[0]
mol_ids = None
mol_pos = array.array("f") # Create a floating point array to hold the positions
mol_orient = array.array("f") # Create a floating point array to hold the orientations
mol_pos.fromfile(mol_file, num_floats) # Read all the positions which should be 3 floats per molecule
if mt[0] == 1: # If mt==1, it's a surface molecule
mol_orient.fromfile(mol_file, num_floats) # Read all the surface molecule orientations
if mcell.cellblender_preferences.mcell4_mode:
elem_mol_names = get_used_molecule_names(mol_name_from_file)
else:
# MCell3(R) in binary viz mode already splits the complexes into individual molecules
elem_mol_names = [mol_name_from_file]
for elem_mol_name in elem_mol_names:
mol_name = "mol_%s" % (elem_mol_name) # Construct name of blender molecule viz object
# we must append positions and orientations if this mol type already exists
if mol_name not in mol_dict:
mol_dict[mol_name] = [mt[0], mol_pos, mol_orient] # Create a dictionary entry for this molecule containing a list of relevant data
else:
mol_dict[mol_name][1].extend(mol_pos)
mol_dict[mol_name][2].extend(mol_orient)
if len(mcell.mol_viz.mol_viz_list) > 0:
for i in range(len(mcell.mol_viz.mol_viz_list)):
if mcell.mol_viz.mol_viz_list[i].name[4:] == mol_name:
dup_check = True
if dup_check == False:
new_item = mcell.mol_viz.mol_viz_list.add() # Create a new collection item to hold the name for this molecule
new_item.name = mol_name # Assign the name to the new item
except EOFError:
# print("Molecules read: %d" % (int(tot)))
mol_file.close()
break
except:
print( "Unexpected Exception: " + str(sys.exc_info()) )
# print("Molecules read: %d" % (int(tot)))
mol_file.close()
break
else:
# Read ASCII format molecule file:
# print ("Reading ASCII file " + filepath )
bin_data = 0
mol_file.close()
# Create a list of molecule names, positions, and orientations
# Each entry in the list is ordered like this (afaik):
# [molec_name, [x_pos, y_pos, z_pos, x_orient, y_orient, z_orient]]
# Orientations are zero in the case of volume molecules.
mol_data = [[s.split()[0], [
float(x) for x in s.split()[2:]]] for s in open(
filepath, "r").read().split("\n") if s != ""]
for mol in mol_data:
# generate one molecule for each used elementary molecule because
# we do not have shapes/glyphs for all complexes
elem_mol_names = get_used_molecule_names(mol[0])
for elem_mol_name in elem_mol_names:
mol_name = "mol_%s" % elem_mol_name
if not mol_name in mol_dict:
mol_orient = mol[1][3:]
mt = 0
# Check to see if it's a surface molecule
if ((mol_orient[0] != 0.0) | (mol_orient[1] != 0.0) |
(mol_orient[2] != 0.0)):
mt = 1
mol_dict[mol_name] = [mt, array.array("f"), array.array("f")]
new_item = mcell.mol_viz.mol_viz_list.add()
new_item.name = mol_name
mt = mol_dict[mol_name][0]
mol_dict[mol_name][1].extend(mol[1][:3])
if mt == 1:
mol_dict[mol_name][2].extend(mol[1][3:])
# Get the parent object to all the molecule positions if it exists.
# Otherwise, create it.
mols_obj = bpy.data.objects.get("molecules")
if not mols_obj:
bpy.ops.object.add(location=[0, 0, 0]) # Create an "Empty" object in the Blender scene