In [83]:
from IPython.display import HTML
HTML('''<script>
code_show=true; 
function code_toggle() {
 if (code_show){
 $('div.input').hide();
 } else {
 $('div.input').show();
 }
 code_show = !code_show
} 
$( document ).ready(code_toggle);
</script>
The raw code for this IPython notebook is by default hidden for easier reading.
To toggle on/off the raw code, click <a href="javascript:code_toggle()">here</a>.''')
Out[83]:
The raw code for this IPython notebook is by default hidden for easier reading. To toggle on/off the raw code, click here.

NETWORK ANALYSIS OF SHAKESPEARE'S MACBETH

By Moses Boudourides & Sergios Lenis

With contributions from the Group of participants of "Literature Networks"

In [84]:
%matplotlib inline 
%load_ext autoreload
from IPython.display import display
# from ipywidgets import interact, interactive, fixed
import ipywidgets as widgets
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import pickle
from prettytable import PrettyTable #sudo pip install prettytable
from utils import *
def choid(x):
    return x
The autoreload extension is already loaded. To reload it, use:
  %reload_ext autoreload

PART A:

Extraction of Shakespeare's Macbeth Network

The original text file of Shakespeare's Macbeth was downloaded from Project Gutenberg and it was modified in such way that all names of characters (from now on, called "actors" in the social networks sense) were put in a uniform form.

Actors and their Attributes

In [85]:
%autoreload 2
from testy2 import *
from syntheticThreeLayerGraph_time import synthetic_multi_level_dict,plot_graph_dict,plot_graph_k_n, plot_total_graph_with_weights

fileName = 'corpora/ShakespeareMacbethOrig_from_PG_mod.txt'
f=open(fileName,'r')
attributes_filename='corpora/Character Atrributes - Macbeth - 1.csv'

act_dict,u,pers_l,pers_dict,pact,lact,scen_dict,lscen,pscen=create_dict_of_acts(fileName)

print 'Actors appearing in Macbeth:'
print
for actor in pers_l:
    print actor
print
print 'The number of actors in Macbeth is', len(pers_l)
print 
print 'Attributes of actors in Macbeth:'
print
attribute_dict={}
af=open(attributes_filename,'r')
lis_pret=['Name','Gender','Social Status','Alliance','Drive','Count of speech characters']
pret=PrettyTable(lis_pret)
pret.padding_width=1
# print
# print 'Names not associated in attributes file'
list_of_attributes_dic={}
list_of_att=[]
for lin in af:
    ll=lin.strip().split(',')
    momo=0
    
    if ll[0]=='Name':
        list_of_att={il:l.strip() for il,l in enumerate(ll)}
        continue
    try:
        for k,l in pers_dict[ll[0]].items():
            momo+= len(l)
    except:
        momo=0
    ll.append(momo)
    pret.add_row(ll)  
    if ll[0].strip() in pers_l:
#         print ll
        for en,vv in enumerate(ll[:-1]):
#             print en,vv
            if list_of_att[en] not in list_of_attributes_dic:
                list_of_attributes_dic[list_of_att[en]]=set()
                list_of_attributes_dic[list_of_att[en]].add(ll[en].strip())
            else:
                list_of_attributes_dic[list_of_att[en]].add(ll[en].strip())
        attribute_dict[ll[0].strip()]=(ll[1].strip(),ll[2].strip(),ll[3].strip(),ll[4].strip(),momo)
    else:
        print ll,'no'
# print
# print 'Atributes'
print pret
fop=open('list_of_attributes_dic.dmpp','w')
pickle.dump(list_of_attributes_dic,fop)
fop.close()
fop=open('attribute_dict.dmpp','w')
pickle.dump(attribute_dict,fop)
fop.close()
fop=open('list_of_att.dmpp','w')
pickle.dump(list_of_att,fop)
fop.close()
Actors appearing in Macbeth:

ANGUS
BANQUO
CAPTAIN
CATHNESS
DONALBAIN
DOCTOR
DUNCAN
ENGLISH DOCTOR
FIRST APPARITION
FIRST MURDERER
FIRST WITCH
FLEANCE
GENTLEWOMAN
HECAT
LADY MACBETH
LENNOX
LORD
LORDS
MACBETH
MACDUFF
MALCOLM
MENTETH
MESSENGER
MESSENGER TO WIFE
MURDERERS
OLD MAN
PORTER
ROSS
SECOND APPARITION
SECOND MURDERER
SECOND WITCH
SERVANT
SEYTON
SEYWARD
SOLDIERS
SON
THIRD APPARITION
THIRD MURDERER
THIRD WITCH
WIFE
WITCHES
YOUNG SEYWARD

The number of actors in Macbeth is 42

Attributes of actors in Macbeth:

+-----------------------+--------+---------------+----------+--------------+----------------------------+
|          Name         | Gender | Social Status | Alliance |    Drive     | Count of speech characters |
+-----------------------+--------+---------------+----------+--------------+----------------------------+
|         ANGUS         |  Male  |     Noble     | Kingdom  |   Justice    |            736             |
|         BANQUO        |  Male  |     Noble     | Macbeth  |   Justice    |            3763            |
|        CAPTAIN        |  Male  |    Commoner   | Kingdom  |   Justice    |            1367            |
|        CATHNESS       |  Male  |     Noble     | Kingdom  |   Justice    |             0              |
|       DONALBAIN       |  Male  |     Noble     | Kingdom  |   Justice    |            290             |
|    DOCTOR             |  Male  |    Commoner   | Neutral  |   Neutral    |             0              |
|         DUNCAN        |  Male  |     Noble     | Kingdom  |   Justice    |            2180            |
|     ENGLISH DOCTOR    |  Male  |    Commoner   | Neutral  |   Neutral    |            189             |
|    FIRST APPARITION   |  Male  |  Supernatural | Macbeth  | Supernatural |             89             |
|     FIRST MURDERER    |  Male  |    Commoner   | Macbeth  |   Neutral    |            583             |
|      FIRST WITCH      | Female |  Supernatural | Neutral  | Supernatural |            1890            |
|        FLEANCE        |  Male  |     Noble     | Kingdom  |   Justice    |            180             |
|      GENTLEWOMAN      | Female |    Commoner   | Macbeth  |   Neutral    |            826             |
|         HECAT         | Female |  Supernatural | Neutral  | Supernatural |            1271            |
|      LADY MACBETH     | Female |     Noble     | Macbeth  |   Ambition   |            8113            |
|         LENNOX        |  Male  |     Noble     | Kingdom  |   Justice    |            2701            |
|          LORD         |  Male  |     Noble     | Kingdom  |   Justice    |            833             |
|         LORDS         |  Male  |     Noble     | Kingdom  |   Justice    |             69             |
|        MACBETH        |  Male  |     Noble     | Macbeth  |   Ambition   |           24275            |
|        MACDUFF        |  Male  |     Noble     | Kingdom  |   Justice    |            5837            |
|        MALCOLM        |  Male  |     Noble     | Kingdom  |   Justice    |            8066            |
|        MENTETH        |  Male  |     Noble     | Kingdom  |   Justice    |             0              |
|       MESSENGER       |  Male  |    Commoner   | Macbeth  |   Neutral    |            295             |
|   MESSENGER TO WIFE   |  Male  |    Commoner   | Kingdom  |   Neutral    |            376             |
|       MURDERERS       |  Male  |    Commoner   | Macbeth  |   Neutral    |             39             |
|        OLD MAN        |  Male  |    Commoner   | Neutral  |   Neutral    |            431             |
|         PORTER        |  Male  |    Commoner   | Neutral  |   Neutral    |            1727            |
|          ROSS         |  Male  |     Noble     | Kingdom  |   Justice    |            4738            |
| SECOND APPARITION     |  Male  |  Supernatural | Macbeth  | Supernatural |             0              |
|    SECOND MURDERER    |  Male  |    Commoner   | Macbeth  |   Neutral    |            413             |
|      SECOND WITCH     | Female |  Supernatural | Neutral  | Supernatural |            664             |
|        SERVANT        |  Male  |    Commoner   | Macbeth  |   Neutral    |            122             |
|         SEYTON        |  Male  |    Commoner   | Macbeth  |   Neutral    |            161             |
|        SEYWARD        |  Male  |     Noble     | Kingdom  |   Justice    |            1037            |
|        SOLDIERS       |  Male  |    Commoner   | Kingdom  |   Justice    |             17             |
|   SON                 |  Male  |     Noble     | Kingdom  |   Justice    |             0              |
|    THIRD APPARITION   |  Male  |  Supernatural | Macbeth  | Supernatural |            190             |
|     THIRD MURDERER    |  Male  |    Commoner   | Macbeth  |   Neutral    |            201             |
|      THIRD WITCH      | Female |  Supernatural | Neutral  |   Neutral    |            702             |
|     WIFE              | Female |     Noble     | Kingdom  |   Justice    |             0              |
|        WITCHES        | Female |  Supernatural | Neutral  | Supernatural |            293             |
|     YOUNG SEYWARD     |  Male  |     Noble     | Kingdom  |   Justice    |            227             |
+-----------------------+--------+---------------+----------+--------------+----------------------------+

Conversations among Actors as Network Ties

The relationship (tie) among actors (detected automatically here) is the so-called "conversational relationship," which is defined whenever two actors are co-participating in a conversation. Actually, due to the structure of Shakespeare's printed text (taken from Project Gutenberg), the unit of conversation (i.e., a conversational chunk) used here is the text body delimited between two empty lines.

In this way, the resulting network is represented by a weighted undirected graph, where tha weight of an edge(tie) joining two actors is the total number of conversational chaunks in which these ctors participate. Moreover, we are decomposing the network into slices (or layers) according either to one of the five Acts or to one of the total 26 Scenes, during which the measured coversations take place.

Decomposition of Shakespeare's Macbeth in Networks of Acts

In [86]:
graph_dic,ract_dic,pernode_dict,nodper_dic,cnum,active_actors=create_graph_dict(act_dict,pers_l,pers_dict,u,attribute_dict)
G, list_of_Graphs_final, Gagr, edgeList ,nmap ,mapping,k,n=synthetic_multi_level_dict(graph_dic,pernode_dict,nodper_dic,ract_dic,No_isolates=True)
conver_rel = 0

pos_dict={}
act_rel=[]
for k,v in graph_dic.items():
    v.remove_nodes_from(nx.isolates(v))
    print nx.info(v)
    for nd in v.nodes():
        act_rel.append(nd)
    conver_rel += len(v.edges())
    print
    
print 'Actors participating in all conversational relationships in all Macbeth Acts:'  
print
for i in pernode_dict:
    print i
print
print 'The total number of actors participating in all conversational relationships in all Macbeth Acts is', len(set(act_rel))
print 
print 'The total number of conversational relationships (edges) among actors \
participating in all Macbeth Acts is', conver_rel
met_acts={'Act '+str(i):u for u,i in enumerate(sorted(graph_dic.keys())) }
rmet_acts={k:v for v,k in met_acts.items()}
Name: Act I
Type: Graph
Number of nodes: 10
Number of edges: 13
Average degree:   2.6000

Name: Act II
Type: Graph
Number of nodes: 8
Number of edges: 10
Average degree:   2.5000

Name: Act IV
Type: Graph
Number of nodes: 12
Number of edges: 17
Average degree:   2.8333

Name: Act III
Type: Graph
Number of nodes: 15
Number of edges: 21
Average degree:   2.8000

Name: Act V
Type: Graph
Number of nodes: 13
Number of edges: 14
Average degree:   2.1538

Actors participating in all conversational relationships in all Macbeth Acts:

DONALBAIN
SERVANT
OLD MAN
THIRD WITCH
YOUNG SEYWARD
MESSENGER
WITCHES
SOLDIERS
SECOND MURDERER
LORDS
LENNOX
MACDUFF
HECAT
DOCTOR
MALCOLM
LADY MACBETH
SON
THIRD MURDERER
BANQUO
FIRST WITCH
LORD
ROSS
FIRST APPARITION
PORTER
SEYWARD
ANGUS
FIRST MURDERER
GENTLEWOMAN
FLEANCE
SECOND APPARITION
DUNCAN
SEYTON
WIFE
MACBETH
MESSENGER TO WIFE
SECOND WITCH
THIRD APPARITION
CAPTAIN
MURDERERS
ENGLISH DOCTOR

The total number of actors participating in all conversational relationships in all Macbeth Acts is 28

The total number of conversational relationships (edges) among actors participating in all Macbeth Acts is 75

The Two-Mode Macbeth Network (Bipartite Graph) of Actors and Acts

In [87]:
act_scene_graph=create_two_mode_act_scene_graph(active_actors)
print nx.info(act_scene_graph)
pos_Scene=nx.spring_layout(act_scene_graph,scale=50)
# nx.draw_networkx(act_scene_graph,pos)
fig=plt.figure(figsize=(12,12))
# print 'aa'
# print act_scene_graph.nodes()
actors=[i for j in active_actors.values() for i in j]
nx.draw_networkx_nodes(act_scene_graph,pos_Scene,nodelist=list(set(actors)),node_color='r',node_size=500, node_shape='o',alpha=.3)
nx.draw_networkx_nodes(act_scene_graph,pos_Scene,nodelist=active_actors.keys(),node_color='b',node_size=700,node_shape='s',alpha =.2)
lso=nx.draw_networkx_edges(act_scene_graph,pos_Scene,edge_color='g',alpha=0.35)
# print "be"
lsbe=nx.draw_networkx_labels(act_scene_graph,pos_Scene,font_size=12)#17)
plt.title('Bipartite graph of actors participating in Macbeth acts',fontsize=22)
# print "be"

mon=plt.axis('off')
Name: 
Type: Graph
Number of nodes: 45
Number of edges: 72
Average degree:   3.2000

Decomposition of Shakespeare's Macbeth in Networks of Scenes (included in Acts)

In [88]:
graph_dic_scene,ract_dic,pernode_dict,nodper_dic,cnum,active_actors_sc=create_graph_dict(scen_dict,pers_l,pers_dict,u,attribute_dict)
G, list_of_Graphs_final, Gagr, edgeList ,nmap ,mapping,k,n=synthetic_multi_level_dict(graph_dic_scene,pernode_dict,nodper_dic,ract_dic,No_isolates=True)
conver_rel = 0

pos_dict={}
counter=0
act_rel=[]
for k in sorted(graph_dic_scene):
    v=graph_dic_scene[k]
