balanced-group-system 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Joshua Si
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.
@@ -0,0 +1,13 @@
1
+ Metadata-Version: 2.3
2
+ Name: balanced-group-system
3
+ Version: 0.1.0
4
+ Summary: A management system to create balanced groups of participants
5
+ Author: Joshua Si
6
+ Author-email: josh.j.si@proton.me
7
+ Requires-Python: >=3.9.0,<4.0.0
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.9
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
@@ -0,0 +1,3 @@
1
+ from .group_system import GroupSystem
2
+ from .balanced_group_system import BalancedGroupSystem
3
+ from .available_group_scheduler import AvailableGroupScheduler
@@ -0,0 +1,88 @@
1
+ import random
2
+ from . import group_system
3
+
4
+ """
5
+ AvailableGroupScheduler.py
6
+
7
+ This module contains a subclass of GroupScheduler that creates groups based on the
8
+ familiarity matrix and takes into account member availability. It creates groups
9
+ in such a way that members meet as many new members as possible and minimize
10
+ repeat meetings.
11
+
12
+ Author: Joshua Si
13
+ """
14
+
15
+ class AvailableGroupScheduler(group_system.GroupSystem):
16
+ def __init__(self, members: list[str] = [], availability_schedules: list[list[bool]] = []):
17
+ super().__init__(members)
18
+ self.familiarity_matrix: dict[frozenset[tuple[str, str]], int] = {frozenset((self.members[i], self.members[j])) : 0 for i in range(len(self.members)) for j in range(i+1, len(self.members))}
19
+ self.participation_count: dict[int] = {member: 0 for member in self.members}
20
+ if len(availability_schedules) == 0:
21
+ self.availability_schedules: list[list[bool]] = [[True for _ in range(len(members))]]
22
+ else:
23
+ self.availability_schedules: list[list[bool]] = availability_schedules
24
+
25
+ def add_schedule(self, availability: list[bool]) -> None:
26
+ self.availability_schedules.append(availability)
27
+
28
+ def update_participation(self, group: set[str]) -> None:
29
+ for member in group:
30
+ self.participation_count[member] += 1
31
+ for m in group:
32
+ if member != m:
33
+ self.familiarity_matrix[frozenset((member, m))] += 1
34
+
35
+ def create_balanced_schedules(self, group_size: int) -> list[set[str]]:
36
+ self.familiarity_matrix: dict[frozenset[tuple[str, str]], int] = {frozenset((self.members[i], self.members[j])) : 0 for i in range(len(self.members)) for j in range(i+1, len(self.members))}
37
+ self.participation_count: dict[int] = {member: 0 for member in self.members}
38
+ schedules = []
39
+ for availability in range(len(self.availability_schedules)):
40
+ candidates = set(member for member, avail in zip(self.members, self.availability_schedules[availability]) if avail)
41
+ # if less candidates than desired group_size, put all possible candidates in the group
42
+ if len(candidates) < group_size:
43
+ schedules.append(candidates)
44
+ continue
45
+ # otherwise filter for those who have participated the least to maximize new members
46
+ min_threshold = min(self.participation_count[member] for member in candidates)
47
+ min_participation_candidates = set(member for member in candidates if self.participation_count[member] == min_threshold)
48
+ if len(min_participation_candidates) > group_size:
49
+ # now select based on familiarity matrix
50
+ group = self.get_balanced_group(min_participation_candidates, set(), group_size)
51
+ schedules.append(group)
52
+ self.update_participation(group)
53
+ else:
54
+ candidates = set(member for member in candidates if member not in min_participation_candidates)
55
+ min_threshold += 1
56
+ new_candidates = set(member for member in candidates if self.participation_count[member] == min_threshold)
57
+ while len(min_participation_candidates) + len(new_candidates) < group_size:
58
+ min_participation_candidates = min_participation_candidates | new_candidates
59
+ min_threshold += 1
60
+ new_candidates = set(member for member in candidates if self.participation_count[member] == min_threshold)
61
+ group = self.get_balanced_group(new_candidates, min_participation_candidates, group_size)
62
+ schedules.append(group)
63
+ self.update_participation(group)
64
+ return schedules
65
+
66
+ # returns group of size group_size, consisting of existing members and adding from candidates based on familiarity
67
+ def get_balanced_group(self, candidates: set[str], existing: set[str], group_size: int) -> set[str]:
68
+ group = existing
69
+ scores = {frozenset(group): 0}
70
+ # Memoized version of evaluate_group for evaluating score when adding one member
71
+ def evaluate_member(group: set[str], member: str) -> int:
72
+ group_key = frozenset(group)
73
+ new_key = frozenset(group | {member})
74
+ if new_key in scores:
75
+ return scores[new_key]
76
+ score = scores[group_key]
77
+ for m in group:
78
+ score += self.familiarity_matrix[frozenset((m, member))]
79
+ scores[new_key] = score + 1
80
+ return score + 1
81
+
82
+ # Balance and distribute members
83
+ while len(group) < group_size and len(candidates) > 0:
84
+ min_candidate = min(candidates, key=lambda c: evaluate_member(group, c))
85
+ group.add(min_candidate)
86
+ candidates.remove(min_candidate)
87
+
88
+ return group
@@ -0,0 +1,95 @@
1
+ import random
2
+ from . import group_system
3
+
4
+ """
5
+ BalancedGroupSystem.py
6
+
7
+ This module contains a subclass of GroupSystem that creates balanced groups based on the familiarity matrix.
8
+ It creates groups in such a way that members meet as many new members as possible and minimize repeat meetings.
9
+
10
+ Author: Joshua Si
11
+ """
12
+
13
+ class BalancedGroupSystem(group_system.GroupSystem):
14
+ def __init__(self, members: list[str] = []):
15
+ super().__init__(members)
16
+ self.familiarity_matrix: dict[frozenset[tuple[str, str]], int] = {
17
+ frozenset((self.members[i], self.members[j])) : 0
18
+ for i in range(len(self.members))
19
+ for j in range(i+1, len(self.members))
20
+ }
21
+
22
+ def __repr__(self) -> str:
23
+ return f"BalancedGroupSystem({self.members})"
24
+
25
+ def add_member(self, member: str) -> None:
26
+ super().add_member(member)
27
+ for i in range(len(self.members)-1):
28
+ self.familiarity_matrix[frozenset((self.members[i], member))] = 0
29
+
30
+ def remove_member(self, member: str) -> None:
31
+ try:
32
+ super().remove_member(member)
33
+ for m in self.members:
34
+ self.familiarity_matrix.pop(frozenset((m, member)))
35
+ except ValueError:
36
+ raise ValueError("Member '{}' was not in members".format(member))
37
+
38
+ def create_groups(self, groups: list[set[str]]) -> list[set[str]]:
39
+ super().create_groups(groups)
40
+ for group in groups:
41
+ self.__update_familiarity(group)
42
+ return groups
43
+
44
+ def print_familiarity(self) -> None:
45
+ for i in self.members:
46
+ print(i, end=' ')
47
+ print()
48
+ for i in self.members:
49
+ print(i, end=' ')
50
+ for j in self.members:
51
+ if i == j:
52
+ print('-', end=' ')
53
+ else:
54
+ print(self.familiarity_matrix[frozenset((i, j))], end=' ')
55
+ print()
56
+
57
+ def evaluate_group(self, group: set[str]) -> int:
58
+ score = 0
59
+ pairs = ((i, j) for i in group for j in group if i != j)
60
+ score = sum(self.familiarity_matrix[frozenset(pair)] for pair in pairs)
61
+ return score
62
+
63
+ def __update_familiarity(self, group: set[str]) -> None:
64
+ pairs = ((i, j) for i in group for j in group if i != j)
65
+ for pair in pairs:
66
+ self.familiarity_matrix[frozenset(pair)] += 1
67
+
68
+ # Calculate balanced groups by trying to minimize score when choosing which group to add each member to
69
+ def __calculate_balanced_groups(self, group_count: int, members: list[str] = [], verbose: bool = False) -> list[set[str]]:
70
+ random.shuffle(members)
71
+ groups = [set() for _ in range(group_count)]
72
+ scores = {(): 0}
73
+ # Memoized version of evaluate_group for evaluating score when adding one member
74
+ def evaluate_member(group: set[str], member: str) -> int:
75
+ new_group: set[str] = group | {member}
76
+ if frozenset(new_group) in scores:
77
+ return scores[frozenset(new_group)]
78
+ score = scores[frozenset(group)] if frozenset(group) in scores else 0
79
+ for i in group:
80
+ score += self.familiarity_matrix[frozenset((i, member))]
81
+ scores[frozenset(new_group)] = score + 2
82
+ return score + 2
83
+
84
+ # Balance and distribute members
85
+ for member in members:
86
+ min_group_index = min(range(group_count), key=lambda i: evaluate_member(groups[i], member))
87
+ groups[min_group_index].add(member)
88
+ if verbose:
89
+ print(groups)
90
+ return groups
91
+
92
+
93
+ def create_balanced_groups(self, group_count: int, verbose: bool = False) -> list[set[str]]:
94
+ groups = self.__calculate_balanced_groups(group_count, self.members.copy(), verbose)
95
+ return self.create_groups(groups)
@@ -0,0 +1,38 @@
1
+ '''
2
+ group_system.py
3
+
4
+ This module contains a class that represents a group system that creates group_list and stores group history.
5
+ '''
6
+
7
+ class GroupSystem:
8
+ def __init__(self, members: list[str] = []):
9
+ self.members: list[str] = members
10
+ self.group_history: list[list[set[str]]] = []
11
+
12
+ def __repr__(self) -> str:
13
+ return f"GroupSystem({self.members})"
14
+
15
+ def print_history(self) -> None:
16
+ for i, group_set in enumerate(self.group_history):
17
+ print(i, ':', group_set)
18
+
19
+ def add_member(self, member: str) -> None:
20
+ self.members.append(member)
21
+
22
+ def remove_member(self, member: str) -> None:
23
+ index = self.members.index(member)
24
+ self.members.pop(index)
25
+
26
+ def create_groups(self, group_list: list[set[str]]) -> None:
27
+ self.group_history.append(group_list)
28
+
29
+ # Slower version of create_groups that validates input
30
+ def create_and_validate_groups(self, group_list: list[set[str]]) -> None:
31
+ member_set = set(self.members)
32
+ for group in group_list:
33
+ for member in group:
34
+ try:
35
+ member_set.remove(member)
36
+ except KeyError:
37
+ raise KeyError("Element '{}' was not in members".format(member))
38
+ self.group_history.append(group_list)
@@ -0,0 +1,18 @@
1
+ [tool.poetry]
2
+ name = "balanced-group-system"
3
+ version = "0.1.0"
4
+ description = "A management system to create balanced groups of participants"
5
+ authors = ["Joshua Si <josh.j.si@proton.me>"]
6
+
7
+ [tool.poetry.dependencies]
8
+ python = "^3.9.0"
9
+
10
+ [tool.poetry.group.test.dependencies]
11
+ pytest = "^6.2.2"
12
+
13
+ [tool.pytest.ini_options]
14
+ testpaths = ["tests"]
15
+
16
+ [build-system]
17
+ requires = ["poetry-core>=1.0.0"]
18
+ build-backend = "poetry.core.masonry.api"