我遇到了一个问题,找不到解决的方法。
输入/输出序列如下:
**input1 :** aaagctgctagag
**output1 :** a3gct2ag2
**input2 :** aaaaaaagctaagctaag
**output2 :** a6agcta2ag
输入的序列可以达到10^6个字符,最长连续模式将被考虑。
例如对于输入2 "agctaagcta",输出不会是"agcta2gcta",而是"agcta2"。
非常感谢您的帮助。
我遇到了一个问题,找不到解决的方法。
输入/输出序列如下:
**input1 :** aaagctgctagag
**output1 :** a3gct2ag2
**input2 :** aaaaaaagctaagctaag
**output2 :** a6agcta2ag
输入的序列可以达到10^6个字符,最长连续模式将被考虑。
例如对于输入2 "agctaagcta",输出不会是"agcta2gcta",而是"agcta2"。
非常感谢您的帮助。
算法说明:
为了找到它,我们将通过归纳法进行。我们要计算B(i+1),已知B(i),B(i-1),B(i-2),…,B(1),B(0),其中B(0)为空序列,B(1)=s(1)。同时,这也是证明解决方案最优的证明。;)
为了计算B(i+1),我们将从候选序列中选择最佳序列:
最后一块只有一个元素的候选序列:
B(i )s(i+1)1 B(i-1)s(i+1)2 ; 仅当s(i)=s(i+1)时 B(i-2)s(i+1)3 ; 仅当s(i-1)=s(i)且s(i)=s(i+1)时 … B(1)s(i+1)[i-1] ; 仅当s(2)=s(3)且s(3)=s(4)且…且s(i)=s(i+1)时 B(0)s(i+1)i = s(i+1)i ; 仅当s(1)=s(2)且s(2)=s(3)且…且s(i)=s(i+1)时
最后一块有2个元素的候选序列:
B(i-1)s(i)s(i+1)1 B(i-3)s(i)s(i+1)2 ; 仅当s(i-2)s(i-1)=s(i)s(i+1)时 B(i-5)s(i)s(i+1)3 ; 仅当s(i-4)s(i-3)=s(i-2)s(i-1)且s(i-2)s(i-1)=s(i)s(i+1)时 …
最后一块有3个元素的候选序列:
…
最后一块有4个元素的候选序列:
…
…
最后一块有n+1个元素的候选序列:
s(1)s(2)s(3)………s(i+1)
对于每个可能性,当序列块不再重复时,算法停止。这就是全部内容。
该算法的数据结构示例代码如下:
B(0) = “”
for (i=1; i<=N; i++) {
// Calculate all the candidates for B(i)
BestCandidate=null
for (j=1; j<=i; j++) {
Calculate all the candidates of length (i)
r=1;
do {
Candidadte = B([i-j]*r-1) s(i-j+1)…s(i-1)s(i) r
If ( (BestCandidate==null)
|| (Candidate is shorter that BestCandidate))
{
BestCandidate=Candidate.
}
r++;
} while ( ([i-j]*r <= i)
&&(s(i-j*r+1) s(i-j*r+2)…s(i-j*r+j) == s(i-j+1) s(i-j+2)…s(i-j+j))
}
B(i)=BestCandidate
}
希望这能再多帮助一些。
下面是执行所需任务的完整C程序。它运行的时间复杂度为O(n^2)。其中核心部分仅有30行代码。
编辑:我稍微改了下代码结构,更改了变量名并添加了一些注释以使其更易读。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
// This struct represents a compressed segment like atg4, g3, agc1
struct Segment {
char *elements;
int nElements;
int count;
};
// As an example, for the segment agagt3 elements would be:
// {
// elements: "agagt",
// nElements: 5,
// count: 3
// }
struct Sequence {
struct Segment lastSegment;
struct Sequence *prev; // Points to a sequence without the last segment or NULL if it is the first segment
int totalLen; // Total length of the compressed sequence.
};
// as an example, for the sequence agt32ta5, the representation will be:
// {
// lastSegment:{"ta" , 2 , 5},
// prev: @A,
// totalLen: 8
// }
// and A will be
// {
// lastSegment{ "agt", 3, 32},
// prev: NULL,
// totalLen: 5
// }
// This function converts a sequence to a string.
// You have to free the string after using it.
// The strategy is to construct the string from right to left.
char *sequence2string(struct Sequence *S) {
char *Res=malloc(S->totalLen + 1);
char *digits="0123456789";
int p= S->totalLen;
Res[p]=0;
while (S!=NULL) {
// first we insert the count of the last element.
// We do digit by digit starting with the units.
int C = S->lastSegment.count;
while (C) {
p--;
Res[p] = digits[ C % 10 ];
C /= 10;
}
p -= S->lastSegment.nElements;
strncpy(Res + p , S->lastSegment.elements, S->lastSegment.nElements);
S = S ->prev;
}
return Res;
}
// Compresses a dna sequence.
// Returns a string with the in sequence compressed.
// The returned string must be freed after using it.
char *dnaCompress(char *in) {
int i,j;
int N = strlen(in);; // Number of elements of a in sequence.
// B is an array of N+1 sequences where B(i) is the best compressed sequence sequence of the first i characters.
// What we want to return is B[N];
struct Sequence *B;
B = malloc((N+1) * sizeof (struct Sequence));
// We first do an initialization for i=0
B[0].lastSegment.elements="";
B[0].lastSegment.nElements=0;
B[0].lastSegment.count=0;
B[0].prev = NULL;
B[0].totalLen=0;
// and set totalLen of all the sequences to a very HIGH VALUE in this case N*2 will be enougth, We will try different sequences and keep the minimum one.
for (i=1; i<=N; i++) B[i].totalLen = INT_MAX; // A very high value
for (i=1; i<=N; i++) {
// at this point we want to calculate B[i] and we know B[i-1], B[i-2], .... ,B[0]
for (j=1; j<=i; j++) {
// Here we will check all the candidates where the last segment has j elements
int r=1; // number of times the last segment is repeated
int rNDigits=1; // Number of digits of r
int rNDigitsBound=10; // We will increment r, so this value is when r will have an extra digit.
// when r = 0,1,...,9 => rNDigitsBound = 10
// when r = 10,11,...,99 => rNDigitsBound = 100
// when r = 100,101,.,999 => rNDigitsBound = 1000 and so on.
do {
// Here we analitze a candidate B(i).
// where the las segment has j elements repeated r times.
int CandidateLen = B[i-j*r].totalLen + j + rNDigits;
if (CandidateLen < B[i].totalLen) {
B[i].lastSegment.elements = in + i - j*r;
B[i].lastSegment.nElements = j;
B[i].lastSegment.count = r;
B[i].prev = &(B[i-j*r]);
B[i].totalLen = CandidateLen;
}
r++;
if (r == rNDigitsBound ) {
rNDigits++;
rNDigitsBound *= 10;
}
} while ( (i - j*r >= 0)
&& (strncmp(in + i -j, in + i - j*r, j)==0));
}
}
char *Res=sequence2string(&(B[N]));
free(B);
return Res;
}
int main(int argc, char** argv) {
char *compressedDNA=dnaCompress(argv[1]);
puts(compressedDNA);
free(compressedDNA);
return 0;
}
ss
变量是什么意思。这个解决方案是否最优?直接给出这样一个解决方案对OP来说太容易了。他应该在论文中给你以功劳 :-))) - Boris Stitnickygcc
编译并自行获得压缩。如果您想继续对此问题感兴趣,可以尝试通过后缀树等方式从O(n ^ 2)过渡到O(n.log n)或线性时间。但在我看来,O(n ^ 2)已经足够好了。 - Boris Stitnickya = "aaagctgctagag"
,则序列位置坐标将从1到13运行。在序列位置3(字母'g')时,如果子序列大小为4,则子序列将为“gctg”。明白了吗?至于“片段数量”,则将a表示为“aaagctgctagag1”包含1个片段(序列本身)。将其表示为“a3gct2ag2”则包含3个片段。“aaagctgct1ag2”则包含2个片段。“a2a1ctg2ag2”将包含4个片段。明白了吗?现在,您可以开始填充一个13 x 13 x 13的三维数组,因此您的时间和内存复杂度似乎约为 n ** 3
。您确定可以处理数百万个碱基对的序列吗?我认为贪心方法可能更好,因为大型DNA序列不太可能完全重复。此外,我建议您将任务扩大到近似匹配,并且您可以直接在期刊上发表。a a a g c t g c t a g a g
1(a1) 1(a1) 1(a1) 1(g1) 1(c1) 1(t1) 1(g1) 1(c1) 1(t1) 1(a1) 1(g1) 1(a1) 1(g1)
这个数字是字符成本(对于这些简单的1个字符序列始终为1;数字1不计入字符成本),括号中的内容是压缩结果(也对于这种简单情况很容易)。第二行仍然很简单:
2(a2) 2(a2) 2(ag1) 2(gc1) 2(ct1) 2(tg1) 2(gc1) 2(ct1) 2(ta1) 2(ag1) 2(ga1) 2(ag1)
将2个字符序列分解为2个子序列只有一种方法--1个字符+1个字符。如果它们相同,结果就像a + a = a2
。如果它们不同,比如a + g
,那么因为只有1段序列是可接受的,结果不能是a1g1
,而必须是ag1
。第三行最终将更加有趣:
2(a3) 2(aag1) 3(agc1) 3(gct1) 3(ctg1) 3(tgc1) 3(gct1) 3(cta1) 3(tag1) 3(aga1) 3(gag1)
aag
可以被组合成 aa + g
或者 a + ag
。但是,我们不能有两个片段,比如 aa1g1
或者 a1ag1
,所以我们必须满足于 aag1
,除非两个组成部分由相同的字符组成,例如 aa + a
=> a3
,其中字符成本为2。我们可以继续到第四行:4(aaag1) 4(aagc1) 4(agct1) 4(gctg1) 4(ctgc1) 4(tgct1) 4(gcta1) 4(ctag1) 4(taga1) 3(ag2)
a3g1
,因为这一层只允许有 1 个片段。但是在最后一个位置,通过 ag1 + ag1 = ag2
可以将压缩成本降低到 3。这样,可以填满整个第一级表格,直到长度为 13 的单个子序列,并且每个子序列都具有其最优字符成本和其在第一级约束下的压缩关联。
然后你进入第二级,在这里允许有 2 个片段... 再次从底部向上,通过比较使用已计算位置组合子序列的所有可能方式,识别给定级别片段计数约束下的每个表格坐标的最优成本和压缩,直到完全填充表格并计算出全局最优解。还有一些细节需要解决,但抱歉,我不会为您编写代码。
n ** 4
,因为需要比较多个组合,甚至可能是更高的指数,最多达到5,我真的很懒得算。 - Boris Stitnicky在尝试自己的方法一段时间后,我对jbaylina的美妙算法和C实现表示赞赏。这是我在Haskell中尝试实现jbaylina算法的版本,并在下面进一步发展了我的线性时间算法的尝试,该算法试图以一对一的方式压缩包含重复模式的段:
import Data.Map (fromList, insert, size, (!))
compress s = (foldl f (fromList [(0,([],0)),(1,([s!!0],1))]) [1..n - 1]) ! n
where
n = length s
f b i = insert (size b) bestCandidate b where
add (sequence, sLength) (sequence', sLength') =
(sequence ++ sequence', sLength + sLength')
j' = [1..min 100 i]
bestCandidate = foldr combCandidates (b!i `add` ([s!!i,'1'],2)) j'
combCandidates j candidate' =
let nextCandidate' = comb 2 (b!(i - j + 1)
`add` ((take j . drop (i - j + 1) $ s) ++ "1", j + 1))
in if snd nextCandidate' <= snd candidate'
then nextCandidate'
else candidate' where
comb r candidate
| r > uBound = candidate
| not (strcmp r True) = candidate
| snd nextCandidate <= snd candidate = comb (r + 1) nextCandidate
| otherwise = comb (r + 1) candidate
where
uBound = div (i + 1) j
prev = b!(i - r * j + 1)
nextCandidate = prev `add`
((take j . drop (i - j + 1) $ s) ++ show r, j + length (show r))
strcmp 1 _ = True
strcmp num bool
| (take j . drop (i - num * j + 1) $ s)
== (take j . drop (i - (num - 1) * j + 1) $ s) =
strcmp (num - 1) True
| otherwise = False
输出:
*Main> compress "aaagctgctagag"
("a3gct2ag2",9)
*Main> compress "aaabbbaaabbbaaabbbaaabbb"
("aaabbb4",7)
线性时间尝试:
import Data.List (sortBy)
group' xxs sAccum (chr, count)
| null xxs = if null chr
then singles
else if count <= 2
then reverse sAccum ++ multiples ++ "1"
else singles ++ if null chr then [] else chr ++ show count
| [x] == chr = group' xs sAccum (chr,count + 1)
| otherwise = if null chr
then group' xs (sAccum) ([x],1)
else if count <= 2
then group' xs (multiples ++ sAccum) ([x],1)
else singles
++ chr ++ show count ++ group' xs [] ([x],1)
where x:xs = xxs
singles = reverse sAccum ++ (if null sAccum then [] else "1")
multiples = concat (replicate count chr)
sequences ws strIndex maxSeqLen = repeated' where
half = if null . drop (2 * maxSeqLen - 1) $ ws
then div (length ws) 2 else maxSeqLen
repeated' = let (sequence,(sequenceStart, sequenceEnd'),notSinglesFlag) = repeated
in (sequence,(sequenceStart, sequenceEnd'))
repeated = foldr divide ([],(strIndex,strIndex),False) [1..half]
equalChunksOf t a = takeWhile(==t) . map (take a) . iterate (drop a)
divide chunkSize b@(sequence,(sequenceStart, sequenceEnd'),notSinglesFlag) =
let t = take (2*chunkSize) ws
t' = take chunkSize t
in if t' == drop chunkSize t
then let ts = equalChunksOf t' chunkSize ws
lenTs = length ts
sequenceEnd = strIndex + lenTs * chunkSize
newEnd = if sequenceEnd > sequenceEnd'
then sequenceEnd else sequenceEnd'
in if chunkSize > 1
then if length (group' (concat (replicate lenTs t')) [] ([],0)) > length (t' ++ show lenTs)
then (((strIndex,sequenceEnd,chunkSize,lenTs),t'):sequence, (sequenceStart,newEnd),True)
else b
else if notSinglesFlag
then b
else (((strIndex,sequenceEnd,chunkSize,lenTs),t'):sequence, (sequenceStart,newEnd),False)
else b
addOne a b
| null (fst b) = a
| null (fst a) = b
| otherwise =
let (((start,end,patLen,lenS),sequence):rest,(sStart,sEnd)) = a
(((start',end',patLen',lenS'),sequence'):rest',(sStart',sEnd')) = b
in if sStart' < sEnd && sEnd < sEnd'
then let c = ((start,end,patLen,lenS),sequence):rest
d = ((start',end',patLen',lenS'),sequence'):rest'
in (c ++ d, (sStart, sEnd'))
else a
segment xs baseIndex maxSeqLen = segment' xs baseIndex baseIndex where
segment' zzs@(z:zs) strIndex farthest
| null zs = initial
| strIndex >= farthest && strIndex > 0 = ([],(0,0))
| otherwise = addOne initial next
where
next@(s',(start',end')) = segment' zs (strIndex + 1) farthest'
farthest' | null s = farthest
| otherwise = if start /= end && end > farthest then end else farthest
initial@(s,(start,end)) = sequences zzs strIndex maxSeqLen
areExclusive ((a,b,_,_),_) ((a',b',_,_),_) = (a' >= b) || (b' <= a)
combs [] r = [r]
combs (x:xs) r
| null r = combs xs (x:r) ++ if null xs then [] else combs xs r
| otherwise = if areExclusive (head r) x
then combs xs (x:r) ++ combs xs r
else if l' > lowerBound
then combs xs (x: reduced : drop 1 r) ++ combs xs r
else combs xs r
where lowerBound = l + 2 * patLen
((l,u,patLen,lenS),s) = head r
((l',u',patLen',lenS'),s') = x
reduce = takeWhile (>=l') . iterate (\x -> x - patLen) $ u
lenReduced = length reduce
reduced = ((l,u - lenReduced * patLen,patLen,lenS - lenReduced),s)
buildString origStr sequences = buildString' origStr sequences 0 (0,"",0)
where
buildString' origStr sequences index accum@(lenC,cStr,lenOrig)
| null sequences = accum
| l /= index =
buildString' (drop l' origStr) sequences l (lenC + l' + 1, cStr ++ take l' origStr ++ "1", lenOrig + l')
| otherwise =
buildString' (drop u' origStr) rest u (lenC + length s', cStr ++ s', lenOrig + u')
where
l' = l - index
u' = u - l
s' = s ++ show lenS
(((l,u,patLen,lenS),s):rest) = sequences
compress [] _ accum = reverse accum ++ (if null accum then [] else "1")
compress zzs@(z:zs) maxSeqLen accum
| null (fst segment') = compress zs maxSeqLen (z:accum)
| (start,end) == (0,2) && not (null accum) = compress zs maxSeqLen (z:accum)
| otherwise =
reverse accum ++ (if null accum || takeWhile' compressedStr 0 /= 0 then [] else "1")
++ compressedStr
++ compress (drop lengthOriginal zzs) maxSeqLen []
where segment'@(s,(start,end)) = segment zzs 0 maxSeqLen
combinations = combs (fst $ segment') []
takeWhile' xxs count
| null xxs = 0
| x == '1' && null (reads (take 1 xs)::[(Int,String)]) = count
| not (null (reads [x]::[(Int,String)])) = 0
| otherwise = takeWhile' xs (count + 1)
where x:xs = xxs
f (lenC,cStr,lenOrig) (lenC',cStr',lenOrig') =
let g = compare ((fromIntegral lenC + if not (null accum) && takeWhile' cStr 0 == 0 then 1 else 0) / fromIntegral lenOrig)
((fromIntegral lenC' + if not (null accum) && takeWhile' cStr' 0 == 0 then 1 else 0) / fromIntegral lenOrig')
in if g == EQ
then compare (takeWhile' cStr' 0) (takeWhile' cStr 0)
else g
(lenCompressed,compressedStr,lengthOriginal) =
head $ sortBy f (map (buildString (take end zzs)) (map reverse combinations))
输出:
*Main> compress "aaaaaaaaabbbbbbbbbaaaaaaaaabbbbbbbbb" 100 []
"a9b9a9b9"
*Main> compress "aaabbbaaabbbaaabbbaaabbb" 100 []
"aaabbb4"
divided = foldr divide [] [div lenOne 2, div lenOne 2 - 1..2]
更改为 divided = foldr divide [] [2..div lenOne 2]
,现在它显示 aaabbb4
。但是这种更改会导致其他不准确性吗? - גלעד ברקן
aabbaabb
,需要提供的输出是两种可能性之一:a2b2a2b2
或aabb2
。 - Egor Skriptunoffaaagctgctxyzagag
?答案:无法确定,因为没有提供更多上下文或要求。需要知道使用什么编码方式和目的是什么才能回答这个问题。 - גלעד ברקן