# for k,v in graph_dic_scene.items():
#     print k,v.nodes()
#     print v.edges()
    v.remove_nodes_from(nx.isolates(v))
#     print v,nx.isolates(v)
    print counter,
    print nx.info(v)
    for nd in v.nodes():
        act_rel.append(nd)
    print 'Number of actors appearing in Macbeth scene %s: %i' %(k,len(active_actors_sc[k]))
    conver_rel += len(v.edges())
    print
    counter+=1
    
print 'Actors participating in all conversational relationships in all Macbeth Scenes:'  
print
for i in pernode_dict:
    print i
print
print 'The total number of actors participating in all conversational relationships in all Macbeth Scenes is', len(set(act_rel))
print 
print 'The total number of conversational relationships (edges) among actors \
participating in all Macbeth Scenes is', conver_rel
0 Name: Act I.I
Type: Graph
Number of nodes: 2
Number of edges: 1
Average degree:   1.0000
Number of actors appearing in Macbeth scene I.I: 3

1 Name: Act I.II
Type: Graph
Number of nodes: 6
Number of edges: 4
Average degree:   1.3333
Number of actors appearing in Macbeth scene I.II: 5

2 Name: Act I.III
Type: Graph
Number of nodes: 6
Number of edges: 7
Average degree:   2.3333
Number of actors appearing in Macbeth scene I.III: 8

3 Name: Act I.IV
Type: Graph
Number of nodes: 3
Number of edges: 2
Average degree:   1.3333
Number of actors appearing in Macbeth scene I.IV: 4

4 Name: Act I.V
Type: Graph
Number of nodes: 2
Number of edges: 1
Average degree:   1.0000
Number of actors appearing in Macbeth scene I.V: 2

5 Name: Act I.VI
Type: Graph
Number of nodes: 0
Number of edges: 0

Number of actors appearing in Macbeth scene I.VI: 3

6 Name: Act I.VII
Type: Graph
Number of nodes: 3
Number of edges: 2
Average degree:   1.3333
Number of actors appearing in Macbeth scene I.VII: 2

7 Name: Act II.I
Type: Graph
Number of nodes: 5
Number of edges: 4
Average degree:   1.6000
Number of actors appearing in Macbeth scene II.I: 9

8 Name: Act II.II
Type: Graph
Number of nodes: 6
Number of edges: 6
Average degree:   2.0000
Number of actors appearing in Macbeth scene II.II: 3

9 Name: Act III.I
Type: Graph
Number of nodes: 3
Number of edges: 2
Average degree:   1.3333
Number of actors appearing in Macbeth scene III.I: 6

10 Name: Act III.II
Type: Graph
Number of nodes: 6
Number of edges: 5
Average degree:   1.6667
Number of actors appearing in Macbeth scene III.II: 3

11 Name: Act III.III
Type: Graph
Number of nodes: 4
Number of edges: 2
Average degree:   1.0000
Number of actors appearing in Macbeth scene III.III: 4

12 Name: Act III.IV
Type: Graph
Number of nodes: 7
Number of edges: 5
Average degree:   1.4286
Number of actors appearing in Macbeth scene III.IV: 5

13 Name: Act III.V
Type: Graph
Number of nodes: 3
Number of edges: 2
Average degree:   1.3333
Number of actors appearing in Macbeth scene III.V: 2

14 Name: Act III.VI
Type: Graph
Number of nodes: 10
Number of edges: 10
Average degree:   2.0000
Number of actors appearing in Macbeth scene III.VI: 2

15 Name: Act IV.I
Type: Graph
Number of nodes: 9
Number of edges: 10
Average degree:   2.2222
Number of actors appearing in Macbeth scene IV.I: 10

16 Name: Act IV.II
Type: Graph
Number of nodes: 0
Number of edges: 0

Number of actors appearing in Macbeth scene IV.II: 5

17 Name: Act IV.III
Type: Graph
Number of nodes: 6
Number of edges: 8
Average degree:   2.6667
Number of actors appearing in Macbeth scene IV.III: 4

18 Name: Act V.I
Type: Graph
Number of nodes: 5
Number of edges: 3
Average degree:   1.2000
Number of actors appearing in Macbeth scene V.I: 3

19 Name: Act V.II
Type: Graph
Number of nodes: 2
Number of edges: 1
Average degree:   1.0000
Number of actors appearing in Macbeth scene V.II: 2

20 Name: Act V.III
Type: Graph
Number of nodes: 6
Number of edges: 6
Average degree:   2.0000
Number of actors appearing in Macbeth scene V.III: 4

21 Name: Act V.IV
Type: Graph
Number of nodes: 0
Number of edges: 0

Number of actors appearing in Macbeth scene V.IV: 4

22 Name: Act V.V
Type: Graph
Number of nodes: 0
Number of edges: 0

Number of actors appearing in Macbeth scene V.V: 3

23 Name: Act V.VI
Type: Graph
Number of nodes: 2
Number of edges: 1
Average degree:   1.0000
Number of actors appearing in Macbeth scene V.VI: 3

24 Name: Act V.VII
Type: Graph
Number of nodes: 3
Number of edges: 3
Average degree:   2.0000
Number of actors appearing in Macbeth scene V.VII: 5

Actors participating in all conversational relationships in all Macbeth Scenes:

DONALBAIN
SERVANT
OLD MAN
THIRD WITCH
YOUNG SEYWARD
MESSENGER
WITCHES
SOLDIERS
SECOND MURDERER
LORDS
LENNOX
MACDUFF
HECAT
DOCTOR
MALCOLM
LADY MACBETH
SON
THIRD MURDERER
BANQUO
FIRST WITCH
LORD
ROSS
FIRST APPARITION
PORTER
SEYWARD
ANGUS
FIRST MURDERER
GENTLEWOMAN
FLEANCE
SECOND APPARITION
DUNCAN
SEYTON
WIFE
MACBETH
MESSENGER TO WIFE
SECOND WITCH
THIRD APPARITION
CAPTAIN
MURDERERS
ENGLISH DOCTOR

The total number of actors participating in all conversational relationships in all Macbeth Scenes is 28

The total number of conversational relationships (edges) among actors participating in all Macbeth Scenes is 85
In [89]:
act_scene_graph=create_two_mode_act_scene_graph(active_actors_sc)
print nx.info(act_scene_graph)
pos_Scene=nx.spring_layout(act_scene_graph,scale=50)
# nx.draw_networkx(act_scene_graph,pos)
fig=plt.figure(figsize=(12,12))
# print 'aa'
# print act_scene_graph.nodes()
actors=[i for j in active_actors_sc.values() for i in j]
nx.draw_networkx_nodes(act_scene_graph,pos_Scene,nodelist=list(set(actors)),node_color='r',node_size=500, node_shape='o',alpha=.3)
nx.draw_networkx_nodes(act_scene_graph,pos_Scene,nodelist=active_actors_sc.keys(),node_color='b',node_size=700,node_shape='s',alpha =.2)
lso=nx.draw_networkx_edges(act_scene_graph,pos_Scene,edge_color='g',alpha=0.35)
# print "be"
lsbe=nx.draw_networkx_labels(act_scene_graph,pos_Scene,font_size=12)#17)
plt.title('Bipartite graph of actors participating in Macbeth scenes',fontsize=22)
# print "be"

mon=plt.axis('off')
Name: 
Type: Graph
Number of nodes: 65
Number of edges: 104
Average degree:   3.2000

PART B:

Interactive Network Computations on Shakespeare's Macbeth

In [90]:
%autoreload 2
from testy2 import *
from syntheticThreeLayerGraph_time import synthetic_multi_level_dict,plot_graph_dict,plot_graph_k_n, plot_total_graph_with_weights

fileName = 'corpora/ShakespeareMacbethOrig_from_PG_mod.txt'
f=open(fileName,'r')
attributes_filename='corpora/Character Atrributes - Macbeth - 1.csv'

act_dict,u,pers_l,pers_dict,pact,lact,scen_dict,lscen,pscen=create_dict_of_acts(fileName)
fop=open('list_of_attributes_dic.dmpp')
list_of_attributes_dic=pickle.load(fop)
fop.close()
fop=open('attribute_dict.dmpp')
attribute_dict=pickle.load(fop)
fop.close()
fop=open('list_of_att.dmpp')
list_of_att=pickle.load(fop)
fop.close()
# attribute_dict={}
# af=open(attributes_filename,'r')

lis_pret=['Name','Gender','Social Status','Alliance','Drive','Count of speech characters']#,'All Attributes']
# pret=PrettyTable(lis_pret)
# pret.padding_width=1
In [91]:
graph_dic,ract_dic,pernode_dict,nodper_dic,cnum,active_actors=create_graph_dict(act_dict,pers_l,pers_dict,u,attribute_dict)
G, list_of_Graphs_final, Gagr, edgeList ,nmap ,mapping,k,n=synthetic_multi_level_dict(graph_dic,pernode_dict,nodper_dic,ract_dic,No_isolates=True)
conver_rel = 0

pos_dict={}

for k,v in graph_dic.items():
    v.remove_nodes_from(nx.isolates(v))
    conver_rel += len(v.edges())
# print cnum
# graph_dic_scene,ract_dicS,pernode_dictS,nodper_dicS,cnumS,active_actors_sc=create_graph_dict(scen_dict,pers_l,pers_dict,u,attribute_dict)
# G, list_of_Graphs_finalS, GagrS, edgeListS ,nmapS ,mappingS,k,n=synthetic_multi_level_dict(graph_dic_scene,pernode_dictS,nodper_dicS,ract_dicS,No_isolates=True)
# for k,v in graph_dic_scene.items():
#     v.remove_nodes_from(nx.isolates(v))
# #     conver_rel += len(v.edges())
# # print cnumS
# ract_dic.update(ract_dicS)
# for ll in cnumS:
#     cnum.append(ll)
# # cnum.update(cnumS)
# uu=len(graph_dic.keys())
# scene_acts={'Scene '+str(i):u+uu for u,i in enumerate(sorted(graph_dic_scene.keys()))}
met_acts={'Act '+str(i):u for u,i in enumerate(sorted(graph_dic.keys())) }
# uu=len()
met_acts['(all Acts)'] = 1000
# met_acts.update(scene_acts)
graph_dic['(all Acts)']=plot_total_graph_with_weights(graph_dic,nodper_dic)
# graph_dic.update(graph_dic_scene)
rmet_acts={k:v for v,k in met_acts.items()}

All Acts Macbeth Network Visualization

In [92]:
import pandas as pd
attr_dict_graph={5:'count_of_speech_characters',1:'gender',2:'social_status',3:'alliance',4:'drive'}
# print ww.result
index_graph=1000
if index_graph !=1000:
    play_st="Macbeth's Act"
   
    
    H = graph_dic[ract_dic[cnum[index_graph]]]
else:
#     print 'a'
    play_st="Macbeth Network"
    H=graph_dic['(all Acts)']
act_st=rmet_acts[index_graph]

# select_attribute=select_attributes.result

# print select_attribute
# print play_st,act_st
try:
    f=open('positions_of_Mc_Shake.dmp')
    pos_dict=pickle.load(f)
    pos =pos_dict[index_graph]
except:
    pos=nx.spring_layout(H,scale=50)
    pos_dict[index_graph]=pos
print "The number of actors in %s %s is %i" %(play_st,act_st, len(H.nodes()))
print "The number of conversational relationships in %s %s is %i" %(play_st,act_st, len(H.edges()))
print
print 'WEIGHTED CONVERSATIONAL RELATIONSHIPS:'
print
for edge in H.edges(data=True):
    print '(%s, %s)' %(nodper_dic[edge[0]],nodper_dic[edge[1]]),edge[2]['weight']
print 
sstt=play_st[:7]+' '+act_st+ ' '+'Network'
H.remove_nodes_from(nx.isolates(H))
posit=draw_network(H,sstt,pos=pos,with_edgewidth=True,withLabels=True,pernode_dict=pernode_dict,labfs=10,valpha=0.4,ealpha=0.4,labelfont=10)
The number of actors in Macbeth Network (all Acts) is 28
The number of conversational relationships in Macbeth Network (all Acts) is 56

WEIGHTED CONVERSATIONAL RELATIONSHIPS:

(DONALBAIN, LADY MACBETH) 1
(DONALBAIN, LENNOX) 1
(DONALBAIN, MACDUFF) 1
(SERVANT, MACBETH) 1
(SERVANT, SOLDIERS) 1
(THIRD WITCH, MACBETH) 4
(THIRD WITCH, BANQUO) 1
(SOLDIERS, MACBETH) 2
(SECOND APPARITION, MACBETH) 1
(LENNOX, MACBETH) 2
(LENNOX, MACDUFF) 3
(LENNOX, MALCOLM) 1
(LENNOX, BANQUO) 1
(LENNOX, SEYWARD) 1
(LENNOX, FLEANCE) 3
(LENNOX, DUNCAN) 2
(MACDUFF, MACBETH) 7
(MACDUFF, WIFE) 3
(MACDUFF, MACDUFF) 2
(MACDUFF, MALCOLM) 4
(MACDUFF, LORD) 1
(MACDUFF, FIRST APPARITION) 1
(MACDUFF, ROSS) 1
(HECAT, MACBETH) 2
(HECAT, FIRST WITCH) 1
(DOCTOR, MACBETH) 3
(DOCTOR, GENTLEWOMAN) 1
(MALCOLM, WIFE) 1
(MALCOLM, MACBETH) 7
(MALCOLM, ROSS) 1
(MALCOLM, SEYWARD) 2
(MALCOLM, DUNCAN) 1
(LADY MACBETH, WIFE) 1
(LADY MACBETH, BANQUO) 2
(LADY MACBETH, DUNCAN) 3
(THIRD MURDERER, MACBETH) 1
(BANQUO, MACBETH) 12
(BANQUO, FIRST WITCH) 1
(BANQUO, FLEANCE) 1
(BANQUO, DUNCAN) 3
(FIRST WITCH, MACBETH) 4
(LORD, SEYWARD) 1
(LORD, DUNCAN) 1
(FIRST APPARITION, MACBETH) 1
(FLEANCE, MACBETH) 4
(DUNCAN, MACBETH) 8
(DUNCAN, ROSS) 2
(SEYTON, MACBETH) 1
(WIFE, MACBETH) 1
(WIFE, ROSS) 1
(MACBETH, MACBETH) 5
(MACBETH, SECOND WITCH) 1
(MACBETH, THIRD APPARITION) 1
(MACBETH, CAPTAIN) 1
(MACBETH, MURDERERS) 1
(MACBETH, ROSS) 2

