StatCalc / StatCalcAsync API¶
StatCalc and StatCalcAsync perform local stat and Galactic Power (GP)
calculations for game units without requiring an external swgoh-stats service.
Quick Start¶
from swgoh_comlink import SwgohComlink, StatCalc
comlink = SwgohComlink()
calc = StatCalc() # fetches game data from GitHub on init
player = comlink.get_player(allycode=245866537)
calc.calc_roster_stats(player["rosterUnit"])
# Each unit in rosterUnit now has "stats" and "gp" keys
for unit in player["rosterUnit"]:
print(unit.get("stats"), unit.get("gp"))
Initialization¶
# Default — fetches latest game data from GitHub
calc = StatCalc()
# Offline — supply pre-loaded game data
calc = StatCalc(game_data=my_game_data_dict)
# Fetch from a mirror or fork, and check the bytes against a known digest
calc = StatCalc(game_data_url="https://mirror.example/gameData.json", expected_sha256="<64 hex digits>")
# Async — same options on the factory
calc = await StatCalcAsync.create(expected_sha256="<64 hex digits>")
The game_data parameter accepts the JSON payload from the
swgoh-utils/gamedata repository.
When game_data is omitted, the calculator downloads the latest gameData.json
from the main branch of that repository over httpx (sync and async alike).
The download is capped at 64 MiB, counted after any gzip decoding; a larger body
raises SwgohComlinkValueError. The keyword-only options apply only to that download:
game_data_urlfetches from another URL instead of the default.expected_sha256hashes the downloaded bytes before parsing and raisesSwgohComlinkValueErrorif they do not match.
Passing either option together with game_data raises SwgohComlinkValueError.
Usage Examples¶
Calculate stats for a single character¶
unit = {
"defId": "BOSSK",
"rarity": 7,
"level": 85,
"gear": 13,
"equipped": [],
"skills": [],
}
calc.calc_char_stats(unit)
print(unit["stats"]) # base, mods, and gear stats
print(unit["gp"]) # galactic power
Calculate stats for a full roster¶
Characters are processed first, then ships (which depend on their crew stats). A ship whose crew
is not fully present in the roster is skipped (no stats or gp key) with a logged warning,
and processing continues with the remaining ships.
Calculate stats for one or more players¶
# Single player dict
player = comlink.get_player(allycode=245866537)
calc.calc_player_stats(player)
# List of player dicts
players = [
comlink.get_player(allycode=245866537),
comlink.get_player(allycode=123456789),
]
calc.calc_player_stats(players)
Calculate GP only¶
Apply a datacron¶
A player owns many datacrons and picks one per squad when they deploy, so there is no such thing as "this unit's stats with datacrons", only "this unit's stats with this datacron". Name the one you mean:
player = comlink.get_player(allycode=245866537)
datacron_id = player["datacron"][0]["id"]
calc.calc_player_stats(player, datacron_id=datacron_id)
unit = player["rosterUnit"][0]
print(unit["stats"]["final"]) # unchanged by the datacron
print(unit["stats"]["datacron"]) # what the datacron adds to this unit
calc_player_stats takes a datacron id and looks it up in the player's own
datacron collection, raising KeyError if the player does not own it.
calc_roster_stats and calc_char_stats take the datacron object, having
no player to look it up in:
datacron = next(d for d in player["datacron"] if d["id"] == datacron_id)
calc.calc_char_stats(unit, datacron)
Leave the argument out and nothing changes: no datacron key appears and the
output is the same as before.
Combining the buckets¶
The datacron bucket is deliberately not summed into final. Add the two
to get a unit's stats as it would fight with that datacron:
stats = unit["stats"]
combined = {name: value + stats["datacron"].get(name, 0) for name, value in stats["final"].items()}
That addition is correct for every stat, including ones reported as percentages such as Armor and Resistance. Those are converted non-linearly, so a raw percentage could not simply be added to them; the bucket instead holds the amount the datacron actually adds on top of everything else.
Worth knowing:
- Ships never get a bucket. Datacrons are a squad mechanic and no game mode applies one to a fleet battle, so ship stats are unaffected.
- Affixes are gated per unit. Each affix requires a gear tier and a relic
tier, so the same datacron adds different amounts to different units. Relic
tiers in the game data count the locked and unlocked states as their first
two values, so a
requiredRelicTierof 5 means relic 3 as a player counts it. - Percentages apply as the datacron card shows them. A stat's affix percentages are summed, rounded to two decimals, and then applied to the unit's base plus gear stats. Mods do not count toward that total.
Async Usage (StatCalcAsync)¶
Use the async create() factory to fetch game data without blocking the event
loop, and the acalc_* methods to calculate stats. Each one runs the matching
calc_* method in a worker thread (asyncio.to_thread), so a large roster or
guild does not stall the loop (for example a Discord bot's gateway heartbeat).
| Async method | Runs |
|---|---|
await calc.acalc_char_stats(unit, datacron=None) |
calc_char_stats |
await calc.acalc_ship_stats(ship, crew) |
calc_ship_stats |
await calc.acalc_roster_stats(units, datacron=None) |
calc_roster_stats |
await calc.acalc_player_stats(players, datacron_id=None) |
calc_player_stats |
from swgoh_comlink import SwgohComlinkAsync, StatCalcAsync
async with SwgohComlinkAsync() as comlink:
calc = await StatCalcAsync.create() # async fetch from GitHub
player = await comlink.get_player(allycode=245866537)
await calc.acalc_player_stats(player)
The inherited synchronous calc_* methods still work, but they block the event
loop while they run.
The game data tables are only read during calculation, so concurrent acalc_*
calls on one instance are safe. Do not call set_game_data() while a
calculation is running, and do not touch a unit or player while its acalc_*
call is in progress: the worker thread updates it in place. Cancelling the
awaiting task does not stop the worker thread.
With pre-loaded data (no async fetch):
GameDataBuilder / GameDataBuilderAsync¶
Instead of fetching game data from a static GitHub file, you can build it dynamically from a running Comlink service.
Sync¶
from swgoh_comlink import SwgohComlink, StatCalc, GameDataBuilder
comlink = SwgohComlink()
game_data = GameDataBuilder(comlink).build()
calc = StatCalc(game_data=game_data)
Async¶
from swgoh_comlink import SwgohComlinkAsync, StatCalcAsync, GameDataBuilderAsync
async with SwgohComlinkAsync() as comlink:
game_data = await GameDataBuilderAsync(comlink).build()
calc = StatCalcAsync(game_data=game_data)
The builder fetches only the collections required for stat calculation
(units, skills, equipment, tables, statProgression, statModSets,
relicTierDefinitions, categories) in a single get_game_data() call and
transforms them into the dict format expected by StatCalc.set_game_data().
API Reference¶
StatCalc¶
StatCalc
¶
SWGOH stat calculator
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
game_data
|
dict[str, Any] | None
|
Optional preloaded game data payload. If omitted, the calculator fetches the latest payload from the swgoh-utils GitHub game data repository. |
None
|
game_data_url
|
str | None
|
Keyword-only. URL to fetch the game data from instead
of the latest |
None
|
expected_sha256
|
str | None
|
Keyword-only. Hex SHA-256 digest the fetched body must match; checked before parsing. Only used when game_data is omitted. |
None
|
__init__(game_data=None, *, game_data_url=None, expected_sha256=None)
¶
Initialize a calculator instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
game_data
|
dict[str, Any] | None
|
Optional game data payload to load immediately. |
None
|
game_data_url
|
str | None
|
URL to fetch the game data from when game_data is
omitted. Defaults to the latest |
None
|
expected_sha256
|
str | None
|
Hex SHA-256 digest the fetched body must match. |
None
|
Raises:
| Type | Description |
|---|---|
SwgohComlinkValueError
|
expected_sha256 is malformed, a fetch option is combined with game_data, the fetched body is larger than 64 MiB, or its digest does not match expected_sha256. |
RuntimeError
|
The game data could not be fetched or parsed. |
calc_char_stats(unit, datacron=None)
¶
Calculate stats and GP for a character unit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unit
|
dict[str, Any]
|
Character object in either normalized ( |
required |
datacron
|
dict[str, Any] | None
|
Optional datacron object, as found in a player's
|
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The input unit with |
calc_ship_stats(unit, crew_member)
¶
Calculate stats and GP for a ship unit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unit
|
dict[str, Any]
|
Ship object in either normalized ( |
required |
crew_member
|
list[dict[str, Any]]
|
Crew member list for the ship. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The input unit with |
calc_roster_stats(units, datacron=None)
¶
Calculate stats for all units in a roster-like payload.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
units
|
Any
|
Either a list of units or a legacy dict keyed by unit id. |
required |
datacron
|
dict[str, Any] | None
|
Optional datacron object to apply to every character, as
in :meth: |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Input object with |
Any
|
whose crew is not fully present in a list-format roster are skipped |
Any
|
(no |
calc_player_stats(players, datacron_id=None)
¶
Calculate stats for one or more player payloads.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
players
|
dict[str, Any] | list[dict[str, Any]]
|
One player object, or a list of player objects, each with a |
required |
datacron_id
|
str | None
|
Optional id of a datacron in each player's own
|
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any] | list[dict[str, Any]]
|
The input object with |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If a dict player is missing a 'rosterUnit' key. |
TypeError
|
If the input object is not a list or dict. |
KeyError
|
If |
calc_char_gp(char)
¶
Calculate GP for a character.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
char
|
dict[str, Any]
|
Character object in normalized or raw format. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Character GP value. |
calc_ship_gp(ship, crew)
¶
Calculate GP for a ship.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ship
|
dict[str, Any]
|
Ship object in normalized or raw format. |
required |
crew
|
list[dict[str, Any]]
|
Crew member list corresponding to the ship. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Ship GP value. |
StatCalcAsync¶
StatCalcAsync
¶
Bases: StatCalc
Async-capable SWGOH stat calculator.
Game data is fetched with httpx.AsyncClient instead of the blocking
httpx.Client. Both apply the same size cap and SHA-256 check.
Stat calculation is CPU-bound: a full roster takes tens of milliseconds.
Use the acalc_* methods (:meth:acalc_char_stats,
:meth:acalc_ship_stats, :meth:acalc_roster_stats,
:meth:acalc_player_stats) from async code; they run the matching
calc_* method in a worker thread via :func:asyncio.to_thread, so the
event loop keeps running. The inherited synchronous calc_* methods
still work but block the loop while they run.
The game data tables are only read during calculation, so concurrent
acalc_* calls on one instance are safe. Do not call
:meth:set_game_data while a calculation is running. Each call updates its
input in place from the worker thread: do not read or change that input
until the call returns. Cancelling the awaiting task does not stop the
thread, which still finishes updating the input.
Because __init__ cannot be async, use the :meth:create
classmethod factory when game data needs to be fetched from GitHub:
.. code-block:: python
calc = await StatCalcAsync.create()
If you already have game data loaded, pass it directly:
.. code-block:: python
calc = StatCalcAsync(game_data=my_data)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
game_data
|
dict[str, Any]
|
Game data payload. Required — use :meth: |
required |
__init__(game_data)
¶
Initialize with pre-loaded game data.
Unlike the sync :class:StatCalc, this constructor does not
auto-fetch from GitHub. Use :meth:create for that.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
game_data
|
dict[str, Any]
|
Game data payload containing unit, gear, CR, GP, relic, and mod set tables. |
required |
create(game_data=None, *, game_data_url=None, expected_sha256=None)
async
classmethod
¶
Factory method to create a :class:StatCalcAsync instance.
If game_data is None, the latest payload is fetched
asynchronously from the swgoh-utils GitHub repository.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
game_data
|
dict[str, Any] | None
|
Optional pre-loaded game data payload. |
None
|
game_data_url
|
str | None
|
URL to fetch the game data from when game_data is
omitted. Defaults to the latest |
None
|
expected_sha256
|
str | None
|
Hex SHA-256 digest the fetched body must match. |
None
|
Returns:
| Type | Description |
|---|---|
StatCalcAsync
|
A fully initialized :class: |
Raises:
| Type | Description |
|---|---|
SwgohComlinkValueError
|
expected_sha256 is malformed, a fetch option is combined with game_data, the fetched body is larger than 64 MiB, or its digest does not match expected_sha256. |
RuntimeError
|
The game data could not be fetched or parsed. |
acalc_char_stats(unit, datacron=None)
async
¶
Run :meth:calc_char_stats in a worker thread.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unit
|
dict[str, Any]
|
Character object in either normalized ( |
required |
datacron
|
dict[str, Any] | None
|
Optional datacron object to apply, as in :meth: |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The input unit with |
acalc_ship_stats(unit, crew_member)
async
¶
Run :meth:calc_ship_stats in a worker thread.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unit
|
dict[str, Any]
|
Ship object in either normalized ( |
required |
crew_member
|
list[dict[str, Any]]
|
Crew member list for the ship. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The input unit with |
acalc_roster_stats(units, datacron=None)
async
¶
Run :meth:calc_roster_stats in a worker thread.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
units
|
Any
|
Either a list of units or a legacy dict keyed by unit id. |
required |
datacron
|
dict[str, Any] | None
|
Optional datacron object to apply to every character, as
in :meth: |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Input object with |
acalc_player_stats(players, datacron_id=None)
async
¶
Run :meth:calc_player_stats in a worker thread.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
players
|
dict[str, Any] | list[dict[str, Any]]
|
One player object, or a list of player objects, each with a |
required |
datacron_id
|
str | None
|
Optional id of a datacron in each player's own
|
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any] | list[dict[str, Any]]
|
The input object with |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If a dict player is missing a 'rosterUnit' key. |
TypeError
|
If the input object is not a list or dict. |
KeyError
|
If |
GameDataBuilder¶
GameDataBuilder
¶
Bases: GameDataBuilderBase
Build StatCalc game data from a running Comlink service (sync).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
SwgohComlink
|
An active |
required |
Example::
from swgoh_comlink import SwgohComlink, StatCalc
from swgoh_comlink.StatCalc.data_builder import GameDataBuilder
comlink = SwgohComlink()
game_data = GameDataBuilder(comlink).build()
calc = StatCalc(game_data=game_data)
GameDataBuilderAsync¶
GameDataBuilderAsync
¶
Bases: GameDataBuilderBase
Build StatCalc game data from a running Comlink service (async).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
SwgohComlinkAsync
|
An active |
required |
Example::
from swgoh_comlink import SwgohComlinkAsync, StatCalcAsync
from swgoh_comlink.StatCalc.data_builder import GameDataBuilderAsync
async with SwgohComlinkAsync() as comlink:
game_data = await GameDataBuilderAsync(comlink).build()
calc = StatCalcAsync(game_data=game_data)