-
Notifications
You must be signed in to change notification settings - Fork 3
/
ruletaker.h
1304 lines (1196 loc) · 47.4 KB
/
ruletaker.h
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
/**
* ruletaker.h - Code to read RukeTaker data and attempt to answer the questions.
*
* Created on: Dec 8, 2020
* Author: asaparov
*/
#ifndef RULETAKER_H_
#define RULETAKER_H_
#include <stdio.h>
#include "json.h"
enum class ruletaker_key {
THEORY,
QUESTIONS,
QUESTION,
ANSWER,
OTHER
};
enum class ruletaker_reader_state {
START,
ROOT_OBJECT,
QUESTIONS,
QUESTION,
TRIPLES,
TRIPLE,
PROOFS_WITH_INTERMEDIATES,
INTERMEDIATES,
INTERMEDIATE
};
enum class ruletaker_label : uint_fast8_t {
FALSE,
TRUE,
UNKNOWN
};
template<typename T>
struct empty_value { };
template<>
struct empty_value<ruletaker_label> {
static constexpr ruletaker_label get_value() {
return ruletaker_label::UNKNOWN;
}
};
template<>
struct empty_value<string> {
static inline string get_value() {
string str;
str.data = nullptr;
return str;
}
};
inline void set_empty(ruletaker_label& label) {
label = ruletaker_label::UNKNOWN;
}
template<typename LabelType>
struct ruletaker_reader {
ruletaker_reader_state state;
ruletaker_key current_key;
char* context;
pair<char*, LabelType> next_question;
array<pair<string, LabelType>> questions;
ruletaker_reader() : state(ruletaker_reader_state::START), context(nullptr), next_question(nullptr, empty_value<LabelType>::get_value()), questions(44) { }
~ruletaker_reader() {
if (context != nullptr)
free(context);
if (next_question.key != nullptr)
free(next_question.key);
if (!is_empty(next_question.value))
free(next_question.value);
for (pair<string, LabelType>& question : questions) {
free(question.key);
free(question.value);
}
}
};
template<typename LabelType>
inline bool begin_object(const position& pos, ruletaker_reader<LabelType>& reader) {
if (reader.state == ruletaker_reader_state::START) {
reader.state = ruletaker_reader_state::ROOT_OBJECT;
} else if (reader.current_key == ruletaker_key::QUESTIONS) {
reader.state = ruletaker_reader_state::QUESTIONS;
} else if (reader.state == ruletaker_reader_state::QUESTIONS) {
reader.state = ruletaker_reader_state::QUESTION;
} else if (reader.state == ruletaker_reader_state::QUESTION) {
reader.state = ruletaker_reader_state::PROOFS_WITH_INTERMEDIATES;
} else if (reader.state == ruletaker_reader_state::PROOFS_WITH_INTERMEDIATES) {
reader.state = ruletaker_reader_state::INTERMEDIATES;
} else if (reader.state == ruletaker_reader_state::INTERMEDIATES) {
reader.state = ruletaker_reader_state::INTERMEDIATE;
} else if (reader.state == ruletaker_reader_state::ROOT_OBJECT) {
reader.state = ruletaker_reader_state::TRIPLES;
} else if (reader.state == ruletaker_reader_state::TRIPLES) {
reader.state = ruletaker_reader_state::TRIPLE;
}
return true;
}
template<typename LabelType>
inline bool end_object(const position& pos, ruletaker_reader<LabelType>& reader) {
if (reader.state == ruletaker_reader_state::ROOT_OBJECT) {
reader.state = ruletaker_reader_state::START;
} else if (reader.state == ruletaker_reader_state::QUESTION) {
if (!reader.questions.ensure_capacity(reader.questions.length + 1))
return false;
reader.questions[reader.questions.length].key.data = reader.next_question.key;
reader.questions[reader.questions.length].key.length = strlen(reader.next_question.key);
move(reader.next_question.value, reader.questions[reader.questions.length++].value);
reader.next_question.key = nullptr;
set_empty(reader.next_question.value);
reader.state = ruletaker_reader_state::QUESTIONS;
} else if (reader.state == ruletaker_reader_state::QUESTIONS) {
reader.state = ruletaker_reader_state::ROOT_OBJECT;
} else if (reader.state == ruletaker_reader_state::PROOFS_WITH_INTERMEDIATES) {
reader.state = ruletaker_reader_state::QUESTION;
} else if (reader.state == ruletaker_reader_state::INTERMEDIATES) {
reader.state = ruletaker_reader_state::PROOFS_WITH_INTERMEDIATES;
} else if (reader.state == ruletaker_reader_state::INTERMEDIATE) {
reader.state = ruletaker_reader_state::INTERMEDIATES;
} else if (reader.state == ruletaker_reader_state::TRIPLES) {
reader.state = ruletaker_reader_state::ROOT_OBJECT;
} else if (reader.state == ruletaker_reader_state::TRIPLE) {
reader.state = ruletaker_reader_state::TRIPLES;
}
return true;
}
template<typename LabelType>
inline bool emit_key(const array<char>& key_name, const position& pos, ruletaker_reader<LabelType>& reader) {
if (compare_strings(key_name, "theory")) {
reader.current_key = ruletaker_key::THEORY;
} else if (compare_strings(key_name, "questions")) {
reader.current_key = ruletaker_key::QUESTIONS;
} else if (compare_strings(key_name, "question")) {
reader.current_key = ruletaker_key::QUESTION;
} else if (compare_strings(key_name, "answer")) {
reader.current_key = ruletaker_key::ANSWER;
} else {
reader.current_key = ruletaker_key::OTHER;
}
return true;
}
template<typename LabelType> inline constexpr bool begin_list(const position& pos, ruletaker_reader<LabelType>& reader) { return true; }
template<typename LabelType> inline constexpr bool end_list(const position& pos, ruletaker_reader<LabelType>& reader) { return true; }
inline bool parse_label(ruletaker_label& label, const array<char>& str, const position& pos) {
if (compare_strings(str, "Unknown")) {
label = ruletaker_label::UNKNOWN;
return true;
} else {
read_error("Label must be either `true`, `false`, or \"Unknown\"", pos);
return false;
}
}
template<bool Value>
inline bool parse_label(ruletaker_label& label, const position& pos) {
label = (Value ? ruletaker_label::TRUE : ruletaker_label::FALSE);
return true;
}
inline bool parse_label(string& label, const array<char>& str, const position& pos) {
return init(label, str.data, str.length);
}
template<bool Value>
inline bool parse_label(string& label, const position& pos) {
read_error("Label must be a string", pos);
return false;
}
template<typename LabelType>
inline bool emit_string(const array<char>& str, const position& pos, ruletaker_reader<LabelType>& reader) {
if (reader.current_key == ruletaker_key::THEORY) {
if (reader.context != nullptr) {
read_error("Found duplicate `theory` entry", pos);
return false;
}
reader.context = (char*) malloc(sizeof(char) * (str.length + 1));
if (reader.context == nullptr) {
fprintf(stderr, "emit_string ERROR: Out of memory.\n");
return false;
}
for (unsigned int i = 0; i < str.length; i++)
reader.context[i] = str[i];
reader.context[str.length] = '\0';
} else if (reader.current_key == ruletaker_key::QUESTION) {
if (reader.next_question.key != nullptr) {
read_error("Found duplicate `question` entry", pos);
return false;
}
reader.next_question.key = (char*) malloc(sizeof(char) * (str.length + 1));
if (reader.next_question.key == nullptr) {
fprintf(stderr, "emit_string ERROR: Out of memory.\n");
return false;
}
for (unsigned int i = 0; i < str.length; i++)
reader.next_question.key[i] = str[i];
reader.next_question.key[str.length] = '\0';
} else if (reader.current_key == ruletaker_key::ANSWER) {
return parse_label(reader.next_question.value, str, pos);
}
return true;
}
template<typename LabelType>
inline bool emit_true(const position& pos, ruletaker_reader<LabelType>& reader) {
if (reader.current_key == ruletaker_key::ANSWER)
return parse_label<true>(reader.next_question.value, pos);
else return true;
}
template<typename LabelType>
inline bool emit_false(const position& pos, ruletaker_reader<LabelType>& reader) {
if (reader.current_key == ruletaker_key::ANSWER)
return parse_label<false>(reader.next_question.value, pos);
else return true;
}
template<typename LabelType> constexpr bool emit_null(const position& pos, ruletaker_reader<LabelType>& reader) { return true; }
template<typename LabelType> constexpr bool emit_number(double value, const position& pos, ruletaker_reader<LabelType>& reader) { return true; }
template<typename Stream>
struct line_reader {
Stream& in;
bool eof;
line_reader(Stream& in) : in(in), eof(false) { }
};
template<typename Stream>
int fgetc(line_reader<Stream>& lr) {
int c = fgetc(lr.in);
if (c == -1)
lr.eof = true;
else if (c == '\n')
return -1;
return c;
}
template<typename Stream>
int ungetc(int c, line_reader<Stream>& lr) {
return ungetc(c, lr.in);
}
template<typename LabelType, typename ProcessQuestionsFunc>
bool read_ruletaker_data(const char* filename, ProcessQuestionsFunc process_questions)
{
FILE* in = (FILE*) fopen(filename, "rb");
if (in == nullptr) {
fprintf(stderr, "ERROR: Unable to open '%s' for reading.\n", filename);
return false;
}
line_reader<FILE*> lr(in);
position current(1, 1);
while (!lr.eof) {
/* check if this is an empty line */
int c = fgetc(lr);
if (c == -1) continue;
ungetc(c, lr);
ruletaker_reader<LabelType> reader;
if (!json_parse(lr, reader, current)) {
fclose(in);
return false;
}
current.line++;
current.column = 1;
if (!process_questions(reader.context, reader.questions)) {
fclose(in);
return false;
}
}
fclose(in);
return true;
}
#include <atomic>
enum class ruletaker_work_item_type {
READ_CONTEXT,
ANSWER_QUESTION
};
template<typename Theory, typename PriorStateType>
struct ruletaker_context_item
{
Theory T;
PriorStateType proof_axioms;
unsigned int context_id;
std::minstd_rand prng_engine;
char* context;
array<pair<string, ruletaker_label>> questions;
static inline void free(ruletaker_context_item<Theory, PriorStateType>& item) {
core::free(item.context);
for (auto& entry : item.questions)
core::free(entry.key);
core::free(item.questions);
if (!core::is_empty(item.T)) {
core::free(item.T);
item.proof_axioms.~PriorStateType();
}
}
};
template<typename Theory, typename PriorStateType>
struct ruletaker_question_item
{
Theory T;
PriorStateType proof_axioms;
unsigned int context_id;
unsigned int question_id;
string question;
ruletaker_label label;
static inline void free(ruletaker_question_item& item) {
core::free(item.question);
if (!core::is_empty(item.T)) {
core::free(item.T);
item.proof_axioms.~PriorStateType();
}
}
};
template<typename BuiltInPredicates>
inline void find_head_or_not(
hol_term* src, hol_term*& head,
head_index& predicate_index)
{
if (src->type == hol_term_type::NOT) {
head = src;
return;
}
find_head<BuiltInPredicates>(src, head, predicate_index);
}
inline bool negate_head(
hol_term* src, hol_term*& dst)
{
array<hol_term*> scopes(8);
auto gather_scopes = [&scopes](hol_term* term) {
if (term->type == hol_term_type::EXISTS || term->type == hol_term_type::FOR_ALL || term->type == hol_term_type::LAMBDA)
return scopes.add(term);
return true;
};
head_index predicate_index;
hol_term* head = find_head(src, predicate_index, find_head_or_not<built_in_predicates>, gather_scopes);
if (head == nullptr)
return false;
hol_term* new_head;
if (head->type == hol_term_type::NOT) {
new_head = head->unary.operand;
new_head->reference_count++;
} else {
/* check if the head is a `same` event */
bool is_same = true;
unsigned int head_index = scopes.length - 1;
do {
is_same = false;
if (head->type == hol_term_type::EXISTS) {
hol_term* operand = head->quantifier.operand;
if (operand->type == hol_term_type::AND) {
for (unsigned int i = 0; !is_same && i < operand->array.length; i++) {
hol_term* conjunct = operand->array.operands[i];
if (conjunct->type == hol_term_type::UNARY_APPLICATION
&& (*conjunct->binary.left == hol_term::constants<(unsigned int) built_in_predicates::SAME>::value
|| *conjunct->binary.left == hol_term::constants<(unsigned int) built_in_predicates::NAME>::value)
&& conjunct->binary.right->type == hol_term_type::VARIABLE && conjunct->binary.right->variable == head->quantifier.variable)
{
is_same = true;
} else if (get_scope<built_in_predicates, (unsigned int) built_in_predicates::NAME>(conjunct, head->quantifier.variable) != nullptr) {
is_same = true;
}
}
} else {
if (operand->type == hol_term_type::UNARY_APPLICATION
&& (*operand->binary.left == hol_term::constants<(unsigned int) built_in_predicates::SAME>::value
|| *operand->binary.left == hol_term::constants<(unsigned int) built_in_predicates::NAME>::value)
&& operand->binary.right->type == hol_term_type::VARIABLE && operand->binary.right->variable == head->quantifier.variable)
{
is_same = true;
} else if (get_scope<built_in_predicates, (unsigned int) built_in_predicates::NAME>(operand, head->quantifier.variable) != nullptr) {
is_same = true;
}
}
if (is_same) {
if (head_index > 0) {
/* negate the scope immediately preceding `head` */
head_index--;
head = scopes[head_index];
} else {
fprintf(stderr, "negate_head ERROR: Unable to find appropriate scope to negate.\n");
return false;
}
}
}
} while (is_same);
new_head = hol_term::new_not(head);
if (new_head == nullptr) return false;
head->reference_count++;
}
dst = substitute_head<any_node_position::NONE>(src, head, new_head);
free(*new_head); if (new_head->reference_count == 0) free(new_head);
return (dst != nullptr);
}
template<typename Proof>
struct dummy_collector {
const Proof* test_proof;
dummy_collector(const Proof* test_proof) : test_proof(test_proof) { }
constexpr inline bool has_prior(const Proof* proof) const {
return (proof != test_proof);
}
};
template<typename Proof>
dummy_collector<Proof> make_dummy_collector(const Proof* test_proof) {
return dummy_collector<Proof>(test_proof);
}
template<typename Theory, typename ProofPrior>
inline void print_theory(const Theory& T, const typename Theory::Proof* test_proof, ProofPrior& proof_prior)
{
typedef typename Theory::Formula Formula;
array<Formula*> extra_axioms(16);
T.get_extra_axioms(extra_axioms);
auto collector = make_dummy_collector(test_proof);
double value = log_probability(T.observations, extra_axioms, proof_prior, collector);
fprintf(stdout, "log probability of theory: %lf\n", value);
T.print_axioms(stdout, *debug_terminal_printer);
T.print_disjunction_introductions(stdout, *debug_terminal_printer);
fflush(stdout);
}
struct question_result {
unsigned int context_id;
unsigned int question_id;
double log_probability_diff;
ruletaker_label true_label;
static inline void swap(question_result& first, question_result& second) {
core::swap(first.context_id, second.context_id);
core::swap(first.question_id, second.question_id);
core::swap(first.log_probability_diff, second.log_probability_diff);
core::swap(first.true_label, second.true_label);
}
};
inline bool operator < (const question_result& first, const question_result& second) {
if (first.context_id < second.context_id) return true;
else if (first.context_id > second.context_id) return false;
else return first.question_id < second.question_id;
}
inline bool operator == (const question_result& first, const question_result& second) {
return first.context_id == second.context_id
&& first.question_id == second.question_id;
}
constexpr unsigned int MAX_CONTEXT_COUNT = 140;
constexpr unsigned int MAX_QUESTION_COUNT = 5270;
constexpr double PREDICT_UNKNOWN_THRESHOLD = 2000.0;
template<typename ProofCalculus, typename Canonicalizer>
inline bool is_formula_possible(
theory<ProofCalculus, Canonicalizer>& T,
typename ProofCalculus::Language* logical_form)
{
typedef typename ProofCalculus::Language Formula;
typedef typename ProofCalculus::Proof Proof;
unsigned int new_constant;
set_changes<Formula> set_diff;
Proof* new_proof = T.add_formula(logical_form, set_diff, new_constant);
if (new_proof == nullptr)
return false;
T.template remove_formula<true>(new_proof, set_diff);
return true;
}
template<typename Theory, typename PriorStateType, typename ProofPrior>
bool resample_observations(Theory& T, PriorStateType& proof_axioms, ProofPrior& proof_prior)
{
typedef typename Theory::Proof Proof;
typedef typename Theory::ProofType ProofType;
array<pair<hol_term*, Proof*>> observations(T.observations.size);
for (Proof* proof : T.observations) {
/* get the logical form conclusion of this proof */
hol_term* formula;
if (proof->type == ProofType::AXIOM) {
formula = proof->formula;
} else if (proof->type == ProofType::EXISTENTIAL_INTRODUCTION) {
unsigned int index;
for (index = 0; index < T.existential_intro_nodes.length; index++)
if (T.existential_intro_nodes[index].value == proof) break;
if (index == T.existential_intro_nodes.length) {
fprintf(stderr, "resample_observations ERROR: Unable to find proof in `theory.existential_intro_nodes`.\n");
return false;
}
formula = T.existential_intro_nodes[index].key;
} else if (proof->type == ProofType::IMPLICATION_INTRODUCTION) {
unsigned int index;
for (index = 0; index < T.implication_intro_nodes.length; index++)
if (T.implication_intro_nodes[index].value == proof) break;
if (index == T.implication_intro_nodes.length) {
fprintf(stderr, "resample_observations ERROR: Unable to find proof in `theory.implication_intro_nodes`.\n");
return false;
}
formula = T.implication_intro_nodes[index].key;
} else if (proof->type == ProofType::DISJUNCTION_INTRODUCTION) {
unsigned int index;
for (index = 0; index < T.disjunction_intro_nodes.length; index++)
if (T.disjunction_intro_nodes[index].value == proof) break;
if (index == T.disjunction_intro_nodes.length) {
fprintf(stderr, "resample_observations ERROR: Unable to find proof in `theory.disjunction_intro_nodes`.\n");
return false;
}
formula = T.disjunction_intro_nodes[index].key;
} else if (proof->type == ProofType::PROOF_BY_CONTRADICTION
&& proof->operands[0]->type == ProofType::NEGATION_ELIMINATION
&& proof->operands[0]->operands[0]->type == ProofType::CONJUNCTION_ELIMINATION
&& proof->operands[0]->operands[0]->operands[0] == proof->operands[1])
{
unsigned int index;
for (index = 0; index < T.negated_conjunction_nodes.length; index++)
if (T.negated_conjunction_nodes[index].value == proof) break;
if (index == T.negated_conjunction_nodes.length) {
fprintf(stderr, "resample_observations ERROR: Unable to find proof in `theory.negated_conjunction_nodes`.\n");
return false;
}
formula = T.negated_conjunction_nodes[index].key;
} else {
fprintf(stderr, "resample_observations ERROR: Unsupported `ProofType`.\n");
return false;
}
observations[observations.length++] = {formula, proof};
}
for (const pair<hol_term*, Proof*>& entry : observations) {
entry.key->reference_count++;
set_changes<hol_term> set_diff;
T.template remove_formula<false>(entry.value, set_diff);
proof_axioms.template subtract(entry.value, set_diff.old_set_axioms, proof_prior);
free(*entry.value); if (entry.value->reference_count == 0) free(entry.value);
}
for (unsigned int i = observations.length - 1; i > 0; i--) {
unsigned int next = sample_uniform(i + 1);
if (next != i) {
core::swap(observations[next].key, observations[i].key);
core::swap(observations[next].value, observations[i].value);
}
}
for (unsigned int i = 0; i < observations.length; i++) {
unsigned int new_constant;
set_changes<hol_term> set_diff;
Proof* new_proof = T.add_formula(observations[i].key, set_diff, new_constant);
while (new_proof == nullptr) {
null_collector collector;
set_diff.clear();
for (unsigned int t = 0; t < 10; t++)
do_exploratory_mh_step(T, proof_prior, proof_axioms, collector);
new_proof = T.add_formula(observations[i].key, set_diff, new_constant);
}
if (new_proof == nullptr) {
for (auto entry : observations) { free(*entry.key); if (entry.key->reference_count == 0) free(entry.key); }
return false;
} else if (!proof_axioms.template add(new_proof, set_diff.new_set_axioms, proof_prior)) {
T.template remove_formula<true>(new_proof, set_diff);
for (auto entry : observations) { free(*entry.key); if (entry.key->reference_count == 0) free(entry.key); }
return false;
}
observations[i].value = new_proof;
Theory& T_MAP = *((Theory*) alloca(sizeof(Theory)));
PriorStateType& proof_axioms_MAP = *((PriorStateType*) alloca(sizeof(PriorStateType)));
hash_map<const hol_term*, hol_term*> formula_map(128);
Theory::clone(T, T_MAP, formula_map);
new (&proof_axioms_MAP) PriorStateType(proof_axioms, formula_map);
auto collector = make_log_probability_collector(T, proof_prior);
double max_log_probability = collector.current_log_probability;
for (unsigned int j = 0; j < 4; j++) {
for (unsigned int t = 0; t < 400; t++) {
do_mh_step(T, proof_prior, proof_axioms, collector);
if (collector.current_log_probability > max_log_probability) {
free(T_MAP); proof_axioms_MAP.~PriorStateType(); formula_map.clear();
Theory::clone(T, T_MAP, formula_map);
new (&proof_axioms_MAP) PriorStateType(proof_axioms, formula_map);
max_log_probability = collector.current_log_probability;
}
}
if (j + 1 < 4) {
for (unsigned int t = 0; t < 20; t++)
do_exploratory_mh_step(T, proof_prior, proof_axioms, collector);
}
}
free(T); proof_axioms.~PriorStateType(); formula_map.clear();
Theory::clone(T_MAP, T, formula_map);
new (&proof_axioms) PriorStateType(proof_axioms_MAP, formula_map);
T_MAP.print_axioms(stdout, *debug_terminal_printer); fflush(stdout);
free(T_MAP); proof_axioms_MAP.~PriorStateType();
}
for (auto entry : observations) { free(*entry.key); if (entry.key->reference_count == 0) free(entry.key); }
return true;
}
template<typename ArticleSource, typename Parser, typename Theory, typename PriorStateType, typename ProofPrior>
void do_ruletaker_experiments(bool& status,
ruletaker_context_item<Theory, PriorStateType>* context_queue,
ruletaker_question_item<Theory, PriorStateType>* question_queue,
unsigned int& context_queue_start,
unsigned int& question_queue_start,
unsigned int& context_queue_length,
unsigned int& question_queue_length,
std::mutex& work_queue_lock,
std::condition_variable& work_queue_cv,
const std::minstd_rand prng_engine,
ArticleSource& corpus, const Parser& parser_src,
ProofPrior& proof_prior,
const hash_map<string, unsigned int>& names_src,
hash_set<unsigned int>& seed_entities,
std::mutex& results_lock,
array<question_result>& results,
array<pair<unsigned int, string>>& unparseable_context,
std::atomic_uint& total,
std::atomic_uint& num_threads_reading_context,
std::atomic_uint& num_threads_running)
{
num_threads_running++;
Parser& parser = *((Parser*) alloca(sizeof(Parser)));
if (!init(parser, parser_src)) {
status = false;
num_threads_running--;
work_queue_cv.notify_all();
return;
}
hash_map<string, unsigned int> names(names_src.table.capacity);
for (const auto& entry : names_src) {
unsigned int index = names.table.index_to_insert(entry.key);
if (!init(names.table.keys[index], entry.key)) {
status = false;
num_threads_running--;
work_queue_cv.notify_all();
for (auto entry : names) free(entry.key);
free(parser); return;
}
names.values[index] = entry.value;
names.table.size++;
}
if (!parser.invert_name_map(names)) {
status = false;
num_threads_running--;
work_queue_cv.notify_all();
for (auto entry : names) free(entry.key);
free(parser); return;
}
while (status)
{
std::unique_lock<std::mutex> lock(work_queue_lock);
while (status && context_queue_length == context_queue_start && question_queue_length == question_queue_start && num_threads_reading_context != 0)
work_queue_cv.wait(lock);
if (!status || (num_threads_reading_context == 0 && context_queue_start == context_queue_length && question_queue_start == question_queue_length)) {
num_threads_running--;
for (auto entry : names) free(entry.key);
free(parser); return;
}
if (question_queue_start < question_queue_length) {
ruletaker_question_item<Theory, PriorStateType>& job = question_queue[question_queue_start++];
lock.unlock();
/*if (job.question_id != 5 - 1)
{
total++;
free(job);
continue;
}*/
/* for reproducibility, reset the PRNG state */
core::engine = context_queue[job.context_id].prng_engine;
/* first clone the theory from the appropriate work item */
Theory& T_copy = *((Theory*) alloca(sizeof(Theory)));
hash_map<const hol_term*, hol_term*> formula_map(128);
if (!Theory::clone(job.T, T_copy, formula_map)) {
status = false;
num_threads_running--;
work_queue_cv.notify_all();
free(job);
for (auto entry : names) free(entry.key);
free(parser); return;
}
PriorStateType proof_axioms_copy(job.proof_axioms, formula_map);
unsigned int parse_count;
constexpr unsigned int max_parse_count = 2;
hol_term* logical_forms[max_parse_count];
double log_probabilities[max_parse_count];
if (parse_sentence(parser, job.question.data, names, logical_forms, log_probabilities, parse_count))
{
typedef typename Theory::Proof Proof;
Theory& T_MAP_true = *((Theory*) alloca(sizeof(Theory)));
Proof* proof_MAP_true; Proof* proof_MAP_false;
timer stopwatch;
double log_probability_true = log_joint_probability_of_truth(job.T, proof_prior, job.proof_axioms, logical_forms[0], 100, 4, 20, T_MAP_true, proof_MAP_true);
for (unsigned int j = 0; isinf(log_probability_true) && j < 400; j++) {
null_collector collector;
for (unsigned int t = 0; t < 10; t++)
do_exploratory_mh_step(job.T, proof_prior, job.proof_axioms, collector);
log_probability_true = log_joint_probability_of_truth(job.T, proof_prior, job.proof_axioms, logical_forms[0], 100, 4, 20, T_MAP_true, proof_MAP_true);
}
if (!isinf(log_probability_true)) {
hol_term* negated;
if (!negate_head(logical_forms[0], negated) || negated == nullptr) {
free_logical_forms(logical_forms, parse_count);
status = false;
num_threads_running--;
work_queue_cv.notify_all();
free(job); free(T_copy); free(T_MAP_true);
total++;
for (auto entry : names) free(entry.key);
free(parser); return;
}
/* for reproducibility, reset the PRNG state */
core::engine = context_queue[job.context_id].prng_engine;
Theory& T_MAP_false = *((Theory*) alloca(sizeof(Theory)));
T_copy.print_axioms(stdout, *debug_terminal_printer);
T_copy.print_disjunction_introductions(stdout, *debug_terminal_printer);
fflush(stdout);
double log_probability_false = log_joint_probability_of_truth(T_copy, proof_prior, proof_axioms_copy, negated, 100, 4, 20, T_MAP_false, proof_MAP_false);
for (unsigned int j = 0; isinf(log_probability_false) && j < 400; j++) {
null_collector collector;
for (unsigned int t = 0; t < 10; t++)
do_exploratory_mh_step(T_copy, proof_prior, proof_axioms_copy, collector);
log_probability_false = log_joint_probability_of_truth(T_copy, proof_prior, proof_axioms_copy, negated, 100, 4, 20, T_MAP_false, proof_MAP_false);
}
free(*negated); if (negated->reference_count == 0) free(negated);
if (fabs(log_probability_true - log_probability_false) < PREDICT_UNKNOWN_THRESHOLD) {
if (job.label != ruletaker_label::UNKNOWN) {
if (!isinf(log_probability_true)) print_theory(T_MAP_true, proof_MAP_true, proof_prior);
if (!isinf(log_probability_false)) print_theory(T_MAP_false, proof_MAP_false, proof_prior);
}
} else if (log_probability_true > log_probability_false) {
if (job.label != ruletaker_label::TRUE) {
if (!isinf(log_probability_true)) print_theory(T_MAP_true, proof_MAP_true, proof_prior);
if (!isinf(log_probability_false)) print_theory(T_MAP_false, proof_MAP_false, proof_prior);
}
} else if (log_probability_false > log_probability_true) {
if (job.label != ruletaker_label::FALSE) {
if (!isinf(log_probability_true)) print_theory(T_MAP_true, proof_MAP_true, proof_prior);
if (!isinf(log_probability_false)) print_theory(T_MAP_false, proof_MAP_false, proof_prior);
}
}
results_lock.lock();
results.add({job.context_id, job.question_id, log_probability_true - log_probability_false, job.label});
results_lock.unlock();
if (!isinf(log_probability_true)) free(T_MAP_true);
if (!isinf(log_probability_false)) free(T_MAP_false);
} else {
if (job.label != ruletaker_label::FALSE) {
if (!isinf(log_probability_true)) print_theory(T_MAP_true, proof_MAP_true, proof_prior);
}
results_lock.lock();
results.add({job.context_id, job.question_id, -std::numeric_limits<double>::infinity(), job.label});
results_lock.unlock();
}
total_reasoning += stopwatch.milliseconds();
fprintf(stderr, "consistency checking time: %llums, total reasoning time: %llums\n", consistency_checking_ms.load(), total_reasoning.load());
total++;
free_logical_forms(logical_forms, parse_count);
} else {
total++;
}
free(T_copy);
free(job);
} else {
num_threads_reading_context++;
ruletaker_context_item<Theory, PriorStateType>& job = context_queue[context_queue_start++];
lock.unlock();
/*if (job.context_id != 6 - 1) {
total += job.questions.length;
num_threads_reading_context--;
free(job);
continue;
}*/
/* for reproducibility, reset the PRNG state */
core::engine = prng_engine;
/* read the context sentences */
unsigned int i = 0;
unsigned int start = 0;
for (; job.context[i] != '\0'; i++) {
if (job.context[i] == '.') {
const char old_next = job.context[i + 1];
job.context[i + 1] = '\0';
if (!read_sentence(corpus, parser, job.context + start, job.T, names, seed_entities, proof_prior, job.proof_axioms, 10, UINT_MAX)) {
std::unique_lock<std::mutex> lock(results_lock);
if (!unparseable_context.ensure_capacity(unparseable_context.length + 1)
|| !init(unparseable_context[unparseable_context.length].value, job.context + start))
{
job.context[i + 1] = old_next;
status = false;
num_threads_running--;
num_threads_reading_context--;
work_queue_cv.notify_all();
free(job);
for (auto entry : names) free(entry.key);
free(parser); return;
}
unparseable_context[unparseable_context.length++].key = job.context_id;
job.context[i + 1] = old_next;
break;
}
job.context[i + 1] = old_next;
start = i + 1;
while (isspace(job.context[start])) start++;
Theory& T_MAP = *((Theory*) alloca(sizeof(Theory)));
PriorStateType& proof_axioms_MAP = *((PriorStateType*) alloca(sizeof(PriorStateType)));
hash_map<const hol_term*, hol_term*> formula_map(128);
Theory::clone(job.T, T_MAP, formula_map);
new (&proof_axioms_MAP) PriorStateType(job.proof_axioms, formula_map);
auto collector = make_log_probability_collector(job.T, proof_prior);
double max_log_probability = collector.current_log_probability;
timer stopwatch;
for (unsigned int j = 0; j < 4; j++) {
for (unsigned int t = 0; t < 100; t++) {
bool print_debug = false;
if (print_debug) job.T.template print_axioms<true>(stdout, *debug_terminal_printer);
if (print_debug) { job.T.print_disjunction_introductions(stdout, *debug_terminal_printer); fflush(stdout); }
/*if (i == 436) {
fprintf(stderr, "DEBUG: i = %u, j = %u, t = %u\n", i, j, t);
job.proof_axioms.check_proof_axioms(job.T);
job.proof_axioms.check_universal_eliminations(job.T, collector);
job.T.check_concept_axioms();
job.T.check_disjunction_introductions();
job.T.are_elements_provable();
job.T.sets.check_freeable_sets();
job.T.sets.are_descendants_valid();
job.T.sets.are_set_sizes_valid();
job.T.sets.check_set_ids();
job.T.template print_axioms<true>(stderr, *debug_terminal_printer);
job.T.print_disjunction_introductions(stderr, *debug_terminal_printer);
}*/
do_mh_step(job.T, proof_prior, job.proof_axioms, collector);
if (collector.current_log_probability > max_log_probability) {
free(T_MAP); proof_axioms_MAP.~PriorStateType(); formula_map.clear();
Theory::clone(job.T, T_MAP, formula_map);
new (&proof_axioms_MAP) PriorStateType(job.proof_axioms, formula_map);
max_log_probability = collector.current_log_probability;
}
}
if (j + 1 < 4) {
for (unsigned int t = 0; t < 20; t++)
do_exploratory_mh_step(job.T, proof_prior, job.proof_axioms, collector);
}
}
free(job.T); job.proof_axioms.~PriorStateType(); formula_map.clear();
Theory::clone(T_MAP, job.T, formula_map);
new (&job.proof_axioms) PriorStateType(proof_axioms_MAP, formula_map);
T_MAP.print_axioms(stdout, *debug_terminal_printer); fflush(stdout);
free(T_MAP); proof_axioms_MAP.~PriorStateType();
total_reasoning += stopwatch.milliseconds();
fprintf(stderr, "consistency checking time: %llums, total reasoning time: %llums\n", consistency_checking_ms.load(), total_reasoning.load());
}
}
if (job.context[i] == '\0') {
/* if we successfully read the context, enqueue the jobs for reading/answering the associated questions */
job.prng_engine = core::engine;
std::unique_lock<std::mutex> lock(work_queue_lock);
if (question_queue_length + job.questions.length > MAX_QUESTION_COUNT) {
fprintf(stderr, "do_ruletaker_experiments ERROR: Requested question queue length exceeds `MAX_QUESTION_COUNT`.\n");
status = false;
num_threads_running--;
num_threads_reading_context--;
work_queue_cv.notify_all();
free(job);
for (auto entry : names) free(entry.key);
free(parser); return;
}
for (unsigned int j = 0; j < job.questions.length; j++) {
ruletaker_question_item<Theory, PriorStateType>& new_question = question_queue[question_queue_length];
set_empty(new_question.T);
new_question.context_id = job.context_id;
new_question.question_id = j;
if (!init(new_question.question, job.questions[j].key.length + 1)) {
status = false;
num_threads_running--;
num_threads_reading_context--;
work_queue_cv.notify_all();
free(job);
for (auto entry : names) free(entry.key);
free(parser); return;
}
for (unsigned int k = 0; k < job.questions[j].key.length; k++)
new_question.question[k] = job.questions[j].key[k];
new_question.question[job.questions[j].key.length] = '\0';
new_question.question.length = job.questions[j].key.length;
new_question.label = job.questions[j].value;
hash_map<const hol_term*, hol_term*> formula_map(128);
if (!Theory::clone(job.T, new_question.T, formula_map)) {
status = false;
num_threads_running--;
num_threads_reading_context--;
work_queue_cv.notify_all();
set_empty(new_question.T);
free(new_question); free(job);
for (auto entry : names) free(entry.key);
free(parser); return;
} else if (new (&new_question.proof_axioms) PriorStateType(job.proof_axioms, formula_map) == nullptr) {
status = false;
num_threads_running--;
num_threads_reading_context--;
work_queue_cv.notify_all();
free(new_question.T);
set_empty(new_question.T);
free(new_question); free(job);
for (auto entry : names) free(entry.key);
free(parser); return;
}
question_queue_length++;
work_queue_cv.notify_one();
}
} else {
total += job.questions.length;
}
num_threads_reading_context--;
free(job);
}
}
num_threads_running--;
for (auto entry : names) free(entry.key);
free(parser);
}
inline char label_to_char(ruletaker_label label) {
switch (label) {
case ruletaker_label::UNKNOWN: return '?';
case ruletaker_label::TRUE: return 'T';
case ruletaker_label::FALSE: return 'F';
}
fprintf(stderr, "label_to_char ERROR: Unrecognized `ruletaker_label`.\n");
exit(EXIT_FAILURE);
}
inline void print_ruletaker_results(
const std::atomic_uint& total,
array<question_result>& results,
array<pair<unsigned int, string>>& unparseable_context,
std::mutex& results_lock,
const char* output_filepath)
{
std::unique_lock<std::mutex> lock(results_lock);
fprintf(stderr, "total_read_sentence = %u, add_formula_failures = %u, total_add_formula = %u\n", total_read_sentence.load(), add_formula_failures.load(), total_add_formula.load());
insertion_sort(results);
FILE* out = open_file(output_filepath, "w");
if (out == nullptr) {
fprintf(stderr, "ERROR: Unable to open `%s` for writing.\n", output_filepath);
return;
}