In [1]:
from plotly.offline import download_plotlyjs
from plotly.graph_objs import *
from plotly import tools
import plotly

import os
#os.chdir('C:/Users/L/Documents/Homework/BME/Neuro Data I/Data/')

import csv,gc  # garbage memory collection :)

import numpy as np
# import matplotlib.pyplot as plt
# from mpl_toolkits.mplot3d import axes3d

# from mpl_toolkits.mplot3d import axes3d
# from collections import namedtuple

import csv
import re
import matplotlib
import time
import seaborn as sns

from collections import OrderedDict

In [37]:
import networkx as nx
import math

In [3]:
token = 'Aut1367'
data_txt = 'Aut1367reorient_atlas.region.csv'
data = np.genfromtxt(data_txt, delimiter=',', dtype='int', usecols = (0,1,2,4), names=['x','y','z','region'])

In [9]:
np.mean(data['x'])*0.01872


Out[9]:
5.6747181832754476

In [4]:
ccf_txt = 'natureCCFOhedited.csv'
ccf = {}

with open(ccf_txt, 'rU') as csvfile:
    csvreader = csv.reader(csvfile)
    for row in csvreader:
        # row[0] is ccf atlas index, row[4] is string of full name
        ccf[row[0]] = row[4]
        
print ccf['214']
print ccf['1']


Red nucleus
Tuberomammillary nucleus, ventral part

In [5]:
unique = [];

for l in data:
    unique.append(l[3])

uniqueNP = np.asarray(unique)
allUnique = np.unique(uniqueNP)
numRegionsA = len(allUnique)

print allUnique
print numRegionsA  ## number of regions


[   1    2    7    8    9   10   12   15   17   19   20   23   26  257  258
  259  260  262  263  266  267  268  269  271  272  274  276  278  279  280
  281  513  515  520  521  523  524  526  527  529  531  532  534  537  769
  771  772  773  774  777  778  780  781  783  785  786  791 1026 1029 1030
 1031 1034 1035 1038 1042 1044 1045 1046 1047 1048 1050]
71

In [6]:
dictNumElementsRegion = {}

for i in range(numRegionsA):
    counter = 0
    for l in data:
        if l[3] == allUnique[i]:
            counter = counter + 1
            dictNumElementsRegion[ccf[str(l[3])]] = counter

In [7]:
region_names = dictNumElementsRegion.keys()
number_repetitions = dictNumElementsRegion.values()

In [71]:
def generate_atlas_region_graph(data, path=None, numRegions = 71*3):
    font = {'weight' : 'bold',
        'size' : 18}

    matplotlib.rc('font', **font)

    region_dict = OrderedDict()
    midpoint = 5.6/0.01876
    for l in data:
        trace = ccf[str(l[3])]
#         trace = 'trace' + str(l[3])
#         print l[0]
        if l[0] > midpoint:
            trace = trace + '_Left'
        else:
            trace = trace + '_Right'
        if trace not in region_dict:
            region_dict[trace] = np.array([[l[0], l[1], l[2], l[3]]])
            #print 'yay'
        else:
            tmp = np.array([[l[0], l[1], l[2], l[3]]])
            region_dict[trace] = np.concatenate((region_dict.get(trace, np.zeros((1,4))), tmp), axis=0)
            #print 'nay'

    current_palette = sns.color_palette("husl", numRegions)
    # print current_palette

    avg_pt = OrderedDict()
    data = []
    for i, key in enumerate(region_dict):
        trace = region_dict[key]
        tmp_col = current_palette[i]
        tmp_col_lit = 'rgb' + str(tmp_col)
        temp = str(np.unique(trace[:,3])).replace("[", "")
        final = temp.replace("]", "")
    
        trace_scatter = Scatter3d(
            x = trace[:,0] * 0.01872, 
            y = trace[:,1] * 0.01872,
            z = trace[:,2] * 0.005,
            mode='markers',
            name=ccf[final],
            marker=dict(
                size=1.2,
                color=tmp_col_lit, #'purple',                # set color to an array/list of desired values
                colorscale='Viridis',   # choose a colorscale
                opacity=0.15
            )
        )

        data.append(trace_scatter)

        avg_pt[key] = [np.mean(trace[:,0])*0.01872, np.mean(trace[:,1])*0.01872, np.mean(trace[:,2])*0.005]

    layout = Layout(
        margin=dict(
            l=0,
            r=0,
            b=0,
            t=0
        ),
        paper_bgcolor='rgb(0,0,0)',
        plot_bgcolor='rgb(0,0,0)'
    )
    Xe = []
    Ye = []
    Ze = []
    locations = avg_pt.keys()
    avg = {}
    for i, key in enumerate(locations):
        if i > 139:
            continue
        print i
        tmp = []
        for j in range(i+1,len(locations)):
            dist = (math.pow(avg_pt[key][0]-avg_pt[locations[j]][0],2) + 
                       math.pow(avg_pt[key][1]-avg_pt[locations[j]][1],2) + 
                       math.pow(avg_pt[key][2]-avg_pt[locations[j]][2],2))
            tmp.append(dist)
#             print dist
        tmp2 = avg_pt.keys()[tmp.index(min(tmp))]
        Xe+=[avg_pt[key][0],avg_pt[tmp2][0],None]
        Ye+=[avg_pt[key][1],avg_pt[tmp2][1],None]
        Ze+=[avg_pt[key][2],avg_pt[tmp2][2],None]
    
    trace_edge = Scatter3d(x=Xe,
               y=Ye,
               z=Ze,
               mode='lines',
               line=Line(color='rgb(190,190,190)', width=3),
               hoverinfo='none'
               )
    data.append(trace_edge)
#     print trace_edge['x']
    fig = Figure(data=data, layout=layout)
    plotly.offline.plot(fig, filename= 'Aut1367' + "_region_color_spaced.html")

In [ ]:
generate_atlas_region_graph(data, path=None, numRegions = 71*2)

In [54]:
print 441 * 0.01872


8.25552

In [ ]: