# Class MoleculeSim

Simulation of a 'molecule' made of 2 or more masses with springs between, moving freely in 2D, and bouncing against the four walls.

## Variables and Parameters

Here is a diagram of two masses showing the definition of the angle `th`:

``````       m2     .
\     .
\ th .
\   .
\  .
\ .
m1
``````

Variables:

``````U1, U2 = position of center of mass of atom 1 or 2
V1, V2 = velocity of atom 1 or 2
th = angle with vertical (radians); 0 = up; positive is counter clockwise
L = displacement of spring from rest length
F1, F2 = force on atom
``````

Parameters:

``````m1, m2 = masses of atom 1 and 2
R = rest length of spring
k = spring constant
b = damping constant
``````

## Equations of Motion

For each pair of masses, they experience the following forces from the spring connecting them (but the damping force occurs only once for each mass).

``````F1x = k L sin(th) -b V1x = m1 V1x'
F1y = -m1 g +k L cos(th) -b V1y = m1 V1y'
F2x = -k L sin(th) -b V2x = m2 V2x'
F2y = -m2 g -k L cos(th) -b V2y = m2 V2y'
xx = U2x - U1x
yy = U2y - U1y
len = sqrt(xx^2+yy^2)
L = len - R
cos(th) = yy / len
sin(th) = xx / len
``````

## Variables Array

Variables are stored in a VarsList. Each PointMass gets a set of four contiguous variables that describe its current position and velocity. The variables are laid out as follows:

1. `x` horizontal world coords position of center of mass
2. `y` vertical world coords position of center of mass
3. `x'` horizontal velocity of center of mass. AKA `vx`
4. `y'` vertical velocity of center of mass. AKA `vy`

Variables at the beginning of the VariablesList:

• time
• kinetic energy
• potential energy
• total energy

## Contact Force

We detect when an atom is in resting contact with floor or wall. Consider contact with the floor. Suppose the atom is 'close' to the floor, then there are 3 cases:

1. vertical velocity is 'large' and positive. Then the atom is separating from the floor, so nothing needs to be done.

2. vertical velocity is 'large' and negative. A collision is imminent, so let the collision software handle this case.

3. vertical velocity is 'small'. Now the atom is likely in contact with the floor. There are two cases:

a. Net force positive: atom is being pulled off floor. In this case do nothing, there is no reaction force from the floor.

b. Net force negative: atom is being pulled downwards. Here, we set the net force to zero, because the force is resisted by the reaction force from the floor.

## How small is 'small' velocity?

We are trying to avoid the case where there is a tiny upwards velocity and a large downwards force, which just results in zillions of collisions over the time step we are solving (typically about 0.03 seconds). Instead, we assume that the atom stops bouncing and comes into contact with the floor in this case.

For a given force (assuming it stays approx constant over the time span of 0.03 seconds), there is an 'escape velocity' that would allow the atom to leave contact and be above the floor at the end of the time step.

Let

``````h = time step
F = force
m = mass
v0 = initial vertical velocity
``````

Then we have (using simple calculus; 2 integrations)

``````v' = F/m
v = (F/m)t + v0
y = (F/2m)t^2 + v0*t
``````

Requiring the atom to be below the floor at time h gives the condition

``````0 > y = (F/2m)h^2 + v0*h
``````

Dividing by h gives

``````0 > F*h/2m + v0
-F*h/2m > v0
``````

For the case of interest, we have that `F` is a large downward force, so `F << 0`. If the initial velocity `v0` is less than `-F*h/2m` then (assuming constant F over the timespan `h`) the atom starting at the floor will still be on or below the floor at the end of the timespan `h`.

This is our definition of a small velocity. Note that it depends on the net force. Because with a large downward force, it would take a big velocity to actually result in contact being lost at the end of the time period. Equivalently, if there is just a slight downward force (e.g. spring almost offsetting gravity), then just a little velocity is enough to result in contact being broken.

## Properties

collisionFunction_: null | ((c, t) => void) = null

Function to print collisions, or null to turn off printing collisions.

#### Type declaration

• (c, t): void

#### Returns void

debugPaint_: null | (() => void) = null

Function to paint canvases, for debugging. If defined, this will be called within `moveObjects()` so you can see the simulation state after each time step (you will need to arrange your debugger to pause after each invocation of debugPaint_ to see the state).

• (): void
• #### Returns void

distTol_: number = 0.02

distance tolerance: how close to a wall to be in resting contact

dragAtom_: number = -1

the atom being dragged, or -1 when no drag is happening

initialState_: null | number[] = null

Initial values.

