rstt.ranking package
Subpackages
- rstt.ranking.observer package
- rstt.ranking.inferer package
- rstt.ranking.standard package
Submodules
rstt.ranking.datamodel module
Module dedictated to RatingSystem
RatingSystem are ranking component acting as defaultdictionary to store rating for player. It provide get(), set() and ordinal() methods.
- class rstt.ranking.datamodel.GaussianModel(*arg, **kwargs)[source]
Bases:
KeyModelGaussian Rating Systems
Associated ratings must have a mu and a sigma attributes.
- class rstt.ranking.datamodel.KeyModel(default: Any | None = None, template: Callable | None = None, factory: Callable | None = None, **kwargs)[source]
Bases:
objectBasic Rating system
The KeyModel is a intuitive implementation of
rstt.stypes.RatingSystemthat strores ratings of player in a defauldict. The default rating value can be specified in three different fashions.Parameters
- defaultAny, optional
A default rating value, by default None.
- templateCallable, optional
A lambda function to generate default ratings, by default None
- factory_type_, optional
A Callable of the form lambda x: …, where x is the SPlayer with no rating, by default None. If you pass a factory, the KeyModel stores ratings in a
rstt.ranking.datamodel.keydefauldict.
Note
If you are using the 'template' or 'factory', you can additionaly specify **kwargs to be passed to the template every time it is called to generate a new rating. And for the 'default', no additonal parameters are allowed.
Raises
- ValueError
Error are raised in the case of incompatible parameters. Examples of valid calls are: KeyModel(default=1500) KeyModel(template=GaussianRating, 1500, 250) KeyModel(factory=GaussianRating, mu=1500, sigma=250)
- default() Any[source]
Getter for default rating
When instanciated, a default rating is generated. In the case of a ‘factory’ instanciation, the default rating is built with the help of a ‘Dummy’
rstt.player.basicplayer.BasicPlayerReturns
- Any
The default rating an unrank player gets.
- get(key: SPlayer) Any[source]
getter method for the rating of a player
Parameters
- keySPlayer
A player to get the rating
Returns
- Any
The rating of the player
- items()[source]
Dict like items() method
return the view object returned by the underlying dict.items method
Returns
- view object
items stored in the KeyModel
- keys()[source]
Dict like keys() method
return the view object returned by the underlying dict.keys method
Returns
- view object
keys, i.e. SPlayer.
- ordinal(rating: Any) float[source]
Convert a rating into a float value
The returned value is used to compare players to each other. An higher value is understood as a ‘better’ player
Note
This method assume the existence of a magic __float__ method for the ratings. If one uses custom ratings object, it is good to either write such method, override the ordinal methods, or design an associated
rstt.stypes.RatingSystem.Parameters
- ratingAny
A rating compatible with the KeyModel.rtypes()
Returns
- float
The corresponding value used to compare players in an ordered fashion.
- rtype() type[source]
Getter for the rating type
Warning
The type of ratings is infered at instanciation of the KeyModel using the type() built-in functions. However this can be inconsistant with the user’s intention.
Returns
- type
The rating type.
- set(key: SPlayer, rating)[source]
Set method to manualy assign a rating to a player.
Parameters
- keySPlayer
A Player to modify the rating
- ratingAny
a new rating.
Warning
The KeyModel class is a ‘Generic’ container in the sense that it can store any sort of rating, however, all values must be of the same type. With the current implementation it is unclear how to enforce it. So it is the responsability of the user to be consistent.
The set operation will not throw any error. Yet, following calls to
rstt.ranking.datamodel.KeyModel.ordinal()ordinal method could fail without proper error traceback.Hopefull future version will fix this issue.
- rstt.ranking.datamodel.get(self, key: SPlayer) Any
getter method for the rating of a player
Parameters
- keySPlayer
A player to get the rating
Returns
- Any
The rating of the player
- class rstt.ranking.datamodel.keydefaultdict(default_factory: Callable[[SPlayer], Any])[source]
Bases:
defaultdict[SPlayer,Any]Defaultdict with default values as function of the missing key.
This allows rating system to have a default rating based on some data available in a Player instance, such has the level or a win rate ratio.
Parameters
- default_factoryCallable[[Player], Any]
A function computing a default value for a missing key.
- rstt.ranking.datamodel.set(self, key: SPlayer, rating)
Set method to manualy assign a rating to a player.
Parameters
- keySPlayer
A Player to modify the rating
- ratingAny
a new rating.
Warning
The KeyModel class is a ‘Generic’ container in the sense that it can store any sort of rating, however, all values must be of the same type. With the current implementation it is unclear how to enforce it. So it is the responsability of the user to be consistent.
The set operation will not throw any error. Yet, following calls to
rstt.ranking.datamodel.KeyModel.ordinal()ordinal method could fail without proper error traceback.Hopefull future version will fix this issue.
rstt.ranking.ranking module
Ranking Module
This module implements utility decorator and a general ranking class.
Glossary
Container Equivalence (Union = Intersection):
(key in self.datamodel.ratings) <=> (key in self.standing).
In the code we refer to ‘equivalence’
Rank Disambiguity (point ‘=’ rating):
self.datamodel.ordinal(key) == self.standing.value(key) for all keys.
In the code we refer to ‘disambiguity’
- class rstt.ranking.ranking.Ranking(name: str, datamodel: RatingSystem, backend: Inference, handler: Observer, players: List[SPlayer] | None = None)[source]
Bases:
objectRanking for players
The rstt package implements its own definition of a ranking.
Formally an rstt ranking consist of a
A standing: An ordered sequence of players associated with an indication of their skills.
A rating system - storing player’s rating.
A statistical inference system - set of equations.
An update procedure
And two ‘hidden’ notions:
Observables: the set of ‘update triggers’ justifying a change of ratings. (what can be processed by the handler)
An ordinal function converting rating into float values (provided by the rating system)
Parameters
- namestr
A name to identify the ranking
- datamodelRatingSystem
A container storing rating of players and providing an orinal() funtion to convert rating into floating values.
- backendInference
The ‘math’ behind the ranking system.
- handlerObserver
A workflow handling the ranking update procedure
- playersOptional[List[SPlayer]], optional
Players to register in the ranking, by default None
- forward(*args, **kwargs)[source]
Internal ‘update’ function
This method calls the handler
rstt.stypes.handle_observations()with the parameters of the update function.Note
FOR RANKING DESIGNER ONLY method designed for devellopers who wants to modify the ranking.update function’s behavivous. In most cases, it is sufficient to write an apropriate observer as the ranking.handler.
However, sometimes it is relevant to do some ranking preprocessing before any rating updates. This would not always be possible to do inside the handle_observations method as the observer do not have access to all ranking attributes.
- players() List[SPlayer][source]
Get method of all keys
Alias for Ranking.standing.keys()
Returns
- List[Player]
A list of all player in descending order of their associated values.
- point(player: SPlayer) float[source]
Get the point associated to a key
Alias for Ranking.standing.value(player)
Returns
- float
the associated value.
- points() List[float][source]
Get method of all values
Alias for Ranking.standing.values()
Returns
- List[float]
A list of all associated values in descending order.
- rank(player: SPlayer) int[source]
Getter for player Rank
Equivalent to ranking.standing[player].
Parameters
- playerSPlayer
A player to get his rank.
Returns
- int
The rank of the player
- ranks(players: List[SPlayer]) List[int][source]
Getter for players Rank
Equivalent to ranking.standing[players].
Parameters
- playersSPlayer
Player to get their ranks.
Returns
- List[int]
The corresponding ranks of the players
- rating(player: SPlayer) Any[source]
Get method for rating
Rating object is the internal model associated to a key. Ratings are used to automaticly compute values for the sorting feature of a Standing.
Parameters
- playerPlayer
A key in the Ranking
Returns
- Any
The associated model to the provided key. The type is defined by Ranking.RatingSystem.rtype
Raises
KeyError
- rstt.ranking.ranking.add(self, keys: List[SPlayer])
Add players to the ranking
Each Player receive a default rating by the datamodel. It is possible to manipulate it using the set_rating() method.
Parameters
- keysList[SPlayer]
Players to be ranked.
- rstt.ranking.ranking.get_disamb(func: Callable[[...], Any]) Callable[[...], Any][source]
Disambiguity Get Decorator
Decorator for ranking methods. It enforces the disambuguity property before the decorated method execution.
Parameters
- funcCallable[…, Any]
A method that needs ‘a-priori’ the disambuguity property to be satisfied.
Returns
- Callable[…, Any]
A function with the expected behaviour.
- rstt.ranking.ranking.get_equi(func: Callable[[...], Any]) Callable[[...], Any][source]
Equivalence Get Decorator
Decorator for Ranking methods. It enforces the equivalence property before the decorated methods execution.
Parameters
- funcCallable[…, Any]
A method that needs ‘a-priori’ the equivalence property to be satisfied
Returns
- Callable[…, Any]
A function with the expected behaviour.
- rstt.ranking.ranking.rerank(self, permutation: List[int], name: str | None = None, direct: bool = True)
Reorder the ranking.
Inplace modification of the ranking state by reordering the players while maintaining a coherent state. This means that each player will be re assigned a new rating corresponding to the desired permuatation
Parameters
- permutationList[int]
A permutation of the ranking indices.
- namestr, optional
A name, by default None
- directbool, optional
Wether to apply the permutation directly, or its inverse, by default True
Raises
- ValueError
When the permutation is not a permutation over the ranking indices.
- rstt.ranking.ranking.set_disamb(func: Callable[[...], Any]) Callable[[...], Any][source]
Disambiguity Set Decorator
Decorator for ranking methods. It enforces the disambuguity property after the decorated method execution.
Parameters
- funcCallable[…, Any]
A method that could alter the disambuguity property.
Returns
- Callable[…, Any]
A function enforcing the disambiguity property
- rstt.ranking.ranking.set_equi(func: Callable[[...], Any]) Callable[[...], Any][source]
Equivalence Set Decorator
Decorator for Ranking methods. It enforces the equivalence property after the decorated methods execution
Parameters
- funcCallable[…, Any]
A method that could alter the equivalence property
Returns
- Callable[…, Any]
A function enforcing the equivalence property
rstt.ranking.rating module
Module for rating
Contains standard rating for common Ranking systems.
rstt.ranking.standing module
Standing Ranking
Standing is a sorted container class implementing a triplet relationship between player, rank and points.
- class rstt.ranking.standing.Standing(default: float = 0.0, lower: float = -2147483648, upper: float = 2147483647, step: float = 1.0, protocol: str = 'set')[source]
Bases:
objectA Standing object emulate a value-based ordered dictionary.
- The Standing also act as a <list> and a <dict> and the following relationship exist:
Index -> Key
Key -> Index
Keys oredring is descedning and based on the associated value of the key, i.e Standing.point(key).
The key ordering is maintain by internal mechanism as long as the Standing is manipulate with the provided methods and functionnalities.
Examples
Note
Ordering is computationaly demanding, which means that repeated operations on a large Standing could result in performances issues. It is possible to turn off the ordering features. This break the whole point of the class. Do it only if needed and if you know what your are doing
In its current form Key are intended to be of Type <Player> and Value of type <float>. This may change in the future to support a more general case such as: Key of type <Hasable> -> Value of type <Comarapble>.
Parameters
- defaultfloat, optional
A key added to the standing without an associated value will be assign this default value, by default 0.0
- minfloat, optional
The minimal boundary for values, by default np.iinfo(np.int32).min
- maxfloat, optional
The maximal boundary for values, by default np.iinfo(np.int32).max
- stepfloat, optional
An interval used for insertion operation , by default 1.0 NOTE: not completely supported, could disapear in futur version.
- fit(keys: List[SPlayer])[source]
Create a new Standing instance containing only the given Keys
The Keys will have the same value as in the current Standing if present otherwise the default value will be assigned.
Parameters
- keysList[Player]
list of <Player> to be present in the new Standing
Returns
Standing
- rstt.ranking.standing.fit(self, keys: List[SPlayer])
Create a new Standing instance containing only the given Keys
The Keys will have the same value as in the current Standing if present otherwise the default value will be assigned.
Parameters
- keysList[Player]
list of <Player> to be present in the new Standing
Returns
Standing
- rstt.ranking.standing.get_sort(func: Callable[[...], Any]) Callable[[...], Any][source]
Sorting Get Decorator
Decorator for Standing methods. It ensures that contained element (Players) are sorted in descending order of their associated values.
Parameters
- funcCallable[…, Any]
A standing that needs ‘a-priori’ correct ordering of the standing.
Returns
- Callable[…, Any]
A function with the expected behaviour.
- rstt.ranking.standing.index(self, key: SPlayer) int
Get index for key
Similar to list.index(). Standing implements an ‘Ordinal Ranking’ upon the set of keys based on associtaed values.
Parameters
- keyPlayer
The key to find in the Standing.
Returns
- int
The rank of the key in the Standing.
- rstt.ranking.standing.items(self) List[Tuple[SPlayer, float]]
Get method for key value pairs
Similar to dict.items(). It returns a list of tuples (key, value).
Returns
- List[Tuple[Player, float]]
List of items as tuple (key, value).
- rstt.ranking.standing.percentile(self, key: SPlayer) float
Getter funtion for the percentile of a player
Informatin about the relative position of a player in the standing
Parameters
- keySPlayer
A player to get his relative postiion
Returns
- float
The percentile of the player as his relative position in the ranking
- rstt.ranking.standing.pop(self, key: int | List[int] | SPlayer | List[SPlayer]) SPlayer | List[SPlayer] | int | List[int]
Get and remove method for element.
Similar list.pop() and dict.pop() with some notable distinction. It deletes the corresponding items but: - If key(s) are index(es)then it returns the keys present at those ranks. - If key(s) are to Player(s) then it and returns the corresponding index(es)/rank(s).
Parameters
- keyUnion[int, List[int], Player, List[Player]]
Accessor to the Elements to delete.
Returns
- Union[Player, List[Player], int, List[int]]
The corresping alternative keys.
- rstt.ranking.standing.remove(self, key: int | List[int] | SPlayer | List[SPlayer]) SPlayer | List[SPlayer] | int | List[int]
Remove item method
Works as Standing.pop() but without return values.
Parameters
- keyUnion[int, List[int], Player, List[Player]]
Accessor of items to delete
- rstt.ranking.standing.rerank(self, permutation: List[int], inverse: bool = False)
Create a new Standing with a different ordering of its keys.
Create a new Standing where key have different value associated. Key at index ‘i’ will have the value of the Key at index permutation[i].
Parameters
- permutationList[int]
a permutation
- inversebool, optional
Wether permutation should be interpreted directly, or as its inverse funtion. If inverse is True then Key at index permutation[i] will have the value of Key at index i , by default False.
Returns
- Standing
A rearranged ordering of the keys.
- rstt.ranking.standing.set_sort(func: Callable[[...], Any]) Callable[[...], Any][source]
Sorting Set Decorator
Decorator for Standing methods. It ensures that contained element (Players) are sorted in descending order of their associated values.
Parameters
- funcCallable[…, Any]
A standing method that can alter the sorting order
Returns
- Callable[…, Any]
A function that enforces the correct standing ordering.
- rstt.ranking.standing.set_sorting(self, sorting: bool | None = None, protocol: str | None = None)
Set the ordering properties of the Standing
Control the internal mechanism. How/When the Standing handle the data and the sorting calls.
Parameters
- sortingbool, optional
Define wether the Standing should be sorted or not, by default None.
True: the Standing will sorts itself automaticly upon future method calls.
False: the Standing will not sorts itself.
None: the current behaviour is maintained.
- protocolstr, optional
Define which sorting stategy is used, by default None
‘get’: An unsorted Standing will be ‘updated’ upon a query on its state (keys(), values(), plot(), …).
‘set’: An unsorted Standing will be ‘updated’ upon a modification of its state (add(), insert(), …)
‘always’: An unsorted Standing will be updated at every opportunity.
None: the current strategy is maintained.
Warning
This method should only be used to optimize code performance when needed and by user aware of the consequences. Here some advice:
protocol=’get’ when a portion of code is slow and performs a lot of ‘set-operations’.
protocol=’set’ when a portion of code is slow and performs a lot of ‘get-operations’.
protocol=’always’ anytime performances are not an issue.
protocol=’never’ the standing stops ordering itself automaticaly.
sorting=False when the order of the keys in the Standing do not matter.
- rstt.ranking.standing.value(self, key: SPlayer | int) float
Get value for a single key
Return the value associated to the key in the Standing. The key can be a index/rank or an element of the Standing
Parameters
- keyUnion[Player, int]
A key to get the value, either the index or the actual element contained in the Standing
Returns
- float
The associated value to the key.
Module contents
Modules for ranking purposes
- class rstt.ranking.BTRanking(name: str = '', players: list[SPlayer] | None = None)[source]
Bases:
RankingConsensus Ranking For the Bradley-Terry Model
Ranking based on the player’s level() method. This also work for Time varying player, inherited class from
rstt.player.playerTVS.PlayerTVS, But it needs to be updated manually everytime player’s level is updated.Attributes
datamodel:
rstt.ranking.datamodel.KeyModel(float as rating type) backend:rstt.ranking.inferer.PlayerLevelhandler:rstt.ranking.observer.PlayerCheckerParameters
- namestr, optional
A name to identify the ranking, by default ‘’
- players_type_, optional
SPlayer to add to the ranking, by default None
Warning
BTRanking validity is limited to Bradley-Terry like models and is not suited for simulation using ‘None-transitive’ level.
- class rstt.ranking.BasicElo(name: str, default: float = 1500, k: float = 20.0, lc: float = 400.0, base: float = 10.0, players: list[SPlayer] | None = None)[source]
Bases:
RankingSimple Elo System
Attributes
datamodel:
rstt.ranking.datamodel.KeyModel(float as rating type) backend:rstt.ranking.inferer.elo.Elohandler:rstt.ranking.observer.GameByGameParameters
- namestr, optional
A name to identify the ranking, by default ‘’
- defaultfloat, optional
Datamodel parameter, a default elo rating, by default 1500.0
- kfloat, optional
Backend parameter, the K value, by default 20.0
- lcfloat, optional
Backend parameter, constant dividing the ratings difference in the expected score formula , by default 400.0
- playersOptional[List[SPlayer]], optional
Players to register in the ranking, by default None
- class rstt.ranking.BasicGlicko(name: str, mu: float = 1500.0, sigma: float = 350.0, minRD: float = 30.0, maxRD: float = 350.0, c: float = 63.2, q: float = 0.005756462732485115, lc: int = 400, players: list[SPlayer] | None = None)[source]
Bases:
RankingSimple Glicko system
Implement A glicko rating system as originaly proposed.
Note
As recommanded in the source paper, the update() method starts by adjusting each players rating before processing any game data (sort of a rating decay)
Attributes
datamodel:
rstt.ranking.datamodel.GaussianModel(rstt.ranking.rating.GlickoRating as rating) backend: :class:`rstt.ranking.inferer.Glickoas backend handlerrstt.ranking.observer.BatchGameas handlerParameters
- namestr, optional
A name to identify the ranking, by default ‘’
- handler_type_, optional
Backend as parameter, by default BatchGame() The original recommendation is to update the ranking by grouping matches within rating period. Which is what the BatchGame Observer do, (each update call represent one period). To match other glicko, use A GameByGame observer
- mufloat, optional
Datamodel parameter, the default mu of the rating, by default 1500.0
- sigmafloat, optional
Datamodel parameter, the default sigma of the rating, by default 350.0
- playersOptional[List[SPlayer]], optional
Players to register in the ranking, by default None
- forward(*args, **kwargs)[source]
Internal ‘update’ function
This method calls the handler
rstt.stypes.handle_observations()with the parameters of the update function.Note
FOR RANKING DESIGNER ONLY method designed for devellopers who wants to modify the ranking.update function’s behavivous. In most cases, it is sufficient to write an apropriate observer as the ranking.handler.
However, sometimes it is relevant to do some ranking preprocessing before any rating updates. This would not always be possible to do inside the handle_observations method as the observer do not have access to all ranking attributes.
- class rstt.ranking.BasicOS(name: str, model=None, players: list[SPlayer] | None = None)[source]
Bases:
RankingSimple OpenSkill Integretion
Ranking to integrate an openskill model into the rstt package.
Attributes
datamodel:
rstt.ranking.datamodel.GaussianModel(openskill.models.rating as rating type) backend: an openskill model instance handler:rstt.ranking.standard.BasicOs.OSGBG, which behaves as a GameByGame observerParameters
- namestr, optional
A name to identify the ranking, by default ‘’
- modelopenskills.models
One of openskills.models implementation, by default None
- playersOptional[List[SPlayer]], optional
Players to register in the ranking, by default None
Example:
1from rstt import Player, BasicOS 2from openskill.models import PlackettLuce 3 4competitors = Player.create(nb=10) 5pl = BasicOS(name='Plackett-Luce', model= PlackettLuce(), players=competitors) 6pl.plot()
- class rstt.ranking.BatchGame[source]
Bases:
ObsTemplateAll Matches at once updating procedure
Alternative to the
rstt.ranking.observer.GamebyGameobserver. Some rating system, like Elo and Glicko support updates where all matches are considered at once for the rating update.In this workflows, ratings are stored after all matches have been processed. Every computation is performed using the prior ratings (i.e the one stored in the datamodel before the method call)
Observations
- gameSMatch, optional
a game justifying a ranking update, by default None
- gameslist[SMatch], optional
a list of games, by default None
- eventEvent, optional
the observer uses Event.games() to extract the observations, by defualt None
- events: list[Event], optional
a list of Event, by default None
Datamodel
- Rating: any
Game based observers make no assumption on ratings type.
Inferer.rate
teams : list[list[SPlayer]] scores : list[float] ratings_groups : list[list[any]]
- class rstt.ranking.Elo(k: float = 20.0, lc: float = 400.0, base: float = 10.0)[source]
Bases:
objectEo Inferer
Simple implementation based on wikipedia
Parameters
- kfloat, optional
The K-factor, by default 20.0
- lcfloat, optional
The constant dividing the ratings difference in the expected score formula, by default 400.0.
- expectedScore(rating1: float, rating2: float) float[source]
Compute the expected score
Parameters
- rating1float
a rating
- rating2float
another rating
Returns
- float
expected result of the player with rating1 against the player with rating2
- post_rating(prior_rating: float, ratings_opponents: list[float], scores: list[float])[source]
Update the rating of a player given a list of opponent’s ratings and corresponding scores against.
Parameters
- prior_ratingfloat
a rating to update
- ratings_opponentslist[float]
opponent’s ratings
- scoreslist[float]
scores associated to the prior_rating
Returns
- float
post rating
- rate(rating_groups: list[list[float]], scores: list[float], *args, **kwars) list[list[float]][source]
Rate method for elo
Parameters
- rating_groupsList[List[float]]
Elo ratings formated by teams, for example [[elo_player1], [elo_player2]].
- scoresList[float]
corresponding scores of the ratings, for example [[1.0],[0.0]] assuming player1 won the duel.
Returns
- List[List[float]]
updated ratings in the formats [[new_elo1][new_elo2]]
- class rstt.ranking.EventScoring(window_range: int = 1, tops: int = 1, default: dict[int, float] = {})[source]
Bases:
object
- class rstt.ranking.GameByGame[source]
Bases:
ObsTemplateGame by Game updating Procedure
Implementing an iterative approach where each observations triggers the entire updating workflows. In particular, new ratings are stored inbetween of each iterations, and the prior ones are lost.
Observations
- gameSMatch, optional
a game justifying a ranking update, by default None
- gameslist[SMatch], optional
a list of games, by default None
- eventEvent, optional
the observer uses Event.games() to extract the observations, by defualt None
- events: list[Event], optional
a list of Event, by default None
Datamodel
- Rating: any
Game based observers make no assumption on ratings type.
Inferer.rate
teams : list[list[SPlayer]] scores : list[float] ranks : list[float] ratings_groups : list[list[any]]
- class rstt.ranking.GaussianModel(*arg, **kwargs)[source]
Bases:
KeyModelGaussian Rating Systems
Associated ratings must have a mu and a sigma attributes.
- class rstt.ranking.Glicko(minRD: float = 30.0, maxRD: float = 350.0, c: float = 63.2, q: float = 0.005756462732485115, lc: int = 400)[source]
Bases:
objectGlicko Inferer
The Glicko rating system is often described as an improvement of
rstt.ranking.inferer.Elo. here, the implementation is based on Dr. Mark E. Glickman description.Note
The source paper gives more instruction (notion of rating period) than what an Inferer class should do in RSTT. Step1, for example is implemented by the
rstt.ranking.standard.BasicGlickobecause it is related to the usage of the system, rather than what the Inferer does.Warning
There is no type-checker support for ‘Glicko ratings’. In the documentation we use the typehint ‘GlickoRating’. Anything with a public mu and sigma attribute fits the bill.
Parameters
- minRDfloat, optional
minimal value of RD, by default 30.0
- maxRDfloat, optional
maximal value of RD, by default 350.0
- cfloat, optional
constant used for ‘inactivity decay’, by default 63.2
- qfloat, optional
No idea what it represent, feel free to play arround, by default math.log(10, math.e)/400
- lcint, optional
Logistic constant similar to the one in
rstt.rnaking.inferer.Elo, by default 400
- G(rd: float) float[source]
_summary_
Implements: page 3, step2, g(RD) formula.
Parameters
- rdfloat
the RD of a rating
Returns
- float
g(RD)
- d2(rating1, games: list[tuple[Any, float]]) float[source]
Implements: page 4, d^2 formula.
Parameters
- rating1GlickoRating
the main rating
- gamesList[Tuple[GlickoRating, float]]
A list of [opponent_rating, score_of_rating1]
Returns
- float
the d2 value
Warns
Rarely a ZeroDivisionError occurs. In this case, the warning contains all the computational information. Execution continues using a very small value instead.
- expectedScore(rating1, rating2, update: bool = True) float[source]
Compute the expected score
Implements: page 4, E(s|r,rj,RDj) when update=True or page 5, E otherwise.
Parameters
- rating1GlickoRating
‘main’ rating
- rating2GlickoRating
opponents rating
- updatebool, optional
Wheter to use the formula for update or not, by default True.
Returns
- float
The expected score of the player with rating1 against player with rating2
- newRating(rating1, games: list[tuple[Any, float]])[source]
Rating Update method
Implements: page 3, step2.
Parameters
- rating1GlickoRating
a rating to update.
- gamesList[Tuple[GlickoRating, float]]
A list of results formated under as [opponent_rating, score_of rating1]
Returns
- GlickoRating
the new updated rating
- prePeriod_RD(rating: Any) float[source]
pre update RD value
Implements: page 3, step1, formula (b).
Parameters
- ratingGlickoRating
A rating to ‘pre-update’
Returns
- float
the new RD value of the rating.
- rate(rating, ratings_opponents: list[Any], scores: list[float], *args, **kwars)[source]
Glicko rate method
End to end method to compute a new glicko rating based on a collection of results
Parameters
- ratingGlickoRating
the rating to update
- ratingsList[GlickoRating]
list of opponent ratings
- scoresList[float]
list of score achieved by rating1 against the ‘ratings’ opponents, in the same order
Returns
- GlickoRating
The new rating.
- class rstt.ranking.KeyModel(default: Any | None = None, template: Callable | None = None, factory: Callable | None = None, **kwargs)[source]
Bases:
objectBasic Rating system
The KeyModel is a intuitive implementation of
rstt.stypes.RatingSystemthat strores ratings of player in a defauldict. The default rating value can be specified in three different fashions.Parameters
- defaultAny, optional
A default rating value, by default None.
- templateCallable, optional
A lambda function to generate default ratings, by default None
- factory_type_, optional
A Callable of the form lambda x: …, where x is the SPlayer with no rating, by default None. If you pass a factory, the KeyModel stores ratings in a
rstt.ranking.datamodel.keydefauldict.
Note
If you are using the 'template' or 'factory', you can additionaly specify **kwargs to be passed to the template every time it is called to generate a new rating. And for the 'default', no additonal parameters are allowed.
Raises
- ValueError
Error are raised in the case of incompatible parameters. Examples of valid calls are: KeyModel(default=1500) KeyModel(template=GaussianRating, 1500, 250) KeyModel(factory=GaussianRating, mu=1500, sigma=250)
- default() Any[source]
Getter for default rating
When instanciated, a default rating is generated. In the case of a ‘factory’ instanciation, the default rating is built with the help of a ‘Dummy’
rstt.player.basicplayer.BasicPlayerReturns
- Any
The default rating an unrank player gets.
- get(key: SPlayer) Any[source]
getter method for the rating of a player
Parameters
- keySPlayer
A player to get the rating
Returns
- Any
The rating of the player
- items()[source]
Dict like items() method
return the view object returned by the underlying dict.items method
Returns
- view object
items stored in the KeyModel
- keys()[source]
Dict like keys() method
return the view object returned by the underlying dict.keys method
Returns
- view object
keys, i.e. SPlayer.
- ordinal(rating: Any) float[source]
Convert a rating into a float value
The returned value is used to compare players to each other. An higher value is understood as a ‘better’ player
Note
This method assume the existence of a magic __float__ method for the ratings. If one uses custom ratings object, it is good to either write such method, override the ordinal methods, or design an associated
rstt.stypes.RatingSystem.Parameters
- ratingAny
A rating compatible with the KeyModel.rtypes()
Returns
- float
The corresponding value used to compare players in an ordered fashion.
- rtype() type[source]
Getter for the rating type
Warning
The type of ratings is infered at instanciation of the KeyModel using the type() built-in functions. However this can be inconsistant with the user’s intention.
Returns
- type
The rating type.
- set(key: SPlayer, rating)[source]
Set method to manualy assign a rating to a player.
Parameters
- keySPlayer
A Player to modify the rating
- ratingAny
a new rating.
Warning
The KeyModel class is a ‘Generic’ container in the sense that it can store any sort of rating, however, all values must be of the same type. With the current implementation it is unclear how to enforce it. So it is the responsability of the user to be consistent.
The set operation will not throw any error. Yet, following calls to
rstt.ranking.datamodel.KeyModel.ordinal()ordinal method could fail without proper error traceback.Hopefull future version will fix this issue.
- class rstt.ranking.NoHandling[source]
Bases:
ObsTemplate- Exclude-members:
- class rstt.ranking.PlayerChecker[source]
Bases:
ObsTemplateUpdate Procedure based on Player’s data
Iterate over a list of SPlayer, each triggering a inferer.rate() call and the new ratings are instantly pushed in the datamodel. The assumption is that the player instance itself contains all the necessary informations to compute a rating.
Caution
Prior ratings, stored in the datamodel, are ignored and not passed to the inferer. The output of the inferer.rate defines the post ratings, which can introduce inconsistency in rating type for the datamodel.
Observations
- playerSMatch, optional
a game justifying a ranking update, by default None
- playerslist[SMatch], optional
a list of games, by default None
- teamEvent, optional
the observer uses Event.games() to extract the observations, by defualt None
- teamslist[Event], optional
a list of Event, by default None
- eventEvent, optional
the observer uses Event.games() to extract the observations, by defualt None
- events: list[Event], optional
a list of Event, by default None
Datamodel
- Rating: any
Game based observers make no assumption on ratings type.
Inferer.rate
player: SPlayer
- class rstt.ranking.PlayerWinPRC(default: float = -1.0, scope: int = 2147483647)[source]
Bases:
objectInferer based on Player win rate
Parameters
- defaultfloat, optional
A rating for when no game was yet played, by default -1.0
- scopeint, optional
The number of game to consider, starting from the most recent one, by default np.iinfo(np.int32).max.
- class rstt.ranking.Ranking(name: str, datamodel: RatingSystem, backend: Inference, handler: Observer, players: List[SPlayer] | None = None)[source]
Bases:
objectRanking for players
The rstt package implements its own definition of a ranking.
Formally an rstt ranking consist of a
A standing: An ordered sequence of players associated with an indication of their skills.
A rating system - storing player’s rating.
A statistical inference system - set of equations.
An update procedure
And two ‘hidden’ notions:
Observables: the set of ‘update triggers’ justifying a change of ratings. (what can be processed by the handler)
An ordinal function converting rating into float values (provided by the rating system)
Parameters
- namestr
A name to identify the ranking
- datamodelRatingSystem
A container storing rating of players and providing an orinal() funtion to convert rating into floating values.
- backendInference
The ‘math’ behind the ranking system.
- handlerObserver
A workflow handling the ranking update procedure
- playersOptional[List[SPlayer]], optional
Players to register in the ranking, by default None
- forward(*args, **kwargs)[source]
Internal ‘update’ function
This method calls the handler
rstt.stypes.handle_observations()with the parameters of the update function.Note
FOR RANKING DESIGNER ONLY method designed for devellopers who wants to modify the ranking.update function’s behavivous. In most cases, it is sufficient to write an apropriate observer as the ranking.handler.
However, sometimes it is relevant to do some ranking preprocessing before any rating updates. This would not always be possible to do inside the handle_observations method as the observer do not have access to all ranking attributes.
- players() List[SPlayer][source]
Get method of all keys
Alias for Ranking.standing.keys()
Returns
- List[Player]
A list of all player in descending order of their associated values.
- point(player: SPlayer) float[source]
Get the point associated to a key
Alias for Ranking.standing.value(player)
Returns
- float
the associated value.
- points() List[float][source]
Get method of all values
Alias for Ranking.standing.values()
Returns
- List[float]
A list of all associated values in descending order.
- rank(player: SPlayer) int[source]
Getter for player Rank
Equivalent to ranking.standing[player].
Parameters
- playerSPlayer
A player to get his rank.
Returns
- int
The rank of the player
- ranks(players: List[SPlayer]) List[int][source]
Getter for players Rank
Equivalent to ranking.standing[players].
Parameters
- playersSPlayer
Player to get their ranks.
Returns
- List[int]
The corresponding ranks of the players
- rating(player: SPlayer) Any[source]
Get method for rating
Rating object is the internal model associated to a key. Ratings are used to automaticly compute values for the sorting feature of a Standing.
Parameters
- playerPlayer
A key in the Ranking
Returns
- Any
The associated model to the provided key. The type is defined by Ranking.RatingSystem.rtype
Raises
KeyError
- class rstt.ranking.Standing(default: float = 0.0, lower: float = -2147483648, upper: float = 2147483647, step: float = 1.0, protocol: str = 'set')[source]
Bases:
objectA Standing object emulate a value-based ordered dictionary.
- The Standing also act as a <list> and a <dict> and the following relationship exist:
Index -> Key
Key -> Index
Keys oredring is descedning and based on the associated value of the key, i.e Standing.point(key).
The key ordering is maintain by internal mechanism as long as the Standing is manipulate with the provided methods and functionnalities.
Examples
Note
Ordering is computationaly demanding, which means that repeated operations on a large Standing could result in performances issues. It is possible to turn off the ordering features. This break the whole point of the class. Do it only if needed and if you know what your are doing
In its current form Key are intended to be of Type <Player> and Value of type <float>. This may change in the future to support a more general case such as: Key of type <Hasable> -> Value of type <Comarapble>.
Parameters
- defaultfloat, optional
A key added to the standing without an associated value will be assign this default value, by default 0.0
- minfloat, optional
The minimal boundary for values, by default np.iinfo(np.int32).min
- maxfloat, optional
The maximal boundary for values, by default np.iinfo(np.int32).max
- stepfloat, optional
An interval used for insertion operation , by default 1.0 NOTE: not completely supported, could disapear in futur version.
- fit(keys: List[SPlayer])[source]
Create a new Standing instance containing only the given Keys
The Keys will have the same value as in the current Standing if present otherwise the default value will be assigned.
Parameters
- keysList[Player]
list of <Player> to be present in the new Standing
Returns
Standing
- class rstt.ranking.SuccessRanking(name: str, window_range: int = 1, tops: int = 1, buffer: int | None = None, nb: int | None = None, players: list[SPlayer] | None = None, default: dict[int, float] | None = None)[source]
Bases:
RankingMerit Based Ranking
Usefull to implement Ranking system like the one in tennis for example.
Attributes
datamodel:
rstt.ranking.datamodel.KeyModel(int as rating) backend:rstt.ranking.inferer.EventScoringhandler:rstt.ranking.observer.PlayerCheckerParameters
- namestr, optional
A name to identify the ranking, by default ‘’
- bufferint
Backend parameter. The number of event to consider for the rating, starting from the last.
- nbint
Backend parameter. The actual number of event in the buffer to use for the ratings computation.
- defaultOptional[Dict[int, float]], optional
Backend Parameter. Mapping placement in event to points for the rating, by default None
- playersOptional[List[SPlayer]], optional
Players to register in the ranking, by default None
- forward(event: Event | None = None, events: list[Event] | None = None)[source]
Internal ‘update’ function
This method calls the handler
rstt.stypes.handle_observations()with the parameters of the update function.Note
FOR RANKING DESIGNER ONLY method designed for devellopers who wants to modify the ranking.update function’s behavivous. In most cases, it is sufficient to write an apropriate observer as the ranking.handler.
However, sometimes it is relevant to do some ranking preprocessing before any rating updates. This would not always be possible to do inside the handle_observations method as the observer do not have access to all ranking attributes.
- class rstt.ranking.WinRate(name: str, default: float = -1.0, scope: int = 2147483647, players: list[SPlayer] | None = None)[source]
Bases:
RankingRanking based on Win rate
Ranking that tracks the winrate of
rstt.player.player.Player. The update function does not take any parameters, win rate is computed directly with the player’s game history.Attributes
datamodel
rstt.ranking.datamodel.KeyModel(float as rating) backendrstt.ranking.inferer.PlayerWinPRChandlerrstt.ranking.observer.PlayerCheckerParameters
- namestr, optional
A name to identify the ranking, by default ‘’
- defaultfloat, optional
A default rating value for when player have no game in their history, by default -1.0
- playersOptional[List[SPlayer]], optional
Players to register in the ranking, by default None
- forward(*args, **kwargs)[source]
Internal ‘update’ function
This method calls the handler
rstt.stypes.handle_observations()with the parameters of the update function.Note
FOR RANKING DESIGNER ONLY method designed for devellopers who wants to modify the ranking.update function’s behavivous. In most cases, it is sufficient to write an apropriate observer as the ranking.handler.
However, sometimes it is relevant to do some ranking preprocessing before any rating updates. This would not always be possible to do inside the handle_observations method as the observer do not have access to all ranking attributes.