supply.py 10 KB

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