Build with it
Short programs that read and use Open Values files. Each one was run when this page was built, against the files on this site, and what it printed is shown under it.
- JavaScript: Node 18 or later
- Python: 3, standard library only
- Nothing to install
The files
Put these in one folder: friend-values.json, group.mjs, my-values.json, read-values.mjs, read_values.py, score.mjs, score.py, the engine open-values-engine.mjs, and one comparison, banking.json. Every comparison is listed on the data page.
Read a values file
A values file says how much each of ten shared values matters to one person, from 0 to 5, and carries no name. Its fields are on its spec page. A reader checks the format and the version, then reads the weights.
// Read a values file and print what it asks for.
// Run: node read-values.mjs my-values.json
import { readFileSync } from 'node:fs';
const file = JSON.parse(readFileSync(process.argv[2], 'utf8'));
if (file.format !== 'open-values-passport') throw new Error('this is not a values file');
const [major, minor] = String(file.version).split('.');
if (major !== '0' || minor !== '1') throw new Error(`version ${file.version} is newer than this reader`);
// A reader of 0.1 ignores fields it does not know, so a file with more in it still reads.
for (const [value, weight] of Object.entries(file.values)) {
console.log(`${value.padEnd(10)} ${weight} of 5`);
}
The same in Python:
# Read a values file and print what it asks for.
# Run: python read_values.py my-values.json
import json
import sys
with open(sys.argv[1], encoding="utf-8") as f:
file = json.load(f)
if file.get("format") != "open-values-passport":
sys.exit("this is not a values file")
major, minor = (str(file["version"]).split(".") + ["", ""])[:2]
if (major, minor) != ("0", "1"):
sys.exit(f"version {file['version']} is newer than this reader")
# A reader of 0.1 ignores fields it does not know, so a file with more in it still reads.
for value, weight in file["values"].items():
print(f"{value:<10} {weight} of 5")
What it printed when this page was built:
planet 5 of 5
people 4 of 5
openness 3 of 5
access 3 of 5
autonomy 4 of 5
Rank a comparison by it
A values file speaks in the ten shared values, and each comparison has its own criteria. You write which criterion each value stands for. A value the comparison has no criterion for is reported, and never turned into a score.
// Rank one comparison by a values file.
// Run: node score.mjs banking.json my-values.json
// Needs open-values-engine.mjs in the same folder.
import { readFileSync } from 'node:fs';
import { score, passportApply } from './open-values-engine.mjs';
const data = JSON.parse(readFileSync(process.argv[2], 'utf8'));
const values = JSON.parse(readFileSync(process.argv[3], 'utf8'));
// Which of this comparison's criteria each shared value stands for. You write this per comparison.
const MAP = { planet: 'environment', people: 'ethics', openness: 'transparency', access: 'fees' };
const { weights, dropped } = passportApply(values, MAP);
const ranked = data.products
.map((p) => ({ p, s: score(p, { criteria: data.criteria, weights }) }))
.filter((r) => r.s)
.sort((a, b) => b.s.score - a.s.score || (a.p.code < b.p.code ? -1 : 1));
for (const { p, s } of ranked.slice(0, 5)) {
console.log(`${String(s.score).padStart(3)} ${p.name} (facts for ${Math.round(s.coverage * 100)}% of the weight)`);
}
console.log(`${data.products.length - ranked.length} of ${data.products.length} have too few facts to score`);
for (const d of dropped) console.log(`${d.universal} matters to you (${d.weight}) but this comparison has no criterion for it`);
What it printed when this page was built:
87 Triodos Bank (facts for 100% of the weight)
81 Amalgamated Bank (facts for 100% of the weight)
80 Beneficial State Bank (facts for 80% of the weight)
78 Climate First Bank (facts for 80% of the weight)
75 Nationwide Building Society (facts for 80% of the weight)
0 of 25 have too few facts to score
autonomy matters to you (4) but this comparison has no criterion for it
The same in Python, with the engine's rules written out instead of imported. It leaves out hard rules such as allergens, which the engine also applies.
# Rank one comparison by a values file, with the engine's rules written out in Python.
# Run: python score.py banking.json my-values.json
import json
import math
import sys
MIN_COVERAGE = 0.25
def score(option, criteria, weights):
"""The score of one option, or None when too little of the weight has facts."""
total = weighted = known = 0
cap = None
for c in criteria:
w = weights.get(c["key"], 0)
if w <= 0:
continue
total += w
s = option["scores"].get(c["key"])
if s is None:
continue
weighted += w * s
known += w
# A value weighted 4 or 5 with a fact of 20 or less caps the score at 49,
# unless the criterion is a label check, where 0 means no label was found.
if w >= 4 and s <= 20 and c.get("tier") != "certified":
cap = s if cap is None else min(cap, s)
if not known or not total or known / total < MIN_COVERAGE:
return None
coverage = known / total
# Missing facts pull the score toward 50. floor(x + 0.5) rounds halves up, as JavaScript does.
raw = math.floor(weighted / known * coverage + 50 * (1 - coverage) + 0.5)
return {"score": 49 if cap is not None and raw > 49 else raw, "coverage": coverage}
def apply_values(values, mapping):
"""Weights for this comparison's criteria, and the strong values it has no place for."""
weights, dropped = {}, []
for value, w in values["values"].items():
if value in mapping:
weights[mapping[value]] = max(w, weights.get(mapping[value], 0))
elif w >= 4:
dropped.append((value, w))
return weights, dropped
if __name__ == "__main__":
with open(sys.argv[1], encoding="utf-8") as f:
data = json.load(f)
with open(sys.argv[2], encoding="utf-8") as f:
values = json.load(f)
# Which of this comparison's criteria each shared value stands for. You write this per comparison.
MAP = {"planet": "environment", "people": "ethics", "openness": "transparency", "access": "fees"}
weights, dropped = apply_values(values, MAP)
ranked = [(p, score(p, data["criteria"], weights)) for p in data["products"]]
ranked = sorted([r for r in ranked if r[1]], key=lambda r: (-r[1]["score"], r[0]["code"]))
for p, s in ranked[:5]:
print(f"{s['score']:>3} {p['name']} (facts for {math.floor(s['coverage'] * 100 + 0.5)}% of the weight)")
print(f"{len(data['products']) - len(ranked)} of {len(data['products'])} have too few facts to score")
for value, w in dropped:
print(f"{value} matters to you ({w}) but this comparison has no criterion for it")
The build runs both on the same files and stops if they print different lines. It also checks the Python rules against the engine on every option in every comparison under three sets of weights: 125,667 scorings when this page was built, 119,952 of them scored and 5,715 with too few facts, and all of them the same.
Add up a group's values
Several values files add up to one group file. The engine keeps how far apart people are on each value instead of hiding it in the average; the values the group agrees on least come first.
// Add two people's values files into one group file, keeping how far apart they are.
// Run: node group.mjs my-values.json friend-values.json
// Needs open-values-engine.mjs in the same folder.
import { readFileSync, writeFileSync } from 'node:fs';
import { mergePassports } from './open-values-engine.mjs';
const files = process.argv.slice(2).map((f) => JSON.parse(readFileSync(f, 'utf8')));
const group = mergePassports(files, 'Our house');
for (const value of group.dissent) {
const a = group.agreement[value];
console.log(`${value.padEnd(10)} average ${a.mean}, ${a.voices} of ${group.n} said, agreement ${a.consensus}`);
}
writeFileSync('group-values.json', JSON.stringify(group.passport, null, 2) + '\n');
console.log('wrote group-values.json, a values file any reader of the format can use');
What it printed when this page was built:
planet average 3.5, 2 of 2 said, agreement 0.4
access average 4, 2 of 2 said, agreement 0.6
people average 4.5, 2 of 2 said, agreement 0.8
openness average 3, 1 of 2 said, agreement 1
autonomy average 4, 1 of 2 said, agreement 1
community average 4, 1 of 2 said, agreement 1
wrote group-values.json, a values file any reader of the format can use
The file it wrote is itself a values file, so any app that reads one can rank by the group's values:
{
"format": "open-values-passport",
"version": "0.1",
"source": "Our house",
"values": {
"planet": 3.5,
"people": 4.5,
"openness": 3,
"access": 4,
"autonomy": 4,
"community": 4
}
}
The full group record, with each value's spread, is the collective format. A group's list of options to use and to move away from is the slate format. One person's view on a question, written to be answered, is the position format, and what a group agreed is the agreement format.
Build an app
Three apps run on this engine. The apps page shows what they share and what each one changes. The starter builder makes a first draft of a new one in the browser and downloads two files: a facts file in the lens format and a page that ranks it.