-
Notifications
You must be signed in to change notification settings - Fork 0
/
ASP_Parser.py
2972 lines (2423 loc) · 158 KB
/
ASP_Parser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
###########################################################################
###########################################################################
## Python script for running ASP programs with Clingo and parsing models ##
## Copyright (C) 2021 Oliver Michael Kamperis ##
## Email: [email protected] ##
## ##
## This program is free software: you can redistribute it and/or modify ##
## it under the terms of the GNU General Public License as published by ##
## the Free Software Foundation, either version 3 of the License, or ##
## any later version. ##
## ##
## This program is distributed in the hope that it will be useful, ##
## but WITHOUT ANY WARRANTY; without even the implied warranty of ##
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ##
## GNU General Public License for more details. ##
## ##
## You should have received a copy of the GNU General Public License ##
## along with this program. If not, see <https://www.gnu.org/licenses/>. ##
###########################################################################
###########################################################################
import contextlib
import enum
import functools
import logging
import os
import re
import time
from abc import abstractclassmethod
from collections import UserDict
from dataclasses import dataclass, field, fields, is_dataclass
from functools import cached_property
from operator import itemgetter
from typing import (Any, Callable, Generator, Hashable, Iterable, Iterator,
Mapping, NamedTuple, Optional, Pattern, Sequence, Tuple,
Type, TypeVar, Union)
import _collections_abc
import clingo
import clingo.ast
import psutil
from clingo.solving import SolveHandle
from tqdm import tqdm
## ASP Parser module logger
_ASP_logger: logging.Logger = logging.getLogger(__name__)
_ASP_logger.setLevel(logging.DEBUG)
class SubscriptableDataClass(_collections_abc.Sequence):
"Makes a dataclass subscriptable by allowing fields to be accessed by index."
def __init__(self) -> None:
super().__init__()
if not is_dataclass(self):
raise TypeError(f"Classes inheriting from {self.__class__} must be dataclasses.")
def __getitem__(self, index: Union[int, slice]) -> Union[Any, list[Any]]:
if isinstance(index, slice):
return [self[i] for i in range(*index.indices(len(self)))]
return getattr(self, fields(self)[index].name)
def __len__(self) -> int:
return len(fields(self))
#############################################################################################################################################
#############################################################################################################################################
######################### █████ ███ ██ ███████ ██ ██ ███████ ██████ ███████ ███████ ████████ ███████ #########################
######################### ██ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ #########################
######################### ███████ ██ ██ ██ ███████ ██ █ ██ █████ ██████ ███████ █████ ██ ███████ #########################
######################### ██ ██ ██ ██ ██ ██ ██ ███ ██ ██ ██ ██ ██ ██ ██ ██ #########################
######################### ██ ██ ██ ████ ███████ ███ ███ ███████ ██ ██ ███████ ███████ ██ ███████ #########################
#############################################################################################################################################
#############################################################################################################################################
## ASP symbol type
ASP_Symbol = Union[str, clingo.Symbol]
def to_clingo_form(symbol: ASP_Symbol) -> clingo.Symbol:
"""
Takes an ASP symbol given as a string or clingo Symbol, and retruns a clingo Symbol.
If a string is given as argument, it is converted to clingo form via the gringo term parser and returned
(gringo errors messages are printed to this solve signal's underlying logic program's logger as warnings).
Otherwise, if a clingo Symbol is given as argument, the argument itself is returned.
Parameters
----------
`symbol : {str | clingo.Symbol}` - An ASP symbol, given as a string or a pre-constructed clingo Symbol.
Returns
-------
`clingo.Symbol` - The argument converted to a clingo Symbol if it was a string, otherwise the argument itself.
Raises
------
`RuntimeError` - If the symbol is given as a string, and has invalid syntax according to gringo's term parser.
"""
if isinstance(symbol, str):
try:
return clingo.parse_term(symbol, logger=lambda code, message: _ASP_logger.warning(f"Clingo warning: {code} {message}"))
except RuntimeError as exception:
_ASP_logger.error(f"Error converting string {symbol} to a clingo symbol.", exc_info=True)
raise exception
elif isinstance(symbol, clingo.Symbol):
return symbol
else: raise ValueError(f"Symbol must be a string or clingo symbol. Got; {symbol} of type {type(symbol)}.")
class Atom(UserDict):
"""
A dictionary class used for representing ASP atoms extracted from ASP models by ASP_Parser.Model.query(...).
Atoms are plain dictionaries, except when converted to a string, they are formatted to represent clingo ASP symbols of the form
`name(arg_1, arg_i, ... arg_n)` where the name is the predicate name of this atom, and the args are defined by the values of the atom's dictionary.
The class requires one additional abstract class method `predicate_name(cls) -> str` to be overridden to define the predicate name of the atom.
Parameters with key 'NAME' and 'TRUTH' are ignored when inserting arguments upon converting an atom to a string.
The value of 'TRUTH' is used to determine the truth of the atom, if it is not present the atom is considered to be true.
If the class method `default_parameters(cls) -> Optional[tuple[str]]` is overridden by a sub-class and does not return None,
then the class type can be passed to ASP_Parser.Model.query(...) as argument for name `atom_name: {str | Atom}`.
Example Usage
-------------
A minimal example might include representing people from a database.
```
import ASP_Parser as ASP
class Person(ASP.Atom):
"Represents a 'person' by the name 'N' and age 'A'."
@classmethod
def default_params(cls) -> tuple[str]:
return ('N', 'A')
@classmethod
def predicate_name(cls) -> str:
return "person"
program = ASP.LogicProgram(\"""
current_date(1, 1, 2021).
person(N, A) :- declare_person(M, D).
\""")
answer: ASP.Answer = program.solve()
people: list[Person] = answer.fmodel.query(Person)
print(*people.items(), sep="\\n")
```
"""
def __str__(self) -> str:
return "{0}{1}({2})".format('' if str(self.get('TRUTH', 'true')).lower() == 'true' else '-',
self.predicate_name(),
', '.join(str(self[param]) for param in self if param not in ['NAME', 'TRUTH']))
def __repr__(self) -> str:
return "{}({})".format(self.__class__.__name__,
super().__repr__())
@property
def symbol(self) -> clingo.Symbol:
"The clingo symbol object form of this atom."
return to_clingo_form(str(self))
@property
def encode(self) -> str:
"An encoded string format of this atom that represents a fact statement."
return str(self) + '.'
@property
def _dict(self) -> dict[str, Any]:
"A raw dictionary copy of this atom."
return {key : value for key, value in self.items()}
@abstractclassmethod
def predicate_name(cls) -> str:
"""
Get the name of the predicate that encode literals of this type.
It is required to override this abstract class method to declare an atom class type.
Returns
-------
`str` - A string defining the predicate name.
"""
raise NotImplementedError
@classmethod
def default_params(cls) -> Optional[tuple[str]]:
"The default parameters of this atom."
return None
@classmethod
def default_cast(cls) -> Optional[dict[str, Callable[[clingo.Symbol], Any]]]:
"""
The default types to cast parameters of this atom to, given as a mapping between parameter names and callables
that take the respective argument for that parameter as its only argument and returns some casted version of it to any desired type.
"""
return None
@classmethod
def default_sort(cls) -> Optional[Union[str, tuple[str]]]:
"The default parameters of this atom to use for sorting, parameters that occur first are higher priority sort keys."
return None
def select(self, *parameters, ignore_missing: bool = False) -> dict[str, Any]:
"Select a sub-set of the parameters of this atom and return the parameter-argument mapping as a dictionary."
selection: dict[str, Any] = {}
for parameter in parameters:
if parameter in self:
selection[parameter] = self[parameter]
elif not ignore_missing:
raise ValueError(f"Paramter {parameter} is not in the atom {self}.")
return selection
@staticmethod
def nest_grouped_atoms(grouped_atoms: dict[tuple, list[Union["Atom", dict[str, Any]]]], as_standard_dict: bool = False) -> dict:
"""
Nest the keys of a sequence of grouped atoms extracted from a model such that the keys tuple is converted to a nested sequence of dictionaries each with singleton keys.
"""
nested_atoms: dict = {}
if grouped_atoms and not isinstance(next(iter(grouped_atoms.keys())), tuple):
raise ValueError("Only atoms grouped with tuple keys can be nested.")
if grouped_atoms and not isinstance(next(iter(grouped_atoms.values())), list):
raise ValueError("Only grouped lists of atoms can be nested.")
for group in grouped_atoms:
level = nested_atoms
for key in group[:-1]:
level = level.setdefault(key, {})
level[group[-1]] = [dict(atom) for atom in grouped_atoms[group]] if as_standard_dict else grouped_atoms[group]
return nested_atoms
@dataclass(frozen=True)
class Result:
"""
Encapsulates satisfiability results for logic program solve calls.
Fields
------
`satisfiable : bool` - A Boolean, True if at least one satisfiable model was found during solving, False otherwise.
`exhausted: bool` - A Boolean, True if the entire search space was exhausted during solving, False otherwise.
Properties
----------
`unsatisfiable : bool` - The negation of the `satisfiable` field (if the program was not satisfiable, it is unsatisfiable, unless search was cancelled).
`interrupted : bool` - The negation of the `exhausted` field (if the search space was not exhausted, search must have been interrupted).
"""
satisfiable: bool
exhausted: bool
def __str__(self) -> str:
return (f"{self.__class__.__name__} :: "
+ " : ".join(["SATISFIABLE" if self.satisfiable else "UNSATISFIABLE",
"SEARCH EXHAUSTED" if self.exhausted else "SEARCH INTERRUPTED"]))
@property
def unsatisfiable(self) -> bool:
return not self.satisfiable
@property
def interrupted(self) -> bool:
return not self.exhausted
@dataclass(frozen=True, order=True)
class Memory:
"""
Represents the memory used by a logic program whilst solving.
Elements
--------
`rss : float` - The Resident Set Size, the non-swapped physical memory a process has used.
`vms : float` - The Virtual Memory Size, the total amount of virtual memory used by the process.
"""
rss: float
vms: float
def __str__(self) -> str:
return f"(RSS = {self.rss:.6f}Mb, VMS = {self.vms:.6f}Mb)"
@dataclass(frozen=True)
class Statistics:
"""
Encapsulates timing statistics for individual logic program solve calls.
Fields
------
`grounding_time : float` - A float defining the 'wall clock' time spent in seconds
grounding the logic program, as reported by Python's highest resolution performance timer.
`solving_time : float` - A float defining the 'wall clock' time spent in seconds
solving the logic program, as reported by Python's highest resolution performance timer.
`total_time : float` - A float defining the total 'wall clock' time spent in seconds
from initiating and returning from the solve call to the logic program. This may be slightly
greater than the sum of the solving and ground time, as it accounts for all additional processing.
`memory : Memory` - A memory object representing the maximum amount of memory needed to solve the program.
`step_range : {range | None}` - The contiguous range of steps solved by the solving increment that this statistics object represents.
If this a cumulative statistics object, then the step range is the entire range over all increments.
If this is a base statistics object, then the step range is None.
`clingo_stats : {dict[str, Any]}` - A dictionary whose keys are strings and whose values are either
floats or nested dictionaries. The dictionary contains statistics returned by the internal Clingo solver.
It is populated only if the solver was called with option ASP_Parser.Options.statistics() or '--stats' enabled.
"""
grounding_time: float
solving_time: float
total_time: float = -1.0
memory: Memory = Memory(0.0, 0.0)
step_range: Optional[range] = None
clingo_stats: dict[str, Any] = field(default_factory=dict)
def __post_init__(self):
if self.total_time < 0.0:
object.__setattr__(self, "total_time", self.grounding_time + self.solving_time)
def __str__(self):
return (f"{self.__class__.__name__} :: "
+ ", ".join([f"Grounding = {self.grounding_time:.6f}s",
f"Solving = {self.solving_time:.6f}s",
f"Total = {self.total_time:.6f}s",
f"Memory = {self.memory!s}"]
+ ([f"Step range = [{min(self.step_range)}-{max(self.step_range)}]"]
if self.step_range is not None else [])))
@dataclass(frozen=True)
class IncrementalStatistics(Statistics):
"""
Encapsulates timing statistics for a series of incremental solve calls.
Fields
------
`cumulative : Statistics` - A statistics object containing cumulative timing statistics
summed over all incremental solve calls. The clingo stats are empty for this object.
`incremental : dict[int, Statistics]` - A dictionary whose keys are integers defining ordinal
incremental solve call numbers and whose values are statistics objects for the respective call.
Properties
----------
`calls : int` - The number of solver calls made to find a solution to the logic program.
This is simply 1 if a standard one-shot solve was made, the number of incremental solve calls made.
`incremental_stats_str : str` - A formatted multiple line string of the incremental statistics.
"""
cumulative: Statistics = Statistics(0.0, 0.0)
incremental: dict[int, Statistics] = field(default_factory=dict)
def __str__(self):
return (f"{self.__class__.__name__} :: "
+ ", ".join([f"Cumulative = ({self.cumulative!s})",
f"Calls = {self.calls}"]))
@property
def calls(self) -> int:
"The number of solver calls made to find a solution to the logic program."
return len(self.incremental)
@property
def grand_totals(self) -> Statistics:
"The grand total times and maximum memory usage, the sum of the base and all incremental times."
return Statistics(self.grounding_time + self.cumulative.grounding_time,
self.solving_time + self.cumulative.solving_time,
memory=Memory(max(self.memory.rss, self.cumulative.memory.rss),
max(self.memory.vms, self.cumulative.memory.vms)))
@property
def incremental_stats_str(self) -> str:
"Format the incremental statistics into a multiple line string."
return "\n".join([f"{step} : {stats}" for step, stats in self.incremental.items()])
def combine_with(self, other: "IncrementalStatistics", shift_increments: int = 0) -> "IncrementalStatistics":
"Combine this incremental statistics object with another. Incremental statistics are combined on a increment-wise basis."
## Form a merged sequence of incremental statistics
incremental: dict[int, Statistics] = self.incremental
for increment, current_stat in other.incremental.items():
_increment: int = increment + shift_increments
if (existing_stat := incremental.get(increment, None)) is not None:
incremental[_increment] = Statistics(existing_stat.grounding_time + current_stat.grounding_time,
existing_stat.solving_time + current_stat.solving_time,
memory=max(existing_stat.memory, current_stat.memory),
step_range=range(min(existing_stat.step_range.start, current_stat.step_range.start),
max(existing_stat.step_range.stop, current_stat.step_range.stop)))
else: incremental[_increment] = current_stat
## Calculate cumulative totals
cumulative_grounding: float = self.cumulative.grounding_time + other.cumulative.grounding_time
cumulative_solving: float = self.cumulative.solving_time + other.cumulative.solving_time
cumulative_memory = Memory(max(self.cumulative.memory.rss, other.cumulative.memory.rss),
max(self.cumulative.memory.vms, other.cumulative.memory.vms))
cumulative_step_range = range(min(self.cumulative.step_range.start, other.cumulative.step_range.start),
max(self.cumulative.step_range.stop, other.cumulative.step_range.stop))
cumulative = Statistics(cumulative_grounding, cumulative_solving,
memory=cumulative_memory, step_range=cumulative_step_range)
return IncrementalStatistics(self.grounding_time,
self.solving_time,
self.total_time,
self.memory,
self.step_range,
cumulative=cumulative,
incremental=incremental)
ParameterConstraint = Union[str, int, tuple[Pattern, "Model.ParseMode"], Callable[[clingo.Symbol], bool]]
@dataclass(frozen=True)
class Model(_collections_abc.Set):
"""
Encapsulates a model returned by logic program solve calls.
A model is an answer set, a finite set of atoms produced by a logic program.
Models have frozen set semantics; they are immutable, unordered and contain no duplicates.
Models support all the usual set operations, and also a variety of additional methods for querying the model for the existence and truth of atoms.
Unlike raw Clingo models, models of this type do not expire upon termination of the Clingo program that produced them, they are safe to store and use later.
Fields
------
`symbols : frozenset[clingo.Symbol]` - A frozen set of Clingo ASP symbols (atoms) encapsulated by this model.
The set is unordered and contains no duplicates.
`cost : tuple[int]` - A tuple of integers defining the optimisation cost of the model.
The tuple is ordered from the highest to the lowest priority of the optimisation statements in the ASP logic program that created this model.
`optimality_proven : bool` - A Boolean, True if the model is optimal respective of the logic program that generated it, False otherwise.
`number : int` - An ordinal natural number representing the order this model was computed model.
This is respective of its index in the sequence of all computed models from the solver call from which this model was generated.
`thread_id : int` - A natural number defining the numerical ID of the thread that found this model.
`model_type : {clingo.ModelType, None}` - Clingo model type for this model, None if the program was unsatisfiable.
"""
symbols: frozenset[clingo.Symbol]
cost: tuple[int] = field(default_factory=tuple)
optimality_proven: bool = False
number: int = -1
thread_id: int = -1
model_type: Optional[clingo.ModelType] = None
def __post_init__(self) -> None:
if not isinstance(self.symbols, frozenset):
object.__setattr__(self, "symbols", frozenset(self.symbols))
if not isinstance(self.cost, tuple):
object.__setattr__(self, "cost", tuple(self.cost))
def __str__(self) -> str:
return (f"{self.__class__.__name__} :: "
+ ", ".join([f"Total atoms = {len(self.symbols)}",
f"Cost = {self.cost}",
f"Optimality proven = {self.optimality_proven}",
f"Number = {self.number}",
f"Thread ID = {self.thread_id}",
f"Model type = {self.model_type}"]))
def __len__(self) -> int:
return len(self.symbols)
def __iter__(self) -> Generator[str, None, None]:
for symbol in self.symbols:
yield str(symbol)
def __bool__(self) -> bool:
return len(self.symbols) != 0
def __contains__(self, atom: Union[str, clingo.Symbol]) -> bool:
if isinstance(atom, str):
return clingo.parse_term(atom) in self.symbols
elif isinstance(atom, clingo.Symbol):
return atom in self.symbols
return False
def __and__(self, other: "Model") -> "Model":
return Model(self.symbols & other.symbols)
def __or__(self, other: "Model") -> "Model":
return Model(self.symbols | other.symbols)
def __xor__(self, other: "Model") -> "Model":
return Model(self.symbols ^ other.symbols)
def union(self, other: "Model") -> "Model":
"""
Find the union of this and another model, returning a new model.
Where the union of two sets is a set containing the elements that occur in either of the originals.
Parameters
----------
`other : Model` - The other model to unite with this model.
Returns
-------
`Model` - A new model representing the union of this and the other model.
"""
return Model(self.symbols.union(other.symbols))
def intersection(self, other: "Model") -> "Model":
"""
Find the intersection of this and another model, returning a new model.
Where the intersection of two sets is a set containing only the elements that occur in both of the originals.
Parameters
----------
`other : Model` - The other model to intersect with this model.
Returns
-------
`Model` - A new model representing the intersection of this and the other model.
"""
return Model(self.symbols.intersection(other.symbols))
def difference(self, other: "Model") -> "Model":
"""
Find the difference between this and another model, returning a new model.
Where the difference between two sets is a set containing only the elements
that occur in the first set (this model) and not in the second (other model).
Parameters
----------
`other : Model` - The other model to find the difference between this model.
Returns
-------
`Model` - A new model representing the difference between this and the other model.
"""
return Model(self.symbols.difference(other.symbols))
def symmetric_difference(self, other: "Model") -> "Model":
"""
Find the symmetric difference between this and another model, returning a new model.
Where the symmetric difference between two sets is a set containing only the elements that occur in either of the originals but not both.
Parameters
----------
`other : Model` - The other model to find the symmetric difference between this model.
Returns
-------
`Model` - A new model representing the symmetric difference between this and the other model.
"""
return Model(self.symbols.symmetric_difference(other.symbols))
def is_true(self, atom: str) -> bool:
"""
Determine whether a given atom is in the model and has a positive truth value.
Parameters
----------
`atom : str` - An alphanumeric string which may contain underscores whose leadering character is a lowercase letter representing an ASP atom.
Usually a function symbol of the form 'name(arg_1, arg_2, ... arg_n)'.
If the string is incorrectly formatted, or has invalid syntax according to Gringo's term parser, this function will return False.
Returns
-------
`bool` - A Boolean, True if the given atom is in the model and has a positive truth value, False otherwise.
"""
return any((str(symbol).lstrip("-") == atom and symbol.positive) for symbol in self.symbols)
def is_false(self, atom: str) -> bool:
"""
Determine whether a given atom is in the model and has a negative truth value.
Parameters
----------
`atom : str` - An alphanumeric string which may contain underscores whose leadering character is a lowercase letter representing an ASP atom.
Usually a function symbol of the form 'name(arg_1, arg_2, ... arg_n)'.
If the string is incorrectly formatted, or has invalid syntax according to Gringo's term parser, this function will return False.
Returns
-------
`bool` - A Boolean, True if the given atom is in the model and has a negative truth value, False otherwise.
"""
return any((str(symbol).lstrip("-") == atom and symbol.negative) for symbol in self.symbols)
def is_in(self, atom: Union[str, clingo.Symbol]) -> bool:
"""
Determine whether a given atom is in the model and has any truth value.
Parameters
----------
`atom : str` - An alphanumeric string which may contain underscores whose leadering character is a lowercase letter representing an ASP atom.
Usually a function symbol of the form 'name(arg_1, arg_2, ... arg_n)'.
If the string is incorrectly formatted, or has invalid syntax according to Gringo's term parser, this function will return False.
Returns
-------
`bool` - A Boolean, True if the given atom is in the model and has either a negative or positive truth value, False otherwise.
"""
return any((str(symbol).lstrip("-") == atom) for symbol in self.symbols)
@enum.unique
class ParseMode(enum.Enum):
"""
An enumeration defining the three possible regular expression matching modes.
These are used when parsing a model with:
- `Model.get_atoms(...)`,
- `Model.query(...)`,
- `Model.regex_parse(...)`.
The enumerated values are functions, stored in singleton tuples to conform with python naming conventions.
Items
-----
`Match = (lambda regex, value: regex.match(value),)` - Match the regular expression from the start of the string.
Functionality is defined by re.match(patten: re.Pattern, string: AnyStr).
`FullMatch = (lambda regex, value: regex.fullmatch(value),)` - Match the regular expression to the entire string.
Functionality is defined by re.fullmatch(patten: re.Pattern, string: AnyStr).
`Search = (lambda regex, value: regex.search(value),)` - Match the regular expression anywhere in the string.
Functionality is defined by re.search(patten: re.Pattern, string: AnyStr).
"""
Match = (lambda regex, value: regex.match(value),)
FullMatch = (lambda regex, value: regex.fullmatch(value),)
Search = (lambda regex, value: regex.search(value),)
@staticmethod
def __satisfies_constraint(value: clingo.Symbol, constr: ParameterConstraint) -> bool:
"Check whether a symbol's argument satisfies a given constraint."
return ((isinstance(constr, tuple)
and constr[1].value[0](constr[0], str(value)) is not None)
or (isinstance(constr, Callable)
and constr(value))
or str(value) == str(constr))
@staticmethod
def __group_atoms(sequence: Sequence[clingo.Symbol], key: Callable[[clingo.Symbol], Union[clingo.Symbol, tuple[clingo.Symbol]]]) -> tuple[clingo.Symbol, list[clingo.Symbol]]:
"Group a sequence of symbols using a given grouping key function."
groups: dict[Union[clingo.Symbol, tuple[clingo.Symbol]], list[clingo.Symbol]] = {}
for item in sequence:
groups.setdefault(key(item), []).append(item)
return tuple(groups.items())
def get_atoms(
self: "Model",
atom_name: Union[str, Tuple[re.Pattern, "Model.ParseMode"]],
arity: int,
/,
truth: Optional[bool] = None,
param_constrs: Mapping[int, Union[str, int, Tuple[re.Pattern, "Model.ParseMode"], Sequence[Union[str, int, Tuple[re.Pattern, "Model.ParseMode"]]]]] = {},
*,
sort_by: Optional[Union[int, Sequence[int]]] = None,
group_by: Optional[Union[int, Sequence[int]]] = None,
convert_keys: Optional[Union[Callable[[clingo.Symbol], Hashable], Mapping[int, Callable[[clingo.Symbol], Hashable]]]] = None,
as_strings: bool = False
) -> Union[list[ASP_Symbol], dict[Union[Hashable, tuple[Hashable]], list[ASP_Symbol]]]:
"""
Extract atoms from the model of a given; name, arity, and classical truth value.
The extracted atoms are returned as a list of either Clingo symbols or strings, optionally sorted according to their arguments.
Paramaters can optionally be constrained such that the returned atoms' arguments must match the constraint for the given parameter.
Parameters
----------
`atom_name : {str | (re.Pattern, ParseMode)}` - The name constraint of the atoms to extract.
If given as a string, the extracted atoms' names must match exactly.
If given as a two-tuple, the first item must be a compiled regular expression and second item an entry from the Model.ParseMode enum specifying how to match the regular expression, only atoms whose name's match will be returned.
`arity : int` - The arity of the atoms to extract.
Only atoms whose number of arguments equals this value will be returned.
`truth : {bool | None}` - The classical truth of the atoms to extract.
True to extract only positive atoms, False to extract only negative atoms, or None to extract all atoms regardless of their truth.
`param_constrs : Mapping[int, {str | int | (re.Pattern, ParseMode)}] = {}` - A mapping whose keys are integers defining parameter indices in the range [0-arity] and whose values are either strings, integers, or two-tuples.
If a two-tuple, its first item is a regular expression and its second item is an entry from the `ParseMode` enum defining how to match the regular expression.
The values define constraints for the arguments of the parameter of that key, only atoms whose arguments match all parameter constraints will be returned.
Keyword Parameters
------------------
`sort_by : Sequence[int] = []` - The sorting priority of arguments for the parameters of the list of returned atoms.
A sequence of integers defining parameter indices in the range [0-arity] specifying.
`group_by : Sequence[int] = []` - Group the returned atoms according to those which have the same arguments for the given parameters.
If given and not None, then the atoms will be returned as a parameter index to atom list mapping, where all atoms in a list have the same argument for the given parameter index.
`convert_keys : Mapping[int, Any] = []` - Convert the keys of a grouped mapping of atoms to the given types.
`as_strings : bool = False` - A Boolean, True to return the extracted atoms as strings, otherwise False (the default) to return them as raw clingo symbols.
Returns
-------
`{list[str] | list[clingo.Symbol]}` - A list of either strings or Clingo symbols containing unique atoms from this model.
Example Usage
-------------
>>> import ASP_Parser as ASP
>>> import clingo
>>> import re
>>> answer: ASP.Answer = ASP.LogicProgram(\"""
occurs(move(robot, library), 0).
occurs(grasp(robot, book), 1).
-occurs(grasp(robot, book), 0).
-occurs(move(robot, library), 1).
holds(in(robot, office), 0).
holds(grasping(robot, book), 2).
holds(in(robot, library), 1).
\""").solve()
Extract positive atoms with name 'occurs' and arity 2. Note that the output's order is arbitrary and not necessarily the same order the atoms occur in the program.
>>> answer.model.get_atoms("occurs", 2, True)
[occurs(grasp(robot,book),1), occurs(move(robot,library),0)]
Extract positive atoms with name 'holds' and arity 2, sort by the second argument.
>>> answer.model.get_atoms("holds", 2, True, sort_by=[1])
[holds(in(robot,office),0), holds(in(robot,library),1), holds(grasping(robot,book),2)]
Extract negative atoms with name 'occurs', arity 2 and whose second argument is 1.
>>> answer.model.get_atoms("occurs", 2, False, param_constrs={1 : 1})
[-occurs(move(robot,library),1)]
Extract atoms regards of truth value with name 'occurs', arity 2 and whose first argument starts with the string 'move'.
>>> answer.model.get_atoms("occurs", 2, None, param_constrs={0 : (re.compile(r"move"), ASP.Model.ParseMode.Match)})
[-occurs(move(robot,library),1), occurs(move(robot,library),0)]
Extract positive atoms whose name contains the letter 's' and which have arity 2, sort first by the first argument and then by the second, return the atoms as strings.
>>> answer.model.get_atoms((re.compile(r"s"), ASP.Model.ParseMode.Search), 2, True, as_strings=True, sort_by=[1, 0])
['holds(in(robot,office),0)', 'occurs(move(robot,library),0)', 'occurs(grasp(robot,book),1)', 'holds(in(robot,library),1)', 'holds(grasping(robot,book),2)']
"""
## Determine which atoms fit the constraints provided
atoms: Union[list[clingo.Symbol], list[str]] = []
for symbol in self.symbols:
if ((truth is None
or truth == symbol.positive)
and len(symbol.arguments) == arity
and ((isinstance(atom_name, tuple)
and atom_name[1].value[0](atom_name[0], symbol.name) is not None)
or symbol.name == atom_name)
and (all((isinstance(param_constrs[index], Iterable) and not isinstance(param_constrs[index], (str, tuple))
and any(self.__satisfies_constraint(symbol.arguments[index], constr) for constr in param_constrs[index]))
or self.__satisfies_constraint(symbol.arguments[index], param_constrs[index])
for index in param_constrs))):
atoms.append(symbol)
def keys_for(list_):
"""Creates functions that extracts atom arguments for sorting and grouping."""
return lambda item: (tuple(item.arguments[index] for index in list_ if index in range(0, arity)) if isinstance(list_, Iterable) else item.arguments[list_])
def convert(index, key):
"""Converts individual keys to the desired type."""
if isinstance(convert_keys, Mapping):
return key if index not in convert_keys else convert_keys[index](key)
else: return convert_keys(key)
## Sort the atoms as requested
if sort_by is not None:
atoms = sorted(atoms, key=keys_for(sort_by))
## Find the valid grouping indices
_group_by: Optional[Union[int, Sequence[int]]] = None
if isinstance(group_by, Iterable):
_group_by = (index for index in group_by if index in range(0, arity))
elif group_by in range(0, arity):
_group_by = group_by
## Group the atoms accordingly
if _group_by is not None:
if convert_keys is not None:
atoms = {tuple(convert(index, key) for index, key in zip(_group_by, keys)) if isinstance(_group_by, list) else convert(_group_by, keys)
: list(group) for keys, group in self.__group_atoms(atoms, key=keys_for(_group_by))}
else: atoms = {keys : list(group) for keys, group in self.__group_atoms(atoms, key=keys_for(_group_by))}
## Convert to strings as requested
return atoms if not as_strings else ([str(atom) for atom in atoms] if _group_by is None else {key : [str(atom) for atom in atoms[key]] for key in atoms})
def query(
self: "Model",
atom_name: Union[str, tuple[re.Pattern, "Model.ParseMode"], Type[Atom]],
atom_params: Optional[Sequence[str]] = None,
/,
truth: bool = True,
param_constrs: Mapping[str, Union[ParameterConstraint, Iterable[ParameterConstraint]]] = {},
*,
sort_by: Optional[Union[str, Sequence[str]]] = None,
group_by: Optional[Union[str, Sequence[str]]] = None,
cast_to: Optional[Union[Callable[[clingo.Symbol], Any], Sequence[Callable[[clingo.Symbol], Any]], Mapping[str, Union[Callable[[clingo.Symbol], Any], Sequence[Callable[[clingo.Symbol], Any]]]]]] = None,
add_truth: Union[bool, Type[str], Type[bool]] = False,
add_name: Union[bool, Type[str]] = False
) -> Union[list[dict[str, ASP_Symbol]], dict[Union[Any, tuple[Any]], list[dict[str, ASP_Symbol]]]]:
"""
Extract atoms from the model of a given; name, arity, and classical truth value, and return their parameter-argument mappings.
Arbitrary names for the parameters of the extracted atoms must be given as a sequence of strings.
The extracted atoms are returned as a list, optionally sorted according to their arguments, of dictionaries.
The dictionarys' keys are the given parameter names and their values are the atoms' arguments for those parameters.
Paramaters can optionally be constrained, such that the returned atoms' arguments must match the constraint for the given parameter.
The constraint can be given either as a string or a regular expression.
Complex queries can choose to:
- sort the atoms in ascending order according to a sub-sequence of their arguments,
- group the return list into a dictionary or lists containing only atoms with the same argument for a given sub-set of their parameters,
- cast the arguments to any desired type.
The returned dictionary can optionally include the name of the atom under key "NAME" and the classical truth of the atom under key "TRUTH".
Parameters
----------
`atom_name : {str | tuple[re.Pattern, ParseMode]}` - The name of the atoms to extract, only atoms whose name's match will be returned.
Given as either a string or a two-tuple whose first element is a compiled regular expression and second is a parsing mode specifying how to match the expression.
`atom_params : Sequence[str]` - An ordered sequence arbitrary names for the parameters of the extracted atoms given as strings.
The arity of the extracted atoms will be equal to the length of this sequence.
`truth : {bool | None}` - The classical truth value of the atoms to extract.
Given as either a Boolean or None, True extracts only positive atoms, False extracts only negative, and None extracts all atoms regardless of truth value.
`param_constrs : Mapping[str, {str, int, Tuple[Pattern, ParseMode], Iterable[{str, int, Tuple[Pattern, ParseMode]}]}] = {}`
- A mapping whose keys are strings defining parameter names from `atom_params` and whose values are constraints for those parameters.
The parameters constraints are applied at atoms such that; the atoms' arguments for the parameters given as the mapping keys must satisfy the respective constraint given as the mapping value.
Constraints must be given as either; strings, integers, two-tuples, or an iterable (which cannot also be a tuple) of any of the latter.
If a two-tuple, its first item is a regular expression and its second item is an entry from the `Model.ParseMode` enum defining how to match the regular expression.
If an iterable, the constraints contained are applied disjunctively such that, the argument for the given parameter must satisfy at least one of the constraints.
Keyword Parameters
------------------
`sort_by : Sequence[str] = []` - A sequence of strings defining parameter names from `atom_params` specifying the sorting priority of arguments of those parameters of the list of returned atoms.
`group_by : Sequence[str] = []` - Group the returned atoms according to those which have the same arguments for the given parameters.
If given and not None, then the atoms will be returned as a parameter name to atom list mapping, where all atoms in a list have the same argument for the given parameter name.
`convert_keys : Mapping[int, Any] = []` - Convert the keys of a grouped mapping of atoms to the given types.
`add_truth : bool = False` - A Boolean, True to include the classical truth of returned atoms under key "TRUTH", otherwise False (the default).
`add_name : bool = False` - A Boolean, True to include the name of returned atoms under key "NAME", otherwise False (the default).
Returns
-------
`list[dict[str, {str, clingo.Symbol}]]` - A list of dictionaries containing the parameter-argument mappings of unique atoms from this model.
The dictionary keys are strings from `atom_params` (insertion order is preserved) and their values are the arguments for those parameters as either strings or Clingo symbols.
Example Usage
-------------
>>> import ASP_Parser as ASP
>>> import clingo
>>> import re
>>> answer: ASP.Answer = ASP.LogicProgram(\"""
occurs(move(robot, library), 0).
occurs(grasp(robot, book), 1).
-occurs(grasp(robot, book), 0).
-occurs(move(robot, library), 1).
holds(in(robot, office), 0).
holds(grasping(robot, book), 2).
holds(in(robot, library), 1).
\""").solve()
Extract positive atoms with name 'occurs' and arity 2. Note that the output's order is arbitrary and not necessarily the same order the atoms occur in the program.
>>> answer.model.query("occurs", ["A", "I"], True)
[{'A': grasp(robot,book), 'I': 1}, {'A': move(robot,library), 'I': 0}]
Extract positive atoms with name 'holds' and arity 2, sort by the second argument.
>>> answer.model.query("holds", ["A", "I"], True, sort_by=["I"])
[{'A': in(robot,office), 'I': 0}, {'A': in(robot,library), 'I': 1}, {'A': grasping(robot,book), 'I': 2}]
Extract negative atoms with name 'occurs', arity 2 and whose second argument is 1.
>>> answer.model.query("occurs", ["A", "I"], False, param_constrs={"I" : 1})
[{'A': move(robot,library), 'I': 1}]
Extract atoms regards of truth value with name 'occurs', arity 2 and whose first argument starts with the string 'move'.
>>> answer.model.query("occurs", ["A", "I"], None, param_constrs={"A" : (re.compile(r"move"), ASP.Model.ParseMode.Match)}, add_truth=True)
[{'TRUTH': false, 'A': move(robot,library), 'I': 1}, {'TRUTH': true, 'A': move(robot,library), 'I': 0}]
Extract positive atoms whose name contains the letter 's' and which have arity 2, sort first by the first argument and then by the second, return the atoms as strings.
>>> answer.model.query((re.compile(r"s"), ASP.Model.ParseMode.Search), ["X", "Y"], True, sort_by=["X", "Y"], add_name=True, as_strings=True)
[{'NAME': 'occurs', 'X': 'grasp(robot,book)', 'Y': '1'}, {'NAME': 'holds', 'X': 'grasping(robot,book)', 'Y': '2'}, {'NAME': 'holds', 'X': 'in(robot,library)', 'Y': '1'}, {'NAME': 'holds', 'X': 'in(robot,office)', 'Y': '0'}, {'NAME': 'occurs', 'X': 'move(robot,library)', 'Y': '0'}]
"""
_atom_name: Union[str, tuple[re.Pattern, "Model.ParseMode"]]
_atom_type: Type[dict]
_atom_params: tuple[str]
if isinstance(atom_name, type) and issubclass(atom_name, Atom):
_atom_name = atom_name.predicate_name()
_atom_type = atom_name
if (atom_params is None
and (_atom_params := atom_name.default_params()) is None):
raise ValueError(f"Atom type {atom_name.__class__} given without explicit or default parameters.")
else:
_atom_name = atom_name
_atom_type = dict
if (_atom_params := atom_params) is None:
raise ValueError(f"Atom parameters must be given explicitly unless an Atom type with default parameters defined is given.")
arity: int = len(_atom_params)
def get_name_checker(name_type: type) -> Callable[[clingo.Symbol], bool]:
"Creates a lambda function for checking an atom's name agaist the constraint given."
if name_type == str:
return lambda symbol: symbol.name == _atom_name
return lambda symbol: _atom_name[1].value[0](_atom_name[0], symbol.name) is not None
name_checker: Callable[[clingo.Symbol], bool] = get_name_checker(type(_atom_name))
constr_params: list[Tuple[str, int]] = []
for param in param_constrs:
if param in _atom_params:
constr_params.append((param, _atom_params.index(param)))
_cast_to = cast_to
_sort_by = sort_by
if issubclass(_atom_type, Atom):
if _cast_to is None:
_cast_to = atom_name.default_cast()
if _sort_by is None:
_sort_by = atom_name.default_sort()
atoms: list[dict[str, Any]] = []
atom: dict[str, clingo.Symbol] = _atom_type()
for symbol in self.symbols:
if ((truth is None or truth == symbol.positive)
and len(symbol.arguments) == arity
and name_checker(symbol)
and (all((isinstance(param_constrs[param], Iterable) and not isinstance(param_constrs[param], (str, tuple))
and any(self.__satisfies_constraint(symbol.arguments[index], constr) for constr in param_constrs[param]))
or self.__satisfies_constraint(symbol.arguments[index], param_constrs[param])
for param, index in constr_params))):
atom = _atom_type()
if add_truth:
if isinstance(add_truth, type) and issubclass(add_truth, (bool, str)):
atom["TRUTH"] = add_truth(symbol.positive)
else: atom["TRUTH"] = clingo.Function(str(symbol.positive).lower())
if add_name:
if isinstance(add_name, type) and issubclass(add_name, str):
atom["NAME"] = add_name(symbol.name)
else: atom["NAME"] = symbol.name
if _cast_to is not None:
for index, param in enumerate(_atom_params):
if isinstance(_cast_to, Mapping):
if param in _cast_to:
if isinstance(_cast_to[param], Sequence):
arg: Any = symbol.arguments[index]
for cast in _cast_to[param]:
arg = cast(arg)
atom[param] = arg
else: atom[param] = _cast_to[param](symbol.arguments[index])
else: atom[param] = symbol.arguments[index]
elif isinstance(_cast_to, Sequence):
arg: Any = symbol.arguments[index]
for cast in _cast_to:
arg = cast(arg)
atom[param] = arg
else: atom[param] = _cast_to(symbol.arguments[index])
else:
for index, param in enumerate(_atom_params):
atom[param] = symbol.arguments[index]
atoms.append(atom)
def validate_params(params: Optional[Union[str, Sequence[str]]]) -> Optional[tuple[str]]:
"Validates sorting and grouping parameters, discarding any that are not in the atom parameter list."
if isinstance(params, str) and params in _atom_params:
return (params,)
elif (isinstance(params, Sequence) and params
and (valid_params := tuple(param for param in params if param in _atom_params))):
return valid_params
else: return None
_sort_by: Optional[tuple[str]] = validate_params(_sort_by)
_group_by: Optional[tuple[str]] = validate_params(group_by)
def keys_for(params: tuple[str]) -> itemgetter:
"Creates an item getter for getting keys for sorting and grouping atoms."
return itemgetter(*[param for param in params])
if _sort_by is not None:
atoms = sorted(atoms, key=keys_for(_sort_by))
if _group_by is not None:
grouped_atoms: dict[Any, list[dict[str, Any]]] = {}
for key, group in self.__group_atoms(atoms, key=keys_for(_group_by)):
grouped_atoms[key] = group
return grouped_atoms
return atoms
def regex_parse(self,
regex: Union[re.Pattern, str],
parse_mode: Optional[ParseMode] = None,
return_as_strings: bool = True
) -> set[ASP_Symbol]:
"""
Parse over each atom in the model using a regular expression.
Those atoms who match the expression according to the given parsing mode are returned.
Parameters
----------
`regex: re.Pattern | str` -
`parse_mode: ParseMode | None = None` -
`return_as_strings: bool = True` -
Returns
-------
`set[str | clingo.Symbol]` -