Attribute Assortativity (Homophily) Coefficients of All Acts Macbeth Network

In [93]:
draw_assor_attr_subplots(H,pos,sstt,attr_dict_graph,lis_pret,label_font=10,titlefont=20)
Macbeth (all Acts) Network

Centralities of All Acts Macbeth Network

In [94]:
draw_centralities_subplots(H,pos,withLabels=True,labfs=15)
labels={i:v for v,i in pernode_dict.items() if i in H.nodes()}
print 'Correspondence between IDs of nodes and names of actors:'
print
print labels
Correspondence between IDs of nodes and names of actors:

{0: 'DONALBAIN', 1: 'SERVANT', 3: 'THIRD WITCH', 7: 'SOLDIERS', 9: 'SECOND APPARITION', 11: 'LENNOX', 12: 'MACDUFF', 13: 'HECAT', 14: 'DOCTOR', 15: 'MALCOLM', 17: 'LADY MACBETH', 19: 'THIRD MURDERER', 20: 'BANQUO', 21: 'FIRST WITCH', 22: 'LORD', 23: 'FIRST APPARITION', 25: 'SEYWARD', 28: 'GENTLEWOMAN', 29: 'FLEANCE', 30: 'DUNCAN', 31: 'SEYTON', 32: 'WIFE', 33: 'MACBETH', 35: 'SECOND WITCH', 36: 'THIRD APPARITION', 37: 'CAPTAIN', 38: 'MURDERERS', 39: 'ROSS'}

Communities of All Acts Macbeth Network

In [95]:
from chAs import draw_comms,modul_arity
import community as comm

# G = graph_dic[ract_dic[cnum[0]]]
H.remove_nodes_from(nx.isolates(H))
labels={i:v for v,i in pernode_dict.items() if i in H.nodes()}

part=comm.best_partition(H) 
print 'Number of communities of %s = %i' %(sstt, max(part.values())+1)
print 'Community partition of %s:' %(sstt)
parLis=[]
partdi={}
for i,k in part.items():
    if k not in partdi:
        partdi[k]=[nodper_dic[i]]
    else:
        partdi[k].append(nodper_dic[i])
for i,k in partdi.items():
    parLis.append(k)
print parLis
print 'Community modularity of %s = %.4f' %(sstt, comm.modularity(part,H))

d=0.8 
dd=0.8
c=1.2
cc=1.4
alpha=0.2
ealpha=.2
vcc={}
sstta="The %s %s Communities" %(max(part.values())+1,sstt)

draw_comms(H,H.nodes(),[],[],[] ,part,part,d,dd,c,cc,alpha,ealpha,nodper_dic,sstta,titlefont=20,labelfont=10)
Number of communities of Macbeth (all Acts) Network = 3
Community partition of Macbeth (all Acts) Network:
[['DONALBAIN', 'LENNOX', 'LADY MACBETH', 'FLEANCE', 'DUNCAN'], ['SERVANT', 'THIRD WITCH', 'SOLDIERS', 'SECOND APPARITION', 'HECAT', 'DOCTOR', 'THIRD MURDERER', 'BANQUO', 'FIRST WITCH', 'GENTLEWOMAN', 'SEYTON', 'MACBETH', 'SECOND WITCH', 'THIRD APPARITION', 'CAPTAIN', 'MURDERERS'], ['MACDUFF', 'MALCOLM', 'LORD', 'FIRST APPARITION', 'SEYWARD', 'WIFE', 'ROSS']]
Community modularity of Macbeth (all Acts) Network = 0.2040

Act I Macbeth Network Visualization

In [96]:
import pandas as pd
attr_dict_graph={5:'count_of_speech_characters',1:'gender',2:'social_status',3:'alliance',4:'drive'}
# print ww.result
# index_graph=ww.result
index_graph=0
if index_graph !=1000:
    play_st="Macbeth's Act"
   
    
    H = graph_dic[ract_dic[cnum[index_graph]]]
else:
#     print 'a'
    play_st="Macbeth Network"
    H=graph_dic['(all Acts)']
act_st=rmet_acts[index_graph]

# select_attribute=select_attributes.result

# print select_attribute
# print play_st,act_st
try:
    f=open('positions_of_Mc_Shake_acts.dmp')
    pos_dict=pickle.load(f)
    pos =pos_dict[index_graph]
except:
    pos=nx.spring_layout(H,scale=50)
    pos_dict[index_graph]=pos
# print sorted(pos_dict.keys())
# print graph_dic.keys()
# for jjj in pos_dict:
#     print jjj
#     print sorted(pos_dict[jjj].keys())
#     print sorted(H.nodes())
print "The number of actors in %s %s is %i" %(play_st,act_st, len(H.nodes()))
print "The number of conversational relationships in %s %s is %i" %(play_st,act_st, len(H.edges()))
print
print 'WEIGHTED CONVERSATIONAL RELATIONSHIPS:'
print
for edge in H.edges(data=True):
    print '(%s, %s)' %(nodper_dic[edge[0]],nodper_dic[edge[1]]),edge[2]['weight']
print 
sstt=play_st[:7]+' '+act_st+ ' '+'Network'
H.remove_nodes_from(nx.isolates(H))
posit=draw_network(H,sstt,pos=pos,with_edgewidth=True,withLabels=True,pernode_dict=pernode_dict,labfs=10,valpha=0.4,ealpha=0.4,labelfont=20)
The number of actors in Macbeth's Act Act I is 10
The number of conversational relationships in Macbeth's Act Act I is 13

WEIGHTED CONVERSATIONAL RELATIONSHIPS:

(THIRD WITCH, MACBETH) 4
(THIRD WITCH, BANQUO) 1
(MALCOLM, DUNCAN) 1
(MALCOLM, ROSS) 1
(LADY MACBETH, DUNCAN) 2
(BANQUO, MACBETH) 1
(BANQUO, FIRST WITCH) 1
(BANQUO, DUNCAN) 3
(FIRST WITCH, MACBETH) 3
(DUNCAN, MACBETH) 5
(MACBETH, SECOND WITCH) 1
(MACBETH, CAPTAIN) 1
(MACBETH, ROSS) 1

Attribute Assortativity (Homophily) Coefficients of Act I Macbeth Network

In [97]:
draw_assor_attr_subplots(H,pos,sstt,attr_dict_graph,lis_pret,label_font=10,titlefont=20)
Macbeth Act I Network

Centralities of Act I Macbeth Network

In [98]:
draw_centralities_subplots(H,pos,withLabels=True,labfs=15)
labels={i:v for v,i in pernode_dict.items() if i in H.nodes()}
print 'Correspondence between IDs of nodes and names of actors:'
print
print labels
Correspondence between IDs of nodes and names of actors:

{33: 'MACBETH', 3: 'THIRD WITCH', 37: 'CAPTAIN', 39: 'ROSS', 15: 'MALCOLM', 17: 'LADY MACBETH', 35: 'SECOND WITCH', 20: 'BANQUO', 21: 'FIRST WITCH', 30: 'DUNCAN'}

Communities of Act I Macbeth Network

In [99]:
from chAs import draw_comms,modul_arity
import community as comm

