Skip to content

Instantly share code, notes, and snippets.

@BenLangmead
Last active December 25, 2015 01:29
Show Gist options
  • Save BenLangmead/6895625 to your computer and use it in GitHub Desktop.
Save BenLangmead/6895625 to your computer and use it in GitHub Desktop.
{
"metadata": {
"name": ""
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "code",
"collapsed": false,
"input": [
"from numpy import zeros\n",
"\n",
"def exampleCost(xc, yc):\n",
" \"\"\" Cost function assigning 0 to match, 2 to transition, 4 to\n",
" transversion, and 8 to gaps \"\"\"\n",
" if xc == yc: return 0 # match\n",
" if xc == '-' or yc == '-': return 8 # gap\n",
" minc, maxc = min(xc, yc), max(xc, yc)\n",
" if minc == 'A' and maxc == 'G': return 2 # transition\n",
" elif minc == 'C' and maxc == 'T': return 2 # transition\n",
" return 4 # transversion\n",
"\n",
"def globalAlignment(x, y, s):\n",
" \"\"\" Calculate global alignment value of sequences x and y using\n",
" dynamic programming. Return global alignment value. \"\"\"\n",
" D = zeros((len(x)+1, len(y)+1), dtype=int)\n",
" for j in xrange(1, len(y)+1):\n",
" D[0, j] = j * s('-', y[j-1])\n",
" for i in xrange(1, len(x)+1):\n",
" D[i, 0] = i * s(x[i-1], '-')\n",
" for i in xrange(1, len(x)+1):\n",
" for j in xrange(1, len(y)+1):\n",
" D[i, j] = min(D[i-1, j-1] + s(x[i-1], y[j-1]), # diagonal\n",
" D[i-1, j ] + s(x[i-1], '-'), # vertical\n",
" D[i , j-1] + s('-', y[j-1])) # horizontal\n",
" return D[len(x), len(y)]"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 1
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"globalAlignment('TACGTCAGC', 'TATGTCATGC', exampleCost)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 2,
"text": [
"10"
]
}
],
"prompt_number": 2
},
{
"cell_type": "code",
"collapsed": false,
"input": [],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 2
}
],
"metadata": {}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment