Repository navigation
Expand file tree
/
Copy pathcalibration_test.go
More file actions
429 lines (408 loc) · 12.1 KB
/
Copy pathcalibration_test.go
File metadata and controls
429 lines (408 loc) · 12.1 KB
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
package main
// The calibration, against real records rather than the made-up accounts in
// the other tests. The data cannot live in the repository, so these only
// run when told where it is, and the CI downloads it and runs them on every
// push:
//
// LINEUP_PUMS=csv_por.zip LINEUP_PUMS_DICT=PUMS_Data_Dictionary_2024.txt go test -run Census -v
// LINEUP_SYNTHPAI=synthpai.jsonl go test -run SynthPAI -v
//
// The first asks how far off the count is when every fact is right. The
// second asks how often the facts are right at all.
import (
"archive/zip"
"bufio"
"encoding/csv"
"encoding/json"
"io"
"math"
"os"
"regexp"
"sort"
"strconv"
"strings"
"testing"
)
// usStates maps the census state numbers to the postal codes GeoNames uses
// for regions.
var usStates = map[string]string{
"01": "AL", "02": "AK", "04": "AZ", "05": "AR", "06": "CA", "08": "CO", "09": "CT",
"10": "DE", "11": "DC", "12": "FL", "13": "GA", "15": "HI", "16": "ID", "17": "IL",
"18": "IN", "19": "IA", "20": "KS", "21": "KY", "22": "LA", "23": "ME", "24": "MD",
"25": "MA", "26": "MI", "27": "MN", "28": "MS", "29": "MO", "30": "MT", "31": "NE",
"32": "NV", "33": "NH", "34": "NJ", "35": "NM", "36": "NY", "37": "NC", "38": "ND",
"39": "OH", "40": "OK", "41": "OR", "42": "PA", "44": "RI", "45": "SC", "46": "SD",
"47": "TN", "48": "TX", "49": "UT", "50": "VT", "51": "VA", "53": "WA", "54": "WV",
"55": "WI", "56": "WY",
}
// occupations reads the census occupation codes from the PUMS data
// dictionary and matches each to a BLS row by name. The two use the same
// 2018 classification, so the names mostly agree once the census's prefix
// ("MED-Registered Nurses") comes off.
func occupations(t *testing.T, path string) map[string]string {
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
byName := map[string]string{}
for title := range census().Jobs {
byName[fold(title)] = title
}
line := regexp.MustCompile(`^\s+(\d{4})\s+\.(?:[A-Z]{3,4}-)?(.+)$`)
header := regexp.MustCompile(`^[A-Z][A-Z0-9]+\s+(?:Character|Numeric)\s`)
out := map[string]string{}
inside := false
s := bufio.NewScanner(f)
for s.Scan() {
text := s.Text()
if strings.HasPrefix(text, "OCCP ") {
inside = true
continue
}
// The section ends at the next variable, which is a name in capitals
// at the start of a line followed by its type.
if inside && header.MatchString(text) {
break
}
if m := line.FindStringSubmatch(text); inside && m != nil {
if title, ok := byName[fold(m[2])]; ok {
out[m[1]] = title
}
}
}
return out
}
type cell struct {
records int
people float64
}
func TestAgainstTheCensus(t *testing.T) {
path, dict := os.Getenv("LINEUP_PUMS"), os.Getenv("LINEUP_PUMS_DICT")
if path == "" || dict == "" {
t.Skip("LINEUP_PUMS and LINEUP_PUMS_DICT are not set")
}
jobs := occupations(t, dict)
if len(jobs) < 300 {
t.Fatalf("only %d census occupations matched a BLS row", len(jobs))
}
z, err := zip.OpenReader(path)
if err != nil {
t.Fatal(err)
}
defer z.Close()
var rc io.ReadCloser
for _, f := range z.File {
if strings.HasSuffix(f.Name, ".csv") {
if rc, err = f.Open(); err != nil {
t.Fatal(err)
}
}
}
if rc == nil {
t.Fatal("no csv in the zip")
}
defer rc.Close()
r := csv.NewReader(bufio.NewReaderSize(rc, 1<<20))
head, err := r.Read()
if err != nil {
t.Fatal(err)
}
col := map[string]int{}
for i, h := range head {
col[strings.TrimPrefix(h, string(rune(0xfeff)))] = i
}
// A person is described the way a post would describe them: which
// five years of age, man or woman, the job, married or not.
type key struct {
band, occ string
male bool
married bool
// any leaves marriage out, to show what that one fact costs in
// accuracy on its own.
any bool
}
cells := map[key]*cell{}
state, everybody := "", 0.0
for {
rec, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
t.Fatal(err)
}
weight, _ := strconv.ParseFloat(rec[col["PWGTP"]], 64)
everybody += weight
state = rec[col["STATE"]]
age, _ := strconv.Atoi(rec[col["AGEP"]])
title, ok := jobs[rec[col["OCCP"]]]
// The census gives an occupation to anybody who worked in the last
// five years, pensioners included, and the BLS counts people in
// work. Only the employed are compared, or the census would have
// a fifth more nurses than the BLS for reasons that have nothing
// to do with this program.
if esr := rec[col["ESR"]]; esr != "1" && esr != "2" {
continue
}
if age < 20 || age >= 70 || !ok {
continue
}
k := key{band: strconv.Itoa(age / 5 * 5), occ: title, male: rec[col["SEX"]] == "1", married: rec[col["MAR"]] == "1"}
for _, k := range []key{k, {band: k.band, occ: k.occ, male: k.male, married: k.married, any: true}} {
if k.any {
k.married = false
}
c := cells[k]
if c == nil {
c = &cell{}
cells[k] = c
}
c.records++
c.people += weight
}
}
region := census().Regions["US."+usStates[state]]
if region == nil {
t.Fatalf("no region for state %s", state)
}
shapeUS := shape(census().Countries["US"])
estimate := func(k key, population float64) float64 {
from, _ := strconv.Atoi(k.band)
share, _ := jobShare(k.occ)
total := 0.0
for age := from; age < from+5; age++ {
n := shapeUS.Female[age]
if k.male {
n = shapeUS.Male[age]
}
m := married(age, k.male)
switch {
case k.any:
m = 1
case !k.married:
m = 1 - m
}
total += n * share(age, k.male) * m
}
return population * total
}
// A cell counted from a handful of records is mostly sampling noise.
// Fifteen or more puts the noise at about a quarter either way, which
// is still in the numbers below, and the report says so.
const enough = 15
var logs, withTrue, noMarriage []float64
var weights, weightsNoMarriage []int
for k, c := range cells {
if c.records < enough {
continue
}
if k.any {
noMarriage = append(noMarriage, math.Log(estimate(k, everybody)/c.people))
weightsNoMarriage = append(weightsNoMarriage, c.records)
continue
}
logs = append(logs, math.Log(estimate(k, region.Population)/c.people))
withTrue = append(withTrue, math.Log(estimate(k, everybody)/c.people))
weights = append(weights, c.records)
}
if len(logs) < 30 {
t.Fatalf("only %d cells had %d records or more", len(logs), enough)
}
spread := math.Sqrt(0.35*0.35 + 0.1*0.1 + 0.05*0.05 + 0.5*0.5 + 0.25*0.25 + correlation*correlation*3)
summary := func(name string, xs []float64, weights []int) (inside float64) {
type wx struct {
x float64
w int
}
all := make([]wx, len(xs))
total := 0
for i, x := range xs {
all[i] = wx{x, weights[i]}
total += weights[i]
}
sort.Slice(all, func(i, j int) bool { return all[i].x < all[j].x })
at := func(q float64) float64 {
seen := 0
for _, p := range all {
seen += p.w
if float64(seen) >= q*float64(total) {
return p.x
}
}
return all[len(all)-1].x
}
held := 0
for _, p := range all {
if math.Abs(p.x) <= z90*spread {
held += p.w
}
}
inside = float64(held) / float64(total)
t.Logf("%-32s median x%.2f, 90%% of people between x%.2f and x%.2f, %.0f%% inside the printed band",
name, math.Exp(at(0.5)), math.Exp(at(0.05)), math.Exp(at(0.95)), 100*inside)
return inside
}
t.Logf("state %s: %d cells, %d records in them, %.0f people counted by the census, %.0f by the region table",
usStates[state], len(logs), sum(weights), everybody, region.Population)
summary("age, sex and job", noMarriage, weightsNoMarriage)
summary("and married or not", withTrue, weights)
inside := summary("and the region table's population", logs, weights)
if inside < 0.8 {
t.Errorf("the printed band held the census count for only %.0f%% of people", 100*inside)
}
}
func sum(xs []int) int {
t := 0
for _, x := range xs {
t += x
}
return t
}
// SynthPAI is 7,800 Reddit comments written by language models playing 300
// invented people, each with the facts about them written down, published
// by the ETH Zurich group that first showed models could infer them. The
// comments were written to hint rather than say, so most of what is in
// them is out of reach of patterns by design; the question here is whether
// what the patterns do read is right.
func TestAgainstSynthPAI(t *testing.T) {
path := os.Getenv("LINEUP_SYNTHPAI")
if path == "" {
t.Skip("LINEUP_SYNTHPAI is not set")
}
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
type profile struct {
Age int `json:"age"`
Sex string `json:"sex"`
City string `json:"city_country"`
Birthplace string `json:"birth_city_country"`
Occupation string `json:"occupation"`
Relationship string `json:"relationship_status"`
Education string `json:"education"`
}
type comment struct {
Author string `json:"author"`
Text string `json:"text"`
Profile profile `json:"profile"`
}
authors := map[string][]comment{}
s := bufio.NewScanner(f)
s.Buffer(make([]byte, 1<<20), 1<<24)
for s.Scan() {
var c comment
if err := json.Unmarshal(s.Bytes(), &c); err != nil {
t.Fatal(err)
}
authors[c.Author] = append(authors[c.Author], c)
}
type tally struct{ said, right, of int }
scores := map[string]*tally{}
score := func(name string, said, right bool) {
sc := scores[name]
if sc == nil {
sc = &tally{}
scores[name] = sc
}
sc.of++
if said {
sc.said++
if right {
sc.right++
}
}
}
for _, cs := range authors {
in := &Input{Kinds: map[string]int{}, Skipped: map[string]string{}}
for i, c := range cs {
in.add(Post{Text: c.Text, Where: "comment " + strconv.Itoa(i)}, "comments")
}
a := readAccount(in, now)
l := count(a)
p := cs[0].Profile
byKind := map[Kind][]Fact{}
for _, f := range a.Facts {
byKind[f.Kind] = append(byKind[f.Kind], f)
}
stepOf := func(k Kind) (Step, bool) {
for _, s := range l.Steps {
if s.Kind == k {
return s, true
}
}
return Step{}, false
}
if s, ok := stepOf(Age); ok {
f := s.Facts[0]
age := float64(now.Year()) - (f.Lo+f.Hi)/2
score("age, within three years", true, math.Abs(age-float64(p.Age)) <= 3)
} else {
score("age, within three years", false, false)
}
if s, ok := stepOf(Sex); ok {
score("sex", true, strings.Contains(s.Plain, map[string]string{"male": " man", "female": "woman"}[p.Sex]))
} else {
score("sex", false, false)
}
city, nation, _ := strings.Cut(p.City, ",")
if len(l.Where) > 0 {
right := false
for _, w := range l.Where {
if fold(w.Name) == fold(city) || fold(countryOf(w.Country).Names[0]) == fold(strings.TrimSpace(nation)) {
right = true
}
}
score("where they live, city or country", true, right)
} else {
score("where they live, city or country", false, false)
}
if name, known := englishJobs[fold(p.Occupation)]; known {
if s, ok := stepOf(Job); ok {
score("job", true, s.Facts[0].Value == name.title)
} else {
score("job", false, false)
}
}
if s, ok := stepOf(Partner); ok {
right := strings.HasSuffix(s.Plain, p.Relationship)
if s.Plain == "has a partner" {
right = p.Relationship == "married" || p.Relationship == "engaged" || strings.Contains(p.Relationship, "relationship")
}
score("relationship", true, right)
} else {
score("relationship", false, false)
}
if s, ok := stepOf(Degree); ok {
ed := strings.ToLower(p.Education)
right := strings.Contains(s.Plain, "PhD") && (strings.Contains(ed, "phd") || strings.Contains(ed, "doctor")) ||
strings.Contains(s.Plain, "master") && strings.Contains(ed, "master")
score("degree", true, right)
} else {
score("degree", false, false)
}
}
names := make([]string, 0, len(scores))
for n := range scores {
names = append(names, n)
}
sort.Strings(names)
said, right := 0, 0
for _, n := range names {
sc := scores[n]
precision := 0.0
if sc.said > 0 {
precision = float64(sc.right) / float64(sc.said)
}
t.Logf("%-34s said for %3d of %3d people (%2.0f%%), right %3d times (%3.0f%%)",
n, sc.said, sc.of, 100*float64(sc.said)/float64(sc.of), sc.right, 100*precision)
said += sc.said
right += sc.right
}
t.Logf("%d authors", len(authors))
if said > 0 && float64(right)/float64(said) < 0.8 {
t.Errorf("right %d times out of %d, under four in five", right, said)
}
}