Skip to content
This repository has been archived by the owner on Sep 6, 2024. It is now read-only.

Commit

Permalink
feat(lab05): initial
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexey N. Alexandrov authored and Alexey N. Alexandrov committed Apr 29, 2024
1 parent b541fec commit 46ba9ab
Show file tree
Hide file tree
Showing 5 changed files with 210 additions and 0 deletions.
Empty file.
149 changes: 149 additions & 0 deletions game_theory/05-lab-sheply_method/cooperative_sheply_method.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
{
"cells": [
{
"metadata": {},
"cell_type": "markdown",
"source": [
"# Лабораторная работа №5\n",
"### \"РАЦИОНАЛЬНЫЙ ДЕЛЕЖ В КООПЕРАТИВНЫХ ИГРАХ: метод Шепли\"\n",
"\n",
"**Вариант:** 1\n",
"\n",
"**Цель работы:** изучить постановку кооперативной игры и найти оптимальное распределение выигрыша (дележ) между игроками путем вычисления компонент вектора Шепли."
],
"id": "85dad192f02ac695"
},
{
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-29T09:50:41.751274Z",
"start_time": "2024-04-29T09:50:41.742248Z"
}
},
"cell_type": "code",
"source": "from utils.cooperative.sheply import CooperativeGame",
"id": "292e0bcb178da52b",
"outputs": [],
"execution_count": 57
},
{
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-29T09:50:42.212391Z",
"start_time": "2024-04-29T09:50:42.209470Z"
}
},
"cell_type": "code",
"source": [
"# Number of players.\n",
"N = 4\n",
"# Characteristic function values in combination order.\n",
"CHAR_VALUES = (0, 4, 1, 3, 1, 6, 8, 6, 5, 3, 5, 9, 8, 10, 7, 11)"
],
"id": "b77a2c954e11d9e5",
"outputs": [],
"execution_count": 58
},
{
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-29T09:50:42.608222Z",
"start_time": "2024-04-29T09:50:42.605794Z"
}
},
"cell_type": "code",
"source": "coop_game = CooperativeGame(N, CHAR_VALUES)",
"id": "6cfef43397783d7",
"outputs": [],
"execution_count": 59
},
{
"metadata": {},
"cell_type": "markdown",
"source": [
"### 1. Проверка игры на супераддитивность и выпуклость\n",
"\n",
"__Опр.__ Кооперативная игра называется **супераддитивной**, если\n",
"$$\\forall S,T \\subseteq I(S \\cap T = \\varnothing): v(S \\cup T) \\leq v(S) + v(T).$$"
],
"id": "14d088dd70b41d59"
},
{
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-29T09:50:43.623616Z",
"start_time": "2024-04-29T09:50:43.620480Z"
}
},
"cell_type": "code",
"source": "coop_game.is_superadditive_game()",
"id": "a114e428e8e7f454",
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 60,
"metadata": {},
"output_type": "execute_result"
}
],
"execution_count": 60
},
{
"metadata": {
"ExecuteTime": {
"end_time": "2024-04-29T09:50:51.723383Z",
"start_time": "2024-04-29T09:50:51.716445Z"
}
},
"cell_type": "code",
"source": "coop_game.is_convex()",
"id": "8d3f1023628ffc42",
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 61,
"metadata": {},
"output_type": "execute_result"
}
],
"execution_count": 61
},
{
"metadata": {},
"cell_type": "code",
"outputs": [],
"execution_count": null,
"source": "",
"id": "8366aaf0c2b29830"
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Empty file.
54 changes: 54 additions & 0 deletions game_theory/utils/cooperative/sheply.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
from itertools import combinations
from typing import Generator

from .types import Coalition, SizeType, ValueType


class CooperativeGame:
def __init__(self, players_count: SizeType, char_values: tuple[ValueType, ...]) -> None:
if len(char_values) != (coalitions_count := 2**players_count):
err_msg = (
f"The `char_values` length must be equal to "
f"`2 ^ players_count = {coalitions_count}` but got {len(char_values)} instead"
)
raise ValueError(err_msg)

self.players_count: SizeType = players_count
# Characteristic function mapping coalition to characteristic function value.
self.__char_mapping: dict[Coalition, ValueType] = dict(zip(self.coalitions_generator, char_values))

def char_function(self, coalition: Coalition) -> ValueType:
return self.__char_mapping[coalition]

@property
def coalitions_generator(self) -> Generator[Coalition, None, None]:
"""Generates all combinations from Ø to total coalition in standard order."""
player_labels = tuple(range(1, self.players_count + 1))
yield from (coalition for k in range(self.players_count + 1) for coalition in combinations(player_labels, k))

@property
def coalitions_pairs_generator(self) -> Generator[tuple[Coalition, Coalition], None, None]:
yield from (coalition_pair for coalition_pair in combinations(self.coalitions_generator, 2))

def is_superadditive_game(self) -> bool:
v = self.char_function
return all(
(
v(tuple(first_subset | second_subset)) >= v(first_subcoalition) + v(second_subcoalition)
for first_subcoalition, second_subcoalition in self.coalitions_pairs_generator
# `first_subcoalition` and `second_subcoalition` are disjoint.
if not ((first_subset := set(first_subcoalition)) & (second_subset := set(second_subcoalition)))
)
)

def is_convex(self) -> bool:
v = self.char_function
return all(
(
v(tuple(first_subset | second_subset)) + v(tuple(first_subset & second_subset))
>= v(first_subcoalition) + v(second_subcoalition)
for first_subcoalition, second_subcoalition in self.coalitions_pairs_generator
if (first_subset := set(first_subcoalition))
if (second_subset := set(second_subcoalition))
)
)
7 changes: 7 additions & 0 deletions game_theory/utils/cooperative/types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from typing import Annotated, TypeAlias

from annotated_types import Gt

Coalition: TypeAlias = tuple[int, ...]
SizeType: TypeAlias = Annotated[int, Gt(0)]
ValueType: TypeAlias = int

0 comments on commit 46ba9ab

Please sign in to comment.