supply.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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 consumption in planet.net_consumption:
  40. ticker = consumption['MaterialTicker']
  41. vol_per_day += materials[ticker]['Volume'] * consumption['net_consumption']
  42. weight_per_day += materials[ticker]['Weight'] * consumption['net_consumption']
  43. days = planet.inventory.get(ticker, 0) / consumption['net_consumption']
  44. if days < target_days:
  45. target_days = days
  46. print(planet.name, f'consumes {vol_per_day:.1f}㎥, {weight_per_day:.1f}t per day')
  47. optimal: dict[str, dict[str, int]] = None # pyright: ignore[reportAssignmentType]
  48. total_weight_used: float = None # pyright: ignore[reportAssignmentType]
  49. total_volume_used: float = None # pyright: ignore[reportAssignmentType]
  50. target_days = round(target_days + 0.05, 1)
  51. load_more = True
  52. while load_more:
  53. buys: dict[str, dict[str, int]] = {}
  54. iteration_weight = iteration_volume = 0
  55. for planet in planets:
  56. buy = planet.supply_for_days(target_days)
  57. weight_used, volume_used = shipping_used(materials, config.supply_config(planet.name).ignore_materials, buy)
  58. iteration_weight += weight_used
  59. iteration_volume += volume_used
  60. if iteration_weight > args.weight or iteration_volume > args.volume:
  61. load_more = False
  62. break
  63. buys[planet.name] = buy
  64. if load_more:
  65. optimal = buys
  66. total_weight_used = iteration_weight
  67. total_volume_used = iteration_volume
  68. target_days += 0.1
  69. print('supply for', round(target_days, 1), 'days,', end=' ')
  70. print(f'consuming {round(total_weight_used, 1)}t and {round(total_volume_used, 1)}㎥') # pyright: ignore[reportPossiblyUnboundVariable]
  71. raw_prices: typing.Mapping[str, market.RawPrice] = {p['MaterialTicker']: p
  72. for p in cache.get('https://refined-prun.github.io/refined-prices/all.json') if p['ExchangeCode'] == 'IC1'}
  73. total_cost = 0
  74. for planet in planets:
  75. print('\n' + cyan(planet.name))
  76. supply_config = config.supply_config(planet.name)
  77. for consumption in planet.net_consumption:
  78. ticker = consumption['MaterialTicker']
  79. avail = planet.inventory.get(ticker, 0)
  80. daily_consumption = consumption['net_consumption']
  81. days = avail / daily_consumption
  82. print(f'{ticker:>3}: {avail:5d} ({daily_consumption:8.2f}/d) {days:4.1f} d', end='')
  83. if need := optimal[planet.name].get(ticker): # pyright: ignore[reportOptionalMemberAccess]
  84. if ticker in supply_config.ignore_materials:
  85. print(f' | {need:5.0f} (ignored)')
  86. else:
  87. cost = raw_prices[ticker]['Ask'] * need
  88. total_cost += cost
  89. print(f' | {need:5.0f} (${cost:6.0f})')
  90. else:
  91. print()
  92. print(f'\ntotal cost: {total_cost:,}')
  93. combined_buy: dict[str, int] = collections.defaultdict(int)
  94. for planet_name, buy in optimal.items():
  95. supply_config = config.supply_config(planet_name)
  96. for ticker, amount in buy.items():
  97. if ticker not in supply_config.ignore_materials:
  98. combined_buy[ticker] += amount
  99. print(cyan('\nbuy:\n') + json.dumps({
  100. 'actions': [
  101. {'name': 'BuyItems', 'type': 'CX Buy', 'group': 'A1', 'exchange': 'IC1',
  102. 'priceLimits': {}, 'buyPartial': False, 'useCXInv': True},
  103. {'type': 'MTRA', 'name': 'TransferAction', 'group': 'A1',
  104. 'origin': 'Hortus Station Warehouse', 'dest': 'Configure on Execution'},
  105. ],
  106. 'global': {'name': 'supply ' + ' '.join(args.planets)},
  107. 'groups': [{
  108. 'type': 'Manual', 'name': 'A1', 'materials': {mat: amount for mat, amount in combined_buy.items()}
  109. }],
  110. }))
  111. for planet in planets:
  112. buy = optimal[planet.name]
  113. print(cyan(f'unload {planet.name}:\n') + json.dumps({
  114. 'actions': [
  115. {'type': 'MTRA', 'name': 'TransferAction', 'group': 'A1',
  116. 'origin': 'Configure on Execution', 'dest': planet.name + ' Base'},
  117. ],
  118. 'global': {'name': 'unload ' + planet.name},
  119. 'groups': [{
  120. 'type': 'Manual', 'name': 'A1', 'materials': {mat: amount for mat, amount in buy.items()}
  121. }],
  122. }))
  123. def get_fio_burn(planet_names: typing.Sequence[str]) -> typing.Iterator[FIOBurn]:
  124. planets: list[FIOBurn] = cache.get('https://rest.fnar.net/fioweb/burn/user/' + config.username,
  125. headers={'Authorization': config.fio_api_key})
  126. for name in planet_names:
  127. name = name.casefold()
  128. for planet_data in planets:
  129. if name in (planet_data['PlanetName'].casefold(), planet_data['PlanetNaturalId'].casefold()):
  130. assert planet_data['Error'] is None
  131. yield planet_data
  132. break
  133. else:
  134. raise ValueError(name + ' not found')
  135. def shipping_used(materials: dict[str, Material], ignore: typing.Collection[str], counts: dict[str, int]) -> tuple[float, float]:
  136. weight = volume = 0
  137. for ticker, amount in counts.items():
  138. if ticker in ignore:
  139. continue
  140. weight += amount * materials[ticker]['Weight']
  141. volume += amount * materials[ticker]['Volume']
  142. return weight, volume
  143. def cyan(text: str) -> str:
  144. return '\033[36m' + text + '\033[0m'
  145. class FIOBurn(typing.TypedDict):
  146. PlanetName: str
  147. PlanetNaturalId: str
  148. Error: typing.Any
  149. OrderConsumption: list[Amount]
  150. WorkforceConsumption: list[Amount]
  151. Inventory: list[market.StorageItem]
  152. OrderProduction: list[Amount]
  153. @dataclasses.dataclass(init=False, eq=False, slots=True)
  154. class Planet:
  155. name: str
  156. inventory: dict[str, int]
  157. net_consumption: typing.Sequence[Amount]
  158. def __init__(self, fio_burn: FIOBurn) -> None:
  159. self.name = fio_burn['PlanetName'] or fio_burn['PlanetNaturalId']
  160. self.inventory = {item['MaterialTicker']: item['MaterialAmount'] for item in fio_burn['Inventory']}
  161. producing = {item['MaterialTicker']: item for item in fio_burn['OrderProduction']}
  162. self.net_consumption = []
  163. for c in fio_burn['OrderConsumption'] + fio_burn['WorkforceConsumption']:
  164. net = c['DailyAmount']
  165. if production := producing.get(c['MaterialTicker']):
  166. net -= production['DailyAmount']
  167. if net < 0:
  168. continue
  169. c['net_consumption'] = net
  170. self.net_consumption.append(c)
  171. def supply_for_days(self, target_days: float) -> dict[str, int]:
  172. buy: dict[str, int] = {}
  173. for consumption in self.net_consumption:
  174. ticker = consumption['MaterialTicker']
  175. avail = self.inventory.get(ticker, 0)
  176. daily_consumption = consumption['net_consumption']
  177. days = avail / daily_consumption
  178. if days < target_days:
  179. buy[ticker] = math.ceil((target_days - days) * daily_consumption)
  180. return buy
  181. class Amount(typing.TypedDict):
  182. MaterialTicker: str
  183. DailyAmount: float
  184. net_consumption: float
  185. class Material(typing.TypedDict):
  186. Ticker: str
  187. Weight: float
  188. Volume: float
  189. if __name__ == '__main__':
  190. main()