supply.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. from __future__ import annotations
  2. import collections
  3. import dataclasses
  4. import json
  5. import math
  6. import typing
  7. import tap
  8. import cache
  9. from config import config
  10. import market
  11. class Args(tap.Tap):
  12. planets: tuple[str, ...]
  13. weight: float
  14. volume: float
  15. include_ship: tuple[str, ...] = ()
  16. def configure(self) -> None:
  17. self.add_argument('planets', nargs='+', metavar='planet') # take planets as positional args instead of flag
  18. def main() -> None:
  19. args = Args().parse_args()
  20. planets = [Planet(fio_burn) for fio_burn in get_fio_burn(args.planets)]
  21. if args.include_ship:
  22. stores: typing.Sequence[market.Storage] = cache.get('https://rest.fnar.net/storage/' + config.username,
  23. headers={'Authorization': config.fio_api_key})
  24. for ship in args.include_ship:
  25. ship_name, planet_name = ship.casefold().split('=')
  26. for store in stores:
  27. if store['Type'] == 'SHIP_STORE' and store['Name'].casefold() == ship_name:
  28. break
  29. else:
  30. raise Exception(f'ship storage {ship_name} not found')
  31. (planet,) = (p for p in planets if p.name.casefold() == planet_name)
  32. for item in store['StorageItems']:
  33. planet.inventory[item['MaterialTicker']] = planet.inventory.get(item['MaterialTicker'], 0) + item['MaterialAmount']
  34. raw_materials: typing.Sequence[Material] = cache.get('https://rest.fnar.net/material/allmaterials')
  35. materials = {mat['Ticker']: mat for mat in raw_materials}
  36. target_days = float('inf')
  37. for planet in planets:
  38. vol_per_day = weight_per_day = 0
  39. for ticker, consumption in planet.net_consumption.items():
  40. vol_per_day += materials[ticker]['Volume'] * consumption
  41. weight_per_day += materials[ticker]['Weight'] * consumption
  42. days = planet.inventory.get(ticker, 0) / consumption
  43. if days < target_days:
  44. target_days = days
  45. print(planet.name, f'consumes {vol_per_day:.1f}㎥, {weight_per_day:.1f}t per day')
  46. optimal: dict[str, dict[str, int]] = None # pyright: ignore[reportAssignmentType]
  47. total_weight_used: float = None # pyright: ignore[reportAssignmentType]
  48. total_volume_used: float = None # pyright: ignore[reportAssignmentType]
  49. target_days = round(target_days + 0.05, 1)
  50. load_more = True
  51. while load_more:
  52. buys: dict[str, dict[str, int]] = {}
  53. iteration_weight = iteration_volume = 0
  54. for planet in planets:
  55. buy = planet.supply_for_days(target_days)
  56. weight_used, volume_used = shipping_used(materials, config.supply_config(planet.name).ignore_materials, buy)
  57. iteration_weight += weight_used
  58. iteration_volume += volume_used
  59. if iteration_weight > args.weight or iteration_volume > args.volume:
  60. load_more = False
  61. break
  62. buys[planet.name] = buy
  63. if load_more:
  64. optimal = buys
  65. total_weight_used = iteration_weight
  66. total_volume_used = iteration_volume
  67. target_days += 0.1
  68. print('supply for', round(target_days, 1), 'days,', end=' ')
  69. print(f'consuming {round(total_weight_used, 1)}t and {round(total_volume_used, 1)}㎥') # pyright: ignore[reportPossiblyUnboundVariable]
  70. raw_prices: typing.Mapping[str, market.RawPrice] = {p['MaterialTicker']: p
  71. for p in cache.get('https://refined-prun.github.io/refined-prices/all.json') if p['ExchangeCode'] == 'IC1'}
  72. warehouse = warehouse_inventory()
  73. from_cx: dict[str, int] = collections.defaultdict(int)
  74. total_cost = 0
  75. for i, planet in enumerate(planets):
  76. print('\n' + cyan(planet.name))
  77. supply_config = config.supply_config(planet.name)
  78. planet_buy = optimal[planet.name]
  79. for ticker, consumption in planet.net_consumption.items():
  80. avail = planet.inventory.get(ticker, 0)
  81. days = avail / consumption
  82. print(f'{ticker:>3}: {avail:5d} ({consumption:8.2f}/d) {days:4.1f} d', end='')
  83. if need := planet_buy.get(ticker): # pyright: ignore[reportOptionalMemberAccess]
  84. if ticker in supply_config.ignore_materials:
  85. print(f' | {need:5.0f} (ignored)')
  86. else:
  87. print(f' | {need:5.0f}', end='')
  88. sources = []
  89. for exporter in planets[:i]:
  90. if ticker in exporter.exporting and (avail := exporter.inventory.get(ticker, 0)):
  91. need -= min(need, avail)
  92. exporter.inventory[ticker] -= max(avail - need, 0)
  93. sources.append(f'{exporter.name}: {avail}')
  94. if need:
  95. from_cx[ticker] += need # count from_cx before subtracting warehouse
  96. if avail := warehouse.get(ticker, 0):
  97. need -= min(need, avail)
  98. warehouse[ticker] -= max(avail - need, 0)
  99. sources.append(f'WH: {avail}')
  100. cost = raw_prices[ticker]['Ask'] * need
  101. print(f' (${cost:6.0f}) ' + ', '.join(sources))
  102. total_cost += cost
  103. else:
  104. print()
  105. print(f'\ntotal cost: {total_cost:,}')
  106. print(cyan('\nload at CX:\n') + json.dumps({
  107. 'actions': [
  108. {'name': 'BuyItems', 'type': 'CX Buy', 'group': 'A1', 'exchange': 'IC1',
  109. 'priceLimits': {}, 'buyPartial': False, 'useCXInv': True},
  110. {'type': 'MTRA', 'name': 'TransferAction', 'group': 'A1',
  111. 'origin': 'Hortus Station Warehouse', 'dest': 'Configure on Execution'},
  112. ],
  113. 'global': {'name': 'supply ' + ' '.join(args.planets)},
  114. 'groups': [{
  115. 'type': 'Manual', 'name': 'A1', 'materials': {mat: amount for mat, amount in from_cx.items()}
  116. }],
  117. }))
  118. for planet in planets:
  119. buy = optimal[planet.name]
  120. print(cyan(f'unload {planet.name}:\n') + json.dumps({
  121. 'actions': [
  122. {'type': 'MTRA', 'name': 'TransferAction', 'group': 'A1',
  123. 'origin': 'Configure on Execution', 'dest': planet.name + ' Base'},
  124. ],
  125. 'global': {'name': 'unload ' + planet.name},
  126. 'groups': [{
  127. 'type': 'Manual', 'name': 'A1', 'materials': {mat: amount for mat, amount in buy.items()}
  128. }],
  129. }))
  130. def get_fio_burn(planet_names: typing.Sequence[str]) -> typing.Iterator[FIOBurn]:
  131. planets: list[FIOBurn] = cache.get('https://rest.fnar.net/fioweb/burn/user/' + config.username,
  132. headers={'Authorization': config.fio_api_key})
  133. for name in planet_names:
  134. name = name.casefold()
  135. for planet_data in planets:
  136. if name in (planet_data['PlanetName'].casefold(), planet_data['PlanetNaturalId'].casefold()):
  137. assert planet_data['Error'] is None
  138. yield planet_data
  139. break
  140. else:
  141. raise ValueError(name + ' not found')
  142. def shipping_used(materials: dict[str, Material], ignore: typing.Collection[str], counts: dict[str, int]) -> tuple[float, float]:
  143. weight = volume = 0
  144. for ticker, amount in counts.items():
  145. if ticker in ignore:
  146. continue
  147. weight += amount * materials[ticker]['Weight']
  148. volume += amount * materials[ticker]['Volume']
  149. return weight, volume
  150. def warehouse_inventory() -> dict[str, int]:
  151. warehouses: typing.Sequence[market.Warehouse] = cache.get('https://rest.fnar.net/sites/warehouses/' + config.username,
  152. headers={'Authorization': config.fio_api_key})
  153. for warehouse in warehouses:
  154. if warehouse['LocationNaturalId'] == 'HRT':
  155. storage: market.Storage = cache.get(f'https://rest.fnar.net/storage/{config.username}/{warehouse["StoreId"]}',
  156. headers={'Authorization': config.fio_api_key})
  157. assert storage['Type'] == 'WAREHOUSE_STORE'
  158. return {item['MaterialTicker']: item['MaterialAmount'] for item in storage['StorageItems']}
  159. raise Exception("couldn't find HRT warehouse")
  160. def cyan(text: str) -> str:
  161. return '\033[36m' + text + '\033[0m'
  162. class FIOBurn(typing.TypedDict):
  163. PlanetName: str
  164. PlanetNaturalId: str
  165. Error: typing.Any
  166. OrderConsumption: list[Amount]
  167. WorkforceConsumption: list[Amount]
  168. Inventory: list[market.StorageItem]
  169. OrderProduction: list[Amount]
  170. class Amount(typing.TypedDict):
  171. MaterialTicker: str
  172. DailyAmount: float
  173. @dataclasses.dataclass(init=False, eq=False, slots=True)
  174. class Planet:
  175. name: str
  176. inventory: dict[str, int]
  177. net_consumption: dict[str, float]
  178. exporting: typing.Set[str]
  179. def __init__(self, fio_burn: FIOBurn) -> None:
  180. self.name = fio_burn['PlanetName'] or fio_burn['PlanetNaturalId']
  181. self.inventory = {item['MaterialTicker']: item['MaterialAmount'] for item in fio_burn['Inventory']}
  182. # producing any amount (including less than consumption)
  183. self.net_consumption = {}
  184. for c in fio_burn['OrderConsumption'] + fio_burn['WorkforceConsumption']:
  185. ticker = c['MaterialTicker']
  186. self.net_consumption[ticker] = self.net_consumption.get(ticker, 0) + c['DailyAmount']
  187. for item in fio_burn['OrderProduction']:
  188. if consumption := self.net_consumption.get(item['MaterialTicker']):
  189. consumption -= item['DailyAmount']
  190. if consumption <= 0:
  191. del self.net_consumption[item['MaterialTicker']]
  192. else:
  193. self.net_consumption[item['MaterialTicker']] = consumption
  194. # producing more than consumption
  195. self.exporting = set()
  196. for item in fio_burn['OrderProduction']:
  197. if item['MaterialTicker'] not in self.net_consumption:
  198. self.exporting.add(item['MaterialTicker'])
  199. def supply_for_days(self, target_days: float) -> dict[str, int]:
  200. buy: dict[str, int] = {}
  201. for ticker, consumption in self.net_consumption.items():
  202. avail = self.inventory.get(ticker, 0)
  203. days = avail / consumption
  204. if days < target_days:
  205. buy[ticker] = math.ceil((target_days - days) * consumption)
  206. return buy
  207. class Material(typing.TypedDict):
  208. Ticker: str
  209. Weight: float
  210. Volume: float
  211. if __name__ == '__main__':
  212. main()