-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogic.py
executable file
·377 lines (322 loc) · 14.2 KB
/
logic.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
import argparse
from sys import exit
# avoid arrow key values
# reference: https://stackoverflow.com/a/66539061/10446972
import readline
from objects import *
parser = argparse.ArgumentParser(prog='Logic',
description='A propositional logic toolkit.',
epilog='')
subparsers = parser.add_subparsers()
make_table_parser = subparsers.add_parser('make-table',
help='Make a truth table for the given propositional statement.')
make_table_parser.add_argument('table_statement',
nargs='?', type=str, action='store', default=None,
metavar=('STATEMENT'),
help='A propositional statement.')
make_table_parser.add_argument('-l', '--labels',
type=str, action='store', default=None,
metavar=('[FALSE][TRUE]'),
help='Custom labels for truth values.')
make_table_parser.add_argument('-n', '--no-atoms',
action='store_true', default=False,
help='Do not include atomic sentences in the table.')
make_table_parser.add_argument('-r', '--reverse-values',
action='store_true', default=False,
help='Reverse the order of the truth values in the table.')
make_table_parser.add_argument('-o', '--output',
type=str, action='store',
metavar=('FILE-PATH'),
help='The file path to be saved.')
check_equivalence_parser = subparsers.add_parser('check-equivalence',
help="Check if multiple statements are logically equivalent.")
check_equivalence_parser.add_argument('equivalent_statements',
nargs='*', type=str, action='store', default=None,
metavar=('STATEMENT'),
help='A set of propositional statements to be checked.')
check_equivalence_parser.add_argument('-l', '--labels',
type=str, action='store', default=None,
metavar=('[FALSE][TRUE]'),
help='Custom labels for truth values.')
check_equivalence_parser.add_argument('-m', '--mode',
type=str.lower, choices=['default',
'paired',
'tree'],
action='store', default='default',
metavar=('MODE'),
help='Mode for testing logical equivalences.')
check_equivalence_parser.add_argument('-r', '--reverse-values',
action='store_true', default=False,
help='Reverse the order of the truth values in the table.')
check_equivalence_parser.add_argument('-o', '--output',
type=str, action='store',
metavar=('FILE-PATH'),
help='The file path to be saved. \
This flag is ignored when mode is set to paired.')
check_validity_parser = subparsers.add_parser('check-validity',
help='Check if an argument is valid.')
check_validity_parser.add_argument('arg_premises',
nargs='*', type=str, action='store', default=None,
metavar=('PREMISE'),
help='A set of premises.')
check_validity_parser.add_argument('-c', '--conclusion',
type=str, action='store', default=None,
help='(Optional) The conclusion of the argument. \
The last premise will be used as the conclusion if one is\'t provided.')
check_validity_parser.add_argument('-l', '--labels',
type=str, action='store', default=None,
metavar=('[FALSE][TRUE]'),
help='Custom labels for truth values.')
check_validity_parser.add_argument('-r', '--reverse-values',
action='store_true', default=False,
help='Reverse the order of the truth values in the table.')
check_validity_parser.add_argument('-o', '--output', type=str, action='store',
metavar=('FILE-PATH'),
help='The file path to be saved.')
# get arguments
args = parser.parse_args()
opts = vars(args)
if 'table_statement' in opts.keys():
# make truth table
def make_table(statement: str):
config = Config(reverse=args.reverse_values,
labels=args.labels,
atoms=(not args.no_atoms))
statement = Proposition(statement, config=config)
# get output file name
filename = args.output.strip() if args.output else None
statement.output_truth_table(filepath=filename)
if args.table_statement:
statement = args.table_statement.strip()
if statement != '':
try:
make_table(statement)
except Exception as err:
print(err)
exit()
while True:
try:
statement = input('Enter a statement: ').strip()
except (KeyboardInterrupt, EOFError):
break # exit
if statement == '':
exit()
try:
make_table(statement)
except Exception as err:
print(err)
continue
elif 'equivalent_statements' in opts.keys():
# check equivalence
def check_equivalence(statements: List[Proposition] | List[str]):
config = Config(reverse=args.reverse_values,
labels=args.labels)
# parse and compile all statements
statements: Argument = Argument(statements, config=config)
# get output file name
filename = args.output.strip() if args.output else None
if args.mode == 'default':
statements.output_truth_table(annotate='equivalence', filepath=filename)
equivalent = statements.test_equivalence(mode=args.mode)
print(end=('' if filename else '\n'))
# print conclusion
if equivalent:
# equivalent
print(
bold(green(CHECK_MARK,
'The sentences are logically equivalent!'))
)
else:
# not equivalent
print(
bold(red(CROSS_MARK,
'The sentences are not logically equivalent!'))
)
print()
if args.equivalent_statements:
# strip all statements
statements = [s.strip() for s in args.equivalent_statements]
# filter empty statements
statements = [s for s in statements if s != '']
if len(statements) < 2:
print('At least 2 sentences are required.')
exit()
# create proposition objects
statements: List[Proposition] = [Proposition(s) for s in statements]
# display statements
print()
for index, statement in enumerate(statements):
print(f"{index + 1}.", display(statement))
print()
# filter statements with equivalent forms
equivalent_statements: List[Tuple[int, Proposition,
List[Tuple[int, Proposition]]]] = []
for i, s1 in enumerate(statements[:-1]):
# skip the ones pending removal
if not s1:
continue
# equivalent pairs
equivalents: List[Proposition] = []
for j, s2 in enumerate(statements[i + 1:]):
if s1 == s2:
# get index to s2
index = i + j + 1
equivalents.append((index + 1, s2))
# mark the later for removal
statements[index] = None
# add to list only if there are equivalents
if len(equivalents) > 0:
equivalent_statements.append((i + 1, s1, equivalents))
statements = [s for s in statements if s is not None]
if len(equivalent_statements) > 0:
print('The following are commutative/associative-equivalent:')
for (i, p1, p2s) in equivalent_statements:
for (j, p2) in p2s:
print(f"({i})",
display(p1) + EQUIV_SYMBOL + f"({j})",
display(p2))
print()
# check the other statements
if len(statements) > 1:
print(BOX_INNER_HLINE * 50, end='\n\n')
check_equivalence(statements)
else:
check_equivalence(statements)
exit()
# interactive mode
while True:
statements: List[Proposition] = []
while True:
try:
statement = input(f"({len(statements) + 1}) ").strip()
except (KeyboardInterrupt, EOFError):
exit()
if statement == '':
break
try:
statement = Proposition(statement)
except Exception as err:
print(err)
continue
# get prior commutative/associative-equivalent statements
equivalences = []
for s in statements:
if statement == s:
equivalences.append(s)
if len(equivalences) > 0:
print('The sentence is commutative/associative-equivalent to:')
for s in equivalences:
print('>', display(s))
else:
print(display(statement))
statements.append(statement)
if statements == []:
exit()
elif len(statements) == 1:
print('At least 2 sentences are required.')
else:
print()
check_equivalence(statements)
elif 'arg_premises' in opts.keys():
# check validity
def check_validity(premises: List[Proposition],
conclusion: Proposition):
config = Config(reverse=args.reverse_values,
labels=args.labels,
log_countermodel=True)
# parse and compile all statements
argument = Argument(premises, conclusion, config=config)
# get output file name
filename = args.output.strip() if args.output else None
argument.output_truth_table(annotate='validity', filepath=filename)
valid = argument.is_valid()
print(end=('' if filename else '\n'))
# print conclusion
if valid:
# valid
print(bold(green(CHECK_MARK, 'The argument is valid!')))
else:
# invalid
print(bold(red(CROSS_MARK, 'The argument is invalid!')))
print()
def display_argument(premises: List[Proposition],
conclusion: Proposition):
# display argument, confirm
print()
max_length = 0
for index, premise in enumerate(premises):
display_text_length = len(str(premise))
# update max length
if display_text_length > max_length:
max_length = display_text_length
print(f"{index + 1}.", display(premise))
# separate w/ max length of display premises + 5
separator(max_length + 5)
print(u'\u2234', display(conclusion), end='\n\n')
if args.arg_premises:
# strip all premises
premises = [p.strip() for p in args.arg_premises]
# filter empty premises
premises = [p for p in premises if p != '']
# take last premise as conclusion if none provided
conclusion = premises[-1]
if args.conclusion:
# conclusion is given
conclusion = args.conclusion.strip()
else:
# exclude the last premise since it was used as conclusion
premises = premises[:-1]
premises = [Proposition(p) for p in premises]
conclusion = Proposition(conclusion)
display_argument(premises, conclusion)
check_validity(premises, conclusion)
exit()
# interactive mode
while True:
premises: List[Proposition] = []
while True:
try:
premise = input(f"Premise {len(premises) + 1}: ").strip()
except (KeyboardInterrupt, EOFError):
exit()
if premise == '':
break
try:
premise = Proposition(premise)
except Exception as err:
print(err)
continue
print(display(premise))
premises.append(premise)
if premises == []:
exit()
while True:
try:
conclusion = input('Conclusion: ').strip()
except (KeyboardInterrupt, EOFError):
exit()
if conclusion == '':
# conclusion is not given
if len(premises) > 1:
# take last premise as conclusion
conclusion = premises[-1]
premises = premises[:-1]
break
else:
print('No conclusion is provided or not enough premises.')
print('NOTE: An argument needs at least 1 premise and 1 conclusion.')
continue
else:
try:
conclusion = Proposition(conclusion)
except Exception as err:
print(err)
continue
print(display(conclusion))
break
display_argument(premises, conclusion)
if confirm('Check? (Y/n)'):
print()
check_validity(premises, conclusion)
else:
parser.print_help()