5D Library › 双人相位耦合、双线性相容张量与时空网格博弈 · English

第五章 洛书、八门与置换群

九宫是一个有限集合

奇门遁甲、九宫飞星一类的择时择向方法,都在同一张三乘三的网格上操作:九个宫位,每个宫位有一个洛书数,外圈八宫依次排着八门,随时间转动或「飞」动。去掉名称以后,这些操作都是同一种数学对象:九个位置上的置换。本章把它们写成置换,看这些置换生成什么样的群、保持什么、破坏什么。

洛书在对称意义下唯一

洛书是一个三阶幻方:1 到 9 九个数排成三行三列,每行、每列与两条对角线之和都是 15。

推导

中心必为 5。 过中心的四条线(中行、中列、两条对角线)合起来,恰好把除中心以外的八个数各用一次,中心用四次。四条线之和为 4×15=604 \times 15 = 60,又等于 45+3c45 + 3c(cc 为中心数),所以 c=5c = 5。

第十段程序检查全部 9!=362,8809! = 362{,}880 种排法,并执行杨辉的构造法。

推导

# Chapter 5. The Luoshu square: enumeration and Yang Hui's rule.
# A 3 x 3 normal magic square holds 1..9 with every row, column and both
# diagonals summing to 15. The program (1) checks all 9! = 362,880
# arrangements, (2) shows that the solutions are the 8 images of one square
# under the symmetries of the square (4 rotations, 4 reflections: the
# dihedral group D4), (3) counts the "semi-magic" arrangements (rows and
# columns only), and (4) carries out Yang Hui's rule of 1275 on a diamond:
# "nine numbers in slanting rows; exchange top and bottom; exchange left and
# right; the four corners step out".
from itertools import permutations

LINES = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8),
         (0, 4, 8), (2, 4, 6)]

def magic(sq, lines=LINES):
    return all(sq[a] + sq[b] + sq[c] == 15 for a, b, c in lines)

def rot(sq):
    return tuple(sq[i] for i in (6, 3, 0, 7, 4, 1, 8, 5, 2))

def flip(sq):
    return tuple(sq[i] for i in (2, 1, 0, 5, 4, 3, 8, 7, 6))

def d4(sq):
    out, s = set(), sq
    for _ in range(4):
        out.add(s)
        out.add(flip(s))
        s = rot(s)
    return out

def show(sq):
    return " / ".join(" ".join(str(v) for v in sq[r * 3:r * 3 + 3])
                      for r in range(3))

if __name__ == "__main__":
    sols = [p for p in permutations(range(1, 10)) if magic(p)]
    semi = sum(magic(p, LINES[:6]) for p in permutations(range(1, 10)))
    print("   magic squares among 362,880 arrangements: {}".format(len(sols)))
    print("   centre value in every one: {}".format(
        sorted({s[4] for s in sols})))
    print("   all 8 are D4 images of one square: {}".format(
        set(sols) == d4(sols[0])))
    print("   semi-magic (rows and columns only): {}".format(semi))
    # Yang Hui on a 5 x 5 board, (row, col) -> number
    board = {(0, 2): 1, (1, 1): 4, (1, 3): 2, (2, 0): 7, (2, 2): 5,
             (2, 4): 3, (3, 1): 8, (3, 3): 6, (4, 2): 9}
    board[(0, 2)], board[(4, 2)] = board[(4, 2)], board[(0, 2)]
    board[(2, 0)], board[(2, 4)] = board[(2, 4)], board[(2, 0)]
    moved = {(1, 2): board.pop((0, 2)), (3, 2): board.pop((4, 2)),
             (2, 1): board.pop((2, 0)), (2, 3): board.pop((2, 4))}
    board.update(moved)
    yang = tuple(board[(r, c)] for r in (1, 2, 3) for c in (1, 2, 3))
    print("   Yang Hui's rule gives  {}   magic: {}".format(
        show(yang), magic(yang)))
    print("   (nine on top, one below, three left, seven right)")
    print("\nReading: up to the eight symmetries of the square there is")
    print("exactly one 3 x 3 magic square, and its centre is forced to be 5")
    print("(the four lines through the centre use every number once plus the")
    print("centre three more times: 4 x 15 = 45 + 3c). Yang Hui's four moves")
    print("produce it directly.")
