supply.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. from __future__ import annotations
  2. import collections
  3. import dataclasses
  4. import json
  5. import math
  6. import tomllib
  7. import typing
  8. import tap
  9. import cache
  10. class Args(tap.Tap):
  11. planets: tuple[str, ...]
  12. weight: float
  13. volume: float
  14. def configure(self) -> None:
  15. self.add_argument('planets', nargs='+', metavar='planet') # take planets as positional args instead of flag
  16. def main() -> None:
  17. args = Args().parse_args()
  18. planets = [Planet(fio_burn) for fio_burn in get_fio_burn(args.planets)]
  19. raw_materials: typing.Sequence[Material] = cache.get('https://rest.fnar.net/material/allmaterials')
  20. materials = {mat['Ticker']: mat for mat in raw_materials}
  21. target_days = float('inf')
  22. for planet in planets:
  23. vol_per_day = weight_per_day = 0
  24. for consumption in planet.net_consumption:
  25. ticker = consumption['MaterialTicker']
  26. vol_per_day += materials[ticker]['Volume'] * consumption['net_consumption']
  27. weight_per_day += materials[ticker]['Weight'] * consumption['net_consumption']
  28. days = planet.inventory.get(ticker, 0) / consumption['net_consumption']
  29. if days < target_days:
  30. target_days = days
  31. print(planet.name, f'consumes {vol_per_day:.1f}㎥, {weight_per_day:.1f}t per day')
  32. load_more = True
  33. optimal: dict[str, dict[str, int]] = None # pyright: ignore[reportAssignmentType]
  34. target_days = round(target_days + 0.05, 1)
  35. while load_more:
  36. buys: dict[str, dict[str, int]] = {}
  37. total_weight_used = total_volume_used = 0
  38. for planet in planets:
  39. buy, weight_used, volume_used = planet.buy_for_target(materials, target_days)
  40. total_weight_used += weight_used
  41. total_volume_used += volume_used
  42. if total_weight_used > args.weight or total_volume_used > args.volume:
  43. load_more = False
  44. break
  45. buys[planet.name] = buy
  46. if load_more:
  47. optimal = buys
  48. target_days += 0.1
  49. print('supply for', round(target_days, 1), 'days')
  50. for planet in planets:
  51. print('\n' + cyan(planet.name))
  52. for consumption in planet.net_consumption:
  53. ticker = consumption['MaterialTicker']
  54. avail = planet.inventory.get(ticker, 0)
  55. daily_consumption = consumption['net_consumption']
  56. days = avail / daily_consumption
  57. print(f'{ticker:>3}: {avail:5d} ({daily_consumption:8.2f}/d) {days:4.1f} d', end='')
  58. if need := optimal[planet.name].get(ticker): # pyright: ignore[reportOptionalMemberAccess]
  59. print(f' | {need:8.1f}')
  60. else:
  61. print()
  62. combined_buy: dict[str, int] = collections.defaultdict(int)
  63. for buy in optimal.values():
  64. for ticker, amount in buy.items():
  65. combined_buy[ticker] += amount
  66. print(cyan('\nbuy:\n') + json.dumps({
  67. 'actions': [
  68. {'name': 'BuyItems', 'type': 'CX Buy', 'group': 'A1', 'exchange': 'IC1',
  69. 'priceLimits': {}, 'buyPartial': False, 'useCXInv': True},
  70. {'type': 'MTRA', 'name': 'TransferAction', 'group': 'A1',
  71. 'origin': 'Hortus Station Warehouse', 'dest': 'Configure on Execution'},
  72. ],
  73. 'global': {'name': 'supply ' + ' '.join(args.planets)},
  74. 'groups': [{
  75. 'type': 'Manual', 'name': 'A1', 'materials': {mat: amount for mat, amount in combined_buy.items()}
  76. }],
  77. }))
  78. for planet in planets:
  79. buy = optimal[planet.name]
  80. print(cyan(f'unload {planet.name}:\n') + json.dumps({
  81. 'actions': [
  82. {'type': 'MTRA', 'name': 'TransferAction', 'group': 'A1',
  83. 'origin': 'Configure on Execution', 'dest': planet.name + ' Base'},
  84. ],
  85. 'global': {'name': 'unload ' + planet.name},
  86. 'groups': [{
  87. 'type': 'Manual', 'name': 'A1', 'materials': {mat: amount for mat, amount in buy.items()}
  88. }],
  89. }))
  90. def get_fio_burn(planet_names: typing.Sequence[str]) -> typing.Iterator[FIOBurn]:
  91. with open('config.toml', 'rb') as f:
  92. config = tomllib.load(f)
  93. planets: list[FIOBurn] = cache.get('https://rest.fnar.net/fioweb/burn/user/' + config['username'],
  94. headers={'Authorization': config['fio_api_key']})
  95. for name in planet_names:
  96. name = name.casefold()
  97. for planet_data in planets:
  98. if name in (planet_data['PlanetName'].casefold(), planet_data['PlanetNaturalId'].casefold()):
  99. assert planet_data['Error'] is None
  100. yield planet_data
  101. break
  102. else:
  103. raise ValueError(name + ' not found')
  104. def cyan(text: str) -> str:
  105. return '\033[36m' + text + '\033[0m'
  106. class FIOBurn(typing.TypedDict):
  107. PlanetName: str
  108. PlanetNaturalId: str
  109. Error: typing.Any
  110. OrderConsumption: list[Amount]
  111. WorkforceConsumption: list[Amount]
  112. Inventory: list[Inventory]
  113. OrderProduction: list[Amount]
  114. @dataclasses.dataclass(init=False, eq=False, slots=True)
  115. class Planet:
  116. name: str
  117. inventory: dict[str, int]
  118. net_consumption: typing.Sequence[Amount]
  119. def __init__(self, fio_burn: FIOBurn) -> None:
  120. self.name = fio_burn['PlanetName'] or fio_burn['PlanetNaturalId']
  121. self.inventory = {item['MaterialTicker']: item['MaterialAmount'] for item in fio_burn['Inventory']}
  122. producing = {item['MaterialTicker']: item for item in fio_burn['OrderProduction']}
  123. self.net_consumption = []
  124. for c in fio_burn['OrderConsumption'] + fio_burn['WorkforceConsumption']:
  125. net = c['DailyAmount']
  126. if production := producing.get(c['MaterialTicker']):
  127. net -= production['DailyAmount']
  128. if net < 0:
  129. continue
  130. c['net_consumption'] = net
  131. self.net_consumption.append(c)
  132. def buy_for_target(self, materials: dict[str, Material], target_days: float) -> tuple[dict[str, int], float, float]:
  133. weight_used = volume_used = 0
  134. buy: dict[str, int] = {}
  135. for consumption in self.net_consumption:
  136. ticker = consumption['MaterialTicker']
  137. avail = self.inventory.get(ticker, 0)
  138. daily_consumption = consumption['net_consumption']
  139. days = avail / daily_consumption
  140. if days < target_days:
  141. buy[ticker] = math.ceil((target_days - days) * daily_consumption)
  142. weight_used += buy[ticker] * materials[ticker]['Weight']
  143. volume_used += buy[ticker] * materials[ticker]['Volume']
  144. return buy, weight_used, volume_used
  145. class Amount(typing.TypedDict):
  146. MaterialTicker: str
  147. DailyAmount: float
  148. net_consumption: float
  149. class Inventory(typing.TypedDict):
  150. MaterialTicker: str
  151. MaterialAmount: int
  152. class Material(typing.TypedDict):
  153. Ticker: str
  154. Weight: float
  155. Volume: float
  156. if __name__ == '__main__':
  157. main()