Skip to content

src/core/nbody.js ​

text
Gravitational N-body dynamics for planetary systems: dynamical transit and eclipse times, transit timing variations,
radial velocities of the star, sky positions for photodynamical light curves, stability checks (Hill, AMD, MEGNO),
and the interpretation of an O - C signal by a grid of
simulations over a hypothetical perturber. No DOM, no dependencies outside src/core. Runs in Node.

============================================================================================================
INTEGRATION (for the owner of src/core/model.js; nothing here edits it)
============================================================================================================
1. Timing likelihood (do this first). `buildProblem` compares each mid-transit time with
   `t0 + E * per` in its "---- timing" loop. With `spec.nbody` set, replace that prediction with

       const dyn = dynamicalModel(
         { mstar: v.mstar, rstar: v.rstar, epoch: spec.nbody.epoch,           // times relative to data.tRef, like tmid
           planets: pv.map((q) => ({ per: q.per, tmid: q.tmid, ecc: q.ecc, omega: q.omega, inc: q.inc, mplanet: q.mplanet })) },
         { timing: tim.map((x) => ({ planet: x.p, t: x.t })),                 // x.p = index into spec.planets
           rv: rvs.map((d) => ({ t: d.t })), event: 'conjunction', dt: spec.nbody.dt });
       if (!dyn.ok) return null;                                              // unbound, close encounter, missing transit
       // timing:   x.model[i] = dyn.timing[k].model[i];  x.epoch[i] = dyn.timing[k].epoch[i]
       // velocity: replace  sum_p rvFns[p](D.t[i])  by  dyn.rv[d][i]   (m/s, positive = receding, no zero point)

   Requirements: every planet needs `mplanet` (M Jup) and the star `mstar` (the spec.kepler case already has
   both); `per`, `tmid`, `ecc`, `omega`, `inc` keep their keys but become OSCULATING elements at
   `spec.nbody.epoch` (see "Reference epoch" below), so with all masses zero the result is identical to the
   present Keplerian one. Cost: one simulation per likelihood call; see the
   timings at the end of this header. `nbodyTimingProblem` below is the same likelihood as a stand-alone
   problem ({ ndim, keys, transform, loglike }) for MiniNest, used by test/nbody.test.mjs.

2. Photodynamics (built: `dynamicalModel(..., { lc })` returns `photo`, used by buildProblem when spec.nbody is set and
   a light curve is in the fit). One integration serves everything: besides the velocities, `simulate` outputs the
   positions and velocities of every body at evenly spaced nodes that cover the light curve's points (plus half an
   exposure and the light-travel margin; runs of nodes only where there are data). `photo.transit(p, { rprs, ldLaw, ld })`
   returns flux(t): a cubic Hermite interpolation of the planet's sky position relative to the star, then
   `blockedFraction` of transit.js. It is a plain function of time, so buildProblem's exposure sub-sampling applies
   unchanged. Planets are treated one at a time: the area two planets share on the stellar disc during a mutual
   event is counted twice (buildProblem multiplies the planets' fluxes), and a planet with its own light or a
   moon keeps its Keplerian curve.
   Accuracy: the interpolation leaves 1e-9 of the flux at the default 150 nodes per orbit; the rest is the
   integrator. Against REBOUND IAS15 positions through batman, for 1 and 2 M_Jup at 10 and 20.3 d over 125 d:
   0.008 ppm with 'ias15', 57 ppm with the Wisdom-Holman defaults (its transit times are 7 s off there, growing
   with time as eps^2 dt^2), 14 ppm at 60 steps per orbit (test/nbodyphoto.test.mjs).

3. Mid-eclipse times: `simulate(..., { eclipses: true })` records the same event on the far side (Z < 0);
   timing sets of kind 'eclipse' go through `dynamicalModel` like transits.

4. Light-travel time (req.ltt / spec.nbody.ltt), referred to the plane through the barycentre: light seen at t
   left a body at t + Z/c. Transits are seen about a/c early, eclipses a/c late (so the pair is 2a/c apart, as in
   phasecurve.js, whose convention keeps the transit at tmid instead). Applied to the light curve and to event times.

5. Mean-ephemeris elements (req.elements = 'mean'): per and tmid of every planet are the straight line through its
   simulated mid-transit times over the span of the data; `osculatingFromMean` finds the osculating values. This is
   what makes a planet's own period and T0 sampleable together with a companion's mass (see that function).

============================================================================================================
Units and frame
============================================================================================================
Internal units: AU, days, solar masses; G = GM_sun day^2 / AU^3 from the constants `C` in derive.js
(2.9591220828559e-4, the IAU 2012 AU and the nominal GM_sun). Planet masses are given in Jupiter masses
(C.Mjup_Msun) and converted at the boundary; positions are returned in stellar radii when `rstar` [R_sun]
is given, velocities of the star in m/s.

Frame: that of kepler.js. X, Y in the plane of the sky, +Z toward the observer. A planet's position on
its osculating orbit is
    X = -r cos(omega + nu),   Y = -r sin(omega + nu) cos i,   Z = r sin(omega + nu) sin i
rotated about the line of sight by the optional `Omega` (degrees, default 0):
    X' = X cos Omega - Y sin Omega,   Y' = X sin Omega + Y cos Omega.
This is REBOUND's (and Winn 2010's) convention with the longitude of the ascending node at Omega + 180 deg:
REBOUND's x, y are -X, -Y here and its z is Z. Only differences of Omega between planets matter.
Mid-transit is inferior conjunction, omega + nu = pi/2. Radial velocity is -dZ/dt of the star in the
barycentric frame, positive when it recedes, as in rv.js.

