-
Notifications
You must be signed in to change notification settings - Fork 12
/
cellblender_simulation.py
3585 lines (2899 loc) · 160 KB
/
cellblender_simulation.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 Simulations.
"""
import cellblender
# blender imports
import bpy
import bgl
import blf
from bpy.props import BoolProperty, CollectionProperty, EnumProperty, \
FloatProperty, FloatVectorProperty, IntProperty, \
IntVectorProperty, PointerProperty, StringProperty
from bpy.app.handlers import persistent
# python imports
import array
import glob
import os
import sys
import random
import re
import subprocess
import time
import shutil
import datetime
import math
# CellBlender imports
import cellblender
from . import parameter_system
from . import cellblender_utils
from . import data_model
from cellblender.mdl import data_model_to_mdl
#from cellblender.mdl import run_data_model_mcell
from cellblender.cellblender_utils import project_files_path, mcell_files_path
from multiprocessing import cpu_count
import cellblender.sim_engines as engine_manager
import cellblender.sim_runners as runner_manager
import cellblender.mcell4 as mcell4
def get_pid(item):
return int(item.name.split(',')[0].split(':')[1])
# Provide a less error-prone version for testing
#l = item.name.split(',')[0].split(':')
#rtn_val = 0
#if len(l) > 1:
# rtn_val = int(l[1])
#return rtn_val
############## Overlay Support (some from sim_runners/queue_local/__init__.py) ##################
handler_list = [] # Holds returns from bpy.types.SpaceView3D.draw_handler_add() for removal
screen_display_lines = {} # Dictionary of lines keyed by integer Process ID (PID)
scroll_offset = 0 # Current Scroll offset
scroll_page_size = 10 # Lines per scroll
clear_flag = False # Drawing when this is set will clear the background
showing_text = False # Flag to indicate whether text is currently being shown
def draw_callback_px(context):
# print ( "draw callback -=-=-=-=" + (50 * "-=" ) + "-" )
# Note that the "context" passed in here is a regular dictionary and not the Blender context
global screen_display_lines
global scroll_offset
global clear_flag
local_display_lines = {}
task_dict = cellblender.simulation_queue.task_dict
pid = None
if 'mcell' in bpy.context.scene:
mcell = bpy.context.scene.mcell
if 'run_simulation' in mcell:
rs = mcell.run_simulation
if len(rs.processes_list) > 0:
pid_str = rs.processes_list[rs.active_process_index].name
pid = pid_str.split(',')[0].split()[1]
if pid != None:
ipid = int(pid)
# print ( " ))))))))))) " + str(task_dict[ipid]['output'][-1]) )
local_display_lines[ipid] = [ l.strip() for l in task_dict[ipid]['output'] ]
local_display_lines[ipid].reverse()
screen_display_lines[str(pid)] = local_display_lines[ipid]
# screen_display_lines[str(pid)].reverse() # Reverse since they'll be drawn from the bottom up
bgl.glPushAttrib(bgl.GL_ENABLE_BIT)
if clear_flag:
bgl.glClearColor ( 0.0, 0.0, 0.0, 1.0 )
bgl.glClear ( bgl.GL_COLOR_BUFFER_BIT )
font_id = 0 # XXX, need to find out how best to get this.
y_pos = 15 * (scroll_offset + 1)
if pid and (pid in screen_display_lines):
for l in screen_display_lines[pid]:
blf.position(font_id, 15, y_pos, 0)
y_pos += 15
blf.size(font_id, 14, 72) # fontid, size, DPI
bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
blf.draw(font_id, l)
else:
keys = screen_display_lines.keys()
for k in keys:
for l in screen_display_lines[k]:
blf.position(font_id, 15, y_pos, 0)
y_pos += 15
blf.size(font_id, 14, 72) # fontid, size, DPI
bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
blf.draw(font_id, l)
# 100% alpha, 2 pixel width line
bgl.glEnable(bgl.GL_BLEND)
bgl.glPopAttrib()
# restore opengl defaults
bgl.glLineWidth(1)
bgl.glDisable(bgl.GL_BLEND)
bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
def get_3d_areas():
global handler_list
areas = []
if len(bpy.data.window_managers) > 0:
if len(bpy.data.window_managers[0].windows) > 0:
if len(bpy.data.window_managers[0].windows[0].screen.areas) > 0:
if len(handler_list) <= 0:
for area in bpy.data.window_managers[0].windows[0].screen.areas:
# print ( "Found an area of type " + str(area.type) )
if area.type == 'VIEW_3D':
areas.append ( area )
return ( areas )
def enable_text_overlay():
global handler_list
global showing_text
areas = get_3d_areas()
for area in areas:
temp_context = bpy.context.copy()
temp_context['area'] = area
args = (temp_context,)
handler_list.append ( bpy.types.SpaceView3D.draw_handler_add(draw_callback_px, args, 'WINDOW', 'POST_PIXEL') )
bpy.context.area.tag_redraw()
showing_text = True
print ( "Enable completed" )
def disable_text_overlay():
global handler_list
global showing_text
while len(handler_list) > 0:
print ( "Removing draw_handler " + str(handler_list[-1]) )
bpy.types.SpaceView3D.draw_handler_remove(handler_list[-1], 'WINDOW')
handler_list.pop()
bpy.context.area.tag_redraw()
showing_text = False
print ( "Disable completed" )
def page_up():
global scroll_offset
global scroll_page_size
if scroll_page_size == 0:
# This provides a way to get back to 0 without searching
scroll_offset = 0
else:
scroll_offset += -scroll_page_size
# Force a redraw of the OpenGL code
bpy.context.area.tag_redraw()
def page_dn():
global scroll_offset
global scroll_page_size
if scroll_page_size == 0:
# This provides a way to get back to 0 without searching
scroll_offset = 0
else:
scroll_offset += scroll_page_size
# Force a redraw of the OpenGL code
bpy.context.area.tag_redraw()
class MCELL_OT_show_text_overlay (bpy.types.Operator):
bl_idname = "mcell.show_text_overlay"
bl_label = "Show Text"
bl_description = ("Show the Text Overlay.")
bl_options = {'REGISTER'}
def execute(self, context):
#print ( "Show text" )
enable_text_overlay()
return {'FINISHED'}
class MCELL_OT_hide_text_overlay (bpy.types.Operator):
bl_idname = "mcell.hide_text_overlay"
bl_label = "Hide Text"
bl_description = ("Hide the Text Overlay.")
bl_options = {'REGISTER'}
def execute(self, context):
#print ( "Hide text" )
disable_text_overlay()
return {'FINISHED'}
class MCELL_OT_page_overlay_up (bpy.types.Operator):
bl_idname = "mcell.page_overlay_up"
bl_label = "View Up"
bl_description = ("Page the Text Overlay Up.")
bl_options = {'REGISTER'}
def execute(self, context):
#print ( "Show text" )
page_up()
return {'FINISHED'}
class MCELL_OT_page_overlay_dn (bpy.types.Operator):
bl_idname = "mcell.page_overlay_dn"
bl_label = "View Dn"
bl_description = ("Page the Text Overlay Down.")
bl_options = {'REGISTER'}
def execute(self, context):
#print ( "Hide text" )
page_dn()
return {'FINISHED'}
class MCELL_OT_page_overlay_hm (bpy.types.Operator):
bl_idname = "mcell.page_overlay_hm"
bl_label = "Home"
bl_description = ("Page the Text Overlay to Home.")
bl_options = {'REGISTER'}
def execute(self, context):
global scroll_offset
scroll_offset = 0
# Force a redraw of the OpenGL code
bpy.context.area.tag_redraw()
return {'FINISHED'}
######################################################################
def run_generic_runner (context, sim_module):
mcell = context.scene.mcell
mcell.run_simulation.last_simulation_run_time = str(time.time())
binary_path = mcell.cellblender_preferences.mcell_binary
mcell.cellblender_preferences.mcell_binary_valid = cellblender_utils.is_executable ( binary_path )
if not mcell.cellblender_preferences.mcell_binary_valid:
print ( "cellblender_simulation.run_generic_runner: invalid binary: " + str(binary_path) )
start = int(mcell.run_simulation.start_seed.get_value())
end = int(mcell.run_simulation.end_seed.get_value())
mcell_processes_str = str(mcell.run_simulation.mcell_processes)
mcell_binary = mcell.cellblender_preferences.mcell_binary
# Force the project directory to be where the .blend file lives
mcell_files = mcell_files_path()
project_dir = os.path.join( mcell_files, "output_data" )
status = ""
if not mcell.cellblender_preferences.decouple_export_run:
bpy.ops.mcell.export_project()
if (mcell.run_simulation.error_list and
mcell.cellblender_preferences.invalid_policy == 'dont_run'):
pass
else:
react_dir = os.path.join(project_dir, "react_data")
if (os.path.exists(react_dir) and
mcell.run_simulation.remove_append == 'remove'):
shutil.rmtree(react_dir)
if not os.path.exists(react_dir):
os.makedirs(react_dir, exist_ok=True)
viz_dir = os.path.join(project_dir, "viz_data")
if (os.path.exists(viz_dir) and
mcell.run_simulation.remove_append == 'remove'):
shutil.rmtree(viz_dir)
if not os.path.exists(viz_dir):
os.makedirs(viz_dir, exist_ok=True)
runner_input = "dm.txt"
if "runner_input" in dir(sim_module):
runner_input = sim_module.runner_input
mcell_dm = mcell.build_data_model_from_properties ( context, geometry=True, scripts=True )
if runner_input.endswith("json"):
data_model.save_data_model_to_json_file ( mcell_dm, os.path.join(project_dir,runner_input) )
else:
print("SAVING to " + os.path.join(project_dir,runner_input))
data_model.save_data_model_to_file ( mcell_dm, os.path.join(project_dir,runner_input) )
base_name = mcell.project_settings.base_name
error_file_option = mcell.run_simulation.error_file
log_file_option = mcell.run_simulation.log_file
script_dir_path = os.path.dirname(os.path.realpath(__file__))
engine_manager.write_default_data_layout(mcell_files, start, end)
processes_list = mcell.run_simulation.processes_list
processes_list.add()
mcell.run_simulation.active_process_index = len(mcell.run_simulation.processes_list) - 1
simulation_process = processes_list[mcell.run_simulation.active_process_index]
print("Starting MCell ... create " + project_files_path() + "/start_time.txt file:")
engine_manager.makedirs_exist_ok ( project_files_path(), exist_ok=True )
with open(os.path.join(project_files_path(),"start_time.txt"), "w") as start_time_file:
start_time_file.write("Started simulation at: " + (str(time.ctime())) + "\n")
commands = []
for sim_seed in range(start,end+1):
new_command = [
mcell_binary,
("-seed %s" % str(sim_seed)),
os.path.join(project_dir, ("%s.main.mdl" % base_name))
]
commands.append ( new_command )
sp_list = sim_module.run_commands ( commands, cwd=project_dir )
for sp in sp_list:
cellblender.simulation_popen_list.append(sp)
if ((end - start) == 0):
simulation_process.name = ("PID: %d, Seed: %d" %
(sp_list[0].pid, start))
else:
simulation_process.name = ("PID: %d-%d, Seeds: %d-%d" %
(sp_list[0].pid, sp_list[-1].pid, start, end))
mcell.run_simulation.status = status
return {'FINISHED'}
# Simulation Operators:
class MCELL_OT_dm_export_mdl(bpy.types.Operator):
bl_idname = "mcell.dm_export_mdl"
bl_label = "Export CellBlender Project"
bl_description = ("Export CellBlender Project (via data model)")
bl_options = {'REGISTER'}
@classmethod
def poll(self,context):
mcell = context.scene.mcell
if mcell.cellblender_preferences.lockout_export and mcell.cellblender_preferences.decouple_export_run:
# print ( "Exporting is currently locked out. See the Preferences/ExtraOptions panel." )
# The "self" here doesn't contain or permit the report function.
# self.report({'INFO'}, "Exporting is Locked Out")
return False
else:
# Note: We could copy more complex logic from mcell.run_simulation's poll method.
return True
return True
def execute(self, context):
print ( "Export via data model" )
mcell = context.scene.mcell
run_sim = mcell.run_simulation
run_sim.export_requested = True
run_sim.run_requested = False
if str(run_sim.simulation_run_control) == 'SWEEP_QUEUE':
bpy.ops.mcell.run_simulation_sweep_queue()
#elif str(run_sim.simulation_run_control) == 'SWEEP_SGE':
# bpy.ops.mcell.run_simulation_sweep_sge()
else:
print ( "Run option \"" + str(run_sim.simulation_run_control) + "\" cannot be exported without being run in this version of CellBlender." )
print ( " Disable the \"Decouple Export and Run\" option to use this runner." )
return {'FINISHED'}
class MCELL_OT_run_simulation(bpy.types.Operator):
bl_idname = "mcell.run_simulation"
bl_label = "Run MCell Simulation"
bl_description = "Run MCell Simulation"
bl_options = {'REGISTER'}
@classmethod
def poll(self,context):
mcell = context.scene.mcell
if mcell.cellblender_preferences.lockout_export and (not mcell.cellblender_preferences.decouple_export_run):
# print ( "Exporting is currently locked out. See the Preferences/ExtraOptions panel." )
# The "self" here doesn't contain or permit the report function.
# self.report({'INFO'}, "Exporting is Locked Out")
return False
elif str(mcell.run_simulation.simulation_run_control) == 'QUEUE':
processes_list = mcell.run_simulation.processes_list
for pl_item in processes_list:
pid = get_pid(pl_item)
q_item = cellblender.simulation_queue.task_dict[pid]
if (q_item['status'] == 'running') or (q_item['status'] == 'queued'):
return False
elif str(mcell.run_simulation.simulation_run_control) == 'DYNAMIC':
global active_engine_module
global active_runner_module
# Force an update of the pluggable items as needed (typically after starting Blender).
if active_engine_module == None:
mcell.sim_engines.plugs_changed_callback ( context )
if active_runner_module == None:
mcell.sim_runners.plugs_changed_callback ( context )
if active_engine_module == None:
# print ( "Cannot run without selecting a simulation engine" )
status = "Error: No simulation engine selected"
elif active_runner_module == None:
# print ( "Cannot run without selecting a simulation runner" )
status = "Error: No simulation runner selected"
elif 'get_pid' in dir(active_runner_module):
processes_list = mcell.run_simulation.processes_list
for pl_item in processes_list:
pid = get_pid(pl_item)
if pid in cellblender.simulation_queue.task_dict:
q_item = cellblender.simulation_queue.task_dict[pid]
if (q_item['status'] == 'running') or (q_item['status'] == 'queued'):
return False
return True
def execute(self, context):
print ( "Call to \"execute\" for MCELL_OT_run_simulation operator" )
mcell = context.scene.mcell
ps = mcell.parameter_system
run_sim = mcell.run_simulation
run_sim.last_simulation_run_time = str(time.time())
# Calculate the number of runs and check against the limit
start_seed = int(run_sim.start_seed.get_value())
end_seed = int(run_sim.end_seed.get_value())
run_limit = int(run_sim.run_limit.get_value())
total_sweep_runs = ps.count_sweep_runs()
print ( "Requested sweep runs = " + str(total_sweep_runs) )
num_runs_requested = (1 + end_seed - start_seed) * total_sweep_runs
print ( "Requested runs (including seeds) = " + str(num_runs_requested) )
if mcell.cellblender_preferences.decouple_export_run:
run_sim.export_requested = False
else:
run_sim.export_requested = True
run_sim.run_requested = True
if mcell.cellblender_preferences.lockout_export and (not mcell.cellblender_preferences.decouple_export_run):
# Exporting is locked out and this operator is in "Export and Run Mode"
print ( "Exporting is currently locked out. See the Preferences/ExtraOptions panel." )
self.report({'INFO'}, "Exporting is Locked Out")
elif (run_limit >=0) and (num_runs_requested > run_limit):
print ( "Run limit exceeded. Reduce number of runs or increase limit." )
self.report({'INFO'}, "Request for %d runs exceeds limit of %d" % (num_runs_requested, run_limit) )
else:
### Note: This section of code was taken from the export for cases where a
### newly opened .blend file is being run without being exported.
### In that case, the project name was still defaulted to "cellblender_project".
# Filter or replace problem characters (like space, ...)
scene_name = context.scene.name.replace(" ", "_")
# Change the actual scene name to the legal MCell Name
context.scene.name = scene_name
# Set this for now to have it hopefully propagate until base_name can
# be removed
mcell.project_settings.base_name = scene_name
print ( "Need to run " + str(mcell.run_simulation.simulation_run_control) )
if str(mcell.run_simulation.simulation_run_control) == 'SWEEP_QUEUE':
bpy.ops.mcell.run_simulation_sweep_queue()
elif str(mcell.run_simulation.simulation_run_control) == 'QUEUE':
bpy.ops.mcell.run_simulation_control_queue()
elif str(mcell.run_simulation.simulation_run_control) == 'COMMAND':
bpy.ops.mcell.run_simulation_normal()
elif str(run_sim.simulation_run_control) == 'SWEEP':
bpy.ops.mcell.run_simulation_sweep()
elif str(run_sim.simulation_run_control) == 'SWEEP_SGE':
bpy.ops.mcell.run_simulation_sweep_sge()
elif str(run_sim.simulation_run_control) == 'DYNAMIC':
bpy.ops.mcell.run_simulation_dynamic()
else:
print ( "Unexpected case (" + str(mcell.run_simulation.simulation_run_control) + ") in MCELL_OT_run_simulation" )
pass
return {'FINISHED'}
class MCELL_OT_run_simulation_control_sweep (bpy.types.Operator):
bl_idname = "mcell.run_simulation_sweep"
bl_label = "Run MCell Simulation Command"
bl_description = "Run MCell Simulation Command Line"
bl_options = {'REGISTER'}
def execute(self, context):
print("Executing Sweep Runner")
mcell = context.scene.mcell
run_sim = mcell.run_simulation
run_sim.last_simulation_run_time = str(time.time())
start = int(run_sim.start_seed.get_value())
end = int(run_sim.end_seed.get_value())
mcell_processes_str = str(run_sim.mcell_processes)
mcell_binary = cellblender_utils.get_mcell_path(mcell)
# Force the project directory to be where the .blend file lives
project_dir = mcell_files_path()
status = ""
python_path = cellblender.cellblender_utils.get_python_path(mcell=mcell)
if python_path:
if not mcell.cellblender_preferences.decouple_export_run:
bpy.ops.mcell.export_project()
if (run_sim.error_list and mcell.cellblender_preferences.invalid_policy == 'dont_run'):
pass
else:
sweep_dir = os.path.join(project_dir, "output_data")
if (os.path.exists(sweep_dir) and run_sim.remove_append == 'remove'):
shutil.rmtree(sweep_dir)
if not os.path.exists(sweep_dir):
os.makedirs(sweep_dir, exist_ok=True)
mcell_dm = mcell.build_data_model_from_properties ( context, geometry=True, scripts=True )
data_model.save_data_model_to_json_file ( mcell_dm, os.path.join(project_dir,"data_model.json") )
# base_name = mcell.project_settings.base_name
base_name = context.scene.name.replace(" ", "_")
error_file_option = run_sim.error_file
log_file_option = run_sim.log_file
script_dir_path = os.path.dirname(os.path.realpath(__file__))
# The following Python program will create the "data_layout.json" file describing the directory structure
script_file_path = os.path.join(script_dir_path, os.path.join("mdl", "run_data_model_mcell.py") )
processes_list = run_sim.processes_list
processes_list.add()
run_sim.active_process_index = len(run_sim.processes_list) - 1
simulation_process = processes_list[run_sim.active_process_index]
print("Starting MCell ... create " + project_files_path() + "/start_time.txt file:")
engine_manager.makedirs_exist_ok ( project_files_path(), exist_ok=True )
with open(os.path.join(project_files_path(),"start_time.txt"), "w") as start_time_file:
start_time_file.write("Started simulation at: " + (str(time.ctime())) + "\n")
# We have to create a new subprocess that in turn creates a
# multiprocessing pool, instead of directly creating it here,
# because the multiprocessing package requires that the __main__
# module be importable by the children.
print ( "Running subprocess with:" +
"\n python_path = " + str(python_path) +
"\n script_file_path = " + str(script_file_path) +
"\n mcell_binary = " + str(mcell_binary) +
"\n start = " + str(start) +
"\n end = " + str(end) +
"\n project_dir = " + str(project_dir) +
"\n base_name = " + str(base_name) +
"\n error_file_option = " + str(error_file_option) +
"\n log_file_option = " + str(log_file_option) +
"\n mcell_processes_str = " + str(mcell_processes_str) +
"\n" )
sp = subprocess.Popen([
python_path,
script_file_path,
os.path.join(project_dir,"data_model.json"),
"-b", mcell_binary,
"-fs", str(start), "-ls", str(end),
"-pd", project_dir,
"-ef", error_file_option,
"-lf", log_file_option,
"-np", mcell_processes_str],
stdout=None,
stderr=None)
self.report({'INFO'}, "Simulation Starting...")
# This is a hackish workaround since we can't return arbitrary
# objects from operators or store arbitrary objects in collection
# properties, and we need to keep track of the progress of the
# subprocess objects for the panels.
cellblender.simulation_popen_list.append(sp)
if ((end - start) == 0):
simulation_process.name = ("PID: %d, Seed: %d" % (sp.pid, start))
else:
simulation_process.name = ("PID: %d, Seeds: %d-%d" % (sp.pid, start, end))
else:
status = "Python not found. Set it in Project Settings."
run_sim.status = status
return {'FINISHED'}
class MCELL_OT_percentage_done_timer(bpy.types.Operator):
"""Update the MCell job list periodically to show percentage done"""
bl_idname = "mcell.percentage_done_timer"
bl_label = "Modal Timer Operator"
bl_options = {'REGISTER'}
_timer = None
def modal(self, context, event):
if event.type == 'TIMER':
task_len = len(cellblender.simulation_queue.task_dict)
task_ctr = 0
mcell = context.scene.mcell
if mcell.run_simulation.print_timer_ticks:
print ( "modal -=-=-=-=" + (50 * "-=" ) + "-" )
processes_list = mcell.run_simulation.processes_list
for simulation_process in processes_list:
#if not mcell.run_simulation.save_text_logs:
# return {'CANCELLED'}
pid = get_pid(simulation_process)
seed = int(simulation_process.name.split(',')[1].split(':')[1])
q_item = cellblender.simulation_queue.task_dict[pid] # q_item is a dictionary with stdout,stderr,status,args,cmd,process,bl_text
percent = None
if 'output' in q_item:
output_lines = q_item['output']
n = len(output_lines)
last_iter = total_iter = 0
for i in reversed(range(n)):
l = output_lines[i]
if l.startswith("Iterations"):
last_iter = int(l.split()[1])
total_iter = int(l.split()[3])
percent = (last_iter/total_iter)*100
break
if ((last_iter == total_iter) and (total_iter != 0)) or (q_item['status'] in ['died','mcell_error']):
task_ctr += 1
if percent is None:
simulation_process.name = "PID: %d, Seed: %d" % (pid, seed)
else:
simulation_process.name = "PID: %d, Seed: %d, %d%%" % (pid, seed, percent)
# just a silly way of forcing a screen update. ¯\_(ツ)_/¯
color = context.preferences.themes[0].view_3d.empty
color[0] += 0.01
color[0] -= 0.01
# if every MCell job is done, quit updating the screen
if task_len == task_ctr:
self.cancel(context)
return {'CANCELLED'}
return {'PASS_THROUGH'}
def execute(self, context):
print ( "Inside MCELL_OT_percentage_done_timer.execute with context = " + str(context) )
print ( "Inside MCELL_OT_percentage_done_timer.execute with mcell = " + str(context.scene.mcell) )
run_sim = context.scene.mcell.run_simulation
delay = run_sim.text_update_timer_delay # this is how often we should update this in seconds
print ( "Setting timer to delay of " + str(delay) )
wm = context.window_manager
self._timer = wm.event_timer_add(time_step=delay, window=context.window)
wm.modal_handler_add(self)
return {'RUNNING_MODAL'}
def cancel(self, context):
wm = context.window_manager
wm.event_timer_remove(self._timer)
class MCELL_OT_run_simulation_sweep_queue(bpy.types.Operator):
bl_idname = "mcell.run_simulation_sweep_queue"
bl_label = "Run MCell Simulation Using Sweep Queue"
bl_description = "Run MCell Simulation Using Sweep Queue"
bl_options = {'REGISTER'}
def execute(self, context):
print ( "+++++++++++++ Begin: mcell.run_simulation_sweep_queue +++++++++++++" )
mcell = context.scene.mcell
run_sim = mcell.run_simulation
mcell4_mode = mcell.cellblender_preferences.mcell4_mode
if mcell.cellblender_preferences.mcell4_mode:
print ( "- Using mcell4 mode" )
run_sim.last_simulation_run_time = str(time.time())
start_seed = int(run_sim.start_seed.get_value())
end_seed = int(run_sim.end_seed.get_value())
mcell_processes = run_sim.mcell_processes
mcell_processes_str = str(run_sim.mcell_processes)
mcell_binary = cellblender_utils.get_mcell_path(mcell)
ext_path = os.path.dirname(os.path.realpath(mcell_binary))
# Set environment variable for the shared library path
my_env = os.environ.copy()
if (sys.platform == 'darwin'):
if my_env.get('DYLD_LIBRARY_PATH'):
my_env['DYLD_LIBRARY_PATH']=os.path.join(ext_path,'lib') + os.pathsep + my_env['DYLD_LIBRARY_PATH']
else:
my_env['DYLD_LIBRARY_PATH']=os.path.join(ext_path,'lib')
else:
if my_env.get('LD_LIBRARY_PATH'):
my_env['LD_LIBRARY_PATH']=os.path.join(ext_path,'lib') + os.pathsep + my_env['LD_LIBRARY_PATH']
else:
my_env['LD_LIBRARY_PATH']=os.path.join(ext_path,'lib')
# Force the project directory to be where the .blend file lives
project_dir = mcell_files_path()
status = ""
python_path = cellblender.cellblender_utils.get_python_path(mcell=mcell)
if python_path:
#if not mcell.cellblender_preferences.decouple_export_run:
# bpy.ops.mcell.export_project()
# The separation between exporting and running is complicated when sweeping
# because the same steps may need to be carried out twice. The sweep needs
# to be traversed when exporting, and it needs to be traversed again to generate
# the run commands. Otherwise it needs to be saved between exporting and running.
#
# For now, this is handled with these two flags:
# export_requested: BoolProperty(name="Export Requested", default=True)
# run_requested: BoolProperty(name="Run Requested", default=True)
# This allows the same code to do what's appropriate for the current requests.
if (run_sim.error_list and mcell.cellblender_preferences.invalid_policy == 'dont_run'):
pass
else:
react_dir = os.path.join(project_dir, "output_data", "react_data")
viz_dir = os.path.join(project_dir, "output_data", "viz_data")
if run_sim.export_requested and (run_sim.remove_append == 'remove'):
# Remove the entire output directory
out_dir = os.path.join(project_dir, "output_data")
if os.path.exists(out_dir):
shutil.rmtree(out_dir)
if run_sim.export_requested and not os.path.exists(react_dir):
os.makedirs(react_dir, exist_ok=True)
if run_sim.export_requested and not os.path.exists(viz_dir):
os.makedirs(viz_dir, exist_ok=True)
# This assumes "mcell.export_project" operator had been run: base_name = mcell.project_settings.base_name
# Do this here since "mcell.export_project" is not being used with this code.
base_name = scene_name = context.scene.name.replace(" ", "_")
if run_sim.export_requested:
# The export checking logic is broken for sweep runs that don't have a main MDL file at the top.
# Rather than muck with that right now, just create a dummy file to signal that it's been exported.
##################################################################
main_mdl = mcell_files_path()
main_mdl = os.path.join(main_mdl, "output_data")
main_mdl = os.path.join(main_mdl, base_name + ".main.mdl")
main_mdl_file = open(main_mdl, "w", encoding="utf8", newline="\n")
main_mdl_file.write ( "/* This file is written to signal to CellBlender that the project has been exported. */" )
main_mdl_file.close()
##################################################################
error_file_option = run_sim.error_file
log_file_option = run_sim.log_file
cellblender.simulation_queue.python_exec = python_path
cellblender.simulation_queue.start(mcell_processes)
cellblender.simulation_queue.notify = True
if run_sim.enable_run_once_script:
# Execute a run once during export data model script before getting the data model
script_name = None
if run_sim.internal_external == "internal":
script_name = run_sim.dm_run_once_internal_fn
print ( "Executing internal script" )
if not script_name in bpy.data.texts:
print ( "Error: Script \"" + script_name + "\" is not an internal script name. Try refreshing the scripts list." )
else:
# This version just runs the script
script_text = bpy.data.texts[script_name].as_string()
print ( 80*"=" )
print ( script_text )
print ( 80*"=" )
exec ( script_text, locals() )
elif run_sim.internal_external == "external":
script_name = run_sim.dm_run_once_external_fn
print ( "Executing external script \"" + str(script_name) + "\" ... not implemented yet!!" )
dm = None
if run_sim.export_requested:
# When exporting, the geometry data will be needed to write the MDL
dm = mcell.build_data_model_from_properties ( context, geometry=True, scripts=True )
else:
# When just running, the geometry data isn't needed so build a data model without it
dm = mcell.build_data_model_from_properties ( context, geometry=False, scripts=False )
sweep_list = engine_manager.build_sweep_list( dm['parameter_system'] )
print ( "Sweep list = " + str(sweep_list) )
# Add a "current_index" of 0 to support the sweeping
for sw_item in sweep_list:
sw_item['current_index'] = 0
print ( " Sweep list item = " + str(sw_item) )
if run_sim.export_requested:
# The following line will create the "data_layout.json" file describing the directory structure
engine_manager.write_sweep_list_to_layout_file ( sweep_list, start_seed, end_seed, os.path.join ( project_dir, "data_layout.json" ) )
# Count the number of sweep runs
num_sweep_runs = engine_manager.count_sweep_runs ( sweep_list )
num_requested_runs = num_sweep_runs * (1 + end_seed - start_seed)
print ( "Number of non-seed sweep runs = " + str(num_sweep_runs) )
print ( "Total runs (sweep and seed) is " + str(num_requested_runs) )
bionetgen_mode = data_model_to_mdl.requires_mcellr ( {'mcell':dm} ) or mcell.cellblender_preferences.bionetgen_mode
# Build a list of "run commands" (one for each run) to be put in the queue
# Note that the format of these came from the original "run_simulations.py" program and may not be what we want in the long run
run_cmd_list = []
# Build a sweep list with an "output_data" prefix directory
for run in range (num_sweep_runs):
sweep_path = "output_data"
for sw_item in sweep_list:
sweep_path += os.sep + sw_item['par_name'] + "_index_" + str(sw_item['current_index'])
print ( "Sweep path = " + sweep_path )
# Set the data model parameters to the current parameter settings
for par in dm['parameter_system']['model_parameters']:
if ('par_name' in par):
for sweep_item in sweep_list:
if par['par_name'] == sweep_item['par_name']:
par['par_expression'] = str(sweep_item['values'][sweep_item['current_index']])
# Sweep through the seeds for this set of parameters creating a run specification for each seed
for seed in range(start_seed,end_seed+1):
# Create the directories and write the MDL
sweep_item_path = os.path.join(project_dir,sweep_path)
if run_sim.export_requested:
engine_manager.makedirs_exist_ok ( sweep_item_path, exist_ok=True )
engine_manager.makedirs_exist_ok ( os.path.join(sweep_item_path,'react_data'), exist_ok=True )
engine_manager.makedirs_exist_ok ( os.path.join(sweep_item_path,'viz_data'), exist_ok=True )
if mcell4_mode:
dm_file = str(os.path.join(sweep_item_path, '%s.data_model.json' % (base_name)))
print ( "Writing data model to " + dm_file )
data_model.save_data_model_to_json_file(dm, dm_file)
print ( "Converting data model to MCell4 Python code" )
error_msg = mcell4.convert_data_model_to_python(mcell_binary, dm_file, sweep_item_path, base_name, bionetgen_mode)
if error_msg:
status = 'Conversion of data model into MCell4 Python code failed. ' + error_msg
self.report({'ERROR'}, status)
return {'FINISHED'} # what should be returned when error was encountered?
else:
print ( "Writing data model as MDL at " + str(os.path.join(sweep_item_path, '%s.main.mdl' % (base_name) )) )
cellblender.current_data_model = {'mcell':dm} # this creates two mcell levels: mcell: { mcell: {
data_model_to_mdl.write_mdl ( cellblender.current_data_model, os.path.join(sweep_item_path, '%s.main.mdl' % (base_name) ), scene_name=context.scene.name )
run_cmd_list.append ( [mcell_binary, sweep_item_path, base_name, error_file_option, log_file_option, seed] )
# Increment the current_index counters from rightmost side (deepest directory)
i = len(sweep_list) - 1
while i >= 0:
sweep_list[i]['current_index'] += 1
if sweep_list[i]['current_index'] >= len(sweep_list[i]['values']):
sweep_list[i]['current_index'] = 0
else:
break
i += -1
# Print the run commands as a record of what's being done
print ( "Run Cmds for Sweep Queue (0:mcell, 1:wd, 2:base_name, 3:error, 4:log, 5:seed):" )
for run_cmd in run_cmd_list:
print ( " " + str(run_cmd) )
if run_sim.run_requested:
processes_list = run_sim.processes_list
#for seed in range(start_seed,end_seed + 1):
for run_cmd in run_cmd_list:
processes_list.add()
run_sim.active_process_index = len(run_sim.processes_list) - 1
simulation_process = processes_list[run_sim.active_process_index]
print("Starting MCell ... create " + project_files_path() + "/start_time.txt file:")
engine_manager.makedirs_exist_ok ( project_files_path(), exist_ok=True )
with open(os.path.join(project_files_path(),"start_time.txt"), "w") as start_time_file:
start_time_file.write("Started simulation at: " + (str(time.ctime())) + "\n")
# Log filename will be log.year-month-day_hour:minute_seed.txt
# (e.g. log.2013-03-12_11:45_1.txt)
time_now = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M")
if error_file_option == 'file':
error_filename = "error.%s_%d.txt" % (time_now, seed) # Note: this is insufficiently unique for sweeps
elif error_file_option == 'none':
error_file = subprocess.DEVNULL
elif error_file_option == 'console':
error_file = None
if log_file_option == 'file':
log_filename = "log.%s_%d.txt" % (time_now, seed) # Note: this is insufficiently unique for sweeps
elif log_file_option == 'none':
log_file = subprocess.DEVNULL
elif log_file_option == 'console':
log_file = None
if not mcell4_mode and bionetgen_mode:
# execute mdlr2mdl.py to generate MDL from MDLR
mdlr_cmd = os.path.join ( ext_path, 'mdlr2mdl.py' )
mdlr_args = [ cellblender.python_path, mdlr_cmd, '-ni', 'Scene.mdlr', '-o', 'Scene' ]
wd = run_cmd[1]
print ( "\n\nConverting MDLR to MDL by running " + str(mdlr_args) + " from " + str(wd) )
#p = subprocess.Popen(mdlr_args, cwd = wd)
# The previous seemed to fail. Try this:
print ( "\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" )
with subprocess.Popen(mdlr_args, env=my_env, cwd=wd, stdout=subprocess.PIPE) as pre_proc:
pre_proc.wait()
print ( "\n\nProcess Finished from Operator with:\n" + str(pre_proc.stdout.read().decode('utf-8')) + "\n\n" )
print ( "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n" )
print ( "Done " + str(mdlr_args) + " from " + str(wd) )
mcellr_args = None
if True:
# TODO This is sending as a list (the new way)
mcellr_args = [ os.path.join(ext_path, "mcell3r.py"), '-s', str(run_cmd[5]), '-r', 'Scene.mdlr_rules.xml', '-m', 'Scene.main.mdl' ]
if len(mcell.initialization.command_options) > 0:
mcellr_args.append ( mcell.initialization.command_options.split() ) # Split by spaces
else:
# TODO This is sending as a string (the old way)
# Passing mcellr_args as a list seemed to cause problems ... try as a string instead ...
# mcellr_args = [ os.path.join(ext_path, "mcell3r.py"), '-s', str(run_cmd[5]), '-r', 'Scene.mdlr_rules.xml', '-m', 'Scene.main.mdl' ]
mcellr_args = os.path.join(ext_path, "mcell3r.py") + ' -s ' + str(run_cmd[5]) + ' -r ' + 'Scene.mdlr_rules.xml' + ' -m ' + 'Scene.main.mdl'
if len(mcell.initialization.command_options) > 0:
mcellr_args = mcellr_args + " " + mcell.initialization.command_options
make_texts = run_sim.save_text_logs
print ( 100 * "@" )
print ( "Add Task:" + cellblender.python_path + " args:" + str(mcellr_args) + " wd:" + str(run_cmd[1]) + " txt:" + str(make_texts) )
proc = cellblender.simulation_queue.add_task([cellblender.python_path], mcellr_args, run_cmd[1], make_texts, env=my_env)
print ( 100 * "@" )
elif not mcell4_mode:
mdl_filename = '%s.main.mdl' % (run_cmd[2])
mcell_args = '-seed %d %s' % (run_cmd[5], mdl_filename)
if len(mcell.initialization.command_options) > 0:
mcell_args = mcell_args + " " + mcell.initialization.command_options
make_texts = run_sim.save_text_logs
print ( 100 * "@" )
print ( "Add Task:" + run_cmd[0] + " args:" + str(mcell_args) + " wd:" + str(run_cmd[1]) + " txt:" + str(make_texts) )
proc = cellblender.simulation_queue.add_task(run_cmd[0], mcell_args, run_cmd[1], make_texts, env=my_env)
print ( 100 * "@" )
else:
# mcell4