Code view

How the simulation thinks

Readable walk-through of the experiment logic, one step at a time. Copy any block to study it or adapt it.

Illustrative, not the project source. These blocks are simplified, hand-written summaries of the logic behind the lab. They are not the files the app runs and may differ in naming and detail.

Step 01

Synthetic population and network

Builds 1,000 consumers in 5 communities. Friendships form more often inside a community than across communities, so the tie probabilities control how connected the groups are.

Illustrative JavaScript
function generateNetwork(settings) {
  const rng = seededRandom(settings.seed)
  const people = []

  for (let id = 0; id < settings.n; id++) {
    const community = Math.floor(rng() * settings.communities)
    const trait = rng() < 0.5 ? 1 : 0              // hidden shared trait
    people.push({
      id,
      community,
      trait,
      preference: clamp(normal(rng, 0, 1) + 0.6 * trait),
      priceSensitivity: clamp(normal(rng, 0, 1) - 0.4 * trait),
      influence: Math.exp(normal(rng, 0, 0.6)),   // a few very influential people
    })
  }

  const friends = people.map(() => [])
  for (let a = 0; a < people.length; a++) {
    for (let b = a + 1; b < people.length; b++) {
      const same = people[a].community === people[b].community
      const chance = same ? settings.p_in : settings.p_out
      if (rng() < chance) {
        friends[a].push(b)
        friends[b].push(a)                          // mutual friendship
      }
    }
  }
  return { people, friends }
}

Assumptions

  • Preference, price sensitivity and influence are drawn once per consumer and never change.
  • A hidden shared trait nudges both preference and price sensitivity. It is what creates confounding later.
  • Friendships are mutual. Within a community the tie chance is p_in; across communities it is p_out.

Step 02

Four seeding strategies and the baseline

Every strategy spends the same budget and must pick exactly that many different people. The baseline invites nobody.

Illustrative JavaScript
function chooseInvites(strategy, network, settings, rng) {
  const { people, friends } = network
  const budget = settings.budget
  const ids = people.map((p) => p.id)

  let picked
  if (strategy === 'no_campaign') {
    picked = []                                     // baseline: nobody is invited
  } else if (strategy === 'random') {
    picked = shuffle(ids, rng).slice(0, budget)
  } else if (strategy === 'high_degree') {
    picked = sortBy(ids, (i) => -friends[i].length).slice(0, budget)
  } else if (strategy === 'high_uptake') {
    picked = sortBy(ids, (i) => -baseScore(people[i], settings)).slice(0, budget)
  } else if (strategy === 'community_coverage') {
    picked = []
    for (const c of communitiesOf(people)) {
      const members = ids.filter((i) => people[i].community === c)
      const share = Math.round((budget * members.length) / people.length)
      picked.push(...sortBy(members, (i) => -friends[i].length).slice(0, share))
    }
    picked = topUpToBudget(picked, ids, friends, budget)   // exactly "budget" people
  }

  assert(new Set(picked).size === picked.length)    // invitations are unique
  return picked
}

Assumptions

  • Highest predicted uptake ranks people by the model's own adoption score, without looking at friends.
  • Community coverage splits the budget across communities in proportion to size, then takes the most connected people in each.
  • Random picks use the run's seed, so they are reproducible.

Step 03

90-day adoption with shared random draws

Each day every eligible consumer who has not adopted yet gets one chance. The same random numbers are used for the baseline and for every strategy, so differences come from the invitations alone.

