Skip to content

Instantly share code, notes, and snippets.

@zpconn
zpconn / README.md
Last active August 29, 2015 14:00
Spherical alpha shapes

This example demonstrates spherical alpha shapes in the orthographic projection. An alpha shape is a generalized concave hull which seeks to characterize the "shape" of a set of points on a surface. It is obtained here by computing the (spherical) Delaunay triangulation (accomplished with the aid of an excellent script from Jason Davies), stripping out triangles that are "too big", and then merging the resulting mesh to remove excess interior geometry that remains from the triangulation.

@zpconn
zpconn / reservoir_max.py
Created August 6, 2014 04:01
Any finite list of integers has a maximum element. There may be multiple occurrences of this maximum. This finds uniformly and randomly the index of one of the occurrences of the maximum element with a single pass over the array using reservoir sampling.
import random
def rand_max(arr):
curr_max = 0
curr_max_idx = 0
curr_max_count = 1
for i,x in enumerate(arr):
if x > curr_max:
curr_max = x
curr_max_idx = i
@zpconn
zpconn / kalman.html
Created April 23, 2015 14:43
Simple Kalman-type filter for position tracking
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html,
body {
margin: 0;
overflow: hidden;
height: 100%;
}
@zpconn
zpconn / Hegex.hs
Last active December 17, 2015 03:49
This is a really short implementation of a pattern matcher for a restricted class of regular expressions, namely those consisting of character literals and the special symbols . ^ & * where . matches any single character, ^ binds the pattern to the target string's beginning, $ binds the pattern to the target's ending, and * matches zero or more …
module Main (main) where
match :: String -> String -> Bool
match ('^':rest) text = matchLocal rest text
match rex (c:rest) = matchLocal rex (c:rest) || match rex rest
match _ _ = False
matchLocal :: String -> String -> Bool
matchLocal [] _ = True
matchLocal "$" [] = True
@zpconn
zpconn / cluster.py
Last active December 24, 2015 22:09
Naive clustering based on gaps between successive numbers. Must have lists.csv in the same directory as cluster.py. lists.csv should contain several columns of real numbers with labels in the header row. This filters out zero values, which will obviously always be in the same cluster. Optional command line argument specifies a custom gap, which …
def pairify(it):
it0, it1 = itertools.tee(it, 2)
first = next(it0)
return zip(itertools.chain([first, first], it0), it1)
def cluster(sequence, maxgap):
batch = []
for prev, val in pairify(sequence):
if abs(val - prev) >= maxgap:
yield batch
@zpconn
zpconn / pid.py
Created November 14, 2013 20:00
A simple discrete-time PID controller.
# A simple discrete-time PID controller. If plot is true, this will use matplotlib to show a graph.
# Otherwise, it will simply print out the successive values of the controller.
plot = True
if __name__ == '__main__':
if plot:
import matplotlib.pyplot as plt
v = [0] * 100
@zpconn
zpconn / markov.py
Created November 16, 2013 05:46
A random text generator based on an N=2 Markov chain model.
from collections import defaultdict
import random
class Markov:
memory = defaultdict(list)
separator = ' '
def get_initial(self):
return (' ', ' ')
@zpconn
zpconn / scatter.py
Created December 2, 2013 21:03
Generates a scatter plot of lat/lon data on a map of the United States.
from mpl_toolkits.basemap import Basemap
from shapely.geometry import Point, MultiPoint
import pandas as pd
import matplotlib.pyplot as plt
x = []
y = []
with open('data.tsv', 'r') as fp:
for line in fp:
s = line.split('\t')
@zpconn
zpconn / expr.py
Created January 13, 2014 04:23
Very simple shunting-yard parser for converting in-fix to post-fix.
def postfix(tokens):
output_stack = []
op_stack = []
for token in tokens:
if is_number(token):
output_stack.append(token)
elif token in ['+', '-', '*', '/']:
while len(op_stack) > 0:
if (token in ['+', '-'] and op_stack[-1] in ['*', '/']) or (token in ['*', '/'] and op_stack[-1] in ['*', '/']):
output_stack.append(op_stack.pop())
@zpconn
zpconn / tree_pairs.py
Created January 13, 2014 04:26
Given a list of pairs, each containing the name of a node and the name of its parent, respectively, this builds the full tree as a nested dictionary. Note that the parent of the root node is specified by None.
def build(pairs, root=None):
tree = {}
for (child, parent) in pairs:
if parent == root:
tree[child] = build(filter(lambda x: x != (child, parent), pairs), child)
return tree
print build([("H", "G"), ("F", "G"), ("G", "D"), ("E", "D"), ("A", "E"), ("B", "C"), ("C", "E"), ("D", None)])