A simple network
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Foundation code for a network-based computational model of | |
# systemic risk in banking networks. These classes are then | |
# inherited from to create the interbank network itself. | |
__author__="Stuart Gordon Reid" | |
__date__ ="$08 Jan 2014 9:06:32 PM$" | |
# This class encapsulates the code for a Node object. To | |
# inherit from this class simple say: class Bank(Node): | |
class Node: | |
neighbours = [] | |
name = "not set" | |
def __init__(self, nodeName): | |
self.neighbours = [] | |
self.name = nodeName | |
def printNeighbours(self): | |
print "\nNeighbours of ", self.name, ": " | |
for neighbour in self.neighbours: | |
print neighbour.name, "," | |
return | |
def addNeighbour(self, newNode): | |
self.neighbours.append(newNode) | |
return | |
# This class contains the list of nodes in the network to | |
# inherit from this class simple say: class BankNetwork(Graph): | |
class Graph: | |
Nodes = [] | |
def __init__(self, nodes): | |
self.Nodes = [] | |
for node in nodes: | |
self.Nodes.append(node) | |
return | |
def addLink(self, nodeA, nodeB): | |
nodeA.addNeighbour(nodeB) | |
return | |
def addTwoWayLink(self, A, B): | |
nodeA = self.get(A) | |
nodeB = self.get(B) | |
self.addLink(nodeA, nodeB) | |
self.addLink(nodeB, nodeA) | |
return | |
def addOneWayLink(self, A, B): | |
intersectionA = self.get(A) | |
intersectionB = self.get(B) | |
self.addLink(intersectionA, intersectionB) | |
return | |
def get(self, name): | |
#Check if any nodes exist | |
if(len(self.Nodes) == 0): | |
self.Nodes.append(Node(name)) | |
else: | |
fetched = self.Nodes[0] | |
#Check if node already exists | |
found = 0 | |
for node in self.Nodes: | |
if node.name == name: | |
fetched = node | |
found = 1 | |
break | |
#If not found append new node and return | |
if found == 0: | |
fetched = Node(name) | |
self.Nodes.append(fetched) | |
#Return the found / new node | |
return fetched | |
def printNodes(self): | |
print "\nList of all Nodes: " | |
for node in self.Nodes: | |
print node.name, "," | |
return |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment