Skip to content

Multinomial mode: ResidualJunctionCompartment.initial_flush() double counts the residual link #552

Open

Description

@RomeshA

Found in review of #539.

Problem

ResidualJunctionCompartment.initial_flush() in atomica/model.py draws

outflow_fractions = rng.multinomial(self.vals[0], outflow_fractions, size=1)[0] / (self.vals[0] * sum(outflow_fractions))

numpy treats the last entry of pvals as the remainder probability, so when the residual link is last in outlinks the drawn residual column already holds the residual people. Dividing by n * sum(fractions) (where the residual fraction is 0) then renormalises so the fractions sum to 2. The residual destination receives n - sum(n * fractions), which is negative.

Reproduced: framework_junction_remainder_test.xlsx loses 13 of 100 people at t0 in multinomial mode; framework_junction_remainder_test_2.xlsx crashes with ValueError: n < 0 inside the first multinomial draw because a compartment was initialised negative.

The same latent issue applies to JunctionCompartment.initial_flush() if any outflow fraction is zero and the ordering of outlinks changes, since correctness currently depends on where numpy places the remainder.

Implementation plan

  1. Build the probability vector explicitly: for a residual junction set the residual link's probability to max(0, 1 - sum(others)), and for a plain junction normalise to sum to 1. Never rely on numpy's implicit remainder handling.
  2. Draw integer counts once and assign them directly to link.dest[0] += counts[i], bypassing the fraction arithmetic entirely in multinomial mode.
  3. Reuse the helper from the balance() fix so initial_flush() and balance() share one code path for probability construction.
  4. Add a regression test that initialises a residual junction with a nonzero value in multinomial mode and asserts all downstream values are non-negative integers summing to the initial value.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions