/*
PER-BODY MAIN PHYSICS ROUTINE
508575
function iterateBody(self, b, dt, noGravity) {
    vec3.copy(oldResting, b.resting)

    // treat bodies with <= mass as static
    if (b.mass <= 0) {
        vec3.set(b.velocity, 0, 0, 0)
        vec3.set(b._forces, 0, 0, 0)
        vec3.set(b._impulses, 0, 0, 0)
        return
    }

    // skip bodies if static or no velocity/forces/impulses
    var localNoGrav = noGravity || (b.gravityMultiplier === 0)
    if (bodyAsleep(self, b, dt, localNoGrav)) return
    b._sleepFrameCount--

    // check if under water, if so apply buoyancy and drag forces
    applyFluidForces(self, b)

    // debug hooks
    sanityCheck(b._forces)
    sanityCheck(b._impulses)
    sanityCheck(b.velocity)
    sanityCheck(b.resting)

    // semi-implicit Euler integration

    // a = f/m + gravity*gravityMultiplier
    vec3.scale(a, b._forces, 1 / b.mass)
    vec3.scaleAndAdd(a, a, self.gravity, b.gravityMultiplier)

    // dv = i/m + a*dt
    // v1 = v0 + dv
    vec3.scale(dv, b._impulses, 1 / b.mass)
    vec3.scaleAndAdd(dv, dv, a, dt)
    vec3.add(b.velocity, b.velocity, dv)

    // apply friction based on change in velocity this frame
    if (b.friction) {
        applyFrictionByAxis(0, b, dv)
        applyFrictionByAxis(1, b, dv)
        applyFrictionByAxis(2, b, dv)
    }

    // linear air or fluid friction - effectively v *= drag
    // body settings override global settings
    var drag = (b.airDrag >= 0) ? b.airDrag : self.airDrag
    if (b.inFluid) {
        drag = (b.fluidDrag >= 0) ? b.fluidDrag : self.fluidDrag
        drag *= 1 - (1 - b.ratioInFluid) ** 2
    }
    var mult = Math.max(1 - drag * dt / b.mass, 0)
    vec3.scale(b.velocity, b.velocity, mult)

    // x1-x0 = v1*dt
    vec3.scale(dx, b.velocity, dt)

    // clear forces and impulses for next timestep
    vec3.set(b._forces, 0, 0, 0)
    vec3.set(b._impulses, 0, 0, 0)

    // cache old position for use in autostepping
    if (b.autoStep) {
        cloneAABB(tmpBox, b.aabb)
    }

    // sweeps aabb along dx and accounts for collisions
    processCollisions(self, b.aabb, dx, b.resting)

    // if autostep, and on ground, run collisions again with stepped up aabb
    if (b.autoStep) {
        tryAutoStepping(self, b, tmpBox, dx)
    }

    // Collision impacts. b.resting shows which axes had collisions:
    for (var i = 0; i < 3; ++i) {
        impacts[i] = 0
        if (b.resting[i]) {
            // count impact only if wasn't collided last frame
            if (!oldResting[i]) impacts[i] = -b.velocity[i]
            b.velocity[i] = 0
        }
    }
    var mag = vec3.length(impacts)
    if (mag > .001) { // epsilon
        // bounce if over minBounceImpulse
        if (mag > self.minBounceImpulse && b.restitution) {
            vec3.scale(impacts, impacts, b.restitution * b.mass)
            b.applyImpulse(impacts)
        }
        // send collision event regardless
        if (b.onCollide) b.onCollide(impacts)
    }


    // sleep check
    var vsq = vec3.squaredLength(b.velocity)
    if (vsq > 1e-5) b._markActive()
}
146666
function FrictionJoint(def, bodyA, bodyB, anchor) {
  if (!(this instanceof FrictionJoint)) {
    return new FrictionJoint(def, bodyA, bodyB, anchor);
  }

  def = options(def, DEFAULTS);
  Joint.call(this, def, bodyA, bodyB);
  bodyA = this.m_bodyA;
  bodyB = this.m_bodyB;

  this.m_type = FrictionJoint.TYPE;

  this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero();
  this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero();

  // Solver shared
  this.m_linearImpulse = Vec2.zero();
  this.m_angularImpulse = 0.0;
  this.m_maxForce = def.maxForce;
  this.m_maxTorque = def.maxTorque;

  // Solver temp
  this.m_rA; // Vec2
  this.m_rB; // Vec2
  this.m_localCenterA; // Vec2
  this.m_localCenterB; // Vec2
  this.m_invMassA; // float
  this.m_invMassB; // float
  this.m_invIA; // float
  this.m_invIB; // float
  this.m_linearMass; // Mat22
  this.m_angularMass; // float

  // Point-to-point constraint
  // Cdot = v2 - v1
  // = v2 + cross(w2, r2) - v1 - cross(w1, r1)
  // J = [-I -r1_skew I r2_skew ]
  // Identity used:
  // w k % (rx i + ry j) = w * (-ry i + rx j)

  // Angle constraint
  // Cdot = w2 - w1
  // J = [0 0 -1 0 0 1]
  // K = invI1 + invI2
}
444995
def energy(q, v):
    """"""
    
    # Number of points
    N: int = len(q)
    
    # Initialize arrays to zero of the correct size
    T: np.ndarray = np.zeros(N)
    U: np.ndarray = np.zeros(N)    
    
    # Add up kinetic energy of each body
    for i in range(B):
        # Kinetic energy is 1/2 mv^2
        m = mass[i]
        vi = v[:, slices[i]]
        T += 0.5 * m * np.sum(vi * vi, axis=1)
    
    # Add up potential energy of each pair of bodies
    for i in range(B):
        for j in range(i+1, B):
            # Masses of these two bodies
            mi = mass[i]
            mj = mass[j]
        
            # Positions of body i and j
            qi: np.ndarray = q[:, slices[i]]
            qj: np.ndarray = q[:, slices[j]]
        
            # Potential energy is -G m1 m2  / r
            dv_ij = qj - qi
            r_ij = np.linalg.norm(dv_ij, axis=1)
            U -= G * mi * mj * 1.0 / r_ij
    
    # Total energy H = T + U
    H = T + U
    
    return H, T, U
1013195
def accel(q: np.ndarray):
    

    # Infer number of dimensions from q
    dims: int = len(q)

    # Initialize acceleration as dimsx1 array
    a: np.ndarray = np.zeros(dims)
    
    # Iterate over each distinct pair of bodies
    for i in range(B):
        for j in range(i+1, B):
    
            # Masses of body i and j
            m0 = mass[i]
            m1 = mass[j]
        
            # Extract position of body i and j as 3-vectors
            pos_0 = q[slices[i]]
            pos_1 = q[slices[j]]
        
            # Displacement vector from body i to body j
            dv_01: np.ndarray = pos_1 - pos_0
        
            # Distance from body i to j
            r_01: float = np.linalg.norm(dv_01)
            
            # Unit vector pointing from body i to body j
            udv_01 = dv_01 / r_01
        
            # The force between these has magnitude G*m0*m1 / r^2
            f_01: float = (G * m0 * m1) / (r_01 ** 2)
            
            # The force vectors are attractive
            a[slices[i]] += f_01 * udv_01 / m0
            a[slices[j]] -= f_01 * udv_01 / m1
        
    # Return the acceleration vector
    return a
950294
public void addBody(final GVRRigidBody gvrBody) {
        mPhysicsContext.runOnPhysicsThread(new Runnable() {
            @Override
            public void run() {
                if (contains(gvrBody)) {
                    return;
                }

                if (gvrBody.getCollisionGroup() < 0 || gvrBody.getCollisionGroup() > 15
                        || mCollisionMatrix == null) {
                    NativePhysics3DWorld.addRigidBody(getNative(), gvrBody.getNative());
                } else {
                    NativePhysics3DWorld.addRigidBodyWithMask(getNative(), gvrBody.getNative(),
                            mCollisionMatrix.getCollisionFilterGroup(gvrBody.getCollisionGroup()),
                            mCollisionMatrix.getCollisionFilterMask(gvrBody.getCollisionGroup()));
                }

                mPhysicsObject.put(gvrBody.getNative(), gvrBody);
                getGVRContext().getEventManager().sendEvent(GVRWorld.this, IPhysicsEvents.class, "onAddRigidBody", GVRWorld.this, gvrBody);
            }
        });
    }
294032
function( data ){

            var self = this
                ,col
                ,collisions = data.collisions// Physics.util.shuffle(data.collisions)
                ,i,l,b
                ;

            for ( i = 0, l = collisions.length; i < l; ++i ){

                col = collisions[ i ];
                // add bodies to list for later
                this._pushUniq( col.bodyA );
                this._pushUniq( col.bodyB );
                // ensure they have mtv stat vectors
                col.bodyA._mtvTotal = col.bodyA._mtvTotal || new Physics.vector();
                col.bodyB._mtvTotal = col.bodyB._mtvTotal || new Physics.vector();
                col.bodyA._oldmtvTotal = col.bodyA._oldmtvTotal || new Physics.vector();
                col.bodyB._oldmtvTotal = col.bodyB._oldmtvTotal || new Physics.vector();

                self.collideBodies(
                    col.bodyA,
                    col.bodyB,
                    col.norm,
                    col.pos,
                    col.mtv,
                    col.collidedPreviously
                );
            }

            // apply mtv vectors from the average mtv vector
            for ( i = 0, l = this._bodyList.length; i < l; ++i ){
                b = this._bodyList.pop();
                // clampMTV( b._oldmtvTotal, b._mtvTotal, b._mtvTotal );

                if ( b._mtvTotal.normSq() < this.options.mtvThreshold ){
                    b._mtvTotal.mult( this.options.bodyExtractDropoff );
                } else if ( this.options.forceWakeupAboveOverlapThreshold ) {
                    // wake up bodies if necessary
                    b.sleep( false );
                }

                b.state.pos.vadd( b._mtvTotal );
                b.state.old.pos.vadd( b._mtvTotal );
                b._oldmtvTotal.swap( b._mtvTotal );
                b._mtvTotal.zero();
            }
        }
921385
function RigidBody(_aabb, mass, friction, restitution, gravMult, onCollide, autoStep) {
    this.aabb = new aabb(_aabb.base, _aabb.vec) // clone
    this.mass = mass
    this.friction = friction
    this.restitution = restitution
    this.gravityMultiplier = gravMult
    this.onCollide = onCollide
    this.autoStep = !!autoStep
    this.airDrag = -1   // overrides global airDrag when >= 0
    this.fluidDrag = -1 // overrides global fluidDrag when >= 0
    this.onStep = null
    
    // internals
    this.velocity = vec3.create()
    this.resting = [0, 0, 0]
    this.inFluid = false
    this._ratioInFluid = 0
    this._forces = vec3.create()
    this._impulses = vec3.create()
    this._sleepFrameCount = 10 | 0
}
697579
function checkPair( bodyA, bodyB ){

        // filter out bodies that don't collide with each other
        if (
            ( bodyA.treatment === 'static' || bodyA.treatment === 'kinematic' ) &&
            ( bodyB.treatment === 'static' || bodyB.treatment === 'kinematic' )
        ){
            return false;
        }

        if ( bodyA.geometry.name === 'circle' && bodyB.geometry.name === 'circle' ){

            return checkCircles( bodyA, bodyB );

        } else if ( bodyA.geometry.name === 'compound' || bodyB.geometry.name === 'compound' ){
            // compound bodies are special. We can't use gjk because
            // they could have concavities. so we do the pieces individually
            var test = (bodyA.geometry.name === 'compound')
                ,compound = test ? bodyA : bodyB
                ,other = test ? bodyB : bodyA
                ,cols
                ,ch
                ,ret = []
                ,scratch = Physics.scratchpad()
                ,vec = scratch.vector()
                ,oldPos = scratch.vector()
                ,otherAABB = other.aabb()
                ,i
                ,l
                ;

            for ( i = 0, l = compound.children.length; i < l; i++ ){

                ch = compound.children[ i ];
                // move body to fake position
                oldPos.clone( ch.state.pos );
                ch.offset.vadd( oldPos.vadd( compound.offset ).rotate( -ch.state.angular.pos ) );
                ch.state.pos.clone( compound.state.pos );
                ch.state.angular.pos += compound.state.angular.pos;

                // check it if the aabbs overlap
                if ( Physics.aabb.overlap(otherAABB, ch.aabb()) ){

                    cols = checkPair( other, ch );

                    if ( cols instanceof Array ){
                        for ( var j = 0, c, ll = cols.length; j < ll; j++ ){
                            c = cols[j];
                            // set body to be the compound body
                            if ( c.bodyA === ch ){
                                c.bodyA = compound;
                            } else {
                                c.bodyB = compound;
                            }
                            ret.push( c );
                        }

                    } else if ( cols ) {
                        // set body to be the compound body
                        if ( cols.bodyA === ch ){
                            cols.bodyA = compound;
                        } else {
                            cols.bodyB = compound;
                        }
                        ret.push( cols );
                    }
                }

                // transform it back
                ch.state.angular.pos -= compound.state.angular.pos;
                ch.offset.vsub( oldPos );
                ch.state.pos.clone( oldPos.rotate( ch.state.angular.pos ).vsub( compound.offset ) );
            }

            return scratch.done( ret );

        } else {

            return checkGJK( bodyA, bodyB );
        }
    }
1194217
function(out) {
        var amount = Math.min(this._particlePool.length, this.amount);

        var particle;
        for (var i = 0; i < amount; i++) {
            particle = this._particlePool.pop();
            // Initialize particle status
            if (this.position) {
                this.position.get(particle.position);
            }
            if (this.rotation) {
                this.rotation.get(particle.rotation);
            }
            if (this.velocity) {
                this.velocity.get(particle.velocity);
            }
            if (this.angularVelocity) {
                this.angularVelocity.get(particle.angularVelocity);
            }
            if (this.life) {
                particle.life = this.life.get();
            }
            if (this.spriteSize) {
                particle.spriteSize = this.spriteSize.get();
            }
            if (this.weight) {
                particle.weight = this.weight.get();
            }
            particle.age = 0;

            out.push(particle);
        }
    }
620441
def accel_ES_fl(q: np.ndarray):
    """"""
    # Number of celestial bodies
    num_bodies: int = 2
    # Number of dimensions in arrays; 3 spatial dimensions times the number of bodies
    dims = 3 * num_bodies

    # The force given the positions q of the bodies
    f = force_ES(q)

    # The accelerations from this force
    a = np.zeros(dims)
    a[slices[0]] = f[slices[0]] / mass[0]
    a[slices[1]] = f[slices[1]] / mass[1]
    
    return a
33198
function() {
      if (bodiesCount === 0) return true; // TODO: This will never fire 'stable'

      var lastMove = physicsSimulator.step();

      // Save the movement in case if someone wants to query it in the step
      // callback.
      api.lastMove = lastMove;

      // Allow listeners to perform low-level actions after nodes are updated.
      api.fire('step');

      var ratio = lastMove/bodiesCount;
      var isStableNow = ratio <= 0.01; // TODO: The number is somewhat arbitrary...

      if (wasStable !== isStableNow) {
        wasStable = isStableNow;
        onStableChanged(isStableNow);
      }

      return isStableNow;
    }
278099
def PartialDynamicSystem(self, ieq, variable):
        

        if ieq == 0:

            if variable == self.physical_nodes[0].variable:
                print('1')
                # U1 is output
                # U1=i1/pC+U2
                Uc = Variable(hidden=True)
                block1 = ODE(self.variables[0], Uc, [1], [0, self.C])
                sub1 = Sum([self.physical_nodes[1].variable, Uc], variable)
                return [block1, sub1]
            elif variable == self.physical_nodes[1].variable:
                print('2')
                # U2 is output
                # U2=U1-i1/pC
                Uc = Variable(hidden=True)
                block1 = ODE(self.variables[0], Uc, [-1], [0, self.C])
                sum1 = Sum([self.physical_nodes[0].variable, Uc], variable)
                return [block1, sum1]
#            elif variable==self.variables[0]:
#                print('3')
#                # i1 is output
#                # i1=pC(U1-U2)
#                ic=Variable(hidden=True)
#                subs1=Subtraction(self.physical_nodes[0].variable,self.physical_nodes[1].variable,ic)
#                block1=ODE(ic,variable,[0,self.C],[1])
#                return [block1,subs1]
        elif ieq == 1:
            # i1=-i2
            if variable == self.variables[0]:
                # i1 as output
                #                print('Bat1#0')
                return [Gain(self.variables[1], self.variables[0], -1)]
            elif variable == self.variables[1]:
                # i2 as output
                #                print('Bat1#1')
                return [Gain(self.variables[0], self.variables[1], -1)]
1060462
function main(options) {
    function markInterval(list, first, last, step, value) {
        if (step > 0) {
            for (var i = first; i <= last; i += step) {
                if (i >= 0 && i < list.length) {
                    list[i] = value;
                }
            }
        }
    }

    /*
     * Parse an expression and mark the corresponding frames with the given value.
     *
     * expr ::= interval ("," interval)*
     *
     * interval ::=
     *      INT                     // frame number
     *    | INT? ":" INT?           // first:last
     *    | INT? ":" INT? ":" INT?  // first:second:last
     *
     * If first is omitted, it is set to 1.
     * If second is omitted, it is set to first + 1.
     * If last is omitted, it is set to list.length.
     */
    function markFrames(list, expr, value) {
        switch (expr) {
            case "all":
                markInterval(list, 0, list.length - 1, 1, value);
                break;
            case "none":
                break;
            default:
                expr.split(",").forEach(function (intervalDef) {
                    var interval = intervalDef.split(":").map(function (s) { return s.trim(); });
                    if (interval.length > 0) {
                        var first = interval[0] !== "" ? parseInt(interval[0]) - 1 : 0;
                        var last = interval[interval.length - 1] !== "" ? parseInt(interval[interval.length - 1]) - 1 : list.length - 1;
                        var second = interval.length > 2 && interval[1] !== "" ? parseInt(interval[1]) - 1 : first + 1;
                        if (!isNaN(first) && !isNaN(second) && !isNaN(last)) {
                            markInterval(list, first, last, second - first, value);
                        }
                    }
                });
        }
    }

    function zeroPadded(value, digits) {
        var result = value.toString();
        while(result.length < digits) {
            result = "0" + result;
        }
        return result;
    }

    var frameCount = sozi.presentation.frames.length;

    var frameSelection = new Array(frameCount);
    markInterval(frameSelection, 0, frameCount - 1, 1, false);
    markFrames(frameSelection, options.include, true);
    markFrames(frameSelection, options.exclude, false);

    var digits = frameCount.toString().length;

    sozi.player.addListener("frameChange", function () {
        var frameIndex = sozi.player.currentFrameIndex; // Sozi < 18
        if (typeof frameIndex !== "number") {
            frameIndex = sozi.player.currentFrame.index; // Sozi 18
        }
        window.callPhantom(zeroPadded((frameIndex + 1).toString(), digits));
    });

    document.querySelector(".sozi-blank-screen").style.display = "none";
    
    frameSelection.forEach(function (frameIsSelected, frameIndex) {
        if (frameIsSelected) {
            console.log("Exporting frame: " + (frameIndex + 1));
            sozi.player.jumpToFrame(frameIndex);
        }
    });
}
856204
function perfmon() {
	var inputs = parseInputs(arguments);
	var pstream = new PerfmonStream(inputs.options.counters);

	if (typeof(inputs.cb) == 'function') {
		pstream.on('data', function(data) {
			inputs.cb(null, data);
		});

		pstream.on('error', inputs.cb);
	}

	if (inputs.options.error) {
		process.nextTick(function() {
			pstream.emit('error', inputs.options.error);
		});
	}
	else {
		inputs.options.hosts.forEach(function(h) {
			init(h, inputs.options, pstream);
		});	
	}

	return pstream;
}
1206479
def _run(self):
        
