Release 10.3.2 (full): ember arlynx's #10 (canonical plurals) and #11 (binomial support and counts), binomial questions reach the statistics specialist in chat; slim carries 10.3's coverage work; release test pre-registration v41, run once; hashes anchored on Solana (part 4)
Browse filesFiles changed (2)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144#!/usr/bin/env python3"""Portable source regressions for Reader7's canonical-plural precedence.
From the repository root: python3 -B tests/reader/test_canonical_plural_first.py(or -m unittest discover -s tests/reader). The source tree defaults toworkbench/swarm; override with --source-dir PATH or READER_SOURCE_DIR=PATH. Imports the suppliedreader source tree only; does not construct KQA/Engine, load corpora, or executeprograms. Standard-library unittest; no dependency installation."""import argparseimport importlibimport jsonimport osfrom pathlib import Pathimport sysimport unittest
SOURCE_DIR = NoneR7 = None
def load_source(directory): directory = Path(directory).resolve(strict=True) sys.dont_write_bytecode = True sys.path.insert(0, str(directory)) r7 = importlib.import_module('reader_v7') for module in (r7, r7.R4, r7.R6): if Path(module.__file__).resolve().parent != directory: raise RuntimeError('reader import escaped supplied source directory') return r7
def step(function, dependencies=(), inputs=()): return dict(function=function, dependencies=list(dependencies), inputs=list(inputs))
def record(question, concept): return dict(question=question, program=[ step('FindAll'), step('FilterConcept', [0], [concept]), step('Count', [1])])
class CanonicalPluralFirst(unittest.TestCase): @classmethod def setUpClass(cls): global R7 if R7 is None: directory = SOURCE_DIR or os.environ.get('READER_SOURCE_DIR') if not directory: directory = Path(__file__).resolve().parents[2] / 'workbench' / 'swarm' R7 = load_source(directory)
def setUp(self): self.old_plural = R7.PLURAL self.old_nested = R7.NESTED self.old_glue = set(R7.GLUE) R7.PLURAL = True R7.NESTED = True
def tearDown(self): R7.PLURAL = self.old_plural R7.NESTED = self.old_nested R7.GLUE.clear() R7.GLUE.update(self.old_glue)
def concept_span(self, question, concept, aliases=None): aligned = R7.align(record(question, concept), False, aliases or {}) self.assertIsNotNone(aligned) q, _spans, refs = aligned s, e, kind = refs[(1, 0)] self.assertEqual(kind, 'C') return q[s:e]
def test_count_cue_not_consumed_by_album_alias(self): aliases = {('C', 'album'): ['number of albums']} self.assertEqual(self.concept_span('Which number of albums?', 'album', aliases), 'albums')
def test_exact_two_training_examples_no_longer_replicate_wrong_outer(self): # Preserve the two actual source questions and their four-step shape. # The source's stored labels are intentionally retained, including the # March question's erroneous Count terminal. No KB execution is needed. march = dict(question='Which calendar month follows March?', program=[ step('Find', inputs=['March']), step('Relate', [0], ['followed by', 'forward']), step('FilterConcept', [1], ['calendar month']), step('Count', [2])]) albums = dict(question='Which number of albums dates not published in 1998?', program=[ step('FindAll'), step('FilterYear', [0], ['publication date', '1998', '!=']), step('FilterConcept', [1], ['album']), step('Count', [2])]) aliases = {('number of albums', 'C'): 'album'} _, outer, _, used = R7.learn7([march, albums], aliases, keys=False) self.assertEqual(used, 2) count_support = lambda key: sum(n for s, n in outer.get(key, {}).items() if json.loads(s)[-1]['function'] == 'Count') self.assertEqual(count_support('which X1'), 1) self.assertEqual(count_support('which number of X1'), 1) # Each example previously contributed the same skeleton to which X1, # reaching MIN_SKEL=2. The repaired source must not reach that threshold. self.assertEqual(R7.R6.MIN_SKEL, 2) self.assertLess(max(outer['which X1'].values()), R7.R6.MIN_SKEL)
def test_how_many_retains_count(self): _, outer, _, used = R7.learn7([record('How many albums?', 'album')], {('number of albums', 'C'): 'album'}, keys=False) self.assertEqual(used, 1) self.assertTrue(outer.get('how many X1')) self.assertTrue(all(json.loads(s)[-1]['function'] == 'Count' for s in outer['how many X1']))
def test_unrelated_alias_remains_usable(self): self.assertEqual(self.concept_span('Which university?', 'university', {('C', 'university'): ['college']}), 'university') self.assertEqual(self.concept_span('Which college?', 'university', {('C', 'university'): ['college']}), 'college')
def test_direct_canonical_phrase_with_number_of_is_unchanged(self): self.assertEqual(self.concept_span('Which number of albums?', 'number of albums'), 'number of albums')
def test_existing_plural_branches(self): for canonical, plural in [('album', 'albums'), ('box', 'boxes'), ('city', 'cities')]: with self.subTest(canonical=canonical): self.assertEqual(self.concept_span('Which ' + plural + '?', canonical), plural) self.assertEqual(self.concept_span('Which city?', 'city'), 'city')
def test_plural_disabled_preserves_alias_behavior(self): R7.PLURAL = False self.assertEqual(self.concept_span('Which number of albums?', 'album', {('C', 'album'): ['number of albums']}), 'number of albums')
def test_nonconcept_literal_still_uses_alias(self): row = dict(question='Which titles refer to record collection?', program=[ step('Find', inputs=['album']), step('What', [0])]) aligned = R7.align(row, False, {('E', 'album'): ['record collection']}) self.assertIsNotNone(aligned) q, _, refs = aligned s, e, kind = refs[(0, 0)] self.assertEqual((q[s:e], kind), ('record collection', 'E'))
if __name__ == '__main__': parser = argparse.ArgumentParser(add_help=False) parser.add_argument('--source-dir') args, remaining = parser.parse_known_args() SOURCE_DIR = args.source_dir unittest.main(argv=[sys.argv[0]] + remaining)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147"""Portable untrusted regressions for complete binomial count/support binding.
ORACLE7_TEST_ROOT selects a read-only source tree. If installed under upstream tests/statistics/, the source root is inferred. Truth for small trials is anindependent enumeration of Bernoulli sequences, not the organ's comb formula."""from fractions import Fractionfrom itertools import productimport importlibimport mathimport osfrom pathlib import Pathimport sysimport unittest
ROOT=Path(os.environ.get('ORACLE7_TEST_ROOT',Path(__file__).resolve().parents[2]))SPECS=[('statistics','organ_stats_v1','StatsOrgan'), ('statistics-v2','organ_stats_v1','StatsOrgan'), ('statistics-v2','organ_stats_v2','StatsOrganV2'), ('statistics-v3','organ_stats_v1','StatsOrgan'), ('statistics-v3','organ_stats_v2','StatsOrganV2'), ('statistics-v3','organ_stats_v3','StatsOrganV3')]LITERALS=[('0',Fraction(0)),('1',Fraction(1)),('0.5',Fraction(1,2)), ('25%',Fraction(1,4)),('0.5%',Fraction(1,200)),('0.5e-2',Fraction(1,200)),('100%',Fraction(1))]
def organ(spec): sid,module,cls=spec for name in ('organ_stats_v1','organ_stats_v2','organ_stats_v3'): sys.modules.pop(name,None) sys.path.insert(0,str(ROOT/'root/specialists'/sid)) try: return getattr(importlib.import_module(module),cls)() finally: sys.path.pop(0)
def question(k,n,p): return f'What is the probability of exactly {k} successes in {n} trials with p = {p}?'
def mass(k,n,p): return sum((math.prod(p if bit else 1-p for bit in bits) for bits in product((0,1),repeat=n) if sum(bits)==k),Fraction())
class BinomialSupport(unittest.TestCase): def test_outside_support_is_zero_including_zero_trials_and_endpoints(self): for spec in SPECS: instance=organ(spec) for n in range(6): for k in range(n+1,n+5): for literal,p in LITERALS: with self.subTest(spec=spec,n=n,k=k,p=literal): reply=instance.answer(question(k,n,literal)) self.assertIsNotNone(reply) self.assertEqual(reply['status'],'answered') self.assertEqual(reply['kind'],'binomial') self.assertEqual(reply['value'],float(mass(k,n,p))) self.assertNotIn('^-',reply['response'])
def test_within_support_small_exact_sequence_truth_is_unchanged(self): for spec in SPECS: instance=organ(spec) for n in range(6): for k in range(n+1): for literal,p in LITERALS: with self.subTest(spec=spec,n=n,k=k,p=literal): reply=instance.answer(question(k,n,literal)) self.assertIsNotNone(reply) self.assertEqual(reply['status'],'answered') self.assertAlmostEqual(reply['value'],float(mass(k,n,p)),places=13)
def test_invalid_or_unsafe_probability_cannot_be_rescued_by_k_above_n(self): invalid=['-0.5','-0.5%','1.01','101%','1e2','1e-10000','0.'+'9'*400, '0.5%%','0.5/2','0.5e-2x','1.2.3','0.5e+'] for spec in SPECS: instance=organ(spec) for p in invalid: with self.subTest(spec=spec,p=p): reply=instance.answer(question(5,3,p)) self.assertTrue(reply is None or reply['status']!='answered')
def test_negative_fractional_and_scientific_count_tokens_are_not_digit_prefixes(self): bad=['-3','3.5','.5','3/2','3e2','3e-2','3e+','3e+2x','3%','3,5'] for spec in SPECS: instance=organ(spec) for token in bad: # Both previously masked out-of-support and in-support parses. for k,n in [(50,token),(0,token),(token,1),(token,50)]: with self.subTest(spec=spec,k=k,n=n): reply=instance.answer(question(k,n,'0.5')) self.assertTrue(reply is None or reply['status']!='answered')
def test_probability_roles_use_the_same_support_rule(self): roles=['p = 0.5%','chance of success is 0.5%','probability of success on each trial is 0.5%', 'success probability is 0.5%','with probability 0.5%'] for spec in [s for s in SPECS if s[1]!='organ_stats_v1']: instance=organ(spec) for role in roles: with self.subTest(spec=spec,role=role): reply=instance.answer(f'Probability of exactly 5 successes in 3 trials, {role}?') self.assertIsNotNone(reply) self.assertEqual(reply['status'],'answered') self.assertEqual(reply['value'],0.0)
def test_complete_signed_nonnegative_integer_counts(self): for spec in SPECS: instance=organ(spec) for k,n,wanted in [('+5','+3',0.0),('1','-0',0.0),('+0','+0',1.0)]: with self.subTest(spec=spec,k=k,n=n): reply=instance.answer(question(k,n,'1')) self.assertIsNotNone(reply) self.assertEqual(reply['status'],'answered') self.assertEqual(reply['value'],wanted)
def test_comma_and_parenthesis_delimiters_preserve_integer_atoms(self): forms=[ 'What is the probability of exactly {k}, in {n} trials with p = 0.5?', 'What is the probability of exactly {k} successes in ({n} trials) with p = 0.5?', 'What is the probability of exactly {k}, in ({n} trials) with p = 0.5?', 'What is the probability of exactly ({k}) successes in ({n}) trials with p = 0.5?', 'What is the probability of exactly (({k})), in (({n} trials)) with p = 0.5?'] for spec in SPECS: instance=organ(spec) for form in forms: for k,n in [(2,3),(5,3),(1,0)]: with self.subTest(spec=spec,form=form,k=k,n=n): reply=instance.answer(form.format(k=k,n=n)) self.assertIsNotNone(reply) self.assertEqual(reply['status'],'answered') self.assertEqual(reply['value'],float(mass(k,n,Fraction(1,2))))
def test_delimiters_do_not_hide_invalid_tokens_or_count_expressions(self): bad=['(-3)','(3.5)','(3e2)','(3e-2)','(3/2)','3,5,','(3,5)', '(2+3)','2+3','(2)*3','3/(2)','(3)/(2)','3e(2)'] for spec in SPECS: instance=organ(spec) for token in bad: for k,n in [(0,token),(token,50)]: with self.subTest(spec=spec,k=k,n=n): reply=instance.answer(question(k,n,'0.5')) self.assertTrue(reply is None or reply['status']!='answered')
if __name__=='__main__': unittest.main()tests/reader/test_canonical_plural_first.pyAdded+144
tests/statistics/test_binomial_support.pyAdded+147