Skip to content

API

CoBaIR is split into the config model and the inference:

  • cobair.model describes a scenario (contexts, intentions, influences, decision threshold), validates it, reads and writes config files and computes the conditional probability tables. It only needs pyyaml.
  • cobair.infer infers the intentions for given evidence with the two-layer Bayesian net. It needs the [infer] extra: pip install "cobair[infer]".
from cobair.model import Config
from cobair.infer import Inference

config = Config.load('small_example.yml')
config.change_influence_value('pick up tool', 'speech commands', 'pickup', 5)
print(config.validate())  # [] if the config is valid

inference = Inference(config)  # create a new Inference after editing the config
intention, decision_threshold, probabilities = inference.infer({'speech commands': 'pickup'})

cobair.model

The config model of CoBaIR: contexts, intentions, influences and the decision threshold.

This module is pure Python (it only needs pyyaml), so it can be used without the inference dependencies, e.g. in the GUIs. The conditional probability tables of the two-layer Bayesian net are computed here as well, cobair.infer only hands them to pgmpy.

Example
from cobair.model import Config

config = Config.load('small_example.yml')
config.add_context('weather', {'sunny': 0.7, 'rainy': 0.3})
config.change_influence_value('pick up tool', 'weather', 'rainy', 4)
print(config.validate())  # [] if the config is valid
config.save('my_config.yml')

CPTs dataclass

The conditional probability tables of the two-layer Bayesian net.

The order of the states is the order of the instantiations in the config. The columns of the intention tables iterate over all combinations of context instantiations in the order of contexts, the last context changes fastest (the order pgmpy expects).

Attributes:

Name Type Description
contexts list

All contexts, the parents of every intention.

states dict

The instantiations of every context.

context_priors dict

The apriori probability of every instantiation of every context.

intentions list

All intentions.

intention_values dict

For every intention [negative values, positive values].

Source code in cobair/model.py
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
@dataclass
class CPTs:
    """The conditional probability tables of the two-layer Bayesian net.

    The order of the states is the order of the instantiations in the config.
    The columns of the intention tables iterate over all combinations of context instantiations
    in the order of `contexts`, the last context changes fastest (the order pgmpy expects).

    Attributes:
        contexts: All contexts, the parents of every intention.
        states: The instantiations of every context.
        context_priors: The apriori probability of every instantiation of every context.
        intentions: All intentions.
        intention_values: For every intention `[negative values, positive values]`.
    """

    contexts: list
    states: dict
    context_priors: dict
    intentions: list
    intention_values: dict

    @property
    def cards(self) -> list:
        """The number of instantiations of every context in the order of `contexts`.

        Returns:
            list: The cardinalities.
        """
        return [len(self.states[context]) for context in self.contexts]

cards property

The number of instantiations of every context in the order of contexts.

Returns:

Name Type Description
list list

The cardinalities.

Config

A mutable CoBaIR config.

Attributes:

Name Type Description
contexts

{context: {instantiation: apriori probability}}

intentions

{intention: {context: {instantiation: influence}}}. Combined influences use a tuple of contexts as context key and a tuple of instantiations as instantiation key.

decision_threshold

The probability an intention must exceed to be picked.