potentialOffset_: number = 0

potential energy offset

timeStep_: number = 0.03

length of timeStep, used in resting contact calculation

## Methods

• Adds a PointMass to the simulation, and gets the initial conditions from that atom.

#### Parameters

• ##### atom: PointMass

the PointMass to add to the simulation

• #### Parameters

• ##### side: Side

which side of the wall colliding with

#### Returns void

• Adds the given Observer to this Subject's list of Observers, so that the Observer will be notified of changes in this Subject. An Observer may call `Subject.addObserver` during its `observe` method.

#### Returns void

• Adds the Parameter to the list of this Subject's available Parameters.

#### Throws

if a Parameter with the same name already exists.

• Adds a Spring to the simulation.

#### Parameters

• ##### spring: Spring

the Spring to add to the simulation

#### Returns void

• Notifies all Observers that the Parameter with the given name has changed by calling observe on each Observer.

#### Parameters

• ##### name: string

the language-independent or English name of the Parameter that has changed

#### Throws

if there is no Parameter with the given name

• Defines the differential equations of this ODESim; for an input set of variables, returns the current rate of change for each variable (the first derivative of each variable with respect to time).

The `timeStep` is the time since the state variables were last fully calculated, which can be and often is zero. The current time can be regarded as `getTime() + timeStep`. The input variables correspond to the Simulation state at that time. Note that `timeStep` is different from the time step used to advance the Simulation (as in AdvanceStrategy.advance). The `timeStep` is typically used when finding collisions in CollisionSim.findCollisions.

#### Parameters

• ##### vars: number[]

the current array of state variables (input), corresponding to the state at `getTime() + timeStep`

• ##### change: number[]

array of change rates for each variable (output), all values are zero on entry.

• ##### _timeStep: number

the current time step (might be zero)

#### Returns null | object

`null` if the evaluation succeeds, otherwise an object relating to the error that occurred. The `change` array contains the output results.

• Finds collisions based on the passed in state variables. Can rely on modifyObjects having been called prior, with this set of state variables. Uses the state saved by saveState as the 'before' state for comparison.

The list of collisions that are passed in can potentially have collisions from the near future that were found previously. The CollisionSim should avoid adding collisions that are duplicates of those already on the list.

#### Parameters

• ##### collisions: MoleculeCollision[]

the list of collisions to add to

• ##### vars: number[]

the current array of state variables

• ##### stepSize: number

the size of the current time step, in seconds

#### Returns void

• Called at the end of a mouse drag operation, performs whatever action is appropriate. Only called if startDrag returned `true`.

#### Parameters

• ##### _simObject: null | SimObject

the SimObject being dragged, or `null` if no SimObject was found

• ##### _location: Vector

the location of the mouse in simulation coordinates of the SimView where `simObject` was found, or in the focus view if `simObject` is `null`.

• ##### _offset: Vector

distance from the initial object position to the mouse location at start of drag.

#### Returns void

• Returns the Parameter with the given name.

#### Parameters

• ##### name: string

the language-independent or English name of the Parameter

#### Returns Parameter

the Parameter with the given name

#### Throws

if there is no Parameter with the given name

• Returns the name of the specified variable for the given atom.

#### Parameters

• ##### atom: PointMass

the PointMass of interest

• ##### index: number

which variable name is desired: 0 = x-position, 1 = x-velocity, 2 = y-position, 3 = y-velocity

• ##### localized: boolean

whether to return localized variable name

#### Returns string

the name of the specified variable for the given atom

• Adjusts the simulation state based on the given Collisions. For example, this might reverse the velocities of objects colliding against a wall. The simulation state is contained in the `vars` array of state variables from getVarsList.

Note that these Collisions will typically be from the very near future; CollisionAdvance backs up to just before the moment of collision before handling Collisions.

#### Parameters

• ##### collisions: MoleculeCollision[]

the list of current collisions

• ##### `Optional`opt_totals: CollisionTotals

CollisionTotals object to update with number of collisions handled

#### Returns boolean

true if was able to handle the collision, changing state of simulation.

• Called when a key is pressed or released, performs whatever action is appropriate for that event.

#### Parameters

• ##### _evt: KeyboardEvent

the KeyboardEvent that happened

• ##### _pressed: boolean

`true` means this is a key-down event; `false` means a key-up event

• ##### _modifiers: ModifierKeys

the modifier keys down during event

#### Returns void

• Sets the simulation variables to match the atom's state (by copying the atom's position and velocity to the simulation's VarsList).

#### Parameters

• ##### atom: PointMass

