
###******************************************************************###
###******************************************************************###
###  "The Shape of Shared Attention: investigating the influence of ###
###  environmental variation on the compositional structure of       ### 
###  traditional decorative artworks"                                ###
###                                                                  ###
###  Image Scaling and Entropy/Statistical Complexity code           ###
###******************************************************************###
###******************************************************************###

#This code has been transfered from a Jupyter notebook and is organized as such


import numpy as np;
import collections
import math
import scipy
import time
import itertools
from PIL import Image
Image.MAX_IMAGE_PIXELS = 9933120000
import os
import glob

from typing import List, Any
from scipy import stats

print("IMPORT DONE")

# load px/cm data
inny = open("px_cm_data.txt", "r")
fff = inny.readlines()
pxcmdict = {}
for i in range(len(fff)):
    rrr = fff[i].strip().split('\t')
    pxcmdict[rrr[1]] = rrr[4]

target_px_cm = 4.15568181818182

files = glob.glob('*.png')

for item in files:
    # parse accession number from filename
    ttt = item.strip().split('_')
    acc = ttt[1]

    if acc in pxcmdict.keys():
        img = Image.open(item)
        width, height = img.size

        # calculate new dimensions
        scale_factor = target_px_cm / float(pxcmdict[acc])
        new_width  = round(width  * scale_factor)
        new_height = round(height * scale_factor)
        print(f"Processing {item}: {width}x{height} -> {new_width}x{new_height} (scale: {scale_factor:.3f})")
        counter+=1
        ## resize
        img_resized = img.resize((new_width, new_height), Image.NEAREST)

        # convert to grayscale
        gray_img = img_resized.convert('L')

        # convert to numpy array and tile
        gray_matrix = np.array(gray_img)
        gray_3ch_side_by_side = np.hstack([gray_matrix] * 3)

        # save
        txt_path = item.split('.')[0] + '_nearest.txt'
        np.savetxt(txt_path, gray_3ch_side_by_side, fmt='%d', delimiter=',')
        print(f"  Saved matrix to {txt_path}")

    else:
        print(f"Warning: {acc} not found in px/cm data, skipping {item}")
        
print("FINISHED MATRIX CONVERSION")


def imm8rx(grayy):
    imgmatrix=[]
    for i in range(0, len(grayy)-1):
        for j in range(0, len(grayy[i])-1):

            termp=[grayy[i][j], grayy[i][j+1], grayy[i+1][j], grayy[i+1][j+1]]
            imgmatrix.append(termp)
    return imgmatrix

#*************************************************************#

def multiDranker(irl, rows, cols, ringey):
    m8rxsz = rows * cols
    combos = itertools
    rnx = []
    for u in range(len(irl) - rows):
        for t in range(len(irl[u]) - cols):
            #print u+t
            gert = []
            for s in range(rows):
                for r in range(cols):
                    gert.append(irl[u + s][t + r])
            raynj = max(gert)-min(gert)
            #if 0 in gert:
            #    pass
            if raynj < ringey:
                rnx.append('1 2 3 4')
            else:
                ranckor = scipy.stats.rankdata(gert, method="ordinal")
                #print ranckor
                rnx.append(str(ranckor).strip('[]'))
                
    #print(len(rnx), "this is the number of d=x matrices")

    return rnx

############################Entropy###########################

def entropy_H(rnx_s, mxsize):
    #finds entropy, H, for sorted matrix
    Sp = []
    oneoverseventyfive = 1.0/mxsize
    Smax = (-((oneoverseventyfive) * np.log(oneoverseventyfive)))*poss_st8s
    for ytem in rnx_s:

        if ytem > 0.0:
            p = -(ytem * np.log(ytem))
            Sp.append(p)
        else:
            pass
    H = sum(Sp)/Smax
    Habs = H*8
    print(Sp)
    return [H, Habs]


##################### Distrib Comparison ######################

def distrib_compar(ornx_s, pawz_skaggs):
    histo_equiprob = []
    for ca in range(len(ornx_s)):
        histo_equiprob.append(1.0 / float(pawz_skaggs))
        
    OvEq = scipy.spatial.distance.jensenshannon(ornx_s, histo_equiprob)
    return OvEq