Source code in cobair/model.py
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
class Config:
    """A mutable CoBaIR config.

    Attributes:
        contexts: `{context: {instantiation: apriori probability}}`
        intentions: `{intention: {context: {instantiation: influence}}}`. Combined influences use
            a tuple of contexts as context key and a tuple of instantiations as instantiation key.
        decision_threshold: The probability an intention must exceed to be picked.
    """

    def __init__(self, contexts: dict = None, intentions: dict = None,
                 decision_threshold: float = 0.0) -> None:
        """Create a config, the given dicts are copied.

        Args:
            contexts: `{context: {instantiation: apriori probability}}`
            intentions: `{intention: {context: {instantiation: influence}}}`
            decision_threshold: The probability an intention must exceed to be picked.
        """
        self.contexts = _to_plain(contexts or {})
        self.intentions = _to_plain(intentions or {})
        self.decision_threshold = decision_threshold

    # ------------------------------------------------------------------------------------------
    # conversion and files

    @classmethod
    def from_dict(cls, config: dict) -> Config:
        """Create a config from a dict in the config file format; unknown keys are ignored.

        Args:
            config: A dict with the keys `contexts`, `intentions` and `decision_threshold`.

        Returns:
            Config: The new config.
        """
        config = config or {}
        return cls(config.get('contexts'), config.get('intentions'),
                   config.get('decision_threshold', 0.0))

    def to_dict(self) -> dict:
        """Return the config as plain dicts in the config file format (without header).

        Returns:
            dict: A deep copy of the config.
        """
        return {'contexts': deepcopy(self.contexts),
                'intentions': deepcopy(self.intentions),
                'decision_threshold': self.decision_threshold}

    def copy(self) -> Config:
        """Return a deep copy.

        Returns:
            Config: The copy.
        """
        return Config.from_dict(self.to_dict())

    @classmethod
    def loads(cls, text: str) -> Config:
        """Create a config from YAML text.

        Args:
            text: The content of a config file.

        Returns:
            Config: The loaded config.

        Raises:
            ValueError: If the text is not a mapping or was written with a newer format version.
        """
        data = yaml.load(text, Loader=PrettySafeLoader)  # noqa: S506 - safe loader + tuples
        if data is None:
            data = {}
        if not isinstance(data, dict):
            raise ValueError('A config must be a YAML mapping')
        format_version = data.get('format_version', FORMAT_VERSION)
        if not isinstance(format_version, int) or format_version > FORMAT_VERSION:
            raise ValueError(
                f'The config has format version {format_version}, but cobair {__version__} '
                f'only supports up to version {FORMAT_VERSION}. Please update cobair.')
        return cls.from_dict(data)

    @classmethod
    def load(cls, path) -> Config:
        """Load a config from a YAML file.

        Args:
            path: Path to the config file.

        Returns:
            Config: The loaded config.
        """
        return cls.loads(Path(path).read_text(encoding='utf-8'))

    def dumps(self) -> str:
        """Return the config as YAML text with header.

        Returns:
            str: The content of a config file.
        """
        data = {'format_version': FORMAT_VERSION, 'created_with': f'cobair {__version__}'}
        data.update(self.to_dict())
        return HEADER + yaml.dump(data, Dumper=_Dumper, sort_keys=False, allow_unicode=True)

    def save(self, path) -> None:
        """Save the config to a YAML file.

        Args:
            path: Path to the config file.
        """
        Path(path).write_text(self.dumps(), encoding='utf-8')

    def __eq__(self, other) -> bool:
        """Configs are equal if contexts, intentions and decision threshold are equal.

        Args:
            other: The object to compare with.

        Returns:
            bool: True if equal.
        """
        if not isinstance(other, Config):
            return NotImplemented
        return self.to_dict() == other.to_dict()

    # ------------------------------------------------------------------------------------------
    # validation

    def validate(self) -> list:
        """Check that the config is complete and consistent.

        Returns:
            list: Messages describing all problems, empty if the config is valid.
        """
        problems = []
        if not self.contexts:
            problems.append('No contexts defined')
        if not self.intentions:
            problems.append('No intentions defined')
        if not _is_number(self.decision_threshold) or not 0 <= self.decision_threshold < 1:
            problems.append('Decision threshold must be a number between 0 and 1')

        for context, instantiations in self.contexts.items():
            for instantiation, value in instantiations.items():
                if not _is_number(value):
                    problems.append(
                        f'Apriori probability of context "{context}.{instantiation}" '
                        'is not a number')
            values = [value for value in instantiations.values() if _is_number(value)]
            if len(values) == len(instantiations) and \
                    not math.isclose(sum(values), 1.0, abs_tol=1e-9):
                problems.append(
                    'The sum of probabilities for context instantiations must be 1 - '
                    f'For "{context}" it is {sum(values)}!')

        for intention, influences in self.intentions.items():
            for context, values in influences.items():
                problems.extend(self._validate_influences(intention, context, values))
        return problems

    def _validate_influences(self, intention, context, values: dict) -> list:
        """Check the influence values of one intention for one (combined) context.

        Args:
            intention: The intention.
            context: A context or a tuple of contexts.
            values: `{instantiation: influence}`

        Returns:
            list: Messages describing all problems.
        """
        problems = []
        contexts = context if isinstance(context, tuple) else (context,)
        unknown = [name for name in contexts if name not in self.contexts]
        if unknown:
            return [f'Context influence {context} of {intention} cannot be found in the defined '
                    f'contexts! Unknown: {unknown}']
        for instantiation, influence in values.items():
            if isinstance(context, tuple):
                if not isinstance(instantiation, tuple) or len(instantiation) != len(context) \
                        or any(inst not in self.contexts[name]
                               for name, inst in zip(context, instantiation)):
                    problems.append(f'{instantiation} is not a valid combination of '
                                    f'instantiations for {context} in {intention}')
            elif instantiation not in self.contexts[context]:
                problems.append(
                    'An influence needs to be defined for all instantiations! '
                    f'{intention}.{context}.{instantiation} does not fit the defined '
                    f'instantiations for {context}')
            if not (isinstance(influence, int) and not isinstance(influence, bool)
                    and 0 <= influence <= 5):
                problems.append(f'Influence Value for {intention}.{context}.{instantiation} '
                                f'must be an integer between 0 and 5! Is {influence}')
        return problems

    @property
    def valid(self) -> bool:
        """True if `validate()` finds no problems.

        Returns:
            bool: Validity of the config.
        """
        return not self.validate()

    # ------------------------------------------------------------------------------------------
    # editing

    def add_context(self, context: Hashable, instantiations: dict) -> None:
        """Add a new context; its influence on all intentions is set to 0.

        Args:
            context: Name of the new context.
            instantiations: `{instantiation: apriori probability}`, e.g. `{True: 0.6, False: 0.4}`

        Raises:
            ValueError: If the context already exists.
        """
        if context in self.contexts:
            raise ValueError(
                'Cannot add existing context - use edit_context to edit an existing context')
        self.contexts[context] = dict(instantiations)
        self._sync_influences()

    def edit_context(self, context: Hashable, instantiations: dict,
                     new_name: Hashable = None) -> None:
        """Change the instantiations of a context and optionally rename it.

        Influences of removed instantiations are removed, new instantiations get the influence 0.
        Combined influences follow a rename and are removed if they use a removed instantiation.

        !!! note
            Changing the name of an instantiation will always set the influence value of this
                instantiation to zero for all intentions!

        Args:
            context: Name of the context to edit.
            instantiations: `{instantiation: apriori probability}`, e.g. `{True: 0.6, False: 0.4}`
            new_name: A new name for the context.

        Raises:
            ValueError: If the context does not exist or `new_name` is another existing context.
        """
        if context not in self.contexts:
            raise ValueError(
                'Cannot edit non existing context - use add_context to add a new context')
        if new_name is not None and new_name != context:
            if new_name in self.contexts:
                raise ValueError(f'Cannot rename "{context}" to "{new_name}" - it exists already')
            self.contexts = _rename_key(self.contexts, context, new_name)
            for intention, influences in self.intentions.items():
                renamed = {}
                for key, values in influences.items():
                    if key == context:
                        renamed[new_name] = values
                    elif isinstance(key, tuple) and context in key:
                        renamed[tuple(new_name if name == context else name for name in key)] = \
                            values
                    else:
                        renamed[key] = values
                self.intentions[intention] = renamed
            context = new_name
        self.contexts[context] = dict(instantiations)
        self._sync_influences()

    def del_context(self, context: Hashable) -> None:
        """Remove a context including all its (combined) influences.

        Args:
            context: Name of the context to delete.

        Raises:
            ValueError: If the context does not exist.
        """
        if context not in self.contexts:
            raise ValueError(
                'Cannot delete non-existing context - use add_context to add a new context')
        del self.contexts[context]
        self._sync_influences()

    def add_intention(self, intention: Hashable) -> None:
        """Add a new intention; the influence of all contexts is set to 0.

        Args:
            intention: Name of the new intention.

        Raises:
            ValueError: If the intention already exists.
        """
        if intention in self.intentions:
            raise ValueError(
                'Cannot add existing intention - use edit_intention to edit an existing intention')
        self.intentions[intention] = {}
        self._sync_influences()

    def edit_intention(self, intention: Hashable, new_name: Hashable) -> None:
        """Rename an intention.

        Args:
            intention: Name of the intention to edit.
            new_name: A new name for the intention.

        Raises:
            ValueError: If the intention does not exist or `new_name` exists already.
        """
        if intention not in self.intentions:
            raise ValueError(
                'Cannot edit non existing intention - use add_intention to add a new intention')
        if new_name in self.intentions:
            raise ValueError(f'{new_name} exists - cannot be given as the new name for {intention}')
        self.intentions = _rename_key(self.intentions, intention, new_name)

    def del_intention(self, intention: Hashable) -> None:
        """Remove an intention.

        Args:
            intention: Name of the intention to delete.

        Raises:
            ValueError: If the intention does not exist.
        """
        if intention not in self.intentions:
            raise ValueError(
                'Cannot delete non existing intention - use add_intention to add a new intention')
        del self.intentions[intention]

    def change_context_apriori_value(self, context: Hashable, instantiation: Hashable,
                                     value: float) -> None:
        """Change the apriori probability of a context instantiation.

        Args:
            context: Name of the context.
            instantiation: The instantiation.
            value: The new apriori probability.

        Raises:
            ValueError: If the context or instantiation does not exist.
        """
        if instantiation not in self.contexts.get(context, {}):
            raise ValueError(
                'change_context_apriori_value can only change values that exist already')
        self.contexts[context][instantiation] = value

    def change_influence_value(self, intention: Hashable, context: Hashable,
                               instantiation: Hashable, value: int) -> None:
        """Change the influence of a context instantiation on an intention.

        Args:
            intention: Name of the intention.
            context: Name of the context (or tuple of contexts for a combined influence).
            instantiation: The instantiation (or tuple of instantiations).
            value: The new influence value, one out of [0, 1, 2, 3, 4, 5].

        Raises:
            ValueError: If the influence does not exist.
        """
        if instantiation not in self.intentions.get(intention, {}).get(context, {}):
            raise ValueError('change_influence_value can only change values that exist already')
        self.intentions[intention][context][instantiation] = value

    def add_combined_influence(self, intention: Hashable, contexts: tuple,
                               instantiations: tuple, value: int) -> None:
        """Set the influence of a combination of context instantiations on an intention.

        If all instantiations of the combination are present, the combined influence replaces
        the single influences of these contexts.

        Args:
            intention: Name of the intention.
            contexts: The names of the contexts.
            instantiations: One instantiation for each of the contexts.
            value: The influence value, one out of [0, 1, 2, 3, 4, 5].

        Raises:
            ValueError: If the contexts are empty, the intention does not exist or an
                instantiation does not exist.
        """
        if not contexts:
            raise ValueError('Contexts list cannot be empty.')
        if intention not in self.intentions:
            raise ValueError(f'"{intention}" does not exist in the list of intentions')
        contexts, instantiations = tuple(contexts), tuple(instantiations)
        if len(contexts) != len(instantiations) or any(
                instantiation not in self.contexts.get(context, {})
                for context, instantiation in zip(contexts, instantiations)):
            raise ValueError(
                'add_combined_influence can only combine context instantiations that already exist')
        self.intentions[intention].setdefault(contexts, {})[instantiations] = value

    def del_combined_influence(self, intention: Hashable, contexts: tuple,
                               instantiations: tuple) -> None:
        """Remove the combined influence of a combination of context instantiations.

        Args:
            intention: Name of the intention.
            contexts: The names of the contexts.
            instantiations: One instantiation for each of the contexts.

        Raises:
            ValueError: If the combined influence does not exist.
        """
        contexts, instantiations = tuple(contexts), tuple(instantiations)
        combinations = self.intentions.get(intention, {}).get(contexts, {})
        if instantiations not in combinations:
            raise ValueError('Combined context instantiations must exist to be removed.')
        del combinations[instantiations]
        if not combinations:
            del self.intentions[intention][contexts]

    def change_decision_threshold(self, decision_threshold: float) -> None:
        """Change the decision threshold.

        Args:
            decision_threshold: The new decision threshold.
        """
        self.decision_threshold = decision_threshold

    def combined_influences(self, intention: Hashable) -> dict:
        """Return the combined influences of an intention.

        Args:
            intention: Name of the intention.

        Returns:
            dict: `{(context, ...): {(instantiation, ...): influence}}`
        """
        return {contexts: values for contexts, values in self.intentions[intention].items()
                if isinstance(contexts, tuple)}

    def _sync_influences(self) -> None:
        """Make the influences of all intentions match the contexts and their instantiations."""
        for intention, influences in self.intentions.items():
            synced = {}
            for context, instantiations in self.contexts.items():
                old = influences.get(context, {})
                synced[context] = {instantiation: old.get(instantiation, 0)
                                   for instantiation in instantiations}
            for contexts, combinations in influences.items():
                if not isinstance(contexts, tuple) or \
                        any(context not in self.contexts for context in contexts):
                    continue
                kept = {instantiations: value for instantiations, value in combinations.items()
                        if all(instantiation in self.contexts[context]
                               for context, instantiation in zip(contexts, instantiations))}
                if kept:
                    synced[contexts] = kept
            self.intentions[intention] = synced

    # ------------------------------------------------------------------------------------------
    # conditional probability tables

    def cpts(self) -> CPTs:
        """Compute the conditional probability tables of the two-layer Bayesian net.

        The probability of an intention for a combination of context instantiations is the
        average of the probabilities of the influences (see `INFLUENCE_TO_PROBABILITY`).
        If a combined influence matches the combination, its value replaces the single influences
        of the combined contexts; if several match, the first one wins.

        Returns:
            CPTs: The conditional probability tables.

        Raises:
            ValueError: If the config is not valid.
        """
        problems = self.validate()
        if problems:
            raise ValueError(f'Invalid configuration: {problems}')
        contexts = list(self.contexts)
        states = {context: list(instantiations) for context, instantiations in
                  self.contexts.items()}
        priors = {context: list(instantiations.values()) for context, instantiations in
                  self.contexts.items()}
        values = {intention: self._intention_values(contexts, states, influences)
                  for intention, influences in self.intentions.items()}
        return CPTs(contexts, states, priors, list(self.intentions), values)

    @staticmethod
    def _intention_values(contexts: list, states: dict, influences: dict) -> list:
        """Compute the CPT of one intention.

        Args:
            contexts: All contexts in CPT order.
            states: The instantiations of every context.
            influences: `{context: {instantiation: influence}}` of the intention.

        Returns:
            list: `[negative values, positive values]`
        """
        combined = [(names, combination, value)
                    for names, combinations in influences.items() if isinstance(names, tuple)
                    for combination, value in combinations.items()]
        positive = []
        for case in itertools.product(*(states[context] for context in contexts)):
            active = dict(zip(contexts, case))
            # missing influences count as 0
            case_influences = {context: influences.get(context, {}).get(active[context], 0)
                               for context in contexts}
            for names, combination, value in combined:
                if all(active[name] == instantiation
                       for name, instantiation in zip(names, combination)):
                    case_influences.update(dict.fromkeys(names, value))
                    break
            probabilities = [INFLUENCE_TO_PROBABILITY.get(influence, 0)
                             for influence in case_influences.values()]
            positive.append(sum(probabilities) / len(probabilities) if probabilities else 0)
        return [[1 - value for value in positive], positive]

valid property

True if validate() finds no problems.

Returns:

Name Type Description
bool bool

Validity of the config.

__eq__(other)

Configs are equal if contexts, intentions and decision threshold are equal.

Parameters:

Name Type Description Default
other

The object to compare with.

required

Returns:

Name Type Description
bool bool

True if equal.

Source code in cobair/model.py
249
250
251
252
253
254
255
256
257
258
259
260
def __eq__(self, other) -> bool:
    """Configs are equal if contexts, intentions and decision threshold are equal.

    Args:
        other: The object to compare with.

    Returns:
        bool: True if equal.
    """
    if not isinstance(other, Config):
        return NotImplemented
    return self.to_dict() == other.to_dict()

__init__(contexts=None, intentions=None, decision_threshold=0.0)

Create a config, the given dicts are copied.

Parameters:

Name Type Description Default
contexts dict

{context: {instantiation: apriori probability}}

None
intentions dict

{intention: {context: {instantiation: influence}}}

None
decision_threshold float

The probability an intention must exceed to be picked.

0.0
Source code in cobair/model.py
146
147
148
149
150
151
152
153
154
155
156
157
def __init__(self, contexts: dict = None, intentions: dict = None,
             decision_threshold: float = 0.0) -> None:
    """Create a config, the given dicts are copied.

    Args:
        contexts: `{context: {instantiation: apriori probability}}`
        intentions: `{intention: {context: {instantiation: influence}}}`
        decision_threshold: The probability an intention must exceed to be picked.
    """
    self.contexts = _to_plain(contexts or {})
    self.intentions = _to_plain(intentions or {})
    self.decision_threshold = decision_threshold

add_combined_influence(intention, contexts, instantiations, value)

Set the influence of a combination of context instantiations on an intention.

If all instantiations of the combination are present, the combined influence replaces the single influences of these contexts.

Parameters:

Name Type Description Default
intention Hashable

Name of the intention.

required
contexts tuple

The names of the contexts.

required
instantiations tuple

One instantiation for each of the contexts.

required
value int

The influence value, one out of [0, 1, 2, 3, 4, 5].

required

Raises:

Type Description
ValueError

If the contexts are empty, the intention does not exist or an instantiation does not exist.

Source code in cobair/model.py
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
def add_combined_influence(self, intention: Hashable, contexts: tuple,
                           instantiations: tuple, value: int) -> None:
    """Set the influence of a combination of context instantiations on an intention.

    If all instantiations of the combination are present, the combined influence replaces
    the single influences of these contexts.

    Args:
        intention: Name of the intention.
        contexts: The names of the contexts.
        instantiations: One instantiation for each of the contexts.
        value: The influence value, one out of [0, 1, 2, 3, 4, 5].

    Raises:
        ValueError: If the contexts are empty, the intention does not exist or an
            instantiation does not exist.
    """
    if not contexts:
        raise ValueError('Contexts list cannot be empty.')
    if intention not in self.intentions:
        raise ValueError(f'"{intention}" does not exist in the list of intentions')
    contexts, instantiations = tuple(contexts), tuple(instantiations)
    if len(contexts) != len(instantiations) or any(
            instantiation not in self.contexts.get(context, {})
            for context, instantiation in zip(contexts, instantiations)):
        raise ValueError(
            'add_combined_influence can only combine context instantiations that already exist')
    self.intentions[intention].setdefault(contexts, {})[instantiations] = value

add_context(context, instantiations)

Add a new context; its influence on all intentions is set to 0.

Parameters:

Name Type Description Default
context Hashable

Name of the new context.

required
instantiations dict

{instantiation: apriori probability}, e.g. {True: 0.6, False: 0.4}

required

Raises:

Type Description
ValueError

If the context already exists.

Source code in cobair/model.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
def add_context(self, context: Hashable, instantiations: dict) -> None:
    """Add a new context; its influence on all intentions is set to 0.

    Args:
        context: Name of the new context.
        instantiations: `{instantiation: apriori probability}`, e.g. `{True: 0.6, False: 0.4}`

    Raises:
        ValueError: If the context already exists.
    """
    if context in self.contexts:
        raise ValueError(
            'Cannot add existing context - use edit_context to edit an existing context')
    self.contexts[context] = dict(instantiations)
    self._sync_influences()

add_intention(intention)

Add a new intention; the influence of all contexts is set to 0.

Parameters:

Name Type Description Default
intention Hashable

Name of the new intention.

required

Raises:

Type Description
ValueError

If the intention already exists.

Source code in cobair/model.py
416
417
418
419
420
421
422
423
424
425
426
427
428
429
def add_intention(self, intention: Hashable) -> None:
    """Add a new intention; the influence of all contexts is set to 0.

    Args:
        intention: Name of the new intention.

    Raises:
        ValueError: If the intention already exists.
    """
    if intention in self.intentions:
        raise ValueError(
            'Cannot add existing intention - use edit_intention to edit an existing intention')
    self.intentions[intention] = {}
    self._sync_influences()

change_context_apriori_value(context, instantiation, value)

Change the apriori probability of a context instantiation.

Parameters:

Name Type Description Default
context Hashable

Name of the context.

required
instantiation Hashable

The instantiation.

required
value float

The new apriori probability.

required

Raises:

Type Description
ValueError

If the context or instantiation does not exist.

Source code in cobair/model.py
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
def change_context_apriori_value(self, context: Hashable, instantiation: Hashable,
                                 value: float) -> None:
    """Change the apriori probability of a context instantiation.

    Args:
        context: Name of the context.
        instantiation: The instantiation.
        value: The new apriori probability.

    Raises:
        ValueError: If the context or instantiation does not exist.
    """
    if instantiation not in self.contexts.get(context, {}):
        raise ValueError(
            'change_context_apriori_value can only change values that exist already')
    self.contexts[context][instantiation] = value

change_decision_threshold(decision_threshold)

Change the decision threshold.

Parameters:

Name Type Description Default
decision_threshold float

The new decision threshold.

required
Source code in cobair/model.py
545
546
547
548
549
550
551
def change_decision_threshold(self, decision_threshold: float) -> None:
    """Change the decision threshold.

    Args:
        decision_threshold: The new decision threshold.
    """
    self.decision_threshold = decision_threshold

change_influence_value(intention, context, instantiation, value)

Change the influence of a context instantiation on an intention.

Parameters:

Name Type Description Default
intention Hashable

Name of the intention.

required
context Hashable

Name of the context (or tuple of contexts for a combined influence).

required
instantiation Hashable

The instantiation (or tuple of instantiations).

required
value int

The new influence value, one out of [0, 1, 2, 3, 4, 5].

required

Raises:

Type Description
ValueError

If the influence does not exist.

Source code in cobair/model.py
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
def change_influence_value(self, intention: Hashable, context: Hashable,
                           instantiation: Hashable, value: int) -> None:
    """Change the influence of a context instantiation on an intention.

    Args:
        intention: Name of the intention.
        context: Name of the context (or tuple of contexts for a combined influence).
        instantiation: The instantiation (or tuple of instantiations).
        value: The new influence value, one out of [0, 1, 2, 3, 4, 5].

    Raises:
        ValueError: If the influence does not exist.
    """
    if instantiation not in self.intentions.get(intention, {}).get(context, {}):
        raise ValueError('change_influence_value can only change values that exist already')
    self.intentions[intention][context][instantiation] = value

combined_influences(intention)

Return the combined influences of an intention.

Parameters:

Name Type Description Default
intention Hashable

Name of the intention.

required

Returns:

Name Type Description
dict dict

{(context, ...): {(instantiation, ...): influence}}

Source code in cobair/model.py
553
554
555
556
557
558
559
560
561
562
563
def combined_influences(self, intention: Hashable) -> dict:
    """Return the combined influences of an intention.

    Args:
        intention: Name of the intention.

    Returns:
        dict: `{(context, ...): {(instantiation, ...): influence}}`
    """
    return {contexts: values for contexts, values in self.intentions[intention].items()
            if isinstance(contexts, tuple)}

copy()

Return a deep copy.

Returns:

Name Type Description
Config Config

The copy.

Source code in cobair/model.py
186
187
188
189
190
191
192
def copy(self) -> Config:
    """Return a deep copy.

    Returns:
        Config: The copy.
    """
    return Config.from_dict(self.to_dict())

cpts()

Compute the conditional probability tables of the two-layer Bayesian net.

The probability of an intention for a combination of context instantiations is the average of the probabilities of the influences (see INFLUENCE_TO_PROBABILITY). If a combined influence matches the combination, its value replaces the single influences of the combined contexts; if several match, the first one wins.

Returns:

Name Type Description
CPTs CPTs

The conditional probability tables.

Raises:

Type Description
ValueError

If the config is not valid.

Source code in cobair/model.py
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
def cpts(self) -> CPTs:
    """Compute the conditional probability tables of the two-layer Bayesian net.

    The probability of an intention for a combination of context instantiations is the
    average of the probabilities of the influences (see `INFLUENCE_TO_PROBABILITY`).
    If a combined influence matches the combination, its value replaces the single influences
    of the combined contexts; if several match, the first one wins.

    Returns:
        CPTs: The conditional probability tables.

    Raises:
        ValueError: If the config is not valid.
    """
    problems = self.validate()
    if problems:
        raise ValueError(f'Invalid configuration: {problems}')
    contexts = list(self.contexts)
    states = {context: list(instantiations) for context, instantiations in
              self.contexts.items()}
    priors = {context: list(instantiations.values()) for context, instantiations in
              self.contexts.items()}
    values = {intention: self._intention_values(contexts, states, influences)
              for intention, influences in self.intentions.items()}
    return CPTs(contexts, states, priors, list(self.intentions), values)

del_combined_influence(intention, contexts, instantiations)

Remove the combined influence of a combination of context instantiations.

Parameters:

Name Type Description Default
intention Hashable

Name of the intention.

required
contexts tuple

The names of the contexts.

required
instantiations tuple

One instantiation for each of the contexts.

required

Raises:

Type Description
ValueError

If the combined influence does not exist.

