Skip to content

Instantly share code, notes, and snippets.

View tansey's full-sized avatar

Wesley Tansey tansey

View GitHub Profile
@tansey
tansey / fast_mvn.py
Last active April 29, 2022 03:32
Fast multivariate normal sampling for some common cases
'''Fast sampling from a multivariate normal with covariance or precision
parameterization. Supports sparse arrays. Params:
- mu: If provided, assumes the model is N(mu, Q)
- mu_part: If provided, assumes the model is N(Q mu_part, Q).
This is common in many conjugate Gibbs steps.
- sparse: If true, assumes we are working with a sparse Q
- precision: If true, assumes Q is a precision matrix (inverse covariance)
- chol_factor: If true, assumes Q is a (lower triangular) Cholesky
decomposition of the covariance matrix
(or of the precision matrix if precision=True).
@tansey
tansey / median_deviations.py
Created July 13, 2022 11:02
code to cap values at median deviations
import numpy as np
import numpy.ma as ma
def cap_outliers(points, thresh=3.5, data=None, median=None, med_abs_deviation=None):
'''
Cap outliers to be within a certain number of median deviations.
'''
if type(points) is np.float64:
points = np.array([points])
@tansey
tansey / gist:1444070
Created December 7, 2011 18:49
Sampling from a Gaussian Distribution in C#
public static double SampleGaussian(Random random, double mean, double stddev)
{
// The method requires sampling from a uniform random of (0,1]
// but Random.NextDouble() returns a sample of [0,1).
double x1 = 1 - random.NextDouble();
double x2 = 1 - random.NextDouble();
double y1 = Math.Sqrt(-2.0 * Math.Log(x1)) * Math.Cos(2.0 * Math.PI * x2);
return y1 * stddev + mean;
}
@tansey
tansey / gist:1375526
Created November 18, 2011 03:40
Linear regression in C#
/// <summary>
/// Fits a line to a collection of (x,y) points.
/// </summary>
/// <param name="xVals">The x-axis values.</param>
/// <param name="yVals">The y-axis values.</param>
/// <param name="inclusiveStart">The inclusive inclusiveStart index.</param>
/// <param name="exclusiveEnd">The exclusive exclusiveEnd index.</param>
/// <param name="rsquared">The r^2 value of the line.</param>
/// <param name="yintercept">The y-intercept value of the line (i.e. y = ax + b, yintercept is b).</param>
/// <param name="slope">The slop of the line (i.e. y = ax + b, slope is a).</param>