234 lines
9.6 KiB
Python
234 lines
9.6 KiB
Python
"""Validated, source-backed observations for the compute comparison cards."""
|
|
|
|
from datetime import date
|
|
from typing import Annotated, Literal, Self
|
|
|
|
from app.services.compute_catalog import COUNTRY_PARTICIPANTS, PARTICIPANTS
|
|
from pydantic import BaseModel, ConfigDict, Field, HttpUrl, field_validator, model_validator
|
|
|
|
Year = Annotated[int, Field(strict=True, ge=2000, le=2100)]
|
|
Value = Annotated[float, Field(strict=True, allow_inf_nan=False, ge=0, le=1e12)]
|
|
SharePercent = Annotated[float, Field(strict=True, allow_inf_nan=False, ge=0, le=100)]
|
|
Identifier = Annotated[str, Field(min_length=1, max_length=80, pattern=r"^[a-zA-Z0-9_-]+$")]
|
|
Text = Annotated[str, Field(min_length=1, max_length=500)]
|
|
PeriodLabel = Annotated[str, Field(min_length=1, max_length=40)]
|
|
|
|
ComputeMetric = Literal[
|
|
"global_share",
|
|
"intelligent_share",
|
|
"absolute",
|
|
"frontier_cluster_share",
|
|
"chip_inflow_share",
|
|
]
|
|
SHARE_METRICS: frozenset[str] = frozenset(
|
|
{
|
|
"global_share",
|
|
"intelligent_share",
|
|
"frontier_cluster_share",
|
|
"chip_inflow_share",
|
|
}
|
|
)
|
|
|
|
|
|
class ConfigurationModel(BaseModel):
|
|
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
|
|
|
|
|
class ComputeSource(ConfigurationModel):
|
|
id: Identifier
|
|
title: Text
|
|
url: HttpUrl
|
|
publisher: Text
|
|
report_year: Year
|
|
published_at: date | None = None
|
|
locator: Text
|
|
|
|
@field_validator("url")
|
|
@classmethod
|
|
def public_reference(cls, value: HttpUrl) -> HttpUrl:
|
|
if value.username or value.password or len(str(value)) > 2000:
|
|
raise ValueError("Use a report URL without credentials (maximum 2000 characters)")
|
|
return value
|
|
|
|
|
|
class ComputeObservation(ConfigurationModel):
|
|
year: Year
|
|
metric: ComputeMetric
|
|
source_id: Identifier
|
|
values: dict[str, Value] = Field(min_length=1, max_length=250)
|
|
value_sources: dict[str, Identifier] | None = None
|
|
period_label: PeriodLabel | None = None
|
|
global_total: Value | None = None
|
|
|
|
@model_validator(mode="after")
|
|
def comparable_values(self) -> Self:
|
|
if any(code not in COUNTRY_PARTICIPANTS for code in self.values):
|
|
raise ValueError(
|
|
"Use countries from the canonical compute catalog, not regional totals"
|
|
)
|
|
if self.value_sources is not None:
|
|
invalid_keys = [code for code in self.value_sources if code not in self.values]
|
|
if invalid_keys:
|
|
raise ValueError(
|
|
"Per-country value_sources keys must be a subset of observation values"
|
|
)
|
|
if self.metric in SHARE_METRICS and sum(self.values.values()) > 100.000001:
|
|
raise ValueError("Global shares for one year must total at most 100 percent")
|
|
return self
|
|
|
|
|
|
def source_for(row: ComputeObservation, code: str) -> str:
|
|
"""Resolve the authoritative source_id for one country inside an observation row."""
|
|
if row.value_sources and code in row.value_sources:
|
|
return row.value_sources[code]
|
|
return row.source_id
|
|
|
|
|
|
def row_source_ids(row: ComputeObservation) -> list[str]:
|
|
"""Return deduplicated source IDs referenced across all countries in an observation row."""
|
|
if not row.values:
|
|
return [row.source_id]
|
|
return list(dict.fromkeys(source_for(row, code) for code in row.values))
|
|
|
|
|
|
def has_mixed_sources(row: ComputeObservation) -> bool:
|
|
"""Return True when countries in one observation row cite more than one distinct source."""
|
|
return len(row_source_ids(row)) > 1
|
|
|
|
|
|
class ComputeStructureObservation(ConfigurationModel):
|
|
scope: str = Field(min_length=2, max_length=16)
|
|
year: Year
|
|
period_label: PeriodLabel | None = None
|
|
intelligent_share: SharePercent
|
|
general_and_super_share: SharePercent
|
|
note: Text | None = None
|
|
note_en: Text | None = None
|
|
source_id: Identifier
|
|
|
|
@model_validator(mode="after")
|
|
def valid_structure(self) -> Self:
|
|
if self.scope != "GLOBAL" and self.scope not in COUNTRY_PARTICIPANTS:
|
|
raise ValueError("Structure scope must be GLOBAL or a canonical country code")
|
|
total = self.intelligent_share + self.general_and_super_share
|
|
if abs(total - 100.0) > 0.5:
|
|
raise ValueError("Internal compute structure shares must total 100 percent")
|
|
return self
|
|
|
|
|
|
class ComputeMilestoneEvent(ConfigurationModel):
|
|
id: Identifier
|
|
year: Year
|
|
month: Annotated[int, Field(strict=True, ge=1, le=12)] | None = None
|
|
title: Text
|
|
title_en: Text
|
|
summary: Text
|
|
summary_en: Text
|
|
participants: list[str] = Field(min_length=1, max_length=12)
|
|
source_id: Identifier
|
|
|
|
@model_validator(mode="after")
|
|
def valid_participants(self) -> Self:
|
|
if any(code not in PARTICIPANTS for code in self.participants):
|
|
raise ValueError("Milestone participants must belong to the compute catalog")
|
|
return self
|
|
|
|
|
|
class NationalComputeHub(ConfigurationModel):
|
|
id: Identifier
|
|
name: Text
|
|
name_en: Text
|
|
country: Literal["CN"] = "CN"
|
|
role: Literal["eastern_demand", "western_green"]
|
|
latitude: Annotated[float, Field(strict=True, allow_inf_nan=False, ge=-90, le=90)]
|
|
longitude: Annotated[float, Field(strict=True, allow_inf_nan=False, ge=-180, le=180)]
|
|
target_pue: Annotated[float, Field(strict=True, allow_inf_nan=False, ge=1.0, le=2.5)]
|
|
green_power_note: Text
|
|
green_power_note_en: Text
|
|
cluster_examples: list[Text] = Field(default_factory=list, max_length=10)
|
|
paired_hub_ids: list[Identifier] = Field(default_factory=list, max_length=8)
|
|
source_id: Identifier
|
|
|
|
|
|
class InnovationObservation(ConfigurationModel):
|
|
year: Year
|
|
value: Annotated[float, Field(strict=True, allow_inf_nan=False, ge=-100, le=100)]
|
|
source_id: Identifier
|
|
|
|
|
|
class ComputeConfiguration(ConfigurationModel):
|
|
reviewed_at: date
|
|
sources: list[ComputeSource] = Field(max_length=200)
|
|
observations: list[ComputeObservation] = Field(max_length=300)
|
|
innovation: list[InnovationObservation] = Field(max_length=101)
|
|
structures: list[ComputeStructureObservation] = Field(default_factory=list, max_length=100)
|
|
milestones: list[ComputeMilestoneEvent] = Field(default_factory=list, max_length=100)
|
|
national_hubs: list[NationalComputeHub] = Field(default_factory=list, max_length=32)
|
|
|
|
@model_validator(mode="after")
|
|
def consistent_evidence(self) -> Self:
|
|
ids = [source.id for source in self.sources]
|
|
if len(ids) != len(set(ids)):
|
|
raise ValueError("Report source IDs must be unique")
|
|
keys = [(row.metric, row.year, row.period_label or "") for row in self.observations]
|
|
metric_year_keys = [(row.metric, row.year) for row in self.observations]
|
|
if len(keys) != len(set(keys)) or len(metric_year_keys) != len(set(metric_year_keys)):
|
|
raise ValueError("Each metric/year may have only one observation")
|
|
years = [row.year for row in self.innovation]
|
|
if len(years) != len(set(years)):
|
|
raise ValueError("Innovation observation years must be unique")
|
|
structure_keys = [(row.scope, row.year) for row in self.structures]
|
|
if len(structure_keys) != len(set(structure_keys)):
|
|
raise ValueError("Each scope/year may have only one structure observation")
|
|
milestone_ids = [row.id for row in self.milestones]
|
|
if len(milestone_ids) != len(set(milestone_ids)):
|
|
raise ValueError("Milestone IDs must be unique")
|
|
hub_ids = [row.id for row in self.national_hubs]
|
|
if len(hub_ids) != len(set(hub_ids)):
|
|
raise ValueError("National compute hub IDs must be unique")
|
|
|
|
if not self.sources and not self.observations and not self.innovation:
|
|
self.structures = []
|
|
self.milestones = []
|
|
self.national_hubs = []
|
|
if self.reviewed_at > date.today():
|
|
raise ValueError("Review date must not be in the future")
|
|
return self
|
|
|
|
sources = {source.id: source for source in self.sources}
|
|
for row in [*self.observations, *self.innovation, *self.structures, *self.milestones]:
|
|
source = sources.get(row.source_id)
|
|
if source is None:
|
|
raise ValueError(f"Missing report source: {row.source_id}")
|
|
if row.year > source.report_year:
|
|
raise ValueError("Observation year must not be after its report year")
|
|
for obs in self.observations:
|
|
if obs.value_sources:
|
|
for code, src_id in obs.value_sources.items():
|
|
source = sources.get(src_id)
|
|
if source is None:
|
|
raise ValueError(f"Missing report source: {src_id}")
|
|
if obs.year > source.report_year:
|
|
raise ValueError("Observation year must not be after its report year")
|
|
hub_id_set = set(hub_ids)
|
|
for hub in self.national_hubs:
|
|
if hub.source_id not in sources:
|
|
raise ValueError(f"Missing report source: {hub.source_id}")
|
|
if any(peer_id not in hub_id_set or peer_id == hub.id for peer_id in hub.paired_hub_ids):
|
|
raise ValueError("Paired national hub IDs must reference another configured hub")
|
|
if self.reviewed_at > date.today():
|
|
raise ValueError("Review date must not be in the future")
|
|
return self
|
|
|
|
|
|
class ComputeConfigurationWrite(ConfigurationModel):
|
|
revision: str = Field(min_length=1, max_length=80)
|
|
config: ComputeConfiguration
|
|
publish_note: str = Field(default="", max_length=1000)
|
|
source_candidate_ids: list[int] = Field(default_factory=list, max_length=50)
|
|
|
|
|
|
class ComputeConfigurationReset(ConfigurationModel):
|
|
revision: str = Field(min_length=1, max_length=80)
|
|
publish_note: str = Field(default="", max_length=1000)
|