print("FUNCTIONS DEFINED")

rose = int(input("how many rows in each matrix"))
kahls = int(input("how many columns in each matrix"))
rainje = float(input("range to consider same"))

msz = rose*kahls
ccc = list(range(msz))

print("msz, ccc", msz, ccc)
poss_st8s = math.factorial(msz)
print(poss_st8s)


piclist=[] #List of matrix files to process 

#***********************************************************#
#************************   WORK!  *************************#
#***********************************************************#

##uncomment below to use list of files from file
# derr = input("name of the dir list file?")
# inny = open(derr, "r")
# fffff = inny.readlines()
# print fffff[0]

outf = input("name of output file?")
DEST = open(outf, "w")

# column headers are H, Absolute H, C, matrix size, smoothing level 
print("Image  H  H_abs C d E", file=DEST)

keepingtrackoflistitemnumber=0
for g in piclist:
    strt = time.time()
    #try:
    print("BEGIN", g)

    #### Read image array file #######
    whatim = open(g.strip(), "r")
    
    msz = rose*kahls
    ccc = list(range(msz))

    print("msz, ccc", msz, ccc)

    poss_st8s = math.factorial(msz)

    #################  AVERAGE LUMINANCE  #################

    fff = whatim.readlines()
    howmany = []
    rgb_shifter = (len(fff[1])/3)
    gryim = []
    for i in range(0,len(fff)):

        rrr = fff[i].strip().split(',')
        howmany.append(rrr)
        rgb_shifter = int(len(rrr)/3)
        #print(rgb_shifter)
        grypx = []
        for j in range(0, len(rrr)):
            rrr[j] = float(rrr[j])
            #print rrr[j]
        for k in range(0,int(len(rrr)/3)):
            temp = [rrr[k], rrr[k+rgb_shifter], rrr[k+rgb_shifter+rgb_shifter]]
            greyy = np.mean(temp)
            grypx.append(greyy)
        gryim.append(grypx)


    print(whatim, len(fff), len(howmany), len(howmany[1]))

    ranx = multiDranker(gryim, rose, kahls, rainje)

    thedist = collections.Counter(ranx)
    mcthedist = thedist.most_common()


    probs = []

    out_of_all_m8rCs = 0
    for ww in range(len(mcthedist)):
        out_of_all_m8rCs += mcthedist[ww][1]
    print(out_of_all_m8rCs)

    for vv in range(len(mcthedist)):
        probs.append(float(mcthedist[vv][1])/out_of_all_m8rCs) # % of the matrices analyzed

    ## uncomment below to check for empty states (not necessary and unlikely in 2x2)
    # empty_st8s = poss_st8s - len(mcthedist)
    # if empty_st8s == 0:
    #     pass
    # else:
    #     for uu in range(int(empty_st8s)):
    #         probs.append(0.0000)
    # print "probs incl empties"
    # print probs
    
    print("poss_st8s", poss_st8s)
    print("used states = ", len(mcthedist))
    percused = len(mcthedist)/poss_st8s
    print("percent of possible states occupied =", percused)

    #*************************************************#
    #************  The Entropy(H) Part!  *************#
    #*************************************************#

    h = entropy_H(probs, poss_st8s)

    #*************************************************#
    #**********  The Complexity(C) Part!  ************#
    #*************************************************#

    C = distrib_compar(probs, poss_st8s)

    stahp = time.time() - strt

    print(" ")
    
    print(piclist[keepingtrackoflistitemnumber].split('.')[0], h[0], h[1], C, rose, rainje, file=DEST)

    print("run in", stahp, "seconds.")
    keepingtrackoflistitemnumber+=1

    ## uncomment below to run unattended
    # except:
    # print("There was some problem.", "Analysis of", g, "was...ABORTED! (dunt-dunt-DUUUNNNNN!!)")
    # pass

# TOTSTp = time.time()
# print("total runtime:", np.round(TOTSTp - TOTSTRT, 4), "seconds")

# inny.close()
# print "inny closed"
DEST.close()
print("DEST closed")
