-
Notifications
You must be signed in to change notification settings - Fork 12
/
parameter_system.py
3167 lines (2666 loc) · 139 KB
/
parameter_system.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
"""
This module supports parameters and evaluation of expressions.
"""
"""
### This CellBlender Data Model script can generate parameters for testing
num_pars_to_gen = 20
num_back = 2
make_loop = False
import cellblender as cb
dm = cb.get_data_model()
def make_par_name ( n ):
name = None
if n < 26:
name = chr(ord('a')+n)
else:
name = "P_" + str(n)
if (n % 3) == 0:
name += 'x'
if (n % 3) == 1:
name += 'y'
return name
pars = []
for n in range(num_pars_to_gen):
pname = make_par_name ( n )
par = {}
par['par_name'] = pname
par['par_description'] = "Description for " + pname
par['par_units'] = "u"
par['par_expression'] = "1"
for i in range(max(n-num_back,0),n):
par['par_expression'] += " + "
par['par_expression'] += make_par_name ( i )
pars.append ( par )
if make_loop:
mid = round(num_pars_to_gen / 2)
print ( " mid = " + str(mid) )
if (mid-1) >= 0:
# There are enough parameters to make a loop
pars[mid-1]['par_expression'] += " + " + pars[mid]['par_name']
dm['mcell']['parameter_system'] = { 'model_parameters':pars }
cb.replace_data_model ( dm )
"""
#Handy debugging line: __import__('code').interact(local={k: v for ns in (globals(), locals()) for k, v in ns.items()})
import bpy
from bpy.props import *
from math import *
from random import uniform, gauss
import parser
import re
import token
import symbol
import sys
import pickle
import time
import io
import math
import inspect
from . import cellblender_utils
def dbprint ( s, thresh=1 ): # Threshold high means no printing, Threshold low (or negative) means lots of printing
ps = bpy.context.scene.mcell.parameter_system
if ps.debug_level >= thresh:
print ( s )
def write_lines_in_box(lines, layout, box):
for var in lines:
row = layout.row(align = True)
row.alignment = 'EXPAND'
box.label(text=var)
####################### Start of Profiling Code #######################
# From: http://wiki.blender.org/index.php/User:Z0r/PyDevAndProfiling
prof = {}
# Defines a dictionary associating a call name with a list of 3 (now 4) entries:
# 0: Name
# 1: Duration
# 2: Count
# 3: Start Time (for non-decorated version)
class profile:
''' Function decorator for code profiling.'''
def __init__(self,name):
self.name = name
def print_call_stack(self):
frame = inspect.currentframe()
call_list_frames = inspect.getouterframes(frame)
filtered_frames = [ {"function":f.function, "line":f.lineno, "file":f.filename} for f in call_list_frames if not ( f.function in ("execute", "print_frame", "profile_fun", "draw", "draw_self", "draw_layout") ) ]
if len(filtered_frames) > 0:
filtered_frames.reverse()
s = ""
last_call = ""
num_repeat = 0
sep = " -> "
for f in filtered_frames:
# this_call = str(f["function"]) + '[' + str(f["line"]) + ' in ' + str(f["file"].split('/')[-1].split('.')[0]) + ']'
this_call = str(f["function"]).strip()
if this_call == last_call:
num_repeat += 1
else:
repeat_str = num_repeat * "*"
#if len(repeat_str) > 0:
# repeat_str = " " + repeat_str + " "
s += last_call + repeat_str + sep
num_repeat = 0
last_call = this_call
# print ( " Frame: " + str(f.function) + " at " + str(f.lineno) + " in " + str(f.filename.split('/')[-1].split('.')[0]) )
if num_repeat > 0:
s += last_call + (num_repeat * "*") + sep
s = s[len(sep):-len(sep)]
if len(s) > 0:
print ( s )
del filtered_frames
del call_list_frames
del frame
def __call__(self,fun):
def profile_fun(*args, **kwargs):
#self.print_call_stack() # This will print the call stack as each function is called
start = time.process_time()
try:
return fun(*args, **kwargs)
finally:
duration = time.process_time() - start
if fun in prof:
prof[fun][1] += duration
prof[fun][2] += 1
else:
prof[fun] = [self.name, duration, 1, 0]
return profile_fun
# Builds on the previous profiling code with non-decorated versions (needed by some Blender functions):
# 0: Name
# 1: Duration
# 2: Count
# 3: Start Time (for non-decorated version)
def start_timer(fun):
start = time.process_time()
if fun in prof:
prof[fun][2] += 1
prof[fun][3] = start
else:
prof[fun] = [fun, 0, 1, start]
def stop_timer(fun):
stop = time.process_time()
if fun in prof:
prof[fun][1] += stop - prof[fun][3] # Stop - Start
# prof[fun][2] += 1
else:
print ( "Timing Error: stop called without start!!" )
pass
def print_statistics(app):
'''Prints profiling results to the console,
appends to plot files,
and generates plotting and deleting scripts.'''
print ( "=== Execution Statistics with " + str(len(app.parameter_system.general_parameter_list)) + " general parameters and " + str(len(app.parameter_system.panel_parameter_list)) + " panel parameters ===" )
def timekey(stat):
return stat[1] / float(stat[2])
stats = sorted(prof.values(), key=timekey, reverse=True)
print ( '{:<55} {:>7} {:>7} {:>8}'.format('FUNCTION', 'CALLS', 'SUM(ms)', 'AV(ms)'))
for stat in stats:
print ( '{:<55} {:>7} {:>7.0f} {:>8.2f}'.format(stat[0],stat[2],stat[1]*1000,(stat[1]/float(stat[2]))*1000))
f = io.open(stat[0]+"_plot.txt",'a')
#f.write ( str(len(app.parameter_system.general_parameter_list)) + " " + str((stat[1]/float(stat[2]))*1000) + "\n" )
f.write ( str(len(app.parameter_system.general_parameter_list)) + " " + str(float(stat[1])*1000) + "\n" )
f.flush()
f.close()
f = io.open("plot_command.bat",'w')
f.write ( "java -jar data_plotters/java_plot/PlotData.jar" )
for stat in stats:
f.write ( " fxy=" + stat[0]+"_plot.txt" )
f.flush()
f.close()
f = io.open("delete_command.bat",'w')
for stat in stats:
f.write ( "rm -f " + stat[0]+"_plot.txt\n" )
f.flush()
f.close()
class MCELL_OT_print_profiling(bpy.types.Operator):
bl_idname = "mcell.print_profiling"
bl_label = "Print Profiling"
bl_description = ("Print Profiling Information")
bl_options = {'REGISTER'}
def execute(self, context):
app = context.scene.mcell
print_statistics(app)
return {'FINISHED'}
def invoke(self, context, event):
app = context.scene.mcell
print_statistics(app)
return {'RUNNING_MODAL'}
class MCELL_OT_clear_profiling(bpy.types.Operator):
bl_idname = "mcell.clear_profiling"
bl_label = "Clear Profiling"
bl_description = ("Clear Profiling Information")
bl_options = {'REGISTER'}
def execute(self, context):
prof.clear()
return {'FINISHED'}
def invoke(self, context, event):
prof.clear()
return {'RUNNING_MODAL'}
####################### End of Profiling Code #######################
#####################################################################
# Forced update operators (may be commented out when not used)
#####################################################################
#class MCELL_OT_update_general(bpy.types.Operator):
# bl_idname = "mcell.update_general"
# bl_label = "Update General Parameters"
# bl_description = "Update all General Parameters"
# #bl_options = {'REGISTER', 'UNDO'}
# bl_options = {'REGISTER' }
# def execute(self, context):
# mcell = context.scene.mcell
# ps = mcell.parameter_system
# ps.evaluate_all_gp_expressions ( context )
# return {'FINISHED'}
#class MCELL_OT_update_panel(bpy.types.Operator):
# bl_idname = "mcell.update_panel"
# bl_label = "Update Panel Parameters"
# bl_description = "Update all Panel Parameters"
# #bl_options = {'REGISTER', 'UNDO'}
# bl_options = {'REGISTER' }
# def execute(self, context):
# mcell = context.scene.mcell
# ps = mcell.parameter_system
# dbprint ( "This doesn't do anything at this time" )
# return {'FINISHED'}
#####################################################################
# Operators for printing and debugging
#####################################################################
class MCELL_OT_print_gen_parameters(bpy.types.Operator):
bl_idname = "mcell.print_gen_parameters"
bl_label = "Print General Parameters"
bl_description = "Print All General Parameters"
#bl_options = {'REGISTER', 'UNDO'}
bl_options = {'REGISTER' }
def print_subdict ( self, pname, item, depth ):
if len(item.keys()) <= 0:
print ( " " + (" "*depth) + pname + " = {}" )
else:
for k in item.keys():
if str(type(item[k])) == "<class 'IDPropertyGroup'>":
self.print_subdict ( pname + "." + str(k), item[k], depth+1 )
else:
print ( " " + (" "*depth) + pname + "." + str(k) + " = " + str(item[k]) )
def print_items (self, d, ps):
#self.print_subdict ( 'gp_dict', d, 0 )
fw = ps.max_field_width
for k in d.keys():
output = " " + str(k) + " = "
item = d[k]
if 'name' in item:
output += str(item['name']) + " = "
if 'elist' in item:
elist = pickle.loads(item['elist'].encode('latin1'))
output += str(elist) + " = "
if str(type(item)) == "<class 'IDPropertyGroup'>":
# output += str(item.to_dict())
ditem = item.to_dict()
output += "{ "
for dk in ditem.keys():
ditem_str = str(ditem[dk])
if dk == 'elist':
#ditem_str = str(pickle.loads(ditem[dk].encode('latin1')))
ditem_str = str(ditem[dk]).replace('\n',' ')
if type(ditem[dk]) == type('abc'):
ditem_str = "\"" + ditem_str + "\""
output += str(dk) + ":" + ps.shorten_string(ditem_str,fw) + " " # ", "
if len(output) > 2:
# Strip off the last ", "
output = output[0:-2]
output += " }"
else:
output += str(item)
print ( output )
def execute(self, context):
#global global_params
mcell = context.scene.mcell
ps = mcell.parameter_system
# ps.init_parameter_system()
print ( "=== ID Parameters ===" )
if 'gp_dict' in ps:
self.print_items ( ps['gp_dict'], ps )
print ( " = Ordered Evaluation List =" )
if 'gp_ordered_list' in ps:
ols = ""
for k in ps['gp_ordered_list']:
ols += str(k) + " "
print ( " " + ols )
return {'FINISHED'}
class MCELL_OT_print_par_expressions(bpy.types.Operator):
bl_idname = "mcell.print_par_expressions"
bl_label = "Print Parameter Expressions"
bl_description = "Print All General Parameters as Expressions"
#bl_options = {'REGISTER', 'UNDO'}
bl_options = {'REGISTER' }
def execute(self, context):
#global global_params
mcell = context.scene.mcell
ps = mcell.parameter_system
# ps.init_parameter_system()
for par in ps.general_parameter_list:
par_id = par.par_id
id_par = ps['gp_dict'][par_id]
is_swept = False
if ('sweep_expr' in id_par) and ('sweep_enabled' in id_par):
if id_par['sweep_enabled']:
is_swept = True
icon = ""
if 'status' in id_par:
status = id_par['status']
if 'undef' in status:
icon="x "
elif 'loop' in status:
icon="o "
disp = id_par['name'] + " = "
if is_swept:
disp += id_par['sweep_expr']
disp += " => " + str(ps.runs_in_sweep(id_par['sweep_expr'])) + " runs"
else:
disp += id_par['expr']
if 'value' in id_par:
disp += " = " + str(id_par['value'])
else:
disp += " = ??"
print ( icon + disp )
return {'FINISHED'}
class MCELL_OT_print_pan_parameters(bpy.types.Operator):
bl_idname = "mcell.print_pan_parameters"
bl_label = "Print Panel Parameters"
bl_description = "Print All Panel Parameters"
bl_options = {'REGISTER' }
def execute(self, context):
#global global_params
mcell = context.scene.mcell
ps = mcell.parameter_system
fw = ps.max_field_width
# ps.init_parameter_system()
print ( "=== RNA Panel Parameters ===" )
ppl = ps.panel_parameter_list
for k in ppl.keys():
pp = ppl[k]
# pp is an RNA property, so the ID properties (and keys) might not exist yet ... prefer RNA references
s = ""
s += " " + ps.shorten_string(str(pp.name),fw)
s += " = " + ps.shorten_string(str(pp['user_name']),fw)
s += " = \"" + ps.shorten_string(str(pp.expr),fw) + "\""
elist = pickle.loads(pp.elist.encode('latin1'))
s += ", elist : \"" + ps.shorten_string(str(elist),fw) + "\""
v = "??"
if 'value' in pp:
v = str(pp['value'])
s += " value : " + v + ""
for pk in pp.keys():
if not (pk in ['name', 'user_name', 'expr', 'elist', 'value']):
v = ps.shorten_string(str(pp[pk]),fw)
if type(pp[pk]) == type('abc'):
v = "\"" + v + "\""
s += " " + str(pk) + " : " + v
s += " elistp : \"" + ps.shorten_string(str(pp.elist),fw) + "\""
print ( s.replace('\n',' ') )
return {'FINISHED'}
class MCELL_OT_add_par_list(bpy.types.Operator):
bl_idname = "mcell.add_par_list"
bl_label = "Add List"
bl_description = "Add a short list of parameters"
bl_options = {'REGISTER'}
def make_par_name ( self, n ):
name = None
if n < 26:
name = chr(ord('a')+n)
else:
name = "P_" + str(n)
"""
# These were helpful for testing filtering (by "x" or "y", for example)
if (n % 3) == 0:
name += 'x'
if (n % 3) == 1:
name += 'y'
"""
return name
def execute(self, context):
num_pars_to_gen = context.scene.mcell.parameter_system.num_pars_to_gen
num_back = context.scene.mcell.parameter_system.num_pars_back
make_loop = False
pars = []
for n in range(num_pars_to_gen):
pname = self.make_par_name ( n )
par = {}
par['par_name'] = pname
par['par_description'] = "Description for " + pname
par['par_units'] = "u"
par['par_expression'] = "1"
if n > 0:
par['par_expression'] = "a"
for i in range(max(n-num_back,0),n):
if i % 2:
par['par_expression'] += " - "
else:
par['par_expression'] += " + "
par['par_expression'] += self.make_par_name ( i )
pars.append ( par )
if make_loop:
mid = round(num_pars_to_gen / 2)
dbprint ( " mid = " + str(mid) )
if (mid-1) >= 0:
# There are enough parameters to make a loop
pars[mid-1]['par_expression'] += " + " + pars[mid]['par_name']
dbprint ( "Before call to add_general_parameters_from_list" )
context.scene.mcell.parameter_system.add_general_parameters_from_list ( context, pars )
dbprint ( "After call to add_general_parameters_from_list" )
return {'FINISHED'}
#####################################################################
# Operators for adding and removing parameters
#####################################################################
class MCELL_OT_add_parameter(bpy.types.Operator):
bl_idname = "mcell.add_parameter"
bl_label = "Add Parameter"
bl_description = "Add a new parameter"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
context.scene.mcell.parameter_system.add_general_parameter()
return {'FINISHED'}
class MCELL_OT_remove_parameter(bpy.types.Operator):
bl_idname = "mcell.remove_parameter"
bl_label = "Remove Parameter"
bl_description = "Remove selected parameter"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
status = context.scene.mcell.parameter_system.remove_active_parameter(context)
if status != "":
self.report({'ERROR'}, status)
return {'FINISHED'}
class MCELL_OT_remove_all_pars(bpy.types.Operator):
bl_idname = "mcell.delete_all_pars"
bl_label = "Delete All Pars"
bl_description = "Delete All Parameters (that aren't used)"
bl_options = {'REGISTER'}
def execute(self, context):
status = ""
ps = context.scene.mcell.parameter_system
num_deleted = 1
while ( len(ps.general_parameter_list) > 0 ) and ( num_deleted > 0 ):
# Delete from end since that's most likely to be the fastest
num_before = len(ps.general_parameter_list)
next_to_delete = len(ps.general_parameter_list) - 1
dbprint ( "Deleting parameters starting with " + str(next_to_delete) )
while next_to_delete >= 0:
dbprint ( " Deleting parameter " + str(next_to_delete) )
ps.active_par_index = next_to_delete
ps.remove_active_parameter(context)
next_to_delete += -1
num_deleted = num_before - len(ps.general_parameter_list)
if len(ps.general_parameter_list) > 0:
self.report({'ERROR'}, "Unable to delete all")
return {'FINISHED'}
#######################################################################
# Parameter Drawing Class - Displays each line in the parameter list
#######################################################################
class MCELL_UL_draw_parameter(bpy.types.UIList):
def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index):
mcell = context.scene.mcell
#icon = 'FILE_TICK'
#layout.label(text="parameter goes here", icon=icon)
ps = mcell.parameter_system
par = ps.general_parameter_list[index]
par_id = par.par_id
id_par = ps['gp_dict'][par_id]
is_swept = False
if ('sweep_expr' in id_par) and ('sweep_enabled' in id_par):
if id_par['sweep_enabled']:
is_swept = True
icon = 'CHECKMARK'
if 'status' in id_par:
status = id_par['status']
if 'undef' in status:
icon='ERROR'
elif 'loop' in status:
icon='LOOP_BACK'
disp = id_par['name'] + " = "
if is_swept:
disp += id_par['sweep_expr']
disp += " => " + str(ps.runs_in_sweep(id_par['sweep_expr'])) + " runs"
else:
disp += id_par['expr']
if 'value' in id_par:
disp += " = " + str(id_par['value'])
else:
disp += " = ??"
col = layout.column()
col.label(text=disp, icon=icon)
col = layout.column()
icon = 'BLANK1'
if ('sweep_expr' in id_par):
icon = 'DOT'
if 'sweep_enabled' in id_par:
if id_par['sweep_enabled']:
icon = 'FCURVE'
col.label(text="", icon=icon)
# BLANK1 = no sweep specification
# DOT = sweepable but off
# FCURVE = sweepable and on
# Optional?: SPACE2 = sweepable and on
"""
#######################################################################
# Top Level Panel for the Parameter System (not currently used)
#######################################################################
class MCELL_PT_parameter_system(bpy.types.Panel):
bl_label = "CellBlender - Model Parameters" # This names the collapse control at the top of the panel
bl_space_type = "VIEW_3D"
bl_region_type = "TOOLS"
bl_category = "ID Parameters" # This is the tab name on the side
@classmethod
def poll(cls, context):
return (context.scene is not None)
def draw(self, context):
mcell = context.scene.mcell
ps = mcell.parameter_system
ps.draw_panel ( context, self.layout )
"""
#######################################################################
# A Panel Parameter Data object exists for each panel parameter
# They are stored in the panel_parameter_list CollectionProperty
# within the ParameterSystemPropertyGroup
#######################################################################
### External callback needed to match the "update=" syntax of Blender.
### This just calls the function with the same name from within the class
##@profile('PanelParameterDataCallBack.update_panel_expression') # profiling callbacks can be problematic
def update_panel_expr ( self, context ):
self.update_panel_expression ( context )
class PanelParameterData ( bpy.types.PropertyGroup ):
""" Holds the actual properties needed for a panel parameter """
# There are only a few properties for items in this class ... most of the rest are in the parameter system itself.
#self.name is a Blender defined key that should be set to the unique_static_name (new_pid_key) on creation (typically "p#")
expr: StringProperty(name="Expression", default="0", description="Expression to be evaluated for this parameter", update=update_panel_expr)
elist: StringProperty(name="elist", default="(lp0\n.", description="Pickled Expression List") # This ("(lp0\n.") is a pickled empty list: pickle.dumps([],protocol=0).decode('latin1')
show_help: BoolProperty ( default=False, description="Toggle more information about this parameter" )
# The following PanelParameterData (PPD) ID properties are added dynamically (for performance reasons):
# PPD['user_name']
# PPD['user_type']
# PPD['user_units']
# PPD['user_descr']
# PPD['expr']
# PPD['value']
# PPD['valid']
@profile('PanelParameterData.update_panel_expression')
def update_panel_expression (self, context, gl=None):
mcell = context.scene.mcell
parameter_system = mcell.parameter_system
dbprint ( "Update the panel expression for " + self.name + " with keys = " + str(self.keys()) )
dbprint ( "Updating " + str(parameter_system.panel_parameter_list[self.name]) )
parameter_system.init_parameter_system() # Do this in case it isn't already initialized
old_parameterized_expr = pickle.loads(self.elist.encode('latin1'))
if True or (len(parameter_system['gp_dict']) > 0):
dbprint ("Parameter string changed to " + self.expr, 10 )
parameterized_expr = parameter_system.parse_param_expr ( self.expr )
self.elist = pickle.dumps(parameterized_expr,protocol=0).decode('latin1')
dbprint ("Parsed expression = " + str(parameterized_expr), 10 )
if parameterized_expr is None:
self['valid'] = False
print ( "Error: expression is None" )
return
if None in parameterized_expr:
self['valid'] = False
print ( "Error: None in " + str(parameterized_expr) )
return
# Check to see if any dependencies have changed
old_who_i_depend_on = set ( [ 'g'+str(w) for w in old_parameterized_expr if type(w) == type(1) ] )
new_who_i_depend_on = set ( [ 'g'+str(w) for w in parameterized_expr if type(w) == type(1) ] )
if old_who_i_depend_on != new_who_i_depend_on:
# Update the "what_depends_on_me" fields of the general parameters based on the changes
dbprint ( "Old: " + str(old_who_i_depend_on) )
dbprint ( "New: " + str(new_who_i_depend_on) )
remove_me_from = old_who_i_depend_on - new_who_i_depend_on
add_me_to = new_who_i_depend_on - old_who_i_depend_on
if len(remove_me_from) > 0:
dbprint ( "Remove " + self.name + " from what_depends_on_me list for: " + str(remove_me_from), 10 )
if len(add_me_to) > 0:
dbprint ( "Add " + self.name + " to what_depends_on_me list for: " + str(add_me_to), 10 )
for k in remove_me_from:
dbprint ( " Removing ( " + self.name + " ) from " + str(k), 10 )
parameter_system['gp_dict'][k]['what_depends_on_me'].pop ( self.name )
for k in add_me_to:
parameter_system['gp_dict'][k]['what_depends_on_me'][self.name] = True
# Recompute the value
# Start by creating a dictionary of values from all general parameters if not passed in:
valid = True
if gl is None:
gl = {}
parameter_system.update_dependency_ordered_name_list() # This call is needed the first time
valid = parameter_system.build_eval_dict ( gl )
if not valid:
print ( "Error: \"" + str(parameterized_expr) + "\" cannot be evaluated (1)" )
self['valid'] = False
self['value'] = 0.0
else:
py_expr = parameter_system.build_expression ( parameterized_expr, as_python=True )
if (py_expr != None) and (len(py_expr.strip()) > 0):
self['valid'] = True
try:
self['value'] = float(eval(py_expr,globals(),gl))
except:
print ( "Error: \"" + str(py_expr) + "\" cannot be evaluated (2)" )
print ( " Globals (gl) = " + str(gl) )
self['valid'] = False
else:
# Empty parameters are intended to be interpreted as defaults by the code that uses them
# print ( "Error: \"" + str(py_expr) + "\" cannot be evaluated (3)" )
self['valid'] = False
self['value'] = 0.0
# It's not clear if this should be integerized here or only on display. Retain full value for now.
#if ('user_type' in self) and (self['user_type'] == 'i'):
# self['value'] = int(self['value'])
#######################################################################
# A Panel Parameter Reference is just an ID that is stored wherever
# a panel parameter is defined. That ID is the name index into the
# the panel_parameter_list CollectionProperty within the top level
# ParameterSystemPropertyGroup. The panel_parameter_list contains
# the PanelParameterData items keyed by this ID.
#######################################################################
class Parameter_Reference ( bpy.types.PropertyGroup ):
""" Simple class to reference a panel parameter - used throughout the application """
# There is ONLY ONE property in this class ... don't add any more without careful thought
unique_static_name: StringProperty ( name="unique_name", default="" )
# __init__ does not appear to be called
#def __init__ ( self ):
# print ( "Parameter_Reference.__init__ called" )
# __del__ appears to be called all the time ... even when nothing is being added or removed
#def __del__ ( self ):
# print ( "Parameter_Reference.__del__ called" )
#######################################################################
# This is the function that actually creates the data associated with
# a panel parameter.
# The "user_int" parameter will probably change to "user_type" when we
# add string parameters giving: 'f', 'i', 's'.
#######################################################################
@profile('Parameter_Reference.init_ref')
def init_ref ( self, parameter_system, user_name=None, user_expr="0", user_descr="Panel Parameter", user_units="", user_int=False ):
parameter_system.init_parameter_system() # Do this in case it isn't already initialized
if user_name == None:
user_name = "none"
t = 'f'
if user_int:
t = 'i'
# Check to see if it already exists ...
new_pid_key = None
if len(self.unique_static_name) <= 0:
# This parameter reference needs a unique name, so create it
new_pid = parameter_system.allocate_available_pid()
new_pid_key = 'p'+str(new_pid)
else:
# This parameter reference already has a unique name, so use it
new_pid_key = self.unique_static_name
self.unique_static_name = new_pid_key
# Add special information for panel parameters:
ppl = parameter_system.panel_parameter_list
# Check to see if this parameter is already in the RNA panel parameters list
new_rna_par = None
i = ppl.find(self.unique_static_name)
if i < 0:
# There is no RNA parameter with this ID so add it
new_rna_par = ppl.add()
else:
# There already is an RNA parameter with this ID so use it
new_rna_par = ppl[i]
# Now set everything as requested by the function call (some are RNA properties, others are ID properties)
new_rna_par.name = new_pid_key
new_rna_par.expr = user_expr # This should trigger an evaluation of the expression into an expression list
new_rna_par['user_name'] = user_name
new_rna_par['user_type'] = t
new_rna_par['user_units'] = user_units
new_rna_par['user_descr'] = user_descr
#new_rna_par['expr'] = user_expr
if (len(user_expr.strip()) > 0):
new_rna_par['value'] = eval(user_expr)
new_rna_par['valid'] = True
else:
new_rna_par['value'] = 0.0
new_rna_par['valid'] = True
dbprint ( 'Finished init_ref for ' + str(user_name) + ' = ' + str(new_pid_key) )
#bpy.ops.mcell.print_gen_parameters()
#bpy.ops.mcell.print_pan_parameters()
dbprint ( "==============================================================================================" )
#######################################################################
# This is the function that deletes the data associated with a panel
# parameter. This was not needed prior to ID properties because the
# RNA properties (supposedly) cleaned up after themselves. This is
# not the case with ID parameters, and this data must be removed.
# Nothing depends on panel parameters (they are leaves in the tree)
# so no dependencies need to be checked.
# However, the general parameters DO keep track of which panel
# parameters depend on them. This relationship is stored in their
# "what_depends_on_me" list. So removing a panel parameter requires
# clearing that panel parameter reference from each general parameter
# that is used by the panel parameter. This function does that.
#######################################################################
def clear_ref ( self, parameter_system ):
dbprint ( "clear_ref for " + self.unique_static_name )
ppl = parameter_system.panel_parameter_list
if 'gp_dict' in parameter_system:
gpd = parameter_system['gp_dict']
rna_par = ppl[self.unique_static_name]
# Start by removing this reference from the what_depends_on_me of any general parameters that it depends on
if 'elist' in rna_par:
elist = pickle.loads(rna_par['elist'].encode('latin1'))
for term in elist:
if type(term) == int:
# This refers to a general parameter, so remove this panel parameter from its "what_depends_on_me" list
gp = gpd['g'+str(term)]
if self.unique_static_name in gp['what_depends_on_me']:
gp['what_depends_on_me'].pop(self.unique_static_name)
# Now remove this parameter from the panel parameters list
i = ppl.find(self.unique_static_name)
if i >= 0:
ppl.remove ( i )
#######################################################################
# These are the general access functions used to set and get the
# parameter's expression and value. They take an optional plist
# argument that should be the panel parameter list. This is done
# to keep this function from looking it up when the list is already
# available in the calling function.
# The available access functions are:
# get_param - Returns a PanelParameterData item for the parameter
# set_expr - Sets the expression for the parameter
# get_expr - Gets the expression for the parameter
# get_value - Returns a numeric value for the parameter
# get_as_string_or_value - Returns a string which might be
# either a string expression or a
# string representation of a number
#######################################################################
@profile('Parameter_Reference.get_param')
def get_param ( self, plist=None ):
#print ( "get_param called on Parameter_Reference " + str(self.unique_static_name) )
if plist == None:
# No list specified, so get it from the top (it would be better to NOT have to do this!!!)
mcell = bpy.context.scene.mcell
plist = mcell.parameter_system.panel_parameter_list # <<<< This appears to be empty after rebuilding parameters from a data model
# print ( "Inside get_param, len(ppl) = " + str(len(plist)) )
return plist[self.unique_static_name]
@profile('Parameter_Reference.set_expr')
def set_expr ( self, expr, plist=None ):
##print ( "###############\n set_expr for " + self.unique_static_name + " Error!!!\n###############\n" )
rna_par = self.get_param(plist)
rna_par.expr = expr
return
@profile('Parameter_Reference.get_expr')
def get_expr ( self, plist=None ):
##print ( "###############\n get_expr for " + self.unique_static_name + "\n###############\n" )
rna_par = self.get_param(plist)
##print ( "###############\n returning " + str(rna_par.expr) + "\n###############\n" )
return rna_par.expr
@profile('Parameter_Reference.get_value')
def get_value ( self, plist=None ):
#print ( "###############\n get_value for " + self.unique_static_name + " Error!!!\n###############\n" )
par = self.get_param()
#print ( "Par.keys() = " + str(par.keys()) )
#print ( "Par.items() = " + str(par.items()) )
user_type = 'f'
user_value = 0.0
if 'user_type' in par:
user_type = par['user_type']
if 'value' in par:
#print ( "Par[value] = " + str(par['value']) )
if True or par['valid']: # Force this to be valid for now
if user_type == 'f':
user_value = float(par['value'])
else:
user_value = int(par['value'])
else:
user_value = None
user_type = ''
#print ( "Returning " + str(user_value) )
return user_value
@profile('Parameter_Reference.get_as_string_or_value')
def get_as_string_or_value ( self, plist=None, as_expr=False ):
'''Return a string represeting the numeric value or a non-blank expression'''
rna_par = self.get_param(plist)
if as_expr and (len(rna_par.expr.strip()) > 0):
return self.get_expr(plist)
else:
isint = False
s = None
if ('user_type' in rna_par) and (rna_par['user_type'] == 'i'):
s = "%g" % (int(self.get_value(plist)))
else:
s = "%g" % (self.get_value(plist))
return s
#######################################################################
# This function draws a panel parameter in a panel "layout".
# This is the function that shows help, labels, double rows, etc.
#######################################################################
@profile('Parameter_Reference.draw')
def draw ( self, layout, parameter_system, label=None ):
row = layout.row()
rna_par = parameter_system.panel_parameter_list[self.unique_static_name]
val = "??"
icon = 'ERROR'
if 'value' in rna_par:
if not (rna_par['value'] is None):
if rna_par['user_type'] == 'i':
val = str(int(rna_par['value']))
else:
val = str(rna_par['value'])
icon = 'NONE'
if 'valid' in rna_par:
if not rna_par['valid']: