# ---
# 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
# ---

import numpy as np 
import pandas as pd
import networkx as nx
from graspy.utils import *
from graspy.embed import AdjacencySpectralEmbed
from graspy.plot import heatmap, pairplot
import seaborn as sns
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
import re
FONTSIZE=20

# +
df = pd.read_excel('SI 3 Synapse lists.xlsx', sheet=0)
new_labels = ['num_contin', 'em_series', 'pre', 'all_post', 'type', 'sections',
 'num_post', 'post1', 'post2', 'post3', 'post4']
df.columns = new_labels
chem = df.loc[df['type'] == 'chemical']
elec = df.loc[df['type'] == 'electrical']
ax = plt.subplots(1,1, figsize=(10,10))[1]
sns.countplot(x='num_post', data=chem)
ax.set_title('Chemical synapse partner number', fontsize=FONTSIZE)

chem_1 = chem.loc[chem['num_post'] == 1]
chem_2 = chem.loc[chem['num_post'] == 2]
chem_3 = chem.loc[chem['num_post'] == 3]
chem_4 = chem.loc[chem['num_post'] == 4]
chem_5 = chem.loc[chem['num_post'] == 5]
chem_adics = [chem_1, chem_2, chem_3, chem_4, chem_5]
# -



names = set()
for i, row in chem.iterrows():
    pre = row.pre
    post_names = re.split('[, .]', row.all_post)
    names.add(pre)
    [names.add(post) for post in post_names]
names.remove('')
cell_ids = np.unique(list(names))
inds = range(len(cell_ids))
cell_id_map = dict(zip(cell_ids,inds))
cell_id_map

adic_graphs = [nx.MultiDiGraph() for n in range(5)]
for i, row in chem.iterrows():
    pre = row.pre
    post_names = row.all_post.split(',')
    post_names = re.split('[, .]', row.all_post)
    for g in adic_graphs:
        g.add_node(pre)
        [g.add_node(post) for post in post_names]
    [adic_graphs[row.num_post - 1].add_edge(pre, post, weight=1) for post in post_names]
adic_As = [nx.to_numpy_array(g, nodelist=cell_ids) for g in adic_graphs]


# +
def df_to_adjacency_undirected(df, nodelist, weight=1):
    rows = []
    for i, row in df.iterrows():
        post_names = re.split('[, .]', row.all_post)
        for a in post_names:
            # pre | post | weight
            rows.append([row.pre, a, weight])
    
    df_split = pd.DataFrame(rows, columns=['source', 'target', 'weight'])
    g = nx.MultiGraph()
    g = nx.from_pandas_edgelist(df_split, create_using=g)
    return nx.to_numpy_array(g, nodelist=cell_ids)

chem_A_undirected = df_to_adjacency_undirected(chem, cell_ids)
# -



adic_counts

# +
adic_undirected_graphs = [nx.MultiGraph() for n in range(5)]
adic_counts = np.zeros(5)
for i, row in chem.iterrows():
    pre = row.pre
    post_names = re.split('[, .]', row.all_post)
    for g in adic_graphs:
        g.add_node(pre)
        [g.add_node(post) for post in post_names]
    [adic_undirected_graphs[row.num_post
                            - 1].add_edge(pre,
                                          post,
                                          weight=1)
    for post in post_names]
    adic_counts[row.num_post-1] += 1

adic_undirected_As = [nx.to_numpy_array(g,
                                        nodelist=cell_ids) 
                      for g in adic_undirected_graphs]
# -

# summing over the columns to get the degree of each node for any-adic
num_possible = np.sum(chem_A_undirected, axis=1) 
num_present = []
# for each adic-graph, getting the number that were actually made
[num_present.append(np.sum(A, axis=1)) 
 for ind, A in enumerate(adic_undirected_As)]


proportions = []
for adic_num_present in num_present:
    proportions.append(np.divide(adic_num_present, num_possible))

proportions

mean_adic_proportions = [prop.sum()/len(cell_ids) for prop in proportions]
mean_adic_proportions

2*list(range(1,6))

5*['mean cell proportion'] + 5*['overall proportion']


mean_adic_proportions + list(adic_props_overall)


adicp = pd.DataFrame()
num_synapses = sum(adic_counts)
adic_props_overall = adic_counts / num_synapses
adicp['proportion'] = mean_adic_proportions + list(adic_props_overall)
adicp['num_post'] = 2*list(range(1,6))
adicp['method'] = 5*['mean cell proportion'] + 5*['overall proportion']


sns.barplot(x='num_post', y='proportion', hue='method', data=adicp)

# Overall proportion is just the total number of synapses in that category, divided by the total number of synapses
#
# Mean cell proportion: 
# For each category (biadic, triadic ...)



StarcoderdataJupyterScriptsDedupFiltered