-
Notifications
You must be signed in to change notification settings - Fork 15
/
base.py
577 lines (509 loc) · 22.4 KB
/
base.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
import copy
import time
from abc import abstractmethod
import numpy as np
from typing import Callable, List, Optional, Tuple, Union
from .expectors import MeanExpector
from .common import _locs, _uppers
from ..common import AgentMechanismInterface, MechanismState
from ..modeling import AdaptiveDiscreteAcceptanceModel
from ..outcomes import Outcome, ResponseType
from ..sao import (
AspirationNegotiator,
SAONegotiator,
)
from ..utilities import (
IPUtilityFunction,
MappingUtilityFunction,
UtilityDistribution,
UtilityFunction,
UtilityValue,
)
__all__ = ["BaseElicitor"]
class BaseElicitor(SAONegotiator):
def __init__(
self,
user: "User",
*,
strategy: Optional["EStrategy"] = None,
base_negotiator: SAONegotiator = AspirationNegotiator(),
opponent_model_factory: Optional[
Callable[["AgentMechanismInterface"], "DiscreteAcceptanceModel"]
] = lambda x: AdaptiveDiscreteAcceptanceModel.from_negotiation(ami=x),
expector_factory: Union["Expector", Callable[[], "Expector"]] = MeanExpector,
single_elicitation_per_round=False,
continue_eliciting_past_reserved_val=False,
epsilon=0.001,
true_utility_on_zero_cost=False,
) -> None:
"""
ABC for all elicitation algorithms.
Args:
user: A `User` object that
strategy: An elicitation strategy that determines the order of deep
elicitation queries.
base_negotiator: A negotiator that is used to propose and rspond to
proposals based on the current state of the utility function.
opponent_model_factory: A callable that can be used to create an opponent
model.
expector_factory: A callable that can be used to construct an `Expector`
object responsible of reducing a probabilistic utility
value into a real number to be used by the negotiator.
single_elicitation_per_round: Forces a single elicitation opportunity per
negotiation round. If the elicitor uses deep
elicitation this will correspond to multiple
calls to the `strategy`.
continue_eliciting_past_reserved_val: If `True`, elicitation continues even
if the expector returns a value under
the reserved value of the negotiator.
epsilon: A small number to stop elicitation when the uncertainty in the ufun
is under.
true_utility_on_zero_cost: If `True`, zero cost will force the final elicited
value of any outcome to exactly match the utility
function. If `False`, the final utility value after
elicitation may be within `epsilon` from the true
value.
"""
super().__init__()
self.add_capabilities(
{
"propose": True,
"respond": True,
"propose-with-value": False,
"max-proposals": None, # indicates infinity
}
)
self.strategy = strategy
self.opponent_model_factory = opponent_model_factory
self.expector_factory = expector_factory
self.single_elicitation = single_elicitation_per_round
self.continue_eliciting_past_reserved_val = continue_eliciting_past_reserved_val
self.epsilon = epsilon
self.true_utility_on_zero_cost = true_utility_on_zero_cost
self.elicitation_history = []
self.opponent_model = None
self._elicitation_time = None
self.asking_time = 0.0
self.offerable_outcomes = (
[]
) # will contain outcomes with known or at least elicited utilities
self.indices = None
self.initial_utility_priors = None
self.user = user
self.acc_limit = self.accuracy_limit(self.user.cost_of_asking())
self.base_negotiator = base_negotiator
self.expect = None
if strategy is not None:
strategy.resolution = max(self.acc_limit, strategy.resolution)
def join(
self,
ami: AgentMechanismInterface,
state: MechanismState,
*,
ufun: Optional["UtilityFunction"] = None,
role: str = "agent",
**kwargs,
) -> bool:
"""
Called to join a negotiation.
Remarks:
- uses the base_negotiator to join the negotiation.
- creates a `MappingUtilityFunction` that maps every outcome to the
result of the expector applied to the corresponding utility value.
- The reserved value of the created ufun is set to -inf
"""
if ufun is None:
ufun = IPUtilityFunction(outcomes=ami.outcomes, reserved_value=0.0)
if not super().join(ami=ami, state=state, ufun=ufun, role=role):
return False
self.expect = self.expector_factory(self._ami)
self.init_elicitation(ufun=ufun, **kwargs)
self.base_negotiator.join(
ami,
state,
ufun=MappingUtilityFunction(
mapping=lambda x: self.expect(self.utility_function(x), state=state),
reserved_value=float("-inf"),
),
)
return True
def on_negotiation_start(self, state: MechanismState):
"""Called when the negotiation starts. Just passes the call to
base_negotiator."""
self.base_negotiator.on_negotiation_start(state=state)
def utility_distributions(self) -> List[UtilityDistribution]:
"""
Returns a `UtilityDistribution` for every outcome
"""
if self.utility_function is None:
return [None] * len(self._ami.outcomes)
if self.utility_function.base_type == "ip":
return list(self.utility_function.distributions.values())
else:
return [self.utility_function(o) for o in self._ami.outcomes]
def user_ufun(self, outcome: Optional["Outcome"]) -> float:
"""
Finds the total utility obtained by the user for this outcome after
discounting elicitation cost.
Args:
outcome: The outcome to find the user utility for. If None, it
returns the reserved value.
Remarks:
The total elicitation cost is *not* discounted from the reserved
value when the input is None
"""
return (
self.user.ufun(outcome) - self.user.total_cost
if outcome is not None
else self.user.ufun(outcome)
)
@property
def elicitation_cost(self) -> float:
"""
The total elicitation cost.
"""
return self.user.total_cost
@property
def elicitation_time(self) -> float:
"""The total elicitation time in seconds."""
return self._elicitation_time
def maximum_attainable_utility(self) -> float:
"""
Maximum utility that could even in principle be attained which
simply means the utility value of the outcome with maximum utility.
"""
return max(_uppers(self.utility_distributions()))
def minimum_guaranteed_utility(self):
"""
Minimum utility that could even in principle be attained which
simply means the utility value of the outcome with minimum utility.
"""
return min(_locs(self.utility_distributions()))
def on_partner_proposal(
self, state: MechanismState, partner_id: str, offer: "Outcome"
):
"""
Called when one of the partners propose (only if enable_callbacks is set
in the `SAOMechanism`).
Args:
state: mechanism state
partner_id: the partner who proposed
offer: The offer from the partner
Remarks:
- Used to update the opponent model by calling `update_offered` then
`on_opponent_model_updated`.
"""
self.base_negotiator.on_partner_proposal(
partner_id=partner_id, offer=offer, state=state
)
old_prob = self.opponent_model.probability_of_acceptance(offer)
self.opponent_model.update_offered(offer)
new_prob = self.opponent_model.probability_of_acceptance(offer)
self.on_opponent_model_updated([offer], old=[old_prob], new=[new_prob])
def on_partner_response(
self,
state: MechanismState,
partner_id: str,
outcome: "Outcome",
response: "ResponseType",
):
"""
Called when one of the partners respond (only if enable_callbacks is set
in the `SAOMechanism`).
Args:
state: mechanism state
partner_id: the partner who offered
outcome: The outcome responded to
response: The partner response including both the response and outcome
Remarks:
- Used to update the opponent model by calling `update_rejected` or
`update_accepted1 then `on_opponent_model_updated`.
"""
self.base_negotiator.on_partner_response(
state=state, partner_id=partner_id, outcome=outcome, response=response
)
if response == ResponseType.REJECT_OFFER:
old_probs = [self.opponent_model.probability_of_acceptance(outcome)]
self.opponent_model.update_rejected(outcome)
new_probs = [self.opponent_model.probability_of_acceptance(outcome)]
self.on_opponent_model_updated([outcome], old=old_probs, new=new_probs)
elif response == ResponseType.ACCEPT_OFFER:
old_probs = [self.opponent_model.probability_of_acceptance(outcome)]
self.opponent_model.update_accepted(outcome)
new_probs = [self.opponent_model.probability_of_acceptance(outcome)]
self.on_opponent_model_updated([outcome], old=old_probs, new=new_probs)
def respond_(self, state: MechanismState, offer: "Outcome") -> ResponseType:
"""
Called by the mechanism directly (through `counter` ) to respond to offers.
Args:
state: mechanism state
offer: the offer to respond to
Remarks:
- Does the following steps:
1. Finds the the best offer using `best_offer` and uses the base negotiator
to respond if that offer was `None`
2. Looks at `offerable_outcomes` and applies the elicitation strategy (one
step) to the outcome if it was not offerable (or if there are no offerable
outcomes defined).
3. Finds the utility of the offer using `utility_function` not taking into accout
elicitation cost and uses the base negotiator if that fails (i.e. `utility_function`
returns `None`).
4. Finds the expected utility of the offer using the `expect` () method which calls the
expector passed during construction.
5. If the maximum attainable utility now (judging from the current estimation of
the utility value of each outcome taking elicitation cost into account) is less
than the reserved value, end the negotiation
6. If the utility of my best offer (returned from `best_offer`) is less than the offered
utility, accept the offer
7. Otherwise, call bhe base negotiator to respond.
"""
my_offer, meu = self.best_offer(state=state)
if my_offer is None:
return self.base_negotiator.respond_(state=state, offer=offer)
if (
self.strategy
and self.offerable_outcomes is not None
and offer not in self.offerable_outcomes
):
self.strategy.apply(user=self.user, outcome=offer)
offered_utility = self.utility_function(offer)
if offered_utility is None:
return self.base_negotiator.respond_(state=state, offer=offer)
offered_utility = self.expect(offered_utility, state=state)
if (
self.maximum_attainable_utility() - self.user.total_cost
< self.reserved_value
):
return ResponseType.END_NEGOTIATION
if meu < offered_utility:
return ResponseType.ACCEPT_OFFER
else:
return self.base_negotiator.respond_(state=state, offer=offer)
def propose(self, state: MechanismState) -> "Outcome":
"""
Called to propose an outcome
Args:
state: mechanism state
Remarks:
- if the negotiator `can_elicit`, it will `elicit`.
- always then calls the base negotiator to propose.
"""
if self.can_elicit():
self.elicit(state=state)
return self.base_negotiator.propose(state=state)
def elicit(self, state: MechanismState) -> None:
"""
Called to do utility elicitation whenever needed.
Args:
state: mechanism state
Remarks:
- Keeps track of elicitation time and asking time.
- If the maximum attainable utility minus elicitation cost is less than the
reserved value, no elicitation will take place because we will end this
negotiation anyway. Note that the maximum attainable utility can **never**
go up.
- Calls `before_eliciting` once to initialize the process then calls
`elicit_single` which does the actual elicitation. This is done only once
if `single_elicitation` is set, otherwise it is repeated until one of the
following conditiosn is met:
- `elicit_single` returns False
- The maximum attainable utility (minus elicitation cost) is less than
the reserved value.
"""
if (
self.maximum_attainable_utility() - self.elicitation_cost
<= self.reserved_value
):
return
start = time.perf_counter()
self.before_eliciting()
if self.single_elicitation:
self.elicit_single(state=state)
else:
while self.elicit_single(state=state):
if (
self.maximum_attainable_utility() - self.elicitation_cost
<= self.reserved_value
or state.relative_time >= 1
):
break
elapsed = time.perf_counter() - start
self._elicitation_time += elapsed
self.asking_time += elapsed
def accuracy_limit(self, cost: float) -> float:
"""The accuracy limit given the cost and `epsilon`."""
return 0.5 * max(self.epsilon, cost)
def init_elicitation(
self,
ufun: Optional[
Union[
"IPUtilityFunction", "UtilityDistribution", List["UtilityDistribution"]
]
],
**kwargs,
) -> None:
"""
Called once to initialize the elicitation process
Args:
ufun: The probabilistic utility function
**kwargs:
Remarks:
- If no `ufun` is given one will be created with 0-1 uniform distributions and
zero reserved value.
- If a single `UtilityDistribution` is given as `ufun`, it is repeated for all
outcomes (and the reserved value is set to zero).
- If a list of `UtilityDistribution` s is given, it must have the same length as
the list of outcomes of this negotiation and is used to set the `ufun`.
- The opponent model
"""
ami = self._ami
self.elicitation_history = []
self.indices = dict(zip(ami.outcomes, range(ami.n_outcomes)))
self.offerable_outcomes = []
self._elicitation_time = 0.0
if self.opponent_model_factory is None:
self.opponent_model = None
else:
self.opponent_model = self.opponent_model_factory(ami)
self.base_negotiator.opponent_model = self.opponent_model
outcomes = ami.outcomes
if ufun is None:
dists = [
UtilityDistribution(dtype="uniform", loc=0.0, scale=1.0)
for _ in outcomes
]
ufun = IPUtilityFunction(
outcomes=outcomes, distributions=dists, reserved_value=0.0
)
elif isinstance(ufun, UtilityDistribution):
ufun = [copy.copy(ufun) for _ in outcomes]
ufun = IPUtilityFunction(
outcomes=outcomes, distributions=ufun, reserved_value=0.0
)
elif (
isinstance(ufun, list)
and len(ufun) > 0
and isinstance(ufun[0], UtilityDistribution)
):
ufun = IPUtilityFunction(
outcomes=outcomes, distributions=ufun, reserved_value=0.0
)
self.utility_function = ufun
self.initial_utility_priors = copy.copy(ufun)
def offering_utility(self, outcome, state) -> UtilityValue:
"""
returns expected utlity of offering `outcome` in `state`
Args:
outcome: The outcome
state: The state
Returns:
A utility value
Remarks:
- returns $u(o) p(o) + ru(o) (1-p(o))$ where $p$ is the opponent model,
$u$ is the utility function, and $r$ is the utility in case of rejections.
- `state` is needed when calculating $r(o)$ by calling `utility_on_rejection`.
- Note that if $u$ or $r$ return a `UtilityDistribution`, this method will return
a `UtilityDistribution` not a real number.
"""
if self.opponent_model is None:
return self.utility_function(outcome)
u = self.utility_function(outcome)
p = self.opponent_model.probability_of_acceptance(outcome)
return p * u + (1 - p) * self.utility_on_rejection(outcome, state=state)
def offering_utilities(self, state) -> np.ndarray:
"""
Calculates the offering utility for all outcomes
Args:
state: Calculates the state at which the offering utilities are to be calculated
Returns:
An ndarray with the offering utility of every outcome (in order)
Remarks:
- This is just a faster version of calling `offering_utility` in a loop.
"""
us = np.asarray(self.utility_distributions())
ps = np.asarray(self.opponent_model.acceptance_probabilities())
return ps * us + (1 - ps) * np.asarray(self.utilities_on_rejection(state=state))
def utility_on_acceptance(self, outcome: "Outcome") -> UtilityValue:
"""
The utility of acceptance which is simply the utility function applied to `outcome`.
"""
return self.utility_function(outcome)
def best_offer(self, state: "MechanismState") -> Tuple[Optional["Outcome"], float]:
"""The outcome with maximum expected utility given the expector and its utility
Args:
state: The mechanism state
Returns:
A tuple containing the best outcome (or None) and its expected utility using the
expector (or reserved value)
Remarks:
- if there are no offerable outcomes, elicitation is done and if still there are no
offerable outcomes, the reserved value is returned (with None as outcome)
- Only offerable outcomes are checked.
- The best outcome is defined as the one with maximum `expect` applied to
`offering_utility`.
"""
if len(self.offerable_outcomes) == 0:
self.elicit(state=state)
if len(self.offerable_outcomes) == 0:
return None, self.reserved_value
best, best_utility, bsf = None, self.reserved_value, self.reserved_value
for i, outcome in enumerate(self.offerable_outcomes):
if outcome is None:
continue
utilitiy = self.offering_utility(outcome, state=state)
expected_utility = self.expect(utilitiy, state=state)
if expected_utility >= bsf:
best, best_utility, bsf = outcome, utilitiy, expected_utility
return best, self.expect(best_utility, state=state)
def utility_on_rejection(
self, outcome: "Outcome", state: MechanismState
) -> UtilityValue:
"""Estimated utility if this outcome rejected at this state.
Args:
outcome: The outcome tested
state: The mechanism state
Remarks:
- MUST be implemented by any Elicitor.
"""
raise NotImplementedError(
f"Must override utility_on_rejection in {self.__class__.__name__}"
)
def utilities_on_rejection(self, state: MechanismState) -> List[UtilityValue]:
"""Finds the utility of rejection for all outputs.
Remarks:
- By default it calls `utility_on_rejection` repeatedly for all outcomes.
Override this method if a faster versin can be implemented
"""
return [
self.utility_on_rejection(outcome=outcome, state=state)
for outcome in self._ami.outcomes
]
def on_opponent_model_updated(
self, outcomes: List[Outcome], old: List[float], new: List[float]
) -> None:
"""
Called whenever an opponents model is updated.
Args:
outcomes: A list of outcomes for which the acceptance probability are changed
old: The old acceptance probability
new: The new acceptance probability
"""
# TODO extend this to take the partner_id as a parameter to handle multiparty negotiation
def __str__(self):
return f"{self.name}"
def before_eliciting(self) -> None:
"""Called by apply just before continuously calling elicit_single"""
pass
@abstractmethod
def can_elicit(self) -> bool:
"""Returns whether we can do more elicitation"""
raise NotImplementedError()
@abstractmethod
def elicit_single(self, state: MechanismState) -> None:
"""Does a single elicitation act
Args:
state: mechanism state
"""
raise NotImplementedError()
def __getattr__(self, item):
return getattr(self.base_negotiator, item)