Source code in cobair/model.py
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
def del_combined_influence(self, intention: Hashable, contexts: tuple,
                           instantiations: tuple) -> None:
    """Remove the combined influence of a combination of context instantiations.

    Args:
        intention: Name of the intention.
        contexts: The names of the contexts.
        instantiations: One instantiation for each of the contexts.

    Raises:
        ValueError: If the combined influence does not exist.
    """
    contexts, instantiations = tuple(contexts), tuple(instantiations)
    combinations = self.intentions.get(intention, {}).get(contexts, {})
    if instantiations not in combinations:
        raise ValueError('Combined context instantiations must exist to be removed.')
    del combinations[instantiations]
    if not combinations:
        del self.intentions[intention][contexts]

del_context(context)

Remove a context including all its (combined) influences.

Parameters:

Name Type Description Default
context Hashable

Name of the context to delete.

required

Raises:

Type Description
ValueError

If the context does not exist.

Source code in cobair/model.py
401
402
403
404
405
406
407
408
409
410
411
412
413
414
def del_context(self, context: Hashable) -> None:
    """Remove a context including all its (combined) influences.

    Args:
        context: Name of the context to delete.

    Raises:
        ValueError: If the context does not exist.
    """
    if context not in self.contexts:
        raise ValueError(
            'Cannot delete non-existing context - use add_context to add a new context')
    del self.contexts[context]
    self._sync_influences()

del_intention(intention)

Remove an intention.

Parameters:

Name Type Description Default
intention Hashable

Name of the intention to delete.

required

Raises:

Type Description
ValueError

If the intention does not exist.

Source code in cobair/model.py
448
449
450
451
452
453
454
455
456
457
458
459
460
def del_intention(self, intention: Hashable) -> None:
    """Remove an intention.

    Args:
        intention: Name of the intention to delete.

    Raises:
        ValueError: If the intention does not exist.
    """
    if intention not in self.intentions:
        raise ValueError(
            'Cannot delete non existing intention - use add_intention to add a new intention')
    del self.intentions[intention]

dumps()

Return the config as YAML text with header.

Returns:

Name Type Description
str str

The content of a config file.

Source code in cobair/model.py
231
232
233
234
235
236
237
238
239
def dumps(self) -> str:
    """Return the config as YAML text with header.

    Returns:
        str: The content of a config file.
    """
    data = {'format_version': FORMAT_VERSION, 'created_with': f'cobair {__version__}'}
    data.update(self.to_dict())
    return HEADER + yaml.dump(data, Dumper=_Dumper, sort_keys=False, allow_unicode=True)

edit_context(context, instantiations, new_name=None)

Change the instantiations of a context and optionally rename it.

Influences of removed instantiations are removed, new instantiations get the influence 0. Combined influences follow a rename and are removed if they use a removed instantiation.

Note

Changing the name of an instantiation will always set the influence value of this instantiation to zero for all intentions!

Parameters:

Name Type Description Default
context Hashable

Name of the context to edit.

required
instantiations dict

{instantiation: apriori probability}, e.g. {True: 0.6, False: 0.4}

required
new_name Hashable

A new name for the context.

None

Raises:

Type Description
ValueError

If the context does not exist or new_name is another existing context.

Source code in cobair/model.py
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
def edit_context(self, context: Hashable, instantiations: dict,
                 new_name: Hashable = None) -> None:
    """Change the instantiations of a context and optionally rename it.

    Influences of removed instantiations are removed, new instantiations get the influence 0.
    Combined influences follow a rename and are removed if they use a removed instantiation.

    !!! note
        Changing the name of an instantiation will always set the influence value of this
            instantiation to zero for all intentions!

    Args:
        context: Name of the context to edit.
        instantiations: `{instantiation: apriori probability}`, e.g. `{True: 0.6, False: 0.4}`
        new_name: A new name for the context.

    Raises:
        ValueError: If the context does not exist or `new_name` is another existing context.
    """
    if context not in self.contexts:
        raise ValueError(
            'Cannot edit non existing context - use add_context to add a new context')
    if new_name is not None and new_name != context:
        if new_name in self.contexts:
            raise ValueError(f'Cannot rename "{context}" to "{new_name}" - it exists already')
        self.contexts = _rename_key(self.contexts, context, new_name)
        for intention, influences in self.intentions.items():
            renamed = {}
            for key, values in influences.items():
                if key == context:
                    renamed[new_name] = values
                elif isinstance(key, tuple) and context in key:
                    renamed[tuple(new_name if name == context else name for name in key)] = \
                        values
                else:
                    renamed[key] = values
            self.intentions[intention] = renamed
        context = new_name
    self.contexts[context] = dict(instantiations)
    self._sync_influences()

edit_intention(intention, new_name)

Rename an intention.

Parameters:

Name Type Description Default
intention Hashable

Name of the intention to edit.

required
new_name Hashable

A new name for the intention.

required

Raises:

Type Description
ValueError

If the intention does not exist or new_name exists already.

Source code in cobair/model.py
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
def edit_intention(self, intention: Hashable, new_name: Hashable) -> None:
    """Rename an intention.

    Args:
        intention: Name of the intention to edit.
        new_name: A new name for the intention.

    Raises:
        ValueError: If the intention does not exist or `new_name` exists already.
    """
    if intention not in self.intentions:
        raise ValueError(
            'Cannot edit non existing intention - use add_intention to add a new intention')
    if new_name in self.intentions:
        raise ValueError(f'{new_name} exists - cannot be given as the new name for {intention}')
    self.intentions = _rename_key(self.intentions, intention, new_name)

from_dict(config) classmethod

Create a config from a dict in the config file format; unknown keys are ignored.

Parameters:

Name Type Description Default
config dict

A dict with the keys contexts, intentions and decision_threshold.

required

Returns:

Name Type Description
Config Config

The new config.

Source code in cobair/model.py
162
163
164
165
166
167
168
169
170
171
172
173
174
@classmethod
def from_dict(cls, config: dict) -> Config:
    """Create a config from a dict in the config file format; unknown keys are ignored.

    Args:
        config: A dict with the keys `contexts`, `intentions` and `decision_threshold`.

    Returns:
        Config: The new config.
    """
    config = config or {}
    return cls(config.get('contexts'), config.get('intentions'),
               config.get('decision_threshold', 0.0))

load(path) classmethod

Load a config from a YAML file.

Parameters:

Name Type Description Default
path

Path to the config file.

required

Returns:

Name Type Description
Config Config

The loaded config.

Source code in cobair/model.py
219
220
221
222
223
224
225
226
227
228
229
@classmethod
def load(cls, path) -> Config:
    """Load a config from a YAML file.

    Args:
        path: Path to the config file.

    Returns:
        Config: The loaded config.
    """
    return cls.loads(Path(path).read_text(encoding='utf-8'))

loads(text) classmethod

Create a config from YAML text.

Parameters:

Name Type Description Default
text str

The content of a config file.

required

Returns:

Name Type Description
Config Config

The loaded config.

Raises:

Type Description
ValueError

If the text is not a mapping or was written with a newer format version.

Source code in cobair/model.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
@classmethod
def loads(cls, text: str) -> Config:
    """Create a config from YAML text.

    Args:
        text: The content of a config file.

    Returns:
        Config: The loaded config.

    Raises:
        ValueError: If the text is not a mapping or was written with a newer format version.
    """
    data = yaml.load(text, Loader=PrettySafeLoader)  # noqa: S506 - safe loader + tuples
    if data is None:
        data = {}
    if not isinstance(data, dict):
        raise ValueError('A config must be a YAML mapping')
    format_version = data.get('format_version', FORMAT_VERSION)
    if not isinstance(format_version, int) or format_version > FORMAT_VERSION:
        raise ValueError(
            f'The config has format version {format_version}, but cobair {__version__} '
            f'only supports up to version {FORMAT_VERSION}. Please update cobair.')
    return cls.from_dict(data)

save(path)

Save the config to a YAML file.

Parameters:

Name Type Description Default
path

Path to the config file.

required
Source code in cobair/model.py
241
242
243
244
245
246
247
def save(self, path) -> None:
    """Save the config to a YAML file.

    Args:
        path: Path to the config file.
    """
    Path(path).write_text(self.dumps(), encoding='utf-8')

to_dict()

Return the config as plain dicts in the config file format (without header).

Returns:

Name Type Description
dict dict

A deep copy of the config.

Source code in cobair/model.py
176
177
178
179
180
181
182
183
184
def to_dict(self) -> dict:
    """Return the config as plain dicts in the config file format (without header).

    Returns:
        dict: A deep copy of the config.
    """
    return {'contexts': deepcopy(self.contexts),
            'intentions': deepcopy(self.intentions),
            'decision_threshold': self.decision_threshold}

validate()

Check that the config is complete and consistent.

Returns:

Name Type Description
list list

Messages describing all problems, empty if the config is valid.

Source code in cobair/model.py
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
def validate(self) -> list:
    """Check that the config is complete and consistent.

    Returns:
        list: Messages describing all problems, empty if the config is valid.
    """
    problems = []
    if not self.contexts:
        problems.append('No contexts defined')
    if not self.intentions:
        problems.append('No intentions defined')
    if not _is_number(self.decision_threshold) or not 0 <= self.decision_threshold < 1:
        problems.append('Decision threshold must be a number between 0 and 1')

    for context, instantiations in self.contexts.items():
        for instantiation, value in instantiations.items():
            if not _is_number(value):
                problems.append(
                    f'Apriori probability of context "{context}.{instantiation}" '
                    'is not a number')
        values = [value for value in instantiations.values() if _is_number(value)]
        if len(values) == len(instantiations) and \
                not math.isclose(sum(values), 1.0, abs_tol=1e-9):
            problems.append(
                'The sum of probabilities for context instantiations must be 1 - '
                f'For "{context}" it is {sum(values)}!')

    for intention, influences in self.intentions.items():
        for context, values in influences.items():
            problems.extend(self._validate_influences(intention, context, values))
    return problems

PrettySafeLoader

Bases: SafeLoader

A YAML loader that constructs Python tuples from YAML sequences.

