logigate/tests/cables.test.ts

180 lines
7.8 KiB
TypeScript

import { describe, expect, it } from 'vitest'
import { nandCounts, shortCount, stats, TRANSISTORS_PER_NAND } from '../app/lib/logic/analyze'
import { bundleWires, cableOf, dissolveCable } from '../app/lib/logic/cables'
import { compile } from '../app/lib/logic/compile'
import { faceLayout, screenLayout, shapeOf } from '../app/lib/logic/geometry'
import { createProject, lookup, pruneWires } from '../app/lib/logic/ops'
import { toProject } from '../app/lib/logic/project'
import { Simulator } from '../app/lib/logic/sim'
import type { ComponentDef, Project } from '../app/lib/logic/types'
/** Four switches wired straight to four lamps. */
function lamps(): { p: Project; def: ComponentDef } {
const p = createProject({ examples: false })
const def: ComponentDef = {
id: 'root',
name: 'Root',
symbol: 'box',
nodes: [
...[0, 1, 2, 3].map(i => ({ id: `s${i}`, kind: 'input' as const, x: 0, y: i * 2, label: `S${i}` })),
...[0, 1, 2, 3].map(i => ({ id: `l${i}`, kind: 'lamp' as const, x: 30, y: 10 + i * 2 })),
],
wires: [0, 1, 2, 3].map(i => ({ id: `w${i}`, from: { node: `s${i}`, pin: 'q' }, to: { node: `l${i}`, pin: 'a' }, ...(i === 0 ? { color: 'blue' as const } : {}) })),
}
p.components.push(def)
return { p, def }
}
/** Lamp values for every switch pattern, as strings like "1010". */
function behaviour(p: Project, def: ComponentDef): string[] {
const out: string[] = []
for (let m = 0; m < 16; m++) {
const s = new Simulator(compile(lookup(p), def.id))
for (let i = 0; i < 4; i++) s.setSource(`s${i}`, ((m >> i) & 1) === 1)
s.run()
out.push([0, 1, 2, 3].map(i => s.pin(`l${i}`, 'a')).join(''))
}
return out
}
describe('cables', () => {
it('bundling wires into a cable keeps every signal on its own wire', () => {
const { p, def } = lamps()
const before = behaviour(p, def)
const res = bundleWires(def, ['w0', 'w1', 'w2', 'w3'], lookup(p))
if (!res.ok) throw new Error(res.error)
expect(res.bundle.bits).toBe(4)
expect(def.wires.filter(w => w.from.node === res.bundle.id)).toHaveLength(1)
expect(def.wires).toHaveLength(9)
expect(behaviour(p, def)).toEqual(before)
// The sleeve starts neutral; the coloured wire keeps its colour into the bundle and out of the split.
expect(def.wires.find(w => w.from.node === res.bundle.id)!.color).toBeUndefined()
expect(def.wires.filter(w => w.color === 'blue').map(w => (w.to.node === res.bundle.id ? 'in' : 'out'))).toEqual(['in', 'out'])
// Both ends sit between sources and targets.
expect(res.bundle.x).toBeGreaterThan(2)
expect(res.split.x).toBeLessThan(30)
})
it('takes a cable apart again into the same connections', () => {
const { p, def } = lamps()
const res = bundleWires(def, ['w0', 'w1', 'w2', 'w3'], lookup(p))
if (!res.ok) throw new Error(res.error)
const cable = def.wires.find(w => w.from.node === res.bundle.id)!
expect(cableOf(def, cable)?.id).toBe(res.bundle.id)
expect(dissolveCable(def, res.bundle.id)).toBe(4)
expect(def.nodes.some(n => n.kind === 'bundle' || n.kind === 'split')).toBe(false)
expect(def.wires.map(w => `${w.from.node}>${w.to.node}`).sort()).toEqual(['s0>l0', 's1>l1', 's2>l2', 's3>l3'])
expect(behaviour(p, def)).toEqual(behaviourOfFresh())
})
it('a cable can fan out to two splits, and a narrower split takes the first wires', () => {
const { p, def } = lamps()
const res = bundleWires(def, ['w0', 'w1', 'w2', 'w3'], lookup(p))
if (!res.ok) throw new Error(res.error)
def.nodes.push({ id: 'sp2', kind: 'split', bits: 2, x: 20, y: 30 }, { id: 'x0', kind: 'lamp', x: 30, y: 30 }, { id: 'x1', kind: 'lamp', x: 30, y: 31 })
def.wires.push(
{ id: 'c2', from: { node: res.bundle.id, pin: 'q' }, to: { node: 'sp2', pin: 'a' } },
{ id: 'o0', from: { node: 'sp2', pin: 'b0' }, to: { node: 'x0', pin: 'a' } },
{ id: 'o1', from: { node: 'sp2', pin: 'b1' }, to: { node: 'x1', pin: 'a' } },
)
const s = new Simulator(compile(lookup(p), def.id))
s.setSource('s1', true)
s.run()
expect([s.pin('x0', 'a'), s.pin('x1', 'a')]).toEqual([0, 1])
})
it('refuses one wire, and cables inside cables', () => {
const { p, def } = lamps()
expect(bundleWires(def, ['w0'], lookup(p)).ok).toBe(false)
const res = bundleWires(def, ['w0', 'w1'], lookup(p))
if (!res.ok) throw new Error(res.error)
const cable = def.wires.find(w => w.from.node === res.bundle.id)!
expect(bundleWires(def, [cable.id, 'w2'], lookup(p)).ok).toBe(false)
})
it('narrowing a cable end drops the wires on pins that are gone', () => {
const { p, def } = lamps()
const res = bundleWires(def, ['w0', 'w1', 'w2', 'w3'], lookup(p))
if (!res.ok) throw new Error(res.error)
res.split.bits = 2
pruneWires(p)
expect(def.wires.filter(w => w.from.node === res.split.id).map(w => w.from.pin).sort()).toEqual(['b0', 'b1'])
expect(shapeOf(res.split, lookup(p)).outputs).toHaveLength(2)
})
})
function behaviourOfFresh() {
const { p, def } = lamps()
return behaviour(p, def)
}
describe('transistors', () => {
it('counts 4 per NAND through every level, the same as the compiled circuit', () => {
const p = createProject({ examples: true })
const counts = nandCounts(p.components)
for (const d of p.components) expect(counts.get(d.id), d.name).toBe(stats(compile(lookup(p), d.id)).nands)
expect(counts.get('ex-not')! * TRANSISTORS_PER_NAND).toBe(4)
expect(counts.get('ex-xor')! * TRANSISTORS_PER_NAND).toBe(16)
expect(counts.get('ex-fa')).toBeGreaterThan(counts.get('ex-ha')!)
})
it('does not hang on a component that contains itself', () => {
const loop: ComponentDef = { id: 'a', name: 'A', symbol: 'box', nodes: [{ id: 'x', kind: 'chip', chip: 'a', x: 0, y: 0 }, { id: 'n', kind: 'nand', x: 0, y: 0 }], wires: [] }
expect(nandCounts([loop]).get('a')).toBe(1)
})
it('shortens big numbers', () => {
expect(shortCount(36)).toBe('36')
expect(shortCount(1234)).toBe('1.2k')
expect(shortCount(56_000)).toBe('56k')
expect(shortCount(2_500_000)).toBe('2.5M')
})
it('keeps challenge records through validation and drops nonsense', () => {
const p = createProject({ examples: false })
const data = JSON.parse(JSON.stringify({ ...p, best: { xor: 16, and: -2, or: 'x', nor: 3.5 } }))
expect(toProject(data).best).toEqual({ xor: 16 })
expect(toProject(JSON.parse(JSON.stringify(p))).best).toBeUndefined()
})
})
describe('pixel screens', () => {
it('packs spaced-out pixels into one screen without gaps', () => {
const def: ComponentDef = {
id: 's',
name: 'S',
symbol: 'box',
nodes: [
{ id: 'a', kind: 'pixel', x: 10, y: 1 },
{ id: 'b', kind: 'pixel', x: 13, y: 1 },
{ id: 'c', kind: 'pixel', x: 10, y: 6, color: 'green' },
],
wires: [],
}
const screen = screenLayout(def)!
expect(screen.pixels).toEqual([
{ id: 'a', col: 0, row: 0, color: undefined },
{ id: 'b', col: 1, row: 0, color: undefined },
{ id: 'c', col: 0, row: 1, color: 'green' },
])
expect([screen.w, screen.h]).toEqual([2, 2])
expect(faceLayout(def).items.map(i => i.kind)).toEqual(['screen'])
})
it('the example screen shows what its inputs say, on the chip box', () => {
const p = createProject({ examples: true })
const get = lookup(p)
const demo = get('ex-demo-screen')!
const chip = demo.nodes.find(n => n.kind === 'chip')!
const shape = shapeOf(chip, get)
const face = shape.face!.find(f => f.kind === 'screen')!
expect(face.pixels).toHaveLength(16)
const s = new Simulator(compile(get, demo.id))
const panel = demo.nodes.find(n => n.kind === 'panel')!
for (const r of panel.rows!) s.setSource(`${panel.id}:${r.id}`, !!r.on)
s.run()
const lit = face.pixels!.map(px => s.face(chip.id, px.id, 'a'))
expect(lit.join('')).toBe('1001000010010110')
})
})