# G = graph_dic[ract_dic[cnum[0]]]
H.remove_nodes_from(nx.isolates(H))
labels={i:v for v,i in pernode_dict.items() if i in H.nodes()}

part=comm.best_partition(H) 
print 'Number of communities of %s = %i' %(sstt, max(part.values())+1)
print 'Community partition of %s:' %(sstt)
parLis=[]
partdi={}
for i,k in part.items():
    if k not in partdi:
        partdi[k]=[nodper_dic[i]]
    else:
        partdi[k].append(nodper_dic[i])
for i,k in partdi.items():
    parLis.append(k)
print parLis
print 'Community modularity of %s = %.4f' %(sstt, comm.modularity(part,H))

d=0.8 
dd=0.8
c=1.2
cc=1.4
alpha=0.2
ealpha=.2
vcc={}
sstta="The %s %s Communities" %(max(part.values())+1,sstt)

draw_comms(H,H.nodes(),[],[],[] ,part,part,d,dd,c,cc,alpha,ealpha,nodper_dic,sstta,titlefont=20,labelfont=20)
Number of communities of Macbeth Act I Network = 3
Community partition of Macbeth Act I Network:
[['MACBETH', 'THIRD WITCH', 'CAPTAIN', 'SECOND WITCH', 'FIRST WITCH'], ['ROSS', 'MALCOLM'], ['LADY MACBETH', 'BANQUO', 'DUNCAN']]
Community modularity of Macbeth Act I Network = 0.1576

Act II Macbeth Network Visualization

In [100]:
import pandas as pd
attr_dict_graph={5:'count_of_speech_characters',1:'gender',2:'social_status',3:'alliance',4:'drive'}
# print ww.result
index_graph=1
if index_graph !=1000:
    play_st="Macbeth's Act"
   
    
    H = graph_dic[ract_dic[cnum[index_graph]]]
else:
#     print 'a'
    play_st="Macbeth Network"
    H=graph_dic['(all Acts)']
act_st=rmet_acts[index_graph]

# select_attribute=select_attributes.result

# print select_attribute
# print play_st,act_st
try:
    f=open('positions_of_Mc_Shake_acts.dmp')
    pos_dict=pickle.load(f)
    pos =pos_dict[index_graph]
except:
    pos=nx.spring_layout(H,scale=50)
    pos_dict[index_graph]=pos
print "The number of actors in %s %s is %i" %(play_st,act_st, len(H.nodes()))
print "The number of conversational relationships in %s %s is %i" %(play_st,act_st, len(H.edges()))
print
print 'WEIGHTED CONVERSATIONAL RELATIONSHIPS:'
print
for edge in H.edges(data=True):
    print '(%s, %s)' %(nodper_dic[edge[0]],nodper_dic[edge[1]]),edge[2]['weight']
print 
sstt=play_st[:7]+' '+act_st+ ' '+'Network'
H.remove_nodes_from(nx.isolates(H))
posit=draw_network(H,sstt,pos=pos,with_edgewidth=True,withLabels=True,pernode_dict=pernode_dict,labfs=10,valpha=0.4,ealpha=0.4,labelfont=20)
The number of actors in Macbeth's Act Act II is 8
The number of conversational relationships in Macbeth's Act Act II is 10

WEIGHTED CONVERSATIONAL RELATIONSHIPS:

(DONALBAIN, LADY MACBETH) 1
(DONALBAIN, MACDUFF) 1
(MACDUFF, MACBETH) 1
(MACDUFF, ROSS) 1
(MACDUFF, MALCOLM) 1
(DUNCAN, MACBETH) 2
(DUNCAN, ROSS) 2
(MACBETH, MACBETH) 2
(MACBETH, MURDERERS) 1
(MACBETH, ROSS) 1

Attribute Assortativity (Homophily) Coefficients of Act II Macbeth Network

In [101]:
draw_assor_attr_subplots(H,pos,sstt,attr_dict_graph,lis_pret,label_font=10,titlefont=20)
Macbeth Act II Network

Centralities of Act II Macbeth Network

In [102]:
draw_centralities_subplots(H,pos,withLabels=True,labfs=15)
labels={i:v for v,i in pernode_dict.items() if i in H.nodes()}
print 'Correspondence between IDs of nodes and names of actors:'
print
print labels
Correspondence between IDs of nodes and names of actors:

{0: 'DONALBAIN', 33: 'MACBETH', 38: 'MURDERERS', 39: 'ROSS', 12: 'MACDUFF', 15: 'MALCOLM', 17: 'LADY MACBETH', 30: 'DUNCAN'}

Communities of Act II Macbeth Network

In [103]:
from chAs import draw_comms,modul_arity
import community as comm

# G = graph_dic[ract_dic[cnum[0]]]
H.remove_nodes_from(nx.isolates(H))
labels={i:v for v,i in pernode_dict.items() if i in H.nodes()}

part=comm.best_partition(H) 
print 'Number of communities of %s = %i' %(sstt, max(part.values())+1)
print 'Community partition of %s:' %(sstt)
parLis=[]
partdi={}
for i,k in part.items():
    if k not in partdi:
        partdi[k]=[nodper_dic[i]]
    else:
        partdi[k].append(nodper_dic[i])
for i,k in partdi.items():
    parLis.append(k)
print parLis
print 'Community modularity of %s = %.4f' %(sstt, comm.modularity(part,H))

d=0.8 
dd=0.8
c=1.2
cc=1.4
alpha=0.2
ealpha=.2
vcc={}
sstta="The %s %s Communities" %(max(part.values())+1,sstt)

draw_comms(H,H.nodes(),[],[],[] ,part,part,d,dd,c,cc,alpha,ealpha,nodper_dic,sstta,titlefont=20,labelfont=20)
Number of communities of Macbeth Act II Network = 3
Community partition of Macbeth Act II Network:
[['DONALBAIN', 'MACDUFF', 'MALCOLM', 'LADY MACBETH'], ['MACBETH', 'MURDERERS'], ['ROSS', 'DUNCAN']]
Community modularity of Macbeth Act II Network = 0.2781

Act III Macbeth Network Visualization

In [104]:
import pandas as pd
attr_dict_graph={5:'count_of_speech_characters',1:'gender',2:'social_status',3:'alliance',4:'drive'}
# print ww.result
index_graph=2
if index_graph !=1000:
    play_st="Macbeth's Act"
   
    
    H = graph_dic[ract_dic[cnum[index_graph]]]
else:
#     print 'a'
    play_st="Macbeth Network"
    H=graph_dic['(all Acts)']
act_st=rmet_acts[index_graph]

# select_attribute=select_attributes.result

# print select_attribute
# print play_st,act_st
try:
    f=open('positions_of_Mc_Shake_acts.dmp')
    pos_dict=pickle.load(f)
    pos =pos_dict[index_graph]
except:
    pos=nx.spring_layout(H,scale=50)
    pos_dict[index_graph]=pos
print "The number of actors in %s %s is %i" %(play_st,act_st, len(H.nodes()))
print "The number of conversational relationships in %s %s is %i" %(play_st,act_st, len(H.edges()))
print
print 'WEIGHTED CONVERSATIONAL RELATIONSHIPS:'
print
for edge in H.edges(data=True):
    print '(%s, %s)' %(nodper_dic[edge[0]],nodper_dic[edge[1]]),edge[2]['weight']
