Skip to content

Commit 52b09ef

Browse files
committed
Linter tweaks.
Code formatting issues from the linter. Pruned imports per linter Provide more information in error-handler. Replace error print statements with logging messages at error level. Tweak error handling.
1 parent 8b1d614 commit 52b09ef

File tree

7 files changed

+357
-278
lines changed

7 files changed

+357
-278
lines changed

popper.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
if __name__ == '__main__':
77
settings = Settings(cmd_line=True)
88
prog, score, stats = learn_solution(settings)
9-
if prog != None:
9+
if prog is not None:
1010
settings.print_prog_score(prog, score)
1111
else:
1212
print('NO SOLUTION')

popper/bkcons.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
1+
import numbers
2+
import sys
3+
import traceback
4+
from collections import defaultdict
5+
from itertools import product
6+
from traceback import format_tb
7+
18
import clingo
29
import clingo.script
3-
import numbers
4-
import operator
5-
import pkg_resources
6-
import time
7-
from . util import rule_is_recursive, format_rule, Constraint, order_prog, Literal, suppress_stdout_stderr
810
from clingo import Function, Number, Tuple_
9-
from collections import defaultdict
10-
from itertools import permutations, product
11-
from pysat.card import *
12-
from pysat.formula import CNF
13-
from pysat.solvers import Solver
11+
12+
from .util import suppress_stdout_stderr
13+
1414
clingo.script.enable_python()
1515

1616
tmp_map = {}
@@ -52,7 +52,8 @@
5252
# return (head_pred, arity), body_preds
5353

5454

55-
from itertools import permutations, combinations
55+
from itertools import permutations
56+
5657
all_myvars = ['A','B','C','D','E','F','G','H']
5758

5859
def connected(xs, ys):
@@ -628,7 +629,6 @@ def atom_to_symbol(pred, args):
628629
return Function(name = pred, arguments = xs)
629630

630631
def deduce_bk_cons(settings, tester):
631-
import re
632632
prog = []
633633
lookup2 = {k: f'({v})' for k,v in tmp_map.items()}
634634
lookup1 = {k:v for k,v in lookup2.items()}
@@ -755,7 +755,8 @@ def deduce_recalls(settings):
755755
solver.add('base', [], bk)
756756
solver.ground([('base', [])])
757757
except Exception as Err:
758-
print('ERROR deducing recalls', Err)
758+
settings.logger.error(f'ERROR deducing recalls: {Err}')
759+
traceback.print_exc(None, file=sys.stderr)
759760
return None
760761

761762
for pred, arity in settings.body_preds:

popper/combine.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ def find_combination(self, timeout):
258258

259259
else:
260260
if not self.settings.lex:
261-
print("ERROR: Combining rec or pi programs not supported with MDL objective. Exiting.")
261+
self.settings.logger.error("ERROR: Combining rec or pi programs not supported with MDL objective. Exiting.")
262262
assert(False)
263263

264264
model_inconsistent = self.tester.test_prog_inconsistent(model_prog)

popper/gen2.py

Lines changed: 35 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
1-
import time
1+
import numbers
22
import re
3+
from itertools import permutations
4+
from typing import Any, Set, Tuple
5+
36
import clingo
4-
import numbers
57
import clingo.script
68
import pkg_resources
7-
from . util import Constraint, Literal
89
from clingo import Function, Number, Tuple_
9-
from itertools import permutations
10+
11+
from .util import Constraint, Literal
12+
1013

1114
def arg_to_symbol(arg):
1215
if isinstance(arg, tuple):
@@ -16,9 +19,11 @@ def arg_to_symbol(arg):
1619
if isinstance(arg, str):
1720
return Function(arg)
1821

22+
1923
def atom_to_symbol(pred, args):
2024
xs = tuple(arg_to_symbol(arg) for arg in args)
21-
return Function(name = pred, arguments = xs)
25+
return Function(name=pred, arguments=xs)
26+
2227

2328
DEFAULT_HEURISTIC = """
2429
#heuristic size(N). [1000-N,true]
@@ -29,6 +34,7 @@ def atom_to_symbol(pred, args):
2934
program_size_at_least(M):- size(N), program_bounds(M), M <= N.
3035
"""
3136

37+
3238
class Generator:
3339

3440
def __init__(self, settings, bkcons=[]):
@@ -44,12 +50,12 @@ def __init__(self, settings, bkcons=[]):
4450

4551
with open(settings.bias_file) as f:
4652
bias_text = f.read()
47-
bias_text = re.sub(r'max_vars\(\d*\).','', bias_text)
48-
bias_text = re.sub(r'max_body\(\d*\).','', bias_text)
49-
bias_text = re.sub(r'max_clauses\(\d*\).','', bias_text)
53+
bias_text = re.sub(r'max_vars\(\d*\).', '', bias_text)
54+
bias_text = re.sub(r'max_body\(\d*\).', '', bias_text)
55+
bias_text = re.sub(r'max_clauses\(\d*\).', '', bias_text)
5056

51-
for p,a in settings.pointless:
52-
bias_text = re.sub(rf'body_pred\({p},{a}\).','', bias_text)
57+
for p, a in settings.pointless:
58+
bias_text = re.sub(rf'body_pred\({p},{a}\).', '', bias_text)
5359
bias_text = re.sub(rf'constant\({p},.*?\).*', '', bias_text, flags=re.MULTILINE)
5460

5561
encoding.append(bias_text)
@@ -71,13 +77,13 @@ def __init__(self, settings, bkcons=[]):
7177
type_encoding = set()
7278
if self.settings.head_types:
7379
types = tuple(self.settings.head_types)
74-
str_types = str(types).replace("'","")
80+
str_types = str(types).replace("'", "")
7581
for i, x in enumerate(self.settings.head_types):
7682
type_encoding.add(f'type_pos({str_types}, {i}, {x}).')
7783

7884
for pred, types in self.settings.body_types.items():
7985
types = tuple(types)
80-
str_types = str(types).replace("'","")
86+
str_types = str(types).replace("'", "")
8187
for i, x in enumerate(types):
8288
type_encoding.add(f'type_pos({str_types}, {i}, {x}).')
8389
encoding.extend(type_encoding)
@@ -104,10 +110,10 @@ def __init__(self, settings, bkcons=[]):
104110
encoding = '\n'.join(encoding)
105111

106112
# with open('ENCODING-GEN.pl', 'w') as f:
107-
# f.write(encoding)
113+
# f.write(encoding)
108114

109115
if self.settings.single_solve:
110-
solver = clingo.Control(['--heuristic=Domain','-Wnone'])
116+
solver = clingo.Control(['--heuristic=Domain', '-Wnone'])
111117

112118
solver.configuration.solve.models = 0
113119
solver.add('base', [], encoding)
@@ -120,12 +126,12 @@ def update_solver(self, size):
120126

121127
def get_prog(self):
122128
if self.handle is None:
123-
self.handle = iter(self.solver.solve(yield_ = True))
129+
self.handle = iter(self.solver.solve(yield_=True))
124130
self.model = next(self.handle, None)
125131
if self.model is None:
126132
return None
127133

128-
return self.parse_model_single_rule(self.model.symbols(shown = True))
134+
return self.parse_model_single_rule(self.model.symbols(shown=True))
129135

130136
def parse_model_single_rule(self, model):
131137
settings = self.settings
@@ -154,13 +160,13 @@ def constrain(self, tmp_new_cons):
154160

155161
if con_type == Constraint.GENERALISATION or con_type == Constraint.BANISH:
156162
con_size = None
157-
if self.settings.noisy and len(xs)>2:
163+
if self.settings.noisy and len(xs) > 2:
158164
con_size = xs[2]
159165
ground_rules2 = tuple(self.build_generalisation_constraint3(con_prog, con_size))
160166
new_ground_cons.update(ground_rules2)
161167
elif con_type == Constraint.SPECIALISATION:
162168
con_size = None
163-
if self.settings.noisy and len(xs)>2:
169+
if self.settings.noisy and len(xs) > 2:
164170
con_size = xs[2]
165171
ground_rules2 = tuple(self.build_specialisation_constraint3(con_prog, con_size))
166172
new_ground_cons.update(ground_rules2)
@@ -241,12 +247,12 @@ def find_deep_bindings4(self, body):
241247
if len(body_types) == 0 or head_types is None:
242248
num_vars = len({var for atom in body for var in atom.arguments})
243249
for xs in permutations(range(self.settings.max_vars), num_vars):
244-
x = {i:xs[i] for i in range(num_vars)}
250+
x = {i: xs[i] for i in range(num_vars)}
245251
yield x
246252
return
247253

248254
# if there are types, only find type-safe permutations
249-
var_type_lookup = {i:head_type for i, head_type in enumerate(head_types)}
255+
var_type_lookup = {i: head_type for i, head_type in enumerate(head_types)}
250256

251257
head_vars = set(range(len(self.settings.head_literal.arguments)))
252258
body_vars = set()
@@ -272,7 +278,7 @@ def find_deep_bindings4(self, body):
272278
k = (x, y)
273279
bad_type_matching.add(k)
274280

275-
lookup = {x:i for i, x in enumerate(body_vars)}
281+
lookup = {x: i for i, x in enumerate(body_vars)}
276282

277283
for xs in permutations(range(self.settings.max_vars), len(lookup)):
278284
assignment = {}
@@ -287,25 +293,27 @@ def find_deep_bindings4(self, body):
287293
continue
288294
yield assignment
289295

290-
def remap_variables(rule):
296+
297+
def remap_variables(rule: Tuple[Literal,Any]):
298+
head: Literal
291299
head, body = rule
292-
head_vars = set()
300+
head_vars: Set = set()
293301

294302
if head:
295-
head_vars.extend(head.arguments)
303+
head_vars |= head.arguments
296304

297305
next_var = len(head_vars)
298-
lookup = {i:i for i in head_vars}
306+
lookup = {i: i for i in head_vars}
299307

300308
new_body = set()
301309
for pred, args in body:
302310
new_args = []
303311
for var in args:
304312
if var not in lookup:
305313
lookup[var] = next_var
306-
next_var+=1
314+
next_var += 1
307315
new_args.append(lookup[var])
308316
new_atom = Literal(pred, tuple(new_args))
309317
new_body.add(new_atom)
310318

311-
return head, frozenset(new_body)
319+
return head, frozenset(new_body)

0 commit comments

Comments
 (0)