-
Notifications
You must be signed in to change notification settings - Fork 38
/
modeler.js
1298 lines (1073 loc) · 36.3 KB
/
modeler.js
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
/*global $ modeler:true, require, d3, benchmark, molecule_container */
/*jslint onevar: true devel:true eqnull: true */
// modeler.js
//
var md2d = require('/md2d'),
arrays = require('arrays'),
engine;
modeler = {};
modeler.VERSION = '0.2.0';
modeler.model = function(initialProperties) {
var model = {},
elements = initialProperties.elements || [{id: 0, mass: 39.95, epsilon: -0.1, sigma: 0.34}],
dispatch = d3.dispatch("tick", "play", "stop", "reset", "stepForward", "stepBack", "seek", "addAtom"),
temperature_control,
chargeShading, showVDWLines,VDWLinesRatio,
showClock,
lennard_jones_forces, coulomb_forces,
gravitationalField = false,
viewRefreshInterval = 50,
stopped = true,
tick_history_list = [],
tick_history_list_index = 0,
tick_counter = 0,
new_step = false,
pressure, pressures = [0],
modelSampleRate = 60,
lastSampleTime,
sampleTimes = [],
// N.B. this is the thermostat (temperature control) setting
temperature,
// current model time, in fs
time,
// potential energy
pe,
// kinetic energy
ke,
modelOutputState,
model_listener,
width = initialProperties.width,
height = initialProperties.height,
//
// A two dimensional array consisting of arrays of atom property values
//
atoms,
//
// A two dimensional array consisting of atom index numbers and atom
// property values - in effect transposed from the atom property arrays.
//
results,
//
// A two dimensional array consisting of radial bond index numbers, radial bond
// property, and the postions of the two bonded atoms.
radialBondResults,
// list of obstacles
obstacles,
// Radial Bonds
radialBonds,
// VDW Pairs
vdwPairs,
viscosity,
// The index of the "spring force" used to implement dragging of atoms in a running model
liveDragSpringForceIndex,
// Cached value of the 'friction' property of the atom being dragged in a running model
liveDragSavedFriction,
default_obstacle_properties = {
vx: 0,
vy: 0,
density: Infinity,
color: [128, 128, 128]
},
listeners = {},
properties = {
temperature : 300,
modelSampleRate : 60,
coulomb_forces : true,
lennard_jones_forces : true,
temperature_control : true,
gravitationalField : false,
chargeShading : false,
showVDWLines : false,
showClock : true,
viewRefreshInterval : 50,
VDWLinesRatio : 1.99,
viscosity : 0,
/**
These functions are optional setters that will be called *instead* of simply setting
a value when 'model.set({property: value})' is called, and are currently needed if you
want to pass a value through to the engine. The function names are automatically
determined from the property name. If you define one of these custom functions, you
must remember to also set the property explicitly (if appropriate) as this won't be
done automatically
*/
set_temperature: function(t) {
this.temperature = t;
if (engine) {
engine.setTargetTemperature(t);
}
},
set_temperature_control: function(tc) {
this.temperature_control = tc;
if (engine) {
engine.useThermostat(tc);
}
},
set_coulomb_forces: function(cf) {
this.coulomb_forces = cf;
if (engine) {
engine.useCoulombInteraction(cf);
}
},
set_epsilon: function(e) {
console.log("set_epsilon: This method is temporarily deprecated");
},
set_sigma: function(s) {
console.log("set_sigma: This method is temporarily deprecated");
},
set_gravitationalField: function(gf) {
this.gravitationalField = gf;
if (engine) {
engine.setGravitationalField(gf);
}
},
set_viewRefreshInterval: function(vri) {
this.viewRefreshInterval = vri;
if (engine) {
engine.setIntegrationDuration(vri);
}
},
set_viscosity: function(v) {
this.viscosity = v;
if (engine) {
engine.setViscosity(v);
}
}
},
// TODO: notSafari and hasTypedArrays belong in the arrays module
// Check for Safari. Typed arrays are faster almost everywhere
// ... except Safari.
notSafari = (function() {
var safarimatch = / AppleWebKit\/([0123456789.+]+) \(KHTML, like Gecko\) Version\/([0123456789.]+) (Safari)\/([0123456789.]+)/,
match = navigator.userAgent.match(safarimatch);
return (match && match[3]) ? false: true;
}()),
hasTypedArrays = (function() {
try {
new Float32Array();
}
catch(e) {
return false;
}
return true;
}()),
arrayType = (hasTypedArrays && notSafari) ? 'Float32Array' : 'regular';
function setupIndices() {
var prop,
i,
offset,
shortName;
//
// Indexes into the atoms array for the individual node property arrays
//
model.INDICES = {};
model.ATOM_PROPERTY_LIST = [];
model.ATOM_PROPERTY_SHORT_NAMES = {};
// Copy property indices and names from md2d
offset = 0;
for (i = 0; i < md2d.ATOM_PROPERTY_LIST.length; i++) {
prop = md2d.ATOM_PROPERTY_LIST[i];
model.ATOM_PROPERTY_LIST[i] = prop;
model.INDICES[prop] = md2d.ATOM_INDICES[prop] + offset;
model.ATOM_PROPERTY_SHORT_NAMES[prop] = md2d.ATOM_PROPERTY_SHORT_NAMES[prop];
}
model.NON_ENGINE_PROPERTY_LIST = [
"VISIBLE",
"MARKED",
"DRAGGABLE"
];
model.NON_ENGINE_PROPERTY_SHORT_NAMES = {
VISIBLE: "visible",
MARKED: "marked",
DRAGGABLE: "draggable"
};
model.NON_ENGINE_DEFAULT_VALUES = {
VISIBLE: 1,
MARKED: 0,
DRAGGABLE: 0
};
// Add non-engine properties to the end of the list of property indices and names
offset = model.ATOM_PROPERTY_LIST.length;
for (i = 0; i < model.NON_ENGINE_PROPERTY_LIST.length; i++) {
prop = model.NON_ENGINE_PROPERTY_LIST[i];
model.ATOM_PROPERTY_LIST.push(prop);
model.INDICES[prop] = i + offset;
model.ATOM_PROPERTY_SHORT_NAMES[prop] = model.NON_ENGINE_PROPERTY_SHORT_NAMES[prop];
}
// Inverse of ATOM_PROPERTY_SHORT_NAMES...
model.ATOM_PROPERTY_LONG_NAMES = {};
for (prop in model.ATOM_PROPERTY_SHORT_NAMES) {
if (model.ATOM_PROPERTY_SHORT_NAMES.hasOwnProperty(prop)) {
shortName = model.ATOM_PROPERTY_SHORT_NAMES[prop];
model.ATOM_PROPERTY_LONG_NAMES[shortName] = prop;
}
}
// TODO. probably save everything *except* a list of "non-saveable properties"
model.SAVEABLE_PROPERTIES = [
"X",
"Y",
"VX",
"VY",
"CHARGE",
"ELEMENT",
"PINNED",
"FRICTION",
"VISIBLE",
"MARKED",
"DRAGGABLE"
];
model.OBSTACLE_INDICES = {
X : md2d.OBSTACLE_INDICES.X,
Y : md2d.OBSTACLE_INDICES.Y,
WIDTH : md2d.OBSTACLE_INDICES.WIDTH,
HEIGHT : md2d.OBSTACLE_INDICES.HEIGHT,
COLOR_R : md2d.OBSTACLE_INDICES.COLOR_R,
COLOR_G : md2d.OBSTACLE_INDICES.COLOR_G,
COLOR_B : md2d.OBSTACLE_INDICES.COLOR_B,
VISIBLE : md2d.OBSTACLE_INDICES.VISIBLE
};
model.RADIAL_INDICES = {
ATOM1 : md2d.RADIAL_INDICES.ATOM1,
ATOM2 : md2d.RADIAL_INDICES.ATOM2,
LENGTH : md2d.RADIAL_INDICES.LENGTH,
STRENGTH : md2d.RADIAL_INDICES.STRENGTH
};
model.VDW_INDICES = md2d.VDW_INDICES;
}
function notifyPropertyListeners(listeners) {
$.unique(listeners);
for (var i=0, ii=listeners.length; i<ii; i++){
listeners[i]();
}
}
function notifyPropertyListenersOfEvents(events) {
var evt,
evts,
waitingToBeNotified = [],
i, ii;
if (typeof events === "string") {
evts = [events];
} else {
evts = events;
}
for (i=0, ii=evts.length; i<ii; i++){
evt = evts[i];
if (listeners[evt]) {
waitingToBeNotified = waitingToBeNotified.concat(listeners[evt]);
}
}
if (listeners["all"]){ // listeners that want to be notified on any change
waitingToBeNotified = waitingToBeNotified.concat(listeners["all"]);
}
notifyPropertyListeners(waitingToBeNotified);
}
function average_speed() {
var i, s = 0, n = model.get_num_atoms();
i = -1; while (++i < n) { s += engine.speed[i]; }
return s/n;
}
function tick(elapsedTime, dontDispatchTickEvent) {
var t,
sampleTime,
doIntegration;
if (stopped) {
doIntegration = true;
} else {
t = Date.now();
if (lastSampleTime) {
sampleTime = t - lastSampleTime;
if (1000/sampleTime < modelSampleRate) {
doIntegration = true;
lastSampleTime = t;
sampleTimes.push(sampleTime);
sampleTimes.splice(0, sampleTimes.length - 128);
} else {
doIntegration = false;
}
} else {
lastSampleTime = t;
doIntegration = true;
}
}
if (doIntegration) {
engine.integrate();
readModelState();
pressures.push(pressure);
pressures.splice(0, pressures.length - 16); // limit the pressures array to the most recent 16 entries
tick_history_list_push();
if (!dontDispatchTickEvent) {
dispatch.tick();
}
}
return stopped;
}
function tick_history_list_is_empty() {
return tick_history_list_index === 0;
}
function tick_history_list_push() {
var i,
newAtoms = [],
n = atoms.length;
i = -1; while (++i < n) {
newAtoms[i] = arrays.clone(atoms[i]);
}
tick_history_list.length = tick_history_list_index;
tick_history_list_index++;
tick_counter++;
new_step = true;
tick_history_list.push({
atoms: newAtoms,
pressure: modelOutputState.pressure,
pe: modelOutputState.PE,
ke: modelOutputState.KE,
time: modelOutputState.time
});
if (tick_history_list_index > 1000) {
tick_history_list.splice(1,1);
tick_history_list_index = 1000;
}
}
function restoreFirstStateinTickHistory() {
tick_history_list_index = 0;
tick_counter = 0;
tick_history_list.length = 1;
tick_history_list_extract(tick_history_list_index);
}
function reset_tick_history_list() {
tick_history_list = [];
tick_history_list_index = 0;
tick_counter = 0;
}
function tick_history_list_reset_to_ptr() {
tick_history_list.length = tick_history_list_index + 1;
}
function tick_history_list_extract(index) {
var i, n=atoms.length;
if (index < 0) {
throw new Error("modeler: request for tick_history_list[" + index + "]");
}
if (index >= tick_history_list.length) {
throw new Error("modeler: request for tick_history_list[" + index + "], tick_history_list.length=" + tick_history_list.length);
}
i = -1; while(++i < n) {
arrays.copy(tick_history_list[index].atoms[i], atoms[i]);
}
ke = tick_history_list[index].ke;
time = tick_history_list[index].time;
engine.setTime(time);
}
function container_pressure() {
return pressures.reduce(function(j,k) { return j+k; })/pressures.length;
}
function average_rate() {
var i, ave, s = 0, n = sampleTimes.length;
i = -1; while (++i < n) { s += sampleTimes[i]; }
ave = s/n;
return (ave ? 1/ave*1000: 0);
}
function set_temperature(t) {
temperature = t;
engine.setTargetTemperature(t);
}
function set_properties(hash) {
var property, propsChanged = [];
for (property in hash) {
if (hash.hasOwnProperty(property) && hash[property] !== undefined && hash[property] !== null) {
// look for set method first, otherwise just set the property
if (properties["set_"+property]) {
properties["set_"+property](hash[property]);
// why was the property not set if the default value property is false ??
// } else if (properties[property]) {
} else {
properties[property] = hash[property];
}
propsChanged.push(property);
}
}
notifyPropertyListenersOfEvents(propsChanged);
}
/**
Use this method to refresh the results array and macrostate variables (KE, PE, temperature)
whenever an engine integration occurs or the model state is otherwise changed.
*/
function readModelState() {
var i,
len,
j,
n;
engine.computeOutputState(modelOutputState);
extendResultsArray();
// Transpose 'atoms' array into 'results' for easier consumption by view code
for (j = 0, len = atoms.length; j < len; j++) {
for (i = 0, n = model.get_num_atoms(); i < n; i++) {
results[i][j+1] = atoms[j][i];
}
}
pressure = modelOutputState.pressure;
pe = modelOutputState.PE;
ke = modelOutputState.KE;
time = modelOutputState.time;
}
/**
Ensure that the 'results' array of arrays is defined and contains one typed array per atom
for containing the atom properties.
*/
function extendResultsArray() {
var i,
n;
if (!results) results = [];
for (i = results.length, n = model.get_num_atoms(); i < n; i++) {
if (!results[i]) {
results[i] = arrays.create(1 + model.ATOM_PROPERTY_LIST.length, 0, arrayType);
results[i][0] = i;
}
}
}
function setToDefaultValue(prop) {
for (var i = 0; i < model.get_num_atoms(); i++) {
atoms[model.INDICES[prop]][i] = model.NON_ENGINE_DEFAULT_VALUES[prop];
}
}
function setFromSerializedArray(prop, serializedArray) {
for (var i = 0; i < model.get_num_atoms(); i++) {
atoms[model.INDICES[prop]][i] = serializedArray[i];
}
}
function initializeNonEngineProperties(serializedAtomProps) {
var prop,
i;
for (i = 0; i < model.NON_ENGINE_PROPERTY_LIST.length; i++) {
prop = model.NON_ENGINE_PROPERTY_LIST[i];
atoms[model.INDICES[prop]] = arrays.create(model.get_num_atoms(), 0, arrayType);
if (serializedAtomProps[prop]) {
setFromSerializedArray(prop, serializedAtomProps[prop]);
}
else {
setToDefaultValue(prop);
}
}
}
/**
Each entry in engine.atoms is a reference to a typed array. When the engine needs to create
a larger typed array, it must create a new object. Therefore, this function exists to copy
over any references to newly created typed arrays from engine.atoms to our atoms array.
*/
function copyEngineAtomReferences() {
var prop;
// Note that the indirection below allows us to correctly account for arbitrary differences
// between the ordering of indices in model and the ordering in the engine.
for (var i = 0; i < md2d.ATOM_PROPERTY_LIST.length; i++) {
prop = md2d.ATOM_PROPERTY_LIST[i];
atoms[ model.INDICES[prop] ] = engine.atoms[ md2d.ATOM_INDICES[prop] ];
}
}
function copyTypedArray(arr) {
var copy = [];
for (var i=0,ii=arr.length; i<ii; i++){
copy[i] = arr[i];
}
return copy;
}
function serializeAtoms() {
var serializedData = {},
prop,
array,
i,
len;
for (i=0, len = model.SAVEABLE_PROPERTIES.length; i < len; i++) {
prop = model.SAVEABLE_PROPERTIES[i];
array = atoms[model.INDICES[prop]];
serializedData[prop] = array.slice ? array.slice() : copyTypedArray(array);
}
return serializedData;
}
// ------------------------------
// finish setting up the model
// ------------------------------
setupIndices();
// Friction parameter temporarily applied to the live-dragged atom.
model.LIVE_DRAG_FRICTION = 10;
// who is listening to model tick completions
model_listener = initialProperties.model_listener;
// set the rest of the regular properties
set_properties(initialProperties);
// ------------------------------------------------------------
//
// Public functions
//
// ------------------------------------------------------------
model.getStats = function() {
return {
speed : average_speed(),
ke : ke,
temperature : temperature,
pressure : container_pressure(),
current_step: tick_counter,
steps : tick_history_list.length-1
};
};
// A convenience for interactively getting energy averages
model.getStatsHistory = function() {
var i, len,
tick,
ret = [];
ret.push("time (fs)\ttotal PE (eV)\ttotal KE (eV)\ttotal energy (eV)");
for (i = 0, len = tick_history_list.length; i < len; i++) {
tick = tick_history_list[i];
ret.push(tick.time + "\t" + tick.pe + "\t" + tick.ke + "\t" + (tick.pe+tick.ke));
}
return ret.join('\n');
};
/**
Current seek position
*/
model.stepCounter = function() {
return tick_counter;
};
/** Total number of ticks that have been run & are stored, regardless of seek
position
*/
model.steps = function() {
return tick_history_list.length - 1;
};
model.isNewStep = function() {
return new_step;
};
model.seek = function(location) {
if (!arguments.length) { location = 0; }
stopped = true;
new_step = false;
tick_history_list_index = location;
tick_counter = location;
tick_history_list_extract(tick_history_list_index);
dispatch.seek();
if (model_listener) { model_listener(); }
return tick_counter;
};
model.stepBack = function(num) {
if (!arguments.length) { num = 1; }
var i = -1;
stopped = true;
new_step = false;
while(++i < num) {
if (tick_history_list_index > 1) {
tick_history_list_index--;
tick_counter--;
tick_history_list_extract(tick_history_list_index-1);
if (model_listener) { model_listener(); }
}
}
return tick_counter;
};
model.stepForward = function(num) {
if (!arguments.length) { num = 1; }
var i = -1;
stopped = true;
while(++i < num) {
if (tick_history_list_index < tick_history_list.length) {
tick_history_list_extract(tick_history_list_index);
tick_history_list_index++;
tick_counter++;
if (model_listener) { model_listener(); }
} else {
tick();
}
}
return tick_counter;
};
/**
Creates a new md2d model with a new set of atoms and leaves it in 'engine'
@config: either the number of atoms (for a random setup) or
a hash specifying the x,y,vx,vy properties of the atoms
When random setup is used, the option 'relax' determines whether the model is requested to
relax to a steady-state temperature (and in effect gets thermalized). If false, the atoms are
left in whatever grid the engine's initialization leaves them in.
*/
model.createNewAtoms = function(config) {
var elemsArray, element, i, ii, num;
if (typeof config === 'number') {
num = config;
} else if (config.num != null) {
num = config.num;
} else if (config.X) {
num = config.X.length;
}
// convert from easily-readble json format to simplified array format
elemsArray = [];
for (i=0, ii=elements.length; i<ii; i++){
element = elements[i];
elemsArray[element.id] = [element.mass, element.epsilon, element.sigma];
}
// get a fresh model
engine = md2d.createEngine();
engine.setSize([width,height]);
engine.setElements(elemsArray);
engine.createAtoms({
num: num
});
// Initialize properties
temperature_control = properties.temperature_control;
temperature = properties.temperature;
modelSampleRate = properties.modelSampleRate,
chargeShading = properties.chargeShading;
showVDWLines = properties.showVDWLines;
VDWLinesRatio = properties.VDWLinesRatio;
showClock = properties.showClock;
viewRefreshInterval = properties.viewRefreshInterval;
viscosity = properties.viscosity;
gravitationalField = properties.gravitationalField;
viewRefreshInterval = properties.viewRefreshInterval;
engine.useLennardJonesInteraction(properties.lennard_jones_forces);
engine.useCoulombInteraction(properties.coulomb_forces);
engine.useThermostat(temperature_control);
engine.setViscosity(viscosity);
engine.setGravitationalField(gravitationalField);
engine.setIntegrationDuration(viewRefreshInterval);
engine.setTargetTemperature(temperature);
if (config.X && config.Y) {
engine.initializeAtomsFromProperties(config);
} else {
engine.initializeAtomsRandomly({
temperature: temperature
});
if (config.relax) engine.relaxToTemperature();
}
atoms = [];
copyEngineAtomReferences(engine.atoms);
initializeNonEngineProperties(config);
window.state = modelOutputState = {};
readModelState();
// tick history stuff
reset_tick_history_list();
tick_history_list_push();
tick_counter = 0;
new_step = true;
// Listeners should consider resetting the atoms a 'reset' event
dispatch.reset();
// return model, for chaining (if used)
return model;
};
model.createRadialBonds = function(_radialBonds) {
engine.initializeRadialBonds(_radialBonds);
radialBonds = engine.radialBonds;
radialBondResults = engine.radialBondResults;
readModelState();
return model;
};
model.createVdwPairs = function(_atoms) {
engine.createVdwPairsArray(_atoms);
vdwPairs = engine.vdwPairs;
readModelState();
return model;
};
model.createObstacles = function(_obstacles) {
var numObstacles = _obstacles.x.length,
i, prop;
// ensure that every property either has a value or the default value
for (i = 0; i < numObstacles; i++) {
for (prop in default_obstacle_properties) {
if (!default_obstacle_properties.hasOwnProperty(prop)) continue;
if (!_obstacles[prop]) {
_obstacles[prop] = [];
}
if (typeof _obstacles[prop][i] === "undefined") {
_obstacles[prop][i] = default_obstacle_properties[prop];
}
}
}
engine.initializeObstacles(_obstacles);
obstacles = engine.obstacles;
return model;
};
// The next four functions assume we're are doing this for
// all the atoms will need to be changed when different atoms
// can have different LJ sigma values
/** Accepts an epsilon value in eV.
Example value for argon is 0.013 (positive)
*/
model.setEpsilon = function(e) {
engine.setLJEpsilon(e);
};
/** Accepts a sigma value in nm
Example value for argon is 3.4 nm
*/
model.setSigma = function(s) {
engine.setLJSigma(s);
};
model.getEpsilon = function() {
return engine.getLJEpsilon();
};
model.getSigma = function() {
return engine.getLJSigma();
};
model.getLJCalculator = function() {
return engine.getLJCalculator();
};
model.reset = function() {
model.resetTime();
restoreFirstStateinTickHistory();
dispatch.reset();
};
model.resetTime = function() {
engine.setTime(0);
};
model.getTime = function() {
return modelOutputState ? modelOutputState.time : undefined;
};
model.getTotalMass = function() {
return engine.getTotalMass();
};
/**
Attempts to add an 0-velocity atom to a random location. Returns false if after 10 tries it
can't find a location. (Intended to be exposed as a script API method.)
Optionally allows specifying the element (default is to randomly select from all elements) and
charge (default is neutral).
*/
model.addRandomAtom = function(el, charge) {
if (el == null) el = Math.floor( Math.random() * elements.length );
if (charge == null) charge = 0;
var size = model.size(),
radius = engine.getRadiusOfElement(el),
x,
y,
loc,
numTries = 0,
// try at most ten times.
maxTries = 10;
do {
x = Math.random() * size[0] - 2*radius;
y = Math.random() * size[1] - 2*radius;
// findMinimimuPELocation will return false if minimization doesn't converge, in which case
// try again from a different x, y
loc = engine.findMinimumPELocation(el, x, y, 0, 0, charge);
if (loc && model.addAtom(el, loc[0], loc[1], 0, 0, charge, 0, 0)) return true;
} while (++numTries < maxTries);
return false;
},
/**
Adds a new atom with element 'el', charge 'charge', and velocity '[vx, vy]' to the model
at position [x, y]. (Intended to be exposed as a script API method.)
Adjusts (x,y) if needed so that the whole atom is within the walls of the container.
Returns false and does not add the atom if the potential energy change of adding an *uncharged*
atom of the specified element to the specified location would be positive (i.e, if the atom
intrudes into the repulsive region of another atom.)
Otherwise, returns true.
*/
model.addAtom = function(el, x, y, vx, vy, charge, friction, pinned, visible, draggable) {
var size = model.size(),
radius = engine.getRadiusOfElement(el),
newLength,
i;
if (visible == null) visible = model.NON_ENGINE_DEFAULT_VALUES.VISIBLE;
if (draggable == null) draggable = model.NON_ENGINE_DEFAULT_VALUES.DRAGGABLE;
// As a convenience to script authors, bump the atom within bounds
if (x < radius) x = radius;
if (x > size[0]-radius) x = size[0]-radius;
if (y < radius) y = radius;
if (y > size[1]-radius) y = size[1]-radius;
// check the potential energy change caused by adding an *uncharged* atom at (x,y)
if (engine.canPlaceAtom(el, x, y)) {
i = engine.addAtom(el, x, y, vx, vy, charge, friction, pinned);
copyEngineAtomReferences();
// Extend the atoms arrays which the engine doesn't know about. This may seem duplicative,
// or something we could ask the engine to do on our behalf, but it may make more sense when
// you realize this is a temporary step until we modify the code further in order to maintain
// the 'visible', 'draggable' propeties *only* in what is now being called the 'results' array
newLength = atoms[model.INDICES.ELEMENT].length;
if (atoms[model.INDICES.VISIBLE].length < newLength) {
atoms[model.INDICES.VISIBLE] = arrays.extend(atoms[model.INDICES.VISIBLE], newLength);
atoms[model.INDICES.DRAGGABLE] = arrays.extend(atoms[model.INDICES.DRAGGABLE], newLength);
}
atoms[model.INDICES.VISIBLE][i] = visible;
atoms[model.INDICES.DRAGGABLE][i] = draggable;
readModelState();
dispatch.addAtom();
return true;
}
// return false on failure
return false;
},
/** Return the bounding box of the molecule containing atom 'atomIndex', with atomic radii taken
into account.
@returns an object with properties 'left', 'right', 'top', and 'bottom'. These are translated
relative to the center of atom 'atomIndex', so that 'left' represents (-) the distance in nm
between the leftmost edge and the center of atom 'atomIndex'.
*/
model.getMoleculeBoundingBox = function(atomIndex) {
var moleculeAtoms,
i,
x,
y,
r,
top = -Infinity,
left = Infinity,
bottom = Infinity,
right = -Infinity,
cx,
cy;
moleculeAtoms = engine.getMoleculeAtoms(atomIndex);
moleculeAtoms.push(atomIndex);
for (i = 0; i < moleculeAtoms.length; i++) {
x = atoms[model.INDICES.X][moleculeAtoms[i]];
y = atoms[model.INDICES.Y][moleculeAtoms[i]];
r = atoms[model.INDICES.RADIUS][moleculeAtoms[i]];
if (x-r < left ) left = x-r;
if (x+r > right ) right = x+r;
if (y-r < bottom) bottom = y-r;
if (y+r > top ) top = y+r;
}
cx = atoms[model.INDICES.X][atomIndex];
cy = atoms[model.INDICES.Y][atomIndex];
return { top: top-cy, left: left-cx, bottom: bottom-cy, right: right-cx };
},
/**
A generic method to set properties on a single existing atom.
Example: setAtomProperties(3, {x: 5, y: 8, px: 0.5, charge: -1})
This can optionally check the new location of the atom to see if it would
overlap with another another atom (i.e. if it would increase the PE).
This can also optionally apply the same dx, dy to any atoms in the same
molecule (if x and y are being changed), and check the location of all
the bonded atoms together.