【问题标题】:What is the best way to find the period of a (repeating) list in Mathematica?在 Mathematica 中查找(重复)列表周期的最佳方法是什么?
【发布时间】:2011-11-18 00:56:17
【问题描述】:

在重复列表中查找句点的最佳方法是什么?

例如:

a = {4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2}

重复了{4, 5, 1, 2, 3},其余的{4, 5, 1, 2}匹配,但不完整。

算法应该足够快以处理更长的情况,如下所示:

b = RandomInteger[10000, {100}];
a = Join[b, b, b, b, Take[b, 27]]

如果没有像上面这样的重复模式,算法应该返回$Failed。

【问题讨论】:

  • 我的第一种方法是使用FindSequenceFunction[a],但后来我想不出一种以编程方式确定周期的好方法。
  • 感谢您迄今为止的回复。看起来@Szabolcs 解决方案是最好的解决方案。我仍在研究自己的独立解决方案,但速度仍然是原来的两倍。
  • 维基百科上有一篇关于Cycle Detection的文章,我相信是相关的。

标签: algorithm wolfram-mathematica


【解决方案1】:

请查看穿插代码的 cmets 了解其工作原理。

(* True if a has period p *)
testPeriod[p_, a_] := Drop[a, p] === Drop[a, -p]

(* are all the list elements the same? *)
homogeneousQ[list_List] := Length@Tally[list] === 1
homogeneousQ[{}] := Throw[$Failed] (* yes, it's ugly to put this here ... *)

(* auxiliary for findPeriodOfFirstElement[] *)
reduce[a_] := Differences@Flatten@Position[a, First[a], {1}]

(* the first element occurs every ?th position ? *)
findPeriodOfFirstElement[a_] := Module[{nl},
  nl = NestWhileList[reduce, reduce[a], ! homogeneousQ[#] &];
  Fold[Total@Take[#2, #1] &, 1, Reverse[nl]]
  ]

(* the period must be a multiple of the period of the first element *)
period[a_] := Catch@With[{fp = findPeriodOfFirstElement[a]},
   Do[
    If[testPeriod[p, a], Return[p]],
    {p, fp, Quotient[Length[a], 2], fp}
    ]
   ]

如果findPeriodOfFirstElement[]不清楚,请询问。我是独立完成的(为了好玩!),但现在我看到原理与 Verbeia 的解决方案相同,除了 Brett 指出的问题已修复。

我正在测试

b = RandomInteger[100, {1000}];
a = Flatten[{ConstantArray[b, 1000], Take[b, 27]}];

(注意低整数值:同一周期内会有很多重复元素*)


编辑:根据下面Leonid 的评论,通过使用专门为整数列表编译的自定义位置函数,可以实现另外 2-3 倍的加速(在我的机器上约为 2.4 倍) :

(* Leonid's reduce[] *)

myPosition = Compile[
  {{lst, _Integer, 1}, {val, _Integer}}, 
  Module[{pos = Table[0, {Length[lst]}], i = 1, ctr = 0}, 
    For[i = 1, i <= Length[lst], i++, 
      If[lst[[i]] == val, pos[[++ctr]] = i]
    ]; 
    Take[pos, ctr]
  ], 
  CompilationTarget -> "C", RuntimeOptions -> "Speed"
]

reduce[a_] := Differences@myPosition[a, First[a]]

编译 testPeriod 在快速测试中可以进一步提高约 20% 的速度,但我相信这将取决于输入数据:

Clear[testPeriod]
testPeriod = 
 Compile[{{p, _Integer}, {a, _Integer, 1}}, 
  Drop[a, p] === Drop[a, -p]]

【讨论】:

  • 经过一番思考,我相信在实际使用中定义homogeneousQ[{x_ ..}] = True等会更好。
  • @Mr.Wizard 这是一回事,另一个是哪个算法更快取决于数据中的模式(唯一元素的数量、它们的分布等)。对于我上面的测试数据,我的版本使用这个 testPeriod 函数比你的快 2 倍,但对于其他数据可能不是。对于此数据,Length@Tally@list 比 Union@Tally@list 快,但对于其他类型的数据则不然。是的,我实际上想问一下homogeneousQ 有哪些替代方案:)
  • @Mr.W 我一直把 testPeriod 复杂化了。查看我的编辑。
  • @Szabolcs 事实证明,代码中的主要瓶颈之一是对Flatten[Position[...]] 的调用。如果您将其替换为对如下自定义位置函数的调用:myPosition = Compile[{{lst, _Integer, 1}, {val, _Integer}}, Module[{pos = Table[0, {Length[lst]}], i = 1, ctr = 0}, For[i = 1, i &lt;= Length[lst], i++, If[lst[[i]] == val, pos[[++ctr]] = i]]; Take[pos, ctr]], CompilationTarget -&gt; "C", RuntimeOptions -&gt; "Speed"],您将获得另外 2-3 倍的加速:reduce[a_] := Differences@myPosition[a, First[a]]。
  • @Szabolcs “凭直觉”。说实话,我早就知道Position不是最适合机器类型的,而上面这个自定义功能我已经在不同的设置下使用过很多次了。另一种稍慢但仍然非常快且不使用编译为 C 的方法归功于 Norbert Pozar 并使用 SparseArrays:extractPositionFromSparseArray[HoldPattern[SparseArray[u___]]]:= {u}[[4, 2, 2]];positionExtr[x_List, n_] := Flatten @ extractPositionFromSparseArray[SparseArray[Unitize[x - n], Automatic, 1]]。我实际上从不使用 WB 分析器,这可能是一个错误。
【解决方案2】:

如果没有噪音,上述方法会更好。如果您的信号只是近似的,那么傅里叶变换方法可能会很有用。我将使用“参数化”设置进行说明,其中基本信号的长度和重复次数、尾随部分的长度以及噪声扰动的界限都是可以使用的变量。

noise = 20;
extra = 40;
baselen = 103;
base = RandomInteger[10000, {baselen}];
repeat = 5;
signal = Flatten[Join[ConstantArray[base, repeat], Take[base, extra]]];
noisysignal = signal + RandomInteger[{-noise, noise}, Length[signal]];

我们计算 FFT 的绝对值。我们将零连接到两端。该对象将通过与邻居进行比较来达到阈值。

sigfft = Join[{0.}, Abs[Fourier[noisysignal]], {0}];

现在我们创建两个 0-1 向量。在一个中,我们通过为 fft 中的每个元素设置一个 1 来设置阈值,该值大于其两个邻居的几何平均值的两倍。在另一个我们使用平均值(算术平均值),但我们将大小限制降低到 3/4。这是基于一些实验。我们计算每种情况下 1 的数量。理想情况下,我们会为每个得到 100,因为这将是在没有噪音和尾部的“完美”情况下非零的数量。

In[419]:= 
thresh1 = 
  Table[If[sigfft[[j]]^2 > 2*sigfft[[j - 1]]*sigfft[[j + 1]], 1, 
    0], {j, 2, Length[sigfft] - 1}];
count1 = Count[thresh1, 1]
thresh2 = 
  Table[If[sigfft[[j]] > 3/4*(sigfft[[j - 1]] + sigfft[[j + 1]]), 1, 
    0], {j, 2, Length[sigfft] - 1}];
count2 = Count[thresh2, 1]

Out[420]= 114

Out[422]= 100

现在,我们通过计算总长度的下限与我们的计数的平均值对“重复”的值进行最佳猜测。

approxrepeats = Floor[2*Length[signal]/(count1 + count2)]
Out[423]= 5

所以我们发现基本信号重复了 5 次。这可以开始精炼以估计正确的长度(baselen,上文)。为此,我们可能会尝试在最后删除元素,并查看何时让 fft 更接近实际在非零值之间运行四个 0。

可能用于估计重复次数的其他方法是在阈值 ffts 的运行长度编码中找到零的模态数。虽然我实际上并没有尝试过,但看起来它可能对在阈值处理方式的细节方面的错误选择具有鲁棒性(我的只是似乎有效的实验)。

丹尼尔·利希特布劳

【讨论】:

  • 这也是我本能地想到的,但无法可靠地工作。所以+1
【解决方案3】:

以下假设循环从第一个元素开始,并给出周期长度和循环。

findCyclingList[a_?VectorQ] :=
  Module[{repeats1, repeats2, cl, cLs, vec}, 
  repeats1 = Flatten@Differences[Position[a, First[a]]];
  repeats2 = Flatten[Position[repeats1, First[repeats1]]]; 
  If[Equal @@ Differences[repeats2] && Length[repeats2] > 2(* 
   is potentially cyclic - first element appears cyclically *),
   cl = Plus @@@ Partition[repeats1, First[Differences[repeats2]]];
   cLs = Partition[a, First[cl]];
   If[SameQ @@ cLs  (* candidate cycles all actually the same *), 
    vec = First[cLs];
    {Length[vec], vec}, $Failed], $Failed]  ]

测试

b = RandomInteger[50, {100}];
a = Join[b, b, b, b, Take[b, 27]];

findCyclingList[a]

{100, {47, 15, 42, 10, 14, 29, 12, 29, 11, 37, 6, 19, 14, 50, 4, 38, 
  23, 3, 41, 39, 41, 17, 32, 8, 18, 37, 5, 45, 38, 8, 39, 9, 26, 33, 
  40, 50, 0, 45, 1, 48, 32, 37, 15, 37, 49, 16, 27, 36, 11, 16, 4, 28,
   31, 46, 30, 24, 30, 3, 32, 31, 31, 0, 32, 35, 47, 44, 7, 21, 1, 22,
   43, 13, 44, 35, 29, 38, 31, 31, 17, 37, 49, 22, 15, 28, 21, 8, 31, 
  42, 26, 33, 1, 47, 26, 1, 37, 22, 40, 27, 27, 16}}

b1 = RandomInteger[10000, {100}]; 
a1 = Join[b1, b1, b1, b1, Take[b1, 23]];

findCyclingList[a1]

{100, {1281, 5325, 8435, 7505, 1355, 857, 2597, 8807, 1095, 4203, 
  3718, 3501, 7054, 4620, 6359, 1624, 6115, 8567, 4030, 5029, 6515, 
  5921, 4875, 2677, 6776, 2468, 7983, 4750, 7609, 9471, 1328, 7830, 
  2241, 4859, 9289, 6294, 7259, 4693, 7188, 2038, 3994, 1907, 2389, 
  6622, 4758, 3171, 1746, 2254, 556, 3010, 1814, 4782, 3849, 6695, 
  4316, 1548, 3824, 5094, 8161, 8423, 8765, 1134, 7442, 8218, 5429, 
  7255, 4131, 9474, 6016, 2438, 403, 6783, 4217, 7452, 2418, 9744, 
  6405, 8757, 9666, 4035, 7833, 2657, 7432, 3066, 9081, 9523, 3284, 
  3661, 1947, 3619, 2550, 4950, 1537, 2772, 5432, 6517, 6142, 9774, 
  1289, 6352}}

这种情况应该失败,因为它不是周期性的。

findCyclingList[Join[b, Take[b, 11], b]]

$Failed

我尝试使用Repeated 做一些事情,例如a /. Repeated[t__, {2, 100}] -&gt; {t} 但它对我不起作用。

【讨论】:

  • 第一个If 语句中的检查会导致您在一个周期内多次出现第一个元素时返回$Failed,例如:{1, 2, 3, 1, 2, 1, 2, 3, 1, 2, 1, 2, 3, 1, 2, 1, 2, 3, 1, 2}。我认为您需要检查差异列表本身是周期性的。
  • 哦,好点子 - 我现在不知道如何解决这个问题
  • 这个修改版应该会更好
  • @Verbeia a /. {Repeated[k__, {2, Infinity}], Shortest[f___]} -&gt; {{k}} 工作但太慢了
【解决方案4】:

这对你有用吗?

period[a_] := 
   Quiet[Check[
      First[Cases[
         Table[
            {k, Equal @@ Partition[a, k]}, 
            {k, Floor[Length[a]/2]}], 
         {k_, True} :> k
         ]], 
      $Failed]]

严格来说,这样的事情会失败

a = {1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 5}

虽然这可以通过以下方式解决:

(Equal @@ Partition[a, k]) && (Equal @@ Partition[Reverse[a], k])

(可能只提前计算一次Reverse[a]。)

【讨论】:

    【解决方案5】:

    我提出这个建议。它借鉴了 Verbeia 和 Brett 的答案。

    Do[
      If[MatchQ @@ Equal @@ Partition[#, i, i, 1, _], Return @@ i],
      {i, #[[ 2 ;; Floor[Length@#/2] ]] ~Position~ First@#}
    ] /. Null -> $Failed &
    

    它在长周期上不如 Vebeia 的功能高效,但在短周期上更快,而且更简单。

    【讨论】:

    • +1 用于创意周期测试功能、简单性和(潜在)速度。如果实际进行周期测试,您的瓶颈。使用更快的(比如我使用的丑陋的),这也是最快的解决方案。我显然把事情复杂化了:-)
    • @Szabolcs,高效的东西不可能是丑陋的。 (别管其他的了,我现在明白了。)
    【解决方案6】:

    我不知道如何在数学中解决它,但是以下算法(用 python 编写)应该可以工作。它是 O(n),所以不用担心速度。

    def period(array):
        if len(array) == 0:
            return False
        else:
            s = array[0]
            match = False
            end = 0
            i = 0
    
            for k in range(1,len(array)):
                c = array[k]
    
                if not match:
                    if c == s:
                        i = 1
                        match = True
                        end = k
                else:
                    if not c == array[i]:
                        match = False
                    i += 1
    
            if match:
                return array[:end]
            else:
                return False
    
    # False         
    print(period([4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2,1]))
    # [4, 5, 1, 2, 3]            
    print(period([4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2]))
    # False
    print(period([4]))
    # [4, 2]
    print(period([4,2,4]))
    # False
    print(period([4,2,1]))
    # False
    print(period([]))
    

    【讨论】:

      【解决方案7】:

      好吧,在这里展示我自己的作品:

      ModifiedTortoiseHare[a_List] := Module[{counter, tortoise, hare},
      Quiet[
       Check[
        counter = 1;
        tortoise = a[[counter]];
        hare = a[[2 counter]];
        While[(tortoise != hare) || (a[[counter ;; 2 counter - 1]] != a[[2 counter ;; 3 counter - 1]]),
         counter++;
         tortoise = a[[counter]];
         hare = a[[2 counter]];
        ];
       counter,
      $Failed]]]
      

      我不确定这是否 100% 正确,尤其是对于像 {pattern,pattern,different,pattern,pattern} 这样的情况,当有很多重复元素时,它会变得越来越慢,如下所示:

      { 1,2,1,1, 1,2,1,1, 1,2,1,1, ...} 
      

      因为它进行了太多昂贵的比较。

      【讨论】:

        【解决方案8】:
        #include <iostream>
        #include <vector>
        using namespace std;
        
        
        int period(vector<int> v)
        {
            int p=0; // period 0
        
            for(int i=p+1; i<v.size(); i++)
            {
        
                if(v[i] == v[0])
                {
                    p=i; // new potential period
        
        
                    bool periodical=true;
                    for(int i=0; i<v.size()-p; i++)
                    {
                        if(v[i]!=v[i+p])
                        {
                            periodical=false;
                            break;
                        }
                    }
                    if(periodical) return p;
        
        
                    i=p; // try to find new period
                }
            }
        
            return 0; // no period
        
        }
        
        
        int main()
        {
        
            vector<int> v3{1,2,3,1,2,3,1,2,3};
            cout<<"Period is :\t"<<period(v3)<<endl;
        
        
            vector<int> v0{1,2,3,1,2,3,1,9,6};
            cout<<"Period is :\t"<<period(v0)<<endl;
        
            vector<int> v1{1,2,1,1,7,1,2,1,1,7,1,2,1,1};
            cout<<"Period is :\t"<<period(v1)<<endl;
            return 0;
        }
        

        【讨论】:

        • 还有一些解释
        【解决方案9】:

        这听起来可能与sequence alignment 有关。这些算法经过深入研究,可能已经在数学中实现。

        【讨论】:

          猜你喜欢
          • 2012-07-30
          • 1970-01-01
          • 1970-01-01
          • 2011-07-10
          • 2010-10-14
          • 1970-01-01
          • 2010-09-16
          • 2011-09-16
          • 2015-10-13
          相关资源
          最近更新 更多