the PointMass to use for updating the simulation variables

#### Returns void

• Called at each movement during a mouse drag, performs whatever action is appropriate. Only called if startDrag returned `true`. The SimObject being moved is passed in, along with the current mouse position, in simulation coordinates, and an offset calculated at the start of the drag.

Setting the SimObject position to `(x - offsetX, y - offsetY)` will move the SimObject smoothly along with the mouse movement.

#### Parameters

• ##### simObject: null | SimObject

the SimObject being dragged, or `null` if no SimObject was found

• ##### location: Vector

the location of the mouse in simulation coordinates of the SimView where `simObject` was found, or in the focus view if `simObject` is `null`.

• ##### offset: Vector

distance from the initial object position (from DisplayObject.getPosition) to the mouse location at start of drag.

#### Returns void

• Removes the Observer from this Subject's list of Observers. An Observer may call `removeObserver` during its `observe` method.

#### Parameters

• ##### observer: Observer

the Observer to detach from list of Observers

#### Returns void

• Removes the Parameter from the list of this Subject's available Parameters.

#### Parameters

• ##### parameter: Parameter

the Parameter to remove

#### Returns void

• Sets whether this Subject will broadcast events, typically used to temporarily disable broadcasting. Intended to be used in situations where a subclass overrides a method that broadcasts an event. This allows the subclass to prevent the superclass broadcasting that event, so that the subclass can broadcast the event when the method is completed.

#### Parameters

• ##### value: boolean

whether this Subject should broadcast events

#### Returns boolean

the previous value

• Sets a function for printing collisions. The function is called whenever a collision occurs. The function takes two variables: a MoleculeCollision and a Terminal. This can be defined from within the Terminal by the user. Here is an example usage

``````sim.setCollisionFunction(function(c,t) {  const s = c.getDetectedTime().toFixed(2)+"\t"    +c.getImpulse().toFixed(2)+"\t"    +c.atom.getPosition().getX().toFixed(2)+"\t"    +c.atom.getPosition().getY().toFixed(2)+"\t"    +c.atom.getName()+"\t"    +c.side;  t.println(s);})
``````

#### Parameters

• ##### f: null | ((c, t) => void)

the function to print collisions,

• or null to turn off printing collisions

• Set damping

damping

#### Returns void

• For debugging, specify a function that will paint canvases, so that you can see the simulation while stepping thru with debugger.

#### Parameters

• ##### fn: null | (() => void)

function that will paint canvases

#### Returns void

• Set elasticity

elasticity

#### Returns void

• Set gravity strength.

#### Parameters

• ##### value: number

gravity strength

#### Returns void

• Sets the potential energy offset.

#### Parameters

• ##### value: number

the potential energy offset

#### Returns void

• Sets the Terminal object that this simulation can print data into.

#### Parameters

• ##### terminal: null | Terminal

the Terminal object that this simulation can print data into.

#### Returns void

• Sets the VarsList for this simulation.

#### Parameters

• ##### varsList: VarsList

the VarsList to use in this simulation

#### Returns void

• Sets the single PointMass that represents the walls.

#### Parameters

• ##### walls: PointMass

the single PointMass that represents the walls.

#### Returns void

• Called at the start of a mouse drag. The nearest dragable SimObject is passed in, along with mouse position in simulation coordinates. If no dragable SimObject was found, `null` is passed for the first argument. If the EventHandler does not recognize the SimObject then it should return `false`.

#### Parameters

• ##### simObject: null | SimObject

the SimObject that is nearest to the mouse drag coordinates, or `null` if no SimObject was found

• ##### _location: Vector

the location of the mouse in simulation coordinates of the SimView where `simObject` was found, or in the focus view if `simObject` is `null`.

• ##### _offset: Vector

distance from the initial object position (from DisplayObject.getPosition) to the mouse location at start of drag

• ##### _dragBody: null | Vector

location of 'drag point' on the SimObject in body coordinates of the SimObject; this is where for example a spring will be attached on the SimObject when dragging; or `null` when no SimObject was found

• ##### _modifiers: ModifierKeys

the modifier keys down during event

#### Returns boolean

`true` if the EventHandler will handle dragging the SimObject

• Returns a minimal string representation of this object, usually giving just identity information like the class name and name of the object.

For an object whose main purpose is to represent another Printable object, it is recommended to include the result of calling `toStringShort` on that other object. For example, calling `toStringShort()` on a DisplayShape might return something like this:

``````DisplayShape{polygon:Polygon{'chain3'}}
``````

#### Returns string

a minimal string representation of this object.

Generated using TypeDoc