-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlagueField.java
More file actions
294 lines (272 loc) · 12.5 KB
/
Copy pathPlagueField.java
File metadata and controls
294 lines (272 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import java.util.Random;
/**
* PlagueField - a stochastic SIR/SIRS epidemic cellular automaton rendered
* live to the terminal, or run headless for reproducible batch stats.
*
* Run with: java PlagueField.java [flags]
* See README.md for the full flag list.
*/
public class PlagueField {
enum State { S, I, R }
/** The grid itself: per-cell epidemic state plus per-cell timers. */
static final class Grid {
final int width, height;
final boolean wrap = true;
State[][] state;
int[][] infectedFor; // ticks spent infected, once state == I
int[][] recoveredFor; // ticks spent recovered, once state == R (for waning immunity)
boolean[][] everInfected; // sticky flag; survives waning so cumulative stats stay correct
long everInfectedCount;
final Random rng;
final double beta; // per-neighbor infection probability
final int infectionDuration; // ticks until I -> R
final int waning; // ticks until R -> S, 0 = permanent immunity
Grid(int width, int height, int initialInfected, long seed,
double beta, int infectionDuration, int waning) {
this.width = width;
this.height = height;
this.beta = beta;
this.infectionDuration = infectionDuration;
this.waning = waning;
this.rng = new Random(seed);
this.state = new State[height][width];
this.infectedFor = new int[height][width];
this.recoveredFor = new int[height][width];
this.everInfected = new boolean[height][width];
for (State[] row : state) java.util.Arrays.fill(row, State.S);
int placed = 0;
int total = width * height;
initialInfected = Math.min(initialInfected, total);
while (placed < initialInfected) {
int x = rng.nextInt(width);
int y = rng.nextInt(height);
if (state[y][x] == State.S) {
state[y][x] = State.I;
everInfected[y][x] = true;
everInfectedCount++;
placed++;
}
}
}
/** Count infected Moore neighbors of (x, y), with optional wraparound. */
private int infectedNeighbors(int x, int y) {
int count = 0;
for (int dy = -1; dy <= 1; dy++) {
for (int dx = -1; dx <= 1; dx++) {
if (dx == 0 && dy == 0) continue;
int nx = x + dx, ny = y + dy;
if (wrap) {
nx = ((nx % width) + width) % width;
ny = ((ny % height) + height) % height;
} else if (nx < 0 || ny < 0 || nx >= width || ny >= height) {
continue;
}
if (state[ny][nx] == State.I) count++;
}
}
return count;
}
/** Advance the whole grid by one tick. Returns true if any cell is still infected. */
boolean step() {
State[][] next = new State[height][width];
int[][] nextInfectedFor = new int[height][width];
int[][] nextRecoveredFor = new int[height][width];
boolean anyInfected = false;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
State s = state[y][x];
switch (s) {
case S -> {
int k = infectedNeighbors(x, y);
double pInfect = 1.0 - Math.pow(1.0 - beta, k);
if (k > 0 && rng.nextDouble() < pInfect) {
next[y][x] = State.I;
if (!everInfected[y][x]) {
everInfected[y][x] = true;
everInfectedCount++;
}
} else {
next[y][x] = State.S;
}
}
case I -> {
int dur = infectedFor[y][x] + 1;
if (dur >= infectionDuration) {
next[y][x] = State.R;
} else {
next[y][x] = State.I;
nextInfectedFor[y][x] = dur;
}
}
case R -> {
if (waning > 0) {
int dur = recoveredFor[y][x] + 1;
if (dur >= waning) {
next[y][x] = State.S;
} else {
next[y][x] = State.R;
nextRecoveredFor[y][x] = dur;
}
} else {
next[y][x] = State.R;
}
}
}
if (next[y][x] == State.I) anyInfected = true;
}
}
state = next;
infectedFor = nextInfectedFor;
recoveredFor = nextRecoveredFor;
return anyInfected;
}
/** Returns {susceptible, infected, recovered} counts. */
int[] counts() {
int s = 0, i = 0, r = 0;
for (State[] row : state) {
for (State c : row) {
switch (c) {
case S -> s++;
case I -> i++;
case R -> r++;
}
}
}
return new int[] { s, i, r };
}
String render(boolean color) {
StringBuilder sb = new StringBuilder();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
char ch = switch (state[y][x]) {
case S -> '.';
case I -> '#';
case R -> 'o';
};
if (color) {
String code = switch (state[y][x]) {
case S -> "[90m"; // grey
case I -> "[91m"; // red
case R -> "[94m"; // blue
};
sb.append(code).append(ch).append("[0m");
} else {
sb.append(ch);
}
}
sb.append('\n');
}
return sb.toString();
}
}
static final class Args {
int width = 60, height = 24;
int initialInfected = 3;
long seed = System.nanoTime();
double beta = 0.22;
int infectionDuration = 6;
int waning = 0;
int ticks = 0; // 0 = live mode: run until extinction or safety cap
int delayMs = 90;
boolean headless = false;
boolean noColor = false;
int maxTicks = 2000; // safety cap for live/extinction mode
static Args parse(String[] argv) {
Args a = new Args();
for (int i = 0; i < argv.length; i++) {
String flag = argv[i];
String val = (i + 1 < argv.length) ? argv[i + 1] : null;
switch (flag) {
case "--width" -> { a.width = Integer.parseInt(val); i++; }
case "--height" -> { a.height = Integer.parseInt(val); i++; }
case "--initial-infected" -> { a.initialInfected = Integer.parseInt(val); i++; }
case "--seed" -> { a.seed = Long.parseLong(val); i++; }
case "--beta" -> { a.beta = Double.parseDouble(val); i++; }
case "--duration" -> { a.infectionDuration = Integer.parseInt(val); i++; }
case "--waning" -> { a.waning = Integer.parseInt(val); i++; }
case "--ticks" -> { a.ticks = Integer.parseInt(val); i++; }
case "--delay" -> { a.delayMs = Integer.parseInt(val); i++; }
case "--headless" -> a.headless = true;
case "--no-color" -> a.noColor = true;
case "--help" -> { printHelp(); System.exit(0); }
default -> {
System.err.println("Unknown flag: " + flag);
printHelp();
System.exit(1);
}
}
}
return a;
}
static void printHelp() {
System.out.println("""
PlagueField - stochastic SIR/SIRS epidemic cellular automaton
Usage: java PlagueField.java [flags]
--width N grid width (default 60)
--height N grid height (default 24)
--initial-infected N seed infections (default 3)
--seed N RNG seed (default random)
--beta F per-neighbor infect chance, 0..1 (default 0.22)
--duration N ticks infected before recovery (default 6)
--waning N ticks until immunity fades, 0=permanent (default 0)
--ticks N run exactly N ticks headless, print summary
--delay MS ms between frames in live mode (default 90)
--headless no animation, print only the final summary
--no-color disable ANSI color in rendered frames
--help show this message
""");
}
}
public static void main(String[] args) throws InterruptedException {
Args a = Args.parse(args);
Grid grid = new Grid(a.width, a.height, a.initialInfected, a.seed,
a.beta, a.infectionDuration, a.waning);
int peakInfected = grid.counts()[1];
int peakTick = 0;
int totalCells = a.width * a.height;
boolean liveMode = a.ticks == 0 && !a.headless;
int tick = 0;
boolean infectedRemain = true;
int limit = a.ticks > 0 ? a.ticks : a.maxTicks;
while (tick < limit && (a.ticks > 0 || infectedRemain)) {
if (liveMode) {
System.out.print("[H[2J");
int[] c = grid.counts();
System.out.printf("PlagueField tick=%d S=%d I=%d R=%d%n", tick, c[0], c[1], c[2]);
System.out.print(grid.render(!a.noColor));
System.out.flush();
Thread.sleep(a.delayMs);
}
infectedRemain = grid.step();
tick++;
int infectedNow = grid.counts()[1];
if (infectedNow > peakInfected) {
peakInfected = infectedNow;
peakTick = tick;
}
if (a.ticks == 0 && a.waning == 0 && !infectedRemain) break; // classic SIR: stop once extinct
}
int[] finalCounts = grid.counts();
if (liveMode) {
System.out.print("[H[2J");
System.out.printf("PlagueField tick=%d S=%d I=%d R=%d%n", tick, finalCounts[0], finalCounts[1], finalCounts[2]);
System.out.print(grid.render(!a.noColor));
} else if (!a.headless) {
System.out.print(grid.render(!a.noColor));
}
long everInfected = grid.everInfectedCount;
System.out.println("---- SIMULATION COMPLETE ----");
System.out.printf("seed=%d ticks=%d grid=%dx%d beta=%.3f duration=%d waning=%d%n",
a.seed, tick, a.width, a.height, a.beta, a.infectionDuration, a.waning);
System.out.printf("final: S=%d I=%d R=%d (total=%d, conserved=%b)%n",
finalCounts[0], finalCounts[1], finalCounts[2],
finalCounts[0] + finalCounts[1] + finalCounts[2],
finalCounts[0] + finalCounts[1] + finalCounts[2] == totalCells);
System.out.printf("peak infected: %d at tick %d%n", peakInfected, peakTick);
System.out.printf("ever infected: %d (%.1f%% of population)%n",
everInfected, 100.0 * everInfected / totalCells);
if (a.waning > 0) {
System.out.printf("mode: SIRS (waning=%d) -- endemic/oscillating, not expected to reach S=0%n", a.waning);
}
}
}