print 
sstt=play_st[:7]+' '+act_st+ ' '+'Network'
H.remove_nodes_from(nx.isolates(H))
posit=draw_network(H,sstt,pos=pos,with_edgewidth=True,withLabels=True,pernode_dict=pernode_dict,labfs=10,valpha=0.4,ealpha=0.4,labelfont=20)
The number of actors in Macbeth's Act Act III is 15
The number of conversational relationships in Macbeth's Act Act III is 21

WEIGHTED CONVERSATIONAL RELATIONSHIPS:

(DONALBAIN, LENNOX) 1
(SERVANT, MACBETH) 1
(LENNOX, MACBETH) 2
(LENNOX, MACDUFF) 2
(LENNOX, MALCOLM) 1
(LENNOX, BANQUO) 1
(LENNOX, FLEANCE) 3
(LENNOX, DUNCAN) 2
(MACDUFF, MACBETH) 1
(MACDUFF, LORD) 1
(HECAT, MACBETH) 2
(HECAT, FIRST WITCH) 1
(LADY MACBETH, BANQUO) 1
(LADY MACBETH, DUNCAN) 1
(THIRD MURDERER, MACBETH) 1
(BANQUO, FLEANCE) 1
(BANQUO, MACBETH) 8
(LORD, SEYWARD) 1
(LORD, DUNCAN) 1
(FLEANCE, MACBETH) 4
(DUNCAN, MACBETH) 1

Attribute Assortativity (Homophily) Coefficients of Act III Macbeth Network

In [105]:
draw_assor_attr_subplots(H,pos,sstt,attr_dict_graph,lis_pret,label_font=10,titlefont=20)
Macbeth Act III Network

Centralities of Act III Macbeth Network

In [106]:
draw_centralities_subplots(H,pos,withLabels=True,labfs=15)
labels={i:v for v,i in pernode_dict.items() if i in H.nodes()}
print 'Correspondence between IDs of nodes and names of actors:'
print
print labels
Correspondence between IDs of nodes and names of actors:

{0: 'DONALBAIN', 1: 'SERVANT', 33: 'MACBETH', 11: 'LENNOX', 12: 'MACDUFF', 13: 'HECAT', 15: 'MALCOLM', 17: 'LADY MACBETH', 19: 'THIRD MURDERER', 20: 'BANQUO', 21: 'FIRST WITCH', 22: 'LORD', 25: 'SEYWARD', 29: 'FLEANCE', 30: 'DUNCAN'}

Communities of Act III Macbeth Network

In [107]:
from chAs import draw_comms,modul_arity
import community as comm

# G = graph_dic[ract_dic[cnum[0]]]
H.remove_nodes_from(nx.isolates(H))
labels={i:v for v,i in pernode_dict.items() if i in H.nodes()}

part=comm.best_partition(H) 
print 'Number of communities of %s = %i' %(sstt, max(part.values())+1)
print 'Community partition of %s:' %(sstt)
parLis=[]
partdi={}
for i,k in part.items():
    if k not in partdi:
        partdi[k]=[nodper_dic[i]]
    else:
        partdi[k].append(nodper_dic[i])
for i,k in partdi.items():
    parLis.append(k)
print parLis
print 'Community modularity of %s = %.4f' %(sstt, comm.modularity(part,H))

d=0.8 
dd=0.8
c=1.2
cc=1.4
alpha=0.2
ealpha=.2
vcc={}
sstta="The %s %s Communities" %(max(part.values())+1,sstt)

draw_comms(H,H.nodes(),[],[],[] ,part,part,d,dd,c,cc,alpha,ealpha,nodper_dic,sstta,titlefont=20,labelfont=20)
Number of communities of Macbeth Act III Network = 3
Community partition of Macbeth Act III Network:
[['DONALBAIN', 'LENNOX', 'MACDUFF', 'MALCOLM', 'LADY MACBETH', 'LORD', 'SEYWARD', 'DUNCAN'], ['SERVANT', 'MACBETH', 'THIRD MURDERER', 'BANQUO', 'FLEANCE'], ['HECAT', 'FIRST WITCH']]
Community modularity of Macbeth Act III Network = 0.2392

Act IV Macbeth Network Visualization

In [108]:
import pandas as pd
attr_dict_graph={5:'count_of_speech_characters',1:'gender',2:'social_status',3:'alliance',4:'drive'}
# print ww.result
index_graph=3
if index_graph !=1000:
    play_st="Macbeth's Act"
   
    
    H = graph_dic[ract_dic[cnum[index_graph]]]
else:
#     print 'a'
    play_st="Macbeth Network"
    H=graph_dic['(all Acts)']
act_st=rmet_acts[index_graph]

# select_attribute=select_attributes.result

# print select_attribute
# print play_st,act_st
try:
    f=open('positions_of_Mc_Shake_acts.dmp')
    pos_dict=pickle.load(f)
    pos =pos_dict[index_graph]
except:
    pos=nx.spring_layout(H,scale=50)
    pos_dict[index_graph]=pos
print "The number of actors in %s %s is %i" %(play_st,act_st, len(H.nodes()))
print "The number of conversational relationships in %s %s is %i" %(play_st,act_st, len(H.edges()))
print
print 'WEIGHTED CONVERSATIONAL RELATIONSHIPS:'
print
for edge in H.edges(data=True):
    print '(%s, %s)' %(nodper_dic[edge[0]],nodper_dic[edge[1]]),edge[2]['weight']
print 
sstt=play_st[:7]+' '+act_st+ ' '+'Network'
H.remove_nodes_from(nx.isolates(H))
posit=draw_network(H,sstt,pos=pos,with_edgewidth=True,withLabels=True,pernode_dict=pernode_dict,labfs=10,valpha=0.4,ealpha=0.4,labelfont=20)
The number of actors in Macbeth's Act Act IV is 12
The number of conversational relationships in Macbeth's Act Act IV is 17

WEIGHTED CONVERSATIONAL RELATIONSHIPS:

(SECOND APPARITION, MACBETH) 1
(LENNOX, MACDUFF) 1
(MACDUFF, WIFE) 2
(MACDUFF, MACBETH) 3
(MACDUFF, MACDUFF) 1
(MACDUFF, MALCOLM) 1
(MACDUFF, FIRST APPARITION) 1
(MALCOLM, WIFE) 1
(MALCOLM, MACBETH) 5
(MALCOLM, SEYWARD) 2
(BANQUO, MACBETH) 3
(FIRST WITCH, MACBETH) 1
(FIRST APPARITION, MACBETH) 1
(WIFE, MACBETH) 1
(WIFE, ROSS) 1
(MACBETH, MACBETH) 1
(MACBETH, THIRD APPARITION) 1

Attribute Assortativity (Homophily) Coefficients of Act IV Macbeth Network

In [109]:
draw_assor_attr_subplots(H,pos,sstt,attr_dict_graph,lis_pret,label_font=10,titlefont=20)
Macbeth Act IV Network

Centralities of Act IV Macbeth Network

In [110]:
draw_centralities_subplots(H,pos,withLabels=True,labfs=15)
labels={i:v for v,i in pernode_dict.items() if i in H.nodes()}
print 'Correspondence between IDs of nodes and names of actors:'
print
print labels
Correspondence between IDs of nodes and names of actors:

