-
Notifications
You must be signed in to change notification settings - Fork 8
/
MultipleParticleModel.js
1445 lines (1202 loc) · 61.2 KB
/
MultipleParticleModel.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
// Copyright 2014-2020, University of Colorado Boulder
/**
* This is the main class for the model portion of the first two screens of the "States of Matter" simulation. Its
* primary purpose is to simulate a set of molecules that are interacting with one another based on the attraction and
* repulsion that is described by the Lennard-Jones potential equation.
*
* Each instance of this class maintains a set of data that represents a normalized model in which all atoms that
* comprise each molecule - and often it is just one atom per molecule - are assumed to have a diameter of 1, since this
* allows for very quick calculations, and also a set of data for atoms that have the actual diameter of the atoms being
* simulated (e.g. Argon). Throughout the comments and in the variable naming the terms "normalized data set" (or
* sometimes simply "normalized set") and "model data set" are used for this date, respectively. When the simulation is
* running, the normalized data set is updated first, since that is where the hardcore calculations are performed, and
* then the model data set is synchronized with the normalized data. It is the model data set that is monitored by the
* view components that actually display the molecule positions to the user.
*
* @author John Blanco
* @author Aaron Davis
* @author Siddhartha Chinthapally (Actual Concepts)
*/
import BooleanProperty from '../../../../axon/js/BooleanProperty.js';
import DerivedProperty from '../../../../axon/js/DerivedProperty.js';
import DerivedPropertyIO from '../../../../axon/js/DerivedPropertyIO.js';
import Emitter from '../../../../axon/js/Emitter.js';
import EnumerationProperty from '../../../../axon/js/EnumerationProperty.js';
import NumberProperty from '../../../../axon/js/NumberProperty.js';
import ObservableArray from '../../../../axon/js/ObservableArray.js';
import Range from '../../../../dot/js/Range.js';
import Utils from '../../../../dot/js/Utils.js';
import Vector2 from '../../../../dot/js/Vector2.js';
import EnumerationIO from '../../../../phet-core/js/EnumerationIO.js';
import merge from '../../../../phet-core/js/merge.js';
import required from '../../../../phet-core/js/required.js';
import PhetioObject from '../../../../tandem/js/PhetioObject.js';
import Tandem from '../../../../tandem/js/Tandem.js';
import BooleanIO from '../../../../tandem/js/types/BooleanIO.js';
import NullableIO from '../../../../tandem/js/types/NullableIO.js';
import NumberIO from '../../../../tandem/js/types/NumberIO.js';
import statesOfMatter from '../../statesOfMatter.js';
import PhaseStateEnum from '../PhaseStateEnum.js';
import SOMConstants from '../SOMConstants.js';
import SubstanceType from '../SubstanceType.js';
import AtomType from './AtomType.js';
import DiatomicAtomPositionUpdater from './engine/DiatomicAtomPositionUpdater.js';
import DiatomicPhaseStateChanger from './engine/DiatomicPhaseStateChanger.js';
import DiatomicVerletAlgorithm from './engine/DiatomicVerletAlgorithm.js';
import AndersenThermostat from './engine/kinetic/AndersenThermostat.js';
import IsokineticThermostat from './engine/kinetic/IsokineticThermostat.js';
import MonatomicAtomPositionUpdater from './engine/MonatomicAtomPositionUpdater.js';
import MonatomicPhaseStateChanger from './engine/MonatomicPhaseStateChanger.js';
import MonatomicVerletAlgorithm from './engine/MonatomicVerletAlgorithm.js';
import WaterAtomPositionUpdater from './engine/WaterAtomPositionUpdater.js';
import WaterPhaseStateChanger from './engine/WaterPhaseStateChanger.js';
import WaterVerletAlgorithm from './engine/WaterVerletAlgorithm.js';
import MoleculeForceAndMotionDataSet from './MoleculeForceAndMotionDataSet.js';
import MoleculeForceAndMotionDataSetIO from './MoleculeForceAndMotionDataSetIO.js';
import MovingAverage from './MovingAverage.js';
import MultipleParticleModelIO from './MultipleParticleModelIO.js';
import HydrogenAtom from './particle/HydrogenAtom.js';
import ScaledAtom from './particle/ScaledAtom.js';
//---------------------------------------------------------------------------------------------------------------------
// constants
//---------------------------------------------------------------------------------------------------------------------
// general constants
const CONTAINER_WIDTH = 10000; // in picometers
const CONTAINER_INITIAL_HEIGHT = 10000; // in picometers
const DEFAULT_SUBSTANCE = SubstanceType.NEON;
const MAX_TEMPERATURE = 50.0;
const MIN_TEMPERATURE = 0.00001;
const NOMINAL_GRAVITATIONAL_ACCEL = -0.045;
const TEMPERATURE_CHANGE_RATE = 0.07; // empirically determined to make temperate change at a reasonable rate
const INJECTED_MOLECULE_SPEED = 2.0; // in normalized model units per second, empirically determined to look reasonable
const INJECTED_MOLECULE_ANGLE_SPREAD = Math.PI * 0.25; // in radians, empirically determined to look reasonable
const INJECTION_POINT_HORIZ_PROPORTION = 0.00;
const INJECTION_POINT_VERT_PROPORTION = 0.25;
// constants related to how time steps are handled
const PARTICLE_SPEED_UP_FACTOR = 4; // empirically determined to make the particles move at a speed that looks reasonable
const MAX_PARTICLE_MOTION_TIME_STEP = 0.025; // max time step that model can handle, empirically determined
// constants that define the normalized temperatures used for the various states
const SOLID_TEMPERATURE = SOMConstants.SOLID_TEMPERATURE;
const LIQUID_TEMPERATURE = SOMConstants.LIQUID_TEMPERATURE;
const GAS_TEMPERATURE = SOMConstants.GAS_TEMPERATURE;
const INITIAL_TEMPERATURE = SOLID_TEMPERATURE;
const APPROACHING_ABSOLUTE_ZERO_TEMPERATURE = SOLID_TEMPERATURE * 0.85;
// parameters to control rates of change of the container size
const MAX_CONTAINER_EXPAND_RATE = 1500; // in model units per second
const POST_EXPLOSION_CONTAINER_EXPANSION_RATE = 9000; // in model units per second
// Range for deciding if the temperature is near the current set point. The units are internal model units.
const TEMPERATURE_CLOSENESS_RANGE = 0.15;
// Values used for converting from model temperature to the temperature for a given substance.
const NEON_TRIPLE_POINT_IN_KELVIN = SOMConstants.NEON_TRIPLE_POINT_IN_KELVIN;
const NEON_CRITICAL_POINT_IN_KELVIN = SOMConstants.NEON_CRITICAL_POINT_IN_KELVIN;
const ARGON_TRIPLE_POINT_IN_KELVIN = SOMConstants.ARGON_TRIPLE_POINT_IN_KELVIN;
const ARGON_CRITICAL_POINT_IN_KELVIN = SOMConstants.ARGON_CRITICAL_POINT_IN_KELVIN;
const O2_TRIPLE_POINT_IN_KELVIN = SOMConstants.O2_TRIPLE_POINT_IN_KELVIN;
const O2_CRITICAL_POINT_IN_KELVIN = SOMConstants.O2_CRITICAL_POINT_IN_KELVIN;
const WATER_TRIPLE_POINT_IN_KELVIN = SOMConstants.WATER_TRIPLE_POINT_IN_KELVIN;
const WATER_CRITICAL_POINT_IN_KELVIN = SOMConstants.WATER_CRITICAL_POINT_IN_KELVIN;
// The following values are used for temperature conversion for the adjustable molecule. These are somewhat
// arbitrary, since in the real world the values would change if epsilon were changed. They have been chosen to be
// similar to argon, because the default epsilon value is half of the allowable range, and this value ends up being
// similar to argon.
const ADJUSTABLE_ATOM_TRIPLE_POINT_IN_KELVIN = 75;
const ADJUSTABLE_ATOM_CRITICAL_POINT_IN_KELVIN = 140;
// Time value used to prevent molecule injections from being too close together so that they don't overlap after
// injection and cause high initial velocities.
const MOLECULE_INJECTION_HOLDOFF_TIME = 0.25; // seconds, empirically determined
const MAX_MOLECULES_QUEUED_FOR_INJECTION = 3;
class MultipleParticleModel extends PhetioObject {
/**
* @param {Tandem} tandem
* @param {Object} [options]
*/
constructor( tandem, options ) {
options = merge( {
validSubstances: SubstanceType.VALUES
}, options );
super( {
tandem: tandem,
phetioType: MultipleParticleModelIO
} );
//-----------------------------------------------------------------------------------------------------------------
// observable model properties
//-----------------------------------------------------------------------------------------------------------------
// @public (read-write)
this.substanceProperty = new EnumerationProperty( SubstanceType, DEFAULT_SUBSTANCE, {
validValues: options.validSubstances,
tandem: tandem.createTandem( 'substanceProperty' ),
phetioState: false
} );
// @public (read-only)
this.containerHeightProperty = new NumberProperty( CONTAINER_INITIAL_HEIGHT, {
tandem: tandem.createTandem( 'containerHeightProperty' ),
phetioState: false,
phetioReadOnly: true,
phetioDocumentation: 'The height of the particle container, in picometers.',
units: 'pm'
} );
// @public (read-only)
this.isExplodedProperty = new BooleanProperty( false, {
tandem: tandem.createTandem( 'isExplodedProperty' ),
phetioState: false,
phetioReadOnly: true
} );
// @public (read-write)
this.temperatureSetPointProperty = new NumberProperty( INITIAL_TEMPERATURE, {
tandem: tandem.createTandem( 'temperatureSetPointProperty' ),
phetioReadOnly: true,
phetioDocumentation: 'In internal model units, solid = 0.15, liquid = 0.34, gas = 1.'
} );
// @public (read-only)
this.pressureProperty = new NumberProperty( 0, {
tandem: tandem.createTandem( 'pressureProperty' ),
phetioReadOnly: true,
units: 'atm'
} );
// @public (read-write)
this.isPlayingProperty = new BooleanProperty( true, {
tandem: tandem.createTandem( 'isPlayingProperty' )
} );
// @public (read-write)
this.heatingCoolingAmountProperty = new NumberProperty( 0, {
tandem: tandem.createTandem( 'heatingCoolingAmountProperty' ),
phetioState: false,
range: new Range( -1, 1 ),
phetioStudioControl: false
} );
// @public (read-write) - the number of molecules that should be in the simulation. This is used primarily for
// injecting new molecules, and when this number is increased, internal model state is adjusted to match.
this.targetNumberOfMoleculesProperty = new NumberProperty( 0, {
tandem: tandem.createTandem( 'targetNumberOfMoleculesProperty' ),
phetioReadOnly: true,
phetioDocumentation: 'This value represents the number of particles being simulated, not the number of particles in the container.'
} );
// @public (read-only)
this.maxNumberOfMoleculesProperty = new NumberProperty( SOMConstants.MAX_NUM_ATOMS );
// @private {NumberProperty}
this.numMoleculesQueuedForInjectionProperty = new NumberProperty( 0 );
// @public (read-only) - indicates whether injection of additional molecules is allowed
this.isInjectionAllowedProperty = new DerivedProperty(
[
this.isPlayingProperty,
this.numMoleculesQueuedForInjectionProperty,
this.isExplodedProperty,
this.maxNumberOfMoleculesProperty,
this.targetNumberOfMoleculesProperty
],
( isPlaying, numberOfMoleculesQueuedForInjection, isExploded, maxNumberOfMoleculesProperty, targetNumberOfMolecules ) => {
return isPlaying &&
numberOfMoleculesQueuedForInjection < MAX_MOLECULES_QUEUED_FOR_INJECTION &&
!isExploded &&
targetNumberOfMolecules < maxNumberOfMoleculesProperty;
}
);
// @public (listen-only) - fires when a reset occurs
this.resetEmitter = new Emitter();
//-----------------------------------------------------------------------------------------------------------------
// other model attributes
//-----------------------------------------------------------------------------------------------------------------
// @public (read-only) {ObservableArray<ScaledAtom>} - array of scaled (i.e. non-normalized) atoms
this.scaledAtoms = new ObservableArray();
// @public {MoleculeForceAndMotionDataSet} - data set containing information about the position, motion, and force
// for the normalized atoms
this.moleculeDataSet = null;
// @public (read-only) {number} - various non-property attributes
this.normalizedContainerWidth = CONTAINER_WIDTH / this.particleDiameter;
this.gravitationalAcceleration = NOMINAL_GRAVITATIONAL_ACCEL;
// @public (read-only) {number} - normalized version of the container height, changes as the lid position changes
this.normalizedContainerHeight = this.containerHeightProperty.get() / this.particleDiameter;
// @public (read-only) {number} - normalized version of the TOTAL container height regardless of the lid position
this.normalizedTotalContainerHeight = this.containerHeightProperty.get / this.particleDiameter;
// @protected - normalized velocity at which lid is moving in y direction
this.normalizedLidVelocityY = 0;
// @protected (read-only) {Vector2} - the location where new molecules are injected, in normalized coordinates
this.injectionPoint = Vector2.ZERO.copy();
// @private, various internal model variables
this.particleDiameter = 1;
this.minModelTemperature = null;
this.residualTime = 0;
this.moleculeInjectionHoldoffTimer = 0;
this.heightChangeThisStep = 0;
this.moleculeInjectedThisStep = false;
// @private, strategy patterns that are applied to the data set
this.atomPositionUpdater = null;
this.phaseStateChanger = null;
this.isoKineticThermostat = null;
this.andersenThermostat = null;
// @protected
this.moleculeForceAndMotionCalculator = null;
// @private - moving average calculator that tracks the average difference between the calculated and target temperatures
this.averageTemperatureDifference = new MovingAverage( 10 );
//-----------------------------------------------------------------------------------------------------------------
// other initialization
//-----------------------------------------------------------------------------------------------------------------
// listen for changes to the substance being simulated and update the internals as needed
this.substanceProperty.link( substance => {
this.handleSubstanceChanged( substance );
} );
// listen for changes to the non-normalized container size and update the normalized dimensions
this.containerHeightProperty.link( this.updateNormalizedContainerDimensions.bind( this ) );
// listen for new molecules being added (generally from the pump)
this.targetNumberOfMoleculesProperty.lazyLink( targetNumberOfMolecules => {
assert && assert(
targetNumberOfMolecules <= this.maxNumberOfMoleculesProperty.value,
'target number of molecules set above max allowed'
);
const currentNumberOfMolecules = Math.floor(
this.moleculeDataSet.numberOfAtoms / this.moleculeDataSet.atomsPerMolecule
);
const numberOfMoleculesToAdd = targetNumberOfMolecules -
( currentNumberOfMolecules + this.numMoleculesQueuedForInjectionProperty.value );
for ( let i = 0; i < numberOfMoleculesToAdd; i++ ) {
this.queueMoleculeForInjection();
}
} );
// @public (read-only) - the model temperature in Kelvin, derived from the temperature set point in model units
this.temperatureInKelvinProperty = new DerivedProperty(
[this.temperatureSetPointProperty, this.substanceProperty, this.targetNumberOfMoleculesProperty],
() => this.getTemperatureInKelvin(),
{
units: 'K',
phetioType: DerivedPropertyIO( NullableIO( NumberIO ) ),
tandem: tandem.createTandem( 'temperatureInKelvinProperty' ),
phetReadOnly: true
}
);
// perform any phet-io-specific state setting actions
Tandem.PHET_IO_ENABLED && phet.phetio.phetioEngine.phetioStateEngine.stateSetEmitter.addListener( () => {
// make sure that we have the right number of scaled (i.e. non-normalized) atoms
const numberOfNormalizedMolecules = this.moleculeDataSet.numberOfMolecules;
const numberOfNonNormalizedMolecules = this.scaledAtoms.length / this.moleculeDataSet.atomsPerMolecule;
if ( numberOfNormalizedMolecules > numberOfNonNormalizedMolecules ) {
this.addAtomsForCurrentSubstance( numberOfNormalizedMolecules - numberOfNonNormalizedMolecules );
}
else if ( numberOfNonNormalizedMolecules > numberOfNormalizedMolecules ) {
_.times( ( numberOfNonNormalizedMolecules - numberOfNormalizedMolecules ) * this.moleculeDataSet.atomsPerMolecule, () => {
this.scaledAtoms.pop();
} );
}
// clear the injection counter - all atoms and molecules should be accounted for at this point
this.numMoleculesQueuedForInjectionProperty.reset();
// synchronize the positions of the scaled atoms to the normalized data set
this.syncAtomPositions();
} );
}
/**
* @param {number} newTemperature
* @public
*/
setTemperature( newTemperature ) {
if ( newTemperature > MAX_TEMPERATURE ) {
this.temperatureSetPointProperty.set( MAX_TEMPERATURE );
}
else if ( newTemperature < MIN_TEMPERATURE ) {
this.temperatureSetPointProperty.set( MIN_TEMPERATURE );
}
else {
this.temperatureSetPointProperty.set( newTemperature );
}
if ( this.isoKineticThermostat !== null ) {
this.isoKineticThermostat.targetTemperature = newTemperature;
}
if ( this.andersenThermostat !== null ) {
this.andersenThermostat.targetTemperature = newTemperature;
}
}
/**
* Get the current temperature in degrees Kelvin. The calculations done are dependent on the type of molecule
* selected. The values and ranges used in this method were derived from information provided by Paul Beale, dept
* of Physics, University of Colorado Boulder. If no atoms are in the container, this returns null.
* @returns {number|null}
* @private
*/
getTemperatureInKelvin() {
if ( this.scaledAtoms.length === 0 ) {
// temperature is reported as null if there are no atoms since the temperature is meaningless in that case
return null;
}
let temperatureInKelvin;
let triplePointInKelvin = 0;
let criticalPointInKelvin = 0;
let triplePointInModelUnits = 0;
let criticalPointInModelUnits = 0;
switch( this.substanceProperty.get() ) {
case SubstanceType.NEON:
triplePointInKelvin = NEON_TRIPLE_POINT_IN_KELVIN;
criticalPointInKelvin = NEON_CRITICAL_POINT_IN_KELVIN;
triplePointInModelUnits = SOMConstants.TRIPLE_POINT_MONATOMIC_MODEL_TEMPERATURE;
criticalPointInModelUnits = SOMConstants.CRITICAL_POINT_MONATOMIC_MODEL_TEMPERATURE;
break;
case SubstanceType.ARGON:
triplePointInKelvin = ARGON_TRIPLE_POINT_IN_KELVIN;
criticalPointInKelvin = ARGON_CRITICAL_POINT_IN_KELVIN;
triplePointInModelUnits = SOMConstants.TRIPLE_POINT_MONATOMIC_MODEL_TEMPERATURE;
criticalPointInModelUnits = SOMConstants.CRITICAL_POINT_MONATOMIC_MODEL_TEMPERATURE;
break;
case SubstanceType.ADJUSTABLE_ATOM:
triplePointInKelvin = ADJUSTABLE_ATOM_TRIPLE_POINT_IN_KELVIN;
criticalPointInKelvin = ADJUSTABLE_ATOM_CRITICAL_POINT_IN_KELVIN;
triplePointInModelUnits = SOMConstants.TRIPLE_POINT_MONATOMIC_MODEL_TEMPERATURE;
criticalPointInModelUnits = SOMConstants.CRITICAL_POINT_MONATOMIC_MODEL_TEMPERATURE;
break;
case SubstanceType.WATER:
triplePointInKelvin = WATER_TRIPLE_POINT_IN_KELVIN;
criticalPointInKelvin = WATER_CRITICAL_POINT_IN_KELVIN;
triplePointInModelUnits = SOMConstants.TRIPLE_POINT_WATER_MODEL_TEMPERATURE;
criticalPointInModelUnits = SOMConstants.CRITICAL_POINT_WATER_MODEL_TEMPERATURE;
break;
case SubstanceType.DIATOMIC_OXYGEN:
triplePointInKelvin = O2_TRIPLE_POINT_IN_KELVIN;
criticalPointInKelvin = O2_CRITICAL_POINT_IN_KELVIN;
triplePointInModelUnits = SOMConstants.TRIPLE_POINT_DIATOMIC_MODEL_TEMPERATURE;
criticalPointInModelUnits = SOMConstants.CRITICAL_POINT_DIATOMIC_MODEL_TEMPERATURE;
break;
default:
throw( new Error( 'unsupported substance' ) ); // should never happen, debug if it does
}
if ( this.temperatureSetPointProperty.get() <= this.minModelTemperature ) {
// we treat anything below the minimum temperature as absolute zero
temperatureInKelvin = 0;
}
else if ( this.temperatureSetPointProperty.get() < triplePointInModelUnits ) {
temperatureInKelvin = this.temperatureSetPointProperty.get() * triplePointInKelvin / triplePointInModelUnits;
if ( temperatureInKelvin < 0.5 ) {
// Don't return zero - or anything that would round to it - as a value until we actually reach the minimum
// internal temperature.
temperatureInKelvin = 0.5;
}
}
else if ( this.temperatureSetPointProperty.get() < criticalPointInModelUnits ) {
const slope = ( criticalPointInKelvin - triplePointInKelvin ) /
( criticalPointInModelUnits - triplePointInModelUnits );
const offset = triplePointInKelvin - ( slope * triplePointInModelUnits );
temperatureInKelvin = this.temperatureSetPointProperty.get() * slope + offset;
}
else {
temperatureInKelvin = this.temperatureSetPointProperty.get() * criticalPointInKelvin /
criticalPointInModelUnits;
}
return temperatureInKelvin;
}
/**
* Get the pressure value which is being calculated by the model and is not adjusted to represent any "real" units
* (such as atmospheres).
* @returns {number}
* @public
*/
getModelPressure() {
return this.moleculeForceAndMotionCalculator.pressureProperty.get();
}
/**
* handler that sets up the various portions of the model to support the newly selected substance
* @param {SubstanceType} substance
* @protected
*/
handleSubstanceChanged( substance ) {
assert && assert(
substance === SubstanceType.DIATOMIC_OXYGEN ||
substance === SubstanceType.NEON ||
substance === SubstanceType.ARGON ||
substance === SubstanceType.WATER ||
substance === SubstanceType.ADJUSTABLE_ATOM,
'unsupported substance'
);
// Retain the current phase so that we can set the atoms back to this phase once they have been created and
// initialized.
const phase = this.mapTemperatureToPhase();
// remove all atoms
this.removeAllAtoms();
// Reinitialize the model parameters.
this.initializeModelParameters();
// Set the model parameters that are dependent upon the substance being simulated.
switch( substance ) {
case SubstanceType.DIATOMIC_OXYGEN:
this.particleDiameter = SOMConstants.OXYGEN_RADIUS * 2;
this.minModelTemperature = 0.5 * SOMConstants.TRIPLE_POINT_DIATOMIC_MODEL_TEMPERATURE /
O2_TRIPLE_POINT_IN_KELVIN;
break;
case SubstanceType.NEON:
this.particleDiameter = SOMConstants.NEON_RADIUS * 2;
this.minModelTemperature = 0.5 * SOMConstants.TRIPLE_POINT_MONATOMIC_MODEL_TEMPERATURE /
NEON_TRIPLE_POINT_IN_KELVIN;
break;
case SubstanceType.ARGON:
this.particleDiameter = SOMConstants.ARGON_RADIUS * 2;
this.minModelTemperature = 0.5 * SOMConstants.TRIPLE_POINT_MONATOMIC_MODEL_TEMPERATURE /
ARGON_TRIPLE_POINT_IN_KELVIN;
break;
case SubstanceType.WATER:
// Use a radius value that is artificially large, because the educators have requested that water look
// "spaced out" so that users can see the crystal structure better, and so that the solid form will look
// larger (since water expands when frozen).
this.particleDiameter = SOMConstants.OXYGEN_RADIUS * 2.9;
this.minModelTemperature = 0.5 * SOMConstants.TRIPLE_POINT_WATER_MODEL_TEMPERATURE /
WATER_TRIPLE_POINT_IN_KELVIN;
break;
case SubstanceType.ADJUSTABLE_ATOM:
this.particleDiameter = SOMConstants.ADJUSTABLE_ATTRACTION_DEFAULT_RADIUS * 2;
this.minModelTemperature = 0.5 * SOMConstants.TRIPLE_POINT_MONATOMIC_MODEL_TEMPERATURE /
ADJUSTABLE_ATOM_TRIPLE_POINT_IN_KELVIN;
break;
default:
throw( new Error( 'unsupported substance' ) ); // should never happen, debug if it does
}
// Reset the container height.
this.containerHeightProperty.reset();
// Make sure the normalized container dimensions are correct for the substance and the current non-normalize size.
this.updateNormalizedContainerDimensions();
// Adjust the injection point based on the new particle diameter. These are using the normalized coordinate values.
this.injectionPoint.setXY(
CONTAINER_WIDTH / this.particleDiameter * INJECTION_POINT_HORIZ_PROPORTION,
CONTAINER_INITIAL_HEIGHT / this.particleDiameter * INJECTION_POINT_VERT_PROPORTION
);
// Add the atoms and set their initial positions.
this.initializeAtoms( phase );
// Reset the moving average of temperature differences.
this.averageTemperatureDifference.reset();
// Set the number of molecules and range for the current substance.
const atomsPerMolecule = this.moleculeDataSet.atomsPerMolecule;
this.targetNumberOfMoleculesProperty.set( Math.floor( this.moleculeDataSet.numberOfAtoms / atomsPerMolecule ) );
this.maxNumberOfMoleculesProperty.set( Math.floor( SOMConstants.MAX_NUM_ATOMS / atomsPerMolecule ) );
}
/**
* @private
*/
updatePressure() {
this.pressureProperty.set( this.getPressureInAtmospheres() );
}
/**
* @public
*/
reset() {
const substanceAtStartOfReset = this.substanceProperty.get();
// reset observable properties
this.containerHeightProperty.reset();
this.isExplodedProperty.reset();
this.temperatureSetPointProperty.reset();
this.pressureProperty.reset();
this.substanceProperty.reset();
this.isPlayingProperty.reset();
this.heatingCoolingAmountProperty.reset();
// reset thermostats
this.isoKineticThermostat.clearAccumulatedBias();
this.andersenThermostat.clearAccumulatedBias();
// if the substance wasn't changed during reset, so some additional work is necessary
if ( substanceAtStartOfReset === this.substanceProperty.get() ) {
this.removeAllAtoms();
this.containerHeightProperty.reset();
this.initializeAtoms( PhaseStateEnum.SOLID );
}
// other reset
this.gravitationalAcceleration = NOMINAL_GRAVITATIONAL_ACCEL;
this.resetEmitter.emit();
}
/**
* Set the phase of the molecules in the simulation.
* @param {number} phaseSate
* @public
*/
setPhase( phaseSate ) {
assert && assert(
phaseSate === PhaseStateEnum.SOLID || phaseSate === PhaseStateEnum.LIQUID || phaseSate === PhaseStateEnum.GAS,
'invalid phase state specified'
);
this.phaseStateChanger.setPhase( phaseSate );
this.syncAtomPositions();
}
/**
* Sets the amount of heating or cooling that the system is undergoing.
* @param {number} normalizedHeatingCoolingAmount - Normalized amount of heating or cooling that the system is
* undergoing, ranging from -1 to +1.
* @public
*/
setHeatingCoolingAmount( normalizedHeatingCoolingAmount ) {
assert && assert( ( normalizedHeatingCoolingAmount <= 1.0 ) && ( normalizedHeatingCoolingAmount >= -1.0 ) );
this.heatingCoolingAmountProperty.set( normalizedHeatingCoolingAmount );
}
/**
* Inject a new molecule of the current type. This method actually queues it for injection, actual injection
* occurs during model steps. Be aware that this silently ignores the injection request if the model is not in a
* state to support injection.
* @private
*/
queueMoleculeForInjection() {
this.numMoleculesQueuedForInjectionProperty.set( this.numMoleculesQueuedForInjectionProperty.value + 1 );
}
/**
* Inject a new molecule of the current type into the model. This uses the current temperature to assign an initial
* velocity.
* @private
*/
injectMolecule() {
assert && assert(
this.numMoleculesQueuedForInjectionProperty.value > 0,
'this method should not be called when nothing is queued for injection'
);
assert && assert(
this.moleculeDataSet.getNumberOfRemainingSlots() > 0,
'injection attempted when there is no room in the data set'
);
// Choose an injection angle with some amount of randomness.
const injectionAngle = ( phet.joist.random.nextDouble() - 0.5 ) * INJECTED_MOLECULE_ANGLE_SPREAD;
// Set the molecule's velocity.
const xVel = Math.cos( injectionAngle ) * INJECTED_MOLECULE_SPEED;
const yVel = Math.sin( injectionAngle ) * INJECTED_MOLECULE_SPEED;
// Set the rotational velocity to a random value within a range (will be ignored for single atom cases).
const moleculeRotationRate = ( phet.joist.random.nextDouble() - 0.5 ) * ( Math.PI / 4 );
// Set the position(s) of the atom(s).
const atomsPerMolecule = this.moleculeDataSet.atomsPerMolecule;
const moleculeCenterOfMassPosition = this.injectionPoint.copy();
const moleculeVelocity = new Vector2( xVel, yVel );
const atomPositions = [];
for ( let i = 0; i < atomsPerMolecule; i++ ) {
atomPositions[ i ] = Vector2.ZERO;
}
// Add the newly created molecule to the data set.
this.moleculeDataSet.addMolecule(
atomPositions,
moleculeCenterOfMassPosition,
moleculeVelocity,
moleculeRotationRate,
true
);
if ( atomsPerMolecule > 1 ) {
// randomize the rotational angle of multi-atom molecules
this.moleculeDataSet.moleculeRotationAngles[ this.moleculeDataSet.getNumberOfMolecules() - 1 ] =
phet.joist.random.nextDouble() * 2 * Math.PI;
}
// Position the atoms that comprise the molecules.
this.atomPositionUpdater.updateAtomPositions( this.moleculeDataSet );
// add the non-normalized atoms
this.addAtomsForCurrentSubstance( 1 );
this.syncAtomPositions();
this.moleculeInjectedThisStep = true;
this.numMoleculesQueuedForInjectionProperty.set( this.numMoleculesQueuedForInjectionProperty.value - 1 );
}
/**
* add non-normalized atoms for the specified number of molecules of the current substance
* @param {number} numMolecules
* @private
*/
addAtomsForCurrentSubstance( numMolecules ) {
_.times( numMolecules, () => {
switch( this.substanceProperty.value ) {
case SubstanceType.ARGON:
this.scaledAtoms.push( new ScaledAtom( AtomType.ARGON, 0, 0 ) );
break;
case SubstanceType.NEON:
this.scaledAtoms.push( new ScaledAtom( AtomType.NEON, 0, 0 ) );
break;
case SubstanceType.ADJUSTABLE_ATOM:
this.scaledAtoms.push( new ScaledAtom( AtomType.ADJUSTABLE, 0, 0 ) );
break;
case SubstanceType.DIATOMIC_OXYGEN:
this.scaledAtoms.push( new ScaledAtom( AtomType.OXYGEN, 0, 0 ) );
this.scaledAtoms.push( new ScaledAtom( AtomType.OXYGEN, 0, 0 ) );
break;
case SubstanceType.WATER:
this.scaledAtoms.push( new ScaledAtom( AtomType.OXYGEN, 0, 0 ) );
this.scaledAtoms.push( new HydrogenAtom( 0, 0, true ) );
this.scaledAtoms.push( new HydrogenAtom( 0, 0, phet.joist.random.nextDouble() > 0.5 ) );
break;
default:
this.scaledAtoms.push( new ScaledAtom( AtomType.NEON, 0, 0 ) );
break;
}
} );
}
/**
* @private
*/
removeAllAtoms() {
// Get rid of any existing atoms from the model set.
this.scaledAtoms.clear();
// Get rid of the normalized atoms too.
this.moleculeDataSet = null;
}
/**
* Initialize the normalized and non-normalized data sets by calling the appropriate initialization routine, which
* will set positions, velocities, etc.
* @param {number} phase - phase of atoms
* @public
*/
initializeAtoms( phase ) {
// Initialize the atoms.
switch( this.substanceProperty.get() ) {
case SubstanceType.DIATOMIC_OXYGEN:
this.initializeDiatomic( this.substanceProperty.get(), phase );
break;
case SubstanceType.NEON:
this.initializeMonatomic( this.substanceProperty.get(), phase );
break;
case SubstanceType.ARGON:
this.initializeMonatomic( this.substanceProperty.get(), phase );
break;
case SubstanceType.ADJUSTABLE_ATOM:
this.initializeMonatomic( this.substanceProperty.get(), phase );
break;
case SubstanceType.WATER:
this.initializeTriatomic( this.substanceProperty.get(), phase );
break;
default:
throw( new Error( 'unsupported substance' ) ); // should never happen, debug if it does
}
// This is needed in case we were switching from another molecule that was under pressure.
this.updatePressure();
}
/**
* @private
*/
initializeModelParameters() {
// Initialize the system parameters.
this.gravitationalAcceleration = NOMINAL_GRAVITATIONAL_ACCEL;
this.heatingCoolingAmountProperty.reset();
this.temperatureSetPointProperty.reset();
this.isExplodedProperty.reset();
}
/**
* Reduce the upward motion of the molecules. This is generally done to reduce some behavior that is sometimes seen
* where the molecules float rapidly upwards after being heated.
* @param {number} dt
* @private
*/
dampUpwardMotion( dt ) {
for ( let i = 0; i < this.moleculeDataSet.getNumberOfMolecules(); i++ ) {
if ( this.moleculeDataSet.moleculeVelocities[ i ].y > 0 ) {
this.moleculeDataSet.moleculeVelocities[ i ].y *= 1 - ( dt * 0.9 );
}
}
}
/**
* Update the normalized full-size container dimensions based on the current particle diameter.
* @private
*/
updateNormalizedContainerDimensions() {
this.normalizedContainerWidth = CONTAINER_WIDTH / this.particleDiameter;
// The non-normalized height will keep increasing after the container explodes, so we need to limit it here.
const nonNormalizedContainerHeight = Math.min( this.containerHeightProperty.value, CONTAINER_INITIAL_HEIGHT );
this.normalizedContainerHeight = nonNormalizedContainerHeight / this.particleDiameter;
this.normalizedTotalContainerHeight = nonNormalizedContainerHeight / this.particleDiameter;
}
/**
* Step the model.
* @param {number} dt - delta time, in seconds
* @public
*/
stepInTime( dt ) {
this.moleculeInjectedThisStep = false;
// update the size of the container, which can be affected by exploding or other external factors
this.updateContainerSize( dt );
// Record the pressure to see if it changes.
const pressureBeforeAlgorithm = this.getModelPressure();
// Calculate the amount of time to advance the particle engine. This is based purely on aesthetics - we looked at
// the particle motion and tweaked the multiplier until we felt that it looked good.
const particleMotionAdvancementTime = dt * PARTICLE_SPEED_UP_FACTOR;
// Determine the number of model steps and the size of the time step.
let numParticleEngineSteps = 1;
let particleMotionTimeStep;
if ( particleMotionAdvancementTime > MAX_PARTICLE_MOTION_TIME_STEP ) {
particleMotionTimeStep = MAX_PARTICLE_MOTION_TIME_STEP;
numParticleEngineSteps = Math.floor( particleMotionAdvancementTime / MAX_PARTICLE_MOTION_TIME_STEP );
this.residualTime = particleMotionAdvancementTime - ( numParticleEngineSteps * particleMotionTimeStep );
}
else {
particleMotionTimeStep = particleMotionAdvancementTime;
}
if ( this.residualTime > particleMotionTimeStep ) {
numParticleEngineSteps++;
this.residualTime -= particleMotionTimeStep;
}
// Inject a new molecule if there is one ready and it isn't too soon after a previous injection. This is done
// before execution of the Verlet algorithm so that its velocity will be taken into account when the temperature
// is calculated.
if ( this.numMoleculesQueuedForInjectionProperty.value > 0 && this.moleculeInjectionHoldoffTimer === 0 ) {
this.injectMolecule();
this.moleculeInjectionHoldoffTimer = MOLECULE_INJECTION_HOLDOFF_TIME;
}
else if ( this.moleculeInjectionHoldoffTimer > 0 ) {
this.moleculeInjectionHoldoffTimer = Math.max( this.moleculeInjectionHoldoffTimer - dt, 0 );
}
// Execute the Verlet algorithm, a.k.a. the "particle engine", in order to determine the new atom positions.
for ( let i = 0; i < numParticleEngineSteps; i++ ) {
this.moleculeForceAndMotionCalculator.updateForcesAndMotion( particleMotionTimeStep );
}
// Sync up the positions of the normalized molecules (the molecule data set) with the atoms being monitored by the
// view (the model data set).
this.syncAtomPositions();
// run the thermostat to keep particle energies from getting out of hand
this.runThermostat();
// If the pressure changed, update it.
if ( this.getModelPressure() !== pressureBeforeAlgorithm ) {
this.updatePressure();
}
// Adjust the temperature set point if needed.
const currentTemperature = this.temperatureSetPointProperty.get(); // convenience variable
if ( this.heatingCoolingAmountProperty.get() !== 0 ) {
let newTemperature;
if ( currentTemperature < APPROACHING_ABSOLUTE_ZERO_TEMPERATURE &&
this.heatingCoolingAmountProperty.get() < 0 ) {
// The temperature adjusts more slowly as we begin to approach absolute zero so that all the molecules have
// time to reach the bottom of the container. This is not linear - the rate of change slows as we get closer,
// to zero degrees Kelvin, which is somewhat real world-ish.
const adjustmentFactor = Math.pow(
currentTemperature / APPROACHING_ABSOLUTE_ZERO_TEMPERATURE,
1.35 // exponent chosen empirically to be as small as possible and still get all molecules to bottom before absolute zero
);
newTemperature = currentTemperature +
this.heatingCoolingAmountProperty.get() * TEMPERATURE_CHANGE_RATE * dt * adjustmentFactor;
}
else {
const temperatureChange = this.heatingCoolingAmountProperty.get() * TEMPERATURE_CHANGE_RATE * dt;
newTemperature = Math.min( currentTemperature + temperatureChange, MAX_TEMPERATURE );
}
// Prevent the substance from floating up too rapidly when heated.
if ( currentTemperature < LIQUID_TEMPERATURE && this.heatingCoolingAmountProperty.get() > 0 ) {
// This is necessary to prevent the substance from floating up when heated from absolute zero.
this.dampUpwardMotion( dt );
}
// Jump to the minimum model temperature if the substance has reached absolute zero.
if ( this.heatingCoolingAmountProperty.get() <= 0 &&
this.getTemperatureInKelvin() === 0 &&
newTemperature > MIN_TEMPERATURE ) {
// Absolute zero has been reached for this substance. Set the temperature to the minimum allowed value to
// minimize motion in the molecules.
newTemperature = MIN_TEMPERATURE;
}
// record the new set point
this.temperatureSetPointProperty.set( newTemperature );
this.isoKineticThermostat.targetTemperature = newTemperature;
this.andersenThermostat.targetTemperature = newTemperature;
}
}
/**
* @param {number} dt - time in seconds
* @protected
*/
updateContainerSize( dt ) {
if ( this.isExplodedProperty.value ) {
// The lid is blowing off the container - increase the container size until the lid is well off the screen.
this.heightChangeThisStep = POST_EXPLOSION_CONTAINER_EXPANSION_RATE * dt;
if ( this.containerHeightProperty.get() < CONTAINER_INITIAL_HEIGHT * 3 ) {
this.containerHeightProperty.set(
this.containerHeightProperty.get() + POST_EXPLOSION_CONTAINER_EXPANSION_RATE * dt
);
}
}
else {
// no changes to the height in this step
this.heightChangeThisStep = 0;
this.normalizedLidVelocityY = 0;
}
}
/**
* main step function, called by the PhET framework
* @param {number} dt
* @public
*/
step( dt ) {
if ( this.isPlayingProperty.get() ) {
this.stepInTime( dt );
}
}
/**
* Run the appropriate thermostat based on the settings and the state of the simulation. This serves to either
* maintain the particle motions in a range that corresponds to a steady temperature or to increase or decrease the
* particle motion if the user is heating or cooling the substance.
* @private
*/
runThermostat() {
if ( this.isExplodedProperty.get() ) {
// Don't bother to run any thermostat if the lid is blown off - just let those little molecules run free!
return;
}
const calculatedTemperature = this.moleculeForceAndMotionCalculator.calculatedTemperature;
const temperatureSetPoint = this.temperatureSetPointProperty.get();
let temperatureAdjustmentNeeded = false;
let thermostatRunThisStep = null;
if ( this.heatingCoolingAmountProperty.get() > 0 && calculatedTemperature < temperatureSetPoint ||
this.heatingCoolingAmountProperty.get() < 0 && calculatedTemperature > temperatureSetPoint ||
Math.abs( calculatedTemperature - temperatureSetPoint ) > TEMPERATURE_CLOSENESS_RANGE ) {
temperatureAdjustmentNeeded = true;
}
if ( this.moleculeInjectedThisStep ) {
// A molecule was injected this step. By design, only one can be injected in a single step, so we use the
// attributes of the most recently added molecule to figure out how much the temperature set point should be
// adjusted. No thermostat is run on this step - it will kick in on the next step.
const numMolecules = this.moleculeDataSet.getNumberOfMolecules();
const injectedParticleTemperature = ( 2 / 3 ) * this.moleculeDataSet.getMoleculeKineticEnergy( numMolecules - 1 );
const newTemperature = temperatureSetPoint * ( numMolecules - 1 ) / numMolecules +