├── README.md ├── index.js ├── package.json ├── LICENSE ├── .gitignore ├── test └── graph.js └── causal-graph.js /README.md: -------------------------------------------------------------------------------- 1 | # cf 2 | Counterfactuals 3 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 2 | // XXX 3 | // - Include a way to save/load a causal graph 4 | // - Ability to viz a causal graph 5 | // - Implement algorithms to: 6 | // - find d-separability 7 | // - find confounders, information propagation 8 | // - project an informational graph 9 | // - other aspects mentioned in book 10 | // - Start to play with some Q models 11 | // - identify unitary vs not 12 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cf", 3 | "version": "0.0.1", 4 | "description": "Counterfactuals / Causal Framework", 5 | "main": "index.js", 6 | "dependencies": { 7 | "lodash.uniq": "^4.5.0" 8 | }, 9 | "devDependencies": { 10 | "eslint-config-robin": "^4.0.0", 11 | "mocha": "^5.2.0" 12 | }, 13 | "scripts": { 14 | "test": "mocha" 15 | }, 16 | "eslintConfig": { 17 | "extends": "robin" 18 | }, 19 | "repository": { 20 | "type": "git", 21 | "url": "git+https://github.com/darobin/cf.git" 22 | }, 23 | "keywords": [ 24 | "causal" 25 | ], 26 | "author": "Robin Berjon ", 27 | "license": "MIT", 28 | "bugs": { 29 | "url": "https://github.com/darobin/cf/issues" 30 | }, 31 | "homepage": "https://github.com/darobin/cf#readme" 32 | } 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Robin Berjon 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | scratch 63 | -------------------------------------------------------------------------------- /test/graph.js: -------------------------------------------------------------------------------- 1 | 2 | let assert = require('assert') 3 | , CausalGraph = require('../causal-graph') 4 | ; 5 | 6 | describe('Causal Graph', () => { 7 | it('should manipulate vertices', () => { 8 | let cg = new CausalGraph(); 9 | assert(cg, 'built a CausalGraph'); 10 | assert.equal(cg.vertices().length, 0, 'no vertices'); 11 | cg.vertex('A', 1); 12 | assert.equal(cg.vertices().length, 1, 'one vertex'); 13 | let g = cg.vertex('B', 2).vertex('C', 3); 14 | assert.equal(cg.vertices().length, 3, 'three vertex'); 15 | assert.equal(g, cg, 'chaining returns graph'); 16 | ['A', 'B', 'C'].forEach((label, idx) => { 17 | let v = cg.vertex(label); 18 | assert(v, `got vertex ${v}`); 19 | assert.equal(v.label, label, `vertex ${v} has the right label`); 20 | assert.equal(v.value, idx + 1, `vertex ${v} has the right value`); 21 | }); 22 | assert.throws( 23 | () => cg.vertex('A', 42), 24 | /Vertex "A" is already in the causal DAG\.$/, 25 | 'cannot add same vertex twice' 26 | ); 27 | }); 28 | it('should manipulate edges', () => { 29 | let cg = new CausalGraph() 30 | .vertex('A', 1) 31 | .vertex('B', 2) 32 | .vertex('C', 3) 33 | .edge('A', 'B') 34 | .edge('B', 'C') 35 | ; 36 | assert.throws( 37 | () => cg.edge('C', 'A'), 38 | /Adding an edge from "C" to "A" created a cycle\.$/, 39 | 'cannot introduce cycles' 40 | ); 41 | let g = cg 42 | .vertex('D', 4) 43 | .vertex('E', 5) 44 | .edge('A', 'D') 45 | .vertex('F', 6) 46 | .vertex('G', 7) 47 | .vertex('H', 8) 48 | .edge('D', 'E') 49 | .edge('E', 'F') 50 | .edge('E', 'G') 51 | .edge('E', 'H') 52 | .edge('C', 'H') 53 | ; 54 | assert.equal(g, cg, 'chaining returns graph'); 55 | let A = cg.vertex('A') 56 | , E = cg.vertex('E') 57 | , H = cg.vertex('H') 58 | , aKids = A.children() 59 | , eKids = E.children() 60 | , aParents = A.parents() 61 | , eParents = E.parents() 62 | , hParents = H.parents() 63 | , aDescendants = A.descendants() 64 | , eDescendants = E.descendants() 65 | , aAncestors = A.ancestors() 66 | , eAncestors = E.ancestors() 67 | , hAncestors = H.ancestors() 68 | , toLabel = (arr) => arr.map(k => k.label).join(',') 69 | ; 70 | assert.equal(aKids.length, 2, 'A has two kids'); 71 | assert.equal(eKids.length, 3, 'E has three kids'); 72 | assert.equal(toLabel(aKids), 'B,D', 'A has kids: B, D'); 73 | assert.equal(toLabel(eKids), 'F,G,H', 'E has kids: F, G, H'); 74 | assert.equal(aParents.length, 0, 'A has no parents'); 75 | assert.equal(eParents.length, 1, 'E has one parent'); 76 | assert.equal(hParents.length, 2, 'H has two parents'); 77 | assert.equal(toLabel(aParents), '', 'A is the root'); 78 | assert.equal(toLabel(eParents), 'D', 'E has parent D'); 79 | assert.equal(toLabel(hParents), 'E,C', 'H has parents E, C'); 80 | assert.equal(aDescendants.length, 7, 'A has seven descendants'); 81 | assert.equal(eDescendants.length, 3, 'E has three descendants'); 82 | assert.equal(toLabel(aDescendants), 'B,D,C,H,E,F,G', 'A has descendants: B, D, C, H, E, F, G'); 83 | assert.equal(toLabel(eDescendants), 'F,G,H', 'E has descendants: F, G, H'); 84 | assert.equal(aAncestors.length, 0, 'A has no ancestors'); 85 | assert.equal(eAncestors.length, 2, 'E has two ancestors'); 86 | assert.equal(hAncestors.length, 5, 'H has five ancestors'); 87 | assert.equal(toLabel(aAncestors), '', 'A is the root'); 88 | assert.equal(toLabel(eAncestors), 'D,A', 'E has ancestors D, A'); 89 | assert.equal(toLabel(hAncestors), 'E,C,D,A,B', 'H has ancestors: E, C, D, A, B'); 90 | }); 91 | }); 92 | -------------------------------------------------------------------------------- /causal-graph.js: -------------------------------------------------------------------------------- 1 | 2 | let uniq = require('lodash.uniq'); 3 | 4 | module.exports = class CausalGraph { 5 | constructor () { 6 | this._vertices = {}; 7 | this._edges = {}; 8 | this._backEdges = {}; 9 | } 10 | // XXX UNTESTED 11 | // The JSON format is simple: 12 | // { 13 | // label: { 14 | // value: 17, 15 | // edges: [A, B...] 16 | // } 17 | // } 18 | fromJSON (obj) { 19 | let allEdges = []; 20 | Object.keys(obj).forEach((label) => { 21 | let { value = null, edges = [] } = obj[label]; 22 | this.vertex(label, value); 23 | allEdges.push({ from: label, edges }); 24 | }); 25 | allEdges.forEach(({ from, edges }) => edges.forEach(to => this.edge(from, to))); 26 | } 27 | // XXX UNTESTED 28 | toJSON () { 29 | let obj = {}; 30 | this.vertices().forEach(v => { 31 | obj[v.label] = { 32 | value: v.value || null, 33 | edges: this.edges(v.label), 34 | }; 35 | }); 36 | return obj; 37 | } 38 | vertex (label, value) { 39 | if (typeof value === 'undefined') return this._vertices[label] || null; 40 | if (this._vertices[label]) throw new Error(`Vertex "${label}" is already in the causal DAG.`); 41 | this._vertices[label] = new Vertex(label, value, this); 42 | return this; 43 | } 44 | edge (from, to) { 45 | from = typeof from === 'string' ? from : from.label; 46 | to = typeof to === 'string' ? to : to.label; 47 | if (!this._vertices[from]) throw new Error(`No vertex "${from}".`); 48 | if (!this._vertices[to]) throw new Error(`No vertex "${to}".`); 49 | if (!this._edges[from]) this._edges[from] = []; 50 | if (!this._backEdges[to]) this._backEdges[to] = []; 51 | this._edges[from].push(to); 52 | this._backEdges[to].push(from); 53 | let findCycle = (vtx) => { 54 | let find = (start) => { 55 | if (!this._backEdges[start]) return false; 56 | for (let i = 0; i < this._backEdges[start].length; i++) { 57 | let parent = this._backEdges[start][i]; 58 | if (parent === vtx || find(parent)) return true; 59 | } 60 | return false; 61 | }; 62 | return find(vtx); 63 | }; 64 | if (findCycle(from)) { 65 | this._edges[from].pop(); 66 | this._backEdges[to].pop(); 67 | throw new Error(`Adding an edge from "${from}" to "${to}" created a cycle.`); 68 | } 69 | return this; 70 | } 71 | vertices () { 72 | return Object.values(this._vertices); 73 | } 74 | edges (from) { 75 | return this._edges[from] || []; 76 | } 77 | backEdges (to) { 78 | return this._backEdges[to] || []; 79 | } 80 | }; 81 | 82 | class Vertex { 83 | constructor (label, value, graph) { 84 | this.label = label; 85 | this.value = value; 86 | this.graph = graph; 87 | } 88 | children () { 89 | return this.graph.edges(this.label).map(label => this.graph.vertex(label)); 90 | } 91 | descendants () { 92 | let desc = [] 93 | , kids = (label) => { 94 | let edges = this.graph.edges(label); 95 | if (edges.length) { 96 | desc = desc.concat(edges); 97 | edges.forEach(kids); 98 | } 99 | } 100 | ; 101 | kids(this.label); 102 | return uniq(desc).map(label => this.graph.vertex(label)); 103 | } 104 | parents () { 105 | return this.graph.backEdges(this.label).map(label => this.graph.vertex(label)); 106 | } 107 | ancestors () { 108 | let anc = [] 109 | , parents = (label) => { 110 | let edges = this.graph.backEdges(label); 111 | if (edges.length) { 112 | anc = anc.concat(edges); 113 | edges.forEach(parents); 114 | } 115 | } 116 | ; 117 | parents(this.label); 118 | return uniq(anc).map(label => this.graph.vertex(label)); 119 | } 120 | } 121 | --------------------------------------------------------------------------------