#    magic squares among 362,880 arrangements: 8
#    centre value in every one: [5]
#    all 8 are D4 images of one square: True
#    semi-magic (rows and columns only): 72
#    Yang Hui's rule gives  4 9 2 / 3 5 7 / 8 1 6   magic: True
#    (nine on top, one below, three left, seven right)
#
# Reading: up to the eight symmetries of the square there is
# exactly one 3 x 3 magic square, and its centre is forced to be 5
# (the four lines through the centre use every number once plus the
# centre three more times: 4 x 15 = 45 + 3c). Yang Hui's four moves
# produce it directly.

三阶幻方一共只有 8 个,中心都是 5,而且 8 个彼此都是正方形对称群(四个旋转、四个反射,记为 D4D_4)的像。换言之,在对称意义下三阶幻方只有一个,就是洛书。只要求行与列(不要求对角线)的「半幻方」则有 72 个。

原典

杨辉《续古摘奇算法》(1275)的构造法。 通行的引文为:

九子斜排,上下對易,左右相更,四維挺出。

并以「戴九履一,左三右七,二四为肩,六八为足」描述结果 (Cammann 1960; Swetz 2008)。程序把它执行为:把 1 到 9 斜排成菱形,交换上下两端(1 与 9),交换左右两端(7 与 3),再让四个角上的数补入正方形的四个角——得到 4 9 2 / 3 5 7 / 8 1 6,即洛书。

注

文本核对。 《续古摘奇算法》成书于 1275 年,其中给出纵横图的构造规则;上面十六字的口诀已据《宜稼堂丛书》本《杨辉算法》核对一致。

两种动作:飞宫与转盘

九宫上有两种传统的动作。飞宫:第 nn 宫的内容移到第 n+1n+1 宫(9 回到 1),路径按洛书数的顺序穿过中宫,阳遁顺飞、阴遁逆飞。转盘:外圈八宫按坎、艮、震、巽、离、坤、兑、乾(洛书数 1、8、3、4、9、2、7、6)的环序,每个时段把内容传给下一宫,中宫不动;八门「休生伤杜景死惊开」就是这样转动的。

九宫与八门:格中大数为洛书数,小字为八门的初始位置(蓝色为传统所称的三吉门,灰色为其余五门);金色箭头为转盘的环序。

第十一段程序把两种动作写成九个位置上的置换 ff(飞宫)与 rr(转盘),计算它们的阶与奇偶性、哪些幂保持幻方,并用广度优先搜索求出两者生成的群。

推导

# Chapter 5. Two motions on the nine palaces as permutations.
# Cells 0..8 are read row by row with south on top, and the Luoshu numbers
# sit on them as 4 9 2 / 3 5 7 / 8 1 6. Two traditional motions:
#   f  "flying palaces": whatever stands on palace n moves to palace n + 1
#      (9 back to 1) - a 9-cycle through the centre, in Luoshu order;
#   r  "turning the ring": the eight outer palaces in the ring order
#      1 8 3 4 9 2 7 6 (Kan, Gen, Zhen, Xun, Li, Kun, Dui, Qian) each pass
#      their content one step on; the centre stays.
# The program reports each motion's order and parity, which powers keep the
# square magic, whether the motions commute, and the size of the group the
# two generate (breadth-first closure over all products).
L = (4, 9, 2, 3, 5, 7, 8, 1, 6)
CELL_OF = {n: L.index(n) for n in range(1, 10)}
RING = [CELL_OF[n] for n in (1, 8, 3, 4, 9, 2, 7, 6)]

def perm_from_map(m):
    return tuple(m[i] for i in range(9))       # content of i goes to m[i]

F = perm_from_map({CELL_OF[n]: CELL_OF[n % 9 + 1] for n in range(1, 10)})
R = perm_from_map({**{RING[i]: RING[(i + 1) % 8] for i in range(8)},
                   CELL_OF[5]: CELL_OF[5]})

def compose(p, q):            # first p, then q
    return tuple(q[p[i]] for i in range(9))

def apply(p, sq):
    out = [0] * 9
    for i in range(9):
        out[p[i]] = sq[i]
    return tuple(out)

def order(p):
    k, q = 1, p
    while q != tuple(range(9)):
        q, k = compose(q, p), k + 1
    return k