Illustrative JavaScript
function simulate(network, draws, invited, settings, peerOn, fixedExposure = null) {
  const { people, friends } = network
  const adoptedOn = new Array(people.length).fill(-1)   // -1 means "not adopted"
  const shocks = dailyShocks(settings.seed, settings.shock_sd)

  for (let day = 0; day < 90; day++) {
    const newToday = []
    for (const p of people) {
      if (adoptedOn[p.id] >= 0) continue
      if (day < settings.launch_day && !invited.has(p.id)) continue  // not yet eligible

      // share of this person's friends (weighted by influence) who adopted BEFORE today
      const exposure = fixedExposure
        ? fixedExposure[day][p.id]
        : weightedShare(friends[p.id], adoptedOn, people, day)

      const score =
        settings.offer_strength * p.preference -
        settings.price * p.priceSensitivity +
        shocks[day] +
        (peerOn ? settings.peer_strength * exposure : 0) +
        (invited.has(p.id) ? settings.invite_boost : 0)

      const chance = settings.base_rate * logistic(score)
      if (draws[day][p.id] < chance) newToday.push(p.id)     // same draw in every scenario
    }
    for (const id of newToday) adoptedOn[id] = day           // apply together
  }
  return adoptedOn
}

Assumptions

  • Adoption is synchronous: everyone decides using yesterday's state, then all new adopters are applied together.
  • Invitees are eligible from day 0. Everyone else becomes eligible on the public launch day.
  • A shared daily shock moves the whole market up or down on the same days in every scenario.
  • This is synthetic data, not calibrated to a real market.

Step 04

Peer-influence toggle

Runs each strategy twice with identical draws: once with friends influencing each other, once without. The gap is how much of the lift depends on peers.

Illustrative JavaScript
function peerDependence(network, draws, invited, settings, baselineOn, baselineOff) {
  const withPeers = simulate(network, draws, invited, settings, true)
  const withoutPeers = simulate(network, draws, invited, settings, false)

  const liftOn = count(withPeers) - count(baselineOn)
  const liftOff = count(withoutPeers) - count(baselineOff)

  return {
    liftOn,
    liftOff,
    peerShare: liftOn > 0 ? (liftOn - liftOff) / liftOn : null,   // null = undefined
  }
}

Assumptions

  • Turning peers off removes only the friends' term; offer, price, invitation and shocks stay as they are.
  • Peer share is undefined when the lift with peers on is zero or negative.

Step 05

Staged experiment with hidden or revealed trait

Invites go to a random half. Truth comes from re-running the simulator under each counterfactual. The recovered estimate uses only what a real study would see, and can adjust for the shared trait only when it is revealed.

Illustrative JavaScript
function mediation(network, draws, settings) {
  const treated = randomHalf(network, settings.seed)
  const none = simulate(network, draws, new Set(), settings, true)           // Y(0, M0)
  const full = simulate(network, draws, treated, settings, true)             // Y(1, M1)
  const direct = simulate(network, draws, treated, settings, true,
                          exposureOf(none))                                  // Y(1, M0)

  const truth = {
    total: mean(treated, full) - mean(treated, none),
    nde:   mean(treated, direct) - mean(treated, none),
    nie:   mean(treated, full) - mean(treated, direct),
  }

  // Recovered from data: stratify on the mediator (friends' adoption), and
  // on the trait only when it is revealed.
  function recover(revealTrait) {
    let nde = 0, nie = 0
    for (const stratum of strata(network, revealTrait)) {
      for (const level of mediatorLevels(full, stratum)) {
        if (tooFew(level.treated) || tooFew(level.control)) continue     // sparse support
        const gap = level.treated.meanOutcome - level.control.meanOutcome
        nde += gap * level.control.share * stratum.weight
        nie += level.treated.meanOutcome *
               (level.treated.share - level.control.share) * stratum.weight
      }
    }
    return { nde, nie, total: nde + nie }
  }
  return { truth, hidden: recover(false), revealed: recover(true) }
}

Assumptions

  • Total effect = direct effect + indirect effect. Direct holds friends' exposure at its no-campaign level; indirect is what changes through friends.
  • Staged window: mediator at day 15, outcome at day 30. Rolling window: mediator at day 30, outcome at day 90.
  • A staged indirect effect can be zero even though rolling peer amplification is not, because feedback chains need time to build.
  • Recovered effects need overlap: cells with too few consumers in either arm are dropped and reported as sparse.

Step 06

Metrics

