Skip to content

Commit

Permalink
Initial implementation, tests, and examples
Browse files Browse the repository at this point in the history
  • Loading branch information
benweissmann committed Mar 12, 2016
1 parent fa7935c commit 2f0f02b
Show file tree
Hide file tree
Showing 20 changed files with 1,305 additions and 2 deletions.
75 changes: 75 additions & 0 deletions .eslintrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
{
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
},
"env": {
"node": true,
},
"rules": {
"brace-style": [2, "stroustrup", { "allowSingleLine": true }],
"comma-dangle": [ 2, "always-multiline" ],
"comma-style": 2,
"consistent-this": 0,
"curly": [ 2, "all" ],
"dot-location": [ 2, "property"],
"dot-notation": 2,
"eol-last": 2,
"eqeqeq": 2,
"func-style": [2, "expression"],
"guard-for-in": 2,
"indent": [2, 4, { "SwitchCase": 1 }],
"no-alert": 2,
"no-caller": 2,
"no-case-declarations": 2,
"no-class-assign": 2,
"no-const-assign": 2,
"no-control-regex": 0,
"no-dupe-class-members": 2,
"no-labels": 2,
"no-empty-pattern": 2,
"no-eval": 2,
"no-extend-native": 2,
"no-extra-bind": 2,
"no-fallthrough": 2,
"no-floating-decimal": 2,
"no-implicit-coercion": [2, {"boolean": false, "number": true, "string": true}],
"no-implied-eval": 2,
"no-iterator": 2,
"no-loop-func": 2,
"no-multi-spaces": 0,
"no-multi-str": 2,
"no-native-reassign": 2,
"no-new-func": 2,
"no-new-wrappers": 2,
"no-octal": 2,
"no-octal-escape": 2,
"no-proto": 2,
"no-redeclare": 2,
"no-return-assign": 2,
"no-script-url": 2,
"no-self-compare": 2,
"no-sequences": 2,
"no-shadow": 2,
"no-shadow-restricted-names": 2,
"no-throw-literal": 2,
"no-underscore-dangle": 0,
"no-unexpected-multiline": 2,
"no-unused-expressions": 2,
"no-use-before-define": 2,
"no-useless-call": 2,
"no-useless-concat": 2,
"no-var": 2,
"no-void": 2,
"no-warning-comments": [2, { "terms": ["fixme"], "location": "anywhere" }],
"no-with": 2,
"prefer-const": 2,
"prefer-spread": 2,
"prefer-template": 2,
"quotes": [ 2, "double" ],
"semi": 2,
"keyword-spacing": 2,
"wrap-iife": [2, "inside"],
}
}
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
# transpiled javascript
dist

# Logs
logs
*.log
Expand Down
145 changes: 143 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,143 @@
# multivariate-normal-js
A Javascript / Node.JS port of NumPy's multivariate_normal
multivariate-normal-js
=====================

A Javascript port of NumPy's `random.multivariate_normal`.

