Compare commits
5
Commits
b24f132210
...
3f8cc91da9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3f8cc91da9 | ||
|
|
80b8fa8bf9 | ||
|
|
84a873f3bc | ||
|
|
264fbf164b | ||
|
|
2aeb0e5674 |
@@ -45,8 +45,11 @@ Run as `puga <tool> ...` (e.g. `puga scan --min-n 3`, `puga plan pull <uuid>`);
|
||||
- `tools/buy.py <spec.yaml|--uuid U> --days N` cash-aware shopping list: construction gap (plan vs empire state's built buildings) plus N days of the plan's NET operating stock (via `simulate()`, so self-produced inputs like AL net against consumption), priced at real fill cost, checked against cash/reserve. Pass a plan covering the WHOLE base for restocking, not just a new addition (see `docs/library.md`).
|
||||
- `tools/sell.py TICKER QTY [--tight]` where to post an ask, expected hours to clear, and a self-contained tranche split: aggressive (undercut) tranche capped at the median 30d-volume quantile (or 80th pct with `--tight`, for when a payment is imminent and stockout risk outweighs a few points of margin), patient tranche priced just under the next competitor tier. `--show-bid` for the instant-bid comparison (off by default; usually worse).
|
||||
- `tools/network.py <chain.yaml>` models a MULTI-BASE chain (e.g. mine LST at Nike, ship it, make BSE at Deimos): simulates each base, nets a transferred material's producer-surplus against consumer-need, charges real freight only on what's moved (`puga/network.py`). Spec and worked example in `plans/chains/`. `cm_free: true` per base for a new founding covered by a Core Module Kit. profit/day per base is the WHOLE plan, not the marginal addition - diff against the base's plan without the addition for a true marginal ROI.
|
||||
- `tools/whatif.py <before.yaml> [--add BUILDING:AMOUNT[:RECIPE]] [--infra HB1:+1] [--after after.yaml]` marginal ROI of adding to a base you already run (whole-plan diff, same rule as buy/runway - pass the WHOLE base, not just the addition). `--add` mutates a copy of `before` in-memory (reuses an existing building's recipe if omitted, e.g. `--add POL:1`); `--after` takes a second full spec instead. Flags any workforce tier the addition newly overloads (vs. a pre-existing one, which it won't flag) - this is what caught the PP2/pioneer-housing and 2nd-CHP/pioneer-housing surprises by hand before this tool existed.
|
||||
- `tools/runway.py <spec.yaml|--uuid U> [--no-inbound]` days of runway per material before a base stalls: real NET consumption via `simulate()` (self-produced inputs excluded), base storage, PLUS (by default) any ship currently flying to that planet, auto-detected from live flight data (`tools/state.py` tags each ship with its flight origin/destination). Pass the WHOLE base plan (see `docs/library.md`).
|
||||
- `tools/chain.py TICKER` make-vs-buy cost tree plus sourcing depth of inputs.
|
||||
- `tools/chain.py TICKER` make-vs-buy cost tree plus sourcing depth of inputs. `--consumers` flips it: what recipes EAT this ticker as an input, with each output's market depth - for "is there a deeper downstream product worth chaining into" questions (e.g. checking BOR/BSE/BBH for further processing).
|
||||
- `tools/planet.py RESOURCE [--min-factor X] [--from PLANET] [--top N]` ranks planets for a raw resource by extraction factor, with founding cost straight from FIO's own `BuildRequirements` (real environment-extras materials, not guessed temperature/pressure thresholds - PRUNplanner's own calculations don't model those either) and optional jump distance via `tools/route.py`. Pure-factor ranking alone is misleading - the best-factor planets are often thousands of ly away; always pass `--from` an existing base. Library: `puga/planet.py`.
|
||||
- `tools/route.py <from planet/system> <to planet/system>` jump-distance route (not a PRUNplanner feature - built from FIO's `/systemstars` graph, Dijkstra by straight-line ly since that's what FTL fuel/time scale with, jump count reported alongside). Accepts planet natural IDs, system natural IDs, or names. Library: `puga/route.py`.
|
||||
- `tools/price.py` prices across exchanges with VWAP, volume, fill price for a quantity; `tools/book.py` order-book ladder.
|
||||
- `tools/prun_scan.py`, `tools/prun_cxarb.py` legacy top-of-book scans; overstate thin markets. Baseline only. `tools/arb.py` replacement is on the roadmap.
|
||||
- `puga/econ.py` pure formulas ported from PRUNplanner (efficiency stack, workforce, extraction, production I/O, hab optimizer); `tests/test_econ.py` holds the reference values.
|
||||
|
||||
+3
-3
@@ -9,10 +9,10 @@ Legend: [ ] todo, [x] done. Build order matters; each step is usable on its own.
|
||||
5. [x] (v1 done; see saturation-design.md for refinements) `tools/scan.py` (replaces prun_scan.py): depth-aware ROI. Per recipe report: buildings the market can absorb (output demand + traded volume, input supply), ROI at fill price for N buildings, absorbable profit/day. Filter `--min-buildings`. Both CX-local and universe.
|
||||
5b. [ ] `tools/arb.py` (replaces prun_cxarb.py): inter-CX arbitrage on `market.walk` at real fill size; capital required, fuel/shipping cost from state, profit per trip within cash. Reason: old script uses top-of-book spread x min(supply,demand); on 2 of 4 top hits it overstated profit 7 to 11x (WAI, SCN).
|
||||
6. [x] `tools/chain.py`: full bill of materials, make-vs-buy per node.
|
||||
7. [ ] `tools/whatif.py`: marginal ROI of adding a building to the actual state (uses `state/company.yaml`, efficiency stack, imports).
|
||||
8. [ ] `tools/planet.py`, `tools/found.py`: rank planets for a resource; founding cost including environment extras.
|
||||
7. [x] `tools/whatif.py`: marginal ROI of adding a building to a base you already run (whole-plan diff via `simulate()`, built dict from `state/company.yaml`; flags newly-caused workforce overloads).
|
||||
8. [x] `tools/planet.py`: rank planets for a resource (FIO bulk `Resources`/`BuildRequirements` data), founding cost from real environment-extras materials, jump distance via `tools/route.py`. `tools/found.py` (full founding workflow/writeback) still todo.
|
||||
13b. [x] `puga/network.py` + `tools/network.py`: multi-base chain modelling (per-base simulate, net transfers against real freight, `cm_free` for kits). Worked example: `plans/chains/nike_deimos_lst.yaml` (Nike LST -> Deimos PP2/BSE). Known gap: reports whole-plan profit per base, not the marginal addition; caller must diff manually.
|
||||
9. [ ] `tools/route.py`, `tools/haul.py`: jump graph, fuel, profit per trip.
|
||||
9. [x] `tools/route.py`: jump graph (FIO `/systemstars`, Dijkstra by straight-line ly, jump count alongside). `tools/haul.py` (fuel cost, profit per trip) still todo.
|
||||
9b. [x] (dry-run default, --apply after user yes) `tools/plan_push.py`: create/update `[PuGa]` plans in PRUNplanner from YAML (Api-Key auth; see decisions.md for guardrails).
|
||||
10. [x] `tools/state.py sync` (sites, production efficiency, storage, ships, cash, permits): inventory, production, ships into `state/`.
|
||||
11. [ ] Docs to fill: `docs/apex.md`, `docs/fio.md`, `docs/playbook.md` (question type -> tool), `docs/decisions.md`.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Rank planets by extraction factor for a resource, with founding cost (environment extras
|
||||
from FIO's own BuildRequirements - authoritative, not guessed from temperature/pressure
|
||||
thresholds, which PRUNplanner's own calculations don't model either)."""
|
||||
from . import fio
|
||||
|
||||
|
||||
def candidates(resource_ticker: str, min_factor: float = 0.0):
|
||||
"""All planets with this resource, sorted by factor descending. Each: PlanetNaturalId,
|
||||
PlanetName, factor, resource_type, plus the raw planet record (temperature/pressure/
|
||||
gravity/fertility/faction/BuildRequirements/SystemId etc)."""
|
||||
mats = {m["Ticker"]: m["MaterialId"] for m in fio.materials()}
|
||||
mid = mats.get(resource_ticker.upper())
|
||||
if not mid:
|
||||
raise ValueError(f"unknown material ticker {resource_ticker!r}")
|
||||
out = []
|
||||
for p in fio.planets_full():
|
||||
for r in p.get("Resources", []):
|
||||
if r["MaterialId"] == mid and r["Factor"] >= min_factor:
|
||||
out.append({
|
||||
"natural_id": p["PlanetNaturalId"], "name": p["PlanetName"],
|
||||
"factor": r["Factor"], "resource_type": r["ResourceType"],
|
||||
"temperature": p["Temperature"], "pressure": p["Pressure"], "gravity": p["Gravity"],
|
||||
"fertility": p["Fertility"], "faction": p.get("FactionCode"),
|
||||
"system_id": p["SystemId"], "build_requirements": p.get("BuildRequirements", []),
|
||||
})
|
||||
out.sort(key=lambda x: -x["factor"])
|
||||
return out
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Jump-graph routing between systems/planets, built from FIO's /systemstars (698 systems,
|
||||
3D coordinates + jump connections). Not in PRUNplanner's own source (it doesn't model travel) -
|
||||
this is the project's own addition. Edge weight = straight-line distance between connected
|
||||
systems (ly); PrUn's own FTL fuel/time scale with this, not raw jump count, so Dijkstra on
|
||||
distance gives the right "cheapest" route, with jump count reported alongside for reference."""
|
||||
import heapq
|
||||
import math
|
||||
from . import fio
|
||||
|
||||
|
||||
def _dist(a, b):
|
||||
return math.dist((a["PositionX"], a["PositionY"], a["PositionZ"]),
|
||||
(b["PositionX"], b["PositionY"], b["PositionZ"]))
|
||||
|
||||
|
||||
def load_graph():
|
||||
"""SystemId -> {name, natural_id, pos, neighbors: {SystemId: distance_ly}}"""
|
||||
systems = {s["SystemId"]: s for s in fio.systems()}
|
||||
g = {}
|
||||
for sid, s in systems.items():
|
||||
neighbors = {}
|
||||
for c in s.get("Connections", []):
|
||||
other = systems.get(c["ConnectingId"])
|
||||
if other:
|
||||
neighbors[c["ConnectingId"]] = _dist(s, other)
|
||||
g[sid] = {"name": s["Name"], "natural_id": s["NaturalId"], "pos": s, "neighbors": neighbors}
|
||||
return g
|
||||
|
||||
|
||||
def resolve_system(query: str) -> str:
|
||||
"""Planet natural id (e.g. ZV-759c), system natural id (ZV-759), or a name -> SystemId."""
|
||||
q = query.strip().upper()
|
||||
for p in fio.planets_full():
|
||||
if p.get("PlanetNaturalId", "").upper() == q or (p.get("PlanetName") or "").upper() == q:
|
||||
return p["SystemId"]
|
||||
for s in fio.systems():
|
||||
if s["NaturalId"].upper() == q or s["Name"].upper() == q:
|
||||
return s["SystemId"]
|
||||
raise ValueError(f"no planet or system matches {query!r}")
|
||||
|
||||
|
||||
def shortest_path(src_system_id: str, dst_system_id: str, graph=None):
|
||||
"""Dijkstra by straight-line ly distance. Returns dict: jumps, distance_ly, path (list of system natural ids)."""
|
||||
g = graph or load_graph()
|
||||
if src_system_id not in g or dst_system_id not in g:
|
||||
raise ValueError("unknown system id")
|
||||
dist = {src_system_id: 0.0}
|
||||
prev = {}
|
||||
pq = [(0.0, src_system_id)]
|
||||
seen = set()
|
||||
while pq:
|
||||
d, u = heapq.heappop(pq)
|
||||
if u in seen:
|
||||
continue
|
||||
seen.add(u)
|
||||
if u == dst_system_id:
|
||||
break
|
||||
for v, w in g[u]["neighbors"].items():
|
||||
nd = d + w
|
||||
if nd < dist.get(v, float("inf")):
|
||||
dist[v] = nd
|
||||
prev[v] = u
|
||||
heapq.heappush(pq, (nd, v))
|
||||
if dst_system_id not in dist:
|
||||
return None
|
||||
path = [dst_system_id]
|
||||
while path[-1] != src_system_id:
|
||||
path.append(prev[path[-1]])
|
||||
path.reverse()
|
||||
return {
|
||||
"jumps": len(path) - 1,
|
||||
"distance_ly": dist[dst_system_id],
|
||||
"path": [g[sid]["natural_id"] for sid in path],
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
from puga import route
|
||||
|
||||
# Small synthetic graph: A-B-C in a line, A-D direct (shorter), D-C (closes a loop so Dijkstra has a choice)
|
||||
GRAPH = {
|
||||
"A": {"name": "A", "natural_id": "A", "pos": None, "neighbors": {"B": 10.0, "D": 3.0}},
|
||||
"B": {"name": "B", "natural_id": "B", "pos": None, "neighbors": {"A": 10.0, "C": 10.0}},
|
||||
"C": {"name": "C", "natural_id": "C", "pos": None, "neighbors": {"B": 10.0, "D": 10.0}},
|
||||
"D": {"name": "D", "natural_id": "D", "pos": None, "neighbors": {"A": 3.0, "C": 10.0}},
|
||||
}
|
||||
|
||||
|
||||
def test_shortest_path_picks_lower_total_distance_not_fewer_jumps():
|
||||
r = route.shortest_path("A", "C", graph=GRAPH)
|
||||
assert r["path"] == ["A", "D", "C"] # 3+10=13, beats A-B-C's 10+10=20 despite same jump count
|
||||
assert r["jumps"] == 2
|
||||
assert r["distance_ly"] == 13.0
|
||||
|
||||
|
||||
def test_same_system_is_zero_jumps():
|
||||
r = route.shortest_path("A", "A", graph=GRAPH)
|
||||
assert r["jumps"] == 0
|
||||
assert r["distance_ly"] == 0.0
|
||||
|
||||
|
||||
def test_no_route_returns_none():
|
||||
graph = dict(GRAPH)
|
||||
graph["E"] = {"name": "E", "natural_id": "E", "pos": None, "neighbors": {}}
|
||||
assert route.shortest_path("A", "E", graph=graph) is None
|
||||
@@ -0,0 +1,29 @@
|
||||
from pathlib import Path
|
||||
import sys
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "tools"))
|
||||
import whatif
|
||||
|
||||
|
||||
def test_apply_add_reuses_existing_recipe():
|
||||
spec = {"buildings": [{"building": "POL", "amount": 1, "recipes": ["EPO,PG=>DEC"]}]}
|
||||
whatif.apply_add(spec, "POL:1")
|
||||
assert spec["buildings"] == [{"building": "POL", "amount": 2, "recipes": ["EPO,PG=>DEC"]}]
|
||||
|
||||
|
||||
def test_apply_add_new_building_needs_explicit_recipe():
|
||||
spec = {"buildings": []}
|
||||
import pytest
|
||||
with pytest.raises(SystemExit):
|
||||
whatif.apply_add(spec, "CHP:1")
|
||||
|
||||
|
||||
def test_apply_add_appends_new_building_with_recipe():
|
||||
spec = {"buildings": []}
|
||||
whatif.apply_add(spec, "CHP:1:MG,S,CU=>IND")
|
||||
assert spec["buildings"] == [{"building": "CHP", "amount": 1, "recipes": ["MG,S,CU=>IND"]}]
|
||||
|
||||
|
||||
def test_apply_infra_adds_delta():
|
||||
spec = {"infrastructure": {"HB1": 4}}
|
||||
whatif.apply_infra(spec, "HB1:+1,HB2:+2")
|
||||
assert spec["infrastructure"] == {"HB1": 5, "HB2": 2}
|
||||
@@ -3,6 +3,7 @@
|
||||
Cost to make = inputs at min(buy, make) per output unit; wages/capex excluded unless --wages.
|
||||
tools/chain.py DEC # AI1
|
||||
tools/chain.py BHP --depth 3 --qty 13
|
||||
tools/chain.py BOR --consumers # what recipes EAT this ticker as an input, with the output's market depth
|
||||
"""
|
||||
import argparse, sys
|
||||
from pathlib import Path
|
||||
@@ -18,6 +19,7 @@ def main():
|
||||
ap.add_argument("--qty", type=float, default=1.0, help="units/day you would make (sourcing check)")
|
||||
ap.add_argument("--wages", action="store_true", help="add wage cost per output unit (both luxuries at ask)")
|
||||
ap.add_argument("--cogc")
|
||||
ap.add_argument("--consumers", action="store_true", help="list recipes that consume this ticker as an input, with the output's market depth, instead of the make-vs-buy tree")
|
||||
a = ap.parse_args()
|
||||
|
||||
snap = market.snapshot()
|
||||
@@ -28,6 +30,24 @@ def main():
|
||||
for o in r["Outputs"]:
|
||||
by_out.setdefault(o["Ticker"], []).append(r)
|
||||
|
||||
if a.consumers:
|
||||
tk = a.ticker.upper()
|
||||
found = False
|
||||
for r in fio.recipes():
|
||||
if not any(i["Ticker"] == tk for i in r["Inputs"]):
|
||||
continue
|
||||
found = True
|
||||
ins = " ".join(f"{i['Amount']}{i['Ticker']}" for i in r["Inputs"])
|
||||
outs = " ".join(f"{o['Amount']}{o['Ticker']}" for o in r["Outputs"])
|
||||
print(f"{r['BuildingTicker']:4} {ins} -> {outs}")
|
||||
for o in r["Outputs"]:
|
||||
q = Q(o["Ticker"])
|
||||
mk = f"ask {q.ask:.0f} bid {q.bid:.0f} sup {q.supply:.0f} dem {q.demand:.0f} flow {sat.tref(q.traded7, q.traded30):.1f}/d" if q and q.ask and q.bid else "no market"
|
||||
print(f" {o['Ticker']:5} {mk}")
|
||||
if not found:
|
||||
print(f"nothing consumes {tk} as an input")
|
||||
return
|
||||
|
||||
def wage_per_day(b):
|
||||
tot = 0.0
|
||||
for t in econ.TIERS:
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Rank planets for a resource, with founding cost (environment extras straight from FIO's
|
||||
BuildRequirements - real game data, not guessed thresholds) and optional jump distance from
|
||||
a base you already have.
|
||||
|
||||
tools/planet.py FEO --top 10
|
||||
tools/planet.py LST --min-factor 0.5 --from ZV-759c --top 5
|
||||
"""
|
||||
import argparse, sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from puga import config, market, planet, route
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("resource", help="raw resource ticker, e.g. LST, FEO, SEA")
|
||||
ap.add_argument("--min-factor", type=float, default=0.0)
|
||||
ap.add_argument("--top", type=int, default=10)
|
||||
ap.add_argument("--from", dest="from_", help="planet/system to measure jump distance from (e.g. an existing base)")
|
||||
ap.add_argument("--cx", default=config.DEFAULT_CX)
|
||||
a = ap.parse_args()
|
||||
|
||||
rows = planet.candidates(a.resource, a.min_factor)
|
||||
if not rows:
|
||||
print(f"no planets found with {a.resource.upper()} (factor >= {a.min_factor})")
|
||||
return
|
||||
rows = rows[:a.top]
|
||||
|
||||
src = route.resolve_system(a.from_) if a.from_ else None
|
||||
graph = route.load_graph() if src else None
|
||||
|
||||
for p in rows:
|
||||
env_cost = 0.0
|
||||
env_items = []
|
||||
for br in p["build_requirements"]:
|
||||
w = market.walk(br["MaterialTicker"], a.cx, br["MaterialAmount"], "buy")
|
||||
env_cost += w["total"]
|
||||
env_items.append(f"{br['MaterialAmount']}{br['MaterialTicker']}")
|
||||
dist = ""
|
||||
if src:
|
||||
r = route.shortest_path(src, p["system_id"], graph=graph) if p["system_id"] != src else {"jumps": 0, "distance_ly": 0.0}
|
||||
dist = f" {r['jumps']} jumps ({r['distance_ly']:.0f} ly)" if r else " unreachable"
|
||||
print(f"{p['natural_id']:8} {p['name']:16} factor {p['factor']:.3f} T {p['temperature']:6.1f}C P {p['pressure']:.2f}bar "
|
||||
f"G {p['gravity']:.2f} fert {p['fertility']:5.2f} faction {p['faction'] or '-':4} env-cost {env_cost:8,.0f} AIC ({', '.join(env_items) or 'none'}){dist}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Jump-distance route between two planets/systems, from FIO's system graph (not PRUNplanner,
|
||||
which doesn't model travel). Straight-line ly is the Dijkstra weight (scales with FTL fuel/time);
|
||||
jump count shown alongside.
|
||||
|
||||
tools/route.py ZV-759c ZV-194a # Deimos -> Nike
|
||||
tools/route.py Deimos "Ironforge" # names also work
|
||||
"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from puga import route
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 3:
|
||||
sys.exit("usage: tools/route.py <from planet/system> <to planet/system>")
|
||||
a, b = sys.argv[1], sys.argv[2]
|
||||
src = route.resolve_system(a)
|
||||
dst = route.resolve_system(b)
|
||||
if src == dst:
|
||||
print(f"{a} and {b} are in the same system - 0 jumps")
|
||||
return
|
||||
r = route.shortest_path(src, dst)
|
||||
if r is None:
|
||||
print(f"no connected route found between {a} and {b}")
|
||||
return
|
||||
print(f"{a} -> {b}: {r['jumps']} jumps, {r['distance_ly']:.1f} ly (straight-line sum along the jump path)")
|
||||
print("path: " + " -> ".join(r["path"]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Marginal ROI of adding to a base you already run: whole-plan-with-addition minus whole-plan-
|
||||
without, per docs/library.md's diffing rule (NOT the plan-level ROI simulate.py/PRUNplanner print,
|
||||
which divides whole-plan profit by only the new capex and badly overstates once a base exists).
|
||||
Also flags any workforce tier the addition pushes over capacity (the recurring surprise this
|
||||
session - e.g. PP2 overloading pioneer housing after POL+CHP already maxed it).
|
||||
|
||||
tools/whatif.py plans/examples/deimos_base.yaml --add CHP:1:MG,S,CU=>IND --infra HB1:+1
|
||||
tools/whatif.py before.yaml --after after.yaml # two explicit full-base specs instead
|
||||
tools/whatif.py before.yaml --add POL:1 # reuses POL's existing recipe in before.yaml
|
||||
"""
|
||||
import argparse, copy, sys
|
||||
from pathlib import Path
|
||||
import yaml
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from puga import config, market, prunplanner as pp
|
||||
from puga.simulate import simulate
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import plan_push
|
||||
|
||||
|
||||
def apply_add(spec: dict, add: str):
|
||||
"""BUILDING:AMOUNT[:RECIPE[|RECIPE...]] - amount is a delta; recipe reuses an existing
|
||||
entry of the same building ticker in spec if omitted."""
|
||||
parts = add.split(":", 2)
|
||||
if len(parts) < 2:
|
||||
sys.exit(f"--add needs BUILDING:AMOUNT[:RECIPE], got {add!r}")
|
||||
ticker, amount = parts[0], int(parts[1])
|
||||
recipes = parts[2].split("|") if len(parts) == 3 else None
|
||||
for b in spec.setdefault("buildings", []):
|
||||
if b["building"] == ticker and (recipes is None or b["recipes"] == recipes):
|
||||
b["amount"] += amount
|
||||
return
|
||||
if recipes is None:
|
||||
sys.exit(f"no existing {ticker} in the plan to infer a recipe from - give one: {ticker}:{amount}:RECIPE")
|
||||
spec["buildings"].append({"building": ticker, "amount": amount, "recipes": recipes})
|
||||
|
||||
|
||||
def apply_infra(spec: dict, infra: str):
|
||||
"""HB1:+1,HB2:+2 - deltas added to spec['infrastructure']."""
|
||||
inf = spec.setdefault("infrastructure", {})
|
||||
for part in infra.split(","):
|
||||
ticker, amount = part.split(":")
|
||||
inf[ticker] = inf.get(ticker, 0) + int(amount)
|
||||
|
||||
|
||||
def run(spec, recipes, blds, price, faction, perm, built):
|
||||
plan = plan_push.build_payload(spec, recipes, {b["building_ticker"] for b in blds})
|
||||
planet = pp._g(f"/data/planet/{plan['planet_natural_id']}/", 3600)
|
||||
return plan, simulate(plan, recipes, blds, planet["resources"], planet["fertility"], price, faction, perm, built=built)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("before", help="full-base plan spec as it stands (or as a baseline you want to compare from)")
|
||||
ap.add_argument("--after", help="full-base plan spec with the addition already in it; skips --add/--infra")
|
||||
ap.add_argument("--add", action="append", default=[], help="BUILDING:AMOUNT[:RECIPE[|RECIPE]], repeatable")
|
||||
ap.add_argument("--infra", action="append", default=[], help="HB1:+1,HB2:+2, repeatable")
|
||||
ap.add_argument("--cx", default=config.DEFAULT_CX)
|
||||
ap.add_argument("--basis", default="uni30", choices=["real", "uni30", "vwap30", "vwap7", "ask", "bid", "mid"])
|
||||
ap.add_argument("--no-faction", action="store_true")
|
||||
a = ap.parse_args()
|
||||
|
||||
before_spec = yaml.safe_load(Path(a.before).read_text())
|
||||
if a.after:
|
||||
after_spec = yaml.safe_load(Path(a.after).read_text())
|
||||
else:
|
||||
if not a.add and not a.infra:
|
||||
sys.exit("give --after, or at least one --add/--infra")
|
||||
after_spec = copy.deepcopy(before_spec)
|
||||
for add in a.add:
|
||||
apply_add(after_spec, add)
|
||||
for infra in a.infra:
|
||||
apply_infra(after_spec, infra)
|
||||
|
||||
recipes, blds = pp.recipes(), pp.buildings()
|
||||
snap = market.snapshot()
|
||||
|
||||
def price(t, side="buy"):
|
||||
if a.basis == "uni30":
|
||||
v = market.uni30(snap, t)
|
||||
if v:
|
||||
return v
|
||||
q = snap.get((t, a.cx))
|
||||
return q.ask if q else None
|
||||
q = snap.get((t, a.cx))
|
||||
if not q:
|
||||
return None
|
||||
return {"real": q.ask if side == "buy" else (q.vwap7 or q.vwap30 or q.bid),
|
||||
"vwap30": q.vwap30 or q.vwap7 or q.ask, "vwap7": q.vwap7 or q.vwap30 or q.ask,
|
||||
"ask": q.ask, "bid": q.bid, "mid": (q.ask + q.bid) / 2 if q.ask and q.bid else None}[a.basis]
|
||||
|
||||
st = yaml.safe_load(config.state_path().read_text())
|
||||
faction = None if a.no_faction else (st.get("company") or {}).get("faction")
|
||||
perm = (st.get("permits", {}).get("used", 1), st.get("permits", {}).get("total", 2))
|
||||
planet_id = before_spec["planet"]
|
||||
built = next((b.get("buildings", {}) for b in st.get("bases", []) if b.get("planet") == planet_id), {})
|
||||
|
||||
# hq comes from each spec file's own "hq:" field (plan_push.build_payload reads it directly) -
|
||||
# keep both before/after specs' hq set explicitly rather than relying on state here.
|
||||
plan_b, r_b = run(before_spec, recipes, blds, price, faction, perm, built)
|
||||
plan_a, r_a = run(after_spec, recipes, blds, price, faction, perm, built)
|
||||
|
||||
d_profit = r_a["profit"] - r_b["profit"]
|
||||
d_capex = r_a["new_capex"] - r_b["new_capex"]
|
||||
|
||||
print(f"BEFORE profit/day {r_b['profit']:,.0f} new_capex {r_b['new_capex']:,.0f}")
|
||||
print(f"AFTER profit/day {r_a['profit']:,.0f} new_capex {r_a['new_capex']:,.0f}")
|
||||
print(f"\nMARGINAL profit/day {d_profit:,.0f} new_capex {d_capex:,.0f}", end="")
|
||||
if d_capex > 0 and d_profit > 0:
|
||||
print(f" ROI/day {100*d_profit/d_capex:.2f}% payback {d_capex/d_profit:.1f} d")
|
||||
elif d_capex <= 0:
|
||||
print(" (no new capex)")
|
||||
else:
|
||||
print(" (marginal profit <= 0 - not worth it)")
|
||||
|
||||
print("\nWORKFORCE (after) need supply open eff%")
|
||||
newly_overloaded = []
|
||||
for t, w in r_a["workforce"].items():
|
||||
if w["need"] or w["supply"]:
|
||||
was_already_overloaded = r_b["workforce"].get(t, {}).get("open", 0) < 0
|
||||
flag = ""
|
||||
if w["open"] < 0 and not was_already_overloaded:
|
||||
flag = " <- NEWLY OVERLOADED by this addition, drags every building's efficiency down"
|
||||
newly_overloaded.append(t)
|
||||
elif w["open"] < 0:
|
||||
flag = " (already overloaded before this addition too - not new)"
|
||||
print(f" {t:10} {w['need']:5.0f} {w['supply']:6.0f} {w['open']:5.0f} {w['eff']*100:7.2f}{flag}")
|
||||
if newly_overloaded:
|
||||
print(f"\nFix before building: more housing for {', '.join(newly_overloaded)} (see which HB covers each tier).")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user