def test_halt_finalise() -> None: class HCModel(no.Model): def __init__(self, timeline: no.Timeline, halt: bool = False) -> None: super().__init__(timeline, no.MonteCarlo.deterministic_identical_stream) self.do_halt = halt self.finalise_called = False def step(self) -> None: if self.do_halt: self.halt() def finalise(self) -> None: self.finalise_called = True m = HCModel(no.LinearTimeline(0, 3, 3)) no.run(m) assert m.finalise_called m = HCModel(no.LinearTimeline(0, 3, 3), True) no.run(m) assert not m.finalise_called assert not m.timeline.at_end() assert m.timeline.index() == 1 no.run(m) assert not m.finalise_called assert not m.timeline.at_end() assert m.timeline.index() == 2 no.run(m) assert m.finalise_called assert m.timeline.at_end() assert m.timeline.index() == 3
def __init__(self, mortality_hazard_file: str, n: int, max_age: float) -> None: # This is case-based model the timeline refers to the age of the cohort timeline = neworder.LinearTimeline(0.0, max_age, int(max_age)) super().__init__(timeline, neworder.MonteCarlo.deterministic_identical_stream) # initialise cohort self.mortality_hazard = pd.read_csv(mortality_hazard_file) # store the largest age we have a rate for self.max_rate_age = max(self.mortality_hazard.DC1117EW_C_AGE) - 1 # neworder.log(self.mortality_hazard.head()) self.population = pd.DataFrame(index=neworder.df.unique_index(n), data={ "alive": True, "age": 0.0, "age_at_death": neworder.time.far_future() }) self.max_age = max_age
def __init__(self, N: int, range: float, vision: float, exclusion: float, speed: float) -> None: super().__init__(no.LinearTimeline(0.0, 0.01), no.MonteCarlo.nondeterministic_stream) self.N = N self.range = range self.vision = vision self.exclusion = exclusion self.speed = speed # continuous wraparound 2d space self.domain = no.Space(np.zeros(2), np.full(2, self.range), edge=no.Edge.WRAP) # maximum turns for each interaction self.sep_max_turn = TWO_PI / 240 # 1.5 degrees self.align_max_turn = TWO_PI / 72 # 5 degrees self.cohere_max_turn = TWO_PI / 120 # 3 degrees # initially in [0,1]^dim self.boids = pd.DataFrame( index=pd.Index(name="id", data=no.df.unique_index(self.N)), data={ "x": self.mc.ustream(N) * self.range, "y": self.mc.ustream(N) * self.range, "theta": self.mc.ustream(N) * TWO_PI # zero is +ve x axis }) self.fig, self.g = self.__init_visualisation() # suppress divsion by zero warnings np.seterr(divide='ignore')
def test_open_ended_timeline() -> None: class OpenEndedModel(no.Model): def __init__(self, timeline: no.Timeline) -> None: super().__init__(timeline, no.MonteCarlo.deterministic_identical_stream) self.i = 0 def step(self) -> None: assert self.i == self.timeline.index() self.i += 1 if self.i > 10: self.halt() m = OpenEndedModel(no.LinearTimeline(0, 1)) assert m.timeline.end() == no.time.far_future() assert m.timeline.nsteps() == -1 assert m.timeline.dt() == 1.0 no.run(m) assert m.i == 11 m = OpenEndedModel(no.CalendarTimeline(date(2020, 12, 17), 1, "d")) assert m.timeline.end() == no.time.far_future() assert m.timeline.nsteps() == -1 assert np.fabs(m.timeline.dt() - 1.0 / 365.2475) < 1e-8 no.run(m) assert m.i == 11 m = OpenEndedModel(no.CalendarTimeline(date(2020, 12, 17), 1, "m")) assert m.timeline.end() == no.time.far_future() assert m.timeline.nsteps() == -1 assert np.fabs(m.timeline.dt() - 31.0 / 365.2475) < 1e-8 no.run(m) assert m.i == 11
def __init__(self, start: float, end: float, steps: int) -> None: super().__init__(no.LinearTimeline(start, end, steps), no.MonteCarlo.deterministic_identical_stream) self.i = 0 self.t = start self.steps = steps self.end = end
def __init__(self) -> None: # 10 steps of 10 super().__init__(no.LinearTimeline(0, 100, 10), no.MonteCarlo.deterministic_identical_stream) self.step_count = 0 self.t_end = 100 self.i_end = 10
def __init__(self, option: dict[str, Any], market: dict[str, float], nsims: int) -> None: # Using exact MC calc of GBM requires only 1 timestep timeline = neworder.LinearTimeline(0.0, option["expiry"], 1) super().__init__(timeline, neworder.MonteCarlo.deterministic_identical_stream) self.option = option self.market = market self.nsims = nsims
def __init__(self, N): super().__init__(no.LinearTimeline(0.0, 0.1), no.MonteCarlo.deterministic_identical_stream) self.N = N self.speed = 0.1 self.range = 1.0 self.vision = 0.2 self.exclusion = 0.01 self.sep_wt = 1e-3 self.align_wt = 1e-2 self.cohere_wt = 1e-4 if TEST_MODE: self.N = 2 self.boids = pd.DataFrame(index=pd.Index(name="id", data=no.df.unique_index( self.N)), data={ "x": [0.01, 1], "y": [0, 1], "z": 0.0, "vx": [0.5, -0.5], "vy": [0.5, -0.5], "vz": 0.0 }) else: # initially in [0,1]^3 vx = self.mc().ustream(N) vy = self.mc().ustream(N) vz = self.mc().ustream(N) self.boids = pd.DataFrame( index=pd.Index(name="id", data=no.df.unique_index(self.N)), data={ "x": self.mc().ustream(N) * self.range, "y": self.mc().ustream(N) * self.range, "z": 0.0, #self.mc().ustream(N) * self.range, "vx": vx - np.mean(vx), # ensure v is balanced "vy": vy - np.mean(vy), "vz": 0, #vz - np.mean(vz) # "vx": 0.0, # "vy": 0.0, # "vz": 0.0 }) self.__normalise_velocity(self.speed) self.ax, self.g = self.__init_visualisation()
def __init__(self, N: int, G: float, dt: float): super().__init__(no.LinearTimeline(0, dt), no.MonteCarlo.deterministic_identical_stream) # unbounded domain self.domain = Space.unbounded(3) self.G = G self.dt = dt m_max = 1.0 x_max = 1.0 y_max = 1.0 r = self.mc.ustream(N) - 0.5 theta = self.mc.ustream(N) * np.pi x = r * np.cos(theta) * x_max y = r * np.sin(theta) * y_max self.bodies = pd.DataFrame( index=no.df.unique_index(N), data={ "m": self.mc.ustream(N) * m_max, "x": x, "y": y, "z": 0.1 * (self.mc.ustream(N) - 0.5), # create angular momentum "vx": -y, "vy": x, "vz": 0.0, "ax": np.nan, "ay": np.nan, "az": np.nan, "ke": np.nan, "pe": np.nan }) # balance momentum by changing velocity of body 0 self.bodies.vx[0] -= (self.bodies.m * self.bodies.vx).sum() / self.bodies.m[0] self.bodies.vy[0] -= (self.bodies.m * self.bodies.vy).sum() / self.bodies.m[0] self.bodies.vz[0] -= (self.bodies.m * self.bodies.vz).sum() / self.bodies.m[0] self.__calc_a() self.E0 = np.sum(self.bodies.pe + self.bodies.ke) self.g = self.__init_visualisation()
def __init__(self, nx: int, ny: int, n: int, edge: no.Edge = no.Edge.WRAP) -> None: super().__init__(no.LinearTimeline(0, 1), no.MonteCarlo.nondeterministic_stream) # create n automata at regular positions init_state = np.zeros((nx * ny)) init_state[::2] = 1 init_state[::7] = 1 self.domain = no.StateGrid(init_state.reshape(ny, nx), edge=edge) #self.domain.state[20:23, 20:23] = Conway.__glider self.fig, self.g = self.__init_visualisation()
def __init__(self, gridsize: tuple[int, int], pct_white: float, pct_black: float) -> None: super().__init__(no.LinearTimeline(0, 1), no.MonteCarlo.deterministic_independent_stream) p = [pct_white, pct_black, 1 - pct_white - pct_black] init_pop = self.mc.sample(np.prod(gridsize), p).reshape(gridsize) self.domain = no.StateGrid(init_pop, edge=no.Edge.WRAP) self.age = (self.mc.ustream(self.domain.state.size) * DaisyWorld.MAX_AGE).astype(int).reshape(self.domain.state.shape) self.temperature = np.zeros(self.domain.state.shape) self.albedo = np.array([0.4, 0.75, 0.25]) self.temperature = self.__calc_local_heating() self.__diffuse() print(self.domain.state) # print(self.age) # print(self.temperature) self.fig, self.img = self.__init_visualisation()
def test_consistency() -> None: # need to wrap timeline in a model to do the stepping, which isnt directly accessible from python class ConsistencyTest(no.Model): def __init__(self, timeline: no.Timeline) -> None: super().__init__(timeline, no.MonteCarlo.deterministic_identical_stream) def step(self) -> None: pass m = ConsistencyTest(no.NoTimeline()) assert m.timeline.nsteps() == 1 no.run(m) assert m.timeline.index() == 1 m = ConsistencyTest(no.LinearTimeline(2020, 2021, 12)) assert m.timeline.nsteps() == 12 no.run(m) assert m.timeline.index() == 12 assert m.timeline.time() == 2021 m = ConsistencyTest(no.NumericTimeline([2020 + i / 12 for i in range(13)])) assert m.timeline.nsteps() == 12 no.run(m) assert m.timeline.index() == 12 assert m.timeline.time() == 2021 s = date(2019, 10, 31) e = date(2020, 10, 31) m = ConsistencyTest(no.CalendarTimeline(s, e, 1, "m")) assert m.timeline.time().date() == s assert m.timeline.nsteps() == 12 no.run(m) assert m.timeline.time().date() == e assert m.timeline.index() == 12
def __init__(self) -> None: super().__init__(no.LinearTimeline(0, 10, 10), no.MonteCarlo.deterministic_identical_stream) self.x = 0.0
# !setup! import neworder from parallel import Parallel # import our model definition #neworder.verbose() #neworder.checked(False) # must be MPI enabled assert neworder.mpi.size( ) > 1, "This configuration requires MPI with >1 process" # !setup! # !run! population_size = 100 p = 0.01 timeline = neworder.LinearTimeline(0, 10, 10) model = Parallel(timeline, p, population_size) neworder.run(model) #!run!
def __init__(self, t0: float, n: int) -> None: super().__init__(no.LinearTimeline(t0, t0 + n, n), no.MonteCarlo.deterministic_identical_stream)
# params of poisson process transitions (p=lambda.exp(-lambda.x) where lambda=1/mean) mu_01 = 13.0 mu_02 = 23.0 mu_12 = 29.0 mu_20 = 17.0 lambda_01 = 1.0 / mu_01 lambda_02 = 1.0 / mu_02 lambda_12 = 1.0 / mu_12 lambda_20 = 1.0 / mu_20 states = np.array([0, 1, 2]) # possible transitions: # 0 -> 1 # \ \ # <-> 2 transition_matrix = np.array( [[1.0 - lambda_01 * dt - lambda_02 * dt, lambda_01 * dt, lambda_02 * dt], [0.0, 1.0 - lambda_12 * dt, lambda_12 * dt], [lambda_20 * dt, 0.0, 1.0 - lambda_20 * dt]]) timeline = no.LinearTimeline(0, tmax, tmax) model = MarkovChain(timeline, npeople, states, transition_matrix) start = time.time() no.run(model) no.log("run time = %.2fs" % (time.time() - start)) visualisation.show(model)
def __init__(self, params: dict[str, Any]) -> None: super().__init__(no.LinearTimeline(0.0, 1.0), no.MonteCarlo.deterministic_independent_stream) # hard-coded to unit timestep self.width = params["grid"]["width"] self.height = params["grid"]["height"] self.domain = no.Space(np.array([0, 0]), np.array([self.width, self.height]), edge=no.Edge.WRAP) n_wolves = params["wolves"]["starting_population"] n_sheep = params["sheep"]["starting_population"] self.wolf_reproduce = params["wolves"]["reproduce"] self.sheep_reproduce = params["sheep"]["reproduce"] self.init_wolf_speed = params["wolves"]["speed"] self.init_sheep_speed = params["sheep"]["speed"] self.wolf_speed_stddev = np.sqrt(params["wolves"]["speed_variance"]) self.sheep_speed_stddev = np.sqrt(params["sheep"]["speed_variance"]) self.wolf_gain_from_food = params["wolves"]["gain_from_food"] self.sheep_gain_from_food = params["sheep"]["gain_from_food"] self.grass_regrowth_time = params["grass"]["regrowth_time"] ncells = self.width * self.height self.grass = pd.DataFrame( index=pd.Index(name="id", data=no.df.unique_index(ncells)), data={ "x": np.tile(np.arange(self.width) + 0.5, self.height), "y": np.repeat(np.arange(self.height) + 0.5, self.width), # 50% initial probability of being fully grown, other states uniform "countdown": self.mc.sample(ncells, [0.5] + [0.5 / (self.grass_regrowth_time - 1)] * (self.grass_regrowth_time - 1)) }) self.wolves = pd.DataFrame( index=pd.Index(name="id", data=no.df.unique_index(n_wolves)), data={ "x": self.mc.ustream(n_wolves) * self.width, "y": self.mc.ustream(n_wolves) * self.height, "speed": self.init_wolf_speed, "energy": (self.mc.ustream(n_wolves) + self.mc.ustream(n_wolves)) * self.wolf_gain_from_food }) self.__assign_cell(self.wolves) self.sheep = pd.DataFrame( index=pd.Index(name="id", data=no.df.unique_index(n_sheep)), data={ "x": self.mc.ustream(n_sheep) * self.width, "y": self.mc.ustream(n_sheep) * self.height, "speed": self.init_sheep_speed, "energy": (self.mc.ustream(n_sheep) + self.mc.ustream(n_sheep)) * self.sheep_gain_from_food }) self.__assign_cell(self.sheep) self.wolf_pop = [len(self.wolves)] self.sheep_pop = [len(self.sheep)] self.grass_prop = [ 100.0 * len(self.grass[self.grass.countdown == 0]) / len(self.grass) ] self.wolf_speed = [self.wolves.speed.mean()] self.sheep_speed = [self.sheep.speed.mean()] self.wolf_speed_var = [self.wolves.speed.var()] self.sheep_speed_var = [self.sheep.speed.var()] self.t = [self.timeline.index()] (self.ax_g, self.ax_w, self.ax_s, self.ax_t1, self.ax_wt, self.ax_st, self.ax_t2, self.ax_gt, self.ax_t3, self.ax_ws, self.b_ws, self.ax_t4, self.ax_ss, self.b_ss) = self.__init_plot() # no.log(self.wolves) # no.log(self.sheep) # no.log(self.grass) self.paused = False # seed numpy random generator using our generator (for reproducible normal samples) self.npgen = np.random.default_rng(self.mc.raw())