gov.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. import {cachedFetchJSON} from './cache';
  2. const renderTarget = document.querySelector('#gov')!;
  3. const planetInput = document.querySelector('#planet') as HTMLInputElement;
  4. const popSelect = document.querySelector('#pop') as HTMLSelectElement;
  5. function serializeToHash(planet: string, pop: Pop): void {
  6. const params = new URLSearchParams({'planet': planet, 'pop': pop});
  7. document.location.hash = params.toString();
  8. }
  9. function deserializeFromHash(): {planet: string, pop: Pop} | null {
  10. const params = new URLSearchParams(document.location.hash.substring(1));
  11. const planet = params.get('planet');
  12. const pop = params.get('pop');
  13. if (planet && pop && ['pio', 'set', 'tec', 'eng', 'sci'].includes(pop)) {
  14. planetInput.value = planet;
  15. popSelect.value = pop;
  16. return {planet, pop: pop as Pop};
  17. } else
  18. return null;
  19. }
  20. document.querySelector('form')!.addEventListener('submit', async (event) => {
  21. event.preventDefault();
  22. const planet = planetInput.value;
  23. const pop = popSelect.value as Pop;
  24. if (planet && pop) {
  25. await render(planet, pop);
  26. serializeToHash(planet, pop);
  27. }
  28. });
  29. {
  30. const deserialized = deserializeFromHash();
  31. if (deserialized)
  32. void render(deserialized.planet, deserialized.pop);
  33. }
  34. async function render(planetName: string, pop: Pop) {
  35. const loader = document.querySelector('#loader') as HTMLElement;
  36. loader.style.display = 'block';
  37. renderTarget.innerHTML = '';
  38. try {
  39. await _render(planetName, pop);
  40. } catch (e) {
  41. renderTarget.textContent = (e as Error).message;
  42. }
  43. loader.style.display = 'none';
  44. }
  45. async function _render(planetName: string, pop: Pop) {
  46. const encodedPlanetName = encodeURIComponent(planetName);
  47. const [planet, siteCounts, infras, allPrices]: [Planet, SiteCount[], Infrastructure[], Price[]] = await Promise.all([
  48. cachedFetchJSON(`https://api.fnar.net/planet/${encodedPlanetName}?include_population_reports=true`),
  49. cachedFetchJSON(`https://api.fnar.net/planet/sitecount?planet=${encodedPlanetName}`),
  50. cachedFetchJSON(`https://api.fnar.net/infrastructure?infrastructure=${encodedPlanetName}&include_upkeeps=true`),
  51. cachedFetchJSON('https://api.prunplanner.org/data/exchanges'),
  52. ]);
  53. let lastPOPR = null;
  54. for (const report of planet.PopulationReports) {
  55. if (!lastPOPR || report.SimulationPeriod > lastPOPR.SimulationPeriod)
  56. lastPOPR = report;
  57. }
  58. if (lastPOPR === null) {
  59. renderTarget.textContent = `no POPR for ${planetName}`;
  60. return;
  61. }
  62. const lastPOPRts = Math.floor(new Date(lastPOPR.ReportTimestamp).getTime() / 1000);
  63. const nextPOPRts = lastPOPRts + 7 * 24 * 60 * 60;
  64. let currentPop = 0;
  65. if (pop == 'pio') currentPop = lastPOPR.NextPopulationPioneer;
  66. else if (pop == 'set') currentPop = lastPOPR.NextPopulationSettler;
  67. else if (pop == 'tec') currentPop = lastPOPR.NextPopulationTechnician;
  68. else if (pop == 'eng') currentPop = lastPOPR.NextPopulationEngineer;
  69. else if (pop == 'sci') currentPop = lastPOPR.NextPopulationScientist;
  70. const siteCount = siteCounts[0].Count;
  71. const totalNeeds: Record<Need, number> = {
  72. 'safety': calcTotalNeeds(lastPOPR, 'safety'),
  73. 'health': calcTotalNeeds(lastPOPR, 'health'),
  74. 'comfort': calcTotalNeeds(lastPOPR, 'comfort'),
  75. 'culture': calcTotalNeeds(lastPOPR, 'culture'),
  76. 'education': calcTotalNeeds(lastPOPR, 'education'),
  77. };
  78. const currentPOPIFilled: POPIFill = new Map();
  79. for (const infra of infras) {
  80. const filled = calcPOPIFilled(infra);
  81. if (filled !== null)
  82. currentPOPIFilled.set(infra.Type, {tier: infra.CurrentLevel, numMats: filled});
  83. }
  84. const prices: Map<string, number> = new Map();
  85. for (const price of allPrices)
  86. if (price.exchange_code === 'IC1')
  87. prices.set(price.ticker, price.vwap_30d);
  88. renderTarget.innerHTML = `last POPR: ${lastPOPR.ReportTimestamp} (${lastPOPRts})
  89. <br>next POPR: ${new Date(nextPOPRts * 1000).toISOString()} (${nextPOPRts})
  90. <table>
  91. <tr>
  92. <th></th>
  93. <th>pio</th>
  94. <th>set</th>
  95. <th>tec</th>
  96. <th>eng</th>
  97. <th>sci</th>
  98. </tr>
  99. <tr>
  100. <th>population</th>
  101. <td>${lastPOPR.NextPopulationPioneer}<br>${formatDelta(lastPOPR.PopulationDifferencePioneer)}</td>
  102. <td>${lastPOPR.NextPopulationSettler}<br>${formatDelta(lastPOPR.PopulationDifferenceSettler)}</td>
  103. <td>${lastPOPR.NextPopulationTechnician}<br>${formatDelta(lastPOPR.PopulationDifferenceTechnician)}</td>
  104. <td>${lastPOPR.NextPopulationEngineer}<br>${formatDelta(lastPOPR.PopulationDifferenceEngineer)}</td>
  105. <td>${lastPOPR.NextPopulationScientist}<br>${formatDelta(lastPOPR.PopulationDifferenceScientist)}</td>
  106. </tr>
  107. <tr>
  108. <th>unemployed</th>
  109. <td>${unemployed(lastPOPR.NextPopulationPioneer, lastPOPR.PopulationDifferencePioneer, lastPOPR.OpenJobsPioneer, lastPOPR.UnemploymentRatePioneer)}</td>
  110. <td>${unemployed(lastPOPR.NextPopulationSettler, lastPOPR.PopulationDifferenceSettler, lastPOPR.OpenJobsSettler, lastPOPR.UnemploymentRateSettler)}</td>
  111. <td>${unemployed(lastPOPR.NextPopulationTechnician, lastPOPR.PopulationDifferenceTechnician, lastPOPR.OpenJobsTechnician, lastPOPR.UnemploymentRateTechnician)}</td>
  112. <td>${unemployed(lastPOPR.NextPopulationEngineer, lastPOPR.PopulationDifferenceEngineer, lastPOPR.OpenJobsEngineer, lastPOPR.UnemploymentRateEngineer)}</td>
  113. <td>${unemployed(lastPOPR.NextPopulationScientist, lastPOPR.PopulationDifferenceScientist, lastPOPR.OpenJobsScientist, lastPOPR.UnemploymentRateScientist)}</td>
  114. </tr>
  115. </table>
  116. <h2>needs</h2>
  117. ${siteCount} bases
  118. <table>
  119. <tr>
  120. <th></th>
  121. <th>safety</th>
  122. <th>health</th>
  123. <th>comfort</th>
  124. <th>culture</th>
  125. <th>education</th>
  126. </tr>
  127. <tr>
  128. <td>last POPR</td>
  129. <td>${formatPct(lastPOPR.NeedFulfillmentSafety)}</td>
  130. <td>${formatPct(lastPOPR.NeedFulfillmentHealth)}</td>
  131. <td>${formatPct(lastPOPR.NeedFulfillmentComfort)}</td>
  132. <td>${formatPct(lastPOPR.NeedFulfillmentCulture)}</td>
  133. <td>${formatPct(lastPOPR.NeedFulfillmentEducation)}</td>
  134. </tr>
  135. <tr>
  136. <td>total needed</td>
  137. <td>${formatNum(totalNeeds['safety'])}</td>
  138. <td>${formatNum(totalNeeds['health'])}</td>
  139. <td>${formatNum(totalNeeds['comfort'])}</td>
  140. <td>${formatNum(totalNeeds['culture'])}</td>
  141. <td>${formatNum(totalNeeds['education'])}</td>
  142. </tr>
  143. </table>
  144. <h2>current POPI</h2>
  145. <table>
  146. <tr>
  147. ${infras.map((infra) => {
  148. if (infra.CurrentLevel === 0)
  149. return '';
  150. const fill = currentPOPIFilled.get(infra.Type)!;
  151. return `<tr>
  152. <td>${infra.Type} T${infra.CurrentLevel}</td>
  153. <td>${fill.numMats}/${infra.Upkeeps.length}</td>
  154. </tr>`;
  155. }).join('')}
  156. </tr>
  157. </table>
  158. current projected ${pop.toUpperCase()} happiness:
  159. ${formatPct(projectedHappiness(pop, totalNeeds, siteCount, currentPOPIFilled))}
  160. <h2>options</h2>
  161. <table class="options">
  162. <tr>
  163. <th>config</th>
  164. <th>projected migration</th>
  165. <th>cost/day</th>
  166. <th>unit cost</th>
  167. </tr>
  168. ${paretoFront(pop, totalNeeds, siteCount, currentPOPIFilled, currentPop, prices).map((result) => {
  169. let unitCost = '';
  170. if (result.cost > 0)
  171. unitCost = formatNum(result.cost / result.migration);
  172. return `<tr>
  173. <td>${[...result.config.entries()].map(([building, fill]) => `${building}: ${fill.numMats}`).join(', ')}</td>
  174. <td>${formatDelta(result.migration)}</td>
  175. <td>${formatNum(result.cost)}</td>
  176. <td>${unitCost}</td>
  177. </tr>`;
  178. }).join('')}
  179. </table>
  180. `;
  181. }
  182. const formatNum = new Intl.NumberFormat(undefined, {maximumFractionDigits: 2}).format;
  183. const formatPct = new Intl.NumberFormat(undefined, {style: 'percent', maximumFractionDigits: 2}).format;
  184. function formatDelta(n: number, withPlus: boolean = true): string {
  185. if (n > 0)
  186. return `<span class="positive">${withPlus ? '+' : ''}${formatNum(n)}</span>`;
  187. else if (n < 0)
  188. return `<span class="negative">${formatNum(n)}</span>`;
  189. else
  190. return n.toString();
  191. }
  192. function unemployed(people: number, change: number, openJobs: number, unemploymentRate: number): string {
  193. let nextUnemployed;
  194. if (openJobs <= people + change) {
  195. let prevUnemploymentRate = unemploymentRate;
  196. if (openJobs > 0)
  197. if (people - change > 0)
  198. prevUnemploymentRate = -openJobs / (people - change);
  199. else
  200. prevUnemploymentRate = -1
  201. const prevUnemployed = prevUnemploymentRate * (people - change);
  202. nextUnemployed = prevUnemployed + change;
  203. } else
  204. nextUnemployed = -openJobs + change;
  205. return formatDelta(Math.round(nextUnemployed), false);
  206. }
  207. function calcTotalNeeds(popReport: POPR, need: Need): number {
  208. return popReport.NextPopulationPioneer * NEEDS.pio[need]
  209. + popReport.NextPopulationSettler * NEEDS.set[need]
  210. + popReport.NextPopulationTechnician * NEEDS.tec[need]
  211. + popReport.NextPopulationEngineer * NEEDS.eng[need]
  212. + popReport.NextPopulationScientist * NEEDS.sci[need];
  213. }
  214. function calcPOPIFilled(infra: Infrastructure): number | null {
  215. if (infra.CurrentLevel === 0)
  216. return null;
  217. let filled = 0;
  218. for (const upkeep of infra.Upkeeps) {
  219. const nextConsumptionAmount = upkeep.StoreCapacity / 30 * upkeep.Duration; // # capacity is always 30 days
  220. if (upkeep.Stored >= nextConsumptionAmount)
  221. filled++;
  222. }
  223. return filled;
  224. }
  225. function paretoFront(pop: Pop, totalNeeds: Record<Need, number>, siteCount: number, currentPOPIFilled: POPIFill,
  226. currentPop: number, prices: Map<string, number>): {config: POPIFill, migration: number, cost: number}[] {
  227. const results: {config: POPIFill, migration: number, cost: number}[] = [];
  228. for (const config of popiFillCombinations(currentPOPIFilled)) {
  229. const happiness = projectedHappiness(pop, totalNeeds, siteCount, config);
  230. let migration = 0;
  231. if (happiness > 0.7)
  232. migration = currentPop * (happiness - 0.7);
  233. else if (happiness < 0.5)
  234. migration = 0.8 * currentPop * (happiness - 0.5);
  235. // TODO: education
  236. let cost = calcCost(config, prices);
  237. // is any result better than this one?
  238. if (results.some((result) => (result.migration >= migration && result.cost < cost) ||
  239. (result.migration > migration && result.cost <= cost)))
  240. continue;
  241. // are any results worse than this one?
  242. for (let i = results.length - 1; i >= 0; i--)
  243. if ((results[i].migration <= migration && results[i].cost > cost) ||
  244. (results[i].migration < migration && results[i].cost >= cost))
  245. results.splice(i, 1);
  246. results.push({config, migration, cost});
  247. }
  248. return results;
  249. }
  250. function* popiFillCombinations(currentPOPIFilled: POPIFill): Generator<POPIFill> {
  251. const entries = [...currentPOPIFilled.keys()];
  252. function* helper(index: number, current: POPIFill): Generator<POPIFill> {
  253. if (index === entries.length) {
  254. yield new Map(current);
  255. return;
  256. }
  257. const building = entries[index];
  258. const tier = currentPOPIFilled.get(building)!.tier;
  259. const maxBuildingMats = Object.keys(POPI[building].mats).length;
  260. for (let i = 0; i <= maxBuildingMats; i++) {
  261. current.set(building, {tier, numMats: i});
  262. yield* helper(index + 1, current);
  263. }
  264. }
  265. yield* helper(0, new Map());
  266. }
  267. function projectedHappiness(pop: Pop, totalNeeds: Record<Need, number>, siteCount: number, popiFilled: POPIFill): number {
  268. let totalProvided: Record<Need, number> = {'safety': 50 * siteCount, 'health': 50 * siteCount,
  269. 'comfort': 0, 'culture': 0, 'education': 0};
  270. for (const [building, fill] of popiFilled.entries()) {
  271. const {needs} = POPI[building];
  272. const maxBuildingMats = Object.keys(POPI[building].mats).length;
  273. for (const {need, supplied} of needs) {
  274. const provided = fill.numMats / maxBuildingMats * fill.tier * supplied;
  275. totalProvided[need] += provided;
  276. }
  277. }
  278. const satisfaction: Map<Need, number> = new Map(); // percentage of needs fulfilled
  279. for (const _need in totalProvided) {
  280. const need = _need as Need;
  281. satisfaction.set(need, Math.min(totalProvided[need] / totalNeeds[need], 1));
  282. }
  283. const safetyHealthCap = Math.min(satisfaction.get('safety')!, satisfaction.get('health')!);
  284. if (satisfaction.get('comfort')! > safetyHealthCap)
  285. satisfaction.set('comfort', safetyHealthCap);
  286. if (satisfaction.get('culture')! > safetyHealthCap)
  287. satisfaction.set('culture', safetyHealthCap);
  288. const comfortCultureCap = Math.min(satisfaction.get('comfort')!, satisfaction.get('culture')!);
  289. if (satisfaction.get('education')! > comfortCultureCap)
  290. satisfaction.set('education', comfortCultureCap);
  291. const weights = NEEDS[pop];
  292. let happiness = 1 - Object.values(weights).reduce((sum, weight) => sum + weight, 0); // assume 100% life support
  293. for (const [need, s] of satisfaction.entries())
  294. happiness += weights[need] * s;
  295. return happiness;
  296. }
  297. function calcCost(config: POPIFill, prices: Map<string, number>): number {
  298. let cost = 0;
  299. for (const [building, fill] of config.entries()) {
  300. const {mats} = POPI[building];
  301. const matPrices: {ticker: string, costPerDay: number}[] = [];
  302. for (const [mat, amount] of Object.entries(mats)) {
  303. const matCost = prices.get(mat)!;
  304. if (matCost === undefined)
  305. throw new Error('no price for ' + mat);
  306. matPrices.push({ticker: mat, costPerDay: matCost * amount});
  307. }
  308. matPrices.sort((a, b) => a.costPerDay - b.costPerDay);
  309. for (let i = 0; i < fill.numMats; i++)
  310. cost += matPrices[i].costPerDay * fill.tier;
  311. }
  312. return cost;
  313. }
  314. const NEEDS: Record<Pop, Record<Need, number>> = {
  315. 'pio': {'safety': 0.25, 'health': 0.15, 'comfort': 0.03, 'culture': 0.02, 'education': 0.01},
  316. 'set': {'safety': 0.30, 'health': 0.20, 'comfort': 0.03, 'culture': 0.03, 'education': 0.03},
  317. 'tec': {'safety': 0.20, 'health': 0.30, 'comfort': 0.20, 'culture': 0.10, 'education': 0.05},
  318. 'eng': {'safety': 0.10, 'health': 0.15, 'comfort': 0.35, 'culture': 0.20, 'education': 0.10},
  319. 'sci': {'safety': 0.10, 'health': 0.10, 'comfort': 0.20, 'culture': 0.25, 'education': 0.30},
  320. }
  321. const POPI: Record<POPIBuilding, {needs: {need: Need, supplied: number}[], mats: Record<string, number>}> = {
  322. 'SAFETY_STATION': {
  323. needs: [{need: 'safety', supplied: 2500}],
  324. mats: {'DW': 10, 'OFF': 10, 'SUN': 2},
  325. },
  326. 'SECURITY_DRONE_POST': {
  327. needs: [{need: 'safety', supplied: 5000}],
  328. mats: {'POW': 1, 'RAD': 0.47, 'CCD': 0.07, 'SUD': 0.07},
  329. },
  330. 'EMERGENCY_CENTER': {
  331. needs: [{need: 'safety', supplied: 1000}, {need: 'health', supplied: 1000}],
  332. mats: {'PK': 2, 'POW': 0.4, 'BND': 4, 'RED': 0.07, 'BSC': 0.07},
  333. },
  334. 'INFIRMARY': {
  335. needs: [{need: 'health', supplied: 2500}],
  336. mats: {'OFF': 10, 'TUB': 6.67, 'STR': 0.67},
  337. },
  338. 'HOSPITAL': {
  339. needs: [{need: 'health', supplied: 5000}],
  340. mats: {'PK': 2, 'SEQ': 0.4, 'BND': 4, 'SDR': 0.07, 'RED': 0.07, 'BSC': 0.13},
  341. },
  342. 'WELLNESS_CENTER': {
  343. needs: [{need: 'health', supplied: 1000}, {need: 'comfort', supplied: 1000}],
  344. mats: {'KOM': 4, 'OLF': 2, 'DW': 6, 'DEC': 0.67, 'PFE': 2.67, 'SOI': 6.67},
  345. },
  346. 'WILDLIFE_PARK': {
  347. needs: [{need: 'comfort', supplied: 2500}],
  348. mats: {'DW': 10, 'FOD': 6, 'PFE': 2, 'SOI': 3.33, 'DEC': 0.33},
  349. },
  350. 'ARCADES': {
  351. needs: [{need: 'comfort', supplied: 5000}],
  352. mats: {'POW': 2, 'MHP': 2, 'OLF': 4, 'BID': 0.2, 'HOG': 0.2, 'EDC': 0.2},
  353. },
  354. 'ART_CAFE': {
  355. needs: [{need: 'comfort', supplied: 1000}, {need: 'culture', supplied: 1000}],
  356. mats: {'MHP': 1, 'HOG': 1, 'UTS': 0.67, 'DEC': 0.67},
  357. },
  358. 'ART_GALLERY': {
  359. needs: [{need: 'culture', supplied: 2500}],
  360. mats: {'MHP': 1, 'HOG': 1, 'UTS': 0.67, 'DEC': 0.67},
  361. },
  362. 'THEATER': {
  363. needs: [{need: 'culture', supplied: 5000}],
  364. mats: {'POW': 1.4, 'MHP': 2, 'HOG': 1.4, 'OLF': 4, 'BID': 0.33, 'DEC': 0.67},
  365. },
  366. 'PLANETARY_BROADCASTING_HUB': {
  367. needs: [{need: 'culture', supplied: 1000}, {need: 'education', supplied: 1000}],
  368. mats: {'OFF': 10, 'MHP': 1, 'SP': 1.33, 'AAR': 0.67, 'EDC': 0.27, 'IDC': 0.13},
  369. },
  370. 'LIBRARY': {
  371. needs: [{need: 'education', supplied: 2500}],
  372. mats: {'MHP': 1, 'HOG': 1, 'CD': 0.33, 'DIS': 0.33, 'BID': 0.2},
  373. },
  374. 'UNIVERSITY': {
  375. needs: [{need: 'education', supplied: 5000}],
  376. mats: {'COF': 10, 'REA': 10, 'TUB': 10, 'BID': 0.33, 'HD': 0.67, 'IDC': 0.2},
  377. },
  378. };
  379. type Pop = 'pio' | 'set' | 'tec' | 'eng' | 'sci';
  380. type Need = 'safety' | 'health' | 'comfort' | 'culture' | 'education';
  381. type POPIBuilding = 'SAFETY_STATION' | 'SECURITY_DRONE_POST' | 'EMERGENCY_CENTER' | 'INFIRMARY' | 'HOSPITAL' |
  382. 'WELLNESS_CENTER' | 'WILDLIFE_PARK' | 'ARCADES' | 'ART_CAFE' | 'ART_GALLERY' | 'THEATER' |
  383. 'PLANETARY_BROADCASTING_HUB' | 'LIBRARY' | 'UNIVERSITY';
  384. type POPIFill = Map<POPIBuilding, {tier: number, numMats: number}>;
  385. interface Planet {
  386. PopulationReports: POPR[]
  387. }
  388. interface POPR {
  389. SimulationPeriod: number;
  390. ReportTimestamp: string;
  391. NeedFulfillmentSafety: number;
  392. NeedFulfillmentHealth: number;
  393. NeedFulfillmentComfort: number;
  394. NeedFulfillmentCulture: number;
  395. NeedFulfillmentEducation: number;
  396. NextPopulationPioneer: number;
  397. NextPopulationSettler: number;
  398. NextPopulationTechnician: number;
  399. NextPopulationEngineer: number;
  400. NextPopulationScientist: number;
  401. PopulationDifferencePioneer: number;
  402. PopulationDifferenceSettler: number;
  403. PopulationDifferenceTechnician: number;
  404. PopulationDifferenceEngineer: number;
  405. PopulationDifferenceScientist: number;
  406. OpenJobsPioneer: number;
  407. OpenJobsSettler: number;
  408. OpenJobsTechnician: number;
  409. OpenJobsEngineer: number;
  410. OpenJobsScientist: number;
  411. UnemploymentRatePioneer: number;
  412. UnemploymentRateSettler: number;
  413. UnemploymentRateTechnician: number;
  414. UnemploymentRateEngineer: number;
  415. UnemploymentRateScientist: number;
  416. }
  417. interface SiteCount {
  418. Count: number;
  419. }
  420. interface Infrastructure {
  421. Type: POPIBuilding;
  422. CurrentLevel: number;
  423. Upkeeps: {Stored: number, StoreCapacity: number, 'Duration': number}[];
  424. }
  425. interface Price {
  426. ticker: string
  427. exchange_code: string
  428. vwap_30d: number
  429. }