#        print("Doing APM Clustering...")
        # Start looping for maxIter times
        n_macrostates = 1  # initialized as 1 because no macrostate exist in loop 0
        metaQ = -1.0
        prevQ = -1.0
        global_maxQ = -1.0
        local_maxQ = -1.0

        for iter in range(self.max_iter):
            self.__max_state = -1
            self.__micro_stack = []
            for k in range(n_macrostates):
                self._do_split(micro_state=k, sub_clus=self.sub_clus)
                self._do_time_clustering(macro_state=k)

            # do Lumping
            n_micro_states = np.amax(self.__temp_labels_) + 1
            if n_micro_states > self.n_macrostates:
#                print("PCCA Lumping...", n_micro_states, "microstates")
                self.__temp_MacroAssignments_ = self._do_lumping(
                    n_macrostates=n_macrostates)
                #self.__temp_labels_ = [copy.copy(element) for element in self.__temp_MacroAssignments_]

                #Calculate Metastabilty
                prevQ = metaQ
                metaQ = self.__temp_transmat_.diagonal().sum()
                metaQ /= len(self.__temp_transmat_)
            else:
                self.__temp_MacroAssignments_ = [
                    copy.copy(element) for element in self.__temp_labels_
                ]

            # Optimization / Monte-Carlo
            acceptedMove = False
            MCacc = np.exp(metaQ * metaQ - prevQ * prevQ)

            if MCacc > 1.0:
                MCacc = 1.0
            optLim = 0.95

            if MCacc > optLim:
                acceptedMove = True

            if acceptedMove:
                local_maxQ = metaQ
                if metaQ > global_maxQ:
                    global_maxQ = metaQ
                    self.MacroAssignments_ = [
                        copy.copy(element)
                        for element in self.__temp_MacroAssignments_
                    ]
                    self.labels_ = [copy.copy(element)
                                    for element in self.__temp_labels_]
                    self.transmat_ = self.__temp_transmat_

#            print("Loop:", iter, "AcceptedMove?", acceptedMove, "metaQ:",
#                  metaQ, "prevQ:", prevQ, "global_maxQ:", global_maxQ,
#                  "local_maxQ:", local_maxQ, "macroCount:", n_macrostates)
            #set n_macrostates
            n_macrostates = self.n_macrostates
            self.__temp_labels_ = [copy.copy(element)
                                   for element in self.__temp_MacroAssignments_
                                   ]
969059
function (body1, body2, springLength, springWeight, springCoefficient) {
      if (!body1 || !body2) {
        throw new Error('Cannot add null spring to force simulator');
      }

      if (typeof springLength !== 'number') {
        springLength = -1; // assume global configuration
      }

      var spring = new Spring(body1, body2, springLength, springCoefficient >= 0 ? springCoefficient : -1, springWeight);
      springs.push(spring);

      // TODO: could mark simulator as dirty.
      return spring;
    }
1108192
function flattenBody (body, bodyStructure) {
  for (const elName in body) {
    if (body[elName].length === 1 && !bodyStructure[elName].alwaysArray) {
      body[elName] = body[elName][0];
    }
  }
}