Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c902e14107 | ||
|
|
74d05009fb | ||
|
|
c660559f74 | ||
|
|
9a4c7cc57c |
@@ -48,12 +48,15 @@ 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/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/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/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/whatif.py <before.yaml> [--add BUILDING:AMOUNT[:RECIPE]] [--infra HB1:+1] [--after after.yaml]` marginal payback 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. Charges marginal freight too (real fuel model, CX-to-planet, via `puga.shipping`): only the EXTRA round trips this addition needs beyond the base's existing traffic, so a small addition riding along on already-necessary hauls correctly costs ~0, while one that meaningfully adds to shipped tonnage doesn't get a free pass - this is what would catch a recipe whose ROI looks great only because its freight cost was left out.
|
||||||
- `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/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/undervalued.py [--cx AI1] [--min-vol 5] [--top 20]` manufactured goods currently priced below implied production cost - buy-and-hold-for-reversion candidates, not build candidates. **Expected ROI is much lower than production builds** (~0.10-0.24%/day backtested, vs 14-29%/day for the builds this toolkit recommends) - only worth it for excess idle capital once better-yielding builds are exhausted. Library: `puga/undervalued.py`.
|
- `tools/undervalued.py [--cx AI1] [--min-vol 5] [--top 20]` manufactured goods currently priced below implied production cost - buy-and-hold-for-reversion candidates, not build candidates. **Expected ROI is much lower than production builds** (~0.10-0.24%/day backtested, vs 14-29%/day for the builds this toolkit recommends) - only worth it for excess idle capital once better-yielding builds are exhausted. Library: `puga/undervalued.py`.
|
||||||
- `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/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/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/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/shiptrip.py SHIP FROM TO [--v0 X --v1 Y]` the simple ship-trip tool: give a ship registration + start + stop, it works out jumps/charges/landing fuel itself via `tools/route.py`'s jump graph and reports fuel cost (defaults to max sliders). Direct-jump routes only - an unconnected pair means gateway-only, and it tells you exactly what to read off the live APEX Ship Flight Control screen (the LOCK fee - genuinely not available via FIO/PRUNplanner, confirmed by inspecting both) and what to run instead (`tools/shipcost.py`). Warns if the given ship's live specs (FIO `/ship/ships/{user}`) don't match the calibrated hull/reactor.
|
||||||
|
- `tools/shipcost.py [--jumps N --charges N] [--v0 X --v1 Y] [--gateways N --lock-fee AMOUNT:CURRENCY] [--to PLANET]` the explicit/manual version: fuel/AIC cost of a ship trip from physics parameters you already know (jump count, slider values, gateway LOCK fees read off the live game) - use `tools/shiptrip.py` instead if you just want "ship X from A to B". Landing fuel is a measured-planet lookup via `--to`, independent of whether the route used jumps or gateways. Both tools scoped to this account's one hull/reactor (blueprint BP-STRT-0000, shared by both ships AVI-07JFB/AVI-07JFC); open caveats (v0 relative to current fuel load, landing fuel confounded with gravity/distance, no second hull to cross-check) are in `puga/shipping.py`'s module docstring - don't trust magnitudes beyond what's there. Raw calibration data (APEX DOM reads, 2026-10-09): `empire/data/shipping_calibration/`. Also wired into `tools/network.py`'s freight cost (direct-jump transfers use the real model; gateway transfers need an explicit `trip_cost` in the chain YAML, else a 9250 AIC fallback). Library: `puga/shipping.py` (`trip_fuel()`, `round_trip_cost()`).
|
||||||
|
- `tools/lmscan.py PLANET [--direction source|destination] [--min-margin X]` live Local Market hauling-ad scan (FIO, public/no-auth - real player-posted freight jobs, not the CONTD player-contract system), ranked by margin after real fuel cost (`puga.shipping.leg_cost`). One-way cost only - margin assumes the next job is picked up near the destination, not an empty flight home. A small measured gateway-fee table covers ANT<->HRT/BEN; other gateway routes can't be priced (LOCK fee isn't available via any API). Library: `puga/contracts.py`.
|
||||||
- `tools/price.py` prices across exchanges with VWAP, volume, fill price for a quantity; `tools/book.py` order-book ladder.
|
- `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.
|
- `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.
|
- `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.
|
||||||
|
|||||||
@@ -16,3 +16,8 @@
|
|||||||
4. Big-money recommendations (e.g. BHP go/no-go, roughly 100k AIC): independent second opinion on the numbers.
|
4. Big-money recommendations (e.g. BHP go/no-go, roughly 100k AIC): independent second opinion on the numbers.
|
||||||
- If a bigger-model spawn is refused, tell the player and ask them to run the review.
|
- If a bigger-model spawn is refused, tell the player and ask them to run the review.
|
||||||
- Routine tool building is not reviewed by a bigger model.
|
- Routine tool building is not reviewed by a bigger model.
|
||||||
|
|
||||||
|
## 2026-10-09 Drop "ROI/day %" terminology
|
||||||
|
- `profit/day ÷ new_capex` (what tools were calling "ROI/day X%") is just 1/payback_days rewritten as a percentage. It is NOT a compoundable rate of return - there's no reinvestment mechanism, and every opportunity here is capacity/market-limited (saturation), so it can't be extrapolated or annualized like an interest rate.
|
||||||
|
- Report **payback in days** as the primary number everywhere. A "%/day" figure, if shown at all, must be labelled as simple/non-compounding and never compared to a real yield/interest rate.
|
||||||
|
- Applies to `tools/whatif.py`, `tools/simulate.py`, `tools/scan.py`, `tools/persistence.py`, `tools/history.py`, and anything built after this that reports a return on a one-time building cost.
|
||||||
|
|||||||
@@ -49,6 +49,23 @@ EOF
|
|||||||
-> SystemId), `shortest_path(src, dst, graph=None)` (Dijkstra by straight-line ly over FIO's
|
-> SystemId), `shortest_path(src, dst, graph=None)` (Dijkstra by straight-line ly over FIO's
|
||||||
`/systemstars` jump graph; returns jumps, distance_ly, path). Not a PRUNplanner feature, built
|
`/systemstars` jump graph; returns jumps, distance_ly, path). Not a PRUNplanner feature, built
|
||||||
for this project since travel isn't modelled anywhere else. CLI: `tools/route.py`.
|
for this project since travel isn't modelled anywhere else. CLI: `tools/route.py`.
|
||||||
|
- **`puga.shipping`** — `cruise_leg_fuel(v0)`, `jump_fuel(v1)`, `charge_fuel(v1)`,
|
||||||
|
`gateway_hop_cost(lock_fee_amount, lock_fee_currency)`, `landing_fuel(planet_natural_id)` (lookup
|
||||||
|
only, `None` if unmeasured), `trip_fuel(...)` (one-way total, shared by the CLIs),
|
||||||
|
`leg_cost(src, dst, sf_price, ff_price, v0=1.0, v1=1.0)` (one-way AIC cost; uses
|
||||||
|
`KNOWN_GATEWAY_ROUTES` when the pair has a measured gateway chain, else the direct-jump graph;
|
||||||
|
`None` if neither applies), `round_trip_cost(...)` (there-and-back via two `leg_cost` calls,
|
||||||
|
`None` if either leg is unpriceable or carries a non-AIC fee - used by `tools/network.py`'s
|
||||||
|
freight cost): real ship flight fuel model, linear in the fuel-usage (v0) / reactor-usage (v1)
|
||||||
|
sliders, additive/no cross-term. Scoped to this account's one hull/reactor (BP-STRT-0000, both
|
||||||
|
ships confirmed identical); see the module
|
||||||
|
docstring for confirmed-vs-open caveats before trusting a number. CLIs: `tools/shiptrip.py`
|
||||||
|
(ship+from+to, auto-computes everything via `puga.route`), `tools/shipcost.py` (explicit
|
||||||
|
jumps/sliders/gateway-fees, for when you already know the breakdown). Raw calibration data:
|
||||||
|
`empire/data/shipping_calibration/`.
|
||||||
|
- **`puga.contracts`** — `scan(planet, direction, sf_price, ff_price, v0=1.0, v1=1.0)`: live
|
||||||
|
Local Market hauling ads (FIO `/localmarket/shipping/{source,destination}`), each enriched with
|
||||||
|
real one-way fuel cost (`puga.shipping.leg_cost`) and margin. CLI: `tools/lmscan.py`.
|
||||||
- **`puga.undervalued`** — `manufacturing_candidates()`, `current_margin(ticker, recipe, cx)`,
|
- **`puga.undervalued`** — `manufacturing_candidates()`, `current_margin(ticker, recipe, cx)`,
|
||||||
`scan_current(cx, min_vol=5.0)`: manufactured goods priced below implied production cost, for
|
`scan_current(cx, min_vol=5.0)`: manufactured goods priced below implied production cost, for
|
||||||
a buy-and-hold-for-reversion trade, not a build decision. Backtested expected return is
|
a buy-and-hold-for-reversion trade, not a build decision. Backtested expected return is
|
||||||
|
|||||||
@@ -59,6 +59,13 @@ Sources: Prosperous Universe dev log #239 "Enlisting Labor" (https://prosperousu
|
|||||||
- Report cadence seen on one planet: weekly, Wednesdays ~08:00 UTC (report #289 on 16 Sep 2026).
|
- Report cadence seen on one planet: weekly, Wednesdays ~08:00 UTC (report #289 on 16 Sep 2026).
|
||||||
- The old handoff detail "bases keep 75% of workforce between reports" is not in these sources; treat as unverified.
|
- The old handoff detail "bases keep 75% of workforce between reports" is not in these sources; treat as unverified.
|
||||||
|
|
||||||
|
## Gateway (GTW) jump transit time (measured 2026-10-09)
|
||||||
|
Sources: our own live APEX Ship Flight Control DOM reads (`empire/data/shipping_calibration/{hrt,ben}.json`) and the official handbook (handbook.apex.prosperousuniverse.com/wiki/infrastructure-gateway). The PrUn forum thread "Gateway Question Roundup" (Oct 2024) quotes a dev (molp) saying the team was "considering a fixed transit time, independent of the link length" during pre-launch design.
|
||||||
|
- Our measured GTW segment durations contradict that design intent, if it shipped as described: 17 parsecs -> 5h41m and 5h43m; 15 parsecs -> 5h1m and 5h3m; 10 parsecs -> 3h18m. All five data points land within 19.8-20.2 minutes per parsec - a tight linear fit, not a fixed duration.
|
||||||
|
- Treat GTW transit time as scaling ~linearly with the link's parsec distance (~20 min/parsec) until a wider sample says otherwise (n=3 distinct distances, 2 routes, not independently varied against other factors). The forum statement is 2024 pre-launch discussion, not a current source - our own measurement wins per this project's source-of-truth order.
|
||||||
|
- No fuel or time model for GTW duration exists yet in `puga/shipping.py` (fuel-only); this is a documented fact for whoever builds that next, not wired into any tool.
|
||||||
|
- Per the handbook: LOCK fees have no public formula (gateway-operator-set, displayed in SFC); some gateway links are one-way; each gateway has its own max per-jump cargo volume (m3), separate from ship hold size - none of these are modelled anywhere in this project yet.
|
||||||
|
|
||||||
## HQ in game vs PRUNplanner's "HQ" flag (observed 2026-09-21)
|
## HQ in game vs PRUNplanner's "HQ" flag (observed 2026-09-21)
|
||||||
- The HQ screen (level 1, base permits 1 / 2) shows "Efficiency gains: Electronics 20.0%", and 23.3% for the next level (permits 1 / 3). That is exactly the faction bonus formula (Antares electronics 5% x 2 x (3 - 2 x used/total)), so the HQ display is the faction bonus.
|
- The HQ screen (level 1, base permits 1 / 2) shows "Efficiency gains: Electronics 20.0%", and 23.3% for the next level (permits 1 / 3). That is exactly the faction bonus formula (Antares electronics 5% x 2 x (3 - 2 x used/total)), so the HQ display is the faction bonus.
|
||||||
- PRUNplanner's plan flag "HQ" (x1.1 on every building) is NOT visible in live efficiencies (smelters 1.3361, HWP 1.0696 both match the model without it). Keep it off. The HQ upgrade adds a base permit and raises the faction bonus.
|
- PRUNplanner's plan flag "HQ" (x1.1 on every building) is NOT visible in live efficiencies (smelters 1.3361, HWP 1.0696 both match the model without it). Keep it off. The HQ upgrade adds a base permit and raises the faction bonus.
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ Legend: [ ] todo, [x] done. Build order matters; each step is usable on its own.
|
|||||||
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.
|
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.
|
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. [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.
|
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.
|
||||||
|
9c. [x] `puga/shipping.py` + `tools/shipcost.py` (explicit params) + `tools/shiptrip.py` (just ship/from/to) + `puga.shipping.round_trip_cost()` wired into `tools/network.py`'s freight cost: real ship flight fuel/cost model (STL cruise + FTL jump/charge, linear in the fuel-usage/reactor-usage sliders, additive/no cross-term; gateway hops free-fuel + manual LOCK fee read off the live game, not lookupable via any FIO/PRUNplanner endpoint - checked; landing fuel a measured per-planet lookup). Calibrated 2026-10-09 on this account's one hull/reactor (blueprint BP-STRT-0000, shared by both ships AVI-07JFB/AVI-07JFC, confirmed identical specs via FIO) via a controlled 4x4-slider-grid sweep across 5 real destinations, read from the live APEX Ship Flight Control DOM. Raw data: `empire/data/shipping_calibration/`. Open gaps (see `puga/shipping.py` docstring): departure-side gravity dependence untested (every calibration DEP left the same origin), landing fuel vs gravity/distance confounded (n=3), no second hull/reactor to cross-check generalization. `tools/scan.py --trip-cost` still uses the flat 9250 AIC placeholder (not yet wired to the real model - needs a per-recipe destination planet, not just a CX code).
|
||||||
|
9d. [x] `puga/contracts.py` + `tools/lmscan.py`: live Local Market hauling-ad scan (FIO `/localmarket/shipping/{source,destination}`, public/no-auth - real player-posted freight jobs, not the CONTD player-contract system) ranked by margin after real fuel cost (`puga.shipping.leg_cost`, one-way, with a small measured gateway-fee table `KNOWN_GATEWAY_ROUTES` for ANT<->HRT/BEN). Ship cargo hold confirmed 500t/500m3 via FIO for both ships.
|
||||||
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).
|
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/`.
|
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`.
|
11. [ ] Docs to fill: `docs/apex.md`, `docs/fio.md`, `docs/playbook.md` (question type -> tool), `docs/decisions.md`.
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
# Multi-base chain: Nike mines LST, ships it to Deimos, Deimos turns it (+ market AL) into BSE.
|
# Multi-base chain: Nike mines LST, ships it to Deimos, Deimos turns it (+ market AL) into BSE.
|
||||||
# trip_cost/cargo are placeholders (see tools/network.py) until a real fuel model exists.
|
# trip_cost omitted below: tools/network.py computes it from the real fuel model (puga.shipping)
|
||||||
|
# since Nike<->Deimos is a direct-jump route. cargo is still a placeholder (ship hold size).
|
||||||
name: "Nike LST -> Deimos PP2 (BSE)"
|
name: "Nike LST -> Deimos PP2 (BSE)"
|
||||||
bases:
|
bases:
|
||||||
nike: {plan: plans/examples/nike_lst_ext.yaml, cm_free: true} # founded via the faction expansion contract's kit
|
nike: {plan: plans/examples/nike_lst_ext.yaml, cm_free: true} # founded via the faction expansion contract's kit
|
||||||
deimos: plans/examples/deimos_pp2_bse.yaml
|
deimos: plans/examples/deimos_pp2_bse.yaml
|
||||||
transfers:
|
transfers:
|
||||||
- {material: LST, src: nike, dst: deimos, trip_cost: 9250, cargo: 500}
|
- {material: LST, src: nike, dst: deimos, cargo: 500}
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""Local Market hauling-ad scan: live ads from FIO's /localmarket/shipping/{source,destination}
|
||||||
|
(public, no auth - real player-posted freight-for-hire jobs, NOT the CONTD player-to-player
|
||||||
|
custom contract system). Evaluates each against the real fuel model (puga.shipping).
|
||||||
|
|
||||||
|
SHIP_CARGO is this account's actual ship hold (both AVI-07JFB/AVI-07JFC: 500 t, 500 m3 - confirmed
|
||||||
|
via FIO /storage/{user} SHIP_STORE). A contract whose cargo exceeds this needs multiple round
|
||||||
|
trips to fulfil in one hull; that case is flagged, not computed.
|
||||||
|
|
||||||
|
One-way cost only: this does NOT add a return trip home, because the realistic loop is picking
|
||||||
|
up the NEXT ad near the destination, not flying back empty. That makes the margin reported here
|
||||||
|
optimistic for a one-off job with nothing lined up on the return leg.
|
||||||
|
"""
|
||||||
|
from . import fio, shipping
|
||||||
|
|
||||||
|
SHIP_CARGO = 500.0 # t and m3, both ships
|
||||||
|
|
||||||
|
|
||||||
|
def scan(planet: str, direction: str, sf_price: float, ff_price: float, v0: float = 1.0, v1: float = 1.0):
|
||||||
|
"""direction: 'source' (ads picking up AT `planet`) or 'destination' (ads dropping off there).
|
||||||
|
Returns a list of ads enriched with cost/margin, deduplicated by ContractNaturalId."""
|
||||||
|
ads = fio.lm_shipping_source(planet) if direction == "source" else fio.lm_shipping_destination(planet)
|
||||||
|
seen, rows = set(), []
|
||||||
|
for ad in ads:
|
||||||
|
cid = ad["ContractNaturalId"]
|
||||||
|
if cid in seen:
|
||||||
|
continue
|
||||||
|
seen.add(cid)
|
||||||
|
over_capacity = ad["CargoWeight"] > SHIP_CARGO or ad["CargoVolume"] > SHIP_CARGO
|
||||||
|
cost = None if over_capacity else shipping.leg_cost(ad["OriginPlanetNaturalId"], ad["DestinationPlanetNaturalId"],
|
||||||
|
sf_price, ff_price, v0, v1)
|
||||||
|
payout = ad["PayoutPrice"] if ad["PayoutCurrency"] == "AIC" else None # non-AIC payout not priced here
|
||||||
|
margin = (payout - cost["aic"]) if (cost and payout is not None) else None
|
||||||
|
rows.append({**ad, "over_capacity": over_capacity, "cost": cost, "margin_aic": margin,
|
||||||
|
"margin_per_day": margin / max(ad["DeliveryTime"], 1) if margin is not None else None})
|
||||||
|
return rows
|
||||||
@@ -22,6 +22,12 @@ def planets_full(refresh=False): return _g("/planet/allplanets/full", STATI
|
|||||||
def workforce_needs(refresh=False): return _g("/global/workforceneeds", STATIC, refresh)
|
def workforce_needs(refresh=False): return _g("/global/workforceneeds", STATIC, refresh)
|
||||||
def systems(refresh=False): return _g("/systemstars", STATIC, refresh)
|
def systems(refresh=False): return _g("/systemstars", STATIC, refresh)
|
||||||
def stations(refresh=False): return _g("/exchange/station", STATIC, refresh)
|
def stations(refresh=False): return _g("/exchange/station", STATIC, refresh)
|
||||||
|
def lm_shipping_source(planet: str, refresh=False):
|
||||||
|
"""Live Local Market hauling ads where `planet` is the pickup - public, no auth needed."""
|
||||||
|
return _g(f"/localmarket/shipping/source/{planet}", 15 * 60, refresh)
|
||||||
|
def lm_shipping_destination(planet: str, refresh=False):
|
||||||
|
"""Live Local Market hauling ads where `planet` is the drop-off - public, no auth needed."""
|
||||||
|
return _g(f"/localmarket/shipping/destination/{planet}", 15 * 60, refresh)
|
||||||
|
|
||||||
|
|
||||||
def own(path: str, ttl: int = 300, refresh: bool = False):
|
def own(path: str, ttl: int = 300, refresh: bool = False):
|
||||||
|
|||||||
+12
-1
@@ -8,6 +8,15 @@ the transferred quantity (base A "sells" it, base B "buys" it, at the same price
|
|||||||
combined total needs only ONE correction: the real freight cost of physically moving it, which
|
combined total needs only ONE correction: the real freight cost of physically moving it, which
|
||||||
isn't in either base's isolated numbers. Leftover surplus (more produced than a partner needs) is
|
isn't in either base's isolated numbers. Leftover surplus (more produced than a partner needs) is
|
||||||
still validly sold at market by the producing base; leftover deficit is still validly bought.
|
still validly sold at market by the producing base; leftover deficit is still validly bought.
|
||||||
|
|
||||||
|
CAVEAT: the "cancel out" claim only holds when the price basis prices buy and sell sides of a
|
||||||
|
ticker identically (true for `uni30`, the default in tools/network.py). Under `--basis real`
|
||||||
|
(or any basis with a genuine bid/ask spread), each base's own `simulate()` correctly books its
|
||||||
|
flows at the real sell (bid/vwap) or buy (ask) price - but for the `moved` quantity, that's not
|
||||||
|
what actually happens: it moves at no transaction price at all, not at both a real sale AND a
|
||||||
|
real purchase. Summing the two bases' independent numbers and subtracting only freight therefore
|
||||||
|
UNDERSTATES the true combined profit by the bid-ask spread on the moved quantity - a real gap,
|
||||||
|
not symmetric cancellation, under any basis with a spread. Not corrected here.
|
||||||
"""
|
"""
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from . import fio
|
from . import fio
|
||||||
@@ -33,7 +42,9 @@ class Transfer:
|
|||||||
material: str
|
material: str
|
||||||
src: str # producing base's name (key in the `bases` dict)
|
src: str # producing base's name (key in the `bases` dict)
|
||||||
dst: str # consuming base's name
|
dst: str # consuming base's name
|
||||||
trip_cost: float = 9250.0 # AIC per round trip; PLACEHOLDER until a real route/fuel model exists
|
trip_cost: float = 9250.0 # AIC per round trip; tools/network.py fills this from puga.shipping.round_trip_cost()
|
||||||
|
# when src/dst are a direct-jump route and no explicit value is given in the chain
|
||||||
|
# YAML - this default is the fallback for gateway routes/transfers without one
|
||||||
cargo: float = 500.0 # t or m3 per trip
|
cargo: float = 500.0 # t or m3 per trip
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+6
-2
@@ -28,15 +28,19 @@ def load_graph():
|
|||||||
|
|
||||||
|
|
||||||
def resolve_system(query: str) -> str:
|
def resolve_system(query: str) -> str:
|
||||||
"""Planet natural id (e.g. ZV-759c), system natural id (ZV-759), or a name -> SystemId."""
|
"""Planet natural id (e.g. ZV-759c), CX station code (ANT), system natural id (ZV-759), or
|
||||||
|
a name -> SystemId."""
|
||||||
q = query.strip().upper()
|
q = query.strip().upper()
|
||||||
for p in fio.planets_full():
|
for p in fio.planets_full():
|
||||||
if p.get("PlanetNaturalId", "").upper() == q or (p.get("PlanetName") or "").upper() == q:
|
if p.get("PlanetNaturalId", "").upper() == q or (p.get("PlanetName") or "").upper() == q:
|
||||||
return p["SystemId"]
|
return p["SystemId"]
|
||||||
|
for st in fio.stations():
|
||||||
|
if st["NaturalId"].upper() == q or st["Name"].upper() == q:
|
||||||
|
return st["SystemId"]
|
||||||
for s in fio.systems():
|
for s in fio.systems():
|
||||||
if s["NaturalId"].upper() == q or s["Name"].upper() == q:
|
if s["NaturalId"].upper() == q or s["Name"].upper() == q:
|
||||||
return s["SystemId"]
|
return s["SystemId"]
|
||||||
raise ValueError(f"no planet or system matches {query!r}")
|
raise ValueError(f"no planet, station, or system matches {query!r}")
|
||||||
|
|
||||||
|
|
||||||
def shortest_path(src_system_id: str, dst_system_id: str, graph=None):
|
def shortest_path(src_system_id: str, dst_system_id: str, graph=None):
|
||||||
|
|||||||
@@ -0,0 +1,210 @@
|
|||||||
|
"""Ship flight fuel/cost model - STL cruise, FTL jumps/charges, gateway hops.
|
||||||
|
|
||||||
|
SCOPED TO ONE HULL/REACTOR: calibrated on AVI-07JFB (Freighter, blueprint BP-STRT-0000, stock
|
||||||
|
reactor). The account has two ships - AVI-07JFB and AVI-07JFC - but both are the SAME blueprint
|
||||||
|
with identical Acceleration/Thrust/ReactorPower/EmitterPower/OperatingEmptyMass (confirmed via
|
||||||
|
FIO `/ship/ships/{user}`), so this model should apply to both; only their current cargo mass
|
||||||
|
differs, and mass is already confirmed not to affect fuel/time (see below). Coefficients below
|
||||||
|
are NOT confirmed to generalize to any OTHER hull or reactor module - there isn't one on this
|
||||||
|
account to test against yet. Do not trust the magnitudes for a different hull/reactor without
|
||||||
|
recalibrating (see "OPEN GAPS" below). Coefficients are fit from a controlled 4x4-grid sweep
|
||||||
|
(fuel-usage x reactor-usage sliders) across 5 real destinations (Deimos, Nike, Vulcan, and
|
||||||
|
gateway-routed Benten/Hortus), with exact values read from the live APEX Ship Flight Control DOM
|
||||||
|
(never screenshots/estimates). Raw data: empire/data/shipping_calibration/.
|
||||||
|
|
||||||
|
CONFIRMED (high confidence, R^2 close to 1 on 4-point linear fits, cross-checked on 5 routes):
|
||||||
|
- Fuel-usage slider (v0, 0..1 - NOT an absolute unit, see OPEN GAPS) and reactor-usage slider
|
||||||
|
(v1, 0..1) are fully INDEPENDENT/additive - zero cross-term on any segment, confirmed on full
|
||||||
|
4x4 grids. STL fuel never changes across different v1 at fixed v0, and vice versa for FTL.
|
||||||
|
- STL cruise fuel (DEP/APP/long-TRA segments) = STL_INTERCEPT + STL_SLOPE * v0. Slope ~240
|
||||||
|
units/unit-v0, essentially identical for DEP and APP and for long in-system TRA legs on
|
||||||
|
gateway routes. Intercept is small (~1-8 units) and segment-specific.
|
||||||
|
- FTL jump fuel = JUMP_FTL_SLOPE * v1 (no intercept). FTL recharge (CHRG, needed between two
|
||||||
|
consecutive jumps with no landing in between) = CHARGE_FTL_SLOPE * v1 (no intercept, lower
|
||||||
|
slope than a jump - recharging is cheaper than jumping).
|
||||||
|
- LND (final landing) fuel is a CONSTANT per destination, independent of BOTH sliders -
|
||||||
|
confirmed across full 4x4 grids on 3 planets (zero variation). This is NOT a formula, it's a
|
||||||
|
per-planet constant that must be measured - see LANDING_FUEL below and its gravity/distance
|
||||||
|
caveat.
|
||||||
|
- Gateway (GTW) hops cost ZERO fuel (STL and FTL) - confirmed by direct inspection of raw
|
||||||
|
segment rows on 2 different gateway-routed destinations (Benten: 3 gateways, Hortus: 2
|
||||||
|
gateways). Cost is a fixed LOCK fee instead (AIC or CIS, varies per specific gateway, not
|
||||||
|
predictable by formula - read it off the real route) plus a small fixed 5-unit STL cost for
|
||||||
|
the LOCK maneuver itself. DCAY and short inter-gateway TRA hops are small fixed STL amounts
|
||||||
|
(5-15 units) independent of both sliders. The reactor-usage slider is INERT on pure-gateway
|
||||||
|
routes (no direct JMP segment) - confirmed its full allowed range changes nothing.
|
||||||
|
|
||||||
|
OPEN GAPS - do not assume these are resolved:
|
||||||
|
1. v0's absolute meaning: at v0=1, STL fuel always came out to exactly the ship's then-current
|
||||||
|
STL tank level (525-526, matching a tank at 526/1500 at calibration time) regardless of
|
||||||
|
route distance - v0 looks like "fraction of CURRENTLY BUNKERED fuel to spend on this leg",
|
||||||
|
not an absolute physical speed/fuel unit. This model's v0->fuel formula is calibrated
|
||||||
|
against THAT fuel load; if the ship's tank level is very different, recalibrate rather than
|
||||||
|
trust the magnitudes.
|
||||||
|
2. DEP's departure-side gravity dependence is UNTESTED - every DEP segment in the calibration
|
||||||
|
sweep departed from Antares Station (same origin, same gravity every time). A hypothesized
|
||||||
|
"gravity-well-escape" term on departure has neither been confirmed nor refuted.
|
||||||
|
3. LND fuel vs gravity vs distance is CONFOUNDED, not resolved - Deimos (gravity 1.032) and
|
||||||
|
Vulcan (gravity 1.238) have near-identical landing distance (4,243 vs 4,441 km) and IDENTICAL
|
||||||
|
landing fuel (38); Nike (gravity 0.624, lower) has a much longer landing distance (7,034 km)
|
||||||
|
and higher fuel (48). This points at distance mattering more than gravity, but n=3 isn't
|
||||||
|
enough for a real coefficient, and gravity/distance aren't varied independently in the
|
||||||
|
sample. Don't predict LND fuel for an unmeasured planet - look it up for real.
|
||||||
|
4. Hull/reactor generalization beyond this one blueprint (BP-STRT-0000, stock reactor) is
|
||||||
|
COMPLETELY UNTESTED - both ships on this account (AVI-07JFB, AVI-07JFC) share it, so there's
|
||||||
|
nothing else to cross-check against yet. The reactor-usage slider's own allowed range was
|
||||||
|
only 0.303-1 even on direct-jump routes, suggesting the stock reactor is itself constrained -
|
||||||
|
a different reactor module would need its own sweep, not an assumption that these
|
||||||
|
slopes/intercepts carry over.
|
||||||
|
5. KNOWN_GATEWAY_ROUTES assumes a gateway chain is usable and equally priced in both directions.
|
||||||
|
Per the official handbook (handbook.apex.prosperousuniverse.com/wiki/infrastructure-gateway),
|
||||||
|
some gateway links are ONE-WAY (map arrows show the permitted direction) - the reverse leg of
|
||||||
|
a known route may not exist at all, not just cost something different. round_trip_cost()
|
||||||
|
and leg_cost() have no way to detect this; don't trust a return leg on a gateway route until
|
||||||
|
it's separately confirmed live.
|
||||||
|
6. Each gateway has its own maximum per-jump VOLUME (m3) cap, per the handbook, independent of
|
||||||
|
ship cargo capacity - not measured or modelled anywhere here. This matters for any "use a
|
||||||
|
bigger ship to bundle more cargo through one gateway trip" reasoning (see tools/lmscan.py
|
||||||
|
analysis) - a bigger hold doesn't help if the gateway's own cap is lower.
|
||||||
|
7. TRIP TIME (not just fuel) is not modelled anywhere in this file. For what we do know about
|
||||||
|
GTW segment duration (scales ~linearly with parsec distance at ~20 min/parsec, contradicting
|
||||||
|
a pre-launch dev statement about a possibly-fixed duration), see docs/mechanics.md's
|
||||||
|
"Gateway (GTW) jump transit time" section - built from the same raw data this module uses.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Calibrated on AVI-07JFB, 2026-10-09. See module docstring for what's confirmed vs open.
|
||||||
|
STL_SLOPE = 240.0 # units per unit of v0 (fuel-usage slider), DEP/APP/long-TRA alike
|
||||||
|
STL_INTERCEPT = 3.0 # small, roughly the DEP/APP average; noise-level, not precise
|
||||||
|
JUMP_FTL_SLOPE = 28.4 # units per unit of v1 (reactor-usage slider), per direct JMP
|
||||||
|
CHARGE_FTL_SLOPE = 22.8 # units per unit of v1, per CHRG (recharge between consecutive jumps)
|
||||||
|
|
||||||
|
# Fixed, slider-independent costs on gateway-routed segments (confirmed on Benten/Hortus):
|
||||||
|
GATEWAY_HOP_FIXED_STL = 5.0 # the LOCK maneuver itself
|
||||||
|
SHORT_TRA_FIXED_STL = 15.0 # the ~10s hop immediately around a gateway
|
||||||
|
DCAY_FIXED_STL = 5.0 # post-gateway decay step
|
||||||
|
|
||||||
|
# The hull/reactor this file is calibrated against (both AVI-07JFB and AVI-07JFC match this via
|
||||||
|
# FIO /ship/ships/{user} - confirmed 2026-10-09). tools/shiptrip.py checks a given ship's live
|
||||||
|
# specs against this and warns if they don't match (a third, different ship would invalidate
|
||||||
|
# the coefficients above - see OPEN GAPS #4).
|
||||||
|
CALIBRATED_SPEC = {"blueprint": "BP-STRT-0000", "acceleration": 78.4800033569336, "thrust": 125000.0,
|
||||||
|
"reactor_power": 2400.0, "emitter_power": 725.0}
|
||||||
|
|
||||||
|
# LOOKUP, not a formula (see OPEN GAPS #3) - only destinations we've actually measured.
|
||||||
|
# {planet_natural_id: (landing_fuel_STL, landing_distance_km, gravity)}
|
||||||
|
LANDING_FUEL = {
|
||||||
|
"ZV-759c": (38, 4243, 1.032), # Deimos
|
||||||
|
"ZV-759b": (38, 4441, 1.238), # Vulcan
|
||||||
|
"ZV-194a": (48, 7034, 0.624), # Nike
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def cruise_leg_fuel(v0: float) -> float:
|
||||||
|
"""One STL cruise leg (DEP, APP, or a long in-system TRA on a gateway route)."""
|
||||||
|
return STL_INTERCEPT + STL_SLOPE * v0
|
||||||
|
|
||||||
|
|
||||||
|
def jump_fuel(v1: float) -> float:
|
||||||
|
"""One direct FTL jump (JMP segment, not a gateway hop)."""
|
||||||
|
return JUMP_FTL_SLOPE * v1
|
||||||
|
|
||||||
|
|
||||||
|
def charge_fuel(v1: float) -> float:
|
||||||
|
"""One FTL recharge (CHRG) between two consecutive jumps with no landing between them."""
|
||||||
|
return CHARGE_FTL_SLOPE * v1
|
||||||
|
|
||||||
|
|
||||||
|
def gateway_hop_cost(lock_fee_amount: float, lock_fee_currency: str):
|
||||||
|
"""One gateway hop (LOCK + GTW + DCAY + the short TRA around it): the GTW segment itself
|
||||||
|
is free (confirmed), but LOCK charges a fixed real-money fee you must supply (not
|
||||||
|
predictable - read it off the actual route, it varies per specific gateway pair)."""
|
||||||
|
stl = GATEWAY_HOP_FIXED_STL + SHORT_TRA_FIXED_STL + DCAY_FIXED_STL
|
||||||
|
return {"stl_fuel": stl, "fee_amount": lock_fee_amount, "fee_currency": lock_fee_currency}
|
||||||
|
|
||||||
|
|
||||||
|
def landing_fuel(planet_natural_id: str):
|
||||||
|
"""Looked-up, not predicted - returns None if we haven't actually measured this planet.
|
||||||
|
See OPEN GAPS #3: don't extrapolate this to an unmeasured planet."""
|
||||||
|
row = LANDING_FUEL.get(planet_natural_id)
|
||||||
|
return row[0] if row else None
|
||||||
|
|
||||||
|
|
||||||
|
# Specific gateway-chain routes we've actually measured, keyed by frozenset so the SAME entry
|
||||||
|
# is used for either direction - NOT confirmed to be valid: the handbook says some gateway links
|
||||||
|
# are one-way, so the reverse leg may not exist or may cost differently (see OPEN GAPS #5).
|
||||||
|
# {frozenset({a, b}): [(fee_amount, fee_currency), ...]}
|
||||||
|
KNOWN_GATEWAY_ROUTES = {
|
||||||
|
frozenset({"ANT", "HRT"}): [(6000, "AIC"), (6000, "AIC")],
|
||||||
|
frozenset({"ANT", "BEN"}): [(6000, "AIC"), (6000, "AIC"), (4000, "CIS")],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def cx_system(cx: str) -> str | None:
|
||||||
|
"""CX code (AI1, CI1, ...) -> the natural id of its physical station, from FIO's own
|
||||||
|
/exchange/station (ComexCode). Feeds leg_cost/round_trip_cost's src argument when the origin
|
||||||
|
is "the home exchange" rather than a specific planet. None if the code isn't a real station."""
|
||||||
|
from . import fio
|
||||||
|
row = next((s for s in fio.stations() if s.get("ComexCode") == cx), None)
|
||||||
|
return row["NaturalId"] if row else None
|
||||||
|
|
||||||
|
|
||||||
|
def leg_cost(src: str, dst: str, sf_price: float, ff_price: float, v0: float = 1.0, v1: float = 1.0):
|
||||||
|
"""One-way fuel (+ gateway fee) AIC cost between two places (station/planet natural ids).
|
||||||
|
Prefers a measured gateway chain (KNOWN_GATEWAY_ROUTES) when this exact pair has one;
|
||||||
|
otherwise tries the direct-jump graph (puga.route). Returns None if neither applies - an
|
||||||
|
unmeasured gateway route, where the LOCK fee can't be priced at all. Non-AIC gateway fees
|
||||||
|
(e.g. CIS) are reported separately, not folded into `aic`."""
|
||||||
|
from . import route
|
||||||
|
key = frozenset({src, dst})
|
||||||
|
if key in KNOWN_GATEWAY_ROUTES:
|
||||||
|
result = trip_fuel(v0, v1, jumps=0, charges=0, cruise_legs=2, dest_planet_natural_id=dst,
|
||||||
|
gateway_lock_fees=KNOWN_GATEWAY_ROUTES[key])
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
src_sys, dst_sys = route.resolve_system(src), route.resolve_system(dst)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
if src_sys == dst_sys:
|
||||||
|
jumps = 0
|
||||||
|
else:
|
||||||
|
r = route.shortest_path(src_sys, dst_sys)
|
||||||
|
if r is None:
|
||||||
|
return None
|
||||||
|
jumps = r["jumps"]
|
||||||
|
result = trip_fuel(v0, v1, jumps, max(jumps - 1, 0), cruise_legs=2, dest_planet_natural_id=dst)
|
||||||
|
aic = result["stl_fuel"] * sf_price + result["ftl_fuel"] * ff_price
|
||||||
|
aic += sum(amt for amt, cur in result["lock_fees"] if cur == "AIC")
|
||||||
|
non_aic_fees = [(amt, cur) for amt, cur in result["lock_fees"] if cur != "AIC"]
|
||||||
|
return {"aic": aic, "non_aic_fees": non_aic_fees, "stl_fuel": result["stl_fuel"], "ftl_fuel": result["ftl_fuel"],
|
||||||
|
"landing_fuel_included": result["landing_fuel_included"]}
|
||||||
|
|
||||||
|
|
||||||
|
def round_trip_cost(src: str, dst: str, sf_price: float, ff_price: float, v0: float = 1.0, v1: float = 1.0):
|
||||||
|
"""AIC cost of a round trip (there and back) between two places - the sum of two `leg_cost`
|
||||||
|
calls, there and back. Returns None if either leg can't be priced (an unmeasured gateway
|
||||||
|
route) or either leg carries a non-AIC fee (no AIC exchange rate assumed here - see
|
||||||
|
`leg_cost`'s `non_aic_fees`, which this collapses rather than silently drop)."""
|
||||||
|
there, back = leg_cost(src, dst, sf_price, ff_price, v0, v1), leg_cost(dst, src, sf_price, ff_price, v0, v1)
|
||||||
|
if there is None or back is None or there["non_aic_fees"] or back["non_aic_fees"]:
|
||||||
|
return None
|
||||||
|
return there["aic"] + back["aic"]
|
||||||
|
|
||||||
|
|
||||||
|
def trip_fuel(v0: float, v1: float, jumps: int, charges: int, cruise_legs: int = 2,
|
||||||
|
dest_planet_natural_id: str | None = None, gateway_lock_fees: list[tuple[float, str]] = ()):
|
||||||
|
"""Total STL/FTL fuel (plus any gateway LOCK fees passed straight through) for one trip.
|
||||||
|
This is the one place the cost arithmetic lives - tools/shipcost.py (manual/explicit
|
||||||
|
params) and tools/shiptrip.py (--ship/--from/--to, auto-derives jumps/charges/landing)
|
||||||
|
both call this instead of duplicating it. Returns {stl_fuel, ftl_fuel, lock_fees:
|
||||||
|
[(amount, currency), ...], landing_fuel_included: bool}."""
|
||||||
|
stl = cruise_legs * cruise_leg_fuel(v0)
|
||||||
|
ftl = jumps * jump_fuel(v1) + charges * charge_fuel(v1)
|
||||||
|
fees = []
|
||||||
|
for amount, currency in gateway_lock_fees:
|
||||||
|
g = gateway_hop_cost(amount, currency)
|
||||||
|
stl += g["stl_fuel"]
|
||||||
|
fees.append((g["fee_amount"], g["fee_currency"]))
|
||||||
|
lnd = landing_fuel(dest_planet_natural_id) if dest_planet_natural_id else None
|
||||||
|
if lnd is not None:
|
||||||
|
stl += lnd
|
||||||
|
return {"stl_fuel": stl, "ftl_fuel": ftl, "lock_fees": fees, "landing_fuel_included": lnd}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
"""Expected values from the real APEX Ship Flight Control DOM reads, 2026-10-09 calibration
|
||||||
|
sweep (AVI-07JFB). Raw data in empire/data/shipping_calibration/."""
|
||||||
|
import pytest
|
||||||
|
from puga import shipping
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("v0,actual", [(0.01, 3), (0.34, 83), (0.67, 162), (1.0, 242)])
|
||||||
|
def test_cruise_leg_fuel_matches_dep(v0, actual):
|
||||||
|
assert shipping.cruise_leg_fuel(v0) == pytest.approx(actual, abs=5)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("v1,actual", [(0.303, 8), (0.535, 15), (0.768, 21), (1.0, 28)])
|
||||||
|
def test_jump_fuel(v1, actual):
|
||||||
|
assert shipping.jump_fuel(v1) == pytest.approx(actual, abs=1)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("v1,actual", [(0.303, 6), (0.535, 12), (0.768, 17), (1.0, 22)])
|
||||||
|
def test_charge_fuel(v1, actual):
|
||||||
|
assert shipping.charge_fuel(v1) == pytest.approx(actual, abs=1)
|
||||||
|
|
||||||
|
|
||||||
|
def test_charge_cheaper_than_jump():
|
||||||
|
for v1 in (0.3, 0.5, 0.7, 1.0):
|
||||||
|
assert shipping.charge_fuel(v1) < shipping.jump_fuel(v1)
|
||||||
|
|
||||||
|
|
||||||
|
def test_landing_fuel_lookup():
|
||||||
|
assert shipping.landing_fuel("ZV-759c") == 38 # Deimos
|
||||||
|
assert shipping.landing_fuel("ZV-759b") == 38 # Vulcan
|
||||||
|
assert shipping.landing_fuel("ZV-194a") == 48 # Nike
|
||||||
|
|
||||||
|
|
||||||
|
def test_landing_fuel_unmeasured_returns_none():
|
||||||
|
assert shipping.landing_fuel("ZV-307") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_gateway_hop_is_fuel_free_plus_fixed_fee():
|
||||||
|
g = shipping.gateway_hop_cost(6000, "AIC")
|
||||||
|
assert g["fee_amount"] == 6000
|
||||||
|
assert g["fee_currency"] == "AIC"
|
||||||
|
assert g["stl_fuel"] == shipping.GATEWAY_HOP_FIXED_STL + shipping.SHORT_TRA_FIXED_STL + shipping.DCAY_FIXED_STL
|
||||||
|
|
||||||
|
|
||||||
|
def test_sliders_additive_no_cross_term():
|
||||||
|
# cruise fuel must not depend on v1, jump fuel must not depend on v0 - the whole point
|
||||||
|
# of the independence finding this model is built on.
|
||||||
|
base = shipping.cruise_leg_fuel(0.5)
|
||||||
|
assert shipping.cruise_leg_fuel(0.5) == base
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Scan live Local Market hauling ads (real player-posted freight jobs, FIO
|
||||||
|
/localmarket/shipping/*) and rank by margin after real fuel cost (puga.shipping). One-way cost
|
||||||
|
only (margin assumes you pick up the next job near the destination, not an empty flight home).
|
||||||
|
|
||||||
|
tools/lmscan.py ANT # ads picking up at Antares Station
|
||||||
|
tools/lmscan.py ANT --direction destination # ads dropping off at Antares Station
|
||||||
|
tools/lmscan.py ZV-759c --min-margin 0 # only profitable ones, from Deimos
|
||||||
|
"""
|
||||||
|
import argparse, sys
|
||||||
|
from pathlib import Path
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
from puga import config, contracts, market
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument("planet", help="station/planet natural id to scan ads at, e.g. ANT, ZV-759c")
|
||||||
|
ap.add_argument("--direction", choices=["source", "destination"], default="source",
|
||||||
|
help="source = ads picking up here (default); destination = ads dropping off here")
|
||||||
|
ap.add_argument("--v0", type=float, default=1.0)
|
||||||
|
ap.add_argument("--v1", type=float, default=1.0)
|
||||||
|
ap.add_argument("--min-margin", type=float, help="only show ads with at least this AIC margin")
|
||||||
|
ap.add_argument("--cx", default=config.DEFAULT_CX)
|
||||||
|
a = ap.parse_args()
|
||||||
|
|
||||||
|
snap = market.snapshot()
|
||||||
|
sf_px = (snap.get(("SF", a.cx)) or market.Quote("SF", a.cx)).ask or 0
|
||||||
|
ff_px = (snap.get(("FF", a.cx)) or market.Quote("FF", a.cx)).ask or 0
|
||||||
|
|
||||||
|
rows = contracts.scan(a.planet, a.direction, sf_px, ff_px, a.v0, a.v1)
|
||||||
|
priced = [r for r in rows if r["margin_aic"] is not None]
|
||||||
|
unpriceable = [r for r in rows if r["margin_aic"] is None]
|
||||||
|
priced.sort(key=lambda r: r["margin_aic"], reverse=True)
|
||||||
|
if a.min_margin is not None:
|
||||||
|
priced = [r for r in priced if r["margin_aic"] >= a.min_margin]
|
||||||
|
|
||||||
|
print(f"{len(rows)} ads ({a.direction} = {a.planet}), {len(priced)} priceable at v0={a.v0} v1={a.v1}\n")
|
||||||
|
print(f"{'route':16} {'jump':4} {'t':>6} {'m3':>6} {'payout':>9} {'fuel/fee':>9} {'margin':>9} {'margin/day':>11}")
|
||||||
|
for r in priced:
|
||||||
|
print(f"{r['OriginPlanetNaturalId']}->{r['DestinationPlanetNaturalId']:11} {r['JumpDistance']:4} "
|
||||||
|
f"{r['CargoWeight']:6.0f} {r['CargoVolume']:6.0f} {r['PayoutPrice']:9,.0f} "
|
||||||
|
f"{r['cost']['aic']:9,.0f} {r['margin_aic']:9,.0f} {r['margin_per_day']:11,.0f}")
|
||||||
|
|
||||||
|
if unpriceable:
|
||||||
|
print(f"\n{len(unpriceable)} ad(s) not priced (over-capacity cargo, non-AIC payout, or an unmeasured gateway route):")
|
||||||
|
for r in unpriceable:
|
||||||
|
reason = "cargo exceeds 500t/500m3 (needs multiple trips, not modelled)" if r["over_capacity"] else \
|
||||||
|
("non-AIC payout" if r["PayoutCurrency"] != "AIC" else "no known route (unmeasured gateway?)")
|
||||||
|
print(f" {r['OriginPlanetNaturalId']}->{r['DestinationPlanetNaturalId']} {r['PayoutPrice']:,.0f} {r['PayoutCurrency']} [{reason}]")
|
||||||
|
|
||||||
|
print("\nCAVEATS: one-way cost only, assumes a return cargo lined up at the destination (no empty flight home "
|
||||||
|
"priced in) - see puga/contracts.py. margin/day divides by the ad's DeliveryTime DEADLINE, not real "
|
||||||
|
"transit time (we don't model trip duration, only fuel) - treat it as a floor, not the real rate. "
|
||||||
|
"Fuel model itself is scoped to this account's one hull/reactor; see puga/shipping.py for open gaps.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+29
-9
@@ -9,7 +9,7 @@ import argparse, sys
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import yaml
|
import yaml
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
from puga import ROOT, config, market, prunplanner as pp
|
from puga import ROOT, config, market, prunplanner as pp, shipping
|
||||||
from puga.network import BaseNode, Transfer, combine
|
from puga.network import BaseNode, Transfer, combine
|
||||||
|
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||||
@@ -56,18 +56,35 @@ def main():
|
|||||||
built["CM"] = 1
|
built["CM"] = 1
|
||||||
bases[key] = BaseNode(key, plan, recipes, blds, planet["resources"], planet["fertility"], price, faction, perm, built)
|
bases[key] = BaseNode(key, plan, recipes, blds, planet["resources"], planet["fertility"], price, faction, perm, built)
|
||||||
|
|
||||||
transfers = [Transfer(**t) for t in net.get("transfers", [])]
|
sf_px = (snap.get(("SF", a.cx)) or market.Quote("SF", a.cx)).ask or 0
|
||||||
|
ff_px = (snap.get(("FF", a.cx)) or market.Quote("FF", a.cx)).ask or 0
|
||||||
|
transfers, cost_notes = [], []
|
||||||
|
for raw in net.get("transfers", []):
|
||||||
|
t = dict(raw)
|
||||||
|
if "trip_cost" not in t and t["src"] in bases and t["dst"] in bases:
|
||||||
|
real = shipping.round_trip_cost(bases[t["src"]].plan["planet_natural_id"], bases[t["dst"]].plan["planet_natural_id"],
|
||||||
|
sf_px, ff_px)
|
||||||
|
if real is not None:
|
||||||
|
t["trip_cost"] = real
|
||||||
|
cost_notes.append(f" {t['material']} {t['src']}->{t['dst']}: real round-trip cost {real:,.0f} AIC (puga.shipping)")
|
||||||
|
else:
|
||||||
|
cost_notes.append(f" {t['material']} {t['src']}->{t['dst']}: no direct-jump route (gateway?) - using placeholder {Transfer.__dataclass_fields__['trip_cost'].default:,.0f} AIC, check SFC in-game")
|
||||||
|
transfers.append(Transfer(**t))
|
||||||
r = combine(bases, transfers)
|
r = combine(bases, transfers)
|
||||||
|
|
||||||
print(f"{net.get('name', a.spec)} ({a.basis} prices)\n")
|
print(f"{net.get('name', a.spec)} ({a.basis} prices)\n")
|
||||||
for key, res in r["results"].items():
|
for key, res in r["results"].items():
|
||||||
line = f"[{key}] area {res['area']:.0f} profit/day {res['profit']:,.0f} new capex {res['new_capex']:,.0f}"
|
line = f"[{key}] area {res['area']:.0f} profit/day {res['profit']:,.0f} new capex {res['new_capex']:,.0f}"
|
||||||
if res["new_capex"] > 0:
|
if res["new_capex"] > 0:
|
||||||
line += f" ({100*res['profit']/res['new_capex']:.1f}%/day)"
|
line += f" (payback {res['new_capex']/res['profit']:.1f} d)"
|
||||||
print(line)
|
print(line)
|
||||||
for b in res["buildings"]:
|
for b in res["buildings"]:
|
||||||
print(f" {b['amount']:2} x {b['building']:4} eff {b['efficiency']*100:6.1f}%")
|
print(f" {b['amount']:2} x {b['building']:4} eff {b['efficiency']*100:6.1f}%")
|
||||||
|
|
||||||
|
if cost_notes:
|
||||||
|
print("\nFREIGHT COST")
|
||||||
|
print("\n".join(cost_notes))
|
||||||
|
|
||||||
print("\nTRANSFERS")
|
print("\nTRANSFERS")
|
||||||
for t in r["ledger"]:
|
for t in r["ledger"]:
|
||||||
note = f"SHORTFALL {t['shortfall']:.1f}/d bought at market by {t['dst']}" if t["shortfall"] > 0.01 else \
|
note = f"SHORTFALL {t['shortfall']:.1f}/d bought at market by {t['dst']}" if t["shortfall"] > 0.01 else \
|
||||||
@@ -77,13 +94,16 @@ def main():
|
|||||||
|
|
||||||
total_new_capex = sum(res["new_capex"] for res in r["results"].values())
|
total_new_capex = sum(res["new_capex"] for res in r["results"].values())
|
||||||
print(f"\nCOMBINED profit/day {r['total_profit']:,.0f} new capex {total_new_capex:,.0f}"
|
print(f"\nCOMBINED profit/day {r['total_profit']:,.0f} new capex {total_new_capex:,.0f}"
|
||||||
+ (f" {100*r['total_profit']/total_new_capex:.1f}%/day" if total_new_capex > 0 else ""))
|
+ (f" payback {total_new_capex/r['total_profit']:.1f} d" if total_new_capex > 0 else ""))
|
||||||
print("CAUTION: a base's 'profit/day' here is its WHOLE plan (existing buildings included), not just the new "
|
print("CAUTION: a base's 'profit/day' here is its WHOLE plan (existing buildings included), not just the new "
|
||||||
"addition, so its %/day overstates the marginal return where new_capex is small relative to an existing "
|
"addition, so its payback here understates the marginal payback where new_capex is small relative to an "
|
||||||
"base. For the true marginal ROI, also simulate the base's plan WITHOUT the new building/transfer and "
|
"existing base. For the true marginal payback, also simulate the base's plan WITHOUT the new "
|
||||||
"diff the profit; see docs/library.md.")
|
"building/transfer and diff the profit; see docs/library.md.")
|
||||||
print("NOTE: trip_cost/cargo are placeholders (default 9250 AIC, 500 t/m3, same as the AI1 route) until a real "
|
print("NOTE: trip_cost is computed from the real fuel model (puga.shipping, max sliders) for direct-jump routes "
|
||||||
"inter-base fuel model exists (docs/roadmap.md tools/route.py) -- check SFC in-game for the real cost.")
|
"between two bases in this chain (see FREIGHT COST above); a gateway route, or a transfer with an "
|
||||||
|
"explicit trip_cost in the YAML, uses that value instead (9250 AIC if neither applies). cargo defaults "
|
||||||
|
"to 500 t/m3 (the account's ship hold size, confirmed via FIO) - override per-transfer if a different "
|
||||||
|
"ship is used.")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
+9
-7
@@ -1,9 +1,10 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""Depth-aware single-step recipe scan at one exchange (saturation model v1, see docs/saturation-design.md).
|
"""Depth-aware single-step recipe scan at one exchange (saturation model v1, see docs/saturation-design.md).
|
||||||
For each recipe: buildings the market can absorb (N*), and ROI/day at N=1 and N* using a patient sell price
|
For each recipe: buildings the market can absorb (N*), and payback/yield at N=1 and N* using a patient sell
|
||||||
(not top-of-book) and ask-walked inputs. Excludes thin markets by default.
|
price (not top-of-book) and ask-walked inputs. Excludes thin markets by default. yld/d is profit/day over
|
||||||
|
capex as a %, NOT a compoundable rate - it's 1/payback; see docs/decisions.md's "Drop ROI/day %" entry.
|
||||||
|
|
||||||
tools/scan.py # AI1, all tiers, top 30 by ROI at N*
|
tools/scan.py # AI1, all tiers, top 30 by yield at N*
|
||||||
tools/scan.py --cogc METALLURGY --tier S # e.g. a Metallurgy-COGC base, up to settlers
|
tools/scan.py --cogc METALLURGY --tier S # e.g. a Metallurgy-COGC base, up to settlers
|
||||||
tools/scan.py --sort total --min-n 3 # rank by absorbable profit/day
|
tools/scan.py --sort total --min-n 3 # rank by absorbable profit/day
|
||||||
"""
|
"""
|
||||||
@@ -35,7 +36,7 @@ def main():
|
|||||||
ap.add_argument("--deprec", type=float, default=0, help="demolish-later mode: building value decays linearly to 0 over this many days (game: ~60); subtracts capex/deprec per day")
|
ap.add_argument("--deprec", type=float, default=0, help="demolish-later mode: building value decays linearly to 0 over this many days (game: ~60); subtracts capex/deprec per day")
|
||||||
ap.add_argument("--input", help="only recipes consuming this ticker as an input, e.g. --input AL for recipes built on top of your own AL chain")
|
ap.add_argument("--input", help="only recipes consuming this ticker as an input, e.g. --input AL for recipes built on top of your own AL chain")
|
||||||
ap.add_argument("--planet", help="planet natural id: adds extraction (EXT/COL/RIG) from its resources, uses its fertility and active COGC; new base (not in state) => no HQ, permits+1")
|
ap.add_argument("--planet", help="planet natural id: adds extraction (EXT/COL/RIG) from its resources, uses its fertility and active COGC; new base (not in state) => no HQ, permits+1")
|
||||||
ap.add_argument("--own", type=int, default=1, help="how many buildings WE would run; ROI is measured at this size (default 1). --min-n is only a market-size filter")
|
ap.add_argument("--own", type=int, default=1, help="how many buildings WE would run; yield/payback is measured at this size (default 1). --min-n is only a market-size filter")
|
||||||
ap.add_argument("--skip", default="", help="tiers left unstaffed, e.g. technician (no housing/wages; efficiency = staffed headcount share)")
|
ap.add_argument("--skip", default="", help="tiers left unstaffed, e.g. technician (no housing/wages; efficiency = staffed headcount share)")
|
||||||
ap.add_argument("--experts", default="", help="expert counts, e.g. METALLURGY=2 (bonus x1.0306..1.284 for 1..5)")
|
ap.add_argument("--experts", default="", help="expert counts, e.g. METALLURGY=2 (bonus x1.0306..1.284 for 1..5)")
|
||||||
ap.add_argument("--hq", action="store_true", help="corp HQ bonus x1.1")
|
ap.add_argument("--hq", action="store_true", help="corp HQ bonus x1.1")
|
||||||
@@ -256,10 +257,11 @@ def main():
|
|||||||
import json
|
import json
|
||||||
Path(a.json).write_text(json.dumps(rows))
|
Path(a.json).write_text(json.dumps(rows))
|
||||||
print(f"# {a.cx} tier<={a.tier or 'any'} cogc={a.cogc or '-'} faction={faction or '-'} ({pu}/{pt} permits) min-n>={a.min_n} sorted by {a.sort}")
|
print(f"# {a.cx} tier<={a.tier or 'any'} cogc={a.cogc or '-'} faction={faction or '-'} ({pu}/{pt} permits) min-n>={a.min_n} sorted by {a.sort}")
|
||||||
print("# ROI/day is for OUR size (--own buildings, default 1) incl. our own price impact; market = buildings the market could absorb (--min-n filters on it, nothing else). Net of freight. Patient asks near VWAP, inputs ask-walked; all estimates")
|
print("# yld/d is profit/day / capex as a %, for OUR size (--own buildings, default 1) incl. our own price impact; this is NOT a compoundable rate (1/payback, see docs/decisions.md) - pback is the number to actually reason about. market = buildings the market could absorb (--min-n filters on it, nothing else). Net of freight. Patient asks near VWAP, inputs ask-walked; all estimates")
|
||||||
print(f"{'ROI/d':>6} {'own':>3} {'market':>6} {'lim':4} {'profit/d':>11} {'capex':>9} {'eff':>4} {'bld':4} {'staff':5} {'t/d':>5} {'frt/d':>6} {'h':>5} recipe")
|
print(f"{'yld/d':>6} {'pback':>6} {'own':>3} {'market':>6} {'lim':4} {'profit/d':>11} {'capex':>9} {'eff':>4} {'bld':4} {'staff':5} {'t/d':>5} {'frt/d':>6} {'h':>5} recipe")
|
||||||
for r in rows[:a.top]:
|
for r in rows[:a.top]:
|
||||||
print(f"{r['roiN']:6.1f} {r['n']:3d} {r['n_lim']:6.1f} {r['lim']:4} {r['total']:11.0f} {r['capex']:9.0f} {r['eff']*100:4.0f} {r['bld']:4} {r['staff']:5} {r['tons']:5.0f} {r['frt']:6.0f} "
|
pback = f"{100/r['roiN']:6.1f}" if r['roiN'] > 0 else " inf"
|
||||||
|
print(f"{r['roiN']:6.1f} {pback} {r['n']:3d} {r['n_lim']:6.1f} {r['lim']:4} {r['total']:11.0f} {r['capex']:9.0f} {r['eff']*100:4.0f} {r['bld']:4} {r['staff']:5} {r['tons']:5.0f} {r['frt']:6.0f} "
|
||||||
f"{r['h']:5.1f} {r['rec']}{' [thin]' if r['thin'] else ''}")
|
f"{r['h']:5.1f} {r['rec']}{' [thin]' if r['thin'] else ''}")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Fuel/AIC cost for a ship trip FROM EXPLICIT PARAMETERS (jumps, sliders, gateways) - for when
|
||||||
|
you already know the trip's physics breakdown (e.g. from tools/route.py, or copying a known
|
||||||
|
route). If you just want "ship X from A to B, what's it cost", use tools/shiptrip.py instead -
|
||||||
|
it works all of this out for you. SCOPED TO the account's one hull/reactor (blueprint
|
||||||
|
BP-STRT-0000, stock reactor), shared by both ships (AVI-07JFB, AVI-07JFC). See puga/shipping.py's
|
||||||
|
module docstring for exactly what's confirmed vs still open (generalization to a different
|
||||||
|
hull/reactor is untested; gravity vs distance on landing fuel is confounded; v0's meaning is
|
||||||
|
relative to current fuel load, not an absolute unit).
|
||||||
|
|
||||||
|
tools/shipcost.py --v0 0.5 --v1 0.65 --jumps 1 --to ZV-759c # one direct jump to Deimos
|
||||||
|
tools/shipcost.py --v0 1.0 --jumps 2 --charges 1 --to ZV-194a # two-jump route to Nike
|
||||||
|
tools/shipcost.py --v0 1.0 --gateways 3 --lock-fee 6000:AIC --lock-fee 6000:AIC --lock-fee 4000:CIS # Benten-style - fees read off the live APEX LOCK segment, not formulaic/lookupable
|
||||||
|
"""
|
||||||
|
import argparse, sys
|
||||||
|
from pathlib import Path
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
from puga import config, market, shipping
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument("--v0", type=float, default=1.0, help="fuel-usage slider, 0..1 (relative to current STL tank level, not absolute)")
|
||||||
|
ap.add_argument("--v1", type=float, default=1.0, help="reactor-usage slider, 0..1")
|
||||||
|
ap.add_argument("--jumps", type=int, default=0, help="number of direct FTL jumps (JMP segments)")
|
||||||
|
ap.add_argument("--charges", type=int, default=0, help="number of FTL recharges (CHRG) between consecutive jumps")
|
||||||
|
ap.add_argument("--cruise-legs", type=int, default=2, help="number of STL cruise legs (DEP+APP=2 for a simple direct route)")
|
||||||
|
ap.add_argument("--gateways", type=int, default=0, help="number of gateway hops (each: free GTW + a LOCK fee you supply)")
|
||||||
|
ap.add_argument("--lock-fee", action="append", default=[], help="AMOUNT:CURRENCY per gateway hop, repeatable, matched in order to --gateways - read the fee off the live APEX LOCK segment, there's no API/formula for it")
|
||||||
|
ap.add_argument("--to", help="destination planet natural id, for a looked-up (not predicted) landing fuel cost")
|
||||||
|
ap.add_argument("--cx", default=config.DEFAULT_CX)
|
||||||
|
a = ap.parse_args()
|
||||||
|
|
||||||
|
if a.gateways and len(a.lock_fee) != a.gateways:
|
||||||
|
print(f"warning: {a.gateways} gateways but {len(a.lock_fee)} --lock-fee given - fees you didn't supply are unknown, not zero", file=sys.stderr)
|
||||||
|
lock_fees = [(float(amt), cur) for amt, cur in (lf.split(":") for lf in a.lock_fee)]
|
||||||
|
|
||||||
|
result = shipping.trip_fuel(a.v0, a.v1, a.jumps, a.charges, a.cruise_legs, a.to, lock_fees)
|
||||||
|
if a.to and result["landing_fuel_included"] is None:
|
||||||
|
print(f"note: landing fuel for {a.to} hasn't been measured - not included in total, see puga/shipping.py LANDING_FUEL", file=sys.stderr)
|
||||||
|
|
||||||
|
snap = market.snapshot()
|
||||||
|
sf_px = (snap.get(("SF", a.cx)) or market.Quote("SF", a.cx)).ask or 0
|
||||||
|
ff_px = (snap.get(("FF", a.cx)) or market.Quote("FF", a.cx)).ask or 0
|
||||||
|
stl, ftl, fees = result["stl_fuel"], result["ftl_fuel"], result["lock_fees"]
|
||||||
|
|
||||||
|
lnd = result["landing_fuel_included"]
|
||||||
|
print(f"jumps {a.jumps} charges {a.charges} cruise legs {a.cruise_legs}" + (f" landing +{lnd:.0f} STL" if lnd else ""))
|
||||||
|
print(f"STL fuel: {stl:.1f} units -> {stl*sf_px:,.0f} AIC")
|
||||||
|
print(f"FTL fuel: {ftl:.1f} units -> {ftl*ff_px:,.0f} AIC")
|
||||||
|
if fees:
|
||||||
|
print("Gateway LOCK fees: " + ", ".join(f"{amt:,.0f} {cur}" for amt, cur in fees))
|
||||||
|
total_aic_fuel = stl * sf_px + ftl * ff_px
|
||||||
|
aic_fees = sum(amt for amt, cur in fees if cur == "AIC")
|
||||||
|
print(f"\nTotal (fuel, AIC-denominated fees only): {total_aic_fuel + aic_fees:,.0f} AIC" + (" + non-AIC fees above" if any(cur != "AIC" for _, cur in fees) else ""))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Simplest possible ship-trip cost: give it a ship, a start and a stop, done - it works out
|
||||||
|
jumps/charges/sliders/landing fuel itself. For when you don't know (and shouldn't need to know)
|
||||||
|
the physics breakdown - if you already have jump counts/slider values/gateway fees in hand, use
|
||||||
|
the lower-level tools/shipcost.py instead.
|
||||||
|
|
||||||
|
tools/shiptrip.py AVI-07JFB ZV-307 ZV-759c # Antares -> Deimos
|
||||||
|
tools/shiptrip.py AVI-07JFC "Antares Station" Nike # names/planets/systems all work
|
||||||
|
|
||||||
|
Defaults to max sliders (v0=v1=1.0, fastest) since that's the common case; pass --v0/--v1 to
|
||||||
|
model a slower/cheaper trip. Covers direct-jump routes (puga/route.py's FTL jump graph) and the
|
||||||
|
handful of gateway chains with a measured LOCK fee (puga.shipping.KNOWN_GATEWAY_ROUTES) - for
|
||||||
|
any other gateway route, the LOCK fee genuinely cannot be looked up (no FIO/PRUNplanner endpoint
|
||||||
|
has it), and this tool tells you exactly where to read it live and what to run afterward.
|
||||||
|
"""
|
||||||
|
import argparse, math, sys
|
||||||
|
from pathlib import Path
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
from puga import config, fio, market, shipping
|
||||||
|
|
||||||
|
|
||||||
|
def check_ship(reg: str):
|
||||||
|
"""Warn (don't fail) if the given ship's live specs don't match what this model is
|
||||||
|
calibrated against - see shipping.CALIBRATED_SPEC."""
|
||||||
|
try:
|
||||||
|
ships = fio.own(f"/ship/ships/{fio.me()}")
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
ship = next((s for s in ships if s.get("Registration") == reg), None)
|
||||||
|
if ship is None:
|
||||||
|
print(f"warning: {reg!r} isn't a ship on this account (known: "
|
||||||
|
+ ", ".join(s.get("Registration", "?") for s in ships) + ") - proceeding anyway", file=sys.stderr)
|
||||||
|
return None
|
||||||
|
spec = shipping.CALIBRATED_SPEC
|
||||||
|
|
||||||
|
def differs(k, v):
|
||||||
|
return v != spec[k] if isinstance(spec[k], str) else not math.isclose(v or 0, spec[k], rel_tol=1e-6)
|
||||||
|
|
||||||
|
mismatches = [k for k, v in {"blueprint": ship.get("BlueprintNaturalId"), "acceleration": ship.get("Acceleration"),
|
||||||
|
"thrust": ship.get("Thrust"), "reactor_power": ship.get("ReactorPower"),
|
||||||
|
"emitter_power": ship.get("EmitterPower")}.items()
|
||||||
|
if differs(k, v)]
|
||||||
|
if mismatches:
|
||||||
|
print(f"warning: {reg} differs from the calibrated hull/reactor on {', '.join(mismatches)} - "
|
||||||
|
f"this model (puga/shipping.py) has NOT been validated for this ship, numbers may be wrong", file=sys.stderr)
|
||||||
|
return ship
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument("ship", help="ship registration, e.g. AVI-07JFB")
|
||||||
|
ap.add_argument("src", help="start: planet natural id, system natural id, or name")
|
||||||
|
ap.add_argument("dst", help="stop: planet natural id, system natural id, or name")
|
||||||
|
ap.add_argument("--v0", type=float, default=1.0, help="fuel-usage slider, 0..1 (default 1.0 = fastest)")
|
||||||
|
ap.add_argument("--v1", type=float, default=1.0, help="reactor-usage slider, 0..1 (default 1.0 = fastest)")
|
||||||
|
ap.add_argument("--cx", default=config.DEFAULT_CX)
|
||||||
|
a = ap.parse_args()
|
||||||
|
|
||||||
|
check_ship(a.ship)
|
||||||
|
|
||||||
|
snap = market.snapshot()
|
||||||
|
sf_px = (snap.get(("SF", a.cx)) or market.Quote("SF", a.cx)).ask or 0
|
||||||
|
ff_px = (snap.get(("FF", a.cx)) or market.Quote("FF", a.cx)).ask or 0
|
||||||
|
|
||||||
|
result = shipping.leg_cost(a.src, a.dst, sf_px, ff_px, a.v0, a.v1)
|
||||||
|
if result is None:
|
||||||
|
sys.exit(f"no priceable route between {a.src} and {a.dst} - not a direct-jump route, and not a measured "
|
||||||
|
f"gateway chain (puga.shipping.KNOWN_GATEWAY_ROUTES). The LOCK fee can't be looked up (no "
|
||||||
|
f"FIO/PRUNplanner endpoint has it) - open the Ship Flight Control screen in APEX for this exact "
|
||||||
|
f"route, read each LOCK segment's fee, then run:\n"
|
||||||
|
f" tools/shipcost.py --v0 {a.v0} --gateways N --lock-fee AMOUNT:CURRENCY [--lock-fee ...]")
|
||||||
|
|
||||||
|
lnd = result["landing_fuel_included"]
|
||||||
|
print(f"{a.src} -> {a.dst}" + (" (landing fuel not measured for this destination - not included)" if lnd is None else ""))
|
||||||
|
print(f"STL fuel: {result['stl_fuel']:.1f} units -> {result['stl_fuel']*sf_px:,.0f} AIC")
|
||||||
|
print(f"FTL fuel: {result['ftl_fuel']:.1f} units -> {result['ftl_fuel']*ff_px:,.0f} AIC")
|
||||||
|
if result["non_aic_fees"]:
|
||||||
|
print("Gateway LOCK fees (non-AIC): " + ", ".join(f"{amt:,.0f} {cur}" for amt, cur in result["non_aic_fees"]))
|
||||||
|
print(f"\nTotal (AIC): {result['aic']:,.0f}" + (" + non-AIC fees above" if result["non_aic_fees"] else ""))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+1
-1
@@ -70,7 +70,7 @@ def main():
|
|||||||
print(f"{plan['plan_name']} {plan['planet_natural_id']} COGC {plan.get('plan_cogc')} prices: {a.cx} {a.basis}")
|
print(f"{plan['plan_name']} {plan['planet_natural_id']} COGC {plan.get('plan_cogc')} prices: {a.cx} {a.basis}")
|
||||||
print(f"Area {r['area']:.0f}/500 Profit/day {r['profit']:,.0f} gross {r['gross']:,.0f} degradation {r['degradation']:,.0f} plan cost {r['plan_cost']:,.0f} ROI {r['roi_days'] and round(r['roi_days'], 2)} d")
|
print(f"Area {r['area']:.0f}/500 Profit/day {r['profit']:,.0f} gross {r['gross']:,.0f} degradation {r['degradation']:,.0f} plan cost {r['plan_cost']:,.0f} ROI {r['roi_days'] and round(r['roi_days'], 2)} d")
|
||||||
nc = r["new_capex"]
|
nc = r["new_capex"]
|
||||||
print(f"NEW CAPEX = planned minus already built ({built or 'nothing built'}): {nc:,.0f} -> payback {nc / r['profit']:.2f} d = {100 * r['profit'] / nc:.1f}%/day" if r["profit"] > 0 and nc > 0 else ("NEW CAPEX: nothing to build" if nc <= 0 else "NEW CAPEX: profit <= 0"))
|
print(f"NEW CAPEX = planned minus already built ({built or 'nothing built'}): {nc:,.0f} -> payback {nc / r['profit']:.2f} d" if r["profit"] > 0 and nc > 0 else ("NEW CAPEX: nothing to build" if nc <= 0 else "NEW CAPEX: profit <= 0"))
|
||||||
print("\nWORKFORCE need supply open eff%")
|
print("\nWORKFORCE need supply open eff%")
|
||||||
for t, w in r["workforce"].items():
|
for t, w in r["workforce"].items():
|
||||||
if w["need"] or w["supply"]:
|
if w["need"] or w["supply"]:
|
||||||
|
|||||||
+44
-3
@@ -14,7 +14,7 @@ from collections import Counter
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import yaml
|
import yaml
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
from puga import config, fio, market, prunplanner as pp
|
from puga import config, contracts, fio, market, prunplanner as pp, shipping
|
||||||
from puga.simulate import simulate
|
from puga.simulate import simulate
|
||||||
|
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||||
@@ -88,6 +88,40 @@ def reclaim_value(ticker: str, qty: int, built_count: int, cx: str):
|
|||||||
return {"value": value, "items": items}
|
return {"value": value, "items": items}
|
||||||
|
|
||||||
|
|
||||||
|
def trip_tonnage(flows: dict, mats: dict):
|
||||||
|
"""Total t/m3 the base needs to haul IN (net importers) and ship OUT (net exporters) per day -
|
||||||
|
same accounting scan.py already uses for its own trip-cost estimate (max of the four, since
|
||||||
|
imports and exports share the same round trips)."""
|
||||||
|
w_in = w_out = v_in = v_out = 0.0
|
||||||
|
for t, f in flows.items():
|
||||||
|
net = f["inp"] - f["out"]
|
||||||
|
m = mats.get(t)
|
||||||
|
if not m or abs(net) < 1e-6:
|
||||||
|
continue
|
||||||
|
if net > 0:
|
||||||
|
w_in += net * m["Weight"]; v_in += net * m["Volume"]
|
||||||
|
else:
|
||||||
|
w_out += -net * m["Weight"]; v_out += -net * m["Volume"]
|
||||||
|
return w_in, w_out, v_in, v_out
|
||||||
|
|
||||||
|
|
||||||
|
def marginal_freight(r_b, r_a, planet_id, cx, sf_price, ff_price, mats):
|
||||||
|
"""AIC/day freight for the EXTRA trips this addition requires - not the base's whole freight
|
||||||
|
bill. If the addition's materials fit in slack the base's existing traffic already has (the
|
||||||
|
common case for a small addition), this comes out to ~0: real freight cost only kicks in once
|
||||||
|
net t/m3 crosses into needing another round trip. Returns (freight_aic_per_day, note)."""
|
||||||
|
origin = shipping.cx_system(cx)
|
||||||
|
if origin is None:
|
||||||
|
return 0.0, f"no station found for CX {cx!r} - freight not modelled"
|
||||||
|
rt = shipping.round_trip_cost(origin, planet_id, sf_price, ff_price)
|
||||||
|
if rt is None:
|
||||||
|
return 0.0, "no priceable route (gateway without a measured LOCK fee?) - freight not modelled"
|
||||||
|
trips_b = max(trip_tonnage(r_b["flows"], mats)) / contracts.SHIP_CARGO
|
||||||
|
trips_a = max(trip_tonnage(r_a["flows"], mats)) / contracts.SHIP_CARGO
|
||||||
|
extra_trips = trips_a - trips_b
|
||||||
|
return extra_trips * rt, f"{extra_trips:+.3f} extra round trips/day x {rt:,.0f} AIC/trip"
|
||||||
|
|
||||||
|
|
||||||
def run(spec, recipes, blds, price, faction, perm, built):
|
def run(spec, recipes, blds, price, faction, perm, built):
|
||||||
plan = plan_push.build_payload(spec, recipes, {b["building_ticker"] for b in blds})
|
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)
|
planet = pp._g(f"/data/planet/{plan['planet_natural_id']}/", 3600)
|
||||||
@@ -151,6 +185,12 @@ def main():
|
|||||||
d_profit = r_a["profit"] - r_b["profit"]
|
d_profit = r_a["profit"] - r_b["profit"]
|
||||||
d_capex = r_a["new_capex"] - r_b["new_capex"]
|
d_capex = r_a["new_capex"] - r_b["new_capex"]
|
||||||
|
|
||||||
|
mats = {m["Ticker"]: m for m in fio.materials()}
|
||||||
|
sf_px = (snap.get(("SF", a.cx)) or market.Quote("SF", a.cx)).ask or 0
|
||||||
|
ff_px = (snap.get(("FF", a.cx)) or market.Quote("FF", a.cx)).ask or 0
|
||||||
|
freight, freight_note = marginal_freight(r_b, r_a, planet_id, a.cx, sf_px, ff_px, mats)
|
||||||
|
d_profit -= freight
|
||||||
|
|
||||||
before_counts = Counter(b["building"] for b in before_spec.get("buildings", []) for _ in range(b["amount"]))
|
before_counts = Counter(b["building"] for b in before_spec.get("buildings", []) for _ in range(b["amount"]))
|
||||||
after_counts = Counter(b["building"] for b in after_spec.get("buildings", []) for _ in range(b["amount"]))
|
after_counts = Counter(b["building"] for b in after_spec.get("buildings", []) for _ in range(b["amount"]))
|
||||||
reclaim_total = 0.0
|
reclaim_total = 0.0
|
||||||
@@ -166,8 +206,9 @@ def main():
|
|||||||
|
|
||||||
print(f"BEFORE profit/day {r_b['profit']:,.0f} new_capex {r_b['new_capex']:,.0f}")
|
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"AFTER profit/day {r_a['profit']:,.0f} new_capex {r_a['new_capex']:,.0f}")
|
||||||
|
print(f"FREIGHT {freight:+,.0f} AIC/day marginal ({freight_note})")
|
||||||
if reclaim_lines:
|
if reclaim_lines:
|
||||||
print(f"\nRECLAIMED MATERIALS (demolishing what's removed, sell value, real FIO data):")
|
print("\nRECLAIMED MATERIALS (demolishing what's removed, sell value, real FIO data):")
|
||||||
for line in reclaim_lines:
|
for line in reclaim_lines:
|
||||||
print(line)
|
print(line)
|
||||||
print(f" total: {reclaim_total:,.0f} AIC")
|
print(f" total: {reclaim_total:,.0f} AIC")
|
||||||
@@ -175,7 +216,7 @@ def main():
|
|||||||
net_label = f" net cash GAINED {-net_capex:,.0f}" if net_capex < 0 and reclaim_total else (f" net new capex {net_capex:,.0f}" if reclaim_total else "")
|
net_label = f" net cash GAINED {-net_capex:,.0f}" if net_capex < 0 and reclaim_total else (f" net new capex {net_capex:,.0f}" if reclaim_total else "")
|
||||||
print(f"\nMARGINAL profit/day {d_profit:,.0f} new_capex {d_capex:,.0f}" + net_label, end="")
|
print(f"\nMARGINAL profit/day {d_profit:,.0f} new_capex {d_capex:,.0f}" + net_label, end="")
|
||||||
if net_capex > 0 and d_profit > 0:
|
if net_capex > 0 and d_profit > 0:
|
||||||
print(f" ROI/day {100*d_profit/net_capex:.2f}% payback {net_capex/d_profit:.1f} d")
|
print(f" payback {net_capex/d_profit:.1f} d (simple, non-compounding - a one-time capex paying itself off; not a reinvestable rate, see docs/decisions.md)")
|
||||||
elif net_capex <= 0 and d_profit > 0:
|
elif net_capex <= 0 and d_profit > 0:
|
||||||
print(" (no net new capex after reclaim)" if reclaim_total else " (no new capex)")
|
print(" (no net new capex after reclaim)" if reclaim_total else " (no new capex)")
|
||||||
else:
|
else:
|
||||||
|
|||||||
Reference in New Issue
Block a user