
## com5d of september 2025, 
#  revisiting magic squares stuff; see also Kiosk Story magic squares

#  here: k x k squares, care about columns and rows
#  and the two diagonals and nothing more 
#  and on this occasion i bother to monitor the changes 

#  f = \exp[-\lambda Q(x)] / constant
#  Q(x) = R(x) + C(x) + D(x) hope to see Q(x) = 0 

kk <- 6
magic <- 0.5*kk*(kk^2+1)

#  34 for magical 4 x 4 squares
# 111 for magical 6 x 6 squares
# 260 for magical 8 x 8 squares 
# 505 for magical 10 x 10 squares 
# 870 for magical 12 x 12 squares 

rr <- 0*(1:kk)
cc <- 0*(1:kk) 
first <- 0*(1:kk) 
second <- 0*(1:kk) 

D <- function(x)
{
for (i in 1:kk)
{
first[i] <- x[i,i]
second[i] <- x[i,kk+1-i]
}
# 
oi1 <- sum(first)
oi2 <- sum(second) 
abs(oi1 - magic) + abs(oi2 - magic)
}

R <- function(x)
{
for (i in 1:kk)
{
rr[i] <- abs( sum(x[i, ]) - magic )
}
sum(rr)
}

C <- function(x)
{
for (j in 1:kk)
{
cc[j] <- abs( sum(x[ ,j]) - magic )
}
sum(cc)
}

gaudiset <- 1:(kk^2)
# aux <- sample(gaudiset,kk^2)
# xx <- array(aux,dim=c(kk,kk)) # i start my mcmc here 
xx <- t( array(1:kk^2,dim=c(kk,kk)) ) # i start my mcmc here

Q <- function(x)
{ R(x) + C(x) + D(x) }

set.seed(123) 

sim <- 30*10^4 # make it bigger, e.g. 1000*10^4 for bigger squares 
uu <- runif(sim)
ok <- 0*(1:sim)
probs <- 0*(1:sim) 
Qcheck <- 0*(1:sim) 
Qcheck[1] <- Q(xx) 

mcmc <- array(0,dim=c(sim,kk,kk))
mcmc[1, , ] <- xx

rAsim <- sample(1:kk,sim,replace=T)
cAsim <- sample(1:kk,sim,replace=T)
rBsim <- sample(1:kk,sim,replace=T)
cBsim <- sample(1:kk,sim,replace=T)

lambda0 <- 1.444 # for k = 6, mean(ok) 
# lambda0 <- 0.999 # for k = 4
# lambda0 <- - 1.035 # for k = 5? 

for (ss in 2:sim)
{
old <- mcmc[ss-1, , ]
# 
prop <- old
prop[rAsim[ss],cAsim[ss]] <- old[rBsim[ss],cBsim[ss]]
prop[rBsim[ss],cBsim[ss]] <- old[rAsim[ss],cAsim[ss]]
# 
diff <- Q(prop) - Q(old)
# pure metropolis: fixed lambda0,
# but i can make it slowly grow with time: 
lambda <- lambda0 + 0.00*log(ss) 
probs[ss] <- min(1,exp(-lambda*diff))
# 
ok[ss] <- 1*(uu[ss] <= probs[ss])
mcmc[ss, , ] <- (1-ok[ss])*old + ok[ss]*prop
Qcheck[ss] <- Q(mcmc[ss, , ])
print(c(ss,Qcheck[ss]))
}

print(range(Qcheck))


starthere0 <- 101 # pre burn-in

par(bty="l")
par(cex.lab=1.4142) 

matplot(starthere0:sim,Qcheck[starthere0:sim],
   type="l",ylim=c(0,max(Qcheck[starthere0:sim])),
   xlab="long magical chain is running",ylab="Q score",lwd=2)

starthere <- 50001 # after burn-in

## then senza ylim, for lambda 0 negative,
#  to find the worst squares ever

par(bty="l")
par(cex.lab=1.4142) 

matplot(starthere:sim,Qcheck[starthere:sim],
   type="l",
   xlab="long magical chain is running",ylab="Q score",lwd=2)

par(bty="l")
par(cex.lab=1.4142) 

matplot(starthere:sim,Qcheck[starthere:sim],
   type="l",ylim=c(0,max(Qcheck[starthere:sim])),
   xlab="long magical chain is running",ylab="Q score",lwd=2)
