Motifs and ILP

Image generated by Gemini AI.

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?

A motif is a pattern. In a DNA sequence, it represents a pattern of nucleotides. A subsequence of nucleotides in a particular sequence may represent that pattern. The subsequence may be a good or a poor representation of a particular motif. Often, we don't know the pattern, so the goal of motif finding is to discover both the pattern and the positions of the pattern in a set of sequences.

Assume we have a collection of DNA sequences and we have chosen two subsequences, sometimes called motif sites, from two different sequences:

ATCACGAGGG
AGTACGTGGG

The sequences look similar, but they differ at three positions. How do we measure the differences between the two subsequences? If we have probabilistic model such as a PWM, we can compare the subsequences to the model and get the probability of how well they fit the model. Another approach might be to calculate the edit distance between the two. For our purpose here, we will use the Hamming distance. The Hamming distance measures the minimum number of substitutions required to change one string into the other. Equivalently, it is the number of differences in the two subsequences.

Note that using the Hamming distance in this way treats all differences equivalently. This may not be biologically realistic, for example, an A-G mismatch may be more common that an A-T mismatch, so we might want weight the differences accordingly. 

Calculating the Hamming distance between two strings is simple:

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.

We can pose the motif finding problem as a binary ILP problem. The goal of the ILP is to find the collection of subsequences, one from each sequence, that minimizes the overall sum of Hamming distances. 

Assume we have a collection of $N$ sequences, each of length L Each sequence contains a motif site of length m.

We define a set of variables ${x_{ij}} = 1$ for the subsequence starting at position j in sequence i, otherwise  ${x_{ij}} = 0$. 

To compare subsequences, we will calculate the Hamming distance across sites in different sequences. ${w_{ijkl}}$ represents the Hamming distance between a subsequence starting at position j in sequence i and on starting at position l in sequence k, $i \ne k$.

${y_{ijkl}}$ is a binary decision variable. ${y_{ijkl}} = 1$ indicates that site j in  sequence i and site l in sequence k are part of the collection of motif sites considered as a solution.

Thus, our ILP problem becomes

\[{\text{minimize }}\sum\limits_{i = 1}^{k - 1} {\sum\limits_{k = i + 1}^N {{w_{ijkl}}{y_{ijkl}}} } \]
subject to:
\[\sum\limits_{j = 1}^{L - m + 1} {{x_{ij}} = 1} \,\,i = 1..N\]
\[\sum\limits_{l = 1}^{L - m + 1} {{y_{ijkl}} = {x_{ij}}\,\,i = 1..k - 1,k = i + 1..N} ,j = 1..L - m + 1\]
\[\sum\limits_{j = 1}^{L - m + 1} {{y_{ijkl}} = {x_{kl}}\,\,i = 1..k - 1,k = i + 1..N} ,l = 1..L - m + 1\]
\[{x_{ij}} = 0,1\]
\[{y_{ijkl}} = 0,1\]

${w_{ijkl}}$ is the Hamming distance between the subsequence starting at j in sequence i and the subsequence starting at l in sequence k. The objective function sums over all sequence pairs. 
 
The first constraint represents the fact that there is one and only one site in each sequence. The next two indicate that comparisons are between single sites from different sequences.

Each sequence has one motif site and there are $L - m + 1$ possible positions for sites. Ignoring the constraints on the variables for the moment, there are $N + N(N - 1)(L - m + 1)$ explicit constraints. For a simple model with $L = 40$, $m = 8$, and $N = 6$, this works out to 996 constraints.

There are $N(L - m + 1)$ binary constraints on the x variables and 
\[chose(N,2){(L - m + 1)^2}\]
 y variable constraints. For our simple example above, this works out to 198 constraints on the x variables and 16,335 constraints on the y variables. 

The explicit constraints grow roughly as $O({N^2}(L - n + 1))$, while the variable count grows at a rate $O({N^2}{(L - m + 1)^2})$. As the number of sequences and sequence length grows, the problem complexity increases rapidly.

A Toy Problem

We will create a small set of N sequences of length L with embedded motif sites of length m. We will use BioPython Bio::SeqRecord objects to hold the sequences. Nucleotides are chosen uniformly from ATCG.

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
 

To generate motifs, we provide a staring motif and a tuple of substitution rates for each motif element. Each element of the tuple is also a tuple with an integer indicating the number of substitutions and the substitution probability. For example ${\text{((0, 0}}{\text{.3), (1, 0}}{\text{.5), (2, 0}}{\text{.2))}}$ shows that there is 30% probability of no substitutions, a 50% probability of 1 substitution, and a 20% probability of 2.

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

Next, we insert the altered motifs into the sequences at random positions.

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)

To complete the problem setup, we generate all possible motif site positions for the calculation of Hamming distances.

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

There are quite a few LP and ILP solvers for Python: PuLP, MINLP in SCIP, OR-Tools, and many others. I chose PuLP for this problem. It's easy to use and handles binary ILP problems.

With PuLP, you declare variables, setup constraints, and use one of the PuLP solvers to obtain a solution. In this case, I used the PuLP default COIN_CM solver.

Here's the complete setup.

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    

The main part of the program reads some arguments from the command line creates the sequences and motifs, and calls ILP() to solve the problem. Each argument has a default value.

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}")

ILP is S-L-O-W for this type of problem. Here's an example for 10 sequences each of length 100. The output shows the position where the motif was planted, the planted motif, the motif predicted and the predicted location. The ILP finds the planted sites, but it took 27 minutes.

$ 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

This is not the way to solve the motif finding problem. For any realistic biological problem ILP is too slow, generates too many variables and constraints, and simply can't compete with modern methods.

All code can be found on GitHub.


Comments

Popular posts from this blog

Julia and the Blockchain

Filter Reads in Bam Files

SECD and Functional Lisp