Source code in cobair/model.py
54
55
56
57
58
59
60
61
62
63
64
65
66
class PrettySafeLoader(yaml.SafeLoader):  # pylint: disable=too-many-ancestors
    """A YAML loader that constructs Python tuples from YAML sequences."""

    def construct_python_tuple(self, node):
        """Construct a Python tuple from a YAML sequence node.

        Args:
            node (Any): The YAML sequence node to construct a tuple from.

        Returns:
            tuple: The constructed tuple.
        """
        return tuple(self.construct_sequence(node))

construct_python_tuple(node)

Construct a Python tuple from a YAML sequence node.

Parameters:

Name Type Description Default
node Any

The YAML sequence node to construct a tuple from.

required

Returns:

Name Type Description
tuple

The constructed tuple.

Source code in cobair/model.py
57
58
59
60
61
62
63
64
65
66
def construct_python_tuple(self, node):
    """Construct a Python tuple from a YAML sequence node.

    Args:
        node (Any): The YAML sequence node to construct a tuple from.

    Returns:
        tuple: The constructed tuple.
    """
    return tuple(self.construct_sequence(node))

cobair.infer

Inference of intentions from context with the two-layer Bayesian net.

This is a thin adapter: the conditional probability tables are computed by cobair.model, this module hands them to pgmpy / bnlearn. It needs the [infer] extra (pip install "cobair[infer]").

Example
from cobair.model import Config
from cobair.infer import Inference

inference = Inference(Config.load('small_example.yml'))
intention, decision_threshold, probabilities = inference.infer({'speech commands': 'pickup'})

Inference

Infers the probabilities of the intentions of a valid config.

The inference works on a copy of the config: create a new Inference after editing it.

Source code in cobair/infer.py
 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
class Inference:
    """Infers the probabilities of the intentions of a valid config.

    The inference works on a copy of the config: create a new `Inference` after editing it.
    """

    def __init__(self, config: Config) -> None:
        """Build the Bayesian net for a config, which must be valid (else `ValueError`).

        Args:
            config: A valid config.
        """
        self.config = config.copy()
        self.cpts = self.config.cpts()
        self.discretization_functions = {}
        # bnlearn uses the index of an instantiation (card) instead of the instantiation
        self.value_to_card = {context: {value: card for card, value in enumerate(states)}
                              for context, states in self.cpts.states.items()}
        self.tabular_cpds = self._create_tabular_cpds()
        edges = list(itertools.product(self.cpts.contexts, self.cpts.intentions))
        self.dag = bn.make_DAG(edges, CPD=self.tabular_cpds)

    def _create_tabular_cpds(self) -> list:
        """Wrap the CPTs in pgmpy TabularCPDs.

        Returns:
            list: One TabularCPD per context and intention.
        """
        cpds = [TabularCPD(variable=context, variable_card=len(priors),
                           values=[[prior] for prior in priors])
                for context, priors in self.cpts.context_priors.items()]
        cpds += [TabularCPD(variable=intention,
                            variable_card=2,  # intentions are always binary
                            values=values,
                            evidence=self.cpts.contexts,
                            evidence_card=self.cpts.cards)
                 for intention, values in self.cpts.intention_values.items()]
        return cpds

    def bind_discretization_function(self, context: Hashable,
                                     discretization_function: Callable) -> None:
        """Bind a discretization function to a context.

        Args:
            context: One of the contexts of the config.
            discretization_function: A function which takes one parameter and returns one of the
                instantiations of the context.

        Raises:
            ValueError: If the context does not exist.
        """
        if context not in self.config.contexts:
            raise ValueError(
                f'Cannot bind discretization function to {context}. Context does not exist!')
        self.discretization_functions[context] = discretization_function

    def check_evidence(self, context: Hashable, instantiation) -> tuple[bool, str]:
        """Check if an instantiation is valid evidence for a context.

        Args:
            context: A context.
            instantiation: An instantiation of the context.

        Returns:
            tuple[bool, str]: Validity and an error or warning message (empty if fine).
        """
        if context not in self.config.contexts:
            return True, f'Context "{context}" not set in config - will be ignored'
        if not isinstance(instantiation, Hashable):
            return False, ('Context instatiations must be hashable! '
                           f'Instantiation "{instantiation}" for context "{context}" '
                           'is not hashable!')
        if instantiation is None:
            return True, (f'No instantiation given for context "{context}" - '
                          'A prori values will be used.')
        if instantiation not in self.config.contexts[context]:
            return True, (f'"{instantiation}" is not a valid instantiation for "{context}". '
                          f'Using None instead Valid options are '
                          f'{list(self.config.contexts[context])}')
        return True, ''

    def _card_evidence(self, evidence: dict) -> dict:
        """Translate evidence into bnlearn's card form.

        Discretization functions are applied to values that are not an instantiation.

        Args:
            evidence: `{context: instantiation}`

        Returns:
            dict: `{context: card}` of all usable evidence.

        Raises:
            ValueError: If evidence is invalid.
        """
        card_evidence = {}
        errors = []
        for context, instantiation in evidence.items():
            if context in self.discretization_functions and instantiation is not None and \
                    not (isinstance(instantiation, Hashable)
                         and instantiation in self.value_to_card[context]):
                instantiation = self.discretization_functions[context](instantiation)
            valid, message = self.check_evidence(context, instantiation)
            if not valid:
                errors.append(message)
            elif message:
                warnings.warn(message, stacklevel=3)
            else:
                card_evidence[context] = self.value_to_card[context][instantiation]
        if errors:
            raise ValueError(f'{errors}')
        return card_evidence

    def infer(self, evidence: dict, normalized: bool = True,
              decision_threshold: float = None) -> InferenceResult:
        """Infer the probabilities of the intentions given evidence.

        Args:
            evidence: `{context: instantiation}`, e.g. `{'speech commands': 'pickup'}`.
                Contexts which are not in the config are ignored (with a warning),
                contexts which are not given use their apriori probabilities.
            normalized: Normalize the probabilities to sum up to 1.
            decision_threshold: A threshold for picking the most likely intention, between 0
                and 1. Defaults to the decision threshold of the config.

        Returns:
            InferenceResult: The most likely intention (None if the decision threshold is not
                exceeded), the decision threshold and the probabilities of all intentions.
        """
        if decision_threshold is None:
            decision_threshold = self.config.decision_threshold
        card_evidence = self._card_evidence(evidence)
        # only the probability of the True state of the binary intentions is kept
        probabilities = {
            intention: bn.inference.fit(self.dag, variables=[intention],
                                        evidence=card_evidence).values[1]
            for intention in self.cpts.intentions}
        if normalized:
            probabilities = normalize(probabilities)
        best = max(probabilities, key=probabilities.get)
        if probabilities[best] <= decision_threshold:
            best = None
        return InferenceResult(best, decision_threshold, probabilities)

__init__(config)

Build the Bayesian net for a config, which must be valid (else ValueError).

Parameters:

Name Type Description Default
config Config

A valid config.

required
Source code in cobair/infer.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def __init__(self, config: Config) -> None:
    """Build the Bayesian net for a config, which must be valid (else `ValueError`).

    Args:
        config: A valid config.
    """
    self.config = config.copy()
    self.cpts = self.config.cpts()
    self.discretization_functions = {}
    # bnlearn uses the index of an instantiation (card) instead of the instantiation
    self.value_to_card = {context: {value: card for card, value in enumerate(states)}
                          for context, states in self.cpts.states.items()}
    self.tabular_cpds = self._create_tabular_cpds()
    edges = list(itertools.product(self.cpts.contexts, self.cpts.intentions))
    self.dag = bn.make_DAG(edges, CPD=self.tabular_cpds)

bind_discretization_function(context, discretization_function)

Bind a discretization function to a context.

Parameters:

Name Type Description Default
context Hashable

One of the contexts of the config.

required
discretization_function Callable

A function which takes one parameter and returns one of the instantiations of the context.

required

Raises:

Type Description
ValueError

If the context does not exist.

Source code in cobair/infer.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def bind_discretization_function(self, context: Hashable,
                                 discretization_function: Callable) -> None:
    """Bind a discretization function to a context.

    Args:
        context: One of the contexts of the config.
        discretization_function: A function which takes one parameter and returns one of the
            instantiations of the context.

    Raises:
        ValueError: If the context does not exist.
    """
    if context not in self.config.contexts:
        raise ValueError(
            f'Cannot bind discretization function to {context}. Context does not exist!')
    self.discretization_functions[context] = discretization_function

check_evidence(context, instantiation)

Check if an instantiation is valid evidence for a context.

Parameters:

Name Type Description Default
context Hashable

A context.

required
instantiation

An instantiation of the context.

required

Returns:

Type Description
tuple[bool, str]

tuple[bool, str]: Validity and an error or warning message (empty if fine).

Source code in cobair/infer.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def check_evidence(self, context: Hashable, instantiation) -> tuple[bool, str]:
    """Check if an instantiation is valid evidence for a context.

    Args:
        context: A context.
        instantiation: An instantiation of the context.

    Returns:
        tuple[bool, str]: Validity and an error or warning message (empty if fine).
    """
    if context not in self.config.contexts:
        return True, f'Context "{context}" not set in config - will be ignored'
    if not isinstance(instantiation, Hashable):
        return False, ('Context instatiations must be hashable! '
                       f'Instantiation "{instantiation}" for context "{context}" '
                       'is not hashable!')
    if instantiation is None:
        return True, (f'No instantiation given for context "{context}" - '
                      'A prori values will be used.')
    if instantiation not in self.config.contexts[context]:
        return True, (f'"{instantiation}" is not a valid instantiation for "{context}". '
                      f'Using None instead Valid options are '
                      f'{list(self.config.contexts[context])}')
    return True, ''

infer(evidence, normalized=True, decision_threshold=None)

Infer the probabilities of the intentions given evidence.

Parameters:

Name Type Description Default
evidence dict

{context: instantiation}, e.g. {'speech commands': 'pickup'}. Contexts which are not in the config are ignored (with a warning), contexts which are not given use their apriori probabilities.

required
normalized bool

Normalize the probabilities to sum up to 1.

True
decision_threshold float

A threshold for picking the most likely intention, between 0 and 1. Defaults to the decision threshold of the config.

None

Returns:

Name Type Description
InferenceResult InferenceResult

The most likely intention (None if the decision threshold is not exceeded), the decision threshold and the probabilities of all intentions.

Source code in cobair/infer.py
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
def infer(self, evidence: dict, normalized: bool = True,
          decision_threshold: float = None) -> InferenceResult:
    """Infer the probabilities of the intentions given evidence.

    Args:
        evidence: `{context: instantiation}`, e.g. `{'speech commands': 'pickup'}`.
            Contexts which are not in the config are ignored (with a warning),
            contexts which are not given use their apriori probabilities.
        normalized: Normalize the probabilities to sum up to 1.
        decision_threshold: A threshold for picking the most likely intention, between 0
            and 1. Defaults to the decision threshold of the config.

    Returns:
        InferenceResult: The most likely intention (None if the decision threshold is not
            exceeded), the decision threshold and the probabilities of all intentions.
    """
    if decision_threshold is None:
        decision_threshold = self.config.decision_threshold
    card_evidence = self._card_evidence(evidence)
    # only the probability of the True state of the binary intentions is kept
    probabilities = {
        intention: bn.inference.fit(self.dag, variables=[intention],
                                    evidence=card_evidence).values[1]
        for intention in self.cpts.intentions}
    if normalized:
        probabilities = normalize(probabilities)
    best = max(probabilities, key=probabilities.get)
    if probabilities[best] <= decision_threshold:
        best = None
    return InferenceResult(best, decision_threshold, probabilities)

InferenceResult

Bases: NamedTuple

The result of an inference, unpacks like the tuple BayesNet.infer returned.

Attributes:

Name Type Description
intention Hashable | None

The most likely intention or None if its probability doesn't exceed the decision threshold.

decision_threshold float

The decision threshold that was used.

probabilities dict

{intention: probability}

Source code in cobair/infer.py
36
37
38
39
40
41
42
43
44
45
46
47
48
class InferenceResult(NamedTuple):
    """The result of an inference, unpacks like the tuple `BayesNet.infer` returned.

    Attributes:
        intention: The most likely intention or None if its probability doesn't exceed
            the decision threshold.
        decision_threshold: The decision threshold that was used.
        probabilities: `{intention: probability}`
    """

    intention: Hashable | None
    decision_threshold: float
    probabilities: dict

normalize(probabilities)

Normalize the probabilities of the intentions to a probability distribution.

Each intention is inferred independently as True or False, so the raw probabilities don't sum up to 1 and can't be compared as a distribution over intentions.

Parameters:

Name Type Description Default
probabilities dict

{intention: probability}

required

Returns:

Name Type Description
dict dict

{intention: normalized probability}

Source code in cobair/infer.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def normalize(probabilities: dict) -> dict:
    """Normalize the probabilities of the intentions to a probability distribution.

    Each intention is inferred independently as True or False, so the raw probabilities don't sum
    up to 1 and can't be compared as a distribution over intentions.

    Args:
        probabilities: `{intention: probability}`

    Returns:
        dict: `{intention: normalized probability}`
    """
    total = sum(probabilities.values())
    return {intention: probability / total for intention, probability in probabilities.items()}

Deprecated: cobair.bayes_net

The 4.x API BayesNet, load_config, config_to_default_dict and default_to_regular still works in 5.x, but raises a DeprecationWarning and will be removed in 6.0.0.

Deprecated 4.x API, use cobair.model and cobair.infer instead. Removed in 6.0.0.

4.x 5.x
BayesNet(config) Config.from_dict(config) + Inference(config)
BayesNet().load(path), load_config(path) Config.load(path)
bayes_net.add_context(...) etc. config.add_context(...) etc.
bayes_net.validate_config() config.validate()
bayes_net.infer(evidence) Inference(config).infer(evidence)
bayes_net.save(path) config.save(path)

BayesNet

Deprecated facade over cobair.model.Config and cobair.infer.Inference.

config is the source of truth like in 4.x: every method reads it, applies the change through Config and replaces it with the result.

Source code in cobair/bayes_net.py
 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
class BayesNet:
    """Deprecated facade over `cobair.model.Config` and `cobair.infer.Inference`.

    `config` is the source of truth like in 4.x: every method reads it, applies the change through
    `Config` and replaces it with the result.
    """

    def __init__(self, config: dict = None, bn_verbosity: int = 0, validate: bool = True) -> None:
        """Initializes the BayesNet with the given config.

        Args:
            config: A dict with a config following the config format.
            bn_verbosity: Ignored since bnlearn 1.x, which logs through `logging`.
            validate: Flag if the given config should be validated or not.
                This is necessary to load invalid configs
        """
        _deprecated('cobair.bayes_net.BayesNet', 'cobair.model.Config and cobair.infer.Inference')
        self.log = logging.getLogger(self.__class__.__name__)
        self.bn_verbosity = bn_verbosity
        self.discretization_functions = {}
        self.value_to_prob = INFLUENCE_TO_PROBABILITY
        self._set_config(Config.from_dict(config), validate=validate and config is not None)

    # ------------------------------------------------------------------------------------------
    # state

    def _model(self) -> Config:
        """Return the current `config` as `Config`.

        Returns:
            Config: The model.
        """
        return Config.from_dict(self.config)

    def _set_config(self, model: Config, validate: bool = True) -> None:
        """Replace the config and rebuild everything that depends on it, like `__init__` in 4.x.

        Args:
            model: The new config.
            validate: Flag if the config should be validated (with warnings).
        """
        self.config = _config_to_default_dict(model.to_dict())
        self.decision_threshold = model.decision_threshold
        self.contexts = self.evidence = list(model.contexts)
        self.intentions = list(model.intentions)
        self.edges = [(context, intention) for context in self.contexts
                      for intention in self.intentions]
        self.evidence_card = [len(model.contexts[context]) for context in self.contexts]
        self.value_to_card = defaultdict(dict, {
            context: {value: card for card, value in enumerate(instantiations)}
            for context, instantiations in model.contexts.items()})
        self.card_to_value = defaultdict(dict, {
            context: dict(enumerate(instantiations))
            for context, instantiations in model.contexts.items()})
        self.valid = self._validate(model) if validate else False
        self.inference = None
        self.cpts = self.DAG = None
        if self.valid:
            self.valid_config = _config_to_default_dict(model.to_dict())
            self.inference = Inference(model)
            self.inference.discretization_functions = self.discretization_functions
            self.cpts = self.inference.tabular_cpds
            self.DAG = self.inference.dag

    def _apply(self, method: str, *args) -> None:
        """Apply an editing method of `Config` and rebuild.

        Args:
            method: Name of the `Config` method.
            *args: Arguments of the method.
        """
        model = self._model()
        getattr(model, method)(*args)
        self._set_config(model)

    @staticmethod
    def _validate(model: Config) -> bool:
        """Validate with a warning for every problem.

        Args:
            model: The config.

        Returns:
            bool: True if the config is valid.
        """
        problems = model.validate()
        for problem in problems:
            warnings.warn(problem, stacklevel=4)
        return not problems

    def validate_config(self) -> bool:
        """Validate that the current config follows the correct format.

        Returns:
            bool: True if config is valid, False otherwise. A warning is raised for every problem.
        """
        model = self._model()
        self.valid = self._validate(model)
        if self.valid:
            self.valid_config = _config_to_default_dict(model.to_dict())
        return self.valid

    # ------------------------------------------------------------------------------------------
    # editing

    def add_context(self, context: str, instantiations: dict):
        """This will add a new context to the config and updates the bayesNet.

        Args:
            context: a new context for the config
            instantiations: a dict of the instantiations and their apriori probabilities
        """
        self._apply('add_context', context, instantiations)

    def add_intention(self, intention: str):
        """This will add a new intention to the config and updates the bayesNet.

        Args:
            intention: Name of a new intention
        """
        self._apply('add_intention', intention)

    def edit_context(self, context: str, instantiations: dict, new_name: str = None):
        """Edits an existing context - this can also be used to remove instantiations.

        Args:
            context: Name of the context to edit
            instantiations: A Dict of instantiations and their apriori probabilities.
            new_name: A new name for the context
        """
        self._apply('edit_context', context, instantiations, new_name)

    def edit_intention(self, intention: str, new_name: str):
        """Edits an existing intention.

        Args:
            intention: Name of the intention to edit
            new_name: A new name for the intention
        """
        self._apply('edit_intention', intention, new_name)

    def del_context(self, context: str):
        """Removes a context.

        Args:
            context: Name of the context to delete
        """
        self._apply('del_context', context)

    def del_intention(self, intention):
        """Remove an intention.

        Args:
            intention: Name of the intention to delete
        """
        self._apply('del_intention', intention)

    def change_context_apriori_value(self, context: str, instantiation, value: float):
        """Changes the apriori_value for a context instantiation.

        Args:
            context: Name of the context
            instantiation: The instantiation for which the apriori value needs to be changed
            value: the new apriori value
        """
        self._apply('change_context_apriori_value', context, instantiation, value)

    def change_influence_value(self, intention: str, context: str, instantiation, value: int):
        """Update the influence value of a specific intention for a particular context instance.

        Args:
            intention: Name of the intention
            context: name of the context
            instantiation: The instantiation for which the influence value should be changed
            value: the new influence value. Can be one out of [0, 1, 2, 3, 4, 5]
        """
        self._apply('change_influence_value', intention, context, instantiation, value)

    def add_combined_influence(self, intention: str, contexts: tuple,
                               instantiations: tuple, value: int):
        """Adds an influence value for a combination of context instantiations.

        Args:
            intention: Name of the intention
            contexts: tuple containing the names of the contexts
            instantiations: Tuple of context instances to set influence value for.
            value: influence value. Can be one out of [0, 1, 2, 3, 4, 5]
        """
        self._apply('add_combined_influence', intention, contexts, instantiations, value)

    def del_combined_influence(self, intention: str, contexts: tuple, instantiations: tuple):
        """Removes the influence value for a combination of context instantiations.

        Args:
            intention: Name of the intention
            contexts: tuple containing the names of the contexts
            instantiations: tuple of context instantiations
        """
        self._apply('del_combined_influence', intention, contexts, instantiations)

    def change_decision_threshold(self, decision_threshold):
        """Changes the decision threshold in the config.

        Args:
            decision_threshold: The new decision threshold.
        """
        self._apply('change_decision_threshold', decision_threshold)

    # ------------------------------------------------------------------------------------------
    # files

    def save(self, path: str, save_invalid: bool = True):
        """Saves the config of the bayesNet to a yml file.

        Args:
            path: path to the file the config will be saved in
            save_invalid: Flag to decide if invalid configs can be saved
        """
        if not self.valid and not save_invalid:
            warnings.warn("Invalid configuration will not be saved.", stacklevel=2)
        else:
            self._model().save(path)

    def load(self, path: str):
        """Loads a config from file and reinitializes the bayesNet.

        Args:
            path: path to the file the config is saved in
        """
        self._set_config(Config.load(path))

    # ------------------------------------------------------------------------------------------
    # inference

    def bind_discretization_function(self, context, discretization_function):
        """Binds a discretization_function to a specific context.

        Args:
            context: One of the possible contexts from the config
            discretization_function: A discretization function which has to take one parameter
                and return one of the possible discrete context instantiations.

        Raises:
            ValueError: If the context does not exist.
        """
        if context not in self.contexts:
            raise ValueError(
                f'Cannot bind discretization function to {context}. Context does not exist!')
        self.discretization_functions[context] = discretization_function

    def valid_evidence(self, context: str, instantiation) -> tuple[bool, str]:
        """Tests if evidence is a valid instantiation for the context.

        Args:
            context: a context
            instantiation: an instantiation of the context

        Returns:
            tuple[bool, str]: validity and an error/warn message

        Raises:
            ValueError: If the config is invalid.
        """
        if self.inference is None:
            raise ValueError('Invalid configuration')
        return self.inference.check_evidence(context, instantiation)

    def infer(self, evidence, normalized=True, decision_threshold=None) -> tuple:
        """Infers the probabilities for the intentions with given evidence.

        Args:
            evidence: Evidence to infer the probabilities of all intentions.
            normalized: Flag if the returned inference is normalized to sum up to 1.
            decision_threshold: a threshold for picking the most likely intention.

        Returns:
            tuple: the highest ranking intention (or None), the decision threshold and a
                dictionary of intentions and the corresponding probabilities.

        Raises:
            ValueError: If the config is invalid.
        """
        if not self.valid or self.inference is None:
            raise ValueError('Invalid configuration')
        return self.inference.infer(evidence, normalized, decision_threshold)

    def normalize_inference(self, inference: dict) -> dict:
        """Normalizes the inference to a proper probability distribution.

        Args:
            inference: dictionary of intentions and the corresponding probabilities

        Returns:
            dict: dictionary of intentions and the corresponding normalized probabilities.
        """
        return normalize(inference)

    # ------------------------------------------------------------------------------------------
    # internals used by old tests

    def _calculate_probability_values(self, context_influence: dict) -> list:
        """Calculates the probability values with the given context_influence from the config.

        Args:
            context_influence: A dict with the influence values for contexts.

        Returns:
            list: `[negative values, positive values]`
        """
        states = {context: list(instantiations)
                  for context, instantiations in self.config['contexts'].items()}
        # pylint: disable-next=protected-access
        return Config._intention_values(self.evidence, states, context_influence)

    def _create_combined_context(self, context_influence: dict) -> dict:
        """Creates a dict with the combined contexts in card index format from context_influence.

        Args:
            context_influence: A dict with the influence values for contexts.

        Returns:
            dict: `{(context index, ...): {(instantiation, ...): influence}}`
        """
        return {tuple(map(self.evidence.index, context)): values
                for context, values in context_influence.items() if isinstance(context, tuple)}

