supply.py 5.7 KB

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