Check out the [live demo](http://tulip.github.io/multivariate-normal-js)!

From the NumPy docs:

Draw random samples from a multivariate normal distribution.

The multivariate normal, multinormal or Gaussian distribution is a generalization of the one-dimensional normal distribution to higher dimensions. Such a distribution is specified by its mean and covariance matrix. These parameters are analogous to the mean (average or "center") and variance (standard deviation, or "width," squared) of the one-dimensional normal distribution.

See [the NumPy documentation](http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.random.multivariate_normal.html) additional notes, examples, and references.


Who's Behind It
====================

Munit Helpers is maintained by Tulip. We're an MIT startup located in Boston, helping enterprises manage, understand, and improve their manufacturing operations. We bring our customers modern web-native user experiences to the challenging world of manufacturing, currently dominated by ancient enterprise IT technology. We work on Meteor web apps, embedded software, computer vision, and anything else we can use to introduce digital transformation to the world of manufacturing. If these sound like interesting problems to you, [we should talk](mailto:[email protected]).


Example
====================

To start, just `npm install multivariate-normal`.

Then you can do:

```javascript
var MultivariateNormal = require("multivariate-normal");

// means of our three dimensions
var meanVector = [1, 2, 3];

// covariance between dimensions. This examples makes the first and third
// dimensions highly correlated, and the second dimension independent.
var covarianceMatrix = [
[ 1.0, 0.0, 0.9 ],
[ 0.0, 1.0, 0.0 ],
[ 0.9, 0.0, 1.0 ],
];

var distribution = MultivariateNormal(mean, covarianceMatrix);
distribution.sample(); // => [1.2, 1.8, 3.3]

var newDistribution = distribution.setMean([3, 2, 1]);
newDistribution.sample(); // => [2.8, 2.1, 0.7]

// distributions are immutable
distribution.getMean(); // => [1, 2, 3];
newDistribution.getMean(); // => [3, 2, 1];

```

API
====================

##### `MultivariateNormal(mean, covarianceMatrix) -> Distribution`

Arguments:
- `mean` *1-D Array, of length N*: Mean of the N-dimensional distribution.
- `cov` *2-D Array, of shape (N, N)*: Covariance matrix of the distribution. It must be symmetric and positive-semidefinite for proper sampling.

Returns: A Distribution object with methods described below. Distributions
are immutable -- the `set` methods return new distributions.


##### `distribution.sample() -> Array`

Draw a random sample from the distribution. Returns an N-dimensional array.


##### `distribution.getMean(newMean) -> Array`

Returns:
- *1-D Array, of length N*: Mean of the N-dimensional distribution.

Returns the mean of this distribution. The array will be [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze).


##### `distribution.setMean(newMean) -> Distribution`

Arguments:
- `newMean` *1-D Array, of length N*: Mean of the N-dimensional distribution.

Returns a new Distribution with the same covariance matrix as the current distribution, but a new mean.


##### `distribution.getCov(newMean) -> Array`

Returns:
- *2-D Array, of shape (N, N)*: Covariance matrix of the distribution.

Returns the covariance of this distribution. The array will be [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze).


##### `distribution.setCov(newMean) -> Distribution`

Arguments:
- `newMean` *2-D Array, of shape (N, N)*: Covariance matrix of the distribution. It must be symmetric and positive-semidefinite for proper sampling.

Returns a new Distribution with the same mean as the current distribution, but a new covariance matrix.


Get Involved
====================

If you've found a bug or have a feature request, [file an issue on Github](https://github.com/tulip/multivariate-normal-js).

To get started developing:

1. Clone this repo.
2. `npm install`
3. `npm install -g webpack-dev-server`

Then, you can run the tests with `npm test`, or run the example app with
`cd example; webpack-dev-server` and then naviating to http://localhost:8080.

Contributing
====================

How to submit changes:

1. Fork this repository.
2. Make your changes, including adding or changing appropriate tests.
3. Verify unit tests and linting passes with `npm test`
4. Play around with the example app. Make sure the correlations look correct.
5. Email us as [email protected] to sign a CLA.
6. Submit a pull request.

Coding Conventions
--------------------

* [Stroustrup Indentation Style](https://en.wikipedia.org/wiki/Indent_style#Variant:_Stroustrup)
* Four spaces, no tabs
* Trailing newline in all files
* Everything in our [eslintrc](.eslintrc)

License
====================

multivariate-normal-js is licensed under the [Apache Public License](LICENSE).
2 changes: 2 additions & 0 deletions example/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
bundle.js
bundle.js.map
80 changes: 80 additions & 0 deletions example/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Multivariate Normal Example</title>
<link rel="stylesheet" href="style.css">
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="bundle.js"></script>
</head>
<body>
<div id="renderTarget"></div>

<div class="controls">
<form class="2d" action="#">
<div class="means">
<div class="label">Mean</div>
<div class="inputs">
<input type="number" step="any" placeholder="X" name="meanX"/>
<input type="number" step="any" placeholder="Y" name="meanY"/>
</div>
</div>

<div class="cov">
<div class="label">Covariance</div>
<div class="inputs">
<input type="number" step="any" value="1" name="cov00"/>
<input type="number" step="any" value="0" name="cov01"/>

<br />

<input type="number" step="any" value="0" name="cov10"/>
<input type="number" step="any" value="1" name="cov11"/>
</div>
</div>

<div class="submit-wrapper">
<button type="submit">Run</button>
</div>
</form>

<form class="3d" action="#">
<div class="means">
<div class="label">Mean</div>
<div class="inputs">
<input type="number" step="any" placeholder="X" name="meanX"/>
<input type="number" step="any" placeholder="Y" name="meanY"/>
<input type="number" step="any" placeholder="Z" name="meanZ"/>
</div>
</div>

<div class="cov">
<div class="label">Covariance</div>
<div class="inputs">
<input type="number" step="any" value="1" name="cov00"/>
<input type="number" step="any" value="0" name="cov01"/>
<input type="number" step="any" value="0" name="cov02"/>

<br />

<input type="number" step="any" value="0" name="cov10"/>
<input type="number" step="any" value="1" name="cov11"/>
<input type="number" step="any" value="0" name="cov12"/>

<br />

<input type="number" step="any" value="0" name="cov20"/>
<input type="number" step="any" value="0" name="cov21"/>
<input type="number" step="any" value="1" name="cov22"/>
</div>
</div>

<div class="submit-wrapper">
<button type="submit">Run</button>
</div>
</form>
</div>

<a href="https://github.com/tulip/multivariate-normal-js"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/652c5b9acfaddf3a9c326fa6bde407b87f7be0f4/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6f72616e67655f6666373630302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_orange_ff7600.png"></a>
</body>
</html>
7 changes: 7 additions & 0 deletions example/js/data.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import _ from "lodash";
import MultivariateNormal from "multivariate-normal";

export const generateData = (params) => {
const dist = MultivariateNormal(params.means, params.cov);
return _.times(params.points, dist.sample);
};
59 changes: 59 additions & 0 deletions example/js/forms.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/* globals alert */
/* eslint no-alert: 0 */

import { drawChart2D, drawChart3D } from "./plot";
import { generateData } from "./data";
import { serializeForm } from "./util";
import $ from "jquery";

const NUM_POINTS = 5000;

const Forms = {
init() {
// form handlers
$("form.2d").submit(function(evt) {
evt.preventDefault();

const f = serializeForm("form.2d");

try {
const data = generateData({
points: NUM_POINTS,
means: [f.meanX, f.meanY],
cov: [
[ f.cov00, f.cov01 ],
[ f.cov10, f.cov11 ],
],
});
drawChart2D(data);
}
catch (e) {
alert(e.message);
}
});

$("form.3d").submit(function(evt) {
evt.preventDefault();

const f = serializeForm("form.3d");

try {
const data = generateData({
points: NUM_POINTS,
means: [f.meanX, f.meanY, f.meanZ],
cov: [
[ f.cov00, f.cov01, f.cov02 ],
[ f.cov10, f.cov11, f.cov12 ],
[ f.cov20, f.cov21, f.cov22 ],
],
});
drawChart3D(data);
}
catch (e) {
alert(e.message);
}
});
},
};

export default Forms;
6 changes: 6 additions & 0 deletions example/js/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import $ from "jquery";
import Forms from "./forms";

$(function() {
Forms.init();
});
Loading

0 comments on commit 2f0f02b

Please sign in to comment.