============================================================================================================
Initial conditions, reference epoch and the Keplerian limit
============================================================================================================
`buildSystem` turns the app's parameters {per, tmid, ecc, omega, inc, Omega, mplanet} of each planet into
positions and velocities at one instant, `epoch` (default: the earliest tmid). The parameters are the
OSCULATING elements at that instant: `tmid` fixes the phase through the mean anomaly
    M(epoch) = M_transit(e, omega) + 2 pi (epoch - tmid) / per
i.e. tmid is the time at which the planet WOULD be at inferior conjunction if it kept the orbit it has at
`epoch`. It need not lie near `epoch`, but a tmid far from it (more than about a TTV period) is no longer
close to any actual transit. Choose `epoch` inside or at the start of the data, as EXOTIC's
NbodySystem.from_multiplanet does.

Elements are Jacobi elements by default (coords: 'jacobi'): planets are ordered by period, and planet k
orbits the centre of mass of the star and the planets inside it with
    a_k^3 = G (M* + m_1 + ... + m_k) per_k^2 / (4 pi^2).
This is what REBOUND's sim.add(m=, P=, ...) does, hence what EXOTIC's nbody.py does, and TTVFast's default
input. coords: 'astrocentric' takes each planet's elements relative to the star with G (M* + m_k).
For a single planet both are the two-body orbit of rv.js (same a, same K).

Keplerian limit: with every planet mass zero, all the choices above reduce to a test particle around M*
with exactly the period `per`, and the interaction part of the integrator vanishes identically, so the map
is the exact two-body solution. Transit times are then tmid + k per to rounding (measured in the tests:
1e-4 s after 5000 circular orbits, 7e-3 s after 1000 orbits of HD 80606 b at 2300 steps per orbit; under
1e-12 of the elapsed time in both cases).

============================================================================================================
What a "mid-transit time" is
============================================================================================================
  event: 'minsep'       (default) the instant of minimum sky-projected separation of planet and star with the
                        planet in front: the root of  (R_sky . V_sky) = 0,  as in TTVFast (Deck et al. 2014).
                        This is the centre of the light curve.
  event: 'conjunction'  the instant the planet crosses the plane through the line of sight and the normal to its
                        line of nodes (X' = 0 with Z > 0). This is what kepler.js calls `tmid`.
The two coincide for circular or edge-on orbits. Otherwise the centre of the light curve comes earlier or
later than conjunction by about  b R* (dr/dt) cos i / v_sky^2 : 684 s (11.4 min) for HD 80606 b (e = 0.93,
i = 89.27 deg, b = 0.78), under a second for hot Jupiters with e < 0.05. `dynamicalModel` defaults to
'conjunction' because it stands in for `tmid + E per` in the timing likelihood and because the app's light
curves are built on tmid = conjunction.
Light-travel time across the system is not applied unless asked for (`ltt`; neither REBOUND-based codes nor
TTVFast apply it).

============================================================================================================
Integrators
============================================================================================================
  'wh'     Wisdom-Holman map in Jacobi coordinates with the same splitting as REBOUND's WHFast (Rein & Tamayo
           2015): Kepler drift of each planet about the mass interior to it (universal variables, Stumpff
           series), interaction kick. Drift-kick-drift, combined between outputs. Optional symplectic
           correctors of order 3 to 11 (Wisdom 2006; coefficients as in WHFast) reduce the error from
           O(eps dt^2) to O(eps dt^4 + eps^2 dt^2), eps = planet/star mass ratio; they are applied once at the
           start and undone on a copy of the state wherever an output or a transit is needed. Fixed step,
           time-reversible, symplectic. Not valid when two planets come within about a mutual Hill radius
           (the result is flagged).
  'ias15'  Gauss-Radau 15th-order predictor-corrector with adaptive step (Everhart 1985; Rein & Spiegel 2015,
           with their original global step criterion, epsilon = 1e-9). Machine-precision energy, handles close
           encounters; its interpolating polynomial gives transit times and outputs inside a step at no cost.
           Used as the internal cross-check and whenever the Wisdom-Holman map is flagged.
