ilc-models 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ilc_models/__init__.py ADDED
@@ -0,0 +1,953 @@
1
+ """Data models for the ILC project"""
2
+
3
+ import abc
4
+ import datetime
5
+ import functools
6
+ import re
7
+ from operator import attrgetter, itemgetter
8
+ from typing import Annotated, Any, Literal, Optional, Self, cast
9
+
10
+ from pydantic import (
11
+ BaseModel,
12
+ Field,
13
+ NonNegativeInt,
14
+ PositiveInt,
15
+ ValidatorFunctionWrapHandler,
16
+ WrapValidator,
17
+ model_validator,
18
+ )
19
+
20
+ __version__ = "0.1.0"
21
+
22
+ type RowTuple = tuple[str, int, int, int, int, int, int, int, int]
23
+
24
+
25
+ class BasePlayer(BaseModel):
26
+ """Basic level of player details.
27
+
28
+ :param player_id: ID of this player in the API
29
+ :type player_id: int
30
+ :param name: Player's full (display) name
31
+ :type name: str
32
+ """
33
+
34
+ player_id: int
35
+ name: str
36
+
37
+ def __str__(self) -> str:
38
+ return self.name
39
+
40
+
41
+ def validate_dob(value: Any, handler: ValidatorFunctionWrapHandler) -> str:
42
+ """Validate that a value conforms to a valid DOB string.
43
+
44
+ Allows empty string, yyyy-m-d and yyyy-mm-dd.
45
+ Any other format will raise a :exc:`ValueError`.
46
+
47
+ :param value: DOB to validate
48
+ :type value: :class:`typing.Any`
49
+ :param handler: Pydantic validation handler
50
+ :type handler: :class:`pydantic.ValidatorFunctionWrapHandler`
51
+ :returns: Validated value in `yyyy-mm-dd` format
52
+ :rtype: str
53
+ :raises: :exc:`ValueError` if format is invalid
54
+ """
55
+ # Will raise a ValidationError for a non-string
56
+ dob = cast(str, handler(value))
57
+
58
+ # Accept the empty string
59
+ if dob == "":
60
+ return dob
61
+
62
+ # yyyy-mm-dd regex
63
+ pattern = re.compile(r"[12][09]\d{2}-[01]\d-[0-3]\d$")
64
+
65
+ # Matches - return as validated
66
+ if re.match(pattern, dob):
67
+ return dob
68
+
69
+ # Allow for missing zeros
70
+ pattern = re.compile(r"[12][09]\d{2}-\d{1,2}-\d{1,2}$")
71
+ if not re.match(pattern, dob):
72
+ raise ValueError(f"{dob} is not a valid ISO date format.")
73
+
74
+ # Convert to yyyy-mm-dd and return
75
+ y, m, d = (int(n) for n in dob.split("-"))
76
+ return f"{y}-{m:02}-{d:02}"
77
+
78
+
79
+ class Player(BasePlayer):
80
+ """Full player details.
81
+
82
+ :param first_name: Player's first name
83
+ :type first_name: str
84
+ :param last_name: Player's last name
85
+ :type last_name: str
86
+ :param dob: Player's date of birth in ISO (yyyy-mm-dd) format
87
+ :type dob: str
88
+ :param nationality: Player's nationality
89
+ :type nationality: str
90
+ """
91
+
92
+ first_name: str
93
+ last_name: str
94
+ dob: Annotated[str, WrapValidator(validate_dob)]
95
+ nationality: str
96
+
97
+ @property
98
+ def base_player(self) -> BasePlayer:
99
+ """Return a `BasePlayer` object corresponding to this `Player`.
100
+
101
+ :returns: The `BasePlayer` corresponding to this `Player`
102
+ :rtype: :class:`BasePlayer`
103
+ """
104
+ return BasePlayer(player_id=self.player_id, name=self.name)
105
+
106
+
107
+ class Lineup(BaseModel):
108
+ """Lineup for one team.
109
+
110
+ Each lineup entry is an (int, BasePlayer) tuple, with the int
111
+ being the player's shirt number if supplied (0 if not).
112
+
113
+ :param starting: Starting XI (default=[])
114
+ :type starting: list[tuple[int, BasePlayer]]
115
+ :param subs: Substitutes (default=[])
116
+ :type subs: list[tuple[int, BasePlayer]]
117
+ """
118
+
119
+ starting: list[tuple[int, BasePlayer]] = Field(max_length=11, default=[])
120
+ subs: list[tuple[int, BasePlayer]] = []
121
+
122
+ def __bool__(self) -> bool:
123
+ """Returns True if this lineup is populated with players."""
124
+ return len(self.starting) + len(self.subs) > 0
125
+
126
+ def sort(self):
127
+ """Sorts the lineup.
128
+
129
+ Each part of the lineup is sorted by shirt number, except
130
+ for the first item in the starting lineup which is
131
+ assumed to be the goalkeeper and is left as the first item.
132
+ """
133
+ self.starting = self.starting[:1] + sorted(self.starting[1:], key=itemgetter(0))
134
+ self.subs.sort(key=itemgetter(0))
135
+
136
+ def players(self) -> list[BasePlayer]:
137
+ """Returns all players in this lineup"""
138
+ return [p[1] for p in self.starting] + [p[1] for p in self.subs]
139
+
140
+ def __len__(self) -> int:
141
+ """Returns the total number of players in this lineup"""
142
+ return len(self.starting) + len(self.subs)
143
+
144
+
145
+ class Lineups(BaseModel):
146
+ """Match lineups for home and away teams.
147
+
148
+ :param home: Home lineup (default=Lineup())
149
+ :type home: :class:`Lineup`
150
+ :param away: Away lineup (default=Lineup())
151
+ :type away: :class:`Lineup`
152
+ """
153
+
154
+ home: Lineup = Lineup()
155
+ away: Lineup = Lineup()
156
+
157
+ def __bool__(self) -> bool:
158
+ """Returns True if either lineup is populated with players."""
159
+ return bool(self.home) or bool(self.away)
160
+
161
+ def sort(self):
162
+ """Sort the lineups.
163
+
164
+ Each part of the lineup is sorted by shirt number, except
165
+ for the first item in the starting lineup which is
166
+ assumed to be the goalkeeper and is left as the first item.
167
+ """
168
+ self.home.sort()
169
+ self.away.sort()
170
+
171
+ def players(self) -> list[BasePlayer]:
172
+ """Returns all players in this lineup"""
173
+ return self.home.players() + self.away.players()
174
+
175
+ def __len__(self) -> int:
176
+ """Returns the total number of players in these lineups"""
177
+ return len(self.home) + len(self.away)
178
+
179
+
180
+ @functools.total_ordering
181
+ class EventTime(BaseModel):
182
+ """The time an event occurred during a match.
183
+
184
+ :param minutes: Minutes elapsed (1-120)
185
+ :type minutes: int
186
+ :param plus: Additional time minutes i.e. after 45, 90 etc. (default=0)
187
+ :type plus: int
188
+ """
189
+
190
+ minutes: int = Field(gt=0, le=120)
191
+ plus: NonNegativeInt = 0
192
+
193
+ @model_validator(mode="after")
194
+ def check_valid_time(self) -> Self:
195
+ """Checks the `minutes` field is valid if `plus` is non-zero"""
196
+ if self.plus != 0 and self.minutes not in (45, 90, 105, 120):
197
+ raise ValueError("Additional time is only valid at the end of a half")
198
+
199
+ return self
200
+
201
+ def __eq__(self, other: Any) -> bool:
202
+ """Returns True if `self` and `other` are equal.
203
+
204
+ :param other: Time to compare to
205
+ :type other: Any
206
+ :returns: `True` if the times are equal
207
+ :rtype: bool
208
+ """
209
+ try:
210
+ return (self.minutes, self.plus) == (other.minutes, other.plus)
211
+ except AttributeError: # pragma: no cover
212
+ return NotImplemented
213
+
214
+ def __gt__(self, other: Any) -> bool:
215
+ """Returns True if `self` is greater than `other.
216
+
217
+ :param other: Time to compare to
218
+ :type other: Any
219
+ :returns: `True` if `self` is greater than `other`
220
+ :rtype: bool
221
+ """
222
+ try:
223
+ return (self.minutes, self.plus) > (other.minutes, other.plus)
224
+ except AttributeError: # pragma: no cover
225
+ return NotImplemented
226
+
227
+ def __str__(self) -> str:
228
+ """The event time in str format"""
229
+ p = f"+{self.plus}" if self.plus else ""
230
+ return f"{self.minutes}{p}'"
231
+
232
+
233
+ class BaseEvent(BaseModel, abc.ABC):
234
+ """Abstract base class for events.
235
+
236
+ :param team: Team this event relates to
237
+ :type team: str
238
+ :param time: Event time
239
+ :type time: :class:`EventTime`
240
+ """
241
+
242
+ team: str
243
+ time: EventTime
244
+
245
+ def time_str(self) -> str:
246
+ """The event time in str format"""
247
+ return str(self.time)
248
+
249
+ @abc.abstractmethod
250
+ def players(self) -> list[BasePlayer]: # pragma: no cover
251
+ """Get the players involved in this event"""
252
+ pass
253
+
254
+
255
+ class Goal(BaseEvent):
256
+ """Represents a goal.
257
+
258
+ :param event_type: The literal string 'goal'
259
+ :type event_type: str
260
+ :param goal_type: One of 'N' (normal goal), 'O' (own goal), 'P' (penalty) (default='N')
261
+ :type goal_type: str
262
+ :param scorer: Goal scorer
263
+ :type scorer: :class:`BasePlayer`
264
+ """
265
+
266
+ event_type: Literal["goal"] = Field(default="goal", frozen=True)
267
+ goal_type: Literal["N", "O", "P"] = "N"
268
+ scorer: BasePlayer
269
+
270
+ def players(self) -> list[BasePlayer]:
271
+ """Get the players involved in this event"""
272
+ return [self.scorer]
273
+
274
+
275
+ class Card(BaseEvent):
276
+ """Represents a red or yellow card.
277
+
278
+ :param event_type: The literal string 'card'
279
+ :type event_type: str
280
+ :param card_type: One of 'R' (red card), 'Y' (yellow card)
281
+ :type card_type: str
282
+ :param player: Player receiving the card
283
+ :type player: :class:`BasePlayer`
284
+ """
285
+
286
+ event_type: Literal["card"] = Field(default="card", frozen=True)
287
+ color: Literal["Y", "R"]
288
+ player: BasePlayer
289
+
290
+ def players(self) -> list[BasePlayer]:
291
+ """Get the players involved in this event"""
292
+ return [self.player]
293
+
294
+
295
+ class Substitution(BaseEvent):
296
+ """Represents a substitution.
297
+
298
+ :param event_type: The literal string 'sub'
299
+ :type event_type: str
300
+ :param player_on: Player entering the field
301
+ :type player_on: :class:`BasePlayer`
302
+ :param player_off: Player leaving the field
303
+ :type player_off: :class:`BasePlayer`
304
+ """
305
+
306
+ event_type: Literal["sub"] = Field(default="sub", frozen=True)
307
+ player_on: BasePlayer
308
+ player_off: BasePlayer
309
+
310
+ def players(self) -> list[BasePlayer]:
311
+ """Get the players involved in this event"""
312
+ return [self.player_off, self.player_on]
313
+
314
+
315
+ type Event = Goal | Card | Substitution
316
+
317
+
318
+ class Teams(BaseModel):
319
+ """The teams in a match.
320
+
321
+ :param home: Home team
322
+ :type home: str
323
+ :param away: Away team
324
+ :type away: str
325
+ """
326
+
327
+ home: str
328
+ away: str
329
+
330
+
331
+ class Score(BaseModel):
332
+ """Match score.
333
+
334
+ :param home: Home team score (default=0)
335
+ :type home: int
336
+ :param away: Away team score (default=0)
337
+ :type away: int
338
+ """
339
+
340
+ home: NonNegativeInt = 0
341
+ away: NonNegativeInt = 0
342
+
343
+
344
+ class Match(BaseModel):
345
+ """Represents a match.
346
+
347
+ :param match_id: API ID of this match
348
+ :type match_id: int
349
+ :param kickoff: Date of match in ISO string format
350
+ :type kickoff: str
351
+ :param round: Round this match is part of
352
+ :type round: str
353
+ :param teams: Teams involved in this match
354
+ :type teams: Teams
355
+ :param status: Match status
356
+ :type status: str
357
+ :param score: Score in this match (default=0-0)
358
+ :type score: Score
359
+ :param goals: Detail of goals scored in the match
360
+ :type goals: list[Goal]
361
+ :param cards: Detail of cards shown in the match
362
+ :type cards: list[Card]
363
+ :param substitutions: Detail of substitutions made in the match
364
+ :type substitutions: list[Substitution]
365
+ """
366
+
367
+ match_id: PositiveInt
368
+ kickoff: str = Field(
369
+ pattern=r"^[12][09]\d{2}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d[+-][01]\d:[0-5]\d$"
370
+ )
371
+ round: str
372
+ teams: Teams
373
+ status: str
374
+ score: Score = Score()
375
+ goals: list[Goal] = []
376
+ cards: list[Card] = []
377
+ substitutions: list[Substitution] = []
378
+ lineups: Lineups = Lineups()
379
+
380
+ @property
381
+ def played(self) -> bool:
382
+ return self.status in ("FT", "AET", "PEN")
383
+
384
+ @property
385
+ def date(self) -> datetime.date:
386
+ return datetime.datetime.fromisoformat(self.kickoff).date()
387
+
388
+ def involves(self, team: str) -> bool:
389
+ """Returns ``True`` if ``team`` is involved in this match.
390
+
391
+ :param team: Team to query
392
+ :type team: str
393
+ :returns: ``True`` if ``team`` is involved in this match, i.e.
394
+ either as the home team or the away team
395
+ :rtype: bool
396
+ """
397
+ return self.teams.home == team or self.teams.away == team
398
+
399
+ def events(self) -> list[Event]:
400
+ """Returns all events in this match in chronological order.
401
+
402
+ :returns: The combined list of goals, cards and subs in the match
403
+ :rtype: list[Event]
404
+ """
405
+ e = self.goals + self.cards + self.substitutions
406
+ return sorted(e, key=attrgetter("time"))
407
+
408
+ def players(self) -> list[BasePlayer]:
409
+ """Returns all players involved in this match"""
410
+ p = self.lineups.players()
411
+ for event in self.events():
412
+ for player in event.players():
413
+ if player not in p:
414
+ p.append(player)
415
+ return p
416
+
417
+ def __str__(self) -> str:
418
+ if self.played:
419
+ return f"{self.teams.home} {self.score.home} - {self.score.away} {self.teams.away}"
420
+ return f"{self.teams.home} vs {self.teams.away}"
421
+
422
+
423
+ @functools.total_ordering
424
+ class TableRow(BaseModel):
425
+ """A row in a league table.
426
+
427
+ :param team: Team name
428
+ :type team: str
429
+ :param won: Matches won (default=0)
430
+ :type won: int
431
+ :param drawn: Matches drawn (default=0)
432
+ :type drawn: int
433
+ :param lost: Matches lost (default=0)
434
+ :type lost: int
435
+ :param scored: Goals scored (default=0)
436
+ :type scored: int
437
+ :param conceded: Goals conceded (default=0)
438
+ :type conceded: int
439
+ """
440
+
441
+ team: str
442
+ won: NonNegativeInt = 0
443
+ drawn: NonNegativeInt = 0
444
+ lost: NonNegativeInt = 0
445
+ scored: NonNegativeInt = 0
446
+ conceded: NonNegativeInt = 0
447
+ deducted: NonNegativeInt = 0
448
+
449
+ @property
450
+ def played(self) -> int:
451
+ """Matches played.
452
+
453
+ :returns: The total number of matches played
454
+ :rtype: int
455
+ """
456
+ return self.won + self.drawn + self.lost
457
+
458
+ @property
459
+ def gd(self) -> int:
460
+ """Goal difference.
461
+
462
+ :returns: The goal difference, i.e. goals scored minus goals conceded
463
+ :rtype: int
464
+ """
465
+ return self.scored - self.conceded
466
+
467
+ @property
468
+ def points(self) -> int:
469
+ """Total points gained.
470
+
471
+ :returns: The total number of points gained
472
+ :rtype: int
473
+ """
474
+ return self.won * 3 + self.drawn - self.deducted
475
+
476
+ def as_tuple(self) -> RowTuple:
477
+ """Returns this row as a tuple.
478
+
479
+ Elements are: (team, played, won, drawn, lost, scored, conceded, gd, points)
480
+
481
+ :returns: This row as a tuple
482
+ :rtype: :type:`RowTuple`
483
+ """
484
+ return (
485
+ self.team,
486
+ self.played,
487
+ self.won,
488
+ self.drawn,
489
+ self.lost,
490
+ self.scored,
491
+ self.conceded,
492
+ self.gd,
493
+ self.points,
494
+ )
495
+
496
+ @classmethod
497
+ def from_tuple(cls, row_tuple: RowTuple) -> "TableRow":
498
+ """Creates a `TableRow` instance from a `RowTuple`.
499
+
500
+ :param row_tuple: Source tuple
501
+ :type row_tuple: :class:`ilc_models.RowTuple`
502
+ :returns: Newly created `TableRow`
503
+ :rtype: :class:`ilc_models.TableRow`
504
+ """
505
+ return cls(
506
+ team=row_tuple[0],
507
+ won=row_tuple[2],
508
+ drawn=row_tuple[3],
509
+ lost=row_tuple[4],
510
+ scored=row_tuple[5],
511
+ conceded=row_tuple[6],
512
+ )
513
+
514
+ def __eq__(self, other: Any) -> bool:
515
+ """Returns True if `self` and `other` are equal.
516
+
517
+ :param other: Row to compare to
518
+ :type other: :class:`ilc_models.TableRow`
519
+ :returns: `True` if the rows are equal
520
+ :rtype: bool
521
+ """
522
+ try:
523
+ return (self.points, self.gd, self.scored, self.team) == (
524
+ other.points,
525
+ other.gd,
526
+ other.scored,
527
+ other.team,
528
+ )
529
+ except AttributeError:
530
+ return NotImplemented
531
+
532
+ def __gt__(self, other: Any) -> bool: # pragma: no cover
533
+ """Returns True if `self` is greater than `other.
534
+
535
+ Ordering is by points, GD and goals scored.
536
+ If all are equal, team name will be compared
537
+ in reverse alphabetical order so that a sorted league table
538
+ will be ordered alphabetically.
539
+
540
+ :param other: Row to compare to
541
+ :type other: :class:`ilc_models.TableRow`
542
+ :returns: `True` if `self` is greater than `other`
543
+ :rtype: bool
544
+ """
545
+ try:
546
+ if (self.points, self.gd, self.scored) == (
547
+ other.points,
548
+ other.gd,
549
+ other.scored,
550
+ ):
551
+ return self.team < other.team
552
+ return (self.points, self.gd, self.scored) > (
553
+ other.points,
554
+ other.gd,
555
+ other.scored,
556
+ )
557
+ except AttributeError:
558
+ return NotImplemented
559
+
560
+ def __str__(self) -> str:
561
+ return " ".join(
562
+ (
563
+ self.team,
564
+ f"P{self.played}",
565
+ f"W{self.won}",
566
+ f"D{self.drawn}",
567
+ f"L{self.lost}",
568
+ f"F{self.scored}",
569
+ f"A{self.conceded}",
570
+ f"GD{self.gd}",
571
+ f"Pts{self.points}",
572
+ )
573
+ )
574
+
575
+
576
+ def validate_deduction_date(value: Any, handler: ValidatorFunctionWrapHandler) -> str:
577
+ """Validate that a value conforms to a valid DOB string.
578
+
579
+ Allows empty string and yyyy-mm-dd.
580
+ Any other format will raise a :exc:`ValueError`.
581
+
582
+ :param value: DOB to validate
583
+ :type value: :class:`typing.Any`
584
+ :param handler: Pydantic validation handler
585
+ :type handler: :class:`pydantic.ValidatorFunctionWrapHandler`
586
+ :returns: Validated value in `yyyy-mm-dd` format
587
+ :rtype: str
588
+ :raises: :exc:`ValueError` if format is invalid
589
+ """
590
+ # Will raise a ValidationError for a non-string
591
+ date = cast(str, handler(value))
592
+
593
+ # Accept the empty string
594
+ if date == "":
595
+ return date
596
+
597
+ # yyyy-mm-dd regex
598
+ pattern = re.compile(r"[12][09]\d{2}-[01]\d-[0-3]\d$")
599
+
600
+ # Matches - return as validated
601
+ if re.match(pattern, date):
602
+ return date
603
+
604
+ raise ValueError(f"{date} is not a valid ISO date format.")
605
+
606
+
607
+ class Deduction(BaseModel):
608
+ """A points deduction.
609
+
610
+ :param team: Team to which this deduction applies
611
+ :type team: str
612
+ :param points: Number of points deducted
613
+ :type points: int
614
+ :param date: Date on which the deduction was implemented - if the empty string
615
+ the deduction should be built in from the start of the season
616
+ (default='')
617
+ :type date: str
618
+ """
619
+
620
+ team: str
621
+ points: PositiveInt
622
+ date: Annotated[str, WrapValidator(validate_deduction_date)] = ""
623
+
624
+
625
+ class EventInfo(BaseModel):
626
+ """Event data with match info added.
627
+
628
+ :param date: Date of match
629
+ :type date: :class:`datetime.date`
630
+ :param teams: Teams involved in the match
631
+ :type teams: :class:`Teams`
632
+ :param event: Event info
633
+ :type event: :class:`Event`
634
+ """
635
+
636
+ date: datetime.date
637
+ teams: Teams
638
+ event: Event
639
+
640
+
641
+ class League(BaseModel):
642
+ """Represents a League.
643
+
644
+ :param league_id: API ID of this league
645
+ :type league_id: int
646
+ :param name: Name of this league e.g. Premiership
647
+ :type name: str
648
+ :param year: Year this season starts
649
+ :type year: int
650
+ :param start: League start date as an ISO format string
651
+ :type start: str
652
+ :param end: League end date as an ISO format string
653
+ :type end: str
654
+ :param current: Whether this league is still being played
655
+ :type current: bool
656
+ :param coverage: Coverage available from the API
657
+ :type coverage: dict[str, bool]
658
+ :param teams: The name of each team in this league (default=[])
659
+ :type teams: list[str]
660
+ :param rounds: This league's rounds, with matches for each round (default={})
661
+ :type rounds: dict[str, list[:class:`Match`]]
662
+ :param excluded: Rounds to exclude from import (default=[])
663
+ :type excluded: list[str]
664
+ :param split: Split point of this league (default=0)
665
+ :type split: int
666
+ :param players: Players who feature in this league
667
+ :type players: dict[int, :class:'Player']
668
+ """
669
+
670
+ league_id: PositiveInt
671
+ name: str
672
+ year: PositiveInt
673
+ start: str = Field(pattern=r"^[12][09]\d{2}-[01]\d-[0-3]\d$")
674
+ end: str = Field(pattern=r"^[12][09]\d{2}-[01]\d-[0-3]\d$")
675
+ current: bool
676
+ coverage: dict[str, bool]
677
+ teams: list[str] = []
678
+ rounds: dict[str, list[Match]] = {}
679
+ excluded: list[str] = []
680
+ deductions: list[Deduction] = []
681
+ split: NonNegativeInt = 0
682
+ players: dict[str, Player] = {}
683
+
684
+ @property
685
+ def title(self) -> str:
686
+ """Title of this league e.g. Premiership 2023/24
687
+
688
+ :returns: Title of the league
689
+ :rtype: str
690
+ """
691
+ year1 = int(self.start[:4])
692
+ year2 = int(self.end[:4])
693
+ season = year1 if year1 == year2 else f"{year1}/{year2 % 100}"
694
+ return f"{self.name} {season}"
695
+
696
+ def matches(self, team: Optional[str] = None) -> list[Match]:
697
+ """Matches in this league.
698
+
699
+ If ``team`` is given, return only matches
700
+ involving this team, otherwise return all matches.
701
+
702
+ :param team: Get matches for this team (default=None)
703
+ :type team: str
704
+ :returns: Matches sorted by date and then home team
705
+ :rtype: list[:class:`Match`]
706
+ """
707
+ _matches = []
708
+ for m in self.rounds.values():
709
+ for match in m:
710
+ if team is None or match.involves(team):
711
+ _matches.append(match)
712
+
713
+ _matches.sort(key=attrgetter("teams.home"))
714
+ _matches.sort(key=attrgetter("date"))
715
+ return _matches
716
+
717
+ def events(self, player: BasePlayer) -> list[EventInfo]:
718
+ """Get all events in this league in which a player is involved.
719
+
720
+ :param player: Find events featuring this player
721
+ :type player: :class:`BasePlayer`
722
+ :returns: The events in this league involving the player
723
+ :rtype: list[BasePlayer]
724
+ """
725
+ e = []
726
+ for match in self.matches():
727
+ for event in match.events():
728
+ if player in event.players():
729
+ e.append(EventInfo(date=match.date, teams=match.teams, event=event))
730
+ return e
731
+
732
+ def update_player(self, old: BasePlayer, new: BasePlayer):
733
+ """Replace all occurrences of ``old`` with ``new``.
734
+
735
+ Searches all lineups and events in this league and
736
+ replaces all occurrences of ``old`` with ``new``.
737
+
738
+ :param old: Player to be replaced
739
+ :type old: :class:`BasePlayer`
740
+ :param new: New player details
741
+ :type new: :class:`BasePlayer`
742
+ """
743
+ for matches in self.rounds.values():
744
+ for match in matches:
745
+ if old in match.players():
746
+ # Update lineups
747
+ for plist in (
748
+ match.lineups.home.starting,
749
+ match.lineups.home.subs,
750
+ match.lineups.away.starting,
751
+ match.lineups.away.subs,
752
+ ):
753
+ for n, player in enumerate(plist):
754
+ if player[1] == old:
755
+ plist[n] = (player[0], new)
756
+ break
757
+ else:
758
+ continue
759
+ break
760
+
761
+ # Update events
762
+ for goal in match.goals:
763
+ if goal.scorer == old:
764
+ goal.scorer = new
765
+
766
+ for card in match.cards:
767
+ if card.player == old:
768
+ card.player = new
769
+
770
+ for sub in match.substitutions:
771
+ if sub.player_on == old:
772
+ sub.player_on = new
773
+ elif sub.player_off == old:
774
+ sub.player_off = new
775
+
776
+ def player_teams(self, player: BasePlayer) -> list[str]:
777
+ """Get all the teams a player features in during this season.
778
+
779
+ :param player: Find teams this player plays for
780
+ :type player: :class:`BasePlayer`
781
+ :returns: The teams the player plays for in this league
782
+ :rtype: list[str]
783
+ """
784
+ teams = set()
785
+
786
+ # Check each match as a player may play for more than
787
+ # one team during a single season
788
+ for match in self.matches():
789
+ if player in match.players():
790
+ found = False
791
+
792
+ # Check lineups
793
+ if match.lineups:
794
+ if player in match.lineups.home.players():
795
+ teams.add(match.teams.home)
796
+ found = True
797
+ elif player in match.lineups.away.players():
798
+ teams.add(match.teams.away)
799
+ found = True
800
+
801
+ # If the player is not in the lineups
802
+ # check all events
803
+ if not found:
804
+ for event in match.events():
805
+ match event:
806
+ case Goal(scorer=scorer, goal_type=goal_type):
807
+ if scorer == player:
808
+ # Adjust for own goal (an event for the opposing team)
809
+ if goal_type == "O":
810
+ teams.add(
811
+ match.teams.home
812
+ if event.team == match.teams.away
813
+ else match.teams.away
814
+ )
815
+ else:
816
+ teams.add(event.team)
817
+ break
818
+
819
+ case Card(player=card_player):
820
+ if card_player == player:
821
+ teams.add(event.team)
822
+ break
823
+
824
+ case Substitution(
825
+ player_on=player_on, player_off=player_off
826
+ ):
827
+ if player in (player_on, player_off):
828
+ teams.add(event.team)
829
+ break
830
+
831
+ return list(teams)
832
+
833
+ def table(
834
+ self,
835
+ played: int = 0,
836
+ split_point: bool = False,
837
+ date: Optional[datetime.date] = None,
838
+ ) -> list[RowTuple]:
839
+ """Get the league table.
840
+
841
+ Returns the league table as a list of :type:`RowTuple` items,
842
+ ordered by league position.
843
+
844
+ If ``played`` is non-zero the table will be returned at
845
+ the first point at which all teams have played at least
846
+ ``played`` matches.
847
+
848
+ If ``split_point`` is ``True`` the table will be returned
849
+ at the league's split point.
850
+
851
+ If ``date`` is not ``None`` the table will be returned
852
+ at the given date, i.e. taking account only of matches
853
+ where the date is earlier than or equal to ``date``.
854
+
855
+ :param played: If non-zero, get table after this number of games (default=0)
856
+ :type played: int
857
+ :param split_point: If True get the table at the split point (default=False)
858
+ :type split_point: bool
859
+ :param date: If given, get the league table on this date (default=None)
860
+ :type date: :class:`datetime.date`
861
+ :returns: The league table as a list of tuples
862
+ :rtype: list[:type:`RowTuple`]
863
+ """
864
+ # Create rows
865
+ rows = {team: TableRow(team=team) for team in self.teams}
866
+
867
+ # Get table at split point
868
+ if split_point:
869
+ played = self.split
870
+
871
+ # Retain the date of the last match processed to manage deductions
872
+ last_date = None
873
+
874
+ # Add matches
875
+ for match in (m for m in self.matches() if m.played):
876
+ # Check for date
877
+ if date is not None and match.date > date:
878
+ last_date = date
879
+ break
880
+
881
+ # Get rows
882
+ home = rows[match.teams.home]
883
+ away = rows[match.teams.away]
884
+
885
+ # W/D/L
886
+ if match.score.home > match.score.away:
887
+ home.won += 1
888
+ away.lost += 1
889
+ elif match.score.home < match.score.away:
890
+ home.lost += 1
891
+ away.won += 1
892
+ else:
893
+ home.drawn += 1
894
+ away.drawn += 1
895
+
896
+ # Goals
897
+ home.scored += match.score.home
898
+ home.conceded += match.score.away
899
+ away.scored += match.score.away
900
+ away.conceded += match.score.home
901
+
902
+ # Retain date
903
+ last_date = match.date
904
+
905
+ # Check if all teams have played the required number of games
906
+ if played and all(row.played >= played for row in rows.values()):
907
+ break
908
+
909
+ # Handle deductions
910
+ for deduction in self.deductions:
911
+ if not deduction.date or (
912
+ last_date is not None
913
+ and datetime.date.fromisoformat(deduction.date) <= last_date
914
+ ):
915
+ rows[deduction.team].deducted += deduction.points
916
+
917
+ # Handle split
918
+ if (
919
+ not split_point
920
+ and self.split
921
+ and any(row.played > self.split for row in rows.values())
922
+ ):
923
+ # Post-split - find the positions at the split point
924
+ split = self.table(split_point=True)
925
+ order = [row[0] for row in split]
926
+
927
+ # Get the top and bottom half teams at the split
928
+ team_count = int(len(rows) / 2)
929
+ top_teams = order[:team_count]
930
+ bottom_teams = order[team_count:]
931
+
932
+ else:
933
+ # Pre-split - just put all teams into the top section
934
+ top_teams = list(rows.keys())
935
+ bottom_teams = []
936
+
937
+ # Sort top and bottom separately
938
+ top = sorted((rows[team] for team in top_teams), reverse=True)
939
+ bottom = sorted((rows[team] for team in bottom_teams), reverse=True)
940
+ return [row.as_tuple() for row in top] + [row.as_tuple() for row in bottom]
941
+
942
+ def head_to_head(self, teams: tuple[str, str]) -> list[Match]:
943
+ """Get all matches played between two teams.
944
+
945
+ :param teams: Teams to query
946
+ :type teams: tuple[str, str]
947
+ :returns: All matches between these two teams
948
+ :rtype: list[:class:`Match`]
949
+ """
950
+ return [match for match in self.matches(teams[0]) if match.involves(teams[1])]
951
+
952
+ def __str__(self) -> str: # pragma: no cover
953
+ return self.title
ilc_models/py.typed ADDED
File without changes
@@ -0,0 +1,33 @@
1
+ Metadata-Version: 2.4
2
+ Name: ilc-models
3
+ Version: 0.1.0
4
+ Summary: Data models for the ILC project
5
+ Project-URL: Repository, https://github.com/fourtreestech/ilc-models
6
+ Author-email: Neil Martin <neil@fourtrees.tech>
7
+ License-Expression: MIT
8
+ License-File: LICENSE.txt
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Natural Language :: English
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Topic :: Software Development :: Libraries
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.11
18
+ Requires-Dist: pydantic>=2.10.6
19
+ Description-Content-Type: text/markdown
20
+
21
+ # ilc-models
22
+
23
+ ![version](https://img.shields.io/badge/version-0.1.0-blue)
24
+ ![Python Version from PEP 621 TOML](https://img.shields.io/python/required-version-toml?tomlFilePath=https%3A%2F%2Fraw.githubusercontent.com%2Ffourtreestech%2Filc-models%2Fmain%2Fpyproject.toml)
25
+ ![coverage](https://img.shields.io/badge/coverage-100%25-green)
26
+
27
+ **ilc-models** contains all data models for the *ILC* project.
28
+
29
+ ## Installation
30
+
31
+ (.venv) $ pip install ilc-models
32
+
33
+
@@ -0,0 +1,6 @@
1
+ ilc_models/__init__.py,sha256=oA8-gD6Xg31jzs2IbYgkwMrPP4bA_bxGuaWZ7qHPMYU,29866
2
+ ilc_models/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ ilc_models-0.1.0.dist-info/METADATA,sha256=c4ppScN72p7leSb2P2tSEmXS2qwgzmJcYzS6qrybMdE,1176
4
+ ilc_models-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
5
+ ilc_models-0.1.0.dist-info/licenses/LICENSE.txt,sha256=4CZnArOl_SkL5nXaKtHPqlie3_JyuQfT51DMC_xtYzA,1067
6
+ ilc_models-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Neil Martin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.