{32: 'WIFE', 33: 'MACBETH', 36: 'THIRD APPARITION', 39: 'ROSS', 9: 'SECOND APPARITION', 11: 'LENNOX', 12: 'MACDUFF', 15: 'MALCOLM', 20: 'BANQUO', 21: 'FIRST WITCH', 23: 'FIRST APPARITION', 25: 'SEYWARD'}

Communities of Act IV Macbeth Network

In [111]:
from chAs import draw_comms,modul_arity
import community as comm

# G = graph_dic[ract_dic[cnum[0]]]
H.remove_nodes_from(nx.isolates(H))
labels={i:v for v,i in pernode_dict.items() if i in H.nodes()}

part=comm.best_partition(H) 
print 'Number of communities of %s = %i' %(sstt, max(part.values())+1)
print 'Community partition of %s:' %(sstt)
parLis=[]
partdi={}
for i,k in part.items():
    if k not in partdi:
        partdi[k]=[nodper_dic[i]]
    else:
        partdi[k].append(nodper_dic[i])
for i,k in partdi.items():
    parLis.append(k)
print parLis
print 'Community modularity of %s = %.4f' %(sstt, comm.modularity(part,H))

d=0.8 
dd=0.8
c=1.2
cc=1.4
alpha=0.2
ealpha=.2
vcc={}
sstta="The %s %s Communities" %(max(part.values())+1,sstt)

draw_comms(H,H.nodes(),[],[],[] ,part,part,d,dd,c,cc,alpha,ealpha,nodper_dic,sstta,titlefont=20,labelfont=20)
Number of communities of Macbeth Act IV Network = 2
Community partition of Macbeth Act IV Network:
[['WIFE', 'ROSS', 'LENNOX', 'MACDUFF', 'FIRST APPARITION'], ['MACBETH', 'THIRD APPARITION', 'SECOND APPARITION', 'MALCOLM', 'BANQUO', 'FIRST WITCH', 'SEYWARD']]
Community modularity of Macbeth Act IV Network = 0.1968

Act V Macbeth Network Visualization

In [112]:
import pandas as pd
attr_dict_graph={5:'count_of_speech_characters',1:'gender',2:'social_status',3:'alliance',4:'drive'}
# print ww.result
index_graph=4
if index_graph !=1000:
    play_st="Macbeth's Act"
   
    
    H = graph_dic[ract_dic[cnum[index_graph]]]
else:
#     print 'a'
    play_st="Macbeth Network"
    H=graph_dic['(all Acts)']
act_st=rmet_acts[index_graph]

# select_attribute=select_attributes.result

# print select_attribute
# print play_st,act_st
try:
    f=open('positions_of_Mc_Shake_acts.dmp')
    pos_dict=pickle.load(f)
    pos =pos_dict[index_graph]
except:
    pos=nx.spring_layout(H,scale=50)
    pos_dict[index_graph]=pos
print "The number of actors in %s %s is %i" %(play_st,act_st, len(H.nodes()))
print "The number of conversational relationships in %s %s is %i" %(play_st,act_st, len(H.edges()))
print
print 'WEIGHTED CONVERSATIONAL RELATIONSHIPS:'
print
for edge in H.edges(data=True):
    print '(%s, %s)' %(nodper_dic[edge[0]],nodper_dic[edge[1]]),edge[2]['weight']
print 
sstt=play_st[:7]+' '+act_st+ ' '+'Network'
H.remove_nodes_from(nx.isolates(H))
posit=draw_network(H,sstt,pos=pos,with_edgewidth=True,withLabels=True,pernode_dict=pernode_dict,labfs=10,valpha=0.4,ealpha=0.4,labelfont=20)
The number of actors in Macbeth's Act Act V is 13
The number of conversational relationships in Macbeth's Act Act V is 14

WEIGHTED CONVERSATIONAL RELATIONSHIPS:

(SERVANT, SOLDIERS) 1
(SOLDIERS, MACBETH) 2
(LENNOX, SEYWARD) 1
(MACDUFF, WIFE) 1
(MACDUFF, MACBETH) 2
(MACDUFF, MACDUFF) 1
(MACDUFF, MALCOLM) 2
(DOCTOR, MACBETH) 3
(DOCTOR, GENTLEWOMAN) 1
(MALCOLM, MACBETH) 2
(LADY MACBETH, WIFE) 1
(LADY MACBETH, BANQUO) 1
(SEYTON, MACBETH) 1
(MACBETH, MACBETH) 2

Attribute Assortativity (Homophily) Coefficients of Act V Macbeth Network

In [113]:
draw_assor_attr_subplots(H,pos,sstt,attr_dict_graph,lis_pret,label_font=10,titlefont=20)
Macbeth Act V Network

Centralities of Act V Macbeth Network

In [114]:
draw_centralities_subplots(H,pos,withLabels=True,labfs=15)
labels={i:v for v,i in pernode_dict.items() if i in H.nodes()}
print 'Correspondence between IDs of nodes and names of actors:'
print
print labels
Correspondence between IDs of nodes and names of actors:

{32: 'WIFE', 1: 'SERVANT', 33: 'MACBETH', 7: 'SOLDIERS', 11: 'LENNOX', 12: 'MACDUFF', 14: 'DOCTOR', 15: 'MALCOLM', 17: 'LADY MACBETH', 20: 'BANQUO', 25: 'SEYWARD', 28: 'GENTLEWOMAN', 31: 'SEYTON'}

Communities of Act V Macbeth Network

In [115]:
from chAs import draw_comms,modul_arity
import community as comm

# G = graph_dic[ract_dic[cnum[0]]]
H.remove_nodes_from(nx.isolates(H))
labels={i:v for v,i in pernode_dict.items() if i in H.nodes()}

part=comm.best_partition(H) 
print 'Number of communities of %s = %i' %(sstt, max(part.values())+1)
print 'Community partition of %s:' %(sstt)
parLis=[]
partdi={}
for i,k in part.items():
    if k not in partdi:
        partdi[k]=[nodper_dic[i]]
    else:
        partdi[k].append(nodper_dic[i])
for i,k in partdi.items():
    parLis.append(k)
print parLis
print 'Community modularity of %s = %.4f' %(sstt, comm.modularity(part,H))

d=0.8 
dd=0.8
c=1.2
cc=1.4
alpha=0.2
ealpha=.2
vcc={}
sstta="The %s %s Communities" %(max(part.values())+1,sstt)

draw_comms(H,H.nodes(),[],[],[] ,part,part,d,dd,c,cc,alpha,ealpha,nodper_dic,sstta,titlefont=20,labelfont=20)
Number of communities of Macbeth Act V Network = 4
Community partition of Macbeth Act V Network:
[['WIFE', 'LADY MACBETH', 'BANQUO'], ['SERVANT', 'MACBETH', 'DOCTOR', 'SOLDIERS', 'GENTLEWOMAN', 'SEYTON'], ['LENNOX', 'SEYWARD'], ['MACDUFF', 'MALCOLM']]
Community modularity of Macbeth Act V Network = 0.3503
In [116]:
f=open('positions_of_Mc_Shake_acts.dmp','w')
# print pos_dict[0]
# print pos_dict[0].keys()

pickle.dump(pos_dict,f)
f.close()
In [ ]: