-
Notifications
You must be signed in to change notification settings - Fork 15
/
mechanismfactory.py
278 lines (263 loc) · 10.2 KB
/
mechanismfactory.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Iterable
from negmas.events import Event
from negmas.helpers import exception2str, instantiate
from negmas.helpers.inout import add_records
from negmas.mechanisms import Mechanism
from negmas.negotiators import Negotiator
from negmas.outcomes import Issue, outcome2dict
from .common import PROTOCOL_CLASS_NAME_FIELD, NegotiationInfo
if TYPE_CHECKING:
from .agent import Agent
from .world import World
__all__ = ["MechanismFactory"]
class MechanismFactory:
"""A mechanism creation class. It can invite agents to join a mechanism and then run it."""
def __init__(
self,
world: World,
mechanism_name: str,
mechanism_params: dict[str, Any],
issues: list[Issue],
req_id: str,
caller: Agent,
partners: list[Agent],
roles: list[str] | None = None,
annotation: dict[str, Any] | None = None,
neg_n_steps: int | None = None,
neg_time_limit: int | None = None,
neg_step_time_limit=None,
allow_self_negotiation=False,
log_ufuns_file=None,
group: str | None = None,
):
self.mechanism_name, self.mechanism_params = mechanism_name, mechanism_params
self.caller = caller
self.group = group
self.partners = partners
self.roles = roles
self.annotation = annotation
self.neg_n_steps = neg_n_steps
self.neg_time_limit = neg_time_limit
self.neg_step_time_limit = neg_step_time_limit
self.world = world
self.req_id = req_id
self.issues = issues
self.mechanism = None
self.allow_self_negotiation = allow_self_negotiation
self.log_ufuns_file = log_ufuns_file
def _create_negotiation_session(
self,
mechanism: Mechanism,
responses: Iterable[tuple[Negotiator, str]],
partners: list[Agent],
) -> Mechanism:
for partner in partners:
mechanism.register_listener(event_type="negotiation_end", listener=partner)
ufun = []
if self.log_ufuns_file is not None:
for outcome in mechanism.discrete_outcomes():
record = {
"mechanism_id": mechanism.id,
"outcome": outcome2dict(outcome, mechanism.issues),
}
ufun.append(record)
for i, (partner_, (_negotiator, _role)) in enumerate(zip(partners, responses)):
if self.log_ufuns_file is not None:
for record in ufun:
record[f"agent{i}"] = partner_.name
# record[f"agent_type{i}"] = partner_.type_name
# record[f"negotiator{i}"] = _negotiator.name
record[f"reserved{i}"] = _negotiator.reserved_value
try:
if not _negotiator.ufun:
record[f"u{i}"] = None
else:
record[f"u{i}"] = _negotiator.ufun(record["outcome"])
except Exception:
record[f"u{i}"] = None
_negotiator.owner = partner_
mechanism.add(negotiator=_negotiator, role=_role)
if self.log_ufuns_file is not None:
for record in ufun:
outcome = record.pop("outcome", {})
record.update(outcome)
add_records(self.log_ufuns_file, ufun)
return mechanism
def _start_negotiation(
self,
mechanism_name,
mechanism_params: dict[str, Any],
roles,
caller,
partners,
annotation,
issues,
req_id,
) -> NegotiationInfo | None:
"""Tries to prepare the negotiation to start by asking everyone to join"""
mechanisms = self.world.mechanisms
if (
(not self.allow_self_negotiation)
and (len({_.id if _ is not None else "" for _ in partners}) < 2)
and len(partners) > 1
):
return None
if issues is None:
self.world.call(
caller, caller.on_neg_request_rejected_, req_id=req_id, by=None
)
return None
if (
mechanisms is not None
and mechanism_name is not None
and mechanism_name not in mechanisms.keys()
):
self.world.call(
caller, caller.on_neg_request_rejected_, req_id=req_id, by=None
)
return None
if mechanisms is not None and mechanism_name is not None:
mechanism_name = mechanisms[mechanism_name].pop(
PROTOCOL_CLASS_NAME_FIELD, mechanism_name
)
if mechanism_params is None:
mechanism_params = {}
if mechanisms and mechanisms.get(mechanism_name, None) is not None:
mechanism_params.update(mechanisms[mechanism_name])
# mechanism_params = {k: v for k, v in mechanism_params.items() if k != PROTOCOL_CLASS_NAME_FIELD}
mechanism_params["n_steps"] = self.neg_n_steps
mechanism_params["time_limit"] = self.neg_time_limit
mechanism_params["step_time_limit"] = self.neg_step_time_limit
mechanism_params["issues"] = issues
mechanism_params["annotation"] = annotation
mechanism_params["name"] = "-".join(_.id for _ in partners)
if mechanism_name is None:
if mechanisms is not None and len(mechanisms) == 1:
mechanism_name = list(mechanisms.keys())[0]
else:
mechanism_name = "negmas.sao.SAOMechanism"
if mechanisms and mechanisms.get(mechanism_name, None) is not None:
mechanism_params.update(mechanisms[mechanism_name])
try:
mechanism = instantiate(class_name=mechanism_name, **mechanism_params)
except Exception as e:
s_ = exception2str()
self.world.mechanism_exceptions[self.world.current_step].append(s_)
self.world.agent_exceptions[caller.id].append((self.world.current_step, s_))
mechanism = None
self.world.logerror(
f"Failed to create {mechanism_name} with params {mechanism_params}",
Event("mechanism-creation-exception", dict(exception=e)),
)
self.mechanism = mechanism
if mechanism is None:
return None
if self.mechanism:
self.mechanism.register_listener("negotiator_exception", self.world)
if roles is None:
roles = [None] * len(partners)
partner_names = [p.id for p in partners]
responses = [
self.world.call(
partner,
partner.respond_to_negotiation_request_,
initiator=caller.id,
partners=partner_names,
issues=issues,
annotation=annotation,
role=role,
mechanism=mechanism.nmi,
req_id=req_id if partner == caller else None,
)
for role, partner in zip(roles, partners)
]
if not all(responses):
rejectors = [p for p, response in zip(partners, responses) if not response]
rej = [_.id for _ in rejectors]
for r in rej:
self.world.neg_requests_rejected[r] += 1
self.world.call(
caller, caller.on_neg_request_rejected_, req_id=req_id, by=rej
)
for partner, response in zip(partners, responses):
if partner.id != caller.id and response:
self.world.call(
partner, partner.on_neg_request_rejected_, req_id=None, by=rej
)
self.world.loginfo(
f"{caller.name} request was rejected by {[_.name for _ in rejectors]}",
Event(
"negotiation-request-rejected",
dict(
req_id=req_id,
caller=caller,
partners=partners,
rejectors=rejectors,
annotation=annotation,
),
),
)
return NegotiationInfo(
mechanism=None,
partners=partners,
annotation=annotation,
issues=issues,
rejectors=rejectors,
requested_at=self.world.current_step,
caller=caller,
group=self.group,
)
mechanism = self._create_negotiation_session(
mechanism=mechanism,
responses=zip(responses, roles),
partners=partners, # type: ignore
)
neg_info = NegotiationInfo(
mechanism=mechanism,
partners=partners,
annotation=annotation,
issues=issues,
requested_at=self.world.current_step,
caller=caller,
group=self.group,
)
self.world.call(
caller,
caller.on_neg_request_accepted_,
req_id=req_id,
mechanism=mechanism.nmi,
)
for partner, response in zip(partners, responses):
if partner.id != caller.id:
self.world.call(
partner,
partner.on_neg_request_accepted_,
req_id=None,
mechanism=mechanism,
)
self.world.loginfo(
f"{caller.name} request was accepted",
Event(
"negotiation-request-accepted",
dict(
req_id=req_id,
caller=caller,
partners=partners,
mechanism=mechanism,
annotation=annotation,
),
),
)
return neg_info
def init(self) -> NegotiationInfo | None:
return self._start_negotiation(
mechanism_name=self.mechanism_name,
mechanism_params=self.mechanism_params,
roles=self.roles,
caller=self.caller,
partners=self.partners,
annotation=self.annotation,
issues=self.issues,
req_id=self.req_id,
)