In this section
- Show storage · cosmic / tools/explore/presentations/show.py lines 1–672
Show
A Python command-line tool in the presentations folder of Cosmic that reads clean, clarity, periodic and receipts, using Louvain. It loads JSON (`load_json`), parses key (`parse_key`) and finds input (`find_input`).
storagecosmic / tools/explore/presentations/show.py · lines 1–672 of 672 · Entry point · pattern lower (shared by 2 files)
- What it does
- It loads clean, clarity, periodic and receipts. Defines 39 functions or classes, including warn, load_json, n, pct, first_sentence. Uses libraries argparse, html, json, os, re. Side effects: reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file clean-manifest.json; JSON file clarity.json; JSON file periodic.json; JSON file receipts.json; JSON file laws.json; JSON file index.json; JSON file places.json; JSON file build_graph.json. Out: JSON file.
- Downstream impact
- Used directly by 2 files: Extras (cosmic); Test Show (cosmic). Reached from 3 other entry points, including Ship (cosmic); Test Extras (cosmic); Test Ship (cosmic).
- What it achieves
- Explore Code story mode: guided, swipeable presentations of the most promising experiments. It accepts `--site`, `--graph` and `--out`.
- Why it matters
- Run by Extras. Checked by Test Show.
- Application
- cosmic · tools/explore/presentations · Python CLI
- Uses
- argparse, html, json, os, re, shutil, sys, collections
- Used by
- run by Extras (script call), imported by Test Show (import)
- Produces
- warn, load_json, n, pct, first_sentence, lower1, slug, parse_key, Graph, Ctx, card, data_key
- Defines here
- warn, load_json, n, pct, first_sentence, lower1, slug, parse_key, Graph, __init__, file, resolve, key, href, ev, ev_key, role, Ctx, __init__, exists, deeper, card, data_key, story_engines, dominant, story_clean, story_communities, hub, story_periodic, sym
- 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/presentations/show.py:1-672 · blob b7b25e914d7c57c5fb94d7597bcf404cd03099b6 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""Explore Code story mode: guided, swipeable presentations of the most promising experiments.
python tools/explore/presentations/show.py --site <explore-code> [--graph G] [--out <explore-code>/show]
[--clean manifest.json] [--clarity clarity.json] [--lab LAB_DIR] [--periodic periodic.json]
[--furnace receipts.json] [--laws laws.json] [--seethrough index.json] [--pilot places.json]
[--about ABOUT_DIR] [--only engines,clean] [--strict]
Writes into --out (default <site>/show/, i.e. explore-code/show/):
index.html the one shared player page (story list + swipeable cards) with a <noscript> plain-text copy
show.css, show.js the player (no CDN, site palette, prefers-reduced-motion respected)
stories/<id>.json one small story per experiment (schema explore-show-story-v1): cards of one picture spec,
one or two plain sentences, evidence keys and one "go deeper" link
stories.json explore-show-index-v1: the list of stories the player offers
extra.json hub card text for extras.py (title, description, entry)
Massless (owner rule "be like a photon without mass"): a story carries counts, labels and KEYS
(`repo@commit path`, schema + field names), never code text; each key links to the real section page and every
card links into the real page that holds the bulk data (section pages, visualiser, Clarity, Kuiper, chess,
periodic table, furnace, laws demo, Pilot), which stream it from the site's own JSON/parquet/DuckDB files.
Inputs are found from the flag, else inside --site (clarity/clarity.json, lab/communities.json, ...). A missing
or unreadable input skips that story with a warning (GitHub "::warning::" under Actions); the run still succeeds
if at least one story is written. A "go deeper" link points only at a page that exists in --site at build time,
else at the next candidate, else the site home.
"""
import argparse
import html
import json
import os
import re
import shutil
import sys
from collections import Counter
GENERATOR_VERSION = 'show-1'
STORY_SCHEMA = 'explore-show-story-v1'
INDEX_SCHEMA = 'explore-show-index-v1'
HERE = os.path.dirname(os.path.abspath(__file__))
TEMPLATE = os.path.join(HERE, 'template')
# site palette (explore.css / role colours)
CYAN, BLUE, AMBER, GREEN, RED, YELLOW, MUTED, GREY = ('#00ffff', '#66ccff', '#ffae00', '#00ff88', '#ff6666',
'#ffd24a', '#a6adbb', '#4c5a65')
# in-site places of each input, tried in order when its flag is not given
SITE_INPUTS = {
'clean': ['clean/manifest.json', 'data/clean-manifest.json', 'clean-manifest.json'],
'clarity': ['clarity/clarity.json'],
'lab': ['lab'],
'periodic': ['periodic/periodic.json'],
'furnace': ['periodic/furnace/receipts.json', 'furnace/receipts.json'],
'laws': ['laws/laws.json'],
'seethrough': ['seethrough/index.json'],
'pilot': ['pilot/places.json'],
}
ORDER = ['engines', 'communities', 'clean', 'periodic', 'laws', 'seethrough']
def warn(msg):
print('show: warning: ' + msg, file=sys.stderr, flush=True)
if os.environ.get('GITHUB_ACTIONS'):
print('::warning::show: ' + msg.replace('\n', ' '), flush=True)
def load_json(path):
with open(path, encoding='utf-8') as fh:
return json.load(fh)
def n(x):
return '{:,}'.format(int(x))
def pct(a, b):
return int(round(100.0 * a / b)) if b else 0
def first_sentence(t, cap=200):
t = re.sub(r'\s+', ' ', (t or '').strip())
m = re.match(r'(.+?[.!?])(\s|$)', t)
t = m.group(1) if m else t
return t if len(t) <= cap else t[:cap - 1].rstrip(' ,;') + '…'
def lower1(t):
return t[:1].lower() + t[1:]
def slug(s):
return re.sub(r'[^a-z0-9]+', '-', str(s).lower()).strip('-') or 'x'
KEY_RE = re.compile(r'^([\w.\-]+)@([0-9a-f]{6,40})[: ](\S+?)(?::\d+(?:-\d+)?)?(?:\s|$)')
def parse_key(k):
"""'repo@commit path:1-9 blob' or 'repo@commit:path' -> (repo, path); None if it is not a file key."""
m = KEY_RE.match(k or '')
return (m.group(1), m.group(3)) if m else None
class Graph:
"""build_graph.json plus the lookups the stories need (file by id or by repo/path, links, keys)."""
def __init__(self, g):
self.g = g
self.files = g.get('files') or []
self.repos = {r['repo']: r for r in g.get('repos') or [] if r.get('repo')}
self.roles = {r['id']: r for r in g.get('roles') or []}
self.by_path = {(f.get('repo'), f.get('path')): f for f in self.files}
self.cut = g.get('cut', '')
self.sec_url = {s.get('section'): s.get('url') for s in g.get('sections') or []}
def file(self, fid):
return self.files[fid] if isinstance(fid, int) and 0 <= fid < len(self.files) else None
def resolve(self, key):
rp = parse_key(key)
return self.by_path.get(rp) if rp else None
def key(self, f):
r = self.repos.get(f['repo'], {})
return '%s@%s %s' % (f['repo'], r.get('commit', '?'), f['path'])
def href(self, f):
sec = f.get('section')
if not sec:
return None
url = self.sec_url.get(sec) or 's/%04d.html' % sec
return '../%s#f%s' % (url, f.get('block', 1)) if f.get('block') else '../' + url
def ev(self, f):
return {'k': self.key(f), 'href': self.href(f)}
def ev_key(self, key):
f = self.resolve(key)
return {'k': key, 'href': self.href(f) if f else None}
def role(self, rid):
r = self.roles.get(rid) or {}
return r.get('title', rid or 'other'), r.get('colour', GREY)
class Ctx:
def __init__(self, site, graph):
self.site, self.G = site, graph
def exists(self, href):
p = href.split('#')[0].split('?')[0]
if p.startswith('../'):
p = p[3:]
return os.path.exists(os.path.join(self.site, p))
def deeper(self, *cands):
"""First (href, label) whose page exists in the site, else the site home."""
for href, label in cands:
if href and self.exists(href):
return {'href': href, 'label': label}
return {'href': '../index.html', 'label': 'Open Explore Code'}
def card(pic, say, keys, deeper, alt):
say = [s for s in say if s][:2]
return {'pic': pic, 'say': say, 'keys': [k for k in keys if k and k.get('k')][:6], 'deeper': deeper, 'alt': alt}
def data_key(schema, field, cut=''):
return {'k': '%s %s%s' % (schema, field, (' @ ' + cut) if cut else ''), 'href': None}
# ------------------------------------------------------------------------------------------------ stories
def story_engines(cx, about_dir=None):
G = cx.G
core = [r for r in G.g.get('repos') or [] if r.get('core')]
if not core:
raise ValueError('build_graph.json marks no core repositories')
per = {r['repo']: [f for f in G.files if f.get('repo') == r['repo']] for r in core}
core.sort(key=lambda r: -len(per[r['repo']]))
total = sum(len(v) for v in per.values())
names = [r['repo'] for r in core]
def dominant(fs):
c = Counter(f.get('role') or 'other' for f in fs)
return c.most_common(1)[0] if c else ('other', 0)
bars = [{'l': r, 'v': len(per[r]), 'c': G.role(dominant(per[r])[0])[1]} for r in names]
cards = [card({'type': 'bars', 'items': bars, 'unit': 'files'},
['GlobalGrid2050 is built on %d core engines: %s.' % (len(names), ', '.join(names)),
'Together they hold %s of the estate\'s %s code files.' % (n(total), n(len(G.files)))],
[{'k': '%s@%s' % (r['repo'], r.get('commit', '?')), 'href': '../repos/%s.html' % slug(r['repo'])}
for r in core],
cx.deeper(('../index.html', 'See the core engines on the home page')),
'Bar chart of files per core engine: ' + ', '.join('%s %d' % (b['l'], b['v']) for b in bars))]
for r in core:
fs = per[r['repo']]
role, cnt = dominant(fs)
title, colour = G.role(role)
desc, prov = None, None
if about_dir:
p = os.path.join(about_dir, r['repo'], 'ABOUT.md')
if os.path.isfile(p):
body = re.sub(r'^#.*$', '', open(p, encoding='utf-8').read(), flags=re.M)
desc, prov = first_sentence(body), 'draft descriptor (ABOUT.md), awaiting owner approval'
if not desc:
desc = first_sentence(r.get('descriptor') or r.get('readme_summary') or '')
prov = 'descriptor (%s)' % (r.get('descriptor_provenance') or 'README')
hub = max(fs, key=lambda f: (len(f.get('dependents') or []) if isinstance(f.get('dependents'), list)
else (f.get('dependents') or 0), -f['id']), default=None)
sections = len({f.get('section') for f in fs if f.get('section')})
cards.append(card(
{'type': 'number', 'v': len(fs), 'l': 'files', 'c': colour,
'sub': '%d%% %s' % (pct(cnt, len(fs)), title)},
[desc or '%s is one of the core engines.' % r['repo'],
'Its %s files sit in %s section pages; the biggest share (%d%%) is %s.'
% (n(len(fs)), n(sections), pct(cnt, len(fs)), lower1(title.split(' (')[0]))],
[{'k': '%s@%s README (%s)' % (r['repo'], r.get('commit', '?'), prov), 'href': None}]
+ ([G.ev(hub)] if hub else []),
cx.deeper(('../repos/%s.html' % slug(r['repo']), 'Open %s' % r['repo']),
('../kuiper/%s.html' % slug(r['repo']), 'See %s in Kuiper' % r['repo'])),
'%s: %d files, %d%% %s' % (r['repo'], len(fs), pct(cnt, len(fs)), title)))
for j in G.g.get('journeys') or []:
steps = j.get('steps') or []
found = [s for s in steps if s.get('found')]
keyfiles = [G.file(i) for s in found[:3] for i in (s.get('key_files') or [])[:1]]
t = j.get('title', '')
short = t.split(':', 1)[1].strip() if ':' in t else t
cards.append(card(
{'type': 'steps', 'items': [s.get('label', '?') for s in steps],
'done': [bool(s.get('found')) for s in steps]},
['%s: %s.' % (t.split(':')[0], short),
'It passes through %s; %d of %d steps were found in the code.'
% (', '.join(s.get('label', '?') for s in steps), len(found), len(steps))],
[G.ev(f) for f in keyfiles if f],
cx.deeper(('../' + j['url'], 'Follow %s' % t.split(':')[0]) if j.get('url') else (None, '')),
'Journey steps: ' + ' then '.join(s.get('label', '?') for s in steps)))
return {'id': 'engines', 'title': 'What GlobalGrid2050 builds',
'blurb': 'Six core engines and the journeys that run through them.', 'cards': cards,
'sources': [{'name': 'build_graph.json', 'schema': G.g.get('schema'), 'cut': G.cut}]}
CLEAN_TITLES = {'near-copy-of': 'Near copy of a file that stays', 'noise-generated': 'Written by a tool',
'unit-duplicate-of': 'Made of code repeated elsewhere'}
def story_clean(cx, man, clarity=None):
G = cx.G
if not man or man.get('schema') != 'clean-manifest-v1':
raise ValueError('clean manifest missing or not clean-manifest-v1')
kept, aside = len(man.get('main_view') or []), len(man.get('set_aside') or [])
total = kept + aside
cut = man.get('graph_cut', '')
summ = man.get('summary', '')
cards = [card(
{'type': 'waffle', 'total': total, 'parts': [{'l': 'Kept in the cleaned view', 'v': kept, 'c': CYAN},
{'l': 'Set aside, with a reason', 'v': aside, 'c': AMBER}]},
['Of %s files, %s stay in the cleaned view and %s are set aside.' % (n(total), n(kept), n(aside)),
'Nothing was deleted: every set-aside file keeps its own page and its reason.'
if 'Nothing was deleted' in summ else ''],
[data_key('clean-manifest-v1', 'main_view + set_aside', cut)],
cx.deeper(('../set-aside.html', 'See what was set aside, and why'),
('../clarity/index.html', 'Open Clarity')),
'Grid of 100 squares: %d%% kept, %d%% set aside' % (pct(kept, total), pct(aside, total)))]
cats = (man.get('counts') or {}).get('by_category') or {}
if cats:
items = [{'l': CLEAN_TITLES.get(c, c), 'v': v, 'c': [AMBER, RED, YELLOW][i % 3]}
for i, (c, v) in enumerate(sorted(cats.items(), key=lambda kv: -kv[1]))]
top = max(man['set_aside'], key=lambda r: (r.get('category') == 'near-copy-of', r.get('confidence', 0)))
cards.append(card(
{'type': 'bars', 'items': items, 'unit': 'files'},
['Most set-aside files (%s) are a near copy of a file that stays.' % n(cats.get('near-copy-of', 0))
if cats.get('near-copy-of') else 'Each set-aside file has a measured reason.',
'For example: ' + first_sentence(top.get('reason', ''), 150) if top.get('reason') else ''],
[G.ev_key(top.get('key')), G.ev_key(top.get('target'))],
cx.deeper(('../set-aside.html', 'Read every reason'), ('../visual/index.html', 'Open the visualiser')),
'Bar chart of set-aside reasons: ' + ', '.join('%s %d' % (i['l'], i['v']) for i in items)))
byrepo = (man.get('counts') or {}).get('by_repo') or {}
if byrepo:
worst = max(byrepo.items(), key=lambda kv: (kv[1].get('set_aside', 0), kv[0]))
rname, rc = worst
rt = rc.get('set_aside', 0) + rc.get('main_view', 0)
cards.append(card(
{'type': 'number', 'v': rc.get('set_aside', 0), 'l': 'set aside in ' + rname, 'c': AMBER,
'sub': 'of %s files' % n(rt)},
['%s has the most set aside: %s of its %s files.' % (rname, n(rc.get('set_aside', 0)), n(rt)),
'%d repositories have nothing set aside at all.' % sum(1 for v in byrepo.values()
if not v.get('set_aside'))],
[data_key('clean-manifest-v1', 'counts.by_repo.' + rname, cut)],
cx.deeper(('../set-aside.html', 'See the set-aside list'), ('../repos/%s.html' % slug(rname), 'Open ' + rname)),
'%s: %d of %d files set aside' % (rname, rc.get('set_aside', 0), rt)))
if clarity and clarity.get('counts'):
cc, tt = clarity['counts'], clarity.get('titles') or {}
order = clarity.get('categories') or list(cc)
col = {'core': CYAN, 'copy': AMBER, 'via': YELLOW, 'unreached': GREY}
items = [{'l': tt.get(c, c), 'v': cc.get(c, 0), 'c': col.get(c, MUTED)} for c in order]
ct = sum(cc.values())
cards.append(card(
{'type': 'bars', 'items': items, 'unit': 'files'},
['Clarity sorts every file into %d groups: %s.' % (len(order), ', '.join(i['l'].lower() for i in items)),
'%s of %s files (%d%%) are unique and in use.' % (n(cc.get('core', 0)), n(ct), pct(cc.get('core', 0), ct))
if 'core' in cc else ''],
[data_key(clarity.get('schema', 'clarity'), 'counts', clarity.get('cut', ''))],
cx.deeper(('../clarity/index.html', 'Open Clarity'), ('../visual/index.html#colour=clarity', 'Colour the visualiser by Clarity group')),
'Bar chart of Clarity groups: ' + ', '.join('%s %d' % (i['l'], i['v']) for i in items)))
return {'id': 'clean', 'title': 'What is real',
'blurb': 'Which files are the real working code, and which are copies or tool output.', 'cards': cards,
'sources': [{'name': 'clean manifest', 'schema': man.get('schema'), 'cut': cut}]
+ ([{'name': 'clarity.json', 'schema': clarity.get('schema'), 'cut': clarity.get('cut')}] if clarity else [])}
def story_communities(cx, lab_dir):
G = cx.G
ov = load_json(os.path.join(lab_dir, 'communities.json'))
leg = ov.get('legend') or {}
cols, rows = leg.get('c') or [], leg.get('rows') or []
if not rows:
raise ValueError('communities.json has no legend rows')
R = [dict(zip(cols, r)) for r in rows]
met = {}
mp = os.path.join(lab_dir, 'communities.metrics.json')
if os.path.isfile(mp):
met = load_json(mp).get('metrics') or {}
keys = {}
kp = os.path.join(lab_dir, 'keys.json')
if os.path.isfile(kp):
kk = load_json(kp).get('k') or []
keys = {i: k for i, k in enumerate(kk)}
same_cut = ov.get('cut') == G.cut
def hub(r):
fid = r.get('hub_file')
if fid is None:
return None, None
if same_cut:
f = G.file(fid)
return f, (G.ev(f) if f else None)
k = keys.get(fid)
f = G.resolve(k) if k else None
return f, ({'k': k, 'href': G.href(f) if f else None} if k else None)
cut = ov.get('cut', '')
mod = met.get('modularity') or {}
ncomm = met.get('louvain_communities') or len(R)
cards = []
if mod.get('louvain') is not None and mod.get('repo_partition') is not None:
items = [{'l': 'Communities (links only)', 'v': mod['louvain'], 'c': CYAN},
{'l': 'Grouping by repository', 'v': mod['repo_partition'], 'c': GREY}]
if mod.get('topic_partition') is not None:
items.append({'l': 'Grouping by topic', 'v': mod['topic_partition'], 'c': GREY})
cards.append(card(
{'type': 'bars', 'items': items, 'unit': 'score 0 to 1', 'max': 1},
['The lab grouped files only by which files use which, and found %s communities.' % n(ncomm),
'These groups fit the real links far better than grouping by repository (%.2f against %.2f on a 0 to 1 score).'
% (mod['louvain'], mod['repo_partition'])],
[data_key('explore-lab-overlay-v1', 'communities metrics.modularity', cut)],
cx.deeper(('../lab/index.html', 'Open the lab'), ('../visual/index.html#colour=community', 'Colour the visualiser by community')),
'Bar chart of fit scores: ' + ', '.join('%s %.2f' % (i['l'], i['v']) for i in items)))
top = sorted(R, key=lambda r: (-r.get('size', 0), r.get('id', 0)))[:5]
t0 = top[0]
f0, e0 = hub(t0)
cards.append(card(
{'type': 'bars', 'items': [{'l': '"%s"' % r.get('label'), 'v': r.get('size', 0),
'c': CYAN if r.get('repos', 1) > 1 else GREY} for r in top], 'unit': 'files'},
['The largest community, "%s", holds %s files across %d repositories.'
% (t0.get('label'), n(t0.get('size', 0)), t0.get('repos', 1)),
'Each name is made from the three words most typical of its files.'],
[e0] + [data_key('explore-lab-overlay-v1', 'communities legend', cut)],
cx.deeper(('../visual/index.html#colour=community' + ('&file=%d' % f0['id'] if f0 else ''),
'See this community in the visualiser'), ('../lab/index.html', 'Open the lab')),
'Bar chart of the five largest communities: ' + ', '.join('%s %d' % (r.get('label'), r.get('size', 0)) for r in top)))
wide = max(R, key=lambda r: (r.get('repos', 0), r.get('size', 0)))
fw, ew = hub(wide)
cards.append(card(
{'type': 'number', 'v': wide.get('repos', 0), 'l': 'repositories in one community', 'c': CYAN,
'sub': '"%s", %s files' % (wide.get('label'), n(wide.get('size', 0)))},
['"%s" spans %d repositories: a working set that neither repositories nor topics show.'
% (wide.get('label'), wide.get('repos', 0)),
'Its hub is %s.' % ((fw or {}).get('title') or 'one file') if ew else ''],
[ew],
cx.deeper(('../visual/index.html#colour=community' + ('&file=%d' % fw['id'] if fw else ''), 'Fly to its hub'),
('../lab/index.html', 'Open the lab')),
'Community "%s" spans %d repositories' % (wide.get('label'), wide.get('repos', 0))))
cards.append(card(
{'type': 'tiles', 'items': [{'s': str(r.get('size', 0)), 'n': '%d repos' % r.get('repos', 1), 'l': r.get('label'), 'c': c}
for r, c in zip(top, [CYAN, BLUE, GREEN, AMBER, YELLOW])]},
['In Code chess, the 32 largest and most connected communities become the pieces.',
'The most central community is the king; the next most central is the queen.'],
[data_key('explore-chess-board-v1', 'pieces[].community', ''),
data_key('explore-lab-overlay-v1', 'communities legend', cut)],
cx.deeper(('../chess/index.html', 'Play Code chess'), ('../lab/index.html', 'Open the lab'),
('../visual/index.html#colour=community', 'Colour the visualiser by community')),
'Five tiles, one per large community, with its size in files: '
+ ', '.join('%s %d' % (r.get('label'), r.get('size', 0)) for r in top)))
return {'id': 'communities', 'title': 'Code communities',
'blurb': 'The lab\'s best finding: files that work together, across repositories.', 'cards': cards,
'sources': [{'name': 'lab communities', 'schema': ov.get('schema'), 'cut': cut}]}
def story_periodic(cx, per, furn=None):
G = cx.G
els = per.get('elements') or []
if not els:
raise ValueError('periodic.json has no elements')
cnt = per.get('counts') or {}
groups = {g['id']: g for g in ((per.get('axes') or {}).get('groups') or [])}
cut = per.get('cut', '')
def sym(e):
return (e.get('analogue') or {}).get('symbol') or e.get('symbol') or (e.get('proposed_symbol') or '?')
def page(e):
return '../periodic/%s.html' % e['symbol'] if e.get('symbol') else '../periodic/index.html'
def ev(e):
k = (e.get('evidence') or [None])[0]
return G.ev_key(k) if k else data_key(per.get('schema', ''), 'elements[%s]' % e.get('key'), cut)
big = sorted(els, key=lambda e: (-(e.get('file_count') or 0), e.get('key', '')))[:6]
cards = [card(
{'type': 'tiles', 'items': [{'s': sym(e), 'n': e.get('file_count', 0), 'l': first_sentence(e.get('title', ''), 40).split(' (')[0],
'c': (groups.get(e.get('group')) or {}).get('colour', MUTED)} for e in big]},
['The estate\'s %s files were sorted into %s elements, like a chemistry table for code.'
% (n(cnt.get('files') or len(G.files)), n(cnt.get('elements') or len(els))),
'These six elements hold the most files; each symbol is a playful chemical lens, never a replacement for the name.'],
[ev(e) for e in big[:3]] + [data_key(per.get('schema', ''), 'counts', cut)],
cx.deeper(('../periodic/index.html', 'Open the periodic table')),
'Six element tiles: ' + ', '.join('%s %s (%d files)' % (sym(e), e.get('title', ''), e.get('file_count', 0)) for e in big))]
h = next((e for e in els if (e.get('analogue') or {}).get('rule') == 'hydrogen'), None)
if h:
cards.append(card(
{'type': 'tiles', 'items': [{'s': 'H', 'n': h.get('tiny_helpers', 0), 'l': h.get('title', ''), 'c': CYAN}]},
['Hydrogen is "%s": it holds the most tiny helpers (%s functions of five lines or fewer).'
% (h.get('title'), n(h.get('tiny_helpers', 0))),
'Like hydrogen, these small parts are the commonest building block.'],
[ev(h)],
cx.deeper((page(h), 'Open this element'), ('../periodic/index.html', 'Open the periodic table')),
'Hydrogen tile for %s' % h.get('title')))
uns = [e for e in els if e.get('state') == 'UNSETTLED']
if uns:
u0 = max(uns, key=lambda e: (len(e.get('competing_values') or []), e.get('key', '')))
cards.append(card(
{'type': 'tiles', 'items': [{'s': sym(e), 'n': len(e.get('competing_values') or []), 'l': e.get('title', ''), 'c': RED}
for e in sorted(uns, key=lambda e: -len(e.get('competing_values') or []))[:6]]},
['%d elements are unsettled: the code writes them with different values in different places.' % len(uns),
'"%s" has %d competing values, so it sits with the restless halogens.'
% (u0.get('title'), len(u0.get('competing_values') or []))],
[ev(u0)],
cx.deeper((page(u0), 'Open this element'), ('../periodic/index.html', 'Open the periodic table')),
'Tiles for unsettled elements, numbered by competing values'))
if furn and furn.get('elements'):
fc = furn.get('counts') or {}
col = {'agree': GREEN, 'annihilate': RED, 'not yet built': GREY}
cells = [{'r': e.get('row'), 'c': e.get('col'), 's': e.get('symbol'),
'k': col.get(e.get('status'), AMBER)} for e in furn['elements'] if e.get('row') and e.get('col')]
stat = Counter(e.get('status') for e in furn['elements'])
cards.append(card(
{'type': 'ptable', 'cells': cells,
'legend': [{'l': s, 'v': v, 'c': col.get(s, AMBER)} for s, v in sorted(stat.items())]},
['The furnace runs one small code experiment for each of the %d real elements, twice, written by two agents.'
% fc.get('elements', len(furn['elements'])),
'So far: %d agree, %d disagree, %d not yet built (%d first versions, %d second versions written).'
% (fc.get('agree', 0), fc.get('annihilate', 0), fc.get('not_yet_built', 0),
fc.get('electron_files', 0), fc.get('positron_files', 0))],
[data_key(furn.get('schema', ''), 'counts', furn.get('graph_cut', ''))],
cx.deeper(('../periodic/furnace/index.html', 'Open the furnace gallery'), ('../periodic/index.html', 'Open the periodic table')),
'Periodic table of 118 experiments coloured by status: ' + ', '.join('%s %d' % kv for kv in sorted(stat.items()))))
return {'id': 'periodic', 'title': 'The periodic table of the estate',
'blurb': 'Every file sorted into elements, and a furnace of 118 experiments.', 'cards': cards,
'sources': [{'name': 'periodic.json', 'schema': per.get('schema'), 'cut': cut}]
+ ([{'name': 'furnace receipts', 'schema': furn.get('schema'), 'cut': furn.get('graph_cut')}] if furn else [])}
def story_laws(cx, laws):
G = cx.G
L = laws.get('laws') or {}
L = list(L.values()) if isinstance(L, dict) else list(L)
if not L:
raise ValueError('laws.json has no laws')
cut = laws.get('graph_cut', '')
vc = {'HOLDS': GREEN, 'PARTLY': AMBER, 'DOES NOT HOLD': RED}
tally = Counter(l.get('verdict') for l in L)
deeper = lambda: cx.deeper(('../laws/index.html', 'Open the laws demo'), ('../laws/demo/index.html', 'Open the laws demo'),
('../visual/index.html#colour=laws', 'Colour the visualiser by law'))
cards = [card(
{'type': 'bars', 'items': [{'l': v.title(), 'v': tally.get(v, 0), 'c': c} for v, c in vc.items()], 'unit': 'laws'},
['%d physical-style laws were measured on the estate; %d hold.' % (len(L), tally.get('HOLDS', 0)),
'Each is an analogy with a fixed test written down before the run, not physics.'],
[data_key(laws.get('schema', 'estate-laws-v1'), 'laws[].verdict', cut)], deeper(),
'Bar chart of law verdicts: ' + ', '.join('%s %d' % (v, tally.get(v, 0)) for v in vc))]
for l in sorted(L, key=lambda l: (l.get('verdict') != 'HOLDS', l.get('id', '')))[:6]:
cards.append(card(
{'type': 'number', 'v': l.get('id', '?'), 'l': l.get('name', ''), 'c': vc.get(l.get('verdict'), MUTED),
'sub': l.get('verdict', '')},
['%s: %s' % ((l.get('verdict') or '?').capitalize(), first_sentence(l.get('law', ''))),
first_sentence(l.get('means', ''), 150)],
[G.ev_key(k) for k in (l.get('evidence') or [])[:3]] + [data_key(laws.get('schema', ''), 'laws.%s' % l.get('id'), cut)],
deeper(), '%s %s: %s' % (l.get('id'), l.get('name'), l.get('verdict'))))
return {'id': 'laws', 'title': 'The laws that hold',
'blurb': 'The estate measured as if it obeyed physical laws.', 'cards': cards,
'sources': [{'name': 'laws.json', 'schema': laws.get('schema'), 'cut': cut}]}
def story_seethrough(cx, st=None, pilot=None):
G = cx.G
if not st and not pilot:
raise ValueError('neither See Through index nor Pilot places found')
cards = []
if st:
files = st.get('files') or {}
best = max(files.items(), key=lambda kv: (kv[1].get('n', 0), -int(kv[0])), default=None)
cards.append(card(
{'type': 'number', 'v': st.get('linked_files', len(files)), 'l': 'code files name a real substation', 'c': AMBER,
'sub': 'out of %s substation names' % n(st.get('names', 0))},
['See Through knows %s substation names from OpenStreetMap; %s code files name one of them.'
% (n(st.get('names', 0)), n(st.get('linked_files', len(files)))),
'Each match is exact or the same words spelt another way, and links straight to that substation.'],
[data_key(st.get('schema', ''), 'names, linked_files', st.get('cut', ''))],
cx.deeper(('../seethrough/index.html', 'Open the substation index'),
(G.href(G.file(int(best[0]))) if best and G.file(int(best[0])) else None, 'Open a file that names substations')),
'Count of code files linked to substations'))
if best:
fid, rec = best
f = G.file(int(fid))
names = [m[0] for m in rec.get('m') or []][:3]
cards.append(card(
{'type': 'steps', 'items': names + (['…'] if rec.get('n', 0) > len(names) else []), 'done': [True] * 4},
['"%s" names the most substations: %s.' % ((f or {}).get('title', rec.get('k')), n(rec.get('n', 0))),
'Open its page and tap a name to see that substation in See Through.'],
[G.ev(f)] if f else [],
cx.deeper((G.href(f) if f else None, 'Open the file page')),
'File naming substations: ' + ', '.join(names)))
if pilot and pilot.get('places'):
P = pilot['places']
top = max(P, key=lambda p: (len(p.get('files') or []), -p.get('i', 0)))
tf = (top.get('files') or [{}])[0]
cards.append(card(
{'type': 'scatter', 'pts': [[p['lon'], p['lat']] for p in P if 'lat' in p and 'lon' in p],
'box': [-10.7, 49.8, 1.9, 60.95], 'hi': [top.get('lon'), top.get('lat'), top.get('name')], 'c': CYAN},
['%s real places are written as coordinates inside the code, all in Great Britain and Ireland.' % n(len(P)),
'%s appears in the most files (%d); Pilot flies you there with the real grid lines around it.'
% (top.get('name'), len(top.get('files') or []))],
[{'k': tf.get('key'), 'href': ('../' + tf['url']) if tf.get('url') else None}]
+ [data_key(pilot.get('schema', ''), 'places', pilot.get('cut', ''))],
cx.deeper(('../pilot/index.html?file=%s' % tf.get('id'), 'Fly there in Pilot'),
(('../' + tf['url']) if tf.get('url') else None, 'Open the file that names it')),
'Map of %d coded places; %s highlighted' % (len(P), top.get('name'))))
return {'id': 'seethrough', 'title': 'From code to substation',
'blurb': 'See Through and Pilot: where the code meets the real grid.', 'cards': cards,
'sources': [s for s in [{'name': 'seethrough index', 'schema': st.get('schema'), 'cut': st.get('cut')} if st else None,
{'name': 'pilot places', 'schema': pilot.get('schema'), 'cut': pilot.get('cut')} if pilot else None] if s]}
# ------------------------------------------------------------------------------------------------ output
def noscript(stories):
e = html.escape
out = ['<noscript><div class="plain"><p>Without JavaScript the stories are shown as plain text.</p>']
for s in stories:
out.append('<h2 id="ns-%s">%s</h2><p class="k">%s</p><ol>' % (e(s['id']), e(s['title']), e(s['blurb'])))
for c in s['cards']:
out.append('<li><p>%s</p><p class="k">Picture: %s</p><p class="k">Evidence: %s</p><p><a href="%s">%s</a></p></li>' % (
' '.join(e(x) for x in c['say']), e(c['alt']), e('; '.join(k['k'] for k in c['keys'])),
e(c['deeper']['href']), e(c['deeper']['label'])))
out.append('</ol>')
out.append('</div></noscript>')
return ''.join(out)
def write(out, stories, G):
os.makedirs(os.path.join(out, 'stories'), exist_ok=True)
for f in os.listdir(os.path.join(out, 'stories')):
if f.endswith('.json'):
os.remove(os.path.join(out, 'stories', f))
for s in stories:
s.update({'schema': STORY_SCHEMA, 'generator': GENERATOR_VERSION, 'graph_cut': G.cut})
with open(os.path.join(out, 'stories', s['id'] + '.json'), 'w', encoding='utf-8') as fh:
json.dump(s, fh, ensure_ascii=False, separators=(',', ':'))
idx = {'schema': INDEX_SCHEMA, 'generator': GENERATOR_VERSION, 'graph_cut': G.cut,
'stories': [{'id': s['id'], 'title': s['title'], 'blurb': s['blurb'], 'cards': len(s['cards']),
'pic': s['cards'][0]['pic'], 'url': 'stories/%s.json' % s['id']} for s in stories]}
with open(os.path.join(out, 'stories.json'), 'w', encoding='utf-8') as fh:
json.dump(idx, fh, ensure_ascii=False, separators=(',', ':'))
for a in ('show.css', 'show.js'):
shutil.copyfile(os.path.join(TEMPLATE, a), os.path.join(out, a))
page = open(os.path.join(TEMPLATE, 'index.html'), encoding='utf-8').read()
page = page.replace('<!--NOSCRIPT-->', noscript(stories)).replace('{{GENERATOR}}', GENERATOR_VERSION) \
.replace('{{CUT}}', html.escape(G.cut))
with open(os.path.join(out, 'index.html'), 'w', encoding='utf-8') as fh:
fh.write(page)
with open(os.path.join(out, 'extra.json'), 'w', encoding='utf-8') as fh:
json.dump({'title': 'Stories: the best experiments, one swipe at a time',
'description': '%d short guided stories for newcomers: one picture and one or two sentences per card.'
% len(stories), 'entry': 'index.html'}, fh)
return idx
def find_input(site, name, flag):
if flag:
return flag if os.path.exists(flag) else None
for rel in SITE_INPUTS[name]:
p = os.path.join(site, rel)
if os.path.exists(p):
return p
return None
def main(argv=None):
ap = argparse.ArgumentParser(description='Explore Code story mode (guided presentations).')
ap.add_argument('--site', required=True, help='the built explore-code folder')
ap.add_argument('--graph', help='build_graph.json (default <site>/build_graph.json)')
ap.add_argument('--out', help='output folder (default <site>/show)')
for k in SITE_INPUTS:
ap.add_argument('--' + k, help='%s input (default: looked for in --site)' % k)
ap.add_argument('--about', help='folder of <repo>/ABOUT.md draft descriptors for the core engines (optional)')
ap.add_argument('--only', default='', help='comma-separated story ids (default all: %s)' % ','.join(ORDER))
ap.add_argument('--strict', action='store_true', help='exit 1 if any story is skipped')
a = ap.parse_args(argv)
site = os.path.abspath(a.site)
out = os.path.abspath(a.out or os.path.join(site, 'show'))
gpath = a.graph or os.path.join(site, 'build_graph.json')
try:
G = Graph(load_json(gpath))
except (OSError, ValueError) as ex:
warn('cannot read build graph %s: %s' % (gpath, ex))
return 1
cx = Ctx(site, G)
inp = {k: find_input(site, k, getattr(a, k)) for k in SITE_INPUTS}
def j(k):
p = inp.get(k)
if not p:
return None
try:
return load_json(p)
except (OSError, ValueError) as ex:
warn('%s input %s unreadable: %s' % (k, p, ex))
return None
builders = {
'engines': lambda: story_engines(cx, a.about),
'communities': lambda: story_communities(cx, inp['lab']) if inp['lab'] else None,
'clean': lambda: story_clean(cx, j('clean'), j('clarity')) if inp['clean'] else None,
'periodic': lambda: story_periodic(cx, j('periodic'), j('furnace')) if inp['periodic'] else None,
'laws': lambda: story_laws(cx, j('laws')) if inp['laws'] else None,
'seethrough': lambda: story_seethrough(cx, j('seethrough'), j('pilot')) if (inp['seethrough'] or inp['pilot']) else None,
}
only = [s for s in a.only.split(',') if s] or ORDER
stories, skipped = [], []
for sid in ORDER:
if sid not in only:
continue
try:
s = builders[sid]()
except Exception as ex: # fail-safe: one bad input never breaks the other stories
warn('story %s skipped: %s: %s' % (sid, type(ex).__name__, ex))
s = None
if s and s.get('cards'):
stories.append(s)
else:
skipped.append(sid)
if s is None:
warn('story %s skipped: input not found' % sid)
if not stories:
warn('no story could be written')
return 1
idx = write(out, stories, G)
print('show: %d stories, %d cards -> %s%s' % (len(stories), sum(s['cards'] for s in idx['stories']), out,
(' (skipped: %s)' % ', '.join(skipped)) if skipped else ''))
return 1 if (a.strict and skipped) else 0
if __name__ == '__main__':
sys.exit(main())