__init__(config=None, bn_verbosity=0, validate=True)

Initializes the BayesNet with the given config.

Parameters:

Name Type Description Default
config dict

A dict with a config following the config format.

None
bn_verbosity int

Ignored since bnlearn 1.x, which logs through logging.

0
validate bool

Flag if the given config should be validated or not. This is necessary to load invalid configs

True
Source code in cobair/bayes_net.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def __init__(self, config: dict = None, bn_verbosity: int = 0, validate: bool = True) -> None:
    """Initializes the BayesNet with the given config.

    Args:
        config: A dict with a config following the config format.
        bn_verbosity: Ignored since bnlearn 1.x, which logs through `logging`.
        validate: Flag if the given config should be validated or not.
            This is necessary to load invalid configs
    """
    _deprecated('cobair.bayes_net.BayesNet', 'cobair.model.Config and cobair.infer.Inference')
    self.log = logging.getLogger(self.__class__.__name__)
    self.bn_verbosity = bn_verbosity
    self.discretization_functions = {}
    self.value_to_prob = INFLUENCE_TO_PROBABILITY
    self._set_config(Config.from_dict(config), validate=validate and config is not None)

add_combined_influence(intention, contexts, instantiations, value)

Adds an influence value for a combination of context instantiations.

Parameters:

Name Type Description Default
intention str

Name of the intention

required
contexts tuple

tuple containing the names of the contexts

required
instantiations tuple

Tuple of context instances to set influence value for.

required
value int

influence value. Can be one out of [0, 1, 2, 3, 4, 5]

required
Source code in cobair/bayes_net.py
219
220
221
222
223
224
225
226
227
228
229
def add_combined_influence(self, intention: str, contexts: tuple,
                           instantiations: tuple, value: int):
    """Adds an influence value for a combination of context instantiations.

    Args:
        intention: Name of the intention
        contexts: tuple containing the names of the contexts
        instantiations: Tuple of context instances to set influence value for.
        value: influence value. Can be one out of [0, 1, 2, 3, 4, 5]
    """
    self._apply('add_combined_influence', intention, contexts, instantiations, value)

add_context(context, instantiations)

This will add a new context to the config and updates the bayesNet.

Parameters:

Name Type Description Default
context str

a new context for the config

required
instantiations dict

a dict of the instantiations and their apriori probabilities

required
Source code in cobair/bayes_net.py
146
147
148
149
150
151
152
153
def add_context(self, context: str, instantiations: dict):
    """This will add a new context to the config and updates the bayesNet.

    Args:
        context: a new context for the config
        instantiations: a dict of the instantiations and their apriori probabilities
    """
    self._apply('add_context', context, instantiations)

add_intention(intention)

This will add a new intention to the config and updates the bayesNet.

Parameters:

Name Type Description Default
intention str

Name of a new intention

required
Source code in cobair/bayes_net.py
155
156
157
158
159
160
161
def add_intention(self, intention: str):
    """This will add a new intention to the config and updates the bayesNet.

    Args:
        intention: Name of a new intention
    """
    self._apply('add_intention', intention)

bind_discretization_function(context, discretization_function)

Binds a discretization_function to a specific context.

Parameters:

Name Type Description Default
context

One of the possible contexts from the config

required
discretization_function

A discretization function which has to take one parameter and return one of the possible discrete context instantiations.

required

Raises:

Type Description
ValueError

If the context does not exist.

Source code in cobair/bayes_net.py
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
def bind_discretization_function(self, context, discretization_function):
    """Binds a discretization_function to a specific context.

    Args:
        context: One of the possible contexts from the config
        discretization_function: A discretization function which has to take one parameter
            and return one of the possible discrete context instantiations.

    Raises:
        ValueError: If the context does not exist.
    """
    if context not in self.contexts:
        raise ValueError(
            f'Cannot bind discretization function to {context}. Context does not exist!')
    self.discretization_functions[context] = discretization_function

change_context_apriori_value(context, instantiation, value)

Changes the apriori_value for a context instantiation.

Parameters:

Name Type Description Default
context str

Name of the context

required
instantiation

The instantiation for which the apriori value needs to be changed

required
value float

the new apriori value

required
Source code in cobair/bayes_net.py
198
199
200
201
202
203
204
205
206
def change_context_apriori_value(self, context: str, instantiation, value: float):
    """Changes the apriori_value for a context instantiation.

    Args:
        context: Name of the context
        instantiation: The instantiation for which the apriori value needs to be changed
        value: the new apriori value
    """
    self._apply('change_context_apriori_value', context, instantiation, value)

change_decision_threshold(decision_threshold)

Changes the decision threshold in the config.

Parameters:

Name Type Description Default
decision_threshold

The new decision threshold.

required
Source code in cobair/bayes_net.py
241
242
243
244
245
246
247
def change_decision_threshold(self, decision_threshold):
    """Changes the decision threshold in the config.

    Args:
        decision_threshold: The new decision threshold.
    """
    self._apply('change_decision_threshold', decision_threshold)

change_influence_value(intention, context, instantiation, value)

Update the influence value of a specific intention for a particular context instance.

Parameters:

Name Type Description Default
intention str

Name of the intention

required
context str

name of the context

required
instantiation

The instantiation for which the influence value should be changed

required
value int

the new influence value. Can be one out of [0, 1, 2, 3, 4, 5]

required
Source code in cobair/bayes_net.py
208
209
210
211
212
213
214
215
216
217
def change_influence_value(self, intention: str, context: str, instantiation, value: int):
    """Update the influence value of a specific intention for a particular context instance.

    Args:
        intention: Name of the intention
        context: name of the context
        instantiation: The instantiation for which the influence value should be changed
        value: the new influence value. Can be one out of [0, 1, 2, 3, 4, 5]
    """
    self._apply('change_influence_value', intention, context, instantiation, value)

del_combined_influence(intention, contexts, instantiations)

