I'd like to align two sequences of words together in order to get the best rapidfuzz ratio score. For example, sequence 1 could be ['Anyway', 'thatShould', 'dow', 'inform'] and sequence 2 be ['ANYWAY,', 'THAT', 'SHOULD', 'DO', 'FOR']. 'Trusting' the position of sequence 1, even if it may be wrong for now, I'd like the function to note that sequence 2' aligned word indices should be [0, 1, 1, 2, 3], because 'that should' aligns best with 'thatShould'. How can I do this
Assistant
To align two sequences of words and compute the best alignment based on the rapidfuzz ratio score, you can use dynamic programming to find the optimal alignment. Here's a Python function that does this:
python
import rapidfuzz
from typing import List, Tuple
def align_sequences(seq1: List[str], seq2: List[str]) -> Tuple[List[str], List[int]]:
"""
Aligns two sequences of words to maximize the rapidfuzz ratio score.
Returns the aligned sequences and the indices mapping from seq2 to seq1.
Args:
seq1: First sequence of words.
seq2: Second sequence of words.
Returns:
Tuple of two lists: The first list is the aligned sequence from seq1, and the second list is the indices of aligned words in seq2.
"""
# Initialize dynamic programming table
n = len(seq1)
m = len(seq2)
dp = [[0] * (m + 1) for _ in range(n + 1)]
parent = [[None] * (m + 1) for _ in range(n + 1)]
# Fill the dynamic programming table
for i in range(1, n + 1):
for j in range(1, m + 1):
if seq1[i - 1] == seq2[j - 1]:
score = dp[i - 1][j - 1] + 1
parent[i][j] = (i - 1, j - 1)
else:
score = max(dp[i - 1][j], dp[i][j - 1])
if dp[i - 1][j] > dp[i][j - 1]:
parent[i][j] = (i - 1, j)
else:
parent[i][j] = (i, j - 1)
dp[i][j] = score
# Reconstruct the aligned sequences
aligned_seq1 = []
aligned_seq2_indices = []
i, j = n, m
while i > 0 or j > 0:
if parent[i][j] is None:
break
pi, pj = parent[i][j]
if pi == i - 1 and pj == j - 1:
aligned_seq1.append(seq1[i - 1])
aligned_seq2_indices.append(j - 1)
i -= 1
j -= 1
elif pi == i - 1:
aligned_seq1.append(seq1[i - 1])
aligned_seq2_indices.append(None)
i -= 1
else:
aligned_seq1.append(None)
aligned_seq2_indices.append(j - 1)
j -= 1
aligned_seq1.reverse()
aligned_seq2_indices.reverse()
return aligned_seq1, aligned_seq2_indices
# Example usage
seq1 = ['Anyway', 'thatShould', 'dow', 'inform']
seq2 = ['ANYWAY,', 'THAT', 'SHOULD', 'DO', 'FOR']
aligned_seq1, aligned_indices = align_sequences(seq1, seq2)
print("Aligned sequence 1:", aligned_seq1)
print("Aligned indices in sequence 2:", aligned_indices)
This function uses dynamic programming to find the optimal alignment between two sequences, considering both insertions and deletions. The aligned_seq2_indices list contains the indices of the aligned words in seq2, or None if there is no corresponding word in seq1.