Transit times: a sign change of the event function between consecutive steps is refined by re-stepping from
the synchronised state (Wisdom-Holman) or on the interpolating polynomial (IAS15), then polished by Newton
iteration on a two-body arc. The root is found to better than 1e-9 d; the accuracy of the time itself is
that of the integration and is given in the README section and in test/nbody.test.mjs.

References
  Wisdom & Holman 1991, AJ 102, 1528; Wisdom, Holman & Touma 1996; Wisdom 2006, AJ 131, 2294 (correctors)
  Rein & Tamayo 2015, MNRAS 452, 376 (WHFast); Rein & Spiegel 2015, MNRAS 446, 1424 (IAS15)
  Deck, Agol, Holman & Nesvorny 2014, ApJ 787, 132 (TTVFast)
  Agol, Steffen, Sari & Clarkson 2005, MNRAS 359, 567; Holman & Murray 2005, Science 307, 1288
  Lithwick, Xie & Wu 2012, ApJ 761, 122 (near-resonant TTV amplitudes)
  Gladman 1993, Icarus 106, 247; Chambers, Wetherill & Boss 1996, Icarus 119, 261 (Hill spacing)
  Laskar & Petit 2017, A&A 605, A72 (AMD stability)
  Cincotta & Simo 2000, A&AS 147, 205; Cincotta, Giordano & Simo 2003, Physica D 182, 151 (MEGNO)
  Carter et al. 2011, Science 331, 562 (photodynamics)
  Pearson 2019, AJ 158, 243 (Nbody-AI: the grid/prior idea reproduced by ttvGrid)

Import: import { … } from './src/core/nbody.js' — no DOM, runs in Node and the browser.

NB ​

js
const NB

Constants of the internal unit system (AU, day, M_sun).

energy ​

js
function energy(n, m, x, v)

Total energy [M_sun AU^2 / d^2] of an inertial state.

angularMomentum ​

js
function angularMomentum(n, m, x, v)

Total angular momentum vector [M_sun AU^2 / d] of an inertial state.

buildSystem ​