Removes the influence value for a combination of context instantiations.

Parameters:

Name Type Description Default
intention str

Name of the intention

required
contexts tuple

tuple containing the names of the contexts

required
instantiations tuple

tuple of context instantiations

required
Source code in cobair/bayes_net.py
231
232
233
234
235
236
237
238
239
def del_combined_influence(self, intention: str, contexts: tuple, instantiations: tuple):
    """Removes the influence value for a combination of context instantiations.

    Args:
        intention: Name of the intention
        contexts: tuple containing the names of the contexts
        instantiations: tuple of context instantiations
    """
    self._apply('del_combined_influence', intention, contexts, instantiations)

del_context(context)

Removes a context.

Parameters:

Name Type Description Default
context str

Name of the context to delete

required
Source code in cobair/bayes_net.py
182
183
184
185
186
187
188
def del_context(self, context: str):
    """Removes a context.

    Args:
        context: Name of the context to delete
    """
    self._apply('del_context', context)

del_intention(intention)

Remove an intention.

Parameters:

Name Type Description Default
intention

Name of the intention to delete

required
Source code in cobair/bayes_net.py
190
191
192
193
194
195
196
def del_intention(self, intention):
    """Remove an intention.

    Args:
        intention: Name of the intention to delete
    """
    self._apply('del_intention', intention)

edit_context(context, instantiations, new_name=None)

Edits an existing context - this can also be used to remove instantiations.

Parameters:

Name Type Description Default
context str

Name of the context to edit

required
instantiations dict

A Dict of instantiations and their apriori probabilities.

required
new_name str

A new name for the context

None
Source code in cobair/bayes_net.py
163
164
165
166
167
168
169
170
171
def edit_context(self, context: str, instantiations: dict, new_name: str = None):
    """Edits an existing context - this can also be used to remove instantiations.

    Args:
        context: Name of the context to edit
        instantiations: A Dict of instantiations and their apriori probabilities.
        new_name: A new name for the context
    """
    self._apply('edit_context', context, instantiations, new_name)

edit_intention(intention, new_name)

Edits an existing intention.

Parameters:

Name Type Description Default
intention str

Name of the intention to edit

required
new_name str

A new name for the intention

required
Source code in cobair/bayes_net.py
173
174
175
176
177
178
179
180
def edit_intention(self, intention: str, new_name: str):
    """Edits an existing intention.

    Args:
        intention: Name of the intention to edit
        new_name: A new name for the intention
    """
    self._apply('edit_intention', intention, new_name)

infer(evidence, normalized=True, decision_threshold=None)

Infers the probabilities for the intentions with given evidence.

Parameters:

Name Type Description Default
evidence

Evidence to infer the probabilities of all intentions.

required
normalized

Flag if the returned inference is normalized to sum up to 1.

True
decision_threshold

a threshold for picking the most likely intention.

None

Returns:

Name Type Description
tuple tuple

the highest ranking intention (or None), the decision threshold and a dictionary of intentions and the corresponding probabilities.

Raises:

Type Description
ValueError

If the config is invalid.

Source code in cobair/bayes_net.py
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
def infer(self, evidence, normalized=True, decision_threshold=None) -> tuple:
    """Infers the probabilities for the intentions with given evidence.

    Args:
        evidence: Evidence to infer the probabilities of all intentions.
        normalized: Flag if the returned inference is normalized to sum up to 1.
        decision_threshold: a threshold for picking the most likely intention.

    Returns:
        tuple: the highest ranking intention (or None), the decision threshold and a
            dictionary of intentions and the corresponding probabilities.

    Raises:
        ValueError: If the config is invalid.
    """
    if not self.valid or self.inference is None:
        raise ValueError('Invalid configuration')
    return self.inference.infer(evidence, normalized, decision_threshold)

load(path)

Loads a config from file and reinitializes the bayesNet.

Parameters:

Name Type Description Default
path str

path to the file the config is saved in

required
Source code in cobair/bayes_net.py
264
265
266
267
268
269
270
def load(self, path: str):
    """Loads a config from file and reinitializes the bayesNet.

    Args:
        path: path to the file the config is saved in
    """
    self._set_config(Config.load(path))

normalize_inference(inference)

Normalizes the inference to a proper probability distribution.

Parameters:

Name Type Description Default
inference dict

dictionary of intentions and the corresponding probabilities

required

Returns:

Name Type Description
dict dict

dictionary of intentions and the corresponding normalized probabilities.

Source code in cobair/bayes_net.py
327
328
329
330
331
332
333
334
335
336
def normalize_inference(self, inference: dict) -> dict:
    """Normalizes the inference to a proper probability distribution.

    Args:
        inference: dictionary of intentions and the corresponding probabilities

    Returns:
        dict: dictionary of intentions and the corresponding normalized probabilities.
    """
    return normalize(inference)

save(path, save_invalid=True)

Saves the config of the bayesNet to a yml file.

Parameters:

Name Type Description Default
path str

path to the file the config will be saved in

required
save_invalid bool

Flag to decide if invalid configs can be saved

True
Source code in cobair/bayes_net.py
252
253
254
255
256
257
258
259
260
261
262
def save(self, path: str, save_invalid: bool = True):
    """Saves the config of the bayesNet to a yml file.

    Args:
        path: path to the file the config will be saved in
        save_invalid: Flag to decide if invalid configs can be saved
    """
    if not self.valid and not save_invalid:
        warnings.warn("Invalid configuration will not be saved.", stacklevel=2)
    else:
        self._model().save(path)

valid_evidence(context, instantiation)

Tests if evidence is a valid instantiation for the context.

Parameters:

Name Type Description Default
context str

a context

required
instantiation

an instantiation of the context

required

Returns:

Type Description
tuple[bool, str]

tuple[bool, str]: validity and an error/warn message

Raises:

Type Description
ValueError

If the config is invalid.

Source code in cobair/bayes_net.py
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
def valid_evidence(self, context: str, instantiation) -> tuple[bool, str]:
    """Tests if evidence is a valid instantiation for the context.

    Args:
        context: a context
        instantiation: an instantiation of the context

    Returns:
        tuple[bool, str]: validity and an error/warn message

    Raises:
        ValueError: If the config is invalid.
    """
    if self.inference is None:
        raise ValueError('Invalid configuration')
    return self.inference.check_evidence(context, instantiation)

validate_config()

Validate that the current config follows the correct format.

Returns:

Name Type Description
bool bool

True if config is valid, False otherwise. A warning is raised for every problem.

Source code in cobair/bayes_net.py
131
132
133
134
135
136
137
138
139
140
141
def validate_config(self) -> bool:
    """Validate that the current config follows the correct format.

    Returns:
        bool: True if config is valid, False otherwise. A warning is raised for every problem.
    """
    model = self._model()
    self.valid = self._validate(model)
    if self.valid:
        self.valid_config = _config_to_default_dict(model.to_dict())
    return self.valid

PrettySafeLoader

Bases: SafeLoader

A YAML loader that constructs Python tuples from YAML sequences.

Source code in cobair/model.py
54
55
56
57
58
59
60
61
62
63
64
65
66
class PrettySafeLoader(yaml.SafeLoader):  # pylint: disable=too-many-ancestors
    """A YAML loader that constructs Python tuples from YAML sequences."""

    def construct_python_tuple(self, node):
        """Construct a Python tuple from a YAML sequence node.

        Args:
            node (Any): The YAML sequence node to construct a tuple from.

        Returns:
            tuple: The constructed tuple.
        """
        return tuple(self.construct_sequence(node))

construct_python_tuple(node)

Construct a Python tuple from a YAML sequence node.

Parameters:

Name Type Description Default
node Any

The YAML sequence node to construct a tuple from.

required

Returns:

Name Type Description
tuple

The constructed tuple.

Source code in cobair/model.py
57
58
59
60
61
62
63
64
65
66
def construct_python_tuple(self, node):
    """Construct a Python tuple from a YAML sequence node.

    Args:
        node (Any): The YAML sequence node to construct a tuple from.

    Returns:
        tuple: The constructed tuple.
    """
    return tuple(self.construct_sequence(node))

config_to_default_dict(config=None)

This casts a config given as dict into a defaultdict.

Parameters:

Name Type Description Default
config dict

A dict with a config following the config format.

None

Returns:

Name Type Description
dict dict

a defaultdict containing the config

Source code in cobair/bayes_net.py
392
393
394
395
396
397
398
399
400
401
402
def config_to_default_dict(config: dict = None) -> dict:
    """This casts a config given as dict into a defaultdict.

    Args:
        config: A dict with a config following the config format.

    Returns:
        dict: a defaultdict containing the config
    """
    _deprecated('config_to_default_dict', 'cobair.model.Config.from_dict')
    return _config_to_default_dict(config)

default_to_regular(d)

This casts a defaultdict to a regular dict which is needed for saving as yml file.

Parameters:

Name Type Description Default
d

the dict which should be casted

required

Returns:

Name Type Description
dict

a regular dict casted from the defaultdict

Source code in cobair/bayes_net.py
418
419
420
421
422
423
424
425
426
427
428
def default_to_regular(d):
    """This casts a defaultdict to a regular dict which is needed for saving as yml file.

    Args:
        d: the dict which should be casted

    Returns:
        dict: a regular dict casted from the defaultdict
    """
    _deprecated('default_to_regular', 'cobair.model.Config.to_dict')
    return _default_to_regular(d)

load_config(path)

Helper function to load a config.

Parameters:

Name Type Description Default
path

path to the file the config is saved in

required

Returns:

Name Type Description
dict dict

a defaultdict containing the config

Source code in cobair/bayes_net.py
405
406
407
408
409
410
411
412
413
414
415
def load_config(path) -> dict:
    """Helper function to load a config.

    Args:
        path: path to the file the config is saved in

    Returns:
        dict: a defaultdict containing the config
    """
    _deprecated('load_config', 'cobair.model.Config.load')
    return _config_to_default_dict(Config.load(path).to_dict())