There are a number of way to answer this. In computer graphics, the problem is often approached using a clipping algorithm. This post examines a couple of simpler techniques using linear inequalities and properties of convexity. To simplify the presentation, we assume we ...
]]>Hedonometer.org popped onto my radar a couple weeks ago. It's a nifty project, attempting to convert samples of words found in the Twitter Gardenhose feed into a time series of happiness.
While I'm not a computational social scientist, I must say the data does have a nice intuitive quality to it. There are obvious trends in happiness associated with major holidays, days of the week, and seasons. It seems like the sort of data that could be decomposed into trends based on those various components. The Hedonometer group has, of course, done extensive analyses of their ...
]]>This post refines those regions, replacing ...
]]>One can think of this problem as a collection of travelling salesman problems, where there are multiple salespeople in different locations and a shared set of destinations. We attempt to find the minimum cost schedule for all salespeople that visits all ...
]]>As a result, I've had to update my ...
]]>This post looks at computing Chebyshev centers for arbitrary convex polygons. We employ essentially ...
]]>Last week, Paul Rubin wrote an excellent post on Extracting a Connected Graph from an existing graph. Lately I've been performing related functions on data from OpenStreetMap, though without access to a solver. In my case I'm taking in arbitrary network data and splitting it into disconnected subnetworks. I thought it might be a good case study to show an algorithmic way doing this and some of the performance issues I ran ...
]]>Correction: $b_{ij}$ is now $b_j$ in the second set of constraints.
We've been studying Lagrangian Relaxation (LR) in the combinatorial optimization course I'm taking this term, and I had some difficulty finding a simple example covering its application. In case anyone else finds it useful, I'm posting a Python version for solving the Generalized Assignment Problem (GAP). This won't discuss the theory of LR at all, just give example code using Gurobi ...
]]>I got back just over a couple hours ago from a weekly rehearsal, so I've got a number of things I'd like to mention swimming around in my head. Here are a few:
However ...
]]>Admittedly, I had a few bugs to fix in the code before I could get this working. If you'd like to run it yourself, the model is here. It works against the latest ...
]]>"I understand the concept of using a companion set to remove duplicates from a list while preserving the order of its elements. But what should I do if these elements are composed of smaller pieces? For instance, say I am generating combinations of numbers in which order is unimportant. How do I make a set recognize that [1,2,3] is the same as [3,2,1] in this case?"
There are a couple points that should help here:
While lists are unhashable and therefore cannot be put into sets, tuples are ...
I'm actually not going to go into anything much resembling algorithmic complexity here. What I'd like to do is present a common performance anti-pattern that I see from novice programmers about once every year or so. If I can prevent one person from committing this error, this post will have achieved its goal. I'd also like to show how an intuitive understanding of time required by operations in relation to the size of data they operate on can be helpful.
Say you ...
]]>Anyone familiar at all with simulation will recognize the last item as the motivating force of the entire field. Simulation models tend to take over when systems become so complex that understanding them is prohibitive in ...
]]>solve.affine <- function(A, rc, x, tolerance=10^-7, R=0.999) {
# Affine scaling method
while (T) {
X_diag <- diag(x)
# Compute (A * X_diag^2 * A^t)-1 using Cholesky factorization.
# This is responsible for scaling the original problem matrix.
q <- A %*% X_diag**2 %*% t(A)
q_inv <- chol2inv(chol(q))
# lambda = q * A * X_diag^2 * c
lambda <- q_inv %*% A %*% X_diag^2 %*% rc
# c - A^t * lambda is used repeatedly
foo <- rc - t(A) %*% lambda
# We converge as s goes to zero
s <- sqrt(sum((X_diag %*% foo)^2))
# Compute new x
x <- (x + R * X_diag^2 %*% foo / s)[,]
# If s is within our tolerance, stop.
if (abs(s) < tolerance) break
}
x
}
This function accepts a matrix A which contains all technological coefficients for an LP, a vector rc containing its reduced costs, and an initial point x interior to the ...
]]>import re
def tokenize(input):
'''Tokenizes an input stream into a list of recognizable tokens'''
token_res = (
r'\(', # open paren -> starts expression
r'\)', # close paren -> ends expression
r'"[^"]*"', # quoted string (don't support ...
]]>import re
def turing(tape, transitions):
# The tape input comes in as a string. We approximate an infinite
# length tape via ...
]]># Build coding tree
def build_tree(scheme):
if scheme.startswith('*'):
left, scheme = build_tree(scheme[1:])
right, scheme = build_tree(scheme)
return (left, right), scheme
else:
return scheme[0], scheme[1:]
def decode(tree, encoded):
ret = ''
node = tree
for direction in encoded:
if direction == '0':
node = node[0]
else:
node = node[1]
if isinstance(node, str):
ret ...
]]>import string
import sys
import time
letters = ' ' + string.ascii_lowercase
for l in 'just another python hacker':
for x in letters:
print(x, end='')
sys.stdout.flush()
time.sleep(0.05)
if x == l ...
]]>$foo = 'whfg nabgure crey unpxre';
$foo =~ y/a-z/n-za-m/;
print $foo;
Python has nothing quite so elegant in its default namespace. However, this does give us the opportunity to explore a little used aspect of strings: the translate method. If we construct a dictionary of ordinals we can accomplish the same thing with a touch more effort.
import string
table = {
ord(x): ord(y) for x ...
]]>x = 'upjohn tehran hectors katy'
y = '1D0HG6JFO9P5ICKAM87B24NL3E'
print(''.join(x[i] for i in sorted(range(len(x)), key=lambda p: y[p])))
Obfuscation consists mostly of using silly machinations to construct the string we use to sort the anagram.
print(''.join('''upjohn tehran hectors katy'''[_]for _ in sorted ...
]]>One day I became disillusioned at the progress of Perl 6 and decided to import this. This appears to be a fairly common story for Perl to Python converts. While I haven't looked back much, there are a number of things I really miss about perl (lower case intentional). Among other things, I miss having value types in a dynamic language, magical and ill-advised use of cryptocontext, and sometimes even pseudohashes because they were inexcusably weird. A language that supports so many ideas out of the box enables ...
]]>I hope you saw China’s way to the top on the Post's website recently. It's a very clear presentation of their statement and is certainly worth a look.
So say you're an economist and you actually do need ...
]]>R provides a function called lm, which is similar in spirit to numpy's linalg.lstsq. As you'll see, lm's interface is a bit more tuned to the concepts of modeling.
We begin by reading in the example CSV into a data frame:
> responses <- read.csv('example_data.csv')
> responses
respondent vanilla.love strawberry.love chocolate.love
1 Serdar 9 4 9
2 Dan 8 6 4
3 Nathaniel 9 4 8
4 Lauren 3 7 9
5 Jen 6 8 5 ...
]]>For purposes of a simple working example, we have collected six records of input data over three dimensions with the ...
]]>Unfortunately, some of the competitors are wily and attached ...
]]>This article commences an ongoing series introducing basic data fitting techniques. With any luck they won't be overly complex, while still being useful enough to get the point across with a real example and real data. We'll start ...
]]>Here's how it works: