# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# +
from config import *
ds = '36p' # Denoising Strategy:
ct = 'pearson' #Correlation Type
negative_corr = False
tm = 'gce' # Thresholding Method:
           # It could be 'GCE' or 'user_defined'
tv = 0.05  # Thresholding Value, For user defined tm

enodes_name = 'all'
# -

import src.group_level_analysis.group_level_analysis as gla
from src.group_level_analysis.general import *
selected_set = 0
group_couples,snd,sep,all_sub_list,all_subjects,subjects_list,sg,str_loc,str_glob,strlist,tm,sgn,measures,RAWmeasures,intersect,removed,removed_subL,r,cols,subL,subLRAW,subL_adj,subLRAW_adj,meanM,meanG,meanM_bin,meanG_bin,meanM_adj,meanG_adj = general(ds,ct,negative_corr,tm,tv,enodes_name,selected_set,'mean_net','load')

sortednd = {
    'Frontoparietal': [14,28,57,62,72,78,80,81,82,83,84,85,90,96,110,143,144,170,178,194,208,242,246,252,253,256,258,260,261,262,263,264,265,268,270,276,277,290,312,323,324,328,349,350,358],
    'Default': [13,25,26,27,29,30,31,32,33,34,60,61,63,64,65,66,67,68,69,70,71,73,74,75,76,86,88,93,97,118,122,127,128,129,131,132,138,148,149,150,154,160,161,169,175,176,179,193,205,209,210,211,212,213,214,240,241,243,244,245,247,248,249,250,251,254,255,266,273,302,307,308,309,311,329,330,340,341,344,355,356,359],
    'Limbic': [87,89,91,92,109,117,121,130,133,134,163,164,165,171,267,269,271,272,297,299,301,310,313,314,343,345,351],
    'Somatomotor': [7,8,11,23,35,38,39,40,50,51,52,53,54,55,99,100,101,102,103,106,114,123,124,167,172,173,174,187,188,203,215,218,219,220,230,231,232,233,234,235,279,280,281,282,283,284,286,294,303,304,318,347,352,353,354],
    'VentralAttention': [24,36,37,42,43,56,58,59,77,98,104,105,107,108,111,112,113,146,147,166,168,177,191,204,207,216,217,222,223,236,237,238,239,257,278,285,287,288,289,291,292,293,326,327,346,348,357],
    'DorsalAttention': [1,9,10,16,41,44,45,46,47,48,49,79,94,95,115,116,135,136,137,139,140,142,156,189,190,196,206,221,224,225,226,227,228,229,259,274,275,295,296,315,316,317,319,320,322,325,336],
    'Visual':[0,2,3,4,5,6,12,15,17,18,19,20,21,22,120,125,126,141,145,151,152,153,155,157,158,159,162,180,181,182,183,184,185,186,192,195,197,198,199,200,201,202,298,300,305,306,321,331,332,333,334,335,337,338,339,342]
    }

sortedndLR = {}
for Mod in nd:
    ndLR[Mod + '_L'] = [i for i in nd[Mod] if i<=180]
    ndLR[Mod + '_R'] = [i for i in nd[Mod] if i> 180]

modulecolor = {
    'Frontoparietal':'cd8221',
    'Default':'d54758',
    'Limbic':'909771',
    'Somatomotor':'498ec4',
    'VentralAttention':'d84bf3',
    'DorsalAttention':'007a0d',
    'Visual':'901d9e'
}

atlasdir=rootdir + '/references/HCP-MMP1'
labelfile=os.path.join(atlasdir,'MMP_yeo2011_networks.csv')
labeldata=pd.read_csv(labelfile)
enc = labeldata.T.loc['MMP']
mod7idx = labeldata.T.loc['Yeo7']
mod7name = labeldata.T.loc['YeoDesc7']

sortedmod7idx = {}
for i in range(360):
    if mod7idx[i] == 1:
        sortedmod7idx[i] = 7
    if mod7idx[i] == 2:
        sortedmod7idx[i] = 4
    if mod7idx[i] == 3:
        sortedmod7idx[i] = 6
    if mod7idx[i] == 4:
        sortedmod7idx[i] = 5
    if mod7idx[i] == 5:
        sortedmod7idx[i] = 3
    if mod7idx[i] == 6:
        sortedmod7idx[i] = 1
    if mod7idx[i] == 7:
        sortedmod7idx[i] = 2

import json
def savejson(dic, path):
    with open(path, 'w') as fp:
        json.dump(dic, fp)


# ### Toy Network

toyjson = {'nodes': [{'id': 'L_V1_ROI', 'group': 1},
                      {'id': 'L_MST_ROI', 'group': 3},
                      {'id': 'L_V6_ROI', 'group': 2},
                      {'id': 'L_V2_ROI', 'group': 2},
                      {'id': 'L_V3_ROI', 'group': 4}
                     ],
            'links': [{'source': 'L_V1_ROI', 'target': 'L_V6_ROI', 'value': 331},
                      {'source': 'L_V1_ROI', 'target': 'L_V2_ROI', 'value': 741},
                      {'source': 'L_V2_ROI', 'target': 'L_V3_ROI', 'value': 621},
                      {'source': 'L_V2_ROI', 'target': 'L_V6_ROI', 'value': 457},
                      {'source': 'L_V3_ROI', 'target': 'L_V1_ROI', 'value': 403}                     ]
           }


# ### Convert to JSON 

def json360_7_bin(M):
    jsondic = {"nodes":[], "links": []}
    for i in range(360):
        if i==119:
            continue
        nodesdic = {"id": enc[i], "group": int(sortedmod7idx[i])}
        jsondic["nodes"].append(nodesdic)
        for j in range(i+1,360):
            if j==119:
                continue
            if M[i][j]!= 0.0:
                linksdic = {"source": enc[i], "target": enc[j], "value": np.around(M[i][j],3)}
                jsondic["links"].append(linksdic)
    return jsondic


def json360_7LR_bin(M):
    jsondic = {"nodes":[], "links": []}
    for i in range(360):
        if i==119:
            continue
        elif i <180:
            name = mod7name[i] + '_L'
        else:
            name = mod7name[i] + '_R'
        nodesdic = {"id": enc[i], "group": list(sortedndLR.keys()).index(name)}
        jsondic["nodes"].append(nodesdic)
        for j in range(i+1,360):
            if j==119:
                continue
            if M[i][j]!= 0.0:
                linksdic = {"source": enc[i], "target": enc[j], "value": np.around(M[i][j],3)}
                jsondic["links"].append(linksdic)
    return jsondic


def json360_7_w(M):
    jsondic = {"nodes":[], "links": []}
    for i in range(360):
        if i==119:
            continue
        nodesdic = {"id": enc[i], "group": int(sortedmod7idx[i])}
        jsondic["nodes"].append(nodesdic)
        for j in range(i+1,360):
            if j==119:
                continue
            if M[i][j]!= 0.0:
                linksdic = {"source": enc[i], "target": enc[j], "value": np.around(M[i][j],3)}
                v = int(10* np.around(M[i][j],1))
                jsondic["links"].extend([linksdic]*v)
    return jsondic


def json360_7LR_w(M):
    jsondic = {"nodes":[], "links": []}
    for i in range(360):
        if i==119:
            continue
        elif i <180:
            name = mod7name[i] + '_L'
        else:
            name = mod7name[i] + '_R'
        nodesdic = {"id": enc[i], "group": list(sortedndLR.keys()).index(name)}
        jsondic["nodes"].append(nodesdic)
        for j in range(i+1,360):
            if j==119:
                continue
            if M[i][j]!= 0.0:
                linksdic = {"source": enc[i], "target": enc[j], "value": np.around(M[i][j],3)}
                v = int(10* np.around(M[i][j],1))
                jsondic["links"].extend([linksdic]*v)
    return jsondic


# ### Different Networks

