/
modeler.js
2408 lines (2034 loc) · 75.4 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
import performance from 'common/performance';
import serialize from 'common/serialize';
import validator from 'common/validator';
import LabModelerMixin from 'common/lab-modeler-mixin';
import OutputSupport from 'common/output-support';
import TickHistory from 'common/models/tick-history';
import { createEngine } from 'models/md2d/models/engine/md2d';
import metadata from 'models/md2d/models/metadata';
import units from 'models/md2d/models/engine/constants/units';
import unitDefinitions from 'models/md2d/models/unit-definitions/index';
import UnitsTranslation from 'models/md2d/models/units-translation';
import PropertyDescription from 'common/property-description';
import Solvent from 'models/md2d/models/solvent';
import aminoacids from 'models/md2d/models/aminoacids-props';
import aminoacidsHelper from 'models/md2d/models/aminoacids-helper';
import GeneticEngine from 'models/md2d/models/engine/genetic-engine';
import PerformanceOptimizer from 'models/md2d/models/performance-optimizer';
import AtomTransition from 'models/md2d/models/atom-transition';
import _ from 'underscore';
import QuantumDynamics from 'models/md2d/models/engine/plugins/quantum-dynamics';
import ChemicalReactions from 'models/md2d/models/engine/plugins/chemical-reactions';
// Dependencies.
var // plugins
md2dModelCount = 0;
export default function Model(initialProperties, initializationOptions, i18n) {
// all models created with this constructor will be of type: "md2d"
this.constructor.type = "md2d";
initializationOptions = initializationOptions || {};
var model = {},
namespace = "md2dModel" + (++md2dModelCount),
customSetters = {
targetTemperature: function(value) {
engine.setTargetTemperature(value);
},
temperatureControl: function(value) {
engine.useThermostat(value);
},
lennardJonesForces: function(value) {
engine.useLennardJonesInteraction(value);
},
coulombForces: function(value) {
engine.useCoulombInteraction(value);
},
solventForceType: function(value) {
engine.setSolventForceType(value);
},
DNAState: function(value) {
engine.setDNAState(value);
},
solventForceFactor: function(value) {
engine.setSolventForceFactor(value);
},
additionalSolventForceMult: function(value) {
engine.setAdditionalSolventForceMult(value);
},
additionalSolventForceThreshold: function(value) {
engine.setAdditionalSolventForceThreshold(value);
},
dielectricConstant: function(value) {
engine.setDielectricConstant(value);
},
realisticDielectricEffect: function(value) {
engine.setRealisticDielectricEffect(value);
},
VDWLinesCutoff: function(value) {
var ratio = VDWLinesCutoffMap[value];
if (ratio) {
engine.setVDWLinesRatio(ratio);
}
},
gravitationalField: function(value) {
engine.setGravitationalField(value);
},
modelSampleRate: function() {
if (!model.isStopped()) model.restart();
},
viscosity: function(value) {
engine.setViscosity(value);
},
polarAAEpsilon: function(value) {
var polarAAs, element1, element2,
i, j, len;
// Set custom pairwise LJ properties for polar amino acids.
// They should attract stronger to better mimic nature.
polarAAs = aminoacidsHelper.getPolarAminoAcids();
for (i = 0, len = polarAAs.length; i < len; i++) {
element1 = polarAAs[i];
for (j = i + 1; j < len; j++) {
element2 = polarAAs[j];
// Set custom pairwise LJ epsilon (default one for AA is -0.1).
engine.pairwiseLJProperties.set(element1, element2, {
epsilon: value
});
}
}
},
electricFieldDensity: function(value) {
electricField.length = 0; // reuse existing array!
if (!value) return;
var minX = 0,
minY = 0,
maxX = model.properties.width,
maxY = model.properties.height,
diff = model.properties.width / value,
yOffset = ((maxY / diff) % 1) * diff,
y = minY + 0.5 * (yOffset + (diff <= maxY ? diff : 0)),
x;
while (y < maxY) {
x = minX + 0.5 * diff;
while (x < maxX) {
electricField.push({
x: x,
y: y
});
x += diff;
}
y += diff;
}
}
},
// The set of units currently in effect. (Determined by the 'unitsScheme' property of the
// model; default value is 'md2d')
unitsDefinition = unitDefinitions.get(initialProperties.unitsScheme || 'md2d'),
// Object that translates between 'native' md2d units and the units defined
// by unitsDefinition.
unitsTranslation = (function() {
var scheme = initialProperties.unitsScheme || 'md2d';
// If we're not using MD2D units, we need a translation (which, for each unit type, allows some
// number of "native" MD2D units to stand for 1 translated unit, e.g., 1 nm represents 1m, with
// the relationships between these ratios set up so that the calculations reamin physically
// consistent.
if (scheme !== 'md2d') {
return new UnitsTranslation(unitsDefinition);
}
return undefined;
}()),
labModelerMixin = new LabModelerMixin({
metadata: metadata,
setters: customSetters,
unitsDefinition: unitsDefinition,
unitsTranslation: unitsTranslation,
initialProperties: initialProperties
}),
dispatch = (function() {
var d = labModelerMixin.dispatchSupport;
d.addEventTypes("tick",
"addAtom", "removeAtom", "addRadialBond", "removeRadialBond",
"addElectricField", "removeElectricField", "changeElectricField",
"removeAngularBond", "textBoxesChanged", "imagesChanged");
return d;
}()),
propertySupport = labModelerMixin.propertySupport,
outputSupport,
VDWLinesCutoffMap = {
"short": 1.33,
"medium": 1.67,
"long": 2.0
},
defaultMaxTickHistory = 1000,
newStep = false,
lastSampleTime,
sampleTimes = [],
// FIXME: do we need global reference?
modelState = window.state = {},
tickHistory,
// Transitions list.
transitions = [],
// Molecular Dynamics engine.
engine = (function() {
var e = createEngine();
// Register invalidating change hooks.
// pairwiseLJProperties object allows to change state which defines state of the whole simulation.
e.pairwiseLJProperties.registerChangeHooks(propertySupport.invalidatingChangePreHook, propertySupport.invalidatingChangePostHook);
return e;
}()),
// Genetic engine.
geneticEngine,
// An array of elements object.
editableElements,
// ######################### Main Data Structures #####################
// They are initialized at the end of this function. These data strucutres
// are mainly managed by the engine.
// A hash of arrays consisting of arrays of element property values
elements,
// A hash of arrays consisting of arrays of obstacle property values
obstacles,
// A hash of arrays consisting of arrays of shape property values
shapes,
// A hash of arrays consisting of arrays of line property values
lines,
// A hash of arrays consisting of arrays of electric field property values
electricFields,
// A hash of arrays consisting of arrays of radial bond property values
radialBonds,
// A hash of arrays consisting of arrays of angular bond property values
angularBonds,
// A hash of arrays consisting of arrays of restraint property values
// (currently atom-only)
restraints,
// ####################################################################
// An array of objects consisting of atom index numbers and atom property values, for easy
// consumption by the view. It is updated conservatively from the "unrolled" form used for
// speedy computation by the engine.
viewAtoms = [],
// An array of objects consisting of radial bond index numbers and radial bond property
// values, for easy consumption by the view.
viewRadialBonds = [],
// An array of objects consisting of photon index numbers and property values, for easy
// consumption by the view. Only defined if the quantum dynamics plugin is used.
viewPhotons,
// An array of objects consisting of point coordinates and electric field force at that point
// (e.g. [{ x: 1, y: 2, fx: 0.1, fy: 0.3 }, ...]).
electricField = [],
// The index of the "spring force" used to implement dragging of atoms in a running model
liveDragSpringForceIndex = null,
// Cached value of the 'friction' property of the atom being dragged in a running model
liveDragSavedFriction,
// Properties hashes for use by plugins
pluginProperties;
function processTransitions(timeDiff) {
var i, len;
model.startBatch();
for (i = 0, len = transitions.length; i < len; i++) {
transitions[i].process(timeDiff);
}
// Cleanup finished transitions.
i = 0;
while (i < transitions.length) {
if (transitions[i].isFinished) {
transitions.splice(i, 1);
} else {
i++;
}
}
model.endBatch();
}
// Returns a copy of 'obj' with value replaced by fn(key, value) for every (key, value) pair.
// (Underscore doesn't do this: https://github.com/documentcloud/underscore/issues/220)
function mapValues(obj, fn) {
obj = _.extend({}, obj);
for (var k in obj) {
if (obj.hasOwnProperty(k)) obj[k] = fn(k, obj[k]);
}
return obj;
}
// Modifies a properties hash which has translated units to have MD2D units. Leaves properties
// without a unitType (or with an unrecognized unitType) unmodified.
// Returns 'properties' unmodified (not a copy) if there is no units translation in effect.
function translateToMD2DUnits(properties, metadata) {
if (!unitsTranslation) return properties;
return mapValues(properties, function(key, value) {
return unitsTranslation.translateToModelUnits(value, metadata[key] && metadata[key].unitType);
});
}
// Modifies a properties hash which has MD2D units to have translated units. Leaves properties
// without a unitType (or with an unrecognized unitType) unmodified.
// Returns 'properties' unmodified (not a copy) if there is no units translation in effect.
function translateFromMD2DUnits(properties, metadata) {
if (!unitsTranslation) return properties;
return mapValues(properties, function(key, value) {
return unitsTranslation.translateFromModelUnits(value, metadata[key] && metadata[key].unitType);
});
}
/**
Executes the closure 'extract' which extracts from the tick history, then dispatches
addAtom/removeAtom, etc, events as needed.
This prevents unneessary creation and removal of atoms.
*/
var runAndDispatchObjectNumberChanges = (function() {
var objects = [{
getNum: 'getNumberOfAtoms',
addEvent: 'addAtom',
removeEvent: 'removeAtom'
}, {
getNum: 'getNumberOfRadialBonds',
addEvent: 'addRadialBond',
removeEvent: 'removeRadialBond'
}];
return function(extract) {
var i, o, newNum;
for (i = 0; i < objects.length; i++) {
o = objects[i];
o.num = engine[o.getNum]();
}
extract();
for (i = 0; i < objects.length; i++) {
o = objects[i];
newNum = engine[o.getNum]();
if (newNum > o.num) {
dispatch[o.addEvent]();
} else if (newNum < o.num) {
dispatch[o.removeEvent]();
}
}
};
})();
/**
This method is called to refresh the viewAtoms array and macrostate variables (KE, PE,
temperature) whenever an engine integration occurs or the model state is otherwise changed.
Normally, you should call the methods updateOutputPropertiesAfterChange or
updateAllOutputProperties rather than calling this method. Calling this method directly does
not cause output-property listeners to be notified, and calling it prematurely will confuse
the detection of changed properties.
*/
function readModelState() {
engine.updateParticlesAccelerations();
engine.computeOutputState(modelState);
// remember that getViewPhotons will eventually be a modeler-layer method that ingests a raw
// representation provided by modelState.photons
viewPhotons = engine.callPluginAccessor('getViewPhotons');
updateViewAtoms(modelState.atoms);
updateViewRadialBonds(modelState.radialBonds, modelState.atoms);
updateViewElectricField();
}
// Transpose 'atoms' object into 'viewAtoms' for consumption by view code
function updateViewAtoms(atoms) {
var n = engine.getNumberOfAtoms(),
i,
prop,
amino,
viewAtom;
// TODO: refactor whole approach to creation of objects from flat arrays.
// Think about more general way of detecting and representing amino acids.
// However it would be reasonable to perform such refactoring later, when all requirements
// related to proteins engine are clearer.
viewAtoms.length = n;
for (i = 0, n; i < n; i++) {
if (!viewAtoms[i]) {
viewAtoms[i] = {
idx: i
};
}
viewAtom = viewAtoms[i];
for (prop in atoms) {
if (atoms.hasOwnProperty(prop)) {
viewAtom[prop] = atoms[prop][i];
}
}
viewAtom.aminoAcid = aminoacidsHelper.isAminoAcid(atoms.element[i]);
if (viewAtom.aminoAcid) {
amino = aminoacidsHelper.getAminoAcidByElement(atoms.element[i]);
viewAtom.symbol = amino.symbol;
viewAtom.label = amino.abbreviation;
}
}
}
function updateViewRadialBonds(radialBonds, atoms) {
var n = engine.getNumberOfRadialBonds(),
viewBond, prop, i;
viewRadialBonds.length = n;
for (i = 0; i < n; i++) {
if (!viewRadialBonds[i]) {
viewRadialBonds[i] = {
idx: i
};
}
viewBond = viewRadialBonds[i];
for (prop in radialBonds) {
viewBond[prop] = radialBonds[prop][i];
}
// Additionally calculate x1, y1, x2, y2 properties that are useful for view.
viewBond.x1 = atoms.x[viewBond.atom1];
viewBond.y1 = atoms.y[viewBond.atom1];
viewBond.x2 = atoms.x[viewBond.atom2];
viewBond.y2 = atoms.y[viewBond.atom2];
}
}
function updateViewElectricField() {
// It may seem strange that model reads "viewOption"
// ("showElectricField"), but this is definitely reasonable
// optimization.
if (!electricField.length || !model.properties.showElectricField) return;
var i, len, p;
for (i = 0, len = electricField.length; i < len; i++) {
p = electricField[i];
engine.getCoulombForceAt(p.x, p.y, p);
}
}
/**
return a random element index ... which is *not* an amino acid element
*/
function randomElement() {
var len = engine.getNumberOfElements(),
el = Math.floor(Math.random() * len);
while (aminoacidsHelper.isAminoAcid(el)) {
el = Math.floor(Math.random() * len);
}
return el;
}
/**
Create set of amino acids elements. Use descriptions
provided in 'aminoacids' array.
*/
function createAminoAcids() {
var sigmaIn01Angstroms,
sigmaInNm,
i, len;
// Note that amino acids ALWAYS have IDs from
// AMINO_ELEMENT_FIRST_IDX (= 5) to AMINO_ELEMENT_LAST_IDX (= 24).
// This is enforced by backward compatibility with Classic MW.
// At the beginning, ensure that elements from 0 to 24 exists.
for (i = engine.getNumberOfElements(); i <= aminoacidsHelper.lastElementID; i++) {
model.addElement({
id: i
});
}
// Set amino acids properties using elements from 5 to 24.
for (i = 0, len = aminoacids.length; i < len; i++) {
// Note that sigma is calculated using Classic MW approach.
// See: org.concord.mw2d.models.AminoAcidAdapter
// Basic length unit in Classic MW is 0.1 Angstrom.
sigmaIn01Angstroms = 18 * Math.pow(aminoacids[i].volume / aminoacids[0].volume, 0.3333333333333);
sigmaInNm = units.convert(sigmaIn01Angstroms / 10, {
from: units.unit.ANGSTROM,
to: units.unit.NANOMETER
});
// Use engine's method instead of modeler's method to avoid validation.
// Modeler's wrapper ensures that amino acid is immutable, so it won't allow
// to set properties of amino acid.
engine.setElementProperties(aminoacidsHelper.firstElementID + i, {
mass: aminoacids[i].molWeight,
sigma: sigmaInNm
// Don't provide epsilon, as default value should be used.
// Classic MW uses epsilon 0.1 for all amino acids, which is default one.
// See: org.concord.mw2d.models.AtomicModel.resetElements()
});
}
}
// ------------------------------------------------------------
//
// Public functions
//
// ------------------------------------------------------------
/**
Current seek position
*/
model.stepCounter = function() {
return tickHistory.get("counter");
};
/**
Current position of first value in tick history, normally this will be 0.
This will be greater than 0 if maximum size of tick history has been exceeded.
*/
model.stepStartCounter = function() {
return tickHistory.get("startCounter");
};
/** Total number of ticks that have been run & are stored, regardless of seek
position
*/
model.steps = function() {
return tickHistory.get("length");
};
model.isNewStep = function() {
return newStep;
};
model.seek = function(location) {
if (!arguments.length) {
location = 0;
}
if (!model.isStopped()) {
model.stop();
}
newStep = false;
runAndDispatchObjectNumberChanges(function() {
tickHistory.seekExtract(location);
readModelState();
model.updateAllOutputProperties();
dispatch.seek();
});
return tickHistory.get("counter");
};
model.stepBack = function(num) {
if (!arguments.length) {
num = 1;
}
if (!model.isStopped()) {
model.stop();
}
newStep = false;
runAndDispatchObjectNumberChanges(function() {
var i, index;
i = -1;
while (++i < num) {
index = tickHistory.get("index");
if (index > 0) {
tickHistory.decrementExtract();
readModelState();
model.updateAllOutputProperties();
dispatch.stepBack();
}
}
});
return tickHistory.get("counter");
};
model.stepForward = function(num) {
if (!arguments.length) {
num = 1;
}
if (!model.isStopped()) {
model.stop();
}
runAndDispatchObjectNumberChanges(function() {
var i, index, size;
i = -1;
while (++i < num) {
index = tickHistory.get("index");
size = tickHistory.get("length");
if (index < size - 1) {
tickHistory.incrementExtract();
readModelState();
model.updateAllOutputProperties();
dispatch.stepForward();
} else {
model.tick();
}
}
});
return tickHistory.get("counter");
};
/**
Initialize minX, minYm, maxX, maxY from width and height
when these options are undefined.
*/
function initializeDimensions(properties) {
var minX = properties.minX,
minY = properties.minY,
maxX = properties.maxX,
maxY = properties.maxY;
properties.minX = minX != null ? minX : 0;
properties.maxX = maxX != null ? maxX : properties.width;
properties.minY = minY != null ? minY : 0;
properties.maxY = maxY != null ? maxY : properties.height;
}
/**
Creates a new md2d engine and leaves it in 'engine'.
*/
function initializeEngine(properties, pluginProperties) {
engine.setDimensions([properties.minX, properties.minY, properties.maxX, properties.maxY]);
if (pluginProperties.quantumDynamics) {
properties.useQuantumDynamics = true;
engine.addPlugin(new QuantumDynamics(engine, pluginProperties.quantumDynamics));
} else {
properties.useQuantumDynamics = false;
}
if (pluginProperties.chemicalReactions) {
properties.useChemicalReactions = true;
engine.addPlugin(new ChemicalReactions(engine, pluginProperties.chemicalReactions));
} else {
properties.useChemicalReactions = false;
}
// Copy reference to basic properties.
// FIXME. This should go away. https://www.pivotaltracker.com/story/show/50086079
elements = engine.elements;
radialBonds = engine.radialBonds;
angularBonds = engine.angularBonds;
restraints = engine.restraints;
obstacles = engine.obstacles;
shapes = engine.shapes;
lines = engine.lines;
electricFields = engine.electricFields;
}
model.createElements = function(_elements) {
var i, num, prop, elementProps;
// Start batch process
model.startBatch();
if (_elements === undefined) {
// Special case when elements are not defined.
// Empty object will be filled with default values.
model.addElement({
id: 0
});
model.endBatch();
return;
}
// _elements is hash of arrays (as specified in JSON model).
// So, for each index, create object containing properties of
// element 'i'. Later, use these properties to add element
// using basic addElement method.
for (i = 0, num = _elements.mass.length; i < num; i++) {
elementProps = {};
for (prop in _elements) {
if (_elements.hasOwnProperty(prop)) {
elementProps[prop] = _elements[prop][i];
}
}
model.addElement(elementProps);
}
// End batch process
model.endBatch();
return model;
};
/**
Creates a new set of atoms.
config: a hash specifying the x,y,vx,vy properties of the atoms
*/
model.createAtoms = function(config) {
// Options for addAtom method.
var options = {
// Do not check the position of atom, assume that it's valid.
suppressCheck: true
},
i, num, prop, atomProps;
dispatch.willReset();
// Start batch process
model.startBatch();
num = config.x.length;
// config is hash of arrays (as specified in JSON model). So, for each index, create object
// containing properties of atom 'i'. Later, use these properties to add atom using basic
// addAtom method.
for (i = 0; i < num; i++) {
atomProps = {};
for (prop in config) {
if (config.hasOwnProperty(prop)) {
atomProps[prop] = config[prop][i];
}
}
model.addAtom(atomProps, options);
}
// End batch process
model.endBatch();
// Listeners should consider resetting the atoms a 'reset' event
dispatch.reset();
};
model.createRadialBonds = function(_radialBonds) {
var num = _radialBonds.strength.length,
i, prop, radialBondProps;
// Start batch process
model.startBatch();
// _radialBonds is hash of arrays (as specified in JSON model).
// So, for each index, create object containing properties of
// radial bond 'i'. Later, use these properties to add radial bond
// using basic addRadialBond method.
for (i = 0; i < num; i++) {
radialBondProps = {};
for (prop in _radialBonds) {
if (_radialBonds.hasOwnProperty(prop)) {
radialBondProps[prop] = _radialBonds[prop][i];
}
}
model.addRadialBond(radialBondProps);
}
// End batch process
model.endBatch();
return model;
};
model.createAngularBonds = function(_angularBonds) {
var num = _angularBonds.strength.length,
i, prop, angularBondProps;
// Start batch process
model.startBatch();
// _angularBonds is hash of arrays (as specified in JSON model).
// So, for each index, create object containing properties of
// angular bond 'i'. Later, use these properties to add angular bond
// using basic addAngularBond method.
for (i = 0; i < num; i++) {
angularBondProps = {};
for (prop in _angularBonds) {
if (_angularBonds.hasOwnProperty(prop)) {
angularBondProps[prop] = _angularBonds[prop][i];
}
}
model.addAngularBond(angularBondProps);
}
// End batch process
model.endBatch();
return model;
};
model.createRestraints = function(_restraints) {
var num = _restraints.atomIndex.length,
i, prop, restraintsProps;
// _restraints is hash of arrays (as specified in JSON model).
// So, for each index, create object containing properties of
// restraint 'i'. Later, use these properties to add restraint
// using basic addRestraint method.
for (i = 0; i < num; i++) {
restraintsProps = {};
for (prop in _restraints) {
if (_restraints.hasOwnProperty(prop)) {
restraintsProps[prop] = _restraints[prop][i];
}
}
model.addRestraint(restraintsProps);
}
return model;
};
model.createObstacles = function(_obstacles) {
var numObstacles = _obstacles.x.length,
i, prop, obstacleProps;
// _obstacles is hash of arrays (as specified in JSON model).
// So, for each index, create object containing properties of
// obstacle 'i'. Later, use these properties to add obstacle
// using basic addObstacle method.
for (i = 0; i < numObstacles; i++) {
obstacleProps = {};
for (prop in _obstacles) {
if (_obstacles.hasOwnProperty(prop)) {
obstacleProps[prop] = _obstacles[prop][i];
}
}
model.addObstacle(obstacleProps);
}
return model;
};
model.createShapes = function(_shapes) {
var numShapes = _shapes.x.length,
i, prop, shapeProps;
// See function above
for (i = 0; i < numShapes; i++) {
shapeProps = {};
for (prop in _shapes) {
if (_shapes.hasOwnProperty(prop)) {
shapeProps[prop] = _shapes[prop][i];
}
}
model.addShape(shapeProps);
}
return model;
};
model.createLines = function(_lines) {
var numLines = _lines.x1.length,
i, prop, lineProps;
// See function above
for (i = 0; i < numLines; i++) {
lineProps = {};
for (prop in _lines) {
if (_lines.hasOwnProperty(prop)) {
lineProps[prop] = _lines[prop][i];
}
}
model.addLine(lineProps);
}
return model;
};
model.createElectricFields = function(_eFields) {
model.batch(function() {
var count = _eFields.intensity.length,
i, prop, eFieldProps;
for (i = 0; i < count; i++) {
eFieldProps = {};
for (prop in _eFields) {
if (_eFields.hasOwnProperty(prop)) {
eFieldProps[prop] = _eFields[prop][i];
}
}
model.addElectricField(eFieldProps);
}
});
return model;
};
// Beware. The "reset" button in Lab interactives do not call this method. Instead they "reload"
// the model, discarding this model object and creating a new one from the model JSON.
model.reset = function() {
dispatch.willReset();
propertySupport.invalidatingChangePreHook();
engine.setTime(0);
tickHistory.restoreInitialState();
propertySupport.invalidatingChangePostHook();
model.resetAllOutputProperties();
dispatch.reset();
};
model.getTotalMass = function() {
return engine.getTotalMass();
};
model.getAtomKineticEnergy = function(i) {
return engine.getAtomKineticEnergy(i);
};
/**
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 editableElements) and
charge (default is neutral).
*/
model.addRandomAtom = function(el, charge) {
if (el == null) el = randomElement();
if (charge == null) charge = 0;
var width = model.get('width'),
height = model.get('height'),
minX = model.get('minX'),
minY = model.get('minY'),
radius = engine.getRadiusOfElement(el),
x,
y,
loc,
numTries = 0,
// try at most ten times.
maxTries = 10;
do {
x = minX + Math.random() * width - 2 * radius;
y = minY + Math.random() * height - 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({
element: el,
x: loc[0],
y: loc[1],
charge: charge
})) return true;
} while (++numTries < maxTries);
return false;
};
/**
Adds a new atom defined by properties.
Intended to be exposed as a script API method also.
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), or if atom is placed inside an obstacle
Otherwise, returns true.
silent = true disables this check.
*/
model.addAtom = function(props, options) {
var minX = model.get('minX'),
minY = model.get('minY'),
maxX = model.get('maxX'),
maxY = model.get('maxY'),
radius;
options = options || {};
// Validate properties, provide default values.
props = validator.validateCompleteness(metadata.atom, props);
// As a convenience to script authors, bump the atom within bounds
radius = engine.getRadiusOfElement(props.element);
if (props.x < (minX + radius)) props.x = minX + radius;
if (props.x > (maxX - radius)) props.x = maxX - radius;
if (props.y < (minY + radius)) props.y = minY + radius;
if (props.y > (maxY - radius)) props.y = maxY - radius;
// check the potential energy change caused by adding an *uncharged* atom at (x,y)
if (!options.suppressCheck && !engine.canPlaceAtom(props.element, props.x, props.y, null, model.get('skipPECheckOnAddAtom'))) {
// return false on failure
return false;
}
propertySupport.invalidatingChangePreHook();
engine.addAtom(props);
propertySupport.invalidatingChangePostHook();
dispatch.addAtom();
return true;
};
model.removeAtom = function(i) {
var prevRadBondsCount = engine.getNumberOfRadialBonds(),
prevAngBondsCount = engine.getNumberOfAngularBonds();
propertySupport.invalidatingChangePreHook();