Skip to content

Commit 4b67f9a

Browse files
committed
Add test program for testing q_shuffle function
Add the test program that invoke the q_shuffle command to test q_shuffle.The program simulates one million shuffle operations, collects the output, and computes the chi-square sum to assess the uniformity of the distribution. Change-Id: I3e619f0267b52b93c934c2682c28cc66c754ea62
1 parent c2296b3 commit 4b67f9a

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

test_shuffle.py

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#!/usr/bin/env python3
2+
3+
import subprocess
4+
import re
5+
import random
6+
from itertools import permutations
7+
import random
8+
import matplotlib.pyplot as plt
9+
import numpy as np
10+
11+
# 測試 shuffle 次數
12+
test_count = 1000000
13+
input = "new\nit 1\nit 2\nit 3\nit 4\n"
14+
for i in range(test_count):
15+
input += "shuffle\n"
16+
input += "free\nquit\n"
17+
18+
# 取得 stdout 的 shuffle 結果
19+
print("Start testing")
20+
command = './qtest -v 3'
21+
clist = command.split()
22+
completedProcess = subprocess.run(
23+
clist, capture_output=True, text=True, input=input)
24+
s = completedProcess.stdout
25+
startIdx = s.find("l = [1 2 3 4]")
26+
endIdx = s.find("l = NULL")
27+
s = s[startIdx + 14: endIdx]
28+
Regex = re.compile(r'\d \d \d \d')
29+
result = Regex.findall(s)
30+
31+
32+
def permute(nums):
33+
nums = list(permutations(nums, len(nums)))
34+
return nums
35+
36+
37+
def chiSquared(observation, expectation):
38+
return ((observation - expectation) ** 2) / expectation
39+
40+
41+
# shuffle 的所有結果
42+
nums = []
43+
for i in result:
44+
nums.append(i.split())
45+
46+
# 找出全部的排序可能
47+
counterSet = {}
48+
shuffle_array = ['1', '2', '3', '4']
49+
s = permute(shuffle_array)
50+
51+
# 初始化 counterSet
52+
for i in range(len(s)):
53+
w = ''.join(s[i])
54+
counterSet[w] = 0
55+
56+
# 計算每一種 shuffle 結果的數量
57+
for num in nums:
58+
permutation = ''.join(num)
59+
counterSet[permutation] += 1
60+
61+
# 計算 chiSquare sum
62+
expectation = test_count // len(s)
63+
c = counterSet.values()
64+
chiSquaredSum = 0
65+
for i in c:
66+
chiSquaredSum += chiSquared(i, expectation)
67+
print("Expectation: ", expectation)
68+
print("Observation: ", counterSet)
69+
print("chi square sum: ", chiSquaredSum)
70+
71+
x = np.arange(len(c))
72+
plt.bar(x, c)
73+
plt.xticks(x, list(counterSet.keys()))
74+
plt.xlabel('permutations')
75+
plt.ylabel('counts')
76+
plt.title('Shuffle result')
77+
plt.show()

0 commit comments

Comments
 (0)