matlines(starthere:sim, 0*(starthere:sim),type="l",lwd=2,lty=3) 

ssgood <- (1:sim)[Qcheck==min(Qcheck)]
firsttime <- min(ssgood)
lasttime <- max(ssgood) 

print(c(firsttime,lasttime))

# when i bother to take lambda negative,
# searching for the Worst Evver Squares: 
# ssbad <- (1:sim)[Qcheck==max(Qcheck)]

# firsttimebad <- min(ssbad)  

magicsolutionA <- mcmc[firsttime, , ]
magicsolutionB <- mcmc[firsttime, , ]

# badsolutionA <- mcmc[firsttimebad, , ]
# mmbad <- badsolutionA

mmA <- magicsolutionA
mmB <- magicsolutionB

wellA <- c(R(mmA),C(mmA),D(mmA))
wellB <- c(R(mmB),C(mmB),D(mmB))
print( wellA )
print( wellB ) 

print("here it is")
print(mmA) 

## for set.seed(123), lambda0 = 1.444, sim = 3*10^5, magic 6 x 6,
#  I get this one, rows, columns, diagonals equal to 111 

#    7   25   13   27   19   20
#   26   22    2   16   15   30
#    3   10   35    6   33   24
#   36   12   11   34   17    1
#    8   28   29    5    9   32
#   31   14   21   23   18    4


## with set.seed(33), sim = 100*10^4, lambda0 = 1.888 
#  firsttime lasttime 135,502 and 793,651

#  mean(ok) = 0.018 :
#  rows, columns, both diagonals sum to 260 

#[1,]   23   38   55   15   52    5   63    9
#[2,]   62   17   12   32   26    1   53   57
#[3,]   34   20   29   48   18   37   50   24
#[4,]    2   61   46   60    6   56   10   19
#[5,]   31   21   11   16   44   47   41   49
#[6,]   27    7   40   51   28   43   25   39
#[7,]   36   54    8   35   22   58   14   33
#[8,]   45   42   59    3   64   13    4   30

## with set.seed(33), sim = 200*10^4, lambda0 = 2.222
#  firsttime lasttime 592,006 163,0779

#  mean(ok) = 0.011
#  rows, columns, both diagonals sum to 550

# [1,]   11   88   98   94   59   99   15   10   18    13
# [2,]   71    4   76   21   91   62    5   77   79    19
# [3,]   29   25   30   22   84   83   97   12   87    36
# [4,]   28   95   47   81   72   26   74   32    8    42
# [5,]   65   48   33   46   38   45   70   85   44    31
# [6,]   66   40   41   55   56   43   51   86    9    58
# [7,]   53   69   16   24   80    6   92   63   68    34
# [8,]   14   64   60   78   20   35   39   17   96    82
# [9,]   75   49   67   27    3   54    1   50   89    90
#[10,]   93   23   37   57    2   52   61   73    7   100

## with set.seed(33), sim = 200*10^4, lambda0 = 2.222
#  firsttime lasttime 1,418,493 and 2,000,000

#  mean(ok) = 0.008
#  rows, columns, both diagonals sum to 870

# [1,]   13   82   73   95  104   83    7   28  119    15   144   107
# [2,]   37    4  142   21  143   10  140  105  111    34    97    26
# [3,]  116  135  117   70   31   81   67   96   52    27    60    18
# [4,]  127   12   43   39   44  128   98   61   42   101   125    50
# [5,]   55  114   51   25   71   54  108  124   74    23   138    33
# [6,]   30  120  134  136   17   99   46   85   24    69    32    78
# [7,]   66   77   76  133  129   80   45   14    8   137    48    57
# [8,]   72  141    1   91  102  100    6   93   41   113    16    94
# [9,]   87   20   64   92   65  126   88   89  106     9    38    86
#[10,]  115   56   11   47   53   22  121   63  132   103    79    68
#[11,]   29   19  118   62   75   84    5  110   49   130    58   131
#[12,]  123   90   40   59   36    3  139    2  112   109    35   122

subs <- (1:sim)[ok == 1] # 5,632 changes 
mcmcsubs <- mcmc[subs, , ]

# fascinating to the see changes to converge to magic 

giveme <- 1001
print(mcmcsubs[giveme, , ])
print(Qcheck[giveme])

# 5 x 5:

#   25   11    4   23    2
#    6    7   18   10   24
#    9   15   19    5   17
#    3   12   16   13   21
#   22   20    8   14    1