Everything is a paired difference against the baseline that used the same draws, repeated over several fresh sets of draws to get an interval.

Illustrative JavaScript
function summarize(runs, baselineRuns, settings) {
  const gains = runs.map((r, i) => count(r) - count(baselineRuns[i]))   // paired
  const mean = average(gains)
  const se = stdev(gains) / Math.sqrt(gains.length)

  const byCommunity = communities.map((c) => countIn(runs[0], c) - countIn(baselineRuns[0], c))
  const positive = byCommunity.map((g) => Math.max(0, g))
  const total = sum(positive)

  return {
    incremental: gains[0],
    mean,
    interval95: [mean - 1.96 * se, mean + 1.96 * se],
    positiveLiftShare: gains.filter((g) => g > 0).length / gains.length,
    timeToTarget: firstDayAtOrAbove(runs[0], settings.target_share * settings.n),  // null = not reached
    costPerIncremental: gains[0] > 0 ? (settings.budget * settings.cost_per_invite) / gains[0] : null,
    herfindahl: total > 0 ? sum(positive.map((g) => (g / total) ** 2)) : null,
    signedCommunityGains: byCommunity,
  }
}

Assumptions

  • The interval is a normal approximation over the paired replicates, a guide rather than a guarantee.
  • Cost per incremental adopter is undefined when incremental adopters are zero or negative.
  • Concentration is a Herfindahl index of positive community gains; higher means gains sit in fewer communities.
  • A consumer is reached when invited, adopted, or a friend adopted.

Step 07

Reproducible seeds and settings

Every run is stored with its full settings and seed, plus a fingerprint of them. Running the same settings again gives identical numbers.

Illustrative JavaScript
function saveRun(kind, settings, results) {
  const canonical = sortKeys(settings)                       // stable key order
  return {
    kind,
    seed: settings.seed,
    settings: canonical,
    configHash: sha1(JSON.stringify(canonical)),             // fingerprint of the config
    results,
  }
}

function replicateSeed(baseSeed, r) {
  return r === 0 ? baseSeed : baseSeed + 7000 * r            // fresh draws, same network
}

// Re-running a saved run:
//   const again = run(saved.kind, saved.settings)
//   again.results deep-equals saved.results

Assumptions

  • Every random choice (network, draws, shocks, random invites) is derived from the seed.
  • Replicate r uses the seed shifted by a fixed step, so replicates are fresh but repeatable.

Step 08

Experiment assistant validation

Turns a plain-language question into a settings object, then checks every value against fixed bounds. Anything out of bounds is refused with a message, never silently changed.

Illustrative JavaScript
const bounds = {
  n:            { min: 12,  max: 2000 },
  communities:  { min: 2,   max: 10 },
  budget:       { min: 1,   max: 200 },
  replicates:   { min: 2,   max: 30 },
  launch_day:   { min: 0,   max: 60 },
  shock_sd:     { min: 0,   max: 1 },
}

function planFromQuestion(text) {
  const q = text.toLowerCase()
  const settings = { ...defaults }
  let kind = 'compare'

  if (/connectivity|cross-community|sweep/.test(q)) kind = 'sweep'
  if (/mediat|direct|indirect|trait/.test(q)) kind = 'mediation'
  if (/walkthrough|24.node/.test(q)) Object.assign(settings, walkthroughPreset)

  const invites = q.match(/(\d+)\s*invites?/)
  if (invites) settings.budget = Number(invites[1])
  if (/no peer|without peer/.test(q)) settings.peer_influence = false

  const problems = Object.entries(bounds)
    .filter(([key, b]) => settings[key] < b.min || settings[key] > b.max)
    .map(([key, b]) => key + ' must be between ' + b.min + ' and ' + b.max)

  return problems.length ? { ok: false, problems } : { ok: true, kind, settings }
}

Assumptions

  • The assistant only recognizes the experiment kinds and settings listed in the bounds table.
  • Words it does not understand fall back to the defaults, and the plan shows which values were assumed.