forked from srlearn/srlearn
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.py
More file actions
292 lines (256 loc) · 10.6 KB
/
background.py
File metadata and controls
292 lines (256 loc) · 10.6 KB
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
# Copyright © 2017, 2018, 2019 Alexander L. Hayes
"""
background.py
"""
import pathlib
class Background:
"""Background Knowledge for a database.
Background knowledge expressed in the form of modes.
"""
# pylint: disable=too-many-instance-attributes,too-many-arguments
def __init__(
self,
modes=None,
node_size=2,
number_of_clauses=100,
number_of_cycles=100,
max_tree_depth=3,
recursion=False,
line_search=False,
use_std_logic_variables=False,
use_prolog_variables=False,
load_all_libraries=False,
load_all_basic_modes=False,
):
"""Initialize a set of background knowledge
Parameters
----------
modes : list of str (default: None)
Modes constrain the search space for hypotheses. If None, this will
attempt to set the modes automatically at learning time.
node_size : int, optional (default: 2)
Maximum number of literals in each node.
max_tree_depth : int, optional (default: 3)
Maximum number of nodes from root to leaf (height) in the tree.
number_of_clauses : int, optional (default: 100)
Maximum number of clauses in the tree (i.e. maximum number of leaves)
number_of_cycles : int, optional (default: 100)
Maximum number of times the code will loop to learn clauses,
increments even if no new clauses are learned.
line_search : bool, optional (default: False)
Use lineSearch
recursion : bool, optional (default: False)
Use recursion
use_std_logic_variables : bool, optional (default: False)
Set the stdLogicVariables parameter to True
use_prolog_variables : bool, optional (default: False)
Set the usePrologVariables parameter to True
load_all_libraries : bool, optional (default: False)
Load libraries: ``arithmeticInLogic``, ``comparisonInLogic``,
``differentInLogic``, ``listsInLogic``
load_all_basic_modes : bool, optional (default: False)
Load ``modes_arithmeticInLogic``, ``modes_comparisonInLogic``,
``modes_differentInLogic``, ``modes_listsInLogic``
These may require many cycles while proving.
Examples
--------
This demonstrates how to add parameters to the Background object.
The main thing to take note of is the ``modes`` parameter, where
background knowledge of the Toy-Cancer domain is specified.
>>> from srlearn import Background
>>> bk = Background(
... modes=[
... "cancer(+Person).",
... "smokes(+Person).",
... "friends(+Person,-Person).",
... "friends(-Person,+Person).",
... ],
... max_tree_depth=2,
... use_std_logic_variables=True,
... )
>>> print(bk)
setParam: nodeSize=2.
setParam: maxTreeDepth=2.
setParam: numberOfClauses=100.
setParam: numberOfCycles=100.
useStdLogicVariables: true.
mode: cancer(+Person).
mode: smokes(+Person).
mode: friends(+Person,-Person).
mode: friends(-Person,+Person).
<BLANKLINE>
This Background object is used by the :class:`srlearn.rdn.BoostedRDN` class to
write the parameters to a ``background.txt`` file before running BoostSRL.
.. code-block:: python
>>> from srlearn import Background
>>> from srlearn import example_data
>>> bk = Background(
... modes=example_data.train.modes,
... max_tree_depth=2,
... node_size=1,
... )
>>> bk.write("training/")
Notes
-----
Descriptions of these parameters are lifted almost word-for-word from the
BoostSRL-Wiki "Advanced Parameters" page [1]_.
Some of these parameters are defined in multiple places. This is mostly
to follow the sklearn-style requirement for all tune-able parameters to
be part of the object while still being relatively similar to the
style where BoostSRL has parameters defined in a modes file.
.. [1] https://starling.utdallas.edu/software/boostsrl/wiki/advanced-parameters/
"""
self.modes = modes
self.node_size = node_size
self.max_tree_depth = max_tree_depth
self.number_of_clauses = number_of_clauses
self.number_of_cycles = number_of_cycles
self.line_search = line_search
self.recursion = recursion
self.use_std_logic_variables = use_std_logic_variables
self.use_prolog_variables = use_prolog_variables
self.load_all_libraries = load_all_libraries
self.load_all_basic_modes = load_all_basic_modes
# Check params are correct at the tail of initialization.
self._check_params()
def _check_params(self) -> None:
"""Check validity of background knowledge, raise ValueError if invalid."""
if not (isinstance(self.modes, list) or self.modes is None):
raise ValueError(
"modes parameter should be None or a list, found {0}".format(self.modes)
)
if not isinstance(self.line_search, bool):
raise ValueError(
"line_search parameter should be bool, found {0}".format(
self.line_search
)
)
if not isinstance(self.recursion, bool):
raise ValueError(
"recursion parameter should be a bool, found {0}".format(self.recursion)
)
if not isinstance(self.max_tree_depth, int) or isinstance(
self.max_tree_depth, bool
):
raise ValueError(
"max_tree_depth should be an int, found {0}".format(self.max_tree_depth)
)
if self.max_tree_depth <= 0:
raise ValueError(
"max_tree_depth must be greater than 0, found {0}".format(
self.max_tree_depth
)
)
if not isinstance(self.number_of_clauses, int) or isinstance(
self.number_of_clauses, bool
):
raise ValueError(
"number_of_clauses must be an int, found {0}".format(
self.number_of_clauses
)
)
if self.number_of_clauses <= 0:
raise ValueError(
"number_of_clauses must be greater than 0, found {0}".format(
self.number_of_clauses
)
)
if not isinstance(self.number_of_cycles, int) or isinstance(
self.number_of_cycles, bool
):
raise ValueError(
"number_of_cycles must be an int, found {0}".format(
self.number_of_cycles
)
)
if self.number_of_cycles <= 0:
raise ValueError(
"number_of_cycles must be greater than 0, found {0}".format(
self.number_of_cycles
)
)
if not isinstance(self.load_all_libraries, bool):
raise ValueError(
"load_all_libraries should be a bool, found {0}".format(
self.load_all_libraries
)
)
if not isinstance(self.load_all_basic_modes, bool):
raise ValueError(
"load_all_basic_modes should be a bool, found {0}".format(
self.load_all_basic_modes
)
)
if not isinstance(self.use_std_logic_variables, bool):
raise ValueError(
"use_std_logic_variables should be a bool, found {0}".format(
self.use_std_logic_variables
)
)
if not isinstance(self.use_prolog_variables, bool):
raise ValueError(
"use_prolog_variables should be a bool, found {0}".format(
self.use_prolog_variables
)
)
def write(self, filename="train", location=pathlib.Path("train")) -> None:
"""Write the background to disk for learning.
Parameters
----------
filename : str
Name of the file to write to: 'train_bk.txt' or 'test_bk.txt'
location : :class:`pathlib.Path`
This should be handled by a manager to ensure locations do not overlap.
"""
with open(location.joinpath("{0}_bk.txt".format(filename)), "w") as _fh:
_fh.write(str(self))
def _to_background_string(self) -> str:
"""Convert self to a string.
This converts the Background object to use the background/mode syntax used
by BoostSRL. Normally this will be accessed via the public __str__ method
or __repr__ method.
Parameters
----------
self : object
Instance of a Background object.
Returns
-------
self : str
A string representation of the Background object.
Notes
-----
This method is based on the description and examples from the
BoostSRL-Wiki "Basic Modes Guide" [1]_.
.. [1] https://starling.utdallas.edu/software/boostsrl/wiki/basic-modes/
"""
_relevant = [
[_attr, _val]
for _attr, _val in self.__dict__.items()
if (_val is not False) and (_val is not None)
]
_background_syntax = {
"line_search": "setParam: lineSearch={0}.\n",
"recursion": "setParam: recursion={0}.\n",
"node_size": "setParam: nodeSize={0}.\n",
"max_tree_depth": "setParam: maxTreeDepth={0}.\n",
"number_of_clauses": "setParam: numberOfClauses={0}.\n",
"number_of_cycles": "setParam: numberOfCycles={0}.\n",
"load_all_libraries": "setParam: loadAllLibraries = {0}.\n",
"load_all_basic_modes": "setParam: loadAllBasicModes = {0}.\n",
"use_std_logic_variables": "useStdLogicVariables: {0}.\n",
"use_prolog_variables": "usePrologVariables: {0}.\n",
}
_background = ""
for _attr, _val in _relevant:
if _attr in ["modes"]:
pass
else:
_background += _background_syntax[_attr].format(str(_val).lower())
if self.modes:
for _mode in self.modes:
_background += "mode: " + _mode + "\n"
return _background
def __str__(self) -> str:
return self._to_background_string()
def __repr__(self) -> str:
return self._to_background_string()