Motifs and ILP
This post is about two subjects that I worked on extensively but separately in the past: motif finding and integer linear programming (ILP).
Motif finding is the problem of finding approximately repeated patterns in unaligned data. In this particular case, the patterns of interest is in nucleotide data such as DNA or RNA sequences. The repeated patterns may correspond to locations where proteins bind to regulate genes, i.e. transcription factor binding sites or other cis-regulatory sites. Today, in practice, motif finding has is usually performed by position weight matrix (PWM) tools like STREME or Gibbs sampling, biophysical likelihood models fit to high-throughput binding data, and deep learning models. These approaches can find patters in thousands to hundreds of thousands of sequences. I won't attempt anything quite so ambitious here.
Linear programming (LP) is an optimization method that maximizes or minimizes a linear objective function subject to linear constraints. Integer linear programming (ILP) restricts some or all decision variables to integer values. A special case of ILP is where integer variables are restricted to be binary (0 or 1). ILP is NP-hard, meaning large models can take exponential time to solve to provable optimality. the special case of 0–1 integer linear programming, in which unknowns are binary, and only the restrictions must be satisfied, is an NP-complete problem. Despite being NP-hard, modern solvers can handle thousands of variables and constraints using heuristics. Typical solution methods are branch and bound or cutting-planes.
What Is the Connection Between ILP and Motif Finding?
def hamming_distance(s1: str, s2: str) -> int: if len(s1) != len(s2): raise ValueError("Strings must be of equal length") return sum(c1 != c2 for c1, c2 in zip(s1, s2))
Given a difference measure and a collection of sequences, the motif discovery problem becomes finding a collection of common subsequences that minimize the differences among the subsequences. We will make a non-realistic assumption to make the problem easy: we will assume that there is one and only one subsequence that matches the motif pattern in each sequence. In addition we will assume each motif site is the same length and each sequence is the same length. Again, this is just to make our toy problem easy.
A Toy Problem
def generate_random_sequences(length: int, num_seqs: int) -> list[SeqRecord]: seq_list = [] for i in range(num_seqs): rec = SeqRecord(seq = Seq(''.join(random.choices("ATCG", k = length))), id = f"seq{i+1}") seq_list.append(rec) return seq_list
def generate_random_motifs(base: str, num_motifs: int, substitution_rates: tuple[tuple[int, float], ...]) -> list[str]: motif_list = [] s = sum([p[1] for p in substitution_rates]) # for normalization for i in range(num_motifs): motif = base substitutions = np.random.choice([p[0] for p in substitution_rates], 1, p = [p[1]/s for p in substitution_rates])[0] for _ in range(substitutions): pos = random.randrange(len(base)) temp = list(motif) r = random.choice("ACGT") while r == temp[pos]: r = random.choice("ACGT") temp[pos] = r motif = "".join(temp) motif_list.append(motif) return motif_list
def insert_motif_in_seq(seq: SeqRecord, motif: str) -> tuple[int, SeqRecord]: if seq.seq is None: raise ValueError(f"SeqRecord {seq.id!r} has no sequence") s = list(seq.seq) pos = random.randrange(len(s) - len(motif)) s[pos:pos+len(motif)] = list(motif) seq.seq = Seq("".join(s)) seq.description = str(pos) return (pos, seq)
def generate_all_sites(seqs: list[SeqRecord], motif_len: int = 10) -> dict[int, list[str]]: W = dict() for i, s in enumerate(seqs): motif_list = [str(s.seq)[j:j+motif_len] for j in range(len(s) - motif_len + 1)] W[i] = motif_list return W
Solving the ILP
def ILP(W: dict[int, list[str]]) -> tuple[pl.core.lp_problem.LpProblem, dict[tuple[int, int], pl.core.lp_variable.LpVariable], dict[tuple[int, int, int, int], pl.core.lp_variable.LpVariable]]: prob = pl.LpProblem("motif", pl.LpMinimize) # definse variables x = {(i, j): prob.add_variable(f"x_{i}_{j}", cat="Binary") for i in W for j in range(len(W[i]))} y = {(i, j, k, l): prob.add_variable(f"y_{i}_{j}_{k}_{l}", cat="Binary") for i, k in itertools.combinations(W, 2) for j in range(len(W[i])) for l in range(len(W[k]))} # objective prob += pl.lpSum(hamming_distance(W[i][j], W[k][l]) * v for (i, j, k, l), v in y.items()) # constraints for i in W: prob += pl.lpSum(x[i, j] for j in range(len(W[i]))) == 1 # one window per sequence for i, k in itertools.combinations(W, 2): for j in range(len(W[i])): prob += pl.lpSum(y[i, j, k, l] for l in range(len(W[k]))) == x[i, j] for l in range(len(W[k])): prob += pl.lpSum(y[i, j, k, l] for j in range(len(W[i]))) == x[k, l] prob.solve(pl.COIN_CMD(msg=False)) return prob, x, y
def main(): os.environ["PYDEVD_WARN_SLOW_RESOLVE_TIMEOUT"] = "1" args = GetArgs() num_seqs = args.num_sequences seq_len = args.seq_length motif_base = args.motif_base substitution_rates = tuple((int(sub[0]), float(sub[1])) for sub in args.substitution) seed = args.random_seed if seed is None: seed = int(time.time()) rng = np.random.default_rng(seed) seqs = generate_random_sequences(seq_len, num_seqs) motifs = generate_random_motifs(motif_base, num_seqs, substitution_rates) pos = [0] * num_seqs for i in range(num_seqs): pos[i], seqs[i] = insert_motif_in_seq(seqs[i], motifs[i]) W = generate_all_sites(seqs, len(motif_base)) prob, x, y = ILP(W) print("Objective:", prob.objective.value()) print(f"{'Seq': <5} {'pos': <5} {'motif': <15} {'site': <15} {'predicted': <5}") for i in W: j = next(j for j in range(len(W[i])) if x[i, j].value() > 0.5) print(f"{i: <5} {j: <5} {motifs[i]: <15} {W[i][j]: <15} {pos[i]: <5}")
$ time python src/motif_ILP.py -N 10 -M ATTACGAGGG -L 100 -S 0 0.1 -S 1 0.4 -S 2 0.6 Objective: 136.0 Seq pos motif site predicted 0 38 ATTAGGGGGG ATTAGGGGGG 38 1 5 ATTTCGAGGT ATTTCGAGGT 5 2 52 ATAACGAGTG ATAACGAGTG 52 3 69 AGGACGAGGG AGGACGAGGG 69 4 77 TTTCCGAGGG TTTCCGAGGG 77 5 82 ATTACGAGGG ATTACGAGGG 82 6 88 ATTCCGAGAG ATTCCGAGAG 88 7 27 ATAACGAGGG ATAACGAGGG 27 8 17 ATTGCGACGG ATTGCGACGG 17 9 65 ATTGCTAGGG ATTGCTAGGG 65 real 25m52.771s user 27m55.368s sys 0m1.879s

Comments
Post a Comment