Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Structural Design Pattern #52

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions seirsplus/networks.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,43 @@

import matplotlib.pyplot as pyplot

from abc import ABCMeta, abstractmethod


class INetwork(metaclass = ABCMeta): #class IBuilder(metaclass = ABCMeta)
"Creational Pattern: The Builder Interface"

@staticmethod
@abstractmethod
def generate_workplace_contact_network():
"Build a workplace contact network"

@staticmethod
@abstractmethod
def generate_demographic_contact_network():
"Build a demographic contact network"

@staticmethod
@abstractmethod
def household_country_data():
"Household data for the United States"

@staticmethod
@asbtractmethod
def custom_exponential_graph():
"Provides the Graph "


@staticmethod
@abstractmethod
def get_result():
"Return all the values"



class Network(INetwork): #class Builder(IBuilder):
"The Concrete Builder"

def generate_workplace_contact_network(num_cohorts=1, num_nodes_per_cohort=100, num_teams_per_cohort=10,
mean_intracohort_degree=6, pct_contacts_intercohort=0.2,
farz_params={'alpha':5.0, 'gamma':5.0, 'beta':0.5, 'r':1, 'q':0.0, 'phi':10,
Expand Down Expand Up @@ -692,7 +726,33 @@ def plot_degree_distn(graph, max_degree=None, show=True, use_seaborn=True):
pyplot.show()


#The Product
class SIERSApp():
"SEIRS Network Models"

def __init__(self):
self.parts = []


#The Director Class
class NetworkDirector:
"Builds the complex representation"

@staticmethod
def construct():
return Builder()\
.generate_workplace_contact_network()\
.generate_demographic_contact_network()\
.household_data()\
.custom_exponential_graph()

#Omitted plot_degree_distn()



#The Client
SEIRSApp = NetworkDirector.construct()
print(APP.parts)



Expand Down
118 changes: 82 additions & 36 deletions seirsplus/utilities.py
Original file line number Diff line number Diff line change
@@ -1,69 +1,115 @@
import numpy
import matplotlib.pyplot as pyplot
from abc import ABCMeta, abstractmethod


class Target(metaclass = ABCMeta):
"Target Interface"

@abstractmethod
def targetRequest(self):
return "Behaviour of the target"

def __init__(self, adaptee: Adaptee):
self.adaptee = adaptee


class Adaptee:

def specificRequest(self):
pass


class Adapter(Target):

def targetRequest(self):
self.adaptee.specificRequest()





def gamma_dist(mean, coeffvar, N):
scale = mean*coeffvar**2
shape = mean/scale
return numpy.random.gamma(scale=scale, shape=shape, size=N)
scale = mean*coeffvar**2
shape = mean/scale
return numpy.random.gamma(scale=scale, shape=shape, size=N)


def dist_info(dists, names=None, plot=False, bin_size=1, colors=None, reverse_plot=False):
dists = [dists] if not isinstance(dists, list) else dists
names = [names] if(names is not None and not isinstance(names, list)) else (names if names is not None else [None]*len(dists))
colors = [colors] if(colors is not None and not isinstance(colors, list)) else (colors if colors is not None else pyplot.rcParams['axes.prop_cycle'].by_key()['color'])
for i, (dist, name) in enumerate(zip(dists, names)):
dists = [dists] if not isinstance(dists, list) else dists
names = [names] if(names is not None and not isinstance(names, list)) else (names if names is not None else [None]*len(dists))
colors = [colors] if(colors is not None and not isinstance(colors, list)) else (colors if colors is not None else pyplot.rcParams['axes.prop_cycle'].by_key()['color'])

for i, (dist, name) in enumerate(zip(dists, names)):
print((name+": " if name else "")+" mean = %.2f, std = %.2f, 95%% CI = (%.2f, %.2f)" % (numpy.mean(dist), numpy.std(dist), numpy.percentile(dist, 2.5), numpy.percentile(dist, 97.5)))
print()

if(plot):
pyplot.hist(dist, bins=numpy.arange(0, int(max(dist)+1), step=bin_size), label=(name if name else False), color=colors[i], edgecolor='white', alpha=0.6, zorder=(-1*i if reverse_plot else i))
pyplot.hist(dist, bins=numpy.arange(0, int(max(dist)+1), step=bin_size), label=(name if name else False), color=colors[i], edgecolor='white', alpha=0.6, zorder=(-1*i if reverse_plot else i))

if(plot):
pyplot.ylabel('num nodes')
pyplot.legend(loc='upper right')
pyplot.show()
if(plot):
pyplot.ylabel('num nodes')
pyplot.legend(loc='upper right')
pyplot.show()


def network_info(networks, names=None, plot=False, bin_size=1, colors=None, reverse_plot=False):
import networkx
networks = [networks] if not isinstance(networks, list) else networks
names = [names] if not isinstance(names, list) else names
colors = [colors] if(colors is not None and not isinstance(colors, list)) else (colors if colors is not None else pyplot.rcParams['axes.prop_cycle'].by_key()['color'])
import networkx
networks = [networks] if not isinstance(networks, list) else networks
names = [names] if not isinstance(names, list) else names
colors = [colors] if(colors is not None and not isinstance(colors, list)) else (colors if colors is not None else pyplot.rcParams['axes.prop_cycle'].by_key()['color'])

for i, (network, name) in enumerate(zip(networks, names)):
for i, (network, name) in enumerate(zip(networks, names)):

degree = [d[1] for d in network.degree()]
degree = [d[1] for d in network.degree()]

if(name):
print(name+":")
print("Degree: mean = %.2f, std = %.2f, 95%% CI = (%.2f, %.2f)\n coeff var = %.2f"
% (numpy.mean(degree), numpy.std(degree), numpy.percentile(degree, 2.5), numpy.percentile(degree, 97.5),
numpy.std(degree)/numpy.mean(degree)))
r = networkx.degree_assortativity_coefficient(network)
print("Assortativity: %.2f" % (r))
c = networkx.average_clustering(network)
print("Clustering coeff: %.2f" % (c))
print()
print(name+":")
print("Degree: mean = %.2f, std = %.2f, 95%% CI = (%.2f, %.2f)\n coeff var = %.2f"
% (numpy.mean(degree), numpy.std(degree), numpy.percentile(degree, 2.5), numpy.percentile(degree, 97.5),
numpy.std(degree)/numpy.mean(degree)))
r = networkx.degree_assortativity_coefficient(network)
print("Assortativity: %.2f" % (r))
c = networkx.average_clustering(network)
print("Clustering coeff: %.2f" % (c))
print()

if(plot):
pyplot.hist(degree, bins=numpy.arange(0, int(max(degree)+1), step=bin_size), label=(name+" degree" if name else False), color=colors[i], edgecolor='white', alpha=0.6, zorder=(-1*i if reverse_plot else i))
pyplot.hist(degree, bins=numpy.arange(0, int(max(degree)+1), step=bin_size), label=(name+" degree" if name else False), color=colors[i], edgecolor='white', alpha=0.6, zorder=(-1*i if reverse_plot else i))

if(plot):
pyplot.ylabel('num nodes')
pyplot.legend(loc='upper right')
pyplot.show()
if(plot):
pyplot.ylabel('num nodes')
pyplot.legend(loc='upper right')
pyplot.show()


def results_summary(model):
print("total percent infected: %0.2f%%" % ((model.total_num_infected()[-1]+model.total_num_recovered()[-1])/model.numNodes * 100) )
print("total percent fatality: %0.2f%%" % (model.numF[-1]/model.numNodes * 100) )
print("peak pct hospitalized: %0.2f%%" % (numpy.max(model.numH)/model.numNodes * 100) )
print("total percent infected: %0.2f%%" % ((model.total_num_infected()[-1]+model.total_num_recovered()[-1])/model.numNodes * 100) )
print("total percent fatality: %0.2f%%" % (model.numF[-1]/model.numNodes * 100) )
print("peak pct hospitalized: %0.2f%%" % (numpy.max(model.numH)/model.numNodes * 100) )




def client(target:Target):
print(target.targetRequest())


if __name__ == "main":
print("Client ")
client(target)
print("\n")


adaptee = Adaptee()
print("Client")
print("Adaptee")
print("Client")


adapter = Adapter(adaptee)
adapter.targetRequest()
client = (adapter)



Expand Down