# delete Connections
def rem_edges(M, remtype):
    newM = M.copy()
    if remtype == "L":
        for i in range(180,360):
            newM[i] = 0
            newM = newM.T
            newM[i] = 0
            newM = newM.T
    if remtype == "R":
        for i in range(180):
            newM[i] = 0
            newM = newM.T
            newM[i] = 0
            newM = newM.T
    if remtype == "intra":
        for Mod in sortednd:
            for i in sortednd[Mod]:
                for j in sortednd[Mod]:
                    newM[i,j] = 0
    if remtype == "intraLR":
        for Mod in sortedndLR:
            for i in sortedndLR[Mod]:
                for j in sortedndLR[Mod]:
                    newM[i,j] = 0
    if remtype == "inter":
        newM = newM - rem_edges(M, remtype = "intra")
    return newM


remtypes = ["non", "L", "R", "intra", "intraLR"]


# ### Save JSON Files

# pth = rootdir + '/data/json'
# for g in subjects_groups:
#     for remtype in remtypes:
#         M = rem_edges(meanM_bin[g], remtype)
#         if remtype not in ['L', 'R', 'intra']:
#             savejson(json360_7LR_bin(M),
#                      pth + '/net360/group-%s_layout-7LR-bin_remtype-%s.json'%(g,remtype))
#             savejson(json360_7LR_w(M),
#                      pth + '/net360/group-%s_layout-7LR-w_remtype-%s.json'%(g,remtype))
#         if remtype not in ['intraLR']:
#             savejson(json360_7_bin(M),
#                      pth + '/net360/group-%s_layout-7-bin_remtype-%s.json'%(g,remtype))
#             savejson(json360_7_w(M),
#                      pth + '/net360/group-%s_layout-7-w_remtype-%s.json'%(g,remtype))
#

# 1 7f1819
#
# 2 e95924
#
# 3 e6e01c
#
# 4 89c97a
#
# 5 3cc2db
#
# 6 3c54a4
#
# 7 252160

# pth = rootdir + '/data/json'
# for g in subjects_groups:
#     M = rem_edges(meanM_bin[g], remtype="inter")
#     savejson(json360_7LR_w(M),
#              pth + '/net360/group-%s_layout-7LR-w_remtype-%s.json'%(g,"inter"))
#     M = rem_edges(meanM_bin[g], remtype="intra")
#     savejson(json360_7LR_w(M),
#              pth + '/net360/group-%s_layout-7LR-w_remtype-%s.json'%(g,"intra"))

# ### Activated and disactivated nodes

def json360_7_w1(M1,M2):
    jsondic = {"nodes":[], "links": []}
    for i in range(360):
        if i==119:
            continue
        nodesdic = {"id": enc[i], "group": int(sortedmod7idx[i])}
        jsondic["nodes"].append(nodesdic)
        for j in range(i+1,360):
            if j==119:
                continue
            if M1[i][j]!= 0.0:
                linksdic = {"source": enc[i], "target": enc[j], "value": np.around(M1[i][j],3), "linktype": "activated" }
                v = int(10* np.around(M1[i][j],1))
                jsondic["links"].extend([linksdic]*v)
            if M2[i][j]!= 0.0:
                linksdic = {"source": enc[i], "target": enc[j], "value": np.around(M2[i][j],3), "linktype": "deactivated" }
                v = int(10* np.around(M2[i][j],1))
                jsondic["links"].extend([linksdic]*v)
    return jsondic


pth = rootdir + '/data/json'
for g in subjects_groups[1:]:
    activatedM = meanM_bin[g] - meanM_bin['CN']
    deactivatedM = meanM_bin['CN'] - meanM_bin[g]
    activatedM = (activatedM > np.mean(activatedM) + 2 * np.std(activatedM)) * activatedM
    deactivatedM = (deactivatedM > np.mean(deactivatedM) + 2 * np.std(deactivatedM)) * deactivatedM
    M1 = rem_edges(activatedM, remtype="intra")
    M2 = rem_edges(deactivatedM, remtype="intra")

    savejson(json360_7_w1(M1,M2),
             pth + '/alternated-%s_layout-7-w_remtype-%s.json'%(g,"intra"))



StarcoderdataJupyterScriptsDedupFiltered