Commit 0b2078e7 authored by Vladimir Reinharz's avatar Vladimir Reinharz
Browse files

v1.0

parent ba064f26
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
(((((((((....((.(((((...((..((((((.......))..))))..))....)))))..))(((.((..(.((....((....)).....)).).)).))).))))))))).
........................................(((((((......)))).......(((....((.....))........)))......)))....(((...)))(((((((((.....)))))..)))).............
...........((((((((((.(((((..........)))))))))))(((......(((.((..........))..)).).....))).(((.((.((.....)).))..))).))))...............(((((.(((((....))))).))))).
......(((.((((....)))).))).....................((((((........)))))).(((((((...)))))))............................((((((((....((((....)))).))))))))..((((((.((((((...........))))))..)))))).......
(((((((..((((.........)))).(((((.......))))).....(((((.......)))))))))))).
.(((((.....((((.((((.......((((.....................(((......)))))))...)))))))).....)))))
...(((((..........)))))........((((((((......))))))))(((((.......))))).............(((((..(((((..((..((.(((((.(((((.......))))).)))))...))....))))))))))))
.((((((.(((((...))))).......((((........))))...)))))).
(((((((..........(((((.........((((((......).))))).........)))))........(((((.....((((......(((((.....)))))((((((.......))))))(((((((.............(((..........................................................................................)))........)))))))))))........................(((((((..................))))))).......)))))........)))....))))
((((((((((((((((((.(((((((((...))))))))).............((((........((((((((((.....)))))(((((....)))).)((...(((((............(((((....((((((....))))))...)))..)).......((((((.......))))))(((((((((....))).))))).)..)))..)))))))))))))...((((......((((((...(((((.....))))))))))).....))))......((((((((....))))))))..........)))))))...................).))))))))))....
...(((((((((((.((((((........)))))).............(((((((((.((......)))))).....(((((((((((..........))))))(((..((((....))))..)).)((.((((....((((...(((....)))..)))).....)))).....(((((............((((((((....))).))))).........)))..))))))))))))))...(((............)))...(((.(((..................))).)))((((((........))))))........))))))).(((((((((..........)))))))))................).)))
...........................................................................((((..............((((((((((((............((((..(((((((((......))))).))))..))))............(((((.(((((...))))).))))))))))))))))).......)))).
..(((((((((((((.(((.............((((.((((((................(((.(((((...(((((((.....((...(((((......)))))..))....)))))))..))))).)))..............)))))).))))...........))))))))))))))))...
...(((((((.....)))))))...(((((.((((((((.....)))))))).)).))).(((((((.((.....)).)))))))..
................((.(((((.(((................))))))))..))....((((...........)))).....(((.((((((((((...)).))))).))).)))...........((((....))))
(((((((((....................................................((((((((............))))))))...............................)))))))))
((((((((((......)))))))....(((....)))))).....((((((((..(((((.((.((..(((((((((((((((((((..(((......(((((((.((.(((((.((((.((((.((((((.((((((((.((....)).)))))))).)))))).......(((((......(((....(((......)))....)))....))))).)))).))))..)))))))....))))))).)))..))))))))).....)))))))))).)).)).))).))..))))))))
....................(((.......)))...............(((((.....)))))...........(((((.....))))).........(((((.....))))).........((((.....)))).......(((((..........))))).(((.......))).........................................((.....))..............................................((......))................(((((......)))))..........((((((((((......))))))))))..........
((((((((.((..((((((((....(((.((.....)).))).........))))))...))..)))))))))).........
..((((..(((((((((((..........((((((((...........))))))))...))))))))))).......)))).................(.((((((......)))))))
........((((.(((((.((((((((((((...))))))....))))))))))).))))..........((((((....))))))((((((((((....))))))))))........
........((((..((....((((((..((((((((....))))))))))))))))))))..................................(((((((.....))))))).((((((...))))))...................
.................((((((((((((..(((((..........................(((((((((.....(((((........(((((((((.................)))))))))...)))))....))))).)))).........................................))))).....))))))))))))..(((((((......((((((((((((((((...(((((.......(((((.((((..(((...............)))...))))))))).(((((...))))).......))))).....))))))))..))))).))).............)))))))..........(((((((((((........(((((..((((........))))..)))))..))))))).))))........
.....((.((..........(((...(((.....)))....)))...................................((((((((......)))))))).......)).))......(((((((....(((.(((((.........((((................))))............))))).))))))))))..........
(((((......))).)).....................................................................................
((((((.(((((((((((((((((((((..((((...))))...........)))))))))))))))))))))))))))
....(((((((((..............)))))))))...(((....................))).......................................(((((.((...((((((...((((((..............................................................................))))))..)).))))((...((((....(.(...........).)....))))...))............)).))))).(((((((((....)))))))))...................(((((....)))))..
..((((((((.(((((....)))))...))))))))..((((.((.................))..)).))..
.((((((((..((((((((.....(((((((.........((((((......................))))))......))))))).........................((((.....))))...........................((((((......)))))).(((.....(((((.....(((........((((((((...))))))))....)))...))))).)))...................................)))))).((((((.................))))))...................)).)))))).))
(((.(((((((((((((((((((((((((((.(.((((((((((((((..((((...))))..)))))))))))))).).)))))))))))))))))))..)))))))).)))..
(((((((((((...)))))))..((((((((((....))))))))))........)))).....((((((((........)))))))).((((((((.....)))))))).....
This diff is collapsed.
This diff is collapsed.
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
from subprocess import Popen, PIPE
from tempfile import mkdtemp
from shutil import rmtree
from os.path import join
from structure import int2str, Structure
from time import sleep
from types import StringType
# Function defining behaviour if a folding program fails
def onfail(f, tries, *args):
if tries < 10:
# Don't retry more than 10 times
sleep(10) # Take ten
return f(*args, tries = tries + 1)
else:
raise RuntimeError, "Function " + f.__name__ + " did not receive result from external program"
# Compute MFE structure of RNA sequence s, return pair of structure in
# bracket notation and MFE as float
def fold(s, T = None, tries = 0):
cmd = ["RNAfold"]
tmpdir = mkdtemp()
if T != None:
cmd.extend(["-T", str(T)])
p = Popen(cmd, stdin = PIPE, stdout = PIPE, cwd = tmpdir)
print >> p.stdin, int2str(s)
p.stdin.close()
t = p.stdout.readlines()[-1].strip().split(None, 1)
p.stdout.close()
rmtree(tmpdir, ignore_errors = True)
if t == [] or len(t[0]) != len(s):
# Did not receive expected output from RNAfold
return onfail(fold, tries, s, T)
return t[0], float(t[1][1:-1])
# Compute base pair probabilities and return as a list of dictionaries
# with the None entry giving the unpaired probability
def boltzmann(s, T = None, tries = 0):
# Class for maintaining probabilities, if none is present return 0
class _ProbVec(dict):
def __getitem__(self, key):
if self.has_key(key):
return super(_ProbVec, self).__getitem__(key)
else:
return 0.0
cmd = ["RNAfold", "-p"]
tmpdir = mkdtemp()
if T != None:
cmd.extend(["-T", str(T)])
p = Popen(cmd, stdin = PIPE, stdout = PIPE, cwd = tmpdir)
print >> p.stdin, int2str(s)
p.stdin.close()
t = p.stdout.readlines()
while p.stdout.readline() != "":
# Make sure RNAfold has properly finished before reading probability plot
pass
p.stdout.close()
try:
mfe = t[1].strip().split(None, 1)
ensemble = float(t[2].strip().split(None, 1)[1][1:-1])
if mfe == [] or len(mfe[0]) != len(s):
# Did not receive expected output from RNAfold
raise IndexError
except IndexError:
return onfail(boltzmann, tries, s, T)
p = [_ProbVec() for i in xrange(len(s))]
for i in p:
i[None] = 1.0
f = open(join(tmpdir, "dot.ps"))
t = f.readline()
while "data starts here" not in t:
t = f.readline()
t = f.readline()
while t != "" and "showpage" not in t:
if "ubox" in t:
t = t.split()
i = int(t[0]) - 1
j = int(t[1]) - 1
q = pow(float(t[2]), 2)
p[i][j] = q
p[j][i] = q
p[i][None] -= q
p[j][None] -= q
t = f.readline()
f.close()
rmtree(tmpdir, ignore_errors = True)
return (p, mfe[0], float(mfe[1][1:-1]), ensemble)
# Evaluate the energy of structure t on sequence s
def energy(s, t, tries = 0):
cmd = ["RNAeval"]
tmpdir = mkdtemp()
if t.temperature != None:
cmd.extend(["-T", str(t.temperature)])
p = Popen(cmd, stdin = PIPE, stdout = PIPE, cwd = tmpdir)
print >> p.stdin, int2str(s)
print >> p.stdin, t.bracket()
p.stdin.close()
u = p.stdout.readlines()[-1].strip().split(None, 1)
p.stdout.close()
rmtree(tmpdir, ignore_errors = True)
if u == [] or len(u[0]) != len(s):
# Did not receive expected output from RNAfold
return onfail(score, tries, s, t)
return float(u[1][1:-1])
# Create initial design using RNAinverse
def design(t, tries = 0):
cmd = ["RNAinverse"]
if t.temperature != None:
cmd.extend(["-T", str(t.temperature)])
p = Popen(cmd, stdin = PIPE, stdout = PIPE)
print >> p.stdin, t.bracket()
print >> p.stdin
p.stdin.close()
try:
s = p.stdout.readline().split()[0]
if type(s) != StringType or len(s) != len(t.bracket()):
# Failed to create initial sequence
raise IndexError
except IndexError:
return onfail(design, tries, t)
return s
# The different classes used to construct a population in the genetic
# algorithm.
from random import uniform, randint, shuffle, choice, sample
from math import sqrt
from types import IntType
from copy import deepcopy
from bisect import bisect
from structure import int2bp, bp2int
from individual import BaseDistribution
from sys import stderr
### POPULATION; general class containing the core of a GA population
class Population:
# Initialise population with n individuals. The target structure(s)
# for the population is given by target, the class structure for
# individuals by indclass, and basedist is used to draw nucleotides
# when initialising and mutating sequences.
def __init__(self, target, indclass, basedist = BaseDistribution(), n = 0):
self.members = set([]) # Current set of individuals
self.new = set([]) # Set of individuals created waiting to be added
self.target = target # Target structure(s) for population
self.__individualclass__ = indclass # Class for creating individuals
self.__basedistribution__ = basedist # Distribution to draw bases from
for i in xrange(n):
self.members.add(indclass(population = self))
# Return target structure(s) for this population
def gettarget(self):
return self.target
# Return distribution for drawing new nucleotides
def getbasedistribution(self):
return self.__basedistribution__
# Add n more individuals to population. If stoppingcriteria is not
# None, it should be a function taking an iterator over the added
# individuals as single argument, returning True if criteria for
# stopping GA has been met and False otherwise, in which case
# addrandom will return the same Boolean value.
def addrandom(self, n, idfunc = None, stoppingcriteria = None):
if idfunc == None:
idfunc = (lambda x: None)
def _addrandom():
for i in xrange(n):
new = self.__individualclass__(population = self, id = idfunc(i))
new.initialise()
self.new.add(new)
yield new
if stoppingcriteria != None:
return stoppingcriteria(_addrandom())
else:
for i in _addrandom():
pass
# Add waiting new individuals to current population
def addnew(self):
self.members.update(self.new)
self.new = set([])
# Size of population
def __len__(self):
return len(self.members)
# Iterator for population
def __iter__(self):
for i in self.members:
yield i
### MUTATE; classes for selecting a set of mutation events creating
### new individuals.
# Simple class that uses each sequence in current population equally many times
class Mutate:
# Add n mutated sequences to population (one for each individual in
# current population if n is undefined), using each current
# individual as starting point the same number of times.
def mutate(self, n = None):
if n == None:
n = len(self)
for i in self.members:
for j in xrange(n / len(self)):
self.new.add(i.mutate(i.getposition()))
if n % len(self) != 0:
# Some current individuals have to be used as staring point one
# more time - choose these at random.
c = sample(range(len(self)), n % len(self))
c.sort()
j = 0
k = 0
for i in self.members:
if c[j] == k:
self.new.add(i.mutate(i.getposition()))
j += 1
if j == len(c):
break
k += 1
# Class choosing starting points independently uniformly at random
class RandomMutate:
### Add n mutated sequences (the same number as in the current
### population if n is undefined)
def mutate(self, n = None):
if n == None:
n = len(self)
m = list(self.members)
for j in xrange(n):
i = choice(m)
self.new.add(i.mutate(i.getposition()))
# Class choosing starting points according to fitness
class FitnessWeightedMutate:
### Add n mutated sequences (the same number as in the current
### population if n is undefined)
def mutate(self, n = None):
z = min(filter(lambda x: x > 0, map(lambda y: y.getfitness(), self.members)))
def _reciprocal(x):
if x <= 0:
# A sequence with fitness of 0 is set to be twice as likely to
# be picked as the sequence with the best fitness larger than
# 0.
return 2.0 / z
else:
return 1.0 / x
if n == None:
n = len(self)
m = list(self.members)
# Generate prefix sum array of fitnesses
w = [_reciprocal(m[0].getfitness())] + (len(self) - 1) * [0]
for i in xrange(1, len(self)):
w[i] = w[i - 1] + _reciprocal(m[i].getfitness())
# Now create mutants
for j in xrange(n):
i = m[bisect(w, uniform(0, w[-1]), hi = len(self) - 1)]
self.new.add(i.mutate(i.getposition()))
### SELECTPAIR; classes for selecting pairs of sequences to create
### recombinants from.
# Simple class just choosing pairs at random
class SelectPair:
def __selectpairs__(self, n):
m = list(self.members)
return [sample(m, 2) for i in xrange(n)]
# Class choosing n pairs based on fitness - it is assumed that fitness
# is a non-negative number, with 0 being a perfectly fit individual.
class WeightedSelectPair:
def __selectpairs__(self, n):
z = min(filter(lambda x: x > 0, map(lambda y: y.getfitness(), self.members)))
def _reciprocal(x):
if x <= 0:
# A sequence with fitness of 0 is set to be twice as likely to
# be picked as the sequence with the best fitness larger than
# 0.
return 2.0 / z
else:
return 1.0 / x
pairs = []
m = list(self.members)
# Generate prefix sum array of fitnesses
w = [_reciprocal(m[0].getfitness())] + (len(self) - 1) * [0]
for i in xrange(1, len(self)):
w[i] = w[i - 1] + _reciprocal(m[i].getfitness())
for i in xrange(n):
# Choose first individual
a = bisect(w, uniform(0, w[-1]), hi = len(self) - 1)
# Choose second individual
x = uniform(0, w[-1] - _reciprocal(m[a].getfitness()))
if x >= w[a] - _reciprocal(m[a].getfitness()):
# Choose beyond a
b = a + 1 + bisect(w[a + 1:], x + _reciprocal(m[a].getfitness()), hi = len(self) - a - 2)
else:
b = bisect(w[:a], x, hi = a - 1)
pairs.append((m[a], m[b]))
return pairs
# Class choosing pairs based on sum of squares of scores of all
# possible cross-overs between the pair.
class CombinedSelectPair:
def __selectpairs__(self, n):
# Function computing one dimensional index from pair of indeces
def pair2idx(a, b):
return a * (a - 1) / 2 + b
# Function computing pair corresponding to one dimensional index
def idx2pair(index):
a = int(sqrt(2 * index)) # Either a or a + 1
a = int(sqrt(2 * index + a)) # 2x is between a^2 - a and a^2 + a - 2
b = index - a * (a - 1) / 2 # Once we know a, b is easy
return a, b
# Compute weight for combining all pairs
m = list(self.members)
w = len(m) * (len(m) - 1) / 2 * [0.0]
for a in xrange(1, len(m)):
for b in xrange(a):
# For each pair, the weight is the combined fitness summed
# over all crossover points.
idx = pair2idx(a, b)
for c in self.gettarget().getcuts():
for i in c:
for j in c:
if i != j:
w[idx] += pow(float(m[a].cweight((i, j)) + m[b].cweight((j, i))), 2) / len(c)
# Choose n pairs according to the computed weights
pairs = []
# Change w to prefix sum array
for i in xrange(1, len(w)):
w[i] += w[i - 1]
for i in xrange(n):
a, b = idx2pair(bisect(w, uniform(0, w[-1]), hi = len(w) - 1))
pairs.append((m[b], m[a]))
return pairs
### SELECTCUT; classes for selecting a set of crossover events creating
### new individuals.
# Class for choosing cross over points uniformly at random
class SelectCut:
# Select a cut for recombining a and b such that positions that can
# be part of a cut are chosen uniformly at random.
def __selectcut__(self, a, b):
cuts = filter(lambda x: len(x) > 1, self.gettarget().getcuts())
w = map(lambda x: len(x), cuts)
for i in xrange(1, len(w)):
w[i] += w[i - 1]
# Select dependency class at random weighted by size
i = bisect(w, randint(0, w[-1] - 1), hi = len(w) - 1)
# Choose random pair of positions in dependency class
return sample(cuts[i], 2)
# Class for choosing cross over points weighted by current fitness
class WeightedSelectCut:
def __selectcut__(self, a, b):
# Compute prefix sums of fitnesses
w = []
cuts = []
for c in self.gettarget().getcuts():
for i in c:
for j in c:
if i != j:
w.append(a.cweight((j, i)) + b.cweight((i, j)))
cuts.append((i, j))
for i in xrange(1, len(w)):
w[i] += w[i - 1]
# Select a cut proportional to its weight
i = bisect(w, uniform(0, w[-1]), hi = len(w) - 1)
return cuts[i]
### RECOMBINE; classes for creating recombinants
class Recombine:
# Add n sequences obtained by crossover (the same number as in the
# current population if n is undefined).
def recombine(self, n = None):
# Choose pairs to create recombinants from
if n == None:
n = len(self)
pairs = self.__selectpairs__(n)
# Choose recombination point for each pair, and create recombinant
for p in pairs:
c = self.__selectcut__(p[0], p[1])
self.new.add(p[0].crossover(p[1], c))
### REDUCE; Classes for reducing the population size
# Method for eliminating duplicates in m, as long as we still have