In this section
- Laws render · cosmic / tools/explore/laws/laws.py lines 701–960
- Test Laws test · cosmic / tools/explore/laws/test_laws.py lines 1–261
Laws
A Python command-line tool in the explore folder of Cosmic that reads build graph, identity and sentences, using SHA-256.
rendercosmic / tools/explore/laws/laws.py · lines 701–960 of 960 (continued from section 1107) · Entry point · pattern _minutes (shared by 2 files)
- What it does
- It loads build graph, identity and sentences. Defines 34 functions or classes, including load_json, ranks, pearson, spearman, gini. Uses libraries argparse, collections, itertools, json, math. Side effects: changes the web page (DOM); reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file build_graph.json; JSON file identity.json; JSON file laws.json; JSON file sentences.json; command-line arguments. Out: JSON file.
- Downstream impact
- Used directly by 1 file: Test Laws (cosmic).
- What it achieves
- It loads JSON (`load_json`) and is built from the ranks step (`ranks`) and the pearson step (`pearson`). The Explore Code estate measured as if it obeyed physical laws (GRAVITON-64, ). It accepts `--out`, `--demo` and `--no-lines`.
- Why it matters
- Checked by Test Laws.
- Application
- cosmic · tools/explore/laws · Python CLI
- Uses
- argparse, collections, itertools, json, math, os, re, sys
- Used by
- imported by Test Laws (import)
- Produces
- load_json, ranks, pearson, spearman, gini, r4, verdict, Estate, law_gravity, law_field, law_conservation, law_entropy
- Defines here
- _title, sentences, demo_data, add, measure, public, sample_ids, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/laws/laws.py:701-960 · blob 8bd2beb55a2caaf840f1c2f2bc0486eabfeebce7 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: unknown
'analogy': 'Light from a star left it long ago (Ventusltd/law L11).',
'law': 'Every layer of the picture is as old as its cut, and must say so.',
'means': 'The graph, the identity layer and the clean manifest were computed at different times. A view '
'that mixes them shows several moments at once; each must carry its own time with its offset.',
'measure': 'Every input carries a cut time with a UTC offset; age of each layer = newest cut - its cut.',
'falsified_by': 'A layer shown without a cut, or with a bare clock time and no offset.',
'numbers': {'layers': dict(layers), 'all_stamped_with_offset': ok, 'age_minutes_behind_newest': ages,
'layers_older_than_graph': len(stale)},
'verdict': verdict(ok),
'note': 'Holds as a rule of record: all layers are stamped. It also shows the identity and clean layers are %s '
'minutes older than the graph they are drawn on; conservation (C1) is what makes that safe.'
% (max(stale.values()) if stale else 0),
'evidence': ['%s cut %s' % (n, c) for n, c in layers],
}
# ---------------------------------------------------------------------------------------------- visual + translation rules
VISUAL = {
'G1': 'Body radius = log(1 + mass) (Kuiper L5). In the layout each use edge pulls the user towards the used file '
'with a spring whose strength grows with the used file\'s mass, so users cluster around heavy bodies. '
'Brightness of a node also follows mass.',
'F1': 'Draw field lines: thin curved dashed lines from each writer to each reader of the same named data file, '
'coloured by the data item, separate from import edges. A data item with no recorded writer shows as a '
'short line coming in from the rim, labelled "no recorded writer", never as an outside source.',
'C1': 'Positions are pinned to the permanent key (Kuiper wafer law: r = sqrt(rank), angle = golden turn), so a '
'node never moves between builds; a soft spring holds every node to its key position while other laws '
'only displace it locally. Labels show the key; changing the description changes nothing visual.',
'S1': 'Near copies are drawn as faint dust around the file they copy, jittering slowly (disorder). A "distil" '
'step animates the dust collapsing into the kept file, showing the clean set-aside count.',
'I1': 'Not adopted, because the law does not hold on this estate. If it did, mass would enter the integration '
'(acceleration = force / (1 + mass)) so heavy bodies barely move when disturbed. The demo keeps the toggle, '
'labelled as not supported, to show what the claim would look like.',
'K9': 'Each node gets an in/out ring: left half lit if it takes something in, right half lit if it gives '
'something out. Leaks (in, no out) glow red so a reviewer can find dead ends.',
'FA': 'Tap a file: a pulse travels outward along the use edges to its users, each user flashing with '
'probability equal to the measured P(user changed | used changed); a second ring for users of users.',
'K1': 'A file whose description rests only on its name is drawn hollow (outline only): a candidate, not a '
'fact. Keyed bodies are filled.',
'L11': 'Each layer is drawn at a brightness set by its age: the newest cut full, older layers dimmed, with '
'its cut time printed in the corner.',
}
TRANSLATION = {
'G1': {'when': 'mass >= 5 (top ~5% of used files)',
'template': 'Used by {mass} files in {repos} repositories: one of the heaviest {pct} of files in the estate.',
'else': 'Used by {mass} file(s).' },
'F1': {'when': 'a named data file in data_contracts.in',
'template': 'Reads {item}, which {writer_title} writes.',
'else': 'Reads {item}; no file in the estate is recorded as writing it.'},
'C1': {'when': 'always (footer)',
'template': 'Key: {key}. The key stays the same when this description changes.'},
'S1': {'when': 'identity verdict near-copy-of',
'template': 'A near copy ({sim}% of lines shared) of {of_title}; read that one first.'},
'I1': {'when': 'only if I1 holds; otherwise do not use',
'template': 'Its copies keep {sim}% of its lines: a stable piece the estate copies rather than changes.'},
'K9': {'when': 'leak (takes in, gives nothing out)',
'template': 'Takes in {inputs}, but no file in the graph uses its result and it records no named output: '
'a possible dead end to review.',
'else': 'Takes in {inputs}; gives out {outputs}.'},
'FA': {'when': 'file has users and lies in a copy family',
'template': 'Across the estate\'s copies, when a used file changed its users changed too in {k} of {n} cases '
'({p}%); this file has {users} user(s) to check when it changes.'},
'K1': {'when': 'achieves_provenance == "name"',
'template': 'Described from its file name only (a candidate, not yet checked against the code).'},
'L11': {'when': 'always (footer)', 'template': 'As of {cut}.'},
}
def _title(E, i):
return E.files[i].get('title') or E.files[i]['path'].rsplit('/', 1)[-1]
def sentences(E, i, R):
"""Law sentences for file i, evidence only. R = results by id (with private indexes)."""
f = E.files[i]
out = []
m = E.mass[i]
if m > 0:
repos = len({E.files[a]['repo'] for a in E.users[i]})
if m >= R['G1']['_heavy_cut']:
out.append(('G1', 'Used by %d files in %d repositor%s: one of the heaviest 5%% of files in the estate.'
% (m, repos, 'y' if repos == 1 else 'ies')))
else:
out.append(('G1', 'Used by %d file%s.' % (m, '' if m == 1 else 's')))
prod = R['F1']['_producers']
for item in (f.get('data_contracts') or {}).get('in', []):
if not _named(item):
continue
writers = sorted(w for w in prod.get(item, ()) if w != i)
if writers:
more = ' (and %d other file%s)' % (len(writers) - 1, '' if len(writers) == 2 else 's') if len(writers) > 1 else ''
out.append(('F1', 'Reads %s, which %s%s writes.' % (item, _title(E, writers[0]), more)))
else:
out.append(('F1', 'Reads %s; no file in the estate is recorded as writing it.' % item))
break
vd = E.I.get(i, {}).get('verdict', {})
if vd.get('verdict') == 'near-copy-of' and vd.get('of_file') is not None:
out.append(('S1', 'A near copy (%d%% of lines shared) of %s; read that one first.'
% (round(100 * vd['similarity']), _title(E, vd['of_file']))))
if i in R['K9']['_leaks']:
ins = (f.get('data_contracts') or {}).get('in', [])[:2]
what = ', '.join(ins) if ins else '%d file(s) it uses' % len(E.used[i])
out.append(('K9', 'Takes in %s, but no file in the graph uses its result and it records no named output: a possible dead end to review.' % what))
if R['FA']['verdict'] == 'HOLDS' and m > 0 and R['_comp_size'][i] > 1:
p = R['FA']['numbers']['p_user_changed_given_used_changed']
n = R['FA']['numbers']
out.append(('FA', 'Across the estate\'s copies, when a used file changed its users changed too in %d of %d cases '
'(%d%%); this file has %d user%s to check when it changes.'
% (n['used_changed_user_changed'], n['used_changed_user_changed'] + n['used_changed_user_same'],
round(100 * p), m, '' if m == 1 else 's')))
if f.get('achieves_provenance') == 'name':
out.append(('K1', 'Described from its file name only (a candidate, not yet checked against the code).'))
out.append(('C1', 'Key: %s.' % E.key(i)))
out.append(('L11', 'As of %s.' % E.g['cut']))
return out
# ---------------------------------------------------------------------------------------------- demo data
def demo_data(E, R, comp, n_nodes=260):
"""A deterministic subgraph: the heaviest bodies, their users, copies and data fields."""
order = sorted(range(E.n), key=lambda i: (-E.mass[i], i))
chosen = []
seen = set()
def add(i):
if i not in seen and len(chosen) < n_nodes:
seen.add(i)
chosen.append(i)
for b in order[:40]:
add(b)
for b in order[:40]:
for a in sorted(E.users[b])[:5]:
add(a)
members = collections.defaultdict(list)
for i in range(E.n):
members[comp[i]].append(i)
for i in list(chosen):
for c in members[comp[i]][:3]:
add(c)
for fld in R['F1']['strongest_fields'][:6]:
it = fld['item']
for w in sorted(R['F1']['_producers'][it])[:3]:
add(w)
for c in sorted(R['F1']['_consumers'][it])[:4]:
add(c)
for i in sorted(R['K9']['_leaks'])[:12]:
add(i)
idx = {i: k for k, i in enumerate(chosen)}
rank = {i: r for r, i in enumerate(sorted(chosen, key=lambda i: (E.files[i]['repo'], E.files[i]['path'])))}
repos = sorted({E.files[i]['repo'] for i in chosen})
nodes = []
for i in chosen:
f = E.files[i]
dc = f.get('data_contracts') or {}
vd = E.I.get(i, {}).get('verdict', {})
nodes.append({
'id': i, 'r': repos.index(f['repo']), 'k': rank[i], 'm': E.mass[i],
't': (f.get('title') or '')[:60], 'p': f['path'][-70:],
'in': 1 if (dc.get('in') or E.used[i]) else 0, 'out': 1 if (dc.get('out') or E.users[i]) else 0,
'leak': 1 if i in R['K9']['_leaks'] else 0,
'cand': 1 if f.get('achieves_provenance') == 'name' else 0,
'of': idx.get(vd.get('of_file')) if vd.get('verdict') == 'near-copy-of' else None,
'sim': vd.get('similarity') if vd.get('verdict') == 'near-copy-of' else None,
'key': E.key(i),
})
edges = sorted({(idx[a], idx[b]) for a, b, _k in E.uses if a in idx and b in idx})
fields = []
for fld in R['F1']['strongest_fields'][:6]:
it = fld['item']
ws = [idx[w] for w in sorted(R['F1']['_producers'][it]) if w in idx]
cs = [idx[c] for c in sorted(R['F1']['_consumers'][it]) if c in idx]
if ws and cs:
fields.append({'item': it, 'w': ws, 'c': cs})
summary = {k: {'name': v['name'], 'law': v['law'], 'verdict': v['verdict']} for k, v in R.items() if not k.startswith('_')}
return {
'rules': RULES, 'cut': E.g['cut'], 'layers': R['L11']['numbers']['layers'],
'ages': R['L11']['numbers']['age_minutes_behind_newest'],
'repos': repos, 'nodes': nodes, 'edges': edges, 'fields': fields,
'p_induce': R['FA']['numbers']['p_user_changed_given_used_changed'],
'laws': summary, 'visual': VISUAL,
}
# ---------------------------------------------------------------------------------------------- run
def measure(E):
comp = _copy_components(E)
R = collections.OrderedDict()
R['G1'] = law_gravity(E)
used_sorted = sorted((x for x in E.mass if x > 0), reverse=True)
R['G1']['_heavy_cut'] = used_sorted[max(0, int(math.ceil(0.05 * len(used_sorted))) - 1)] if used_sorted else 1
R['F1'] = law_field(E)
R['C1'] = law_conservation(E)
R['S1'] = law_entropy(E)
R['I1'] = law_inertia(E, comp)
R['K9'] = law_kirchhoff(E)
R['FA'] = law_induction(E, comp)
R['K1'] = law_key(E)
R['L11'] = law_light(E)
for k in list(R):
R[k]['visual'] = VISUAL[k]
R[k]['translation'] = TRANSLATION[k]
size = collections.Counter(comp)
R['_comp_size'] = [size[c] for c in comp]
R['_comp'] = comp
return R
def public(R):
out = collections.OrderedDict()
for k, v in R.items():
if k.startswith('_'):
continue
out[k] = {kk: vv for kk, vv in v.items() if not kk.startswith('_')}
return out
def sample_ids(E, n=40):
"""Fixed sample: every (n)th file by id plus the 10 heaviest."""
step = max(1, E.n // n)
heavy = sorted(range(E.n), key=lambda i: (-E.mass[i], i))[:10]
return sorted(set(list(range(0, E.n, step))[:n] + heavy))
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
for k, v in DEFAULTS.items():
ap.add_argument('--' + k.replace('_', '-'), dest=k, default=v)
ap.add_argument('--out', default='/tmp/vk/laws')
ap.add_argument('--demo', default=os.path.join(HERE, 'demo'))
ap.add_argument('--no-lines', action='store_true')
a = ap.parse_args(argv)
paths = {k: getattr(a, k) for k in DEFAULTS}
E = Estate(paths, read_lines=not a.no_lines)
R = measure(E)
os.makedirs(a.out, exist_ok=True)
doc = {'schema': 'estate-laws-v1', 'rules': RULES, 'thresholds': THRESH, 'graph_cut': E.g['cut'],
'inputs': {k: v for k, v in paths.items()}, 'laws': public(R)}
with open(os.path.join(a.out, 'laws.json'), 'w', encoding='utf-8') as fh:
json.dump(doc, fh, indent=1, sort_keys=False, ensure_ascii=False)
fh.write('\n')
sents = {str(i): {'key': E.key(i), 'title': E.files[i].get('title', ''),
'sentences': [{'law': l, 'text': t} for l, t in sentences(E, i, R)]} for i in sample_ids(E)}
with open(os.path.join(a.out, 'sentences.json'), 'w', encoding='utf-8') as fh:
json.dump(sents, fh, indent=1, ensure_ascii=False)
fh.write('\n')
if a.demo:
os.makedirs(a.demo, exist_ok=True)
dd = demo_data(E, R, R['_comp'])
with open(os.path.join(a.demo, 'data.js'), 'w', encoding='utf-8') as fh:
fh.write('/* generated by laws.py (%s) from graph cut %s; do not edit */\n' % (RULES, E.g['cut']))
fh.write('window.LAWS_DATA = ')
json.dump(dd, fh, separators=(',', ':'), ensure_ascii=False)
fh.write(';\n')
for k, v in public(R).items():
print('%-4s %-42s %s' % (k, v['name'][:42], v['verdict']))
return 0
if __name__ == '__main__':
sys.exit(main())Test Laws
A test in the explore folder of Cosmic that checks Laws, using SHA-256. It builds fixture (`build_fixture`), sets up (`setUp`) and sets up class (`setUpClass`).
testcosmic / tools/explore/laws/test_laws.py · lines 1–261 of 261 · Entry point · pattern Synthetic (shared by 2 files)
- What it does
- It tests its inputs. Defines 31 functions or classes, including fmeta, ident, build_fixture, rj, wj. Uses libraries json, os, re, shutil, sys. Side effects: reads or writes files.
- Inputs & outputs
- Out: JSON file.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- Tests for `laws.py` (unittest, no network).
- Why it matters
- Guards the behaviour of Laws.
- Application
- cosmic · tools/explore/laws · test
- Uses
- Laws (import), json, os, re, shutil, sys, tempfile, unittest
- Used by
- none found
- Produces
- fmeta, ident, build_fixture, rj, wj, rt, Synthetic, RealEstate
- Defines here
- fmeta, ident, build_fixture, rj, wj, rt, Synthetic, setUp, tearDown, test_mass_excludes_mentions, test_gravity_concentrated, test_field_closed_share, test_conservation_holds_and_counts_words, test_conservation_breaks_on_reused_number, test_conservation_partly_when_modular_not_one_to_one, test_kirchhoff_leak, test_induction_table, test_induction_counts_unchanged_user, test_key_law_counts_name_only, test_light_ages, test_light_fails_on_bare_clock, test_sentences_grounded, test_spearman_and_gini, test_no_religious_wording, RealEstate, setUpClass, test_every_law_has_a_verdict_and_rules, test_known_results, test_deterministic, test_sentences_use_only_record_facts
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/laws/test_laws.py:1-261 · blob 8122f20db712b8b8ad117113b68ccf2d1f52a9d6 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""Tests for laws.py (unittest, no network). A tiny synthetic estate checks each law's arithmetic and its
verdict in both directions; a smoke test runs the real estate when the inputs exist and checks determinism
and that every sentence is grounded in the record.
Run: python3 -m unittest test_laws -v (from tools/explore/laws)
"""
import json
import os
import re
import shutil
import sys
import tempfile
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import laws # noqa: E402
CUT = '2026-12-05T15:00:00+00:00'
OLD = '2026-12-05T13:00:00+00:00'
def fmeta(i, repo, path, dc_in=(), dc_out=(), prov='comment', lines=10, stage='transform'):
return {'id': i, 'repo': repo, 'path': path, 'lines': lines, 'section': 1, 'title': 'File %d' % i,
'synopsis': 's', 'achieves_provenance': prov, 'stage': stage, 'canonical_status': 'production_core',
'data_contracts': {'in': list(dc_in), 'out': list(dc_out), 'crs': [], 'voltages': []}}
def ident(i, repo, path, fams, verdict='unique', of=None, sim=None):
return {'id': i, 'repo': repo, 'path': path,
'keys': {'commit': 'c' * 40, 'git_blob': 'b%039d' % i, 'sha256': 's%063d' % i,
'key': '%s@%s %s:1-10 b%039d' % (repo, 'c' * 40, path, i)},
'functions': [{'family_sha': f, 'verdict': 'copy' if f.startswith('x') else 'unique'} for f in fams],
'verdict': {'verdict': verdict, 'of_file': of, 'similarity': sim}}
def build_fixture(d, user_changes=True):
"""Eight files. 0 is heavy (used by 1..5). Two copies of a small system: 6 uses 0 and 7 uses 5.
Copy family A = {6, 7}, family B = {0, 5}; 0 and 5 differ in functions, and 6/7 differ when user_changes."""
files = [fmeta(0, 'r1', 'lib/core.js', dc_out=['JSON file a.json']),
fmeta(1, 'r1', 'app/one.js', dc_in=['JSON file a.json']),
fmeta(2, 'r1', 'app/two.js', dc_in=['JSON file missing.json']),
fmeta(3, 'r1', 'app/three.js', prov='name'),
fmeta(4, 'r2', 'x/four.js'),
fmeta(5, 'r2', 'releases/202609051921/core.js'),
fmeta(6, 'r2', 'releases/202609051921/use.js'),
fmeta(7, 'r2', 'releases/202609061921/use.js', dc_out=['web page'])]
edges = [[1, 0, 'import', ''], [2, 0, 'import', ''], [3, 0, 'import', ''], [4, 0, 'import', ''],
[5, 0, 'import', ''], [6, 0, 'import', ''], [7, 5, 'import', ''], [1, 2, 'comment-url', '']]
g = {'schema': 'explore-build-graph-v1', 'cut': CUT,
'repos': [{'repo': 'r1', 'commit': 'c' * 40, 'core': True}, {'repo': 'r2', 'commit': 'c' * 40, 'core': False}],
'files': files, 'edges': edges}
g_old = json.loads(json.dumps(g))
g_old['cut'] = OLD
g_old['files'][1]['synopsis'] = 'older words'
I = {str(f['id']): ident(f['id'], f['repo'], f['path'], ['u%d' % f['id']]) for f in files}
I['0']['functions'] = [{'family_sha': 'B0', 'verdict': 'unique'}]
I['5'] = ident(5, 'r2', files[5]['path'], ['B5', 'x1'], 'near-copy-of', 0, 0.9)
I['6']['functions'] = [{'family_sha': 'A6', 'verdict': 'unique'}]
I['7'] = ident(7, 'r2', files[7]['path'], ['A7', 'x2'] if user_changes else ['A6'], 'near-copy-of', 6, 0.95)
idn = {'schema': 'explore-identity-v1', 'graph': {'cut': OLD, 'sha256': '0' * 64},
'checks': {'files_blob_found_at_clone_head': len(files),
'modular': {'number_to_several_family_shas': 0, 'family_sha_to_several_numbers': 0}},
'counts': {'functions': 10, 'function_verdicts': {'copy': 6, 'unique': 4},
'verdicts': {'unique': 6, 'near-copy-of': 2}},
'files': I}
man = {'graph_cut': OLD, 'graph_sha256': '0' * 64,
'main_view': [{'file_id': i, 'key': 'k%d' % i} for i in range(7)],
'set_aside': [{'file_id': 7, 'evidence': ['line-jaccard 0.95']}]}
lines = '# Every unique line\n\n3 unique lines, numbered 1 to 5. text\n\n```text\n1\ta\n2\tb\n5\tc\n```\n'
paths = {}
for name, obj in (('graph', g), ('graph_old', g_old), ('identity', idn), ('manifest', man)):
p = os.path.join(d, name + '.json')
with open(p, 'w') as fh:
json.dump(obj, fh)
paths[name] = p
p = os.path.join(d, 'LINES.md')
with open(p, 'w') as fh:
fh.write(lines)
paths['lines'] = p
paths['wafer'] = os.path.join(d, 'none.tsv')
paths['repos'] = os.path.join(d, 'none.tsv')
return paths
def rj(p):
with open(p, encoding='utf-8') as fh:
return json.load(fh)
def wj(p, obj):
with open(p, 'w', encoding='utf-8') as fh:
json.dump(obj, fh)
def rt(p):
with open(p, encoding='utf-8') as fh:
return fh.read()
class Synthetic(unittest.TestCase):
def setUp(self):
self.d = tempfile.mkdtemp()
self.E = laws.Estate(build_fixture(self.d))
self.R = laws.measure(self.E)
def tearDown(self):
shutil.rmtree(self.d)
def test_mass_excludes_mentions(self):
self.assertEqual(self.E.mass[0], 6)
self.assertEqual(self.E.mass[2], 0) # only a comment-url points at file 2
def test_gravity_concentrated(self):
g = self.R['G1']
self.assertEqual(g['numbers']['use_edges'], 7)
self.assertEqual(g['numbers']['top5pct_files'], 1)
self.assertAlmostEqual(g['numbers']['top5pct_share'], 6 / 7, places=4)
self.assertEqual(g['verdict'], 'HOLDS')
def test_field_closed_share(self):
f = self.R['F1']['numbers']
self.assertEqual(f['named_items_read'], 2)
self.assertEqual(f['closed_items'], 1)
self.assertEqual(self.R['F1']['verdict'], 'HOLDS') # 1/2 = 50% meets the threshold
self.assertEqual(f['pairs_also_joined_by_a_code_edge'], 1) # 1 imports 0
def test_conservation_holds_and_counts_words(self):
c = self.R['C1']
self.assertEqual(c['verdict'], 'HOLDS')
self.assertEqual(c['numbers']['two_cuts']['synopsis_kept'], 7)
self.assertEqual(c['numbers']['lines_md']['rows'], 3)
def test_conservation_breaks_on_reused_number(self):
with open(self.E.paths['lines'], 'a') as fh:
fh.write('5\tdup\n')
R = laws.measure(laws.Estate(self.E.paths))
self.assertEqual(R['C1']['verdict'], 'DOES NOT HOLD')
def test_conservation_partly_when_modular_not_one_to_one(self):
idn = rj(self.E.paths['identity'])
idn['checks']['modular']['number_to_several_family_shas'] = 3
wj(self.E.paths['identity'], idn)
R = laws.measure(laws.Estate(self.E.paths))
self.assertEqual(R['C1']['verdict'], 'PARTLY')
self.assertIn('3 numbers', R['C1']['note'])
def test_kirchhoff_leak(self):
k = self.R['K9']
# files taking in: 1..7 (use edges or inputs); leaks are those with no user and no output
self.assertIn(1, k['_leaks'])
self.assertNotIn(5, k['_leaks']) # used by 7
self.assertNotIn(7, k['_leaks']) # gives out a web page
self.assertEqual(k['verdict'], 'DOES NOT HOLD')
def test_induction_table(self):
n = self.R['FA']['numbers']
self.assertEqual(n['replicated_pairs'], 1)
self.assertEqual(n['used_changed_user_changed'], 1)
def test_induction_counts_unchanged_user(self):
d = tempfile.mkdtemp()
try:
R = laws.measure(laws.Estate(build_fixture(d, user_changes=False)))
self.assertEqual(R['FA']['numbers']['used_changed_user_same'], 1)
self.assertEqual(R['FA']['verdict'], 'DOES NOT HOLD')
finally:
shutil.rmtree(d)
def test_key_law_counts_name_only(self):
k = self.R['K1']
self.assertEqual(k['numbers']['descriptions_from_name_only'], 1)
self.assertEqual(k['verdict'], 'PARTLY')
def test_light_ages(self):
l = self.R['L11']['numbers']
self.assertTrue(l['all_stamped_with_offset'])
self.assertEqual(l['age_minutes_behind_newest']['identity (graph it read)'], 120.0)
def test_light_fails_on_bare_clock(self):
g = rj(self.E.paths['graph'])
g['cut'] = '2026-12-05T15:00:00'
wj(self.E.paths['graph'], g)
R = laws.measure(laws.Estate(self.E.paths))
self.assertEqual(R['L11']['verdict'], 'DOES NOT HOLD')
def test_sentences_grounded(self):
s = dict((l, t) for l, t in laws.sentences(self.E, 0, self.R))
self.assertTrue(s['G1'].startswith('Used by 6 files in 2 repositories'))
s2 = dict(laws.sentences(self.E, 2, self.R))
self.assertEqual(s2['F1'], 'Reads JSON file missing.json; no file in the estate is recorded as writing it.')
s1 = dict(laws.sentences(self.E, 1, self.R))
self.assertIn('which File 0 writes', s1['F1'])
s7 = dict(laws.sentences(self.E, 7, self.R))
self.assertIn('near copy (95% of lines shared) of File 6', s7['S1'])
self.assertIn('Key: r2@', s7['C1'])
self.assertEqual(s7['L11'], 'As of %s.' % CUT)
def test_spearman_and_gini(self):
self.assertEqual(laws.spearman([1, 2, 3, 4], [10, 20, 30, 40]), 1.0)
self.assertEqual(laws.spearman([1, 2, 3, 4], [4, 3, 2, 1]), -1.0)
self.assertIsNone(laws.spearman([1, 1, 1], [1, 2, 3]))
self.assertEqual(laws.gini([1, 1, 1, 1]), 0.0)
self.assertGreater(laws.gini([0, 0, 0, 10]), 0.7)
def test_no_religious_wording(self):
words = re.compile(r'\b(god|gods|divine|holy|sacred|heaven|soul|miracle|prayer|scripture|bible|church)\b', re.I)
for p in ('laws.py', 'LAWS.md', os.path.join('demo', 'index.html')):
fp = os.path.join(HERE, p)
if os.path.exists(fp):
self.assertIsNone(words.search(rt(fp)), p)
REAL = all(os.path.exists(laws.DEFAULTS[k]) for k in ('graph', 'identity', 'manifest'))
@unittest.skipUnless(REAL, 'real estate inputs not present')
class RealEstate(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.E = laws.Estate(dict(laws.DEFAULTS), read_lines=False)
cls.R = laws.measure(cls.E)
def test_every_law_has_a_verdict_and_rules(self):
for k, v in laws.public(self.R).items():
self.assertIn(v['verdict'], ('HOLDS', 'PARTLY', 'DOES NOT HOLD'), k)
self.assertTrue(v['visual'] and v['translation'] and v['falsified_by'], k)
def test_known_results(self):
self.assertEqual(self.R['C1']['numbers']['identity']['identity_blob_found_at_clone_head'], self.E.n)
self.assertEqual(self.R['K1']['numbers']['files_keyed'], self.E.n)
self.assertEqual(self.R['FA']['verdict'], 'HOLDS')
self.assertEqual(self.R['I1']['verdict'], 'DOES NOT HOLD')
def test_deterministic(self):
R2 = laws.measure(laws.Estate(dict(laws.DEFAULTS), read_lines=False))
a = json.dumps(laws.public(self.R), sort_keys=True, default=list)
b = json.dumps(laws.public(R2), sort_keys=True, default=list)
self.assertEqual(a, b)
def test_sentences_use_only_record_facts(self):
for i in laws.sample_ids(self.E):
for law, text in laws.sentences(self.E, i, self.R):
if law == 'G1':
self.assertIn(str(self.E.mass[i]), text)
if law == 'C1':
self.assertIn(self.E.key(i), text)
self.assertNotIn('comes from outside', text)
def test_demo_data_offline(self):
dd = laws.demo_data(self.E, self.R, self.R['_comp'])
self.assertLessEqual(len(dd['nodes']), 260)
for e in dd['edges']:
self.assertTrue(0 <= e[0] < len(dd['nodes']) and 0 <= e[1] < len(dd['nodes']))
html = rt(os.path.join(HERE, 'demo', 'index.html'))
self.assertNotRegex(html, r'(src|href)=["\']https?://')
if __name__ == '__main__':
unittest.main()