js
function buildSystem(p)
text
Initial conditions from the app's parameters.
p = {
  mstar [M_sun], rstar [R_sun] (optional; needed for impact parameters, durations, positions in stellar radii),
  planets: [{ per [d] (or a [AU]), tmid [d], ecc, omega [deg], inc [deg], Omega [deg] (optional), mplanet [M_Jup],
              rprs (optional, for T14), letter (optional) }],
  epoch [d]   instant at which the elements are osculating (default: the earliest tmid),
  coords      'jacobi' (default) | 'astrocentric'
}
Returns { n (bodies, star first), np, m [M_sun], x, v (barycentric, AU and AU/d, bodies ordered by period),
          epoch, order (order[j] = index in p.planets of body j+1), slot (inverse), per, a [AU], ecc, rstarAU, rprs,
          nodeC, nodeS (cos, sin of each body's Omega), mstar, coords }.
Throws on parameters that do not describe a bound orbit.

defaultStep ​

js
function defaultStep(sys, stepsPerOrbit = 30)

Default Wisdom-Holman step [d]: the shortest "periastron period" P (1 - e)^(3/2) / sqrt(1 + e) of the planets, divided by stepsPerOrbit (default 30). For circular orbits this is P/30; an eccentric orbit needs its periastron passage resolved (HD 80606 b: 1/75 of the period per unit, so about 2300 steps per orbit).

simulate ​

js
function simulate(sys, opt = {})
text
Integrate a system and collect transits, radial velocities and positions.

sys: from buildSystem (not modified).
opt = {
  tStart, tEnd      window [d] (same time system as tmid/epoch). The integration starts at sys.epoch and runs
                    forward to tEnd and, when tStart < epoch, backward to tStart. Defaults: epoch.
  integrator        'wh' (default) | 'ias15'
  dt                Wisdom-Holman step [d]; default: defaultStep(sys, stepsPerOrbit)
  stepsPerOrbit     default 30 (per shortest periastron period, see defaultStep)
  corrector         0 | 3 | 5 (default) | 7 | 11: order of the symplectic corrector
  exactSync         true (default): undo the corrector at every transit and output. false: skip that, which
                    is up to twice as fast and adds a bounded error of order eps dt^2 to the times (at most
                    0.12 s in the reference systems of test/nbody.test.mjs)
  epsilon           IAS15 accuracy parameter (default 1e-9)
  transits          true (default): find mid-transit times of every planet
  eclipses          true: also find mid-eclipse times (the same event on the far side, Z < 0); default false
  velocities        true (with positions): also return velocities at `times`
  event             'minsep' (default) | 'conjunction'
  times             output times [d] (any order, inside the window): radial velocity and positions there
  positions         true: also return positions at `times` (default false)
  maxTransits       capacity per planet (default from the window and the periods)
}
Returns {
  ok, status ('ok' | 'unbound' | 'close encounter' | 'not converged'), warnings: [strings],
  integrator, dt, steps, forceEvaluations, seconds,
  transits: [per planet, in the order of p.planets]
             { n, t (mid-transit times, sorted), b (sky separation at mid-transit in stellar radii; AU when
               rstar is not given), vsky [stellar radii or AU per day], dur (first to fourth contact, days;
               0 when grazing-out or rstar unknown), z (always > 0), ltt (light-travel path in the same length
               unit: the event is seen at t - ltt / c, referred to the plane through the barycentre) }  as Float64Array views,
  eclipses:   the same per planet for mid-eclipse (z < 0), filled when opt.eclipses,
  rv:  Float64Array, m/s at opt.times in the order given (positive = receding), barycentric, no zero point,
  samples: { x: [per body incl. star, Float64Array 3*nt], v: the same for velocities (per day) or null }
           positions relative to the barycentre at opt.times (stellar radii when rstar is given, else AU),
  energy: { initial, final, relErr (|dE/E| at the end), maxRelErr (largest seen at the checks) },
  angmom: { relErr },
  minSepHill: smallest planet-planet distance met, in mutual Hill radii (Infinity for one planet),
  minStar: smallest planet-star distance met [AU],
  state: { t, x, v } inertial state at the end of the forward leg (tEnd; or the epoch when there is none)
}

nbody ​

js
function nbody(p, opt = {})

One call from parameters to results: simulate(buildSystem(p), opt). p as in buildSystem; opt as in simulate. Returns the simulate result with system attached.

dynamicalModel ​

js
function dynamicalModel(system, req = {})
text
Dynamical mid-transit and mid-eclipse times, radial velocities and sky positions in place of the Keplerian ones.

system: { mstar [M_sun], rstar [R_sun; needed for a light curve], epoch [d, default earliest tmid], coords,
          planets: [{ per, tmid, ecc, omega [deg], inc [deg], Omega [deg, optional], mplanet [M_Jup] }] }
        times in any consistent system (the app uses days relative to data.tRef)
req:    { timing: [{ planet: index into system.planets, t: observed times, kind: 'transit' (default) | 'eclipse' }],
          rv:     [{ t: times }],
          lc:     { t: times of the light curve, pad: half the longest exposure [d], sorted: true when t is ascending }
                  -> `photo`, position tracks for the transit kernel (see makeTrack below),
          photoStep [d] or nodesPerOrbit (default 150 per periastron period of the innermost planet): spacing of the track nodes,
          ltt: true to apply the light-travel time across the system to the light curve and to the event times,
          elements: 'mean' when per and tmid of the planets are the mean ephemeris of their simulated transits over
                  the span of the data (osculatingFromMean below); meanTol, meanIter; warm: an object the caller keeps
                  between calls, in which the last solution is stored as the starting point of the next,
          event: 'conjunction' (default here) | 'minsep',
          integrator, dt, stepsPerOrbit, corrector, exactSync, epsilon   (passed to simulate),
          pad: extra time simulated beyond the first and last datum, in periods of the longest orbit (default 0.6) }
Returns { ok, status, warnings,
          timing: [{ model: Float64Array (simulated event nearest each observed one, as seen when ltt),
                     epoch: Int32Array (index of that event counted from the first simulated one at or after
                            the start of the window; consecutive events differ by 1),
                     miss: number of observed times with no simulated event within half a period }],
          rv: [Float64Array m/s, positive = receding, no zero point],
          photo: null | { position(p, t, out), transit(p, { rprs, ldLaw, ld }) -> flux(t), nodes, h },
          osculating: null | [{ per, tmid }] (with elements: 'mean'), iterations (simulations spent finding them),
          sim: the simulate() result (transits of every planet, energy error, ...) }
ok is false when the integration failed, a close encounter invalidated the Wisdom-Holman map, an observed
time has no simulated event near it (the planet stopped transiting or left), or the mean elements were not found.

AU_LIGHT_DAYS ​

js
const AU_LIGHT_DAYS

Light-travel time across one astronomical unit, in days (499.005 s).

osculatingFromMean ​

js
function osculatingFromMean(system, opt = {})
text
Osculating period and conjunction time of each planet such that the straight line through its simulated
mid-transit times is the given one.

`per` and `tmid` of every planet in `system` are read as that line (the mean, "observed" ephemeris): with E the
whole number of orbits from tmid, the least-squares line  A + B E  through the planet's simulated times between
opt.lo and opt.hi (the span of the data) has A = tmid and B = per. Found by iteration, one simulation of transit
times each: the osculating tmid and per are first corrected by (tmid - A) and (per - B), then by Broyden's method
(a secant update of that unit Jacobian), until the line is matched to opt.tol (default 2e-7 d, 0.02 s, anywhere in
the span). Typically 4 to 7 simulations (the first guess is off by the difference between mean and osculating
period times the number of orbits in the span, and the timing variations respond non-linearly to that); inside a
mean-motion resonance, where the mean period hardly depends on the osculating one, it may not converge (ok: false,
and the likelihood rejects the point). A planet with fewer than three transits in the span keeps its
values as osculating elements. ecc, omega, inc and the masses are osculating in both descriptions.

Why: the osculating period of a planet near a resonance differs from its mean period by a part in a thousand,
by an amount that depends on the companion's mass and phase. A sampler that moves the companion then has to
move the planet's period and T0 with it along a curved ridge a few parts in a million wide; in these parameters
the ridge is straight and the planet's ephemeris is nearly uncorrelated with the companion.

opt: { tStart, tEnd, lo, hi, kappa (light-travel days per length unit, 0 for none), tol, maxIter (default 12),
       start: [{ per, tmid }] offsets (osculating - mean) of a nearby solution to start from (the `offset` returned),
       event, integrator, dt, stepsPerOrbit, corrector, exactSync, epsilon }
Returns { ok, status, warnings, system (a copy with osculating per and tmid), osculating: [{ per, tmid }], offset,
          iterations, residual (days: how far the simulated line is from the wanted one), sim (the transit-only
          simulation of exactly these elements) }.

nbodyTimingProblem ​

js
function nbodyTimingProblem(spec)
text
A timing likelihood on dynamical transit times, as a stand-alone problem for MiniNest (nested.js):
  lnL = sum_i -0.5 [ (t_i - T_nbody(E_i))^2 / s_i^2 + ln(2 pi s_i^2) ],   s_i^2 = err_i^2 + noise^2
spec = {
  system: as in dynamicalModel (the starting values),
  timing: [{ planet: index, t, e }],
  free:   [{ key, prior }]   key = '<field>@<planet index>' with field one of per, tmid, ecc, omega, inc, Omega,
                             mplanet, or 'mstar'; prior as in priors.js ({ type, a, b })
  linear: true to remove, for each timing set, the best straight line in transit number from the residuals
          before chi-square (a profile over that planet's T0 and period, as ttvGrid does). Then `per` and `tmid`
          of that planet need not be free: two fewer dimensions, and they are the two most tightly constrained,
  noise:  days, added in quadrature (default 0),
  sim:    options passed to dynamicalModel (integrator, dt, stepsPerOrbit, corrector, event ...)
}
Returns { ndim, keys, transform(u, theta), loglike(theta), detail(theta) -> { lnL, chi2, dyn, system } }.

ttvSummary ​

js
function ttvSummary(times, opt = {})
text
O - C of a sequence of mid-transit times against its best linear ephemeris, and what is periodic in it.
times: consecutive transits (days). opt: { errs (default: equal weights), epochs (default 0, 1, 2, ...),
       periodogram: true (default) to run timingPeriodogram (needs at least 6 times), sigma: nominal error in
       days used when errs is not given (default 1 s; it only sets the scale of chi-square) }
Returns { n, epochs, t0, per (linear ephemeris), oc (days), rms, amplitude (half the peak-to-peak, days),
          periods: [{ period (epochs), periodDays, power, amp (days, of the fitted sinusoid when it is the first) }],
          pg: the timingPeriodogram result or null }.
With noiseless simulated times the false-alarm probabilities in pg are meaningless (the error bars are nominal);
the periods and amplitudes are not affected.

laplaceCoefficient ​

js
function laplaceCoefficient(s, j, alpha)

Laplace coefficient b_s^(j)(alpha) and its derivative with respect to alpha, by the trapezoid rule (spectrally accurate).

nearestFirstOrder ​

js
function nearestFirstOrder(P1, P2)
text
The first-order mean-motion resonance j : j-1 nearest to a pair of periods (inner P1 < outer P2).
Returns { j, delta (normalised distance  (P2/P1) (j-1)/j - 1), superPeriod (days) = 1 / |j/P2 - (j-1)/P1| }.
The super-period is the period of the near-resonant TTV of both planets (Lithwick, Xie & Wu 2012, eq. 5).

lithwickTTV ​

js
function lithwickTTV(p)
text
Near-resonant TTV of a pair close to a first-order resonance (Lithwick, Xie & Wu 2012, eqs. 8-10 and A1-A2):
  V1 = P1 mu2 / (pi j^(2/3) (j-1)^(1/3) Delta) * (-f - (3/2) conj(Zfree) / Delta)
  V2 = P2 mu1 / (pi j Delta)                   * (-g + (3/2) conj(Zfree) / Delta),     Zfree = f z1 + g z2
with mu = planet/star mass ratio, z = e exp(i pomega), and the TTV of planet k a sinusoid of amplitude |Vk| at
the super-period. f and g are the sums of Laplace coefficients evaluated at the actual period ratio.
P1, P2 must be the MEAN periods (those of the ephemerides), not osculating periods at some instant: a
Jupiter-mass neighbour shifts the osculating period by a few tenths of a percent, which near a resonance
changes Delta, and with it the super-period and the amplitude, by ten percent or more.
p = { mstar [M_sun], P1, P2 [d], m1, m2 [M_Jup], e1 = 0, e2 = 0, omega1 = 0, omega2 = 0 [deg, kepler.js convention] }
Longitudes of pericentre are measured from the line of sight, pomega = omega - 90 deg (coplanar, Omega = 0).
Returns { j, delta, superPeriod, f, g, V1: [re, im], V2: [re, im], amp1, amp2 (days), zfree: [re, im], valid }.
valid is false within |Delta| < about 2 (mu)^(2/3) of the resonance, where the formula (linear in the masses,
no libration) does not apply, and for |Delta| > 0.1 where other terms are as large.

agolTTV ​

js
function agolTTV(p)
text
Order-of-magnitude TTV scalings of Agol, Steffen, Sari & Clarkson (2005) for a transiting planet (period P,
mass m) and a perturber (period Pp, mass mp, eccentricity ep). Masses in M_Jup, mstar in M_sun, times in days.
Returns {
  regime: 'interior' | 'exterior',
  wobble:     interior perturber, star's reflex motion (their eq. 7): amplitude  (mp/M*) (Pp/P)^(2/3) P / (2 pi)
              (0 for an exterior perturber),
  tidal:      exterior perturber on an eccentric orbit with Pp >> P (their eq. 25, after Borkovits et al. 2003):
              dt = beta (f - M + ep sin f),  beta = mp / (2 pi (M* + m)) (P^2 / Pp) (1 - ep^2)^(-3/2);
              the value returned is the half range of that expression over one orbit of the perturber
              (0 for a circular or interior perturber),
  resonant:   maximum for a pair IN a first-order j:j+1 resonance (their eq. 33):  P / (4.5 j) mp / (mp + m),
  libration:  period of that resonant TTV (their eq. 32):  0.5 j^(-4/3) ((m + mp)/M*)^(-2/3) P,
  j }
These are scalings: the tests compare `wobble` and `tidal` with simulations to the stated tolerance; `resonant`
and `libration` are quoted as the paper gives them and are not tested here.

amdCritical ​

js
function amdCritical(alpha, gamma)
text
Critical relative AMD of a pair for collision (Laskar & Petit 2017, eqs. 35 and 39).
alpha = a_inner / a_outer, gamma = m_inner / m_outer. Returns { Cc, e, ep } (the eccentricities at the critical point).

megno ​

js
function megno(p, opt = {})
text
MEGNO, the Mean Exponential Growth factor of Nearby Orbits (Cincotta & Simo 2000; Cincotta, Giordano & Simo 2003):
a chaos indicator from the variational equations. With delta the displacement in phase space (positions and
velocities of every body) of an infinitesimally close orbit,
    Y(t) = (2 / t) int_0^t (delta . d delta/dt) / (delta . delta) s ds,      <Y>(t) = (1 / t) int_0^t Y(s) ds.
<Y> tends to 2 for quasi-periodic (regular) motion and grows as lambda t / 2 for chaotic motion with Lyapunov
exponent lambda. Which it is shows within a few hundred to a few thousand orbits, long before any planet is lost.

The orbit and the variational equations  d2 delta_i/dt2 = sum_j G m_j [ D/r^3 - 3 (r . D) r / r^5 ],  r = x_j - x_i,
D = delta_j - delta_i, are integrated together with the 15th-order Gauss-Radau scheme of IAS15 (step controlled by
the orbit only, as in REBOUND). The initial displacement is a random direction (opt.seed). The displacement
carries no shift or drift of the centre of mass. Y is integrated with the Gauss-Radau rule on the nodes of each step,
and the Lyapunov exponent is the least-squares slope of Y(t), as in REBOUND.

p: as in buildSystem, or a system from buildSystem. opt: { orbits (of the outermost planet, default 1000) or days,
   seed (default 1), epsilon (default 1e-9), threshold (default 0.5), stopAbove (default 20: stop as soon as <Y> exceeds
   it after 20 outer orbits, the answer is then known; 0 to run to the end), maxSteps (default 400 per inner orbit) }.
Returns { megno (<Y> at the end), lyapunov [1/d] (slope of Y; about 0 when regular), lyapunovTime [d] (1 / lyapunov
          when chaotic, else Infinity), chaotic (megno > 2 + threshold, or the integration stopped early), threshold (default 0.5),
          days, orbits (those integrated), steps, stopped (true when stopAbove ended it), ok (false when the integration
          failed: an escape, or close encounters that collapse the step; megno is then that of the part integrated and
          chaotic is true), status, energyErr, seconds }.
The value for a chaotic orbit depends on the initial displacement and on rounding (two seeds give 225 and 394 in
REBOUND for the same system): only "about 2" against "much more than 2" is meaningful.

stabilityReport ​

js
function stabilityReport(p, opt = {})
text
Stability checks that need no integration, plus (opt.integrate) a short monitored one.
p: as in buildSystem. opt: { integrate: number of orbits of the outermost planet to integrate (default 0: none),
                             stepsPerOrbit (default 30), shadow: true (default) also integrate a copy displaced by
                             1e-10 and report how fast the two diverge, megno: true (default) also compute MEGNO over
                             the same span, seed }
Returns {
  pairs: [{ inner, outer (indices into p.planets), periodRatio, deltaHill (separation in mutual Hill radii),
            hillStable (deltaHill > 2 sqrt(3), Gladman 1993: two planets on circular coplanar orbits can never
            have a close encounter), crossing (the osculating orbits overlap: a_in (1 + e_in) > a_out (1 - e_out)),
            amdBeta (AMD / critical AMD of the pair, Laskar & Petit 2017; < 1 means collisions are impossible
            as long as the semi-major axes stay put), resonance: { j, delta } }],
  amd (total, M_sun AU^2 / d), amdStable (every pair and the star: beta < 1), amdBetaStar (innermost planet reaching the star),
  chambers: smallest deltaHill when there are three or more planets (Chambers et al. 1996: below about 10 such
            systems go unstable within about 1e8 orbits),
  integration: null | { orbits, days, ok, status, energyErr, minSepHill, divergence (growth factor of the
                        displacement), megno (see megno(); null with opt.megno: false), megnoOrbits, megnoStopped, lyapunovTime [d],
                        chaotic (MEGNO above 2.5, or the displaced copy grew far faster than the shear of regular orbits), seconds },
  stable: true | false | null   (null: the criteria do not decide),
  findings: [strings]   plain-language statements, most important first
}

ttvGridSim ​

js
function ttvGridSim(prep, mass, period, phase)

One simulation of the grid: the transiting planet with a perturber of the given mass [M_Jup], period [d] and starting phase (0..1: fraction of its orbit by which its conjunction follows the start of the simulation), scored against the observed times after a straight line in epoch (T0 and period of the transiting planet) has been removed by weighted least squares. Returns { ok, status, chi2, amp, c0, c1 }.

ttvGridCell ​

js
function ttvGridCell(prep, mass, period)

One cell of the grid (exported so a Web Worker can evaluate cells): the best chi-square over the perturber's phase for one mass and one period. Returns { chi2, phase, amp, stable, status }.

ttvGridRefine ​

js
function ttvGridRefine(obs, base, start, opt = {})
text
Polish a grid cell: minimise chi-square over (ln mass, period, phase) of the perturber by the Nelder-Mead
simplex, starting from `start` = { mass, period, phase } (e.g. ttvGrid(...).best). The chi-square surface is
narrow in period and phase (the TTV must stay in step with the data over many super-periods), so the grid
minimum is usually a poor fit until it is polished.
opt: as ttvGrid, plus { maxSim = 400, tol = 1e-3 (in chi-square) }.
Returns { mass, period (osculating, at the start of the simulation), periodMean (mean period between the
          perturber's conjunctions: the number to compare with an ephemeris), phase, chi2, ndata, amp (days), nSim, converged,
          planet: { per, tmid } of the transiting planet after the linear refit,
          oc: { epoch, obs, err, model }  observed O - C and the simulated one at the same epochs, both against the
                straight line fitted to the observations (days),
          curve: { E, y } simulated O - C at every epoch of the simulation (days) }.

ttvGridPrepare ​

js
function ttvGridPrepare(obsIn, base, optIn = {})

Shared preparation for ttvGrid and its workers: epochs, weights, the simulation window.

ttvGrid ​

js
function ttvGrid(obs, base, grid, opt = {})
text
How well does a perturber of each (mass, period) explain observed mid-transit times of one planet?
The EXOTIC/Nbody-AI interpretation step (Pearson 2019), but scoring each simulation against the times
themselves instead of only the amplitude and period of the periodogram peak.

obs:  { t: mid-transit times [d], e: 1-sigma errors [d] }  of the transiting planet
base: { mstar [M_sun], rstar [R_sun, optional],
        planet: { per, tmid (linear ephemeris of the data), ecc, omega, inc, mplanet [M_Jup] },
        perturber: { ecc = 0, omega = 0, inc = planet.inc, Omega = 0 }   fixed properties of the perturber }
grid: { mass: [M_Jup ...], period: [days ...]  (or periodRatio: [...] relative to the planet's period) }
opt:  { phases = 8        starting orbital phases of the perturber tried in each cell (the best is kept);
                          each costs one simulation,
        stepsPerOrbit = 20, corrector = 5, exactSync = false, dt       integrator settings (coarser than simulate's
                          defaults: a grid needs the shape of the O - C to a few seconds, not the absolute times),
        ampTol = 0.3, perTol = 0.15   relative tolerances of the EXOTIC-style mask (needs opt.observed),
        observed: { amp [d], period [d] }   amplitude and period of the periodogram peak, for the mask,
        onProgress(fraction) }
Each simulation spans the data; the transiting planet's T0 and period are refitted linearly for every cell.
Returns {
  mass, period (Float64Array axes), nm, np,
  chi2 (Float64Array nm*np, row = mass index, column = period index; Infinity where no stable simulation),
  dchi2 (chi2 - min), amp (simulated TTV half-amplitude of the transiting planet, days), phase (best, 0..1),
  stable (Uint8Array), hill (separation in mutual Hill radii),
  mask (Uint8Array | null: cells whose simulated amplitude matches opt.observed.amp within ampTol and whose
        super-period matches opt.observed.period within perTol: EXOTIC's estimate_prior),
  best: { im, ip, mass, period, chi2, phase, amp }, chi2Linear (no perturber), ndata,
  region: cells with dchi2 < 2.30, 6.18 (1 and 2 sigma for two parameters): { n1, n2, massRange1, periodRange1 },
  nSim, seconds, simsPerSecond
}

ttvGridAssemble ​

js
function ttvGridAssemble(prep, base, mass, period, chi2, amp, phase, stable, hill, opt = {})

Turn filled grid arrays into the ttvGrid result (also used after a worker pool has filled them).

MIT licensed · Kyle A. Pearson