def parity(p):
    seen, s = set(), 0
    for i in range(9):
        if i in seen:
            continue
        j, n = i, 0
        while j not in seen:
            seen.add(j)
            j, n = p[j], n + 1
        s += n - 1
    return "even" if s % 2 == 0 else "odd"

def is_magic(sq):
    lines = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7),
             (2, 5, 8), (0, 4, 8), (2, 4, 6)]
    return all(sq[a] + sq[b] + sq[c] == 15 for a, b, c in lines)

def powers_magic(p):
    out, q = [], p
    for k in range(1, order(p)):
        if is_magic(apply(q, L)):
            out.append(k)
        q = compose(q, p)
    return out

if __name__ == "__main__":
    for name, p in (("f (flying)", F), ("r (ring)", R)):
        print("   {:11s} order {}  {}  magic after powers {}".format(
            name, order(p), parity(p), powers_magic(p)))
    print("   f then r equals r then f: {}".format(
        compose(F, R) == compose(R, F)))
    seen, frontier = {tuple(range(9))}, [tuple(range(9))]
    while frontier:
        nxt = []
        for p in frontier:
            for g in (F, R):
                q = compose(p, g)
                if q not in seen:
                    seen.add(q)
                    nxt.append(q)
        frontier = nxt
    magic_count = sum(is_magic(apply(p, L)) for p in seen)
    print("   group generated by f and r: {:,} arrangements".format(
        len(seen)))
    print("   of which magic squares: {}".format(magic_count))
    print("\nReading: turning the ring by two steps is a quarter-turn of")
    print("the square and keeps it magic; flying the palaces never does.")
    print("The two motions do not commute, and together they reach all 9!")
    print("arrangements: the traditional moves generate the full symmetric")
    print("group, of which only 8 elements keep the square magic.")
#    f (flying)  order 9  even  magic after powers []
#    r (ring)    order 8  odd  magic after powers [2, 4, 6]
#    f then r equals r then f: False
#    group generated by f and r: 362,880 arrangements
#    of which magic squares: 8
#
# Reading: turning the ring by two steps is a quarter-turn of
# the square and keeps it magic; flying the palaces never does.
# The two motions do not commute, and together they reach all 9!
# arrangements: the traditional moves generate the full symmetric
# group, of which only 8 elements keep the square magic.

飞宫 ff 是一个 9-循环,阶为 9,是偶置换;它的任何非平凡幂都不保持幻方——九宫飞星的每一张「飞」出来的盘都不是幻方。转盘 rr 是外圈上的 8-循环,阶为 8,是奇置换;它的 2、4、6 次幂分别是正方形的四分之一转、半转与四分之三转,所以保持幻方,奇数次幂则把边宫与角宫互换,破坏幻方。

两种动作不交换:先飞后转与先转后飞结果不同。更重要的是最后两行:ff 与 rr 合起来生成了全部 362,880 种排列,即九个元素上的完全对称群 S9S_9;其中保持幻方的只有 8 种。这有一个直接的推论:如果一套规则允许任意组合飞宫与转盘,那么从洛书出发,任何排列都可以到达;规则体系的约束力全部来自它规定的组合顺序,而不是来自这两种动作本身。

小结

三阶幻方在对称意义下只有一个,即洛书,中心必为 5,杨辉的四步构造法直接给出它。飞宫是九个位置上的 9-循环,从不保持幻方;转盘是外圈的 8-循环,转两步就是正方形的四分之一转,保持幻方。两种动作不交换,合起来生成九个元素的完全对称群,共 362,880 个元素,其中只有 8 个保持幻方:传统规则的结构全部在于它如何限定动作的组合。

参考文献

Cammann, Schuyler. 1960. “The Evolution of Magic Squares in China.” Journal of the American Oriental Society 80 (2): 116–24.
Swetz, Frank J. 2008. Legacy of the Luoshu: The 4,000 Year Search for the Meaning of the Magic Square of Order Three. A K Peters.

Fan, Y. (2026). Dyadic Phase Coupling, Bilinear Compatibility Tensors and Spatiotemporal Grid Games: Asymmetric Kuramoto Locking, Stopping-Time Separation Hazards and Magic-Square Permutation Operators [双人相位耦合、双线性相容张量与时空网格博弈] (Version 1.0.0). 5D Library. https://doi.org/10.5281/zenodo.24090172 · Licensed under Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0).