index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
5,372
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/static/graph.py
|
import tkinter as tk
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.colors import rgb2hex
from networkit.nxadapter import nk2nx
from networkit.viztasks import drawGraph
from networkx import spring_layout
class GraphFrame(tk.Frame):
"""
Frame for showing the current state and actions that can be taken for the static model being run
"""
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.fig = plt.figure(figsize=(8, 8))
self.ax = self.fig.add_subplot(111)
self.canvas = FigureCanvasTkAgg(self.fig, master=self)
self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
self.results = []
self.graph = None
self.pos = None
self.briber = None
button1 = tk.Button(self, text="Exit", command=lambda: self.master.show_frame("WizardFrame"))
button1.pack()
button2 = tk.Button(self, text="Show Influential Nodes", command=self.show_influential)
button2.pack()
button3 = tk.Button(self, text="Bribe", command=self.next_bribe)
button3.pack()
button4 = tk.Button(self, text="Results", command=self.to_results)
button4.pack()
self.txt = tk.StringVar()
lbl = tk.Label(self, textvariable=self.txt)
lbl.pack()
self.txt.set("Average P-Rating: -- \nLast Briber: --")
def set_graph(self, graph, briber):
self.graph = graph
self.pos = spring_layout(nk2nx(self.graph.get_graph()))
self.briber = briber
self.results.append(self.graph.eval_graph())
self.display_graph()
def to_results(self):
self.master.plot_results(self.results)
self.results = []
self.master.show_frame("ResultsFrame")
def display_graph(self, last=None):
cmap = plt.get_cmap("Purples")
colors = []
for c in self.graph.get_customers():
if np.isnan(self.graph.get_vote(c)):
colors.append("gray")
else:
colors.append(rgb2hex(cmap(self.graph.get_vote(c)[0])[:3]))
# labels = {c: round(self.graph.p_rating(c), 2) for c in self.graph.get_customers()}
self.ax.clear()
drawGraph(self.graph.get_graph(), node_size=400, node_color=colors, ax=self.ax, pos=self.pos)
for c in self.graph.get_customers():
if np.isnan(self.graph.get_vote(c)):
rating = "None"
else:
rating = round(self.graph.get_vote(c)[0], 2)
self.ax.annotate(
str(c) + ":\n" +
"Rating: " + str(rating) + "\n" +
"PRating: " + str(round(self.graph.get_rating(c), 2)),
xy=(self.pos[c][0], self.pos[c][1]),
bbox=dict(boxstyle="round", fc="w", ec="0.5", alpha=0.9)
)
if last is not None:
self.ax.add_artist(plt.Circle(
(self.pos[last][0], self.pos[last][1]), 0.1,
color="r",
fill=False,
linewidth=3.0
))
self.canvas.draw()
avp = str(round(self.graph.eval_graph(), 2))
if last is not None:
self.txt.set("Average P-Rating: " + avp + " \nLast Bribed: --")
else:
self.txt.set("Average P-Rating: " + avp + " \nLast Bribed: " + str(last))
def next_bribe(self):
c = self.briber.next_bribe()
self.display_graph(last=c)
avp = self.graph.eval_graph()
self.results.append(avp)
self.canvas.draw()
def show_influential(self):
cmap = plt.get_cmap("Purples")
colors = []
for c in self.graph.get_customers():
if self.graph.is_influential(c, charge_briber=False):
colors.append("yellow")
elif np.isnan(self.graph.get_vote(c)):
colors.append("gray")
else:
colors.append(rgb2hex(cmap(self.graph.get_vote(c)[0])[:3]))
self.ax.clear()
for c in self.graph.get_customers():
if np.isnan(self.graph.get_vote(c)):
rating = "None"
else:
rating = round(self.graph.get_vote(c)[0], 2)
self.ax.annotate(
str(c) + ":\n" +
"Rating: " + str(rating) + "\n" +
"PRating: " + str(round(self.graph.get_rating(c), 2)),
xy=(self.pos[c][0], self.pos[c][1]),
bbox=dict(boxstyle="round", fc="w", ec="0.5", alpha=0.9)
)
drawGraph(self.graph.get_graph(), node_size=500, node_color=colors, ax=self.ax, pos=self.pos)
self.canvas.draw()
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,373
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/wizard/rating_methods/o_rating.py
|
from BribeNet.graph.ratingMethod import RatingMethod
from BribeNet.gui.apps.temporal.wizard.rating_methods.rating_method_frame import RatingMethodFrame
class ORating(RatingMethodFrame):
enum_value = RatingMethod.O_RATING
name = 'o_rating'
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,374
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/wizard/wizard.py
|
import tkinter as tk
import numpy as np
from BribeNet.graph.ratingMethod import RatingMethod
from BribeNet.gui.apps.temporal.wizard.bribers import TemporalBribers
from BribeNet.gui.apps.temporal.wizard.generation import TemporalGeneration
from BribeNet.gui.apps.temporal.wizard.rating_method import TemporalRatingMethod
from BribeNet.gui.apps.temporal.wizard.settings import TemporalSettings
from BribeNet.helpers.bribeNetException import BribeNetException
SUBFRAME_CLASSES = (TemporalSettings, TemporalBribers, TemporalGeneration, TemporalRatingMethod)
SUBFRAME_DICT = {i: c.__class__.__name__ for (i, c) in enumerate(SUBFRAME_CLASSES)}
class WizardFrame(tk.Frame):
"""
Frame for the wizard to construct a temporal model run
"""
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.parent = parent
self.controller = controller
self.subframes = {}
for c in SUBFRAME_CLASSES:
page_name = c.__name__
frame = c(self)
self.subframes[page_name] = frame
self.subframes[TemporalSettings.__name__].grid(row=0, column=0, padx=10, pady=10, sticky="nsew")
self.subframes[TemporalBribers.__name__].grid(row=0, column=1, rowspan=2, padx=10, pady=10, sticky="nsew")
self.subframes[TemporalGeneration.__name__].grid(row=1, column=0, rowspan=2, padx=10, pady=10, sticky="nsew")
self.subframes[TemporalRatingMethod.__name__].grid(row=1, column=1, padx=10, pady=10, sticky="nsew")
run_button = tk.Button(self, text="Run", command=self.on_button)
run_button.grid(row=2, column=1, pady=20, sticky='nesw')
def add_briber(self, b_type, u0):
self.controller.add_briber(b_type, u0)
def on_button(self):
graph_type = self.subframes[TemporalGeneration.__name__].get_graph_type()
graph_args = self.subframes[TemporalGeneration.__name__].get_args()
bribers = self.subframes[TemporalBribers.__name__].get_all_bribers()
rating_method = self.subframes[TemporalRatingMethod.__name__].get_rating_method()
rating_method_args = self.subframes[TemporalRatingMethod.__name__].get_args()
if not bribers:
# noinspection PyUnresolvedReferences
tk.messagebox.showerror(message="Graph needs one or more bribers")
return
try:
for briber in bribers:
strat_type = briber[0]
briber_args = briber[1:]
self.controller.add_briber(strat_type, *(briber_args[:-2]))
true_averages = np.asarray([args[-2] for args in bribers])
true_std_devs = np.asarray([args[-1] for args in bribers])
params = self.subframes[TemporalSettings.__name__].get_args() + (true_averages, true_std_devs)
self.controller.add_graph(graph_type, graph_args, params)
self.controller.g.set_rating_method(rating_method)
if rating_method == RatingMethod.P_GAMMA_RATING:
self.controller.g.set_gamma(rating_method_args[0])
self.controller.update_results()
except Exception as e:
if issubclass(e.__class__, BribeNetException):
# noinspection PyUnresolvedReferences
tk.messagebox.showerror(message=f"{e.__class__.__name__}: {str(e)}")
self.controller.clear_graph()
return
self.controller.clear_graph()
raise e
self.controller.show_frame("GraphFrame")
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,375
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/wizard/rating_methods/weighted_median_p_rating.py
|
from BribeNet.graph.ratingMethod import RatingMethod
from BribeNet.gui.apps.temporal.wizard.rating_methods.rating_method_frame import RatingMethodFrame
class WeightedMedianPRating(RatingMethodFrame):
enum_value = RatingMethod.WEIGHTED_MEDIAN_P_RATING
name = 'weighted_median_p_rating'
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,376
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/graph/static/test_ratingGraphBuilder.py
|
from unittest import TestCase
from BribeNet.bribery.static.influentialNodeBriber import InfluentialNodeBriber
from BribeNet.bribery.static.mostInfluentialNodeBriber import MostInfluentialNodeBriber
from BribeNet.bribery.static.nonBriber import NonBriber
from BribeNet.bribery.static.oneMoveInfluentialNodeBriber import OneMoveInfluentialNodeBriber
from BribeNet.bribery.static.oneMoveRandomBriber import OneMoveRandomBriber
from BribeNet.bribery.static.randomBriber import RandomBriber
from BribeNet.graph.static.ratingGraphBuilder import RatingGraphBuilder, BriberType
class TestRatingGraphBuilder(TestCase):
def setUp(self) -> None:
self.builder = RatingGraphBuilder()
def tearDown(self) -> None:
del self.builder
def test_add_briber(self):
classes = zip(BriberType._member_names_, [NonBriber, RandomBriber, OneMoveRandomBriber, InfluentialNodeBriber,
MostInfluentialNodeBriber, OneMoveInfluentialNodeBriber])
for b, c in classes:
self.builder.add_briber(getattr(BriberType, b), u0=10)
self.assertIsInstance(self.builder.bribers[-1], c)
def test_build_no_bribers(self):
rg = self.builder.build()
self.assertIsInstance(rg.get_bribers()[0], NonBriber)
def test_build_one_briber(self):
self.builder.add_briber(BriberType.Random)
rg = self.builder.build()
self.assertIsInstance(rg.get_bribers()[0], RandomBriber)
def test_build_multiple_bribers(self):
self.builder.add_briber(BriberType.Random).add_briber(BriberType.InfluentialNode)
rg = self.builder.build()
bribers = rg.get_bribers()
self.assertEqual(len(bribers), 2)
self.assertIsInstance(bribers[0], RandomBriber)
self.assertIsInstance(bribers[1], InfluentialNodeBriber)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,377
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/docker_main.py
|
from sys import exit
from BribeNet.gui.main import GUI
"""
Due to a bug where app.mainloop() will not exit on closing of the root Tk instance if a Toplevel was at any stage
instantiated, we use sys.exit(0) to 'hard exit' such that the Docker container does not hang after closing.
"""
def hard_exit(tk_app):
tk_app.destroy()
exit(0)
if __name__ == "__main__":
app = GUI()
app.protocol("WM_DELETE_WINDOW", lambda: hard_exit(app))
app.mainloop()
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,378
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/graph/temporal/action/actionType.py
|
import enum
@enum.unique
class ActionType(enum.Enum):
NONE = 0
BRIBED = 1
SELECT = 2
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,379
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/graph/temporal/weighting/communityWeighting.py
|
import random
# noinspection PyUnresolvedReferences
from networkit import Graph
# noinspection PyUnresolvedReferences
from networkit.community import PLM
def get_communities(graph: Graph) -> [[int]]:
"""
Gets the underlying communities of the graph, as sets of nodes.
"""
communities = PLM(graph, refine=False).run().getPartition()
return [communities.getMembers(i) for i in communities.getSubsetIds()]
def gauss_constrained(mean: float, std: float) -> float:
return max(0, min(1, random.gauss(mean, std)))
def get_std_dev(total_size: int, comm_size: int) -> float:
"""
In community generation, larger communities should have a smaller standard
deviation (representing tighter-knit communities). This generates a std dev
based on the ratio of the number of nodes in this community to the number
of nodes in the total graph.
Since we want a larger standard deviation for a smaller ratio, we take
1/ratio, which goes from total_size (for comm_size=1) to 1 (for ratio = 1).
We divide this by total_size to get a normalised value, and then by 3 so
that we can easily go three standard deviations without leaving the range.
"""
ratio = comm_size / total_size # range 0 to 1.
return (1 / ratio) / (total_size * 3)
def assign_community_weights(graph: Graph, mean: float, std_dev: float = 0.05) -> [float]:
"""
For each community, assign it a mean and then give values within it a
normally distributed random value with that mean and standard deviation
proportional to community size.
"""
weights = [0 for _ in graph.iterNodes()]
communities = get_communities(graph)
print(communities)
total_size = len(weights)
for community in communities:
comm_size = len(community)
comm_mean = gauss_constrained(mean, std_dev)
if comm_size == 1:
# noinspection PyTypeChecker
# manually verified to be correct typing (rob)
weights[community[0]] = comm_mean
else:
for node in community:
# noinspection PyTypeChecker
# manually verified to be correct typing (rob)
weights[node] = gauss_constrained(comm_mean, get_std_dev(total_size, comm_size))
return weights
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,380
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/graph/temporal/weighting/traverseWeighting.py
|
from random import gauss
# noinspection PyUnresolvedReferences
from networkit import Graph
from numpy import mean as average
def assign_traverse_averaged(graph: Graph, mean: float, std_dev: float = 0.2) -> [float]:
"""
Assign node 0 with the mean. Then assign all of its neighbours with a value
close to that mean (weight + N(0, std_dev)), then their neighbours and so on.
By properties of normals, every node has weight ~ N(mean, x * (std_dev**2))
where x is the shortest distance from node 0, but nodes that are linked
share very similar weights. Locally similar, globally variable.
This version allows nodes with already assigned weights to be affected, by
tracking each weight as a set and using its average.
"""
weight_sets = [[] for _ in graph.iterNodes()]
weight_sets[0] = [mean]
nodeset = [0]
while len(nodeset) > 0:
node = nodeset[0]
nodeset = nodeset[1:]
for neighbour in graph.neighbors(node):
if len(weight_sets[neighbour]) == 0:
nodeset.append(neighbour)
weight_sets[neighbour].append(average(weight_sets[node]) + gauss(0, std_dev))
weights = [average(weight_sets[i]) for i in range(len(weight_sets))]
avg_weight = average(weights)
return [min(1, max(0, weights[i] * mean / avg_weight)) for i in range(len(weights))]
def assign_traverse_weights(graph: Graph, mean: float, std_dev: float = 0.05) -> [float]:
"""
Assign node 0 with the mean. Then assign all of its neighbours with a value
close to that mean (weight + N(0, std_dev)), then their neighbours and so on.
By properties of normals, every node has weight ~ N(mean, x * (std_dev**2))
where x is the shortest distance from node 0, but nodes that are linked
share very similar weights. Locally similar, globally variable.
"""
weights = [-1 for _ in graph.iterNodes()]
# noinspection PyTypeChecker
weights[0] = mean
nodeset = [0]
while len(nodeset) > 0:
node = nodeset[0]
nodeset = nodeset[1:]
for neighbour in graph.neighbors(node):
if weights[neighbour] == -1:
weights[neighbour] = weights[node] + gauss(0, std_dev)
nodeset.append(neighbour)
avg_weight = average(weights)
return [min(1, max(0, weights[i] * mean / avg_weight)) for i in range(len(weights))]
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,381
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/classes/tooltip.py
|
import tkinter as tk
# noinspection PyUnusedLocal
class ToolTip(object):
"""
Show a tooltip
from https://stackoverflow.com/a/56749167/5539184
"""
def __init__(self, widget, text):
self.widget = widget
self.tip_window = None
self.id = None
self.x = self.y = 0
self.text = text
def show_tip(self, *args):
if self.tip_window is not None or not self.text:
return
x, y, cx, cy = self.widget.bbox("insert")
x = x + self.widget.winfo_rootx() + 57
y = y + cy + self.widget.winfo_rooty() + 27
self.tip_window = tw = tk.Toplevel(self.widget)
tw.wm_overrideredirect(1)
tw.wm_geometry("+%d+%d" % (x, y))
label = tk.Label(tw, text=self.text, wraplength=400, justify=tk.LEFT,
background="#ffffe0", relief=tk.SOLID, borderwidth=1,
font=("tahoma", "10", "normal"))
label.pack(ipadx=1)
def hide_tip(self, *args):
if self.tip_window is not None:
self.tip_window.destroy()
self.tip_window = None
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,382
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/graph/static/test_multiBriberRatingGraph.py
|
from copy import deepcopy
from unittest import TestCase
from BribeNet.bribery.static.nonBriber import NonBriber
from BribeNet.bribery.static.randomBriber import RandomBriber
from BribeNet.graph.static.ratingGraph import StaticRatingGraph
class TestMultiBriberRatingGraph(TestCase):
def setUp(self) -> None:
# noinspection PyTypeChecker
self.rg = StaticRatingGraph((RandomBriber(10), NonBriber(10)))
def tearDown(self) -> None:
del self.rg
def test_neighbours(self):
for i in range(len(self.rg.get_bribers())):
for node in self.rg.get_customers():
self.assertIsInstance(self.rg._neighbours(node, i), list)
def test_p_rating(self):
for b in range(len(self.rg.get_bribers())):
for i in self.rg.get_customers():
self.assertTrue(self.rg._p_rating(i, b) >= 0)
def test_median_p_rating(self):
for b in range(len(self.rg.get_bribers())):
for i in self.rg.get_customers():
self.assertTrue(self.rg._median_p_rating(i, b) >= 0)
def test_sample_p_rating(self):
for b in range(len(self.rg.get_bribers())):
for i in self.rg.get_customers():
self.assertTrue(self.rg._sample_p_rating(i, b) >= 0)
def test_p_gamma_rating(self):
for b in range(len(self.rg.get_bribers())):
for i in self.rg.get_customers():
self.assertTrue(self.rg._p_gamma_rating(i) >= 0)
self.assertAlmostEqual(self.rg._p_gamma_rating(i, gamma=0), self.rg._p_rating(i))
def test_weighted_p_rating(self):
for b in range(len(self.rg.get_bribers())):
for i in self.rg.get_customers():
self.assertTrue(self.rg._p_gamma_rating(i) >= 0)
def test_weighted_median_p_rating(self):
for b in range(len(self.rg.get_bribers())):
for i in self.rg.get_customers():
self.assertTrue(self.rg._p_gamma_rating(i) >= 0)
def test_o_rating(self):
for b in range(len(self.rg.get_bribers())):
rating = self.rg._o_rating(b)
self.assertTrue(rating >= 0)
def test_is_influential(self):
for b in range(len(self.rg.get_bribers())):
for i in self.rg.get_customers():
self.assertGreaterEqual(self.rg.is_influential(i, 0.2, b, charge_briber=False), 0)
def test_bribe(self):
for i in range(len(self.rg.get_bribers())):
initial_value = self.rg.eval_graph(i)
for j in self.rg.get_customers():
g_copy = deepcopy(self.rg)
g_copy.bribe(j, 0.1, i)
bribed_value = g_copy.eval_graph(i)
self.assertTrue(initial_value != bribed_value)
def test_eval_graph(self):
for b in range(len(self.rg.get_bribers())):
self.assertGreaterEqual(self.rg.eval_graph(b), 0)
def test_trust(self):
for u in self.rg.get_customers():
for v in self.rg.get_customers():
trust1 = self.rg.trust(u, v)
trust2 = self.rg.trust(v, u)
self.assertEqual(trust1, trust2)
self.assertGreaterEqual(trust1, 0)
self.assertLessEqual(trust1, 1)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,383
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/main.py
|
import tkinter as tk
import os
from networkit.nxadapter import nk2nx
from networkx import spring_layout
from BribeNet.bribery.temporal.budgetNodeBriber import BudgetNodeBriber
from BribeNet.bribery.temporal.influentialNodeBriber import InfluentialNodeBriber
from BribeNet.bribery.temporal.mostInfluentialNodeBriber import MostInfluentialNodeBriber
from BribeNet.bribery.temporal.nonBriber import NonBriber
from BribeNet.bribery.temporal.oneMoveEvenBriber import OneMoveEvenBriber
from BribeNet.bribery.temporal.oneMoveRandomBriber import OneMoveRandomBriber
from BribeNet.bribery.temporal.pGreedyBriber import PGreedyBriber
from BribeNet.graph.generation import GraphGeneratorAlgo
from BribeNet.graph.generation.flatWeightGenerator import FlatWeightedGraphGenerator
from BribeNet.graph.temporal.action.actionType import ActionType
from BribeNet.graph.temporal.thresholdGraph import ThresholdGraph
from BribeNet.gui.apps.static.wizard.algos.barabasi_albert import BarabasiAlbert
from BribeNet.gui.apps.static.wizard.algos.composite import Composite
from BribeNet.gui.apps.temporal.briber_wizard.strategies.budget import BudgetFrame
from BribeNet.gui.apps.temporal.briber_wizard.strategies.even import EvenFrame
from BribeNet.gui.apps.temporal.briber_wizard.strategies.influential import InfluentialFrame
from BribeNet.gui.apps.temporal.briber_wizard.strategies.most_influential import MostInfluentialFrame
from BribeNet.gui.apps.temporal.briber_wizard.strategies.non import NonFrame
from BribeNet.gui.apps.temporal.briber_wizard.strategies.p_greedy import PGreedyFrame
from BribeNet.gui.apps.temporal.briber_wizard.strategies.random import RandomFrame
from BribeNet.gui.apps.temporal.graph import GraphFrame
from BribeNet.gui.apps.temporal.result import ResultsFrame
from BribeNet.gui.apps.temporal.results_wizard.results import ResultsStore
from BribeNet.gui.apps.temporal.wizard.wizard import WizardFrame
from BribeNet.helpers.override import override
FRAMES_CLASSES = (WizardFrame, GraphFrame, ResultsFrame)
FRAMES_DICT = {i: c.__class__.__name__ for (i, c) in enumerate(FRAMES_CLASSES)}
X_AXIS_OPTIONS = ("Time", "Utility Spent")
Y_AXIS_OPTIONS = ("Average Rating", "Total Utility", "Average Trust")
def switch_briber(strategy_type, *args):
switcher = {
RandomFrame.name: OneMoveRandomBriber,
InfluentialFrame.name: InfluentialNodeBriber,
MostInfluentialFrame.name: MostInfluentialNodeBriber,
NonFrame.name: NonBriber,
EvenFrame.name: OneMoveEvenBriber,
BudgetFrame.name: BudgetNodeBriber,
PGreedyFrame.name: PGreedyBriber
}
return switcher.get(strategy_type)(*args)
class TemporalGUI(tk.Toplevel):
"""
Window for the temporal wizard and running environment
"""
def __init__(self, controller, *args, **kwargs):
super().__init__(controller, *args, **kwargs)
self.title("Temporal Model")
self.controller = controller
# application window
container = tk.Frame(self)
container.grid(row=0, column=0, sticky='nsew')
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
# frame for each displayed page
self.frames = {}
for F in FRAMES_CLASSES:
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(WizardFrame.__name__)
self.bribers = []
self.bribers_spent = []
self.results = ResultsStore(X_AXIS_OPTIONS, Y_AXIS_OPTIONS)
self.briber_names = []
self.g = None
def clear_graph(self):
self.bribers = []
self.bribers_spent = []
self.results = ResultsStore(X_AXIS_OPTIONS, Y_AXIS_OPTIONS)
self.briber_names = []
self.g = None
def show_frame(self, page):
self.frames[page].tkraise()
def add_briber(self, b, *args):
self.bribers.append(switch_briber(b, *args))
self.bribers_spent.append(0)
self.briber_names.append(f"Briber{len(self.bribers)}: {b}: u0={args[0]}")
def add_graph(self, gtype, args, params):
if not self.bribers:
raise RuntimeError("No Bribers added to graph")
if gtype == BarabasiAlbert.name:
gen = FlatWeightedGraphGenerator(GraphGeneratorAlgo.BARABASI_ALBERT, *args)
elif gtype == Composite.name:
gen = FlatWeightedGraphGenerator(GraphGeneratorAlgo.COMPOSITE, *args)
else:
gen = FlatWeightedGraphGenerator(GraphGeneratorAlgo.WATTS_STROGATZ, *args)
self.g = ThresholdGraph(
tuple(self.bribers),
generator=gen,
non_voter_proportion=params[0],
threshold=params[1],
d=params[2],
q=params[3],
pay=params[4],
apathy=params[5],
learning_rate=params[6],
true_averages=params[7],
true_std_devs=params[8]
)
self.frames[GraphFrame.__name__].set_pos(spring_layout(nk2nx(self.g.get_graph())))
self.frames[GraphFrame.__name__].add_briber_dropdown()
self.frames[GraphFrame.__name__].draw_basic_graph(self.g)
def update_results(self):
self.results.add("Average Rating", [self.g.average_rating(briber_id=b) for b in range(0, len(self.bribers))])
self.results.add("Total Utility", [b.get_resources() for b in self.bribers])
self.results.add("Average Trust", self.g.average_trust())
self.results.add("Utility Spent", [self.bribers_spent[b] for b in range(0, len(self.bribers))])
self.results.add("Time", self.g.get_time_step())
def plot_results(self, x_label, y_label):
self.frames[ResultsFrame.__name__].plot_results(self.results, x_label, y_label)
self.show_frame(ResultsFrame.__name__)
def next_step(self):
last_round_was_bribery = self.g.is_bribery_round()
self.g.step()
if last_round_was_bribery:
for bribers, bribe in self.g.get_last_bribery_actions()[-1].get_bribes().items():
self.bribers_spent[bribers] += sum(bribe.values())
self.update_results()
if last_round_was_bribery:
info = "BRIBES\n"
for bribers, bribe in self.g.get_last_bribery_actions()[-1].get_bribes().items():
for c, n in bribe.items():
info += f"Briber {bribers + 1}: {c} --> {n}\n"
else:
info = "CUSTOMERS\n"
for c, a in self.g.get_last_customer_action().actions.items():
if a[0] == ActionType.NONE:
info += f"Customer {c}: No Action\n"
elif a[0] == ActionType.BRIBED:
info += f"Customer {c}: Bribed to {a[1]}\n"
elif a[0] == ActionType.SELECT:
info += f"Customer {c}: Going to {a[1]}\n"
self.frames[GraphFrame.__name__].draw_basic_graph(self.g)
self.frames[GraphFrame.__name__].set_info(info)
@override
def destroy(self):
if self.controller is not None:
self.controller.show_main()
super().destroy()
if __name__ == '__main__':
app = TemporalGUI(None)
app.mainloop()
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,384
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/graph/temporal/action/test_customerAction.py
|
from unittest import TestCase
from BribeNet.bribery.temporal.action.singleBriberyAction import SingleBriberyAction
from BribeNet.graph.temporal.action.customerAction import CustomerAction, CustomerActionExecutedMultipleTimesException,\
CustomerActionTimeNotCorrectException
from BribeNet.bribery.temporal.nonBriber import NonBriber
from BribeNet.graph.temporal.noCustomerActionGraph import NoCustomerActionGraph
from BribeNet.graph.temporal.action.actionType import ActionType
from random import sample, randint, shuffle
from unittest.mock import MagicMock
class TestCustomerAction(TestCase):
def setUp(self) -> None:
self.briber = NonBriber(0)
self.rg = NoCustomerActionGraph(self.briber)
def test_set_bribed_from_bribery_action(self):
nodes = self.rg.get_customers()
for _ in range(10):
customer_action = CustomerAction(self.rg)
bribery_action = SingleBriberyAction(self.briber)
bribed_nodes = sample(nodes, randint(1, len(nodes)))
for bribed_node in bribed_nodes:
bribery_action.add_bribe(bribed_node, 1.0)
customer_action.set_bribed_from_bribery_action(bribery_action)
bribed_in_customer_action = [c[0] for c in customer_action.actions.items() if c[1][0] == ActionType.BRIBED]
self.assertEqual(set(bribed_in_customer_action), set(bribed_nodes))
not_bribed_in_customer_action = [c[0] for c in customer_action.actions.items()
if c[1][0] != ActionType.BRIBED]
self.assertEqual(set(not_bribed_in_customer_action) & set(bribed_nodes), set())
@staticmethod
def __partition(list_in, n):
shuffle(list_in)
return [list_in[i::n] for i in range(n)]
def test_perform_action_runs_normally(self):
nodes = self.rg.get_customers()
for _ in range(10):
customer_action = CustomerAction(self.rg)
partition = TestCustomerAction.__partition(nodes, 3)
for n in partition[0]:
customer_action.set_bribed(n, [0])
for n in partition[1]:
customer_action.set_select(n, 0)
customer_action.perform_action(0)
self.assertTrue(customer_action.get_performed())
def test_perform_action_fails_when_time_incorrect(self):
customer_action = CustomerAction(self.rg)
self.rg.get_time_step = MagicMock(return_value=self.rg.get_time_step()+1)
self.assertRaises(CustomerActionTimeNotCorrectException, customer_action.perform_action, 0)
def test_perform_action_fails_when_executed_twice(self):
customer_action = CustomerAction(self.rg)
customer_action.perform_action(0)
self.assertRaises(CustomerActionExecutedMultipleTimesException, customer_action.perform_action, 0)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,385
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/bribery/temporal/randomBriber.py
|
import random
from BribeNet.bribery.temporal.action.singleBriberyAction import SingleBriberyAction
from BribeNet.bribery.temporal.briber import TemporalBriber
DELTA = 0.001 # ensures total bribes do not exceed budget
class RandomBriber(TemporalBriber):
def _next_action(self) -> SingleBriberyAction:
customers = self.get_graph().get_customers()
# array of random bribes
bribes = [random.uniform(0.0, 1.0) for _ in customers]
bribes = [b * (max(0.0, self.get_resources() - DELTA)) / sum(bribes) for b in bribes]
bribery_dict = {i: bribes[i] for i in customers}
return SingleBriberyAction(self, bribes=bribery_dict)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,386
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/graph/test_ratingGraph.py
|
from unittest import TestCase
class TestRatingGraph(TestCase):
"""
See test/graph/static/test_singleBriberRatingGraph and test/graph/static/test_multiBriberRatingGraph
"""
pass
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,387
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/graph/generation/__init__.py
|
import enum
from networkit.generators import WattsStrogatzGenerator, BarabasiAlbertGenerator
from BribeNet.graph.generation.algo.compositeGenerator import CompositeGenerator
from BribeNet.helpers.bribeNetException import BribeNetException
class GraphGenerationAlgoNotDefinedException(BribeNetException):
pass
@enum.unique
class GraphGeneratorAlgo(enum.Enum):
"""
Enum of usable NetworKit graph generation algorithms
"""
WATTS_STROGATZ = 0
BARABASI_ALBERT = 1
COMPOSITE = 2
def algo_to_constructor(g: GraphGeneratorAlgo):
"""
Conversion method from an instance of the GraphGeneratorAlgo enum to a instantiable NetworKit generator class
:param g: the algorithm
:return: the relevant NetworKit generator class
:raises GraphGenerationAlgoNotDefinedException: if g is not a member of the GraphGeneratorAlgo enum
"""
if g == GraphGeneratorAlgo.WATTS_STROGATZ:
return WattsStrogatzGenerator
if g == GraphGeneratorAlgo.BARABASI_ALBERT:
return BarabasiAlbertGenerator
if g == GraphGeneratorAlgo.COMPOSITE:
return CompositeGenerator
# Add more algorithms here if needed
raise GraphGenerationAlgoNotDefinedException(f"{g} is not a member of the GraphGeneratorAlgo enum")
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,388
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/graph/generation/generator.py
|
import abc
# noinspection PyUnresolvedReferences
from networkit import Graph
from BribeNet.graph.generation import GraphGeneratorAlgo, algo_to_constructor
class GraphGenerator(abc.ABC):
def __init__(self, a: GraphGeneratorAlgo, *args, **kwargs):
"""
Thin wrapper class for NetworKit graph generation algorithms
:param a: the GraphGenerationAlgo to use
:param args: any arguments to this generator
:param kwargs: any keyword arguments to this generator
"""
self._algo = a
self._args = args
self._kwargs = kwargs
self._generator = algo_to_constructor(self._algo)(*args, **kwargs)
@abc.abstractmethod
def generate(self) -> Graph:
"""
Call generate on the generator defined by this class and perform any additional actions
:return: a NetworKit Graph
"""
raise NotImplementedError
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,389
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/graph/generation/algo/compositeGenerator.py
|
from math import floor, log, ceil
from random import gauss, sample, random
import networkit as nk
# noinspection PyUnresolvedReferences
from networkit import Graph
from networkit.generators import BarabasiAlbertGenerator, WattsStrogatzGenerator
def _make_complete(n: int):
g_ = Graph(n)
for i in g_.iterNodes():
for j in g_.iterNodes():
if i < j:
g_.addEdge(i, j)
return g_
class CompositeGenerator(object):
"""
Pretend to extend inaccessible networkit._NetworKit.StaticGraphGenerator
"""
def __init__(self, n: int, community_count: int, small_world_neighbours: int, rewiring: float,
scale_free_k: int, probability_reduce: float = 0.05):
self._n = n
self._community_count = community_count
self._small_world_neighbours = small_world_neighbours
self._rewiring = rewiring
self._scale_free_k = scale_free_k
self._probability_reduce = probability_reduce
def generate(self):
# First, generate a scale free network, which acts as our community network.
communities = BarabasiAlbertGenerator(self._scale_free_k, self._community_count, 4, True).generate()
small_world_graphs = {}
node_count = communities.numberOfNodes()
community_size = self._n / self._community_count
# Then generate a small world graph for each node with size decided
# by a Gaussian distribution around the average node size.
i = node_count - 1
for node in communities.iterNodes():
local_size = gauss(community_size, community_size / 3)
# Choose local_n such that all communities have size at least two.
local_n = max(min(round(local_size), self._n - (2 * i)), 2)
# If it's the last iteration, we much "use up" the rest of the nodes.
if i == 0:
local_n = self._n
# For a random graph to be connected, we require that 2k >> ln(n).
# (2k because of how NetworKit defines k.)
# => k < (n-1)/2
connectivity = max(self._small_world_neighbours, floor(log(local_n)))
# However, we also require that 2k < n-1, since otherwise you end
# up with double links.
connectivity = max(0, min(ceil((local_n - 1) / 2) - 1, connectivity))
if local_n > 3:
# Sometimes WattsStrogatzGenerators return unconnected graphs.
# This is due to the fact that 2k >> ln(n) is vague, and also
# bounded above by 2k < n-1.
# Therefore, we repeat the process until a connected graph is
# created. This shouldn't loop too many times.
is_connected = False
while not is_connected:
small_world_graphs[node] = WattsStrogatzGenerator(local_n, connectivity, self._rewiring).generate()
# noinspection PyUnresolvedReferences
connected_components = nk.components.ConnectedComponents(small_world_graphs[node]).run()
is_connected = connected_components.numberOfComponents() == 1
else:
small_world_graphs[node] = _make_complete(local_n)
self._n -= local_n
i -= 1
# Build a merged graph.
big_graph = Graph(0, False, False)
ranges = [0]
partition = []
neighbours = [list(communities.neighbors(node)) for node in communities.iterNodes()]
# To avoid neighbour sets having edges going both ways, delete references to nodes larger than themselves.
for n in range(len(neighbours)):
neighbours[n] = list(filter(lambda x: x < n, neighbours[n]))
for graph in small_world_graphs.values():
# noinspection PyUnresolvedReferences
nk.graphtools.append(big_graph, graph)
ranges.append(big_graph.numberOfNodes())
partition.append(list(range(ranges[-2], ranges[-1])))
# Finally, connect these small world graphs where their parent nodes are connected.
for i in range(len(neighbours)):
for j in neighbours[i]:
# Connect partitions i and j
n1 = partition[i]
n2 = partition[j]
p = 1.0
for nc1 in sample(n1, len(n1)):
for nc2 in sample(n2, len(n2)):
# Connect with probability p
if random() <= p:
big_graph.addEdge(nc1, nc2)
p = p * self._probability_reduce
return big_graph
if __name__ == '__main__':
import matplotlib.pyplot as plt
from networkit.viztasks import drawGraph
g = CompositeGenerator(4000, 15, 50, 0.1, 2).generate()
drawGraph(g)
plt.show()
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,390
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/static/briber_wizard/frame.py
|
import tkinter as tk
class StaticBriberWizardFrame(tk.Frame):
"""
Frame for pop-up wizard for adding a static briber
"""
pass
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,391
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/bribery/static/briber.py
|
from abc import ABC, abstractmethod
from BribeNet.bribery.briber import Briber, BriberyGraphNotSetException
from BribeNet.helpers.bribeNetException import BribeNetException
class GraphNotSubclassOfStaticRatingGraphException(BribeNetException):
pass
class StaticBriber(Briber, ABC):
"""
Static bribers perform static bribery actions instantaneously on StaticRatingGraphs
The abstract method next_bribe must be implemented to define the bribery action of the briber
"""
def __init__(self, u0: float):
super().__init__(u0=u0)
def _set_graph(self, g):
from BribeNet.graph.static.ratingGraph import StaticRatingGraph
if not issubclass(g.__class__, StaticRatingGraph):
raise GraphNotSubclassOfStaticRatingGraphException(f"{g.__class__.__name__} is not a subclass of "
"StaticRatingGraph")
super()._set_graph(g)
@abstractmethod
def _next_bribe(self):
"""
Statically perform some bribery action on the graph
"""
raise NotImplementedError
def next_bribe(self):
if self.get_graph() is None:
raise BriberyGraphNotSetException()
self._next_bribe()
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,392
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/classes/param_list_frame.py
|
import abc
import os
import tkinter as tk
from PIL import ImageTk, Image
from BribeNet.gui.classes.tooltip import ToolTip
class ParamListFrame(tk.Frame, abc.ABC):
name = "ABC"
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
self.params = {}
self.descriptions = {}
img_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'info.png')
self.info_img = ImageTk.PhotoImage(Image.open(img_path))
self.tooltips = []
self.images = []
def get_args(self):
return tuple(p.get() for p in self.params.values())
def get_name(self):
return self.name
def grid_params(self, show_name=True):
offset = 0
if show_name:
name_label = tk.Label(self, text=self.name)
name_label.grid(row=0, column=0, columnspan=3, pady=10)
offset = 1
for i, (name, var) in enumerate(self.params.items()):
label = tk.Label(self, text=name)
label.grid(row=i + offset, column=0)
canvas_frame = tk.Frame(self)
canvas = tk.Canvas(master=canvas_frame, width=16, height=16)
self.tooltips.append(ToolTip(canvas_frame, self.descriptions[name]))
canvas_frame.bind('<Enter>', self.tooltips[i].show_tip)
canvas_frame.bind('<Leave>', self.tooltips[i].hide_tip)
self.images.append(canvas.create_image(0, 0, anchor=tk.NW, image=self.info_img))
entry = tk.Entry(self, textvariable=var)
canvas.pack()
canvas_frame.grid(row=i + offset, column=1, padx=30)
entry.grid(row=i + offset, column=2)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,393
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/graph/temporal/test_multiBriberRatingGraph.py
|
from copy import deepcopy
from unittest import TestCase
from BribeNet.bribery.temporal.nonBriber import NonBriber
from BribeNet.bribery.temporal.randomBriber import RandomBriber
from BribeNet.graph.temporal.noCustomerActionGraph import NoCustomerActionGraph
class TestMultiBriberRatingGraph(TestCase):
def setUp(self) -> None:
self.rg = NoCustomerActionGraph((RandomBriber(10), NonBriber(10)))
def tearDown(self) -> None:
del self.rg
def test_neighbours(self):
for i in range(len(self.rg.get_bribers())):
for node in self.rg.get_customers():
self.assertIsInstance(self.rg._neighbours(node, i), list)
def test_p_rating(self):
for b in range(len(self.rg.get_bribers())):
for i in self.rg.get_customers():
self.assertTrue(self.rg._p_rating(i, b) >= 0)
def test_median_p_rating(self):
for b in range(len(self.rg.get_bribers())):
for i in self.rg.get_customers():
self.assertTrue(self.rg._median_p_rating(i, b) >= 0)
def test_sample_p_rating(self):
for b in range(len(self.rg.get_bribers())):
for i in self.rg.get_customers():
self.assertTrue(self.rg._sample_p_rating(i, b) >= 0)
def test_o_rating(self):
for b in range(len(self.rg.get_bribers())):
self.assertTrue(self.rg._o_rating(b) >= 0)
def test_p_gamma_rating(self):
for b in range(len(self.rg.get_bribers())):
for i in self.rg.get_customers():
self.assertTrue(self.rg._p_gamma_rating(i) >= 0)
self.assertAlmostEqual(self.rg._p_gamma_rating(i, gamma=0), self.rg._p_rating(i))
def test_weighted_p_rating(self):
for b in range(len(self.rg.get_bribers())):
for i in self.rg.get_customers():
self.assertTrue(self.rg._p_gamma_rating(i) >= 0)
def test_weighted_median_p_rating(self):
for b in range(len(self.rg.get_bribers())):
for i in self.rg.get_customers():
self.assertTrue(self.rg._p_gamma_rating(i) >= 0)
def test_is_influential(self):
for b in range(len(self.rg.get_bribers())):
for i in self.rg.get_customers():
self.assertGreaterEqual(self.rg.is_influential(i, 0.2, b, charge_briber=False), 0)
def test_bribe(self):
for i in range(len(self.rg.get_bribers())):
initial_value = self.rg.eval_graph(i)
for j in self.rg.get_customers():
g_copy = deepcopy(self.rg)
g_copy.bribe(j, 0.1, i)
bribed_value = g_copy.eval_graph(i)
self.assertTrue(initial_value != bribed_value)
def test_eval_graph(self):
for b in range(len(self.rg.get_bribers())):
self.assertGreaterEqual(self.rg.eval_graph(b), 0)
def test_trust_update(self):
# Set all votes to 0.
g_copy = deepcopy(self.rg)
for u in g_copy.get_customers():
g_copy._votes[u][0] = 0
for c in g_copy.get_customers():
g_copy_2 = deepcopy(g_copy)
# Then bribe one individual.
g_copy_2.bribe(0, 1, 0)
# Update the trust.
g_copy_2._update_trust()
# Make sure that the trust goes down for each connected node.
for n in g_copy.get_customers():
if self.rg._g.hasEdge(c, n):
initial_trust = g_copy.get_weight(c, n)
updated_trust = g_copy_2.get_weight(c, n)
self.assertGreaterEqual(initial_trust, updated_trust)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,394
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/bribery/static/test_randomBriber.py
|
from BribeNet.bribery.static.randomBriber import RandomBriber
from BribeNet.graph.static.ratingGraph import StaticRatingGraph
from test.BribeNet.bribery.static.briberTestCase import BriberTestCase
class TestRandomBriber(BriberTestCase):
def setUp(self) -> None:
self.briber = RandomBriber(10)
self.rg = StaticRatingGraph(self.briber)
def test_next_bribe_does_not_exceed_budget(self):
self.briber.next_bribe()
self.assertTrue(self.briber.get_resources() >= 0)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,395
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/bribery/static/oneMoveRandomBriber.py
|
import random
import numpy as np
from BribeNet.bribery.static.briber import StaticBriber
class OneMoveRandomBriber(StaticBriber):
def _next_bribe(self):
customers = self.get_graph().get_customers()
# pick random customer from list
c = random.choice(customers)
max_rating = self.get_graph().get_max_rating()
vote = self.get_graph().get_vote(c)[self.get_briber_id()]
if np.isnan(vote):
self.bribe(c, max_rating)
else:
self.bribe(c, max_rating - vote)
return c
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,396
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/wizard/rating_methods/weighted_p_rating.py
|
from BribeNet.graph.ratingMethod import RatingMethod
from BribeNet.gui.apps.temporal.wizard.rating_methods.rating_method_frame import RatingMethodFrame
class WeightedPRating(RatingMethodFrame):
enum_value = RatingMethod.WEIGHTED_P_RATING
name = 'weighted_p_rating'
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,397
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/bribery/static/oneMoveInfluentialNodeBriber.py
|
from BribeNet.bribery.briber import BriberyGraphNotSetException
from BribeNet.bribery.static.briber import StaticBriber
from BribeNet.helpers.override import override
class OneMoveInfluentialNodeBriber(StaticBriber):
def __init__(self, u0, k=0.1):
super().__init__(u0)
self.influencers = []
self._k = k # will be reassigned when graph set
@override
def _set_graph(self, g):
super()._set_graph(g)
# Make sure that k is set such that there are enough resources left to actually bribe people.
self._k = min(self._k, 0.5 * (self.get_resources() / self.get_graph().customer_count()))
# sets influencers to ordered list of most influential nodes
def _get_influencers(self):
if self.get_graph() is None:
raise BriberyGraphNotSetException()
self.influencers = []
for c in self.get_graph().get_customers():
reward = self.get_graph().is_influential(c, k=self._k, briber_id=self.get_briber_id())
if reward > 0:
self.influencers.append((reward, c))
# Sort based on highest reward
self.influencers = sorted(self.influencers, reverse=True)
# returns node bribed number
def _next_bribe(self):
if self.get_graph() is None:
raise BriberyGraphNotSetException()
self.influencers = self._get_influencers()
if self.influencers:
(r, c) = self.influencers[0]
self.bribe(c, self.get_graph().get_max_rating() - self.get_graph().get_vote(c))
return c
else:
return 0
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,398
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/results_wizard/results.py
|
class ResultsStore:
"""
Class for storing results during runs, identified by keys, seperated to xs and ys
"""
def __init__(self, xs, ys):
self.xs = xs
self.ys = ys
self.data = {k: [] for k in (xs + ys)}
def add(self, k, v):
self.data[k].append(v)
def get(self, k):
return self.data[k]
def get_x_options(self):
return self.xs
def get_y_options(self):
return self.ys
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,399
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/bribery/temporal/test_budgetBriber.py
|
from BribeNet.bribery.temporal.budgetNodeBriber import BudgetNodeBriber
from BribeNet.graph.temporal.noCustomerActionGraph import NoCustomerActionGraph
from test.BribeNet.bribery.temporal.briberTestCase import BriberTestCase
from unittest.mock import MagicMock
class TestBudgetBriber(BriberTestCase):
def setUp(self) -> None:
self.briber = BudgetNodeBriber(10, b=0.5)
self.rg = NoCustomerActionGraph(self.briber)
def test_next_action_increases_p_rating(self):
graph = self.briber._g
action = self.briber.next_action()
briber_id = self.briber.get_briber_id()
prev_eval = graph.eval_graph(briber_id=briber_id)
action.perform_action()
self.assertGreaterEqual(graph.eval_graph(briber_id=briber_id), prev_eval)
def test_next_action_bribes_if_suitable(self):
graph = self.briber._g
self.briber._previous_rating = 0
graph.eval_graph = MagicMock(return_value=1)
graph.get_vote = MagicMock(return_value=[0.5])
self.briber._next_node = 0
action = self.briber.next_action()
self.assertDictEqual(action._bribes, {0: 0.5})
def test_next_action_moves_on_if_not_influential(self):
graph = self.briber._g
self.briber._previous_rating = 1
graph.eval_graph = MagicMock(return_value=1) # will never be influential
graph.get_vote = MagicMock(return_value=[1.0]) # will always be affordable
prev_nodes = []
for i in range(graph.customer_count()):
action = self.briber.next_action()
for prev_node in prev_nodes:
self.assertNotIn(prev_node, action._bribes)
prev_nodes.append(self.briber._next_node)
def test_next_action_moves_on_if_not_in_budget(self):
graph = self.briber._g
graph.eval_graph = MagicMock(return_value=1)
graph.get_vote = MagicMock(return_value=[0.0]) # will always be not in budget
prev_nodes = []
for i in range(graph.customer_count()):
self.briber._previous_rating = 0 # will always be influential
action = self.briber.next_action()
for prev_node in prev_nodes:
self.assertNotIn(prev_node, action._bribes)
prev_nodes.append(self.briber._next_node)
def test_next_action_does_not_fail_if_no_nodes_influential(self):
graph = self.briber._g
self.briber._previous_rating = 1
graph.eval_graph = MagicMock(return_value=1) # will never be influential
graph.get_vote = MagicMock(return_value=[1.0]) # will always be affordable
prev_nodes = []
for i in range(graph.customer_count() + 1):
action = self.briber.next_action()
for prev_node in prev_nodes:
self.assertNotIn(prev_node, action._bribes)
prev_nodes.append(self.briber._next_node)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,400
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/wizard/generation.py
|
from BribeNet.gui.apps.static.wizard.generation import StaticGeneration
class TemporalGeneration(StaticGeneration):
pass
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,401
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/bribery/temporal/oneMoveEvenBriber.py
|
import random
import numpy as np
from BribeNet.bribery.temporal.action.singleBriberyAction import SingleBriberyAction
from BribeNet.bribery.temporal.briber import TemporalBriber
class OneMoveEvenBriber(TemporalBriber):
def _next_action(self) -> SingleBriberyAction:
customers = self.get_graph().get_customers()
# pick random customer from list
c = random.choice(list(filter(lambda x: x % 2 == 0, customers)))
max_rating = self.get_graph().get_max_rating()
vote = self.get_graph().get_vote(c)[self.get_briber_id()]
resources = self.get_resources()
if np.isnan(vote):
bribery_dict = {c: min(resources, max_rating)}
else:
bribery_dict = {c: min(resources, max_rating - vote)}
return SingleBriberyAction(self, bribes=bribery_dict)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,402
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/wizard/rating_methods/rating_method_frame.py
|
import abc
from typing import Optional
from BribeNet.graph.ratingMethod import RatingMethod
from BribeNet.gui.classes.param_list_frame import ParamListFrame
class RatingMethodFrame(ParamListFrame, abc.ABC):
enum_value: Optional[RatingMethod] = None
def __init__(self, parent):
super().__init__(parent)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,403
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/bribery/temporal/action/singleBriberyAction.py
|
import sys
from typing import Dict, Optional
from BribeNet.bribery.temporal.action import BribeMustBeGreaterThanZeroException, NodeDoesNotExistException, \
BriberyActionExceedsAvailableUtilityException
from BribeNet.bribery.temporal.action.briberyAction import BriberyAction
class SingleBriberyAction(BriberyAction):
def __init__(self, briber, bribes: Optional[Dict[int, float]] = None):
from BribeNet.bribery.temporal.briber import TemporalBriber
from BribeNet.graph.temporal.ratingGraph import BriberNotSubclassOfTemporalBriberException
if not issubclass(briber.__class__, TemporalBriber):
raise BriberNotSubclassOfTemporalBriberException(f"{briber.__class__.__name__} is not a subclass of "
"TemporalBriber")
super().__init__(graph=briber.get_graph())
if bribes is not None:
for _, bribe in bribes.items():
if bribe < 0:
raise BribeMustBeGreaterThanZeroException()
self.briber = briber
self._bribes: Dict[int, float] = bribes or {}
self.__time = self.briber.get_graph().get_time_step()
@classmethod
def empty_action(cls, briber):
return cls(briber, None)
def add_bribe(self, node_id: int, bribe: float):
if bribe < 0:
raise BribeMustBeGreaterThanZeroException()
if node_id not in self.briber.get_graph().get_customers():
raise NodeDoesNotExistException()
if node_id in self._bribes:
print(f"WARNING: node {node_id} bribed twice in single time step, combining...", file=sys.stderr)
self._bribes[node_id] += bribe
else:
self._bribes[node_id] = bribe
def _perform_action(self):
if sum(self._bribes.values()) > self.briber.get_resources():
raise BriberyActionExceedsAvailableUtilityException()
for customer, bribe in self._bribes.items():
self.briber.bribe(node_id=customer, amount=bribe)
def is_bribed(self, node_id):
if node_id in self._bribes:
return True, [self.briber.get_briber_id()]
return False, []
def get_bribes(self):
return self._bribes
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,404
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/graph/ratingMethod.py
|
import enum
@enum.unique
class RatingMethod(enum.Enum):
O_RATING = 0
P_RATING = 1
MEDIAN_P_RATING = 2
SAMPLE_P_RATING = 3
P_GAMMA_RATING = 4
WEIGHTED_P_RATING = 5
WEIGHTED_MEDIAN_P_RATING = 6
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,405
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/main.py
|
import tkinter as tk
class Main(tk.Frame):
"""
Frame for the main menu of the GUI
"""
def __init__(self, master, *args, **kwargs):
tk.Frame.__init__(self, master=master, *args, **kwargs)
title_text = tk.Label(self, text="Bribery Networks", font=("Calibri", 16, "bold"), pady=20)
title_text.pack()
static_button = tk.Button(self, text="Static Model", command=self.master.show_static_gui, pady=10)
static_button.pack(pady=10)
temporal_button = tk.Button(self, text="Temporal Model", command=self.master.show_temporal_gui, pady=10)
temporal_button.pack()
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,406
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/graph/temporal/ratingGraph.py
|
import abc
import random
from sys import maxsize
from typing import Tuple, Union, Any, Optional, List
import numpy as np
from BribeNet.bribery.temporal.action.briberyAction import BriberyAction
from BribeNet.bribery.temporal.action.multiBriberyAction import MultiBriberyAction
from BribeNet.graph.ratingGraph import DEFAULT_GEN, RatingGraph, BribersAreNotTupleException, NoBriberGivenException
from BribeNet.graph.static.ratingGraph import DEFAULT_NON_VOTER_PROPORTION # (0.2)
from BribeNet.graph.temporal.action.customerAction import CustomerAction
from BribeNet.graph.temporal.weighting.traverseWeighting import assign_traverse_averaged
from BribeNet.helpers.bribeNetException import BribeNetException
from BribeNet.helpers.override import override
DEFAULT_REMOVE_NO_VOTE = False
DEFAULT_Q = 0.5
DEFAULT_PAY = 1.0
DEFAULT_APATHY = 0.0
DEFAULT_D = 2 # number of rounds in a cycle (D-1 bribes and then one customer round)
DEFAULT_TRUE_AVERAGE = 0.5
DEFAULT_TRUE_STD_DEV = 0.2
DEFAULT_LEARNING_RATE = 0.1
KWARG_NAMES = ("non_voter_proportion", "remove_no_vote", "q", "pay", "apathy", "d", "learning_rate")
KWARG_LOWER_BOUNDS = dict(zip(KWARG_NAMES, (0, False, 0, 0, 0, 2, 0)))
KWARG_UPPER_BOUNDS = dict(zip(KWARG_NAMES, (1, True, 1, float('inf'), 1, maxsize, 1)))
MIN_TRUE_AVERAGE = 0.0
MAX_TRUE_AVERAGE = 1.0
MIN_TRUE_STD_DEV = 0.0
MAX_TRUE_STD_DEV = float('inf')
class BriberNotSubclassOfTemporalBriberException(BribeNetException):
pass
class BriberKeywordArgumentOutOfBoundsException(BribeNetException):
pass
class TrueAverageIncorrectShapeException(BribeNetException):
pass
class TrueStdDevIncorrectShapeException(BribeNetException):
pass
class TemporalRatingGraph(RatingGraph, abc.ABC):
def __init__(self, bribers: Union[Tuple[Any], Any], generator=DEFAULT_GEN, **kwargs):
from BribeNet.bribery.temporal.briber import TemporalBriber
if issubclass(bribers.__class__, TemporalBriber):
bribers = tuple([bribers])
if not isinstance(bribers, tuple):
raise BribersAreNotTupleException("bribers must be a tuple of instances of subclasses of TemporalBriber")
if not bribers:
raise NoBriberGivenException("must be at least one briber")
for b in bribers:
if not issubclass(b.__class__, TemporalBriber):
raise BriberNotSubclassOfTemporalBriberException(f"{b.__class__.__name__} is not a subclass of "
"TemporalBriber")
self.__tmp_bribers = bribers
self.__tmp_kwargs = kwargs
self._time_step: int = 0
super().__init__(bribers, generator, specifics=self.__specifics, **kwargs)
# must come after super().__init__() such that bribers[0] has graph set
if len(bribers) == 1:
self._last_bribery_actions: List[BriberyAction] = []
self._last_customer_action: Optional[CustomerAction] = CustomerAction.empty_action(self)
else:
self._last_bribery_actions: List[BriberyAction] = []
self._last_customer_action: Optional[CustomerAction] = CustomerAction.empty_action(self)
@staticmethod
def kwarg_in_bounds(k, v):
return KWARG_LOWER_BOUNDS[k] <= v <= KWARG_UPPER_BOUNDS[k]
def __specifics(self):
self._votes = np.zeros((self.get_graph().numberOfNodes(), len(self._bribers)))
self._truths = np.zeros((self.get_graph().numberOfNodes(), len(self._bribers)))
for kwarg in KWARG_NAMES:
if kwarg in self.__tmp_kwargs:
if not self.kwarg_in_bounds(kwarg, self.__tmp_kwargs[kwarg]):
raise BriberKeywordArgumentOutOfBoundsException(
f"{kwarg}={self.__tmp_kwargs[kwarg]} out of bounds ({KWARG_LOWER_BOUNDS[kwarg]}, "
f"{KWARG_UPPER_BOUNDS[kwarg]})")
# Generate random ratings network
if "non_voter_proportion" in self.__tmp_kwargs:
non_voter_proportion = self.__tmp_kwargs["non_voter_proportion"]
else:
non_voter_proportion = DEFAULT_NON_VOTER_PROPORTION
if "q" in self.__tmp_kwargs:
self._q: float = self.__tmp_kwargs["q"] * self._max_rating
else:
self._q: float = DEFAULT_Q * self._max_rating
if "pay" in self.__tmp_kwargs:
self._pay: float = self.__tmp_kwargs["pay"]
else:
self._pay: float = DEFAULT_PAY
if "apathy" in self.__tmp_kwargs:
self._apathy: float = self.__tmp_kwargs["apathy"]
else:
self._apathy: float = DEFAULT_APATHY
if "d" in self.__tmp_kwargs:
self._d: int = self.__tmp_kwargs["d"]
else:
self._d: int = DEFAULT_D
if "true_averages" in self.__tmp_kwargs:
true_averages = self.__tmp_kwargs["true_averages"]
if true_averages.shape[0] != len(self._bribers):
raise TrueAverageIncorrectShapeException(f"{true_averages.shape[0]} != {len(self._bribers)}")
if not np.all(true_averages >= MIN_TRUE_AVERAGE):
raise BriberKeywordArgumentOutOfBoundsException(f"All true averages must be >= {MIN_TRUE_AVERAGE}")
if not np.all(true_averages <= MAX_TRUE_AVERAGE):
raise BriberKeywordArgumentOutOfBoundsException(f"All true averages must be <= {MAX_TRUE_AVERAGE}")
self._true_averages: np.ndarray[float] = true_averages
else:
self._true_averages: np.ndarray[float] = np.repeat(DEFAULT_TRUE_AVERAGE, len(self._bribers))
if "true_std_devs" in self.__tmp_kwargs:
true_std_devs = self.__tmp_kwargs["true_std_devs"]
if true_std_devs.shape[0] != len(self._bribers):
raise TrueStdDevIncorrectShapeException(f"{true_std_devs.shape[0]} != {len(self._bribers)}")
if not np.all(true_std_devs >= MIN_TRUE_STD_DEV):
raise BriberKeywordArgumentOutOfBoundsException(f"All true std devs must be >= {MIN_TRUE_STD_DEV}")
if not np.all(true_std_devs <= MAX_TRUE_STD_DEV):
raise BriberKeywordArgumentOutOfBoundsException(f"All true std devs must be <= {MAX_TRUE_STD_DEV}")
self._true_std_devs: np.ndarray[float] = true_std_devs
else:
self._true_std_devs: np.ndarray[float] = np.repeat(DEFAULT_TRUE_STD_DEV, len(self._bribers))
if "learning_rate" in self.__tmp_kwargs:
self._learning_rate: float = self.__tmp_kwargs["learning_rate"]
else:
self._learning_rate: float = DEFAULT_LEARNING_RATE
community_weights = {}
for b, _ in enumerate(self._bribers):
community_weights[b] = assign_traverse_averaged(self.get_graph(), self._true_averages[b],
self._true_std_devs[b])
for n in self.get_graph().iterNodes():
for b, _ in enumerate(self._bribers):
rating = community_weights[b][n]
self._truths[n][b] = rating
if random.random() > non_voter_proportion:
self._votes[n][b] = rating
else:
self._votes[n][b] = np.nan
self._time_step = 0
del self.__tmp_bribers, self.__tmp_kwargs
@override
def _finalise_init(self):
"""
Perform assertions that ensure everything is initialised
"""
from BribeNet.bribery.temporal.briber import TemporalBriber
for briber in self._bribers:
if not issubclass(briber.__class__, TemporalBriber):
raise BriberNotSubclassOfTemporalBriberException("member of graph bribers not an instance of a "
"subclass of TemporalBriber")
super()._finalise_init()
def get_time_step(self):
return self._time_step
def get_d(self):
return self._d
def get_last_bribery_actions(self):
return self._last_bribery_actions
def get_last_customer_action(self):
return self._last_customer_action
@abc.abstractmethod
def _customer_action(self) -> CustomerAction:
"""
Perform the action of each customer in the graph
"""
raise NotImplementedError
def _bribery_action(self) -> MultiBriberyAction:
actions = [b.next_action() for b in self._bribers]
return MultiBriberyAction.make_multi_action_from_single_actions(actions)
def _update_trust(self):
"""
Update the weights of the graph based on the trust between nodes.
"""
# Get the weights and calculate the new weights first.
new_weights = {}
for (u, v) in self.get_edges():
prev_weight = self.get_weight(u, v)
new_weight = prev_weight + self._learning_rate * (self.trust(u, v) - prev_weight)
new_weights[(u, v)] = new_weight
# Then set them, as some ratings systems could give different values
# if the weights are modified during the calculations.
for (u, v) in self.get_edges():
self.set_weight(u, v, new_weights[(u, v)])
def is_bribery_round(self):
return not (self._time_step % self._d == self._d - 1)
def step(self):
"""
Perform the next step, either bribery action or customer action and increment the time step
We do d-1 bribery steps (self._time_step starts at 0) and then a customer step.
"""
if self.is_bribery_round():
bribery_action = self._bribery_action()
bribery_action.perform_action()
self._last_bribery_actions.append(bribery_action)
else:
customer_action = self._customer_action()
customer_action.perform_action(pay=self._pay)
self._last_customer_action = customer_action
self._last_bribery_actions = []
self._update_trust()
self._time_step += 1
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,407
|
RobMurray98/BribeNet
|
refs/heads/master
|
/setup.py
|
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="BribeNet",
version="1.0.0",
author="Robert Murray",
author_email="R.Murray.1@warwick.ac.uk",
description="Simulation of networks of bribers and consumers",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/RobMurray98/CS407Implementation",
install_requires=[
'matplotlib==3.1.2',
'networkit==6.1.0',
'networkx==2.4',
'snap==0.5',
'cython==0.29.14',
'numpy==1.17.4',
'pandas==0.25.3',
'pytest==5.3.0',
'ipython==7.13.0',
'pillow==7.0.0',
'weightedstats==0.4.1'
],
package_data={'': ['*.png']},
include_package_data=True,
package_dir={'': 'src'},
packages=setuptools.find_packages(where='src'),
python_requires='>=3.7'
)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,408
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/wizard/bribers.py
|
import tkinter as tk
from BribeNet.gui.apps.temporal.briber_wizard.window import TemporalBriberWizardWindow
from BribeNet.helpers.override import override
class TemporalBribers(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
self.briber_wizard = None
self.bribers_list = []
bribers_title_label = tk.Label(self, text="Bribers")
bribers_title_label.grid(row=1, column=1, columnspan=2, pady=10)
self.bribers_listbox = tk.Listbox(self)
self.bribers_listbox.grid(row=2, column=1, rowspan=3)
scrollbar = tk.Scrollbar(self, orient="vertical")
scrollbar.config(command=self.bribers_listbox.yview)
scrollbar.grid(row=2, column=2, rowspan=3, sticky="ns")
self.bribers_listbox.config(yscrollcommand=scrollbar.set)
self.add_briber_button = tk.Button(self, text="Add", command=self.open_briber_wizard)
self.add_briber_button.grid(row=2, column=3, sticky='nsew')
self.duplicate_briber_button = tk.Button(self, text="Duplicate", command=self.duplicate_selected_briber)
self.duplicate_briber_button.grid(row=3, column=3, sticky='nsew')
self.delete_briber_button = tk.Button(self, text="Delete", command=self.delete_selected_briber)
self.delete_briber_button.grid(row=4, column=3, sticky='nsew')
def open_briber_wizard(self):
if self.briber_wizard is None:
self.briber_wizard = TemporalBriberWizardWindow(self)
else:
self.briber_wizard.lift()
def duplicate_selected_briber(self):
cur_sel = self.bribers_listbox.curselection()
if not cur_sel:
return
self.bribers_list.append(self.bribers_list[cur_sel[0]])
self.bribers_listbox.insert(tk.END, self.bribers_list[cur_sel[0]][0])
def delete_selected_briber(self):
cur_sel = self.bribers_listbox.curselection()
if not cur_sel:
return
self.bribers_listbox.delete(cur_sel[0])
del self.bribers_list[cur_sel[0]]
def add_briber(self, strat_type, *args):
self.bribers_list.append((strat_type, *args))
self.bribers_listbox.insert(tk.END, strat_type)
def get_all_bribers(self):
return self.bribers_list
@override
def destroy(self):
if self.briber_wizard is not None:
self.briber_wizard.destroy()
super().destroy()
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,409
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/graph/temporal/test_ratingGraphBuilder.py
|
from unittest import TestCase
class TestRatingGraphBuilder(TestCase):
pass
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,410
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/bribery/static/briberTestCase.py
|
from abc import ABC, abstractmethod
from unittest import TestCase
from BribeNet.bribery.static.nonBriber import NonBriber
from BribeNet.graph.static.ratingGraph import StaticRatingGraph
class BriberTestCase(TestCase, ABC):
@abstractmethod
def setUp(self) -> None:
self.briber = NonBriber(1)
self.rg = StaticRatingGraph(self.briber)
def tearDown(self) -> None:
del self.briber, self.rg
def _p_rating_increase(self, g1, g2):
rating2 = g2.eval_graph()
rating1 = g1.eval_graph()
self.assertGreaterEqual(rating2, rating1)
return None
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,411
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/graph/generation/test_weightedGenerator.py
|
from unittest import TestCase
from BribeNet.graph.generation.flatWeightGenerator import FlatWeightedGraphGenerator
from BribeNet.graph.generation import GraphGeneratorAlgo
class TestFlatWeightedGraphGenerator(TestCase):
def test_generate_ws(self):
graph_gen = FlatWeightedGraphGenerator(GraphGeneratorAlgo.WATTS_STROGATZ, 30, 5, 0.3)
graph = graph_gen.generate()
self.assertTrue(graph.isWeighted())
def test_generate_ba(self):
graph_gen = FlatWeightedGraphGenerator(GraphGeneratorAlgo.BARABASI_ALBERT, 5, 30, 0, True)
graph = graph_gen.generate()
self.assertTrue(graph.isWeighted())
def test_generate_composite(self):
graph_gen = FlatWeightedGraphGenerator(GraphGeneratorAlgo.COMPOSITE, 30, 15, 50, 0.1, 2)
graph = graph_gen.generate()
self.assertTrue(graph.isWeighted())
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,412
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/static/wizard/algos/watts_strogatz.py
|
import tkinter as tk
from BribeNet.gui.classes.param_list_frame import ParamListFrame
class WattsStrogatz(ParamListFrame):
name = "Watts-Strogatz"
def __init__(self, parent):
super().__init__(parent)
self.params = {
'n_nodes': tk.IntVar(self, value=30),
'n_neighbours': tk.IntVar(self, value=5),
'p': tk.DoubleVar(self, value=0.3)
}
self.descriptions = {
'n_nodes': 'number of nodes in the graph',
'n_neighbours': 'number of neighbors on each side of a node',
'p': 'the probability of rewiring a given edge'
}
self.grid_params(show_name=False)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,413
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/graph/static/test_singleBriberRatingGraph.py
|
from copy import deepcopy
from unittest import TestCase
from BribeNet.bribery.static.nonBriber import NonBriber
from BribeNet.graph.static.ratingGraph import StaticRatingGraph
class TestSingleBriberRatingGraph(TestCase):
def setUp(self) -> None:
self.rg = StaticRatingGraph(NonBriber(0))
def tearDown(self) -> None:
del self.rg
def test_neighbors(self):
for i in self.rg.get_customers():
self.assertIsInstance(self.rg._neighbours(i), list)
def test_p_rating(self):
for i in self.rg.get_customers():
self.assertTrue(self.rg._p_rating(i) >= 0)
def test_median_p_rating(self):
for i in self.rg.get_customers():
self.assertTrue(self.rg._median_p_rating(i) >= 0)
def test_sample_p_rating(self):
for i in self.rg.get_customers():
self.assertTrue(self.rg._sample_p_rating(i) >= 0)
def test_weighted_p_rating(self):
for b in range(len(self.rg.get_bribers())):
for i in self.rg.get_customers():
self.assertTrue(self.rg._p_gamma_rating(i) >= 0)
def test_weighted_median_p_rating(self):
for b in range(len(self.rg.get_bribers())):
for i in self.rg.get_customers():
self.assertTrue(self.rg._p_gamma_rating(i) >= 0)
def test_p_gamma_rating(self):
for b in range(len(self.rg.get_bribers())):
for i in self.rg.get_customers():
self.assertTrue(self.rg._p_gamma_rating(i) >= 0)
self.assertAlmostEqual(self.rg._p_gamma_rating(i, gamma=0), self.rg._p_rating(i))
def test_o_rating(self):
self.assertTrue(self.rg._o_rating() >= 0)
def test_bribe(self):
initial_value = self.rg.eval_graph()
for i in self.rg.get_customers():
g_copy = deepcopy(self.rg)
g_copy.bribe(i, 0.1)
bribed_value = g_copy.eval_graph()
self.assertTrue(initial_value != bribed_value)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,414
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/bribery/temporal/action/test_multiBriberyAction.py
|
from unittest import TestCase
from BribeNet.bribery.temporal.action.multiBriberyAction import MultiBriberyAction, \
BriberyActionsAtDifferentTimesException, BriberyActionsOnDifferentGraphsException, \
NoActionsToFormMultiActionException
from BribeNet.bribery.temporal.action import *
from BribeNet.bribery.temporal.action.singleBriberyAction import SingleBriberyAction
from BribeNet.bribery.temporal.nonBriber import NonBriber
from BribeNet.graph.temporal.noCustomerActionGraph import NoCustomerActionGraph
from unittest.mock import MagicMock
# noinspection PyBroadException
class TestMultiBriberyAction(TestCase):
def setUp(self) -> None:
self.bribers = (NonBriber(1), NonBriber(1), NonBriber(1), NonBriber(1))
self.valid_action_dict = {0: {0: 0.5}, 2: {0: 0.5}, 3: {0: 0.5}}
self.graph = NoCustomerActionGraph(self.bribers)
def tearDown(self) -> None:
del self.bribers, self.graph
def test_add_bribe_fails_if_bribe_not_greater_than_zero(self):
action = MultiBriberyAction(self.graph)
self.assertRaises(BribeMustBeGreaterThanZeroException, action.add_bribe, 0, 0, -1.0)
def test_add_bribe_fails_if_node_id_not_present(self):
action = MultiBriberyAction(self.graph)
self.assertRaises(NodeDoesNotExistException, action.add_bribe, 0, -1, 1.0)
def test_add_bribe_fails_if_briber_id_not_present_1(self):
action = MultiBriberyAction(self.graph)
self.assertRaises(BriberDoesNotExistException, action.add_bribe, -1, 0, 1.0)
def test_add_bribe_fails_if_briber_id_not_present_2(self):
action = MultiBriberyAction(self.graph)
self.assertRaises(BriberDoesNotExistException, action.add_bribe, 4, 0, 1.0)
def test_add_bribe_passes_1(self):
action = MultiBriberyAction(self.graph)
action.add_bribe(0, 0, 1.0)
self.assertEqual(action._bribes[0][0], 1.0)
def test_add_bribe_passes_2(self):
action = MultiBriberyAction(self.graph, bribes={0: {0: 1.0}})
action.add_bribe(0, 0, 1.0)
self.assertEqual(action._bribes[0][0], 2.0)
def test_perform_action_fails_when_bribes_exceed_budget(self):
action = MultiBriberyAction(self.graph, bribes={0: {0: 10.0}})
self.assertRaises(BriberyActionExceedsAvailableUtilityException, action.perform_action)
def test_perform_action(self):
action = MultiBriberyAction(self.graph, bribes=self.valid_action_dict)
action.perform_action()
self.assertTrue(action.get_performed())
def test_make_multi_action_from_single_actions_fails_if_on_different_graphs(self):
other_briber = NonBriber(1)
# noinspection PyUnusedLocal
other_graph = NoCustomerActionGraph(other_briber)
action0 = SingleBriberyAction(other_briber)
action1 = SingleBriberyAction(self.bribers[0])
self.assertRaises(BriberyActionsOnDifferentGraphsException,
MultiBriberyAction.make_multi_action_from_single_actions, [action0, action1])
def test_make_multi_action_from_single_actions_fails_if_no_actions(self):
self.assertRaises(NoActionsToFormMultiActionException,
MultiBriberyAction.make_multi_action_from_single_actions, [])
def test_make_multi_action_from_single_actions_fails_if_bribe_not_greater_than_zero(self):
action = SingleBriberyAction(self.bribers[0])
action._bribes[0] = -1.0
self.assertRaises(BribeMustBeGreaterThanZeroException,
MultiBriberyAction.make_multi_action_from_single_actions, [action])
def test_make_multi_action_from_single_actions_fails_if_at_different_times(self):
action0 = SingleBriberyAction(self.bribers[0])
action1 = SingleBriberyAction(self.bribers[1])
action0.get_time_step = MagicMock(return_value=action0.get_time_step()+1)
self.assertRaises(BriberyActionsAtDifferentTimesException,
MultiBriberyAction.make_multi_action_from_single_actions, [action0, action1])
def test_make_multi_action_from_single_actions(self):
single_actions = [SingleBriberyAction(self.bribers[i], self.valid_action_dict[i])
for i in self.valid_action_dict.keys()]
multi_action = MultiBriberyAction.make_multi_action_from_single_actions(single_actions)
self.assertEqual(multi_action._bribes, self.valid_action_dict)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,415
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/graph/temporal/action/customerAction.py
|
from typing import Dict, Any, Tuple, List
import numpy as np
from BribeNet.bribery.temporal.action.briberyAction import BriberyAction
from BribeNet.bribery.temporal.briber import GraphNotSubclassOfTemporalRatingGraphException
from BribeNet.graph.temporal.action.actionType import ActionType
from BribeNet.helpers.bribeNetException import BribeNetException
class CustomerActionExecutedMultipleTimesException(BribeNetException):
pass
class CustomerActionTimeNotCorrectException(BribeNetException):
pass
class CustomerAction(object):
def __init__(self, graph):
from BribeNet.graph.temporal.ratingGraph import TemporalRatingGraph # local import to remove cyclic dependency
if not issubclass(graph.__class__, TemporalRatingGraph):
raise GraphNotSubclassOfTemporalRatingGraphException(f"{graph.__class__.__name__} is not a subclass of "
"TemporalRatingGraph")
self.graph = graph
self.actions: Dict[int, Tuple[ActionType, Any]] = {c: (ActionType.NONE, None)
for c in self.graph.get_customers()}
self.__time_step = self.graph.get_time_step()
self.__performed = False
@classmethod
def empty_action(cls, graph):
return cls(graph)
def get_time_step(self):
return self.__time_step
def get_performed(self):
return self.__performed
def get_action_type(self, node_id: int):
return self.actions[node_id][0]
def set_bribed(self, node_id: int, briber_ids: List[int]):
self.actions[node_id] = (ActionType.BRIBED, briber_ids)
def set_none(self, node_id: int):
self.actions[node_id] = (ActionType.NONE, 0)
def set_select(self, node_id: int, briber_id):
self.actions[node_id] = (ActionType.SELECT, briber_id)
def set_bribed_from_bribery_action(self, bribery_action: BriberyAction):
for c in self.actions:
bribed, bribers = bribery_action.is_bribed(c)
if bribed:
self.set_bribed(c, bribers)
# noinspection PyProtectedMember
def perform_action(self, pay: float):
"""
Perform the described action on the graph
:param pay: the amount to increase a selected briber's utility
"""
if not self.__performed:
if self.__time_step == self.graph.get_time_step():
for c in self.actions:
if self.actions[c][0] == ActionType.SELECT:
selected = self.actions[c][1]
if np.isnan(self.graph._votes[c][selected]): # no previous vote or bribe
self.graph._votes[c][selected] = self.graph._truths[c][selected]
self.graph._bribers[selected].add_resources(pay)
self.__performed = True
else:
message = f"The time step of the TemporalRatingGraph ({self.graph.get_time_step()}) is not equal to " \
f"the intended execution time ({self.__time_step})"
raise CustomerActionTimeNotCorrectException(message)
else:
raise CustomerActionExecutedMultipleTimesException()
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,416
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/wizard/rating_method.py
|
import tkinter as tk
from BribeNet.graph.ratingMethod import RatingMethod
from BribeNet.gui.apps.temporal.wizard.rating_methods.median_p_rating import MedianPRating
from BribeNet.gui.apps.temporal.wizard.rating_methods.o_rating import ORating
from BribeNet.gui.apps.temporal.wizard.rating_methods.p_gamma_rating import PGammaRating
from BribeNet.gui.apps.temporal.wizard.rating_methods.p_rating import PRating
from BribeNet.gui.apps.temporal.wizard.rating_methods.weighted_median_p_rating import WeightedMedianPRating
from BribeNet.gui.apps.temporal.wizard.rating_methods.weighted_p_rating import WeightedPRating
METHOD_SUBFRAMES = (ORating, PRating, MedianPRating, PGammaRating, WeightedPRating, WeightedMedianPRating)
METHOD_DICT = {v: k for k, v in enumerate([a.name for a in METHOD_SUBFRAMES])}
class TemporalRatingMethod(tk.Frame):
"""
Frame for pop-up wizard for adding a temporal briber
"""
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
self.method_type = tk.StringVar(self)
self.subframes = tuple(c(self) for c in METHOD_SUBFRAMES)
self.options = tuple(f.get_name() for f in self.subframes)
name_label = tk.Label(self, text="Rating Method")
name_label.grid(row=0, column=0, pady=10)
self.dropdown = tk.OptionMenu(self, self.method_type, *self.options)
self.dropdown.grid(row=1, column=0, pady=10)
self.method_type.set(self.options[0])
for f in self.subframes:
f.grid(row=2, column=0, sticky="nsew", pady=20)
self.method_type.trace('w', self.switch_frame)
self.show_subframe(1) # (p-rating)
def show_subframe(self, page_no):
frame = self.subframes[page_no]
frame.tkraise()
# noinspection PyUnusedLocal
def switch_frame(self, *args):
self.show_subframe(METHOD_DICT[self.method_type.get()])
def get_rating_method(self) -> RatingMethod:
return self.subframes[METHOD_DICT[self.method_type.get()]].enum_value
def get_args(self):
return self.subframes[METHOD_DICT[self.method_type.get()]].get_args()
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,417
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/graph.py
|
import tkinter as tk
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.colors import rgb2hex
from networkit.viztasks import drawGraph
from BribeNet.gui.apps.temporal.results_wizard.window import TemporalResultsWizardWindow
class GraphFrame(tk.Frame):
"""
Frame for showing the current state and actions that can be taken for the temporal model being run
"""
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.parent = parent
self.fig = plt.figure(figsize=(8, 8))
self.ax = self.fig.add_subplot(111)
self.canvas = FigureCanvasTkAgg(self.fig, master=self)
self.grid_rowconfigure(1, weight=1)
self.canvas.get_tk_widget().grid(row=1, column=0, rowspan=10)
self.results = []
self.pos = None
self.gamma = None
self.briber_buttons = None
self.briber_name_to_index = None
self.rating_string_var = None
step_button = tk.Button(self, text="Next Step", command=self.controller.next_step)
step_button.grid(row=3, column=2, sticky='nsew')
results_button = tk.Button(self, text="Results", command=self.show_results_wizard)
results_button.grid(row=4, column=2, sticky='nsew')
exit_button = tk.Button(self, text="Exit", command=self.return_to_wizard)
exit_button.grid(row=7, column=2, sticky='nsew')
steps_slide = tk.Scale(self, from_=1, to=100, orient=tk.HORIZONTAL)
steps_slide.grid(row=6, column=2, sticky='nsew')
n_steps_button = tk.Button(self, text="Perform n steps", command=lambda: self.n_steps(steps_slide.get()))
n_steps_button.grid(row=5, column=2, sticky='nsew')
self.info = tk.StringVar(parent)
round_desc_canvas = tk.Canvas(self)
round_desc_scroll = tk.Scrollbar(self, orient='vertical', command=round_desc_canvas.yview)
round_desc_frame = tk.Frame(self)
round_desc_frame.bind(
"<Configure>",
lambda e: round_desc_canvas.configure(
scrollregion=round_desc_canvas.bbox("all")
)
)
round_desc_canvas.create_window((0, 0), window=round_desc_frame, anchor="n")
round_desc_canvas.config(yscrollcommand=round_desc_scroll.set)
round_desc_label = tk.Label(round_desc_frame, textvariable=self.info)
round_desc_label.pack(fill=tk.BOTH, expand=1)
round_desc_canvas.grid(row=1, column=1, columnspan=2, pady=10, padx=10, sticky='nsew')
round_desc_scroll.grid(row=1, column=2, pady=10, sticky='nse')
self.info.set("--")
def return_to_wizard(self):
self.results = []
self.info.set("--")
self.controller.clear_graph()
self.controller.show_frame("WizardFrame")
def set_info(self, s):
self.info.set(s)
def set_pos(self, pos):
self.pos = pos
def n_steps(self, n):
for i in range(0, n):
self.controller.next_step()
def add_briber_dropdown(self):
view_title_label = tk.Label(self, text="View rating for briber")
view_title_label.grid(row=3, column=1)
rating_choices = ['None'] + self.controller.briber_names
self.briber_name_to_index = {v: k for k, v in enumerate(self.controller.briber_names)}
self.rating_string_var = tk.StringVar(self)
self.rating_string_var.set('None')
rating_dropdown = tk.OptionMenu(self, self.rating_string_var, *rating_choices)
# noinspection PyUnusedLocal
def change_dropdown(*args):
var_val = self.rating_string_var.get()
if var_val == 'None':
self.draw_basic_graph(self.controller.g)
else:
self.draw_briber_graph(self.briber_name_to_index[var_val])
self.rating_string_var.trace('w', change_dropdown)
rating_dropdown.grid(row=4, column=1, sticky='nsew')
trust_button = tk.Button(self, text="Show Trust", command=lambda: self.show_trust(self.controller.g))
trust_button.grid(row=6, column=1, sticky='nsew')
def show_results_wizard(self):
results_wizard = TemporalResultsWizardWindow(self.controller, self.controller.results)
results_wizard.lift()
def draw_basic_graph(self, graph):
colours = ["gray" for _ in graph.get_customers()] # nodes
edge_colours = ["#000000" for _ in graph.get_edges()] # edges
self._update_graph(graph, colours, edge_colours)
self.canvas.draw()
def draw_briber_graph(self, b):
# node colours
graph = self.controller.g
colour_map = plt.get_cmap("Purples")
colours = []
for c in graph.get_customers():
if np.isnan(graph.get_vote(c)[b]):
colours.append("gray")
else:
colours.append(rgb2hex(colour_map(graph.get_vote(c)[b])[:3]))
edge_colours = ["#000000" for _ in graph.get_edges()] # edges
self._update_graph(graph, colours, edge_colours)
self._add_annotations(b)
self.canvas.draw()
def _update_graph(self, graph, colours, edge_colours):
self.ax.clear()
drawGraph(
graph.get_graph(),
node_size=400,
node_color=colours,
edge_color=edge_colours,
ax=self.ax, pos=self.pos,
with_labels=True
)
def _add_annotations(self, b):
graph = self.controller.g
for c in graph.get_customers():
if np.isnan(graph.get_vote(c)[b]):
rating = "None"
else:
rating = round(graph.get_vote(c)[b], 2)
self.ax.annotate(
str(c) + ":\n"
+ "Vote: " + str(rating) + "\n"
+ "Rating: " + str(round(graph.get_rating(c), 2)),
xy=(self.pos[c][0], self.pos[c][1]),
bbox=dict(boxstyle="round", fc="w", ec="0.5", alpha=0.9)
)
def show_trust(self, graph):
colours = ["gray" for _ in graph.get_customers()] # nodes
colour_map = plt.get_cmap("Greys")
edge_colours = []
for (u, v) in graph.get_edges():
edge_colours.append(rgb2hex(colour_map(graph.get_weight(u, v))[:3]))
self._update_graph(graph, colours, edge_colours)
self.canvas.draw()
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,418
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/bribery/briber.py
|
from abc import ABC
from typing import Optional
from BribeNet.helpers.bribeNetException import BribeNetException
class BriberyGraphNotSetException(BribeNetException):
pass
class BriberyGraphAlreadySetException(BribeNetException):
pass
class BriberNotRegisteredOnGraphException(BribeNetException):
pass
class GraphNotSubclassOfRatingGraphException(BribeNetException):
pass
class Briber(ABC):
def __init__(self, u0: float):
"""
Abstract class for bribing actors
:param u0: the initial utility available to the briber
"""
self._u = u0
from BribeNet.graph.ratingGraph import RatingGraph
self._g: Optional[RatingGraph] = None
def _set_graph(self, g):
from BribeNet.graph.ratingGraph import RatingGraph
if not issubclass(g.__class__, RatingGraph):
raise GraphNotSubclassOfRatingGraphException(f"{g.__class__.__name__} is not a subclass of RatingGraph")
if self._g is not None:
raise BriberyGraphAlreadySetException()
self._g = g
def get_graph(self):
return self._g
def get_briber_id(self):
if self._g is None:
raise BriberyGraphNotSetException()
g_bribers = self._g.get_bribers()
if issubclass(g_bribers.__class__, Briber):
return 0
for i, briber in enumerate(g_bribers):
if briber is self:
return i
raise BriberNotRegisteredOnGraphException()
def set_resources(self, u: float):
self._u = u
def add_resources(self, u: float):
self._u += u
def get_resources(self) -> float:
return self._u
def bribe(self, node_id: int, amount: float):
if self._g is None:
raise BriberyGraphNotSetException()
if amount <= self._u:
self._g.bribe(node_id, amount, self.get_briber_id())
self._u -= amount
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,419
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/static/static.py
|
import tkinter as tk
from BribeNet.bribery.static.oneMoveInfluentialNodeBriber import OneMoveInfluentialNodeBriber
from BribeNet.bribery.static.oneMoveRandomBriber import OneMoveRandomBriber
from BribeNet.graph.generation import GraphGeneratorAlgo
from BribeNet.graph.generation.flatWeightGenerator import FlatWeightedGraphGenerator
from BribeNet.graph.static.ratingGraph import StaticRatingGraph
from BribeNet.gui.apps.static.graph import GraphFrame
from BribeNet.gui.apps.static.result import ResultsFrame
from BribeNet.gui.apps.static.wizard.wizard import WizardFrame
from BribeNet.helpers.override import override
FRAMES_CLASSES = [WizardFrame,
GraphFrame,
ResultsFrame]
FRAMES_DICT = {i: c.__class__.__name__ for (i, c) in enumerate(FRAMES_CLASSES)}
def switch_briber(argument):
switcher = {
"r": lambda: OneMoveRandomBriber(10),
"i": lambda: OneMoveInfluentialNodeBriber(10)
}
return switcher.get(argument)
class StaticGUI(tk.Toplevel):
"""
Window for the static wizard and running environment
"""
def __init__(self, controller, *args, **kwargs):
super().__init__(controller, *args, **kwargs)
self.title("Static Model")
self.controller = controller
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in FRAMES_CLASSES:
page_name = F.__name__
frame = F(parent=self, controller=controller)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("WizardFrame")
def show_frame(self, page):
frame = self.frames[page]
frame.tkraise()
def generate_graph(self, gtype, btype):
briber = switch_briber(btype)()
ba_gen = FlatWeightedGraphGenerator(GraphGeneratorAlgo.BARABASI_ALBERT, 5, 30, 0, True)
comp_gen = FlatWeightedGraphGenerator(GraphGeneratorAlgo.COMPOSITE, 50, 5, 2, 0.1, 3, 0.05)
if gtype == "ba":
rg = StaticRatingGraph(briber, generator=ba_gen)
elif gtype == "cg":
rg = StaticRatingGraph(briber, generator=comp_gen)
else:
rg = StaticRatingGraph(briber)
self.frames["GraphFrame"].set_graph(rg, briber)
def plot_results(self, results):
self.frames["ResultsFrame"].plot_results(results)
@override
def destroy(self):
if self.controller is not None:
self.controller.show_main()
super().destroy()
if __name__ == '__main__':
app = StaticGUI(None)
app.mainloop()
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,420
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/bribery/static/randomBriber.py
|
import random
from BribeNet.bribery.static.briber import StaticBriber
DELTA = 0.001 # ensures total bribes do not exceed budget
class RandomBriber(StaticBriber):
def _next_bribe(self):
customers = self.get_graph().get_customers()
# array of random bribes
bribes = [random.uniform(0.0, 1.0) for _ in customers]
bribes = [b * (self.get_resources() - DELTA) / sum(bribes) for b in bribes]
# enact bribes
for i in customers:
self.bribe(i, bribes[i])
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,421
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/bribery/test_briber.py
|
import random
from test.BribeNet.bribery.static.briberTestCase import BriberTestCase
from BribeNet.bribery.briber import BriberyGraphAlreadySetException, BriberyGraphNotSetException
from BribeNet.bribery.static.nonBriber import NonBriber
class TestBriber(BriberTestCase):
def setUp(self) -> None:
super().setUp()
def test_bribe(self):
initial_u = self.briber.get_resources()
bribe = random.randrange(0, initial_u)
self.briber.bribe(0, bribe)
self.assertEqual(self.briber.get_resources(), initial_u-bribe)
def test_next_bribe_fails_if_graph_not_set(self):
briber = NonBriber(0)
self.assertRaises(BriberyGraphNotSetException, briber.next_bribe)
def test_set_graph_fails_if_graph_already_set(self):
self.assertRaises(BriberyGraphAlreadySetException, self.briber._set_graph, self.rg)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,422
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/results_wizard/window.py
|
import tkinter as tk
from BribeNet.gui.apps.temporal.results_wizard.frame import TemporalResultsWizardFrame
class TemporalResultsWizardWindow(tk.Toplevel):
"""
Window for pop-up wizard for selecting results displayed
"""
def __init__(self, controller, results):
super().__init__(controller)
self.title("Results Wizard")
self.controller = controller
self.frame = TemporalResultsWizardFrame(self, results)
self.frame.pack(pady=10, padx=10)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,423
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/static/briber_wizard/window.py
|
import tkinter as tk
class StaticBriberWizardWindow(tk.Toplevel):
"""
Window for pop-up wizard for adding a static briber
"""
pass
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,424
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/graph/generation/unweightedGenerator.py
|
from BribeNet.graph.generation import GraphGeneratorAlgo
from BribeNet.graph.generation.generator import GraphGenerator
class UnweightedGraphGenerator(GraphGenerator):
def __init__(self, a: GraphGeneratorAlgo, *args, **kwargs):
super().__init__(a, *args, **kwargs)
def generate(self):
return self._generator.generate()
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,425
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/briber_wizard/frame.py
|
import tkinter as tk
from BribeNet.gui.apps.temporal.briber_wizard.strategies.budget import BudgetFrame
from BribeNet.gui.apps.temporal.briber_wizard.strategies.even import EvenFrame
from BribeNet.gui.apps.temporal.briber_wizard.strategies.influential import InfluentialFrame
from BribeNet.gui.apps.temporal.briber_wizard.strategies.most_influential import MostInfluentialFrame
from BribeNet.gui.apps.temporal.briber_wizard.strategies.non import NonFrame
from BribeNet.gui.apps.temporal.briber_wizard.strategies.p_greedy import PGreedyFrame
from BribeNet.gui.apps.temporal.briber_wizard.strategies.random import RandomFrame
STRAT_SUBFRAMES = (NonFrame, RandomFrame, InfluentialFrame, MostInfluentialFrame, EvenFrame, BudgetFrame, PGreedyFrame)
STRAT_DICT = {v: k for k, v in enumerate([a.name for a in STRAT_SUBFRAMES])}
class TemporalBriberWizardFrame(tk.Frame):
"""
Frame for pop-up wizard for adding a temporal briber
"""
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
self.strat_type = tk.StringVar(self)
self.subframes = tuple(c(self) for c in STRAT_SUBFRAMES)
self.options = tuple(f.get_name() for f in self.subframes)
self.dropdown = tk.OptionMenu(self, self.strat_type, *self.options)
self.dropdown.grid(row=0, column=0)
self.strat_type.set(self.options[0])
for f in self.subframes:
f.grid(row=1, column=0, sticky="nsew", pady=20)
self.strat_type.trace('w', self.switch_frame)
self.show_subframe(0)
self.submit_button = tk.Button(self, text="Submit", command=self.add_briber)
self.submit_button.grid(row=2, column=0)
def show_subframe(self, page_no):
frame = self.subframes[page_no]
frame.tkraise()
# noinspection PyUnusedLocal
def switch_frame(self, *args):
self.show_subframe(STRAT_DICT[self.strat_type.get()])
def get_args(self):
return self.subframes[STRAT_DICT[self.strat_type.get()]].get_args()
def get_graph_type(self):
return self.strat_type.get()
def add_briber(self):
self.parent.controller.add_briber(self.get_graph_type(), *(self.get_args()))
self.parent.destroy()
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,426
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/graph/temporal/noCustomerActionGraph.py
|
from BribeNet.graph.ratingGraph import DEFAULT_GEN
from BribeNet.graph.temporal.action.customerAction import CustomerAction
from BribeNet.graph.temporal.ratingGraph import TemporalRatingGraph
class NoCustomerActionGraph(TemporalRatingGraph):
"""
A temporal rating graph solely for testing purposes.
"""
def __init__(self, bribers, generator=DEFAULT_GEN, **kwargs):
super().__init__(bribers, generator=generator, **kwargs)
def _customer_action(self):
return CustomerAction(self)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,427
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/results_wizard/frame.py
|
import tkinter as tk
class TemporalResultsWizardFrame(tk.Frame):
"""
Frame for pop-up wizard for selecting results displayed
"""
def __init__(self, parent, results):
super().__init__(parent)
self.parent = parent
self.x_string_var = tk.StringVar(self)
self.y_string_var = tk.StringVar(self)
self.title_text = tk.Label(self, text="Select Values", font=("Calibri", 16, "bold"), pady=20)
self.title_text.grid(row=0, column=0, columnspan=2)
self.x_text = tk.Label(self, text="X-axis", padx=20, pady=10)
self.x_text.grid(row=1, column=0)
self.y_text = tk.Label(self, text="Y-axis", padx=20, pady=10)
self.y_text.grid(row=2, column=0)
x_options = results.get_x_options()
self.x_string_var.set(x_options[0])
self.drop_xs = tk.OptionMenu(self, self.x_string_var, *x_options)
self.drop_xs.grid(row=1, column=1, sticky='ew')
y_options = results.get_y_options()
self.y_string_var.set(y_options[0])
self.drop_ys = tk.OptionMenu(self, self.y_string_var, *y_options)
self.drop_ys.grid(row=2, column=1, sticky='ew')
self.submit_button = tk.Button(self, text="Submit", command=self.submit)
self.submit_button.grid(row=3, column=0, columnspan=2, pady=20, sticky='nsew')
def submit(self):
self.parent.controller.plot_results(self.x_string_var.get(), self.y_string_var.get())
self.parent.destroy()
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,428
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/static/wizard/algos/barabasi_albert.py
|
import tkinter as tk
from BribeNet.gui.classes.param_list_frame import ParamListFrame
class BarabasiAlbert(ParamListFrame):
name = "Barabási-Albert"
def __init__(self, parent):
super().__init__(parent)
self.params = {
'k': tk.DoubleVar(self, value=5),
'n_max': tk.IntVar(self, value=30),
'n_0': tk.IntVar(self, value=0)
}
self.descriptions = {
'k': 'number of attachments per node',
'n_max': 'number of nodes in the graph',
'n_0': 'number of connected nodes to begin with'
}
self.grid_params(show_name=False)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,429
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/graph/temporal/test_thresholdGraph.py
|
from unittest import TestCase
from BribeNet.bribery.temporal.nonBriber import NonBriber
from BribeNet.graph.temporal.action.actionType import ActionType
from BribeNet.graph.temporal.thresholdGraph import ThresholdGraph
from unittest.mock import MagicMock
class TestThresholdGraph(TestCase):
def setUp(self) -> None:
self.rg = ThresholdGraph((NonBriber(10), NonBriber(10)), threshold=0.4, q=0.5)
def tearDown(self) -> None:
del self.rg
def test_customer_action_runs_successfully(self):
self.rg.step()
self.rg.step()
action = self.rg.get_last_customer_action()
self.assertIsNotNone(action)
self.assertTrue(action.get_performed())
def test_customer_action_no_votes_runs_successfully(self):
self.rg.get_rating = MagicMock(return_value=0)
self.rg.step()
self.rg.step()
action = self.rg.get_last_customer_action()
self.assertIsNotNone(action)
for k in action.actions:
self.assertNotEqual(action.actions[k], ActionType.SELECT)
self.assertTrue(action.get_performed())
def test_customer_action_disconnected_graph_runs_successfully(self):
self.rg._neighbours = MagicMock(return_value=[])
self.rg._q = 0.5
self.rg.step()
self.rg.step()
action = self.rg.get_last_customer_action()
self.assertIsNotNone(action)
for k in action.actions:
self.assertEqual(action.actions[k][0], ActionType.SELECT)
self.assertTrue(action.get_performed())
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,430
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py
|
from copy import deepcopy
from BribeNet.bribery.static.oneMoveInfluentialNodeBriber import OneMoveInfluentialNodeBriber
from BribeNet.graph.static.ratingGraph import StaticRatingGraph
from test.BribeNet.bribery.static.briberTestCase import BriberTestCase
class TestOneMoveInfluentialNodeBriber(BriberTestCase):
def setUp(self) -> None:
self.briber = OneMoveInfluentialNodeBriber(10)
self.rg = StaticRatingGraph(self.briber)
def test_next_bribe_increases_p_rating(self):
initial_g = deepcopy(self.briber._g)
self.briber.next_bribe()
self._p_rating_increase(initial_g, self.briber._g)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,431
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/bribery/static/influentialNodeBriber.py
|
from BribeNet.bribery.static.briber import StaticBriber
from BribeNet.helpers.override import override
class InfluentialNodeBriber(StaticBriber):
def __init__(self, u0, k=0.1):
super().__init__(u0)
self._k = k # will be reassigned when graph set
@override
def _set_graph(self, g):
super()._set_graph(g)
# Make sure that k is set such that there are enough resources left to actually bribe people.
self._k = min(self._k, 0.5 * (self.get_resources() / self.get_graph().customer_count()))
def _next_bribe(self):
for c in self.get_graph().get_customers():
reward = self.get_graph().is_influential(c, k=self._k, briber_id=self.get_briber_id())
if reward > 0:
# max out customers rating
self.bribe(c, self.get_graph().get_max_rating() - self.get_graph().get_vote(c))
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,432
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/bribery/temporal/pGreedyBriber.py
|
import sys
import numpy as np
from BribeNet.bribery.temporal.action.singleBriberyAction import SingleBriberyAction
from BribeNet.bribery.temporal.briber import TemporalBriber
"""
IMPORTANT!
This briber cheats and uses the direct influential node information.
This is for testing whether trust is powerful enough to beat P-greedy bribery
even when the briber has perfect information.
"""
class PGreedyBriber(TemporalBriber):
def __init__(self, u0: float):
"""
Constructor
:param u0: initial utility
"""
super().__init__(u0)
self._targets = []
self._index = 0
self._bribed = set()
def _set_graph(self, g):
super()._set_graph(g)
def _get_influential_nodes(self, g):
# noinspection PyProtectedMember
influence_weights = [(n, g._get_influence_weight(n, self.get_briber_id())) for n in self._g.get_customers()]
influence_weights = sorted(influence_weights, key=lambda x: x[1], reverse=True)
self._targets = [n for (n, w) in influence_weights if w >= 1 and not n in self._bribed]
def _next_action(self) -> SingleBriberyAction:
"""
Next action of briber, just bribe the next node as fully as you can.
:return: SingleBriberyAction for the briber to take in the next temporal time step
"""
next_act = SingleBriberyAction(self)
if self._index >= len(self._targets):
self._get_influential_nodes(self._g)
self._index = 0
if self._index < len(self._targets):
# Bribe the next target as fully as you can.
target = self._targets[self._index]
target_vote = self._g.get_vote(target)[self.get_briber_id()]
if np.isnan(target_vote): target_vote = 0
next_act.add_bribe(target, min(self.get_resources(),
self._g.get_max_rating() - target_vote))
self._index += 1
self._bribed.add(target)
else:
print(f"WARNING: {self.__class__.__name__} found no influential nodes, not acting...", file=sys.stderr)
return next_act
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,433
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/static/wizard/algos/composite.py
|
import tkinter as tk
from BribeNet.gui.classes.param_list_frame import ParamListFrame
class Composite(ParamListFrame):
name = "Composite"
def __init__(self, parent):
super().__init__(parent)
self.params = {
'n_nodes': tk.IntVar(self, value=50),
'n_communities': tk.IntVar(self, value=5),
'n_neighbours': tk.IntVar(self, value=2),
'p_rewiring': tk.DoubleVar(self, value=0.3),
'k': tk.DoubleVar(self, value=3),
'p_reduce': tk.DoubleVar(self, value=0.05)
}
self.descriptions = {
'n_nodes': 'number of nodes in the graph',
'n_communities': 'how many small world networks the composite network should consist of',
'n_neighbours': 'how many neighbours each node should have at the start of small world generation (k from '
'Watts-Strogatz)',
'p_rewiring': 'the probability of rewiring a given edge during small world network generation (p from '
'Watts-Strogatz)',
'k': 'number of attachments per community (k for Barabasi-Albert for our parent graph)',
'p_reduce': "how much the probability of joining two nodes in two different communities is reduced by - "
"once a successful connection is made, the probability of connecting two edges p' becomes p' "
"* probability_reduce "
}
self.grid_params(show_name=False)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,434
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/bribery/temporal/action/briberyAction.py
|
from abc import ABC, abstractmethod
from typing import List
from BribeNet.helpers.bribeNetException import BribeNetException
class BriberyActionExecutedMultipleTimesException(BribeNetException):
pass
class BriberyActionTimeNotCorrectException(BribeNetException):
pass
class BriberyAction(ABC):
def __init__(self, graph):
from BribeNet.graph.temporal.ratingGraph import TemporalRatingGraph # local import to remove cyclic dependency
from BribeNet.bribery.temporal.briber import GraphNotSubclassOfTemporalRatingGraphException
if not issubclass(graph.__class__, TemporalRatingGraph):
raise GraphNotSubclassOfTemporalRatingGraphException(f"{graph.__class__.__name__} is not a subclass of "
"TemporalRatingGraph")
self.graph = graph
self.__time_step = self.graph.get_time_step()
self.__performed = False
@classmethod
@abstractmethod
def empty_action(cls, graph):
raise NotImplementedError
def perform_action(self):
"""
Perform the action safely
:raises BriberyActionTimeNotCorrectException: if action not at same time step as graph
:raises BriberyActionExecutedMultipleTimesException: if action already executed
"""
if not self.__performed:
if self.__time_step == self.graph.get_time_step():
self._perform_action()
self.__performed = True
else:
message = f"The time step of the TemporalRatingGraph ({self.graph.get_time_step()}) is not equal to " \
f"the intended execution time ({self.__time_step})"
raise BriberyActionTimeNotCorrectException(message)
else:
raise BriberyActionExecutedMultipleTimesException()
def get_time_step(self):
return self.__time_step
def get_performed(self):
return self.__performed
@abstractmethod
def _perform_action(self):
"""
Perform the stored bribery actions simultaneously
"""
raise NotImplementedError
@abstractmethod
def is_bribed(self, node_id) -> (bool, List[int]):
"""
Determine if the bribery action results in a node being bribed this time step
:param node_id: the node
:return: whether the node is bribed this time step
"""
raise NotImplementedError
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,435
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/graph/generation/test_unweightedGenerator.py
|
from unittest import TestCase
from BribeNet.graph.generation.unweightedGenerator import UnweightedGraphGenerator
from BribeNet.graph.generation import GraphGeneratorAlgo
class TestUnweightedGraphGenerator(TestCase):
def test_generate_ws(self):
graph_gen = UnweightedGraphGenerator(GraphGeneratorAlgo.WATTS_STROGATZ, 30, 5, 0.3)
graph = graph_gen.generate()
self.assertFalse(graph.isWeighted())
def test_generate_ba(self):
graph_gen = UnweightedGraphGenerator(GraphGeneratorAlgo.BARABASI_ALBERT, 5, 30, 0, True)
graph = graph_gen.generate()
self.assertFalse(graph.isWeighted())
def test_generate_composite(self):
graph_gen = UnweightedGraphGenerator(GraphGeneratorAlgo.COMPOSITE, 30, 15, 50, 0.1, 2)
graph = graph_gen.generate()
self.assertFalse(graph.isWeighted())
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,436
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/graph/static/ratingGraph.py
|
import random
from typing import Tuple, Union, Any
import numpy as np
from BribeNet.graph.ratingGraph import RatingGraph, DEFAULT_GEN, BribersAreNotTupleException, NoBriberGivenException
from BribeNet.helpers.bribeNetException import BribeNetException
from BribeNet.helpers.override import override
DEFAULT_NON_VOTER_PROPORTION = 0.2
class BriberNotSubclassOfStaticBriberException(BribeNetException):
pass
class StaticRatingGraph(RatingGraph):
def __init__(self, bribers: Union[Tuple[Any], Any], generator=DEFAULT_GEN, **kwargs):
from BribeNet.bribery.static.briber import StaticBriber
if issubclass(bribers.__class__, StaticBriber):
bribers = tuple([bribers])
if not isinstance(bribers, tuple):
raise BribersAreNotTupleException()
if not bribers:
raise NoBriberGivenException()
for b in bribers:
if not issubclass(b.__class__, StaticBriber):
raise BriberNotSubclassOfStaticBriberException(f"{b.__class__.__name__} is not a subclass of "
"StaticBriber")
self.__tmp_bribers = bribers
self.__tmp_kwargs = kwargs
super().__init__(bribers, generator=generator, specifics=self.__specifics, **kwargs)
@override
def _finalise_init(self):
"""
Perform assertions that ensure everything is initialised
"""
from BribeNet.bribery.static.briber import StaticBriber
for briber in self._bribers:
if not issubclass(briber.__class__, StaticBriber):
raise BriberNotSubclassOfStaticBriberException(f"{briber.__class__.__name__} is not a subclass of "
"StaticBriber")
super()._finalise_init()
def __specifics(self):
from BribeNet.bribery.static.briber import StaticBriber
self._bribers: Tuple[StaticBriber] = self.__tmp_bribers
# noinspection PyTypeChecker
self._votes = np.zeros((self.get_graph().numberOfNodes(), len(self._bribers)))
self._truths = np.zeros((self.get_graph().numberOfNodes(), len(self._bribers)))
# Generate random ratings network
if "non_voter_proportion" in self.__tmp_kwargs:
non_voter_proportion = self.__tmp_kwargs["non_voter_proportion"]
else:
non_voter_proportion = DEFAULT_NON_VOTER_PROPORTION
for n in self.get_graph().iterNodes():
for b, _ in enumerate(self._bribers):
rating = random.uniform(0, self._max_rating)
self._truths[n][b] = rating
if random.random() > non_voter_proportion:
self._votes[n][b] = rating
else:
self._votes[n][b] = np.nan
del self.__tmp_bribers, self.__tmp_kwargs
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,437
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/briber_wizard/strategies/p_greedy.py
|
import tkinter as tk
from BribeNet.gui.classes.param_list_frame import ParamListFrame
class PGreedyFrame(ParamListFrame):
name = "P-Greedy"
def __init__(self, parent):
super().__init__(parent)
self.params = {
'u_0': tk.DoubleVar(self, value=10),
'true_average': tk.DoubleVar(self, value=0.5),
'true_std_dev': tk.DoubleVar(self, value=0.2)
}
self.descriptions = {
'u_0': 'starting budget',
'true_average': 'the average of customer ground truth for this briber',
'true_std_dev': 'the standard deviation of customer ground truth for this briber'
}
self.grid_params(show_name=False)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,438
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/graph/temporal/thresholdGraph.py
|
import random
from typing import List
import numpy as np
from BribeNet.graph.ratingGraph import DEFAULT_GEN
from BribeNet.graph.temporal.action.actionType import ActionType
from BribeNet.graph.temporal.action.customerAction import CustomerAction
from BribeNet.graph.temporal.ratingGraph import TemporalRatingGraph, BriberKeywordArgumentOutOfBoundsException
DEFAULT_THRESHOLD = 0.5
MIN_THRESHOLD = 0.0
MAX_THRESHOLD = 1.0
class ThresholdGraph(TemporalRatingGraph):
def __init__(self, bribers, generator=DEFAULT_GEN, **kwargs):
"""
Threshold model for temporal rating graph
:param bribers: the bribers active on the network
:param generator: the generator to be used to generate the customer graph
:param kwargs: additional parameters to the threshold temporal rating graph
:keyword threshold: float - threshold for being considered
:keyword remove_no_vote: bool - whether to allow non voted restaurants
:keyword q: float - percentage of max rating given to non voted restaurants
:keyword pay: float - the amount of utility gained by a restaurant when a customer visits
:keyword apathy: float - the probability a customer does not visit any restaurant
"""
super().__init__(bribers, generator=generator, **kwargs)
if "threshold" in kwargs:
threshold = kwargs["threshold"]
if not MIN_THRESHOLD <= threshold <= MAX_THRESHOLD:
raise BriberKeywordArgumentOutOfBoundsException(
f"threshold={threshold} out of bounds ({MIN_THRESHOLD}, {MAX_THRESHOLD})")
self._threshold: float = threshold
else:
self._threshold: float = DEFAULT_THRESHOLD
def _customer_action(self):
# obtain customers ratings before any actions at this step, assumes all customers act simultaneously
curr_ratings: List[List[float]] = [[self.get_rating(n, b.get_briber_id(), nan_default=0) for b in self._bribers]
for n in self.get_customers()]
voted: List[List[bool]] = [[len(self._neighbours(n, b.get_briber_id())) > 0 for b in self._bribers]
for n in self.get_customers()]
action = CustomerAction(self)
for bribery_action in self._last_bribery_actions:
action.set_bribed_from_bribery_action(bribery_action)
# for each customer
for n in self.get_graph().iterNodes():
# get weightings for restaurants
# 0 if below_threshold, q if no votes
weights = np.zeros(len(self._bribers))
for b in range(0, len(self._bribers)):
# Check for no votes
if not voted[n][b]:
weights[b] = self._q
# P-rating below threshold
elif curr_ratings[n][b] < self._threshold:
weights[b] = 0
# Else probability proportional to P-rating
else:
weights[b] = curr_ratings[n][b]
# no restaurants above threshold so no action for this customer
if np.count_nonzero(weights) == 0:
continue
# select at random
selected = random.choices(range(0, len(self._bribers)), weights=weights)[0]
if random.random() >= self._apathy: # has no effect by default (DEFAULT_APATHY = 0.0)
if action.get_action_type(n) == ActionType.NONE: # if not already selected or bribed
action.set_select(n, selected)
return action
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,439
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/bribery/temporal/action/test_singleBriberyAction.py
|
from unittest import TestCase
from BribeNet.bribery.temporal.action.singleBriberyAction import SingleBriberyAction
from BribeNet.bribery.temporal.nonBriber import NonBriber
from BribeNet.graph.temporal.noCustomerActionGraph import NoCustomerActionGraph
from BribeNet.bribery.temporal.action import *
class TestSingleBriberyAction(TestCase):
def setUp(self) -> None:
self.briber = NonBriber(1)
self.graph = NoCustomerActionGraph(self.briber)
def test_add_bribe_fails_if_bribe_not_greater_than_zero(self):
action = SingleBriberyAction(self.briber)
self.assertRaises(BribeMustBeGreaterThanZeroException, action.add_bribe, 0, -1.0)
def test_add_bribe_fails_if_node_id_not_present(self):
action = SingleBriberyAction(self.briber)
self.assertRaises(NodeDoesNotExistException, action.add_bribe, -1, 1.0)
def test_add_bribe_passes_1(self):
action = SingleBriberyAction(self.briber)
action.add_bribe(0, 1.0)
self.assertEqual(action._bribes[0], 1.0)
def test_add_bribe_passes_2(self):
action = SingleBriberyAction(self.briber, bribes={0: 1.0})
action.add_bribe(0, 1.0)
self.assertEqual(action._bribes[0], 2.0)
def test__perform_action_fails_when_bribes_exceed_budget(self):
action = SingleBriberyAction(self.briber, bribes={1: 10.0})
self.assertRaises(BriberyActionExceedsAvailableUtilityException, action._perform_action)
def test_perform_action(self):
action = SingleBriberyAction(self.briber, bribes={0: 0.5})
action.perform_action()
self.assertTrue(action.get_performed())
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,440
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/briber_wizard/window.py
|
import tkinter as tk
from BribeNet.gui.apps.temporal.briber_wizard.frame import TemporalBriberWizardFrame
from BribeNet.helpers.override import override
class TemporalBriberWizardWindow(tk.Toplevel):
"""
Window for pop-up wizard for adding a temporal briber
"""
def __init__(self, controller):
super().__init__(controller)
self.title("Briber Wizard")
self.controller = controller
self.frame = TemporalBriberWizardFrame(self)
self.frame.pack(pady=10, padx=10)
@override
def destroy(self):
self.controller.briber_wizard = None
super().destroy()
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,441
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/static/wizard/wizard.py
|
import tkinter as tk
class WizardFrame(tk.Frame):
"""
Frame for the wizard to construct a static model run
"""
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
gtype = tk.StringVar(parent)
gtype.set("L")
btype = tk.StringVar(parent)
btype.set("L")
rb1 = tk.Radiobutton(self, variable=gtype, value="ws", text="Watts-Strogatz")
rb2 = tk.Radiobutton(self, variable=gtype, value="ba", text="Barabási–Albert")
rb3 = tk.Radiobutton(self, variable=gtype, value="cg", text="Composite Generator")
rb1.grid(row=0, column=0)
rb2.grid(row=1, column=0)
rb3.grid(row=2, column=0)
rba = tk.Radiobutton(self, variable=btype, value="r", text="Random")
rbb = tk.Radiobutton(self, variable=btype, value="i", text="Influential")
rba.grid(row=0, column=1)
rbb.grid(row=1, column=1)
b = tk.Button(self, text="Graph + Test", command=lambda: self.on_button(gtype.get(), btype.get()))
b.grid(row=1, column=2)
def on_button(self, gtype, btype):
self.master.generate_graph(gtype, btype)
self.master.show_frame("GraphFrame")
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,442
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/helpers/bribeNetException.py
|
class BribeNetException(Exception):
pass
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,443
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/wizard/settings.py
|
import tkinter as tk
from BribeNet.gui.classes.param_list_frame import ParamListFrame
class TemporalSettings(ParamListFrame):
name = 'Model Parameters'
def __init__(self, parent):
super().__init__(parent)
self.descriptions = {
'non_voter_proportion': 'the proportion of customers which start with no vote',
'threshold': 'the minimum rating for a customer to consider visiting a bribing actor',
'd': 'the period of non-bribery rounds (minimum 2)',
'q': 'the vote value to use in place of non-votes in rating calculations',
'pay': 'the amount of utility given to a bribing actor each time a customer chooses them',
'apathy': 'the probability that a customer performs no action',
'learning_rate': 'how quickly the edge weights are updated by trust'
}
self.params = {
'non_voter_proportion': tk.DoubleVar(self, value=0.2),
'threshold': tk.DoubleVar(self, value=0.5),
'd': tk.IntVar(self, value=2),
'q': tk.DoubleVar(self, value=0.5),
'pay': tk.DoubleVar(self, value=1.0),
'apathy': tk.DoubleVar(self, value=0.0),
'learning_rate': tk.DoubleVar(self, value=0.1),
}
self.grid_params()
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,444
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py
|
from BribeNet.bribery.temporal.mostInfluentialNodeBriber import MostInfluentialNodeBriber
from BribeNet.graph.temporal.noCustomerActionGraph import NoCustomerActionGraph
from test.BribeNet.bribery.temporal.briberTestCase import BriberTestCase
from unittest.mock import MagicMock
TEST_I = 7
class TestMostInfluentialBriber(BriberTestCase):
def setUp(self) -> None:
self.briber = MostInfluentialNodeBriber(10, i=TEST_I)
self.rg = NoCustomerActionGraph(self.briber)
def test_next_action_increases_p_rating(self):
graph = self.briber._g
action = self.briber.next_action()
briber_id = self.briber.get_briber_id()
prev_eval = graph.eval_graph(briber_id=briber_id)
action.perform_action()
self.assertGreaterEqual(graph.eval_graph(briber_id=briber_id), prev_eval)
def test_next_action_gains_information_for_suitable_time(self):
prev_nodes = []
for i in range(TEST_I - 1):
action = self.briber.next_action()
self.assertEqual(len(action._bribes), 1)
for prev_node in prev_nodes:
self.assertNotIn(prev_node, action._bribes)
prev_nodes.append(self.briber._next_node)
def test_next_action_performs_bribe_on_best_node(self):
self.briber._c = self.briber._i
self.briber._best_node = 1
graph = self.briber._g
graph.eval_graph = MagicMock(return_value=0)
action = self.briber.next_action()
self.assertIn(1, action._bribes)
self.assertEqual(self.briber._c, 0)
self.assertEqual(self.briber._max_rating_increase, 0)
def test_next_action_finds_best_node(self):
graph = self.briber._g
graph.eval_graph = MagicMock(return_value=10)
graph.get_random_customer = MagicMock(return_value=3)
self.briber._previous_rating = 1
self.briber._max_rating_increase = 0
action = self.briber.next_action()
self.assertIn(3, action._bribes)
self.assertEqual(self.briber._max_rating_increase, 9)
def test_next_action_does_not_fail_if_no_nodes_influential_within_i_step(self):
graph = self.briber._g
self.briber._previous_rating = 1
graph.eval_graph = MagicMock(return_value=1) # will never be influential
prev_nodes = []
for i in range(TEST_I + 1):
action = self.briber.next_action()
for prev_node in prev_nodes:
self.assertNotIn(prev_node, action._bribes)
prev_nodes.append(self.briber._next_node)
def test_next_action_does_not_fail_if_no_nodes_influential_at_all(self):
graph = self.briber._g
self.briber._previous_rating = 1
graph.eval_graph = MagicMock(return_value=1) # will never be influential
prev_nodes = []
for i in range(graph.customer_count() + 1):
action = self.briber.next_action()
for prev_node in prev_nodes:
self.assertNotIn(prev_node, action._bribes)
prev_nodes.append(self.briber._next_node)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,445
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/prediction/parameterPrediction.py
|
# noinspection PyUnresolvedReferences
from networkit.centrality import LocalClusteringCoefficient
# noinspection PyUnresolvedReferences
from networkit.distance import APSP
from networkit.generators import WattsStrogatzGenerator
from numpy import logspace
from numpy import sum as np_sum
TRIALS = 5
INFINITY = float("inf")
'''
Finds the clustering coefficient of a given graph.
'''
class ParameterPrediction(object):
def __init__(self, graph):
self.__g = graph
def average_clustering(self, turbo=True):
# If graphs get too large, turn off Turbo mode (which requires more memory)
lcc = LocalClusteringCoefficient(self.__g, turbo)
lcc.run()
scores = lcc.scores()
return sum(scores) / len(scores)
'''
Finds the average shortest path length of a given graph.
'''
def average_shortest_path_length(self):
apsp = APSP(self.__g)
apsp.run()
n = self.__g.numberOfNodes()
# npsum needed as we are summing values in a matrix
# Note! The matrix returned by getDistances is n*n, but we divide by n*n-1
# since the central diagonal represents distances from a node to itself.
distances = apsp.getDistances()
return np_sum(distances) / (n * (n - 1))
'''
Given an existing graph (from networkx), predict the parameters that should be used given.
Returns (n,k,p), where:
n: the number of nodes
k: the degree of nodes of the starting regular graph (that we rewire)
p: the probability of rewiring
'''
def predict_small_world(self):
n = self.__g.numberOfNodes()
k = sum([len(self.__g.neighbors(i)) for i in self.__g.iterNodes()]) // (2 * n)
probs = logspace(-5, 0, 64, False, 10)
(lvs, cvs, l0, c0) = self.generate_example_graphs(n, k, probs)
lp = self.average_shortest_path_length()
l_ratio = lp / l0
cp = self.average_clustering()
c_ratio = cp / c0
# Find the p according to l and c ratios
index_l = self.closest_index(lvs, l_ratio)
index_c = self.closest_index(cvs, c_ratio)
prob_l = probs[index_l]
prob_c = probs[index_c]
p = (prob_l + prob_c) / 2
return n, k, p
@staticmethod
def closest_index(values, target):
min_diff = INFINITY
best = 0
for i in range(len(values)):
lv = values[i]
diff = abs(lv - target)
if diff < min_diff:
best = i
min_diff = diff
return best
'''
For a set of p-values, generate existing WS graphs and get the values of L(p)/L(0) and C(p)/C(0).
Returns (l_values, c_values, l0, c0)
'''
@staticmethod
def generate_example_graphs(n, k, ps):
generator0 = WattsStrogatzGenerator(n, k, 0)
graph0 = generator0.generate()
pred0 = ParameterPrediction(graph0)
l0 = pred0.average_shortest_path_length()
c0 = pred0.average_clustering()
result = ([], [], l0, c0)
for p in ps:
l_tot = 0
c_tot = 0
generator = WattsStrogatzGenerator(n, k, p)
for i in range(TRIALS):
graph = generator.generate()
pred_i = ParameterPrediction(graph)
l_tot += pred_i.average_shortest_path_length()
c_tot += pred_i.average_clustering()
lp = l_tot / TRIALS
cp = c_tot / TRIALS
result[0].append(lp / l0)
result[1].append(cp / c0)
return result
def test_parameter_prediction():
print("Testing small world prediction with obviously Watts-Strogatz Graph (50,6,0.1)")
generator = WattsStrogatzGenerator(50, 6, 0.1)
pred = ParameterPrediction(generator.generate())
print(pred.predict_small_world())
if __name__ == '__main__':
test_parameter_prediction()
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,446
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/bribery/temporal/briber.py
|
from abc import ABC, abstractmethod
from BribeNet.bribery.briber import Briber, BriberyGraphNotSetException
from BribeNet.bribery.temporal.action.singleBriberyAction import SingleBriberyAction
from BribeNet.helpers.bribeNetException import BribeNetException
class GraphNotSubclassOfTemporalRatingGraphException(BribeNetException):
pass
class TemporalBriber(Briber, ABC):
def __init__(self, u0: float):
super().__init__(u0=u0)
def _set_graph(self, g):
from BribeNet.graph.temporal.ratingGraph import TemporalRatingGraph
if not issubclass(g.__class__, TemporalRatingGraph):
raise GraphNotSubclassOfTemporalRatingGraphException(f"{g.__class__.__name__} is not a subclass of "
"TemporalRatingGraph")
super()._set_graph(g)
def next_action(self) -> SingleBriberyAction:
if self.get_graph() is None:
raise BriberyGraphNotSetException()
return self._next_action()
@abstractmethod
def _next_action(self) -> SingleBriberyAction:
"""
Defines the temporal model behaviour
"""
raise NotImplementedError
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,447
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/prediction/test_parameterPrediction.py
|
from unittest import TestCase
from networkit.generators import WattsStrogatzGenerator
from numpy import logspace
from BribeNet.prediction.parameterPrediction import ParameterPrediction
class TestParameterPrediction(TestCase):
def setUp(self) -> None:
self.generator = WattsStrogatzGenerator(50, 6, 0.1)
self.pred = ParameterPrediction(self.generator.generate())
def tearDown(self) -> None:
del self.pred, self.generator
def test_average_clustering(self):
self.assertTrue(self.pred.average_clustering() > 0)
def test_average_shortest_path_length(self):
self.assertTrue(self.pred.average_shortest_path_length() > 0)
def test_predict_small_world(self):
n, k, p = self.pred.predict_small_world()
self.assertTrue(n > 0)
self.assertTrue(k > 0)
self.assertTrue(p > 0)
def test_generate_example_graphs(self):
l_values, c_values, l0, c0 = ParameterPrediction.generate_example_graphs(50, 6, logspace(-5, 0, 64, False, 10))
self.assertTrue(l0 > 0)
self.assertTrue(c0 > 0)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,448
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/static/wizard/generation.py
|
import tkinter as tk
from BribeNet.gui.apps.static.wizard.algos.barabasi_albert import BarabasiAlbert
from BribeNet.gui.apps.static.wizard.algos.composite import Composite
from BribeNet.gui.apps.static.wizard.algos.watts_strogatz import WattsStrogatz
ALGO_SUBFRAMES = (BarabasiAlbert, Composite, WattsStrogatz)
ALGO_DICT = {v: k for k, v in enumerate([a.name for a in ALGO_SUBFRAMES])}
class StaticGeneration(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
self.graph_type = tk.StringVar(self)
title_label = tk.Label(self, text='Graph Generation Algorithm')
title_label.grid(row=0, column=0, pady=10)
self.subframes = tuple(c(self) for c in ALGO_SUBFRAMES)
self.options = tuple(f.get_name() for f in self.subframes)
self.dropdown = tk.OptionMenu(self, self.graph_type, *self.options)
self.dropdown.grid(row=1, column=0, pady=10, sticky='nsew')
self.graph_type.set(self.options[0])
for f in self.subframes:
f.grid(row=2, column=0, sticky="nsew")
self.graph_type.trace('w', self.switch_frame)
self.show_subframe(0)
def show_subframe(self, page_no):
frame = self.subframes[page_no]
frame.tkraise()
# noinspection PyUnusedLocal
def switch_frame(self, *args):
self.show_subframe(ALGO_DICT[self.graph_type.get()])
def get_args(self):
return self.subframes[ALGO_DICT[self.graph_type.get()]].get_args()
def get_graph_type(self):
return self.graph_type.get()
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,449
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/bribery/temporal/action/multiBriberyAction.py
|
import sys
from typing import Dict, Optional, List
from BribeNet.bribery.temporal.action import BribeMustBeGreaterThanZeroException, NodeDoesNotExistException, \
BriberDoesNotExistException, BriberyActionExceedsAvailableUtilityException
from BribeNet.bribery.temporal.action.briberyAction import BriberyAction
from BribeNet.bribery.temporal.action.singleBriberyAction import SingleBriberyAction
from BribeNet.bribery.temporal.briber import GraphNotSubclassOfTemporalRatingGraphException
from BribeNet.helpers.bribeNetException import BribeNetException
class NoActionsToFormMultiActionException(BribeNetException):
pass
class BriberyActionsOnDifferentGraphsException(BribeNetException):
pass
class BriberyActionsAtDifferentTimesException(BribeNetException):
pass
class MultiBriberyAction(BriberyAction):
def __init__(self, graph, bribes: Optional[Dict[int, Dict[int, float]]] = None):
from BribeNet.graph.temporal.ratingGraph import TemporalRatingGraph
if not issubclass(graph.__class__, TemporalRatingGraph):
raise GraphNotSubclassOfTemporalRatingGraphException(f"{graph.__class__.__name__} is not a subclass of "
"TemporalRatingGraph")
super().__init__(graph=graph)
if bribes is not None:
for _, bribe in bribes.items():
for _, value in bribe.items():
if value < 0:
raise BribeMustBeGreaterThanZeroException()
self._bribes: Dict[int, Dict[int, float]] = bribes or {}
@classmethod
def empty_action(cls, graph):
return cls(graph, None)
@classmethod
def make_multi_action_from_single_actions(cls, actions: List[SingleBriberyAction]):
if not actions:
raise NoActionsToFormMultiActionException()
graph = actions[0].briber.get_graph()
if not all(b.briber.get_graph() is graph for b in actions):
raise BriberyActionsOnDifferentGraphsException()
time_step = actions[0].get_time_step()
if not all(b.get_time_step() == time_step for b in actions):
raise BriberyActionsAtDifferentTimesException()
return cls(graph=graph, bribes={b.briber.get_briber_id(): b.get_bribes() for b in actions})
def add_bribe(self, briber_id: int, node_id: int, bribe: float):
if bribe <= 0:
raise BribeMustBeGreaterThanZeroException()
if node_id not in self.graph.get_customers():
raise NodeDoesNotExistException()
if briber_id not in range(len(self.graph.get_bribers())):
raise BriberDoesNotExistException()
if briber_id in self._bribes:
if node_id in self._bribes[briber_id]:
print("WARNING: node bribed twice in single time step, combining...", file=sys.stderr)
self._bribes[briber_id][node_id] += bribe
else:
self._bribes[briber_id][node_id] = bribe
else:
self._bribes[briber_id] = {node_id: bribe}
def _perform_action(self):
bribers = self.graph.get_bribers()
for briber_id, bribe in self._bribes.items():
total_bribe_quantity = sum(bribe.values())
if total_bribe_quantity > bribers[briber_id].get_resources():
message = f"MultiBriberyAction exceeded resources available to briber {briber_id}: " \
f"{str(bribers[briber_id])} - {total_bribe_quantity} > {bribers[briber_id].get_resources()}"
raise BriberyActionExceedsAvailableUtilityException(message)
for briber_id, bribe in self._bribes.items():
for customer, value in bribe.items():
bribers[briber_id].bribe(node_id=customer, amount=value)
def is_bribed(self, node_id):
bribers = []
for briber_id in self._bribes:
if node_id in self._bribes[briber_id]:
bribers.append(briber_id)
if not bribers:
return False, bribers
return True, bribers
def get_bribes(self):
return self._bribes
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,450
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/bribery/temporal/mostInfluentialNodeBriber.py
|
import sys
import numpy as np
from BribeNet.bribery.temporal.action.singleBriberyAction import SingleBriberyAction
from BribeNet.bribery.temporal.briber import TemporalBriber
class MostInfluentialNodeBriber(TemporalBriber):
def __init__(self, u0: float, k: float = 0.1, i: int = 7):
"""
Constructor
:param u0: initial utility
:param k: cost of information
:param i: maximum loop iterations for finding most influential node
"""
super().__init__(u0)
self._k = k
self._c = 0 # current loop iteration
self._i = i # maximum loop iterations for finding most influential node
self._current_rating = None
self._previous_rating = None
self._max_rating_increase = 0
self._best_node = None
self._next_node = 0
self._last_node = 0
self._info_gained = set()
self._bribed = set()
def _set_graph(self, g):
super()._set_graph(g)
# Make sure that k is set such that there are enough resources left to actually bribe people.
self._k = min(self._k, 0.5 * (self.get_resources() / self.get_graph().customer_count()))
def _bribe_to_max(self):
bribe_to_max = self.get_graph().get_max_rating() - self.get_graph().get_vote(self._next_node)[self.get_briber_id()]
if np.isnan(bribe_to_max): bribe_to_max = 1.0
return bribe_to_max
def _next_action(self) -> SingleBriberyAction:
"""
Next action of briber, either to gain information or to fully bribe the most influential node
:return: SingleBriberyAction for the briber to take in the next temporal time step
"""
self._current_rating = self.get_graph().eval_graph(self.get_briber_id())
if self._previous_rating is None:
self._previous_rating = self._current_rating
next_act = SingleBriberyAction(self)
try:
self._next_node = self.get_graph().get_random_customer(excluding=self._info_gained | self._bribed)
except IndexError:
print(f"WARNING: {self.__class__.__name__} found no influential nodes, not acting...", file=sys.stderr)
return next_act
if self._current_rating - self._previous_rating > self._max_rating_increase:
self._best_node = self._last_node
self._max_rating_increase = self._current_rating - self._previous_rating
maximum_bribe = min(self.get_resources(), self._bribe_to_max())
if self._c >= self._i and self._best_node is not None and maximum_bribe > 0:
next_act.add_bribe(self._best_node, maximum_bribe)
self._bribed.add(self._best_node)
self._info_gained = set()
self._c = 0
self._max_rating_increase = 0
self._best_node = 0
else:
if self._c >= self._i:
print(f"WARNING: {self.__class__.__name__} has not found an influential node in {self._c} tries "
f"(intended maximum tries {self._i}), continuing search...",
file=sys.stderr)
# Bid an information gaining bribe, which is at most k, but is
# smaller if you need to bribe less to get to the full bribe
# or don't have enough money to bid k.
next_act.add_bribe(self._next_node, min(self._bribe_to_max(), min(self.get_resources(), self._k)))
self._info_gained.add(self._next_node)
self._c = self._c + 1
self._last_node = self._next_node
self._previous_rating = self._current_rating
return next_act
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,451
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/graph/generation/flatWeightGenerator.py
|
import networkit as nk
import networkit.nxadapter as adap
from BribeNet.graph.generation import GraphGeneratorAlgo
from BribeNet.graph.generation.weightedGenerator import WeightedGraphGenerator
class FlatWeightedGraphGenerator(WeightedGraphGenerator):
def __init__(self, a: GraphGeneratorAlgo, *args, **kwargs):
super().__init__(a, *args, **kwargs)
# Networkit does not let you add weights to a previously unweighted graph.
# Thus we convert it to a Networkx graph, add weights and then revert.
def generate(self) -> nk.graph:
nxg = adap.nk2nx(self._generator.generate())
for (u, v) in nxg.edges():
nxg[u][v]['weight'] = 1.0
return adap.nx2nk(nxg, 'weight')
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,452
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/wizard/rating_methods/median_p_rating.py
|
from BribeNet.graph.ratingMethod import RatingMethod
from BribeNet.gui.apps.temporal.wizard.rating_methods.rating_method_frame import RatingMethodFrame
class MedianPRating(RatingMethodFrame):
enum_value = RatingMethod.MEDIAN_P_RATING
name = 'median_p_rating'
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,453
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/wizard/rating_methods/p_gamma_rating.py
|
import tkinter as tk
from BribeNet.graph.ratingMethod import RatingMethod
from BribeNet.gui.apps.temporal.wizard.rating_methods.rating_method_frame import RatingMethodFrame
class PGammaRating(RatingMethodFrame):
enum_value = RatingMethod.P_GAMMA_RATING
name = 'p_gamma_rating'
def __init__(self, parent):
super().__init__(parent)
self.params = {
'gamma': tk.DoubleVar(self, value=0.05)
}
self.descriptions = {
'gamma': 'dampening factor that defines the effect of nodes based on their distance'
}
self.grid_params(show_name=False)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,454
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/bribery/temporal/test_randomBriber.py
|
from BribeNet.bribery.temporal.randomBriber import RandomBriber
from BribeNet.graph.temporal.noCustomerActionGraph import NoCustomerActionGraph
from test.BribeNet.bribery.temporal.briberTestCase import BriberTestCase
class TestRandomBriber(BriberTestCase):
def setUp(self) -> None:
self.briber = RandomBriber(10)
self.rg = NoCustomerActionGraph(self.briber)
def test_next_action_increases_p_rating(self):
graph = self.briber._g
action = self.briber.next_action()
briber_id = self.briber.get_briber_id()
prev_eval = graph.eval_graph(briber_id=briber_id)
action.perform_action()
self.assertGreaterEqual(graph.eval_graph(briber_id=briber_id), prev_eval)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,455
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/bribery/temporal/action/__init__.py
|
from BribeNet.helpers.bribeNetException import BribeNetException
class BribeMustBeGreaterThanZeroException(BribeNetException):
pass
class NodeDoesNotExistException(BribeNetException):
pass
class BriberDoesNotExistException(BribeNetException):
pass
class BriberyActionExceedsAvailableUtilityException(BribeNetException):
pass
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,456
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/result.py
|
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from BribeNet.gui.apps.temporal.results_wizard.window import TemporalResultsWizardWindow
class ResultsFrame(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.parent = parent
self.fig = plt.figure(figsize=(8, 8))
self.ax = self.fig.add_subplot(111)
self.canvas = FigureCanvasTkAgg(self.fig, master=self)
self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
replot_button = tk.Button(self, text="Change Variables", command=self.replot)
replot_button.pack()
exit_button = tk.Button(self, text="Exit", command=self.exit)
exit_button.pack()
def plot_results(self, results, x_label, y_label):
self.ax.clear()
# for each briber
xs = results.get(x_label)
ys = results.get(y_label)
if not isinstance(xs[0], list) and not isinstance(ys[0], list):
self.ax.plot(xs, ys)
else:
for b in range(0, len(self.controller.briber_names)):
x_plot = [r[b] for r in xs] if isinstance(xs[0], list) else xs
y_plot = [r[b] for r in ys] if isinstance(ys[0], list) else ys
print(x_plot)
print(y_plot)
self.ax.plot(x_plot, y_plot, label=self.controller.briber_names[b])
self.ax.legend()
self.ax.set_xlabel(x_label)
self.ax.set_ylabel(y_label)
self.canvas.draw()
def replot(self):
results_wizard = TemporalResultsWizardWindow(self.controller, self.controller.results)
results_wizard.lift()
def exit(self):
self.controller.show_frame("GraphFrame")
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,457
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/main.py
|
import tkinter as tk
from BribeNet.gui.apps.main import Main
from BribeNet.gui.apps.static.static import StaticGUI
from BribeNet.gui.apps.temporal.main import TemporalGUI
from BribeNet.helpers.override import override
class GUI(tk.Tk):
"""
Main menu window for the GUI
Self-withdraws when model wizard opened, and deiconifies when wizard closed
"""
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title("Bribery Networks")
self.main_frame = Main(self)
self.main_frame.grid(row=1, column=1)
self.grid_rowconfigure(1, weight=1)
self.grid_columnconfigure(1, weight=1)
self.minsize(400, 400)
self.static_gui = None
self.temporal_gui = None
def show_static_gui(self):
if (self.static_gui is None) and (self.temporal_gui is None):
self.static_gui = StaticGUI(self)
self.withdraw()
def show_temporal_gui(self):
if (self.static_gui is None) and (self.temporal_gui is None):
self.temporal_gui = TemporalGUI(self)
self.withdraw()
def show_main(self):
self.static_gui = None
self.temporal_gui = None
self.deiconify()
@override
def destroy(self):
if self.static_gui is not None:
self.static_gui.destroy()
if self.temporal_gui is not None:
self.temporal_gui.destroy()
super().destroy()
if __name__ == "__main__":
app = GUI()
app.mainloop()
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,458
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/graph/generation/weightedGenerator.py
|
import abc
from BribeNet.graph.generation import GraphGeneratorAlgo
from BribeNet.graph.generation.generator import GraphGenerator
class WeightedGraphGenerator(GraphGenerator, abc.ABC):
def __init__(self, a: GraphGeneratorAlgo, *args, **kwargs):
"""
Thin wrapper class for NetworKit graph generation algorithms which add weights to edges
:param a: the GraphGenerationAlgo to use
:param args: any arguments to this generator
:param kwargs: any keyword arguments to this generator
"""
super().__init__(a, *args, **kwargs)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,459
|
RobMurray98/BribeNet
|
refs/heads/master
|
/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py
|
from copy import deepcopy
from BribeNet.bribery.static.oneMoveRandomBriber import OneMoveRandomBriber
from BribeNet.graph.static.ratingGraph import StaticRatingGraph
from test.BribeNet.bribery.static.briberTestCase import BriberTestCase
class TestOneMoveInfluentialNodeBriber(BriberTestCase):
def setUp(self) -> None:
self.briber = OneMoveRandomBriber(10)
self.rg = StaticRatingGraph(self.briber)
def test_next_bribe_increases_p_rating(self):
initial_g = deepcopy(self.briber._g)
self.briber.next_bribe()
self._p_rating_increase(initial_g, self.briber._g)
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,460
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/static/result.py
|
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
class ResultsFrame(tk.Frame):
"""
Frame for showing the current results of the static model being run
"""
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.fig = plt.figure(figsize=(8, 8))
self.ax = self.fig.add_subplot(111)
self.canvas = FigureCanvasTkAgg(self.fig, master=self)
self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
button1 = tk.Button(self, text="Exit", command=self.exit)
button1.pack()
self.results = []
def plot_results(self, results):
xs = [i for i in range(0, len(results))]
self.ax.clear()
self.ax.plot(xs, results)
self.ax.set_xlabel("Moves over time")
self.ax.set_ylabel("Average P-rating")
self.canvas.draw()
def exit(self):
self.results = []
self.master.show_frame("WizardFrame")
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,461
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/gui/apps/temporal/wizard/rating_methods/p_rating.py
|
from BribeNet.graph.ratingMethod import RatingMethod
from BribeNet.gui.apps.temporal.wizard.rating_methods.rating_method_frame import RatingMethodFrame
class PRating(RatingMethodFrame):
enum_value = RatingMethod.P_RATING
name = 'p_rating'
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,462
|
RobMurray98/BribeNet
|
refs/heads/master
|
/src/BribeNet/graph/static/ratingGraphBuilder.py
|
import enum
import sys
from typing import List
from BribeNet.bribery.briber import Briber
from BribeNet.bribery.static.influentialNodeBriber import InfluentialNodeBriber
from BribeNet.bribery.static.mostInfluentialNodeBriber import MostInfluentialNodeBriber
from BribeNet.bribery.static.nonBriber import NonBriber
from BribeNet.bribery.static.oneMoveInfluentialNodeBriber import OneMoveInfluentialNodeBriber
from BribeNet.bribery.static.oneMoveRandomBriber import OneMoveRandomBriber
from BribeNet.bribery.static.randomBriber import RandomBriber
from BribeNet.graph.ratingGraph import DEFAULT_GEN
from BribeNet.graph.static.ratingGraph import StaticRatingGraph
@enum.unique
class BriberType(enum.Enum):
Non = 0
Random = 1
OneMoveRandom = 2
InfluentialNode = 3
MostInfluentialNode = 4
OneMoveInfluentialNode = 5
@classmethod
def get_briber_constructor(cls, idx, *args, **kwargs):
c = None
if idx == cls.Non:
c = NonBriber
if idx == cls.Random:
c = RandomBriber
if idx == cls.OneMoveRandom:
c = OneMoveRandomBriber
if idx == cls.InfluentialNode:
c = InfluentialNodeBriber
if idx == cls.MostInfluentialNode:
c = MostInfluentialNodeBriber
if idx == cls.OneMoveInfluentialNode:
c = OneMoveInfluentialNodeBriber
return lambda u0: c(u0, *args, **kwargs)
class RatingGraphBuilder(object):
def __init__(self):
self.bribers: List[Briber] = []
self.generator = DEFAULT_GEN
def add_briber(self, briber: BriberType, u0: int = 0, *args, **kwargs):
self.bribers.append(BriberType.get_briber_constructor(briber, *args, **kwargs)(u0))
return self
def set_generator(self, generator):
self.generator = generator
return self
def build(self) -> StaticRatingGraph:
if not self.bribers:
print("WARNING: StaticRatingGraph built with no bribers. Using NonBriber...", file=sys.stderr)
return StaticRatingGraph(tuple([NonBriber(0)]))
return StaticRatingGraph(tuple(self.bribers))
|
{"/test/BribeNet/bribery/temporal/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_randomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_budgetBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/test_briber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveInfluentialNodeBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_mostInfluentialBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/temporal/test_randomBriber.py": ["/test/BribeNet/bribery/temporal/briberTestCase.py"], "/test/BribeNet/bribery/static/test_oneMoveRandomBriber.py": ["/test/BribeNet/bribery/static/briberTestCase.py"]}
|
5,466
|
AdamWlodarczyk/jobqueue_features
|
refs/heads/master
|
/jobqueue_features/functions.py
|
from .clusters_controller import clusters_controller_singleton
from .clusters import ClusterType # noqa
def set_default_cluster(cluster):
# type: (ClusterType) -> None
"""Function sets default cluster type for clusters controller.
This should be the right way of setting that."""
clusters_controller_singleton.default_cluster = cluster
|
{"/jobqueue_features/functions.py": ["/jobqueue_features/clusters_controller.py"], "/examples/mpi_tasks_srun.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py"], "/jobqueue_features/tests/test_cluster.py": ["/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/clusters_controller.py"], "/examples/mpi_tasks_mpiexec.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/functions.py"], "/jobqueue_features/decorators.py": ["/jobqueue_features/clusters_controller.py", "/jobqueue_features/mpi_wrapper.py"], "/examples/forked_mpi_task_srun.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/functions.py"]}
|
5,467
|
AdamWlodarczyk/jobqueue_features
|
refs/heads/master
|
/examples/mpi_tasks_srun.py
|
from __future__ import print_function
import sys
from jobqueue_features.clusters import CustomSLURMCluster
from jobqueue_features.decorators import on_cluster, mpi_task
from jobqueue_features.mpi_wrapper import SRUN
# import logging
# logging.basicConfig(format="%(levelname)s:%(message)s", level=logging.DEBUG)
custom_cluster = CustomSLURMCluster(
name="mpiCluster", walltime="00:03:00", nodes=2, mpi_mode=True, mpi_launcher=SRUN
)
@mpi_task(cluster_id="mpiCluster")
def task1(task_name):
from mpi4py import MPI
comm = MPI.COMM_WORLD
size = comm.Get_size()
name = MPI.Get_processor_name()
all_nodes = comm.gather(name, root=0)
if all_nodes:
all_nodes = set(all_nodes)
else:
all_nodes = []
# Since it is a return value it will only get printed by root
return_string = "Running %d tasks of type %s on nodes %s." % (
size,
task_name,
all_nodes,
)
# The flush is required to ensure that the print statements appear in the job log
# files
print(return_string)
sys.stdout.flush()
return return_string
@mpi_task(cluster_id="mpiCluster")
def task2(name, task_name="default"):
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
# This only appears in the slurm job output
return_string = "Hi %s, my rank is %d for task of type %s" % (name, rank, task_name)
# The flush is required to ensure that the print statements appear in the job log
# files
print(return_string)
sys.stdout.flush()
return return_string
@on_cluster(cluster=custom_cluster, cluster_id="mpiCluster")
def main():
t1 = task1("task1")
t2 = task1("task1, 2nd iteration")
t3 = task2("Alan", task_name="Task 2")
print(t1.result())
print(t2.result())
print(t3.result())
if __name__ == "__main__":
main()
|
{"/jobqueue_features/functions.py": ["/jobqueue_features/clusters_controller.py"], "/examples/mpi_tasks_srun.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py"], "/jobqueue_features/tests/test_cluster.py": ["/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/clusters_controller.py"], "/examples/mpi_tasks_mpiexec.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/functions.py"], "/jobqueue_features/decorators.py": ["/jobqueue_features/clusters_controller.py", "/jobqueue_features/mpi_wrapper.py"], "/examples/forked_mpi_task_srun.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/functions.py"]}
|
5,468
|
AdamWlodarczyk/jobqueue_features
|
refs/heads/master
|
/jobqueue_features/tests/test_cluster.py
|
from unittest import TestCase
from dask.distributed import Client
from jobqueue_features.clusters import get_cluster, SLURM
from jobqueue_features.mpi_wrapper import SRUN
from jobqueue_features.cli.mpi_dask_worker import MPI_DASK_WRAPPER_MODULE
from jobqueue_features.clusters_controller import (
clusters_controller_singleton as controller,
)
class TestClusters(TestCase):
def setUp(self):
self.cluster_name = "dask-worker-batch" # default
self.kwargs = {
# 'interface': 'eth0', # most likely won't have ib0 available so just use
# a safe default for the tests
"interface": "",
"fork_mpi": False,
"mpi_launcher": SRUN,
}
def test_custom_cluster(self):
cluster = get_cluster(scheduler=SLURM, **self.kwargs)
self.assertEqual(cluster.name, self.cluster_name)
self.assertIsInstance(cluster.client, Client)
with self.assertRaises(ValueError):
get_cluster(SLURM, cores=128, **self.kwargs)
controller.delete_cluster(cluster.name)
def test_gpu_cluster(self):
cluster = get_cluster(queue_type="gpus", **self.kwargs)
self.assertEqual(cluster.name, "dask-worker-gpus")
self.assertIn("#SBATCH -p gpus", cluster.job_header)
self.assertIn("#SBATCH --gres=gpu:4", cluster.job_header)
self.assertIsInstance(cluster.client, Client)
controller.delete_cluster(cluster.name)
def test_knl_cluster(self):
cluster = get_cluster(queue_type="knl", **self.kwargs)
self.assertEqual(cluster.name, "dask-worker-knl")
self.assertIn("#SBATCH -p booster", cluster.job_header)
self.assertIn("#SBATCH --cpus-per-task=64", cluster.job_header)
self.assertIsInstance(cluster.client, Client)
controller.delete_cluster(cluster.name)
def test_nonexistent_queue_type(self):
with self.assertRaises(ValueError) as context:
get_cluster(queue_type="chicken", **self.kwargs)
self.assertIn(
"queue_type kwarg value 'chicken' not in available options",
str(context.exception),
)
def test_mpi_job_cluster(self):
# First do a simple mpi job
cluster = get_cluster(queue_type="knl", mpi_mode=True, cores=64, **self.kwargs)
self.assertIn("#SBATCH --cpus-per-task=1", cluster.job_header)
self.assertIn("#SBATCH --ntasks-per-node=64", cluster.job_header)
self.assertIn("#SBATCH -n 64", cluster.job_script())
self.assertIn(MPI_DASK_WRAPPER_MODULE, cluster._command_template)
self.assertEqual(cluster.worker_cores, 1)
self.assertEqual(cluster.worker_processes, 1)
self.assertEqual(cluster.worker_process_threads, 1)
self.assertIsInstance(cluster.client, Client)
controller.delete_cluster(cluster.name)
with self.assertRaises(ValueError):
cluster = get_cluster(
queue_type="knl", mpi_mode=True, nodes=64, cores=64, **self.kwargs
)
controller.delete_cluster(cluster.name)
def test_fork_mpi_job_cluster(self):
# First do a simple mpi job
kwargs = self.kwargs
kwargs.update({"fork_mpi": True})
cluster = get_cluster(queue_type="knl", mpi_mode=True, cores=64, **kwargs)
self.assertNotIn(MPI_DASK_WRAPPER_MODULE, cluster._command_template)
controller.delete_cluster(cluster.name)
def test_mpi_multi_node_job_cluster(self):
# First do a simple mpi job
cluster = get_cluster(queue_type="knl", mpi_mode=True, cores=130, **self.kwargs)
self.assertIn("#SBATCH --cpus-per-task=1", cluster.job_header)
self.assertIn("#SBATCH --ntasks-per-node=64", cluster.job_header)
self.assertIn("#SBATCH -n 130", cluster.job_script())
self.assertEqual(cluster.worker_cores, 1)
self.assertEqual(cluster.worker_processes, 1)
self.assertEqual(cluster.worker_process_threads, 1)
with self.assertRaises(ValueError):
get_cluster(queue_type="knl", mpi_mode=True, **self.kwargs)
with self.assertRaises(ValueError):
get_cluster(
queue_type="knl",
cpus_per_task=37,
cores=2,
mpi_mode=True,
**self.kwargs
)
with self.assertRaises(ValueError):
get_cluster(
queue_type="knl",
cores=1,
ntasks_per_node=13,
mpi_mode=True,
**self.kwargs
)
controller.delete_cluster(cluster.name)
def test_mpi_complex_job_cluster(self):
# Now a few more variables
cluster = get_cluster(
queue_type="gpus", mpi_mode=True, nodes=2, ntasks_per_node=4, **self.kwargs
)
self.assertIn("#SBATCH --cpus-per-task=6", cluster.job_header)
self.assertIn("#SBATCH --ntasks-per-node=4", cluster.job_header)
self.assertIn("#SBATCH --nodes=2", cluster.job_header)
self.assertIn("#SBATCH --gres=gpu:4", cluster.job_header)
self.assertEqual(cluster.worker_cores, 1)
self.assertEqual(cluster.worker_processes, 1)
self.assertEqual(cluster.worker_process_threads, 1)
self.assertIn("#SBATCH -n 8", cluster.job_script())
self.assertIn(
"export OMP_NUM_THREADS=${SLURM_CPUS_PER_TASK}", cluster.job_script()
)
self.assertIn("export OMP_PROC_BIND=spread", cluster.job_script())
self.assertIn("export OMP_PLACES=threads", cluster.job_script())
controller.delete_cluster(cluster.name)
def test_mpi_complex_job_cluster_fail(self):
# Now a few more variables
with self.assertRaises(ValueError) as ctx:
# When we provide ntasks_per_node, cpus_per_tasks is derived (in this case
# 24/2 = 12). For an MPI job we expect the core count (which is the total
# number of cores to be used) to be divisible by cpus_per_tasks but that is
# not true in this case resulting in a ValueError
get_cluster(
queue_type="gpus",
mpi_mode=True,
cores=2,
ntasks_per_node=2,
**self.kwargs
)
# If you really want this you ask for it explicitly
cluster = get_cluster(
queue_type="gpus",
mpi_mode=True,
cores=2,
ntasks_per_node=2,
cpus_per_task=1,
**self.kwargs
)
self.assertIn("#SBATCH --cpus-per-task=1", cluster.job_header)
self.assertIn("#SBATCH --ntasks-per-node=2", cluster.job_header)
self.assertIn("#SBATCH -n 2", cluster.job_header)
self.assertNotIn("#SBATCH --nodes", cluster.job_header)
self.assertIn("#SBATCH --gres=gpu:4", cluster.job_header)
controller.delete_cluster(cluster.name)
# For memory pinning stuff that may be done by the scheduler, it is probably
# better to ask for it like this (even if you don't intend to use OpenMP)
cluster = get_cluster(
queue_type="gpus", mpi_mode=True, nodes=1, ntasks_per_node=2, **self.kwargs
)
self.assertIn("#SBATCH --cpus-per-task=12", cluster.job_header)
self.assertIn("#SBATCH --ntasks-per-node=2", cluster.job_header)
self.assertIn("#SBATCH -n 2", cluster.job_header)
self.assertIn("#SBATCH --nodes=1", cluster.job_header)
self.assertIn("#SBATCH --gres=gpu:4", cluster.job_header)
controller.delete_cluster(cluster.name)
def test_mpi_explicit_job_cluster(self):
# Now a few more variables
cluster = get_cluster(
queue_type="gpus",
mpi_mode=True,
nodes=2,
cpus_per_task=2,
ntasks_per_node=12,
**self.kwargs
)
self.assertIn("#SBATCH --cpus-per-task=2", cluster.job_header)
self.assertIn("#SBATCH --ntasks-per-node=12", cluster.job_header)
self.assertIn("#SBATCH --nodes=2", cluster.job_header)
self.assertIn("#SBATCH --gres=gpu:4", cluster.job_header)
self.assertEqual(cluster.worker_cores, 1)
self.assertEqual(cluster.worker_processes, 1)
self.assertEqual(cluster.worker_process_threads, 1)
self.assertIn("#SBATCH -n 24", cluster.job_script())
self.assertIn(
"export OMP_NUM_THREADS=${SLURM_CPUS_PER_TASK}", cluster.job_script()
)
self.assertIn("export OMP_PROC_BIND=spread", cluster.job_script())
self.assertIn("export OMP_PLACES=threads", cluster.job_script())
controller.delete_cluster(cluster.name)
def test_scheduler_fail_job_cluster(self):
with self.assertRaises(NotImplementedError):
get_cluster(scheduler="pbs", **self.kwargs)
def test_non_integer_kwargs(self):
with self.assertRaises(ValueError):
get_cluster(SLURM, minimum_cores="a", **self.kwargs)
with self.assertRaises(ValueError):
get_cluster(SLURM, cores_per_node=0, **self.kwargs)
with self.assertRaises(ValueError):
get_cluster(SLURM, hyperthreading_factor=[], **self.kwargs)
def test_wrong_hyperthreading_factor(self):
with self.assertRaises(ValueError):
get_cluster(
SLURM,
minimum_cores=2,
cores_per_node=1,
hyperthreading_factor=1,
**self.kwargs
)
|
{"/jobqueue_features/functions.py": ["/jobqueue_features/clusters_controller.py"], "/examples/mpi_tasks_srun.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py"], "/jobqueue_features/tests/test_cluster.py": ["/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/clusters_controller.py"], "/examples/mpi_tasks_mpiexec.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/functions.py"], "/jobqueue_features/decorators.py": ["/jobqueue_features/clusters_controller.py", "/jobqueue_features/mpi_wrapper.py"], "/examples/forked_mpi_task_srun.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/functions.py"]}
|
5,469
|
AdamWlodarczyk/jobqueue_features
|
refs/heads/master
|
/jobqueue_features/tests/test_mpi_wrapper.py
|
from __future__ import print_function
from unittest import TestCase
import os
from distributed import LocalCluster
from jobqueue_features import (
mpi_wrap,
MPIEXEC,
SRUN,
on_cluster,
mpi_task,
which,
serialize_function_and_args,
deserialize_and_execute,
mpi_deserialize_and_execute,
verify_mpi_communicator,
flush_and_abort,
)
class TestMPIWrap(TestCase):
def setUp(self):
self.number_of_processes = 4
self.local_cluster = LocalCluster()
self.executable = "python"
self.script_path = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
"..",
"..",
"examples",
"resources",
"helloworld.py",
)
)
@mpi_task(cluster_id="test", default_mpi_tasks=4)
def mpi_wrap_task(**kwargs):
return mpi_wrap(**kwargs)
@on_cluster(cluster=self.local_cluster, cluster_id="test")
def test_function(script_path, return_wrapped_command=False):
t = mpi_wrap_task(
executable=self.executable,
exec_args=script_path,
mpi_launcher=MPIEXEC,
mpi_tasks=self.number_of_processes,
return_wrapped_command=return_wrapped_command,
)
if return_wrapped_command:
result = t.result()
else:
result = t.result()["out"]
return result
self.test_function = test_function
def mpi_task1(task_name):
from mpi4py import MPI
comm = MPI.COMM_WORLD
size = comm.Get_size()
# Since it is a return value it will only get printed by root
return "Running %d tasks of type %s." % (size, task_name)
self.mpi_task1 = mpi_task1
def string_task(string, kwarg_string=None):
return " ".join([s for s in [string, kwarg_string] if s])
self.string_task = string_task
def test_which(self):
# Check it finds a full path
self.assertEqual(which(self.script_path), self.script_path)
# Check it searches the PATH envvar
os.environ["PATH"] += os.pathsep + os.path.dirname(self.script_path)
self.assertEqual(which(os.path.basename(self.script_path)), self.script_path)
# Check it returns None if the executable doesn't exist
self.assertIsNone(which("not_an_executable"))
# Check it returns None when a file is not executable
self.assertIsNone(which(os.path.realpath(__file__)))
def test_mpi_wrap(self):
#
# Assume here we have mpiexec support
if which(MPIEXEC) is not None:
print("Found {}, running MPI test".format(MPIEXEC))
result = self.test_function(self.script_path)
for n in range(self.number_of_processes):
text = "Hello, World! I am process {} of {}".format(
n, self.number_of_processes
)
self.assertIn(text.encode(), result)
result = self.test_function(self.script_path, return_wrapped_command=True)
expected_result = "{} -np {} {} {}".format(
MPIEXEC, self.number_of_processes, self.executable, self.script_path
)
self.assertEqual(result, expected_result)
else:
pass
# Test the MPI wrapper in isolation for srun (which we assume doesn't exist):
def test_mpi_srun_wrapper(self):
if which(SRUN) is None:
print(
"Didn't find {}, running OSError test for no available launcher".format(
SRUN
)
)
with self.assertRaises(OSError) as context:
mpi_wrap(
executable="python",
exec_args=self.script_path,
mpi_launcher=SRUN,
mpi_tasks=self.number_of_processes,
)
self.assertTrue(
"OS error caused by constructed command" in str(context.exception)
)
else:
pass
# Test our serialisation method
def test_serialize_function_and_args(self):
# First check elements in our dict
serialized_object = serialize_function_and_args(self.string_task)
for key in serialized_object.keys():
self.assertIn(key, ["header", "frames"])
serialized_object = serialize_function_and_args(self.string_task, "chicken")
for key in serialized_object.keys():
self.assertIn(key, ["header", "frames", "args_header", "args_frames"])
serialized_object = serialize_function_and_args(
self.string_task, kwarg_string="dog"
)
for key in serialized_object.keys():
self.assertIn(key, ["header", "frames", "kwargs_header", "kwargs_frames"])
serialized_object = serialize_function_and_args(
self.string_task, "chicken", kwarg_string="dog"
)
for key in serialized_object.keys():
self.assertIn(
key,
[
"header",
"frames",
"args_header",
"args_frames",
"kwargs_header",
"kwargs_frames",
],
)
def test_deserialize_and_execute(self):
serialized_object = serialize_function_and_args(
self.string_task, "chicken", kwarg_string="dog"
)
self.assertEqual("chicken dog", deserialize_and_execute(serialized_object))
def test_flush_and_abort(self):
with self.assertRaises(SystemExit) as cm:
flush_and_abort(mpi_abort=False)
self.assertEqual(cm.exception.code, 1)
with self.assertRaises(SystemExit) as cm:
flush_and_abort(error_code=2, mpi_abort=False)
self.assertEqual(cm.exception.code, 2)
def test_verify_mpi_communicator(self):
from mpi4py import MPI
comm = MPI.COMM_WORLD
with self.assertRaises(SystemExit) as cm:
verify_mpi_communicator("Not a communicator", mpi_abort=False)
self.assertEqual(cm.exception.code, 1)
self.assertTrue(verify_mpi_communicator(comm, mpi_abort=False))
def test_mpi_deserialize_and_execute(self):
trivial = "trivial"
serialized_object = serialize_function_and_args(self.mpi_task1, trivial)
# The test framework is not started with an MPI launcher so we have a single task
expected_string = "Running 1 tasks of type {}.".format(trivial)
return_value = mpi_deserialize_and_execute(serialized_object)
self.assertEqual(expected_string, return_value)
|
{"/jobqueue_features/functions.py": ["/jobqueue_features/clusters_controller.py"], "/examples/mpi_tasks_srun.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py"], "/jobqueue_features/tests/test_cluster.py": ["/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/clusters_controller.py"], "/examples/mpi_tasks_mpiexec.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/functions.py"], "/jobqueue_features/decorators.py": ["/jobqueue_features/clusters_controller.py", "/jobqueue_features/mpi_wrapper.py"], "/examples/forked_mpi_task_srun.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/functions.py"]}
|
5,470
|
AdamWlodarczyk/jobqueue_features
|
refs/heads/master
|
/examples/mpi_tasks_mpiexec.py
|
from __future__ import print_function
import os
from dask.distributed import LocalCluster
from jobqueue_features.decorators import on_cluster, mpi_task
from jobqueue_features.mpi_wrapper import mpi_wrap, MPIEXEC
from jobqueue_features.functions import set_default_cluster
# import logging
# logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
set_default_cluster(LocalCluster)
@mpi_task()
def mpi_wrap_task(**kwargs):
return mpi_wrap(**kwargs)
@on_cluster()
def main():
script_path = os.path.join(os.path.dirname(__file__), "resources", "helloworld.py")
t = mpi_wrap_task(executable="python", exec_args=script_path, mpi_launcher=MPIEXEC)
print(t.result())
if __name__ == "__main__":
main()
|
{"/jobqueue_features/functions.py": ["/jobqueue_features/clusters_controller.py"], "/examples/mpi_tasks_srun.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py"], "/jobqueue_features/tests/test_cluster.py": ["/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/clusters_controller.py"], "/examples/mpi_tasks_mpiexec.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/functions.py"], "/jobqueue_features/decorators.py": ["/jobqueue_features/clusters_controller.py", "/jobqueue_features/mpi_wrapper.py"], "/examples/forked_mpi_task_srun.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/functions.py"]}
|
5,471
|
AdamWlodarczyk/jobqueue_features
|
refs/heads/master
|
/jobqueue_features/decorators.py
|
from __future__ import print_function
from typing import Callable, List, Dict # noqa
from functools import wraps
from dask.distributed import LocalCluster, Client, Future # noqa
from .clusters_controller import clusters_controller_singleton, ClusterType # noqa
from .custom_exceptions import ClusterException
from .mpi_wrapper import (
MPIEXEC,
serialize_function_and_args,
mpi_deserialize_and_execute,
)
def _get_workers_number(client):
return len(client._scheduler_identity.get("workers", {}))
class on_cluster(object):
"""Decorator gets or create clusters from clusters controller.
Parameters
----------
cluster : ClusterType
Work on given cluster
cluster_id : str
Gets or create cluster with given id. If no id provided controller
gets default cluster (cluster_id = 'default').
scale : int
Scale cluster (default or given by id or passes by cluster parameter).
"""
def __init__(self, cluster=None, cluster_id=None, scale=None):
# type: (ClusterType, str, int) -> None
_id = self._get_cluster_id(cluster=cluster, cluster_id=cluster_id)
try:
self.cluster, client = clusters_controller_singleton.get_cluster(
id_=_id
) # type: ClusterType
except ClusterException:
self.cluster, client = clusters_controller_singleton.add_cluster(
id_=_id, cluster=cluster
) # type: ClusterType
if not self._is_local_cluster(cluster=self.cluster):
if scale is not None:
# If the kwarg 'scale' has been used in the decorator call we adaptively
# scale up to that many workers
if scale > self.cluster.maximum_scale:
print(
"Scaling cluster {cluster_id} to {scale} exceeds default "
"maximum workers ({maximum_scale})".format(
cluster_id=_id,
scale=scale,
maximum_scale=self.cluster.maximum_scale,
)
)
self.cluster.adapt(
minimum=0, maximum=scale, wait_count=10, interval="6s"
)
else:
self.cluster.adapt(
minimum=0,
maximum=self.cluster.maximum_scale,
wait_count=10,
interval="6s",
)
# We immediately start up `scale` workers rather than wait for adapt to
# kick in the `wait_count`*`interval` should keep them from shutting
# down too fast (allows 1 minute idle)
self.cluster.scale(scale)
else:
# Otherwise we adaptively scale to the maximum number of workers
self.cluster.adapt(minimum=0, maximum=self.cluster.maximum_scale)
def __call__(self, f):
# type: (Callable) -> Callable
@wraps(f)
def wrapped_function(*args, **kwargs):
return f(*args, **kwargs)
return wrapped_function
@staticmethod
def _is_local_cluster(cluster):
# type: (ClusterType) -> bool
return type(cluster) is LocalCluster
def _get_cluster_id(self, cluster=None, cluster_id=None):
# type: (ClusterType, str) -> str
if cluster:
if not self._is_local_cluster(cluster=cluster):
if cluster_id is not None:
assert cluster_id == cluster.name
return cluster_id
else:
return cluster.name
else:
if cluster_id is None:
raise ClusterException(
'LocalCluster requires "cluster_id" argument.'
)
return cluster_id
return cluster_id
class task(object):
"""Decorator gets client from clusters controller and submits
wrapped function to given cluster.
Parameters
----------
cluster : ClusterType
cluster_id : str
Gets client of given cluster by id or 'default' if none given.
"""
def __init__(self, cluster_id=None, cluster=None):
# type: (str) -> None
self.cluster_id = cluster_id
if cluster:
if type(cluster) is not LocalCluster:
_id = getattr(cluster, "name", None)
if not _id:
raise ClusterException("Cluster has no name attribute set.")
elif cluster_id and _id != cluster_id:
raise ClusterException(
"Cluster 'name' and cluster_id are different."
)
else:
self.cluster_id = _id
elif not cluster_id:
raise ClusterException(
"'cluster_id' argument is required for LocalCluster."
)
def __call__(self, f):
# type: (Callable) -> Callable
@wraps(f)
def wrapped_f(*args, **kwargs): # type: (...) -> Future
cluster, client = self._get_cluster_and_client()
return self._submit(cluster, client, f, *args, **kwargs)
return wrapped_f
def _get_cluster_and_client(self):
try:
return clusters_controller_singleton.get_cluster(id_=self.cluster_id)
except KeyError:
raise ClusterException(
"Could not find Cluster or Client. " "Use @on_cluster() decorator."
)
def _submit(self, cluster, client, f, *args, **kwargs):
# type: (ClusterType, Client, Callable, List[...], Dict[...]) -> Future
# For normal tasks, we maintain the Dask default that functions are pure (by
# default)
kwargs.update({"pure": getattr(cluster, "pure", getattr(kwargs, "pure", True))})
return client.submit(f, *args, **kwargs)
class mpi_task(task):
def __init__(self, cluster_id=None, default_mpi_tasks=1):
# type: (str, int) -> None
# set a default number of MPI tasks (in case we are running on a localcluster)
self.default_mpi_tasks = default_mpi_tasks
super(mpi_task, self).__init__(cluster_id=cluster_id)
def _get_cluster_attribute(self, cluster, attribute, default, **kwargs):
dict_value = kwargs.pop(attribute, default)
return getattr(cluster, attribute, dict_value), kwargs
def _submit(self, cluster, client, f, *args, **kwargs):
# For MPI tasks, let's assume functions are not pure (by default)
pure, kwargs = self._get_cluster_attribute(cluster, "pure", False, **kwargs)
# For a LocalCluster, mpi_mode/fork_mpi will not have been set so let's assume
# MPI forking
mpi_mode, kwargs = self._get_cluster_attribute(
cluster, "mpi_mode", None, **kwargs
)
if mpi_mode is None:
fork_mpi = True
else:
# Check if it is a forking task
fork_mpi, kwargs = self._get_cluster_attribute(
cluster, "fork_mpi", False, **kwargs
)
# type: (ClusterType, Client, Callable, List[...], Dict[...]) -> Future
if fork_mpi:
# Add a set of kwargs that define the job layout to be picked up by
# our mpi_wrap function
mpi_launcher, kwargs = self._get_cluster_attribute(
cluster, "mpi_launcher", MPIEXEC, **kwargs
)
mpi_tasks, kwargs = self._get_cluster_attribute(
cluster, "mpi_tasks", self.default_mpi_tasks, **kwargs
)
nodes, kwargs = self._get_cluster_attribute(
cluster, "nodes", None, **kwargs
)
cpus_per_task, kwargs = self._get_cluster_attribute(
cluster, "cpus_per_task", None, **kwargs
)
ntasks_per_node, kwargs = self._get_cluster_attribute(
cluster, "ntasks_per_node", None, **kwargs
)
return super(mpi_task, self)._submit(
cluster,
client,
f,
*args,
pure=pure,
mpi_launcher=mpi_launcher,
mpi_tasks=mpi_tasks,
nodes=nodes,
cpus_per_task=cpus_per_task,
ntasks_per_node=ntasks_per_node,
**kwargs
)
else:
# If we are not forking we need to serialize the task and arguments
serialized_object = serialize_function_and_args(f, *args, **kwargs)
# Then we submit our deserializing/executing function as the task
return super(mpi_task, self)._submit(
cluster,
client,
mpi_deserialize_and_execute,
serialized_object,
pure=pure,
)
|
{"/jobqueue_features/functions.py": ["/jobqueue_features/clusters_controller.py"], "/examples/mpi_tasks_srun.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py"], "/jobqueue_features/tests/test_cluster.py": ["/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/clusters_controller.py"], "/examples/mpi_tasks_mpiexec.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/functions.py"], "/jobqueue_features/decorators.py": ["/jobqueue_features/clusters_controller.py", "/jobqueue_features/mpi_wrapper.py"], "/examples/forked_mpi_task_srun.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/functions.py"]}
|
5,472
|
AdamWlodarczyk/jobqueue_features
|
refs/heads/master
|
/jobqueue_features/mpi_wrapper.py
|
from distributed.protocol import serialize, deserialize
import os
import shlex
import subprocess
import sys
from typing import Dict # noqa
SRUN = "srun"
MPIEXEC = "mpiexec"
SUPPORTED_MPI_LAUNCHERS = [SRUN, MPIEXEC]
def which(filename):
result = None
# Check we can immediately find the executable
if os.path.exists(filename) and os.access(filename, os.X_OK):
result = filename
else:
# Look everywhere in the users PATH
for path in os.environ["PATH"].split(os.pathsep):
full_path = os.path.join(path, filename)
if os.path.exists(full_path) and os.access(full_path, os.X_OK):
result = full_path
return result
def mpi_wrap(
executable=None,
pre_launcher_opts="",
mpi_launcher=None,
launcher_args="",
mpi_tasks=None,
nodes=None,
cpus_per_task=None,
ntasks_per_node=None,
exec_args="",
return_wrapped_command=False,
**kwargs
):
# type: (str, str, str, str, str, ...) -> Dict[str, str]
def get_default_mpi_params(
mpi_launcher, mpi_tasks, nodes, cpus_per_task, ntasks_per_node
):
"""
Based on the requested process distribution, return default arguments for the
MPI launcher.
:param mpi_launcher: The MPI launcher (such as mpiexec, srun, mpirun,...)
:param mpi_tasks: Total number of MPI tasks
:param nodes: Number of nodes requested (optional)
:param cpus_per_task: Number of CPUs per MPI task (most relevant for hybrid
jobs)
:param ntasks_per_node: Number of MPI tasks per node
:return: string
"""
if mpi_launcher == SRUN:
# SLURM already has everything it needs from the environment variables set
# by the batch script
return ""
elif mpi_launcher == MPIEXEC:
# Let's not error-check excessively, only the most obvious
if mpi_tasks is None and any([nodes is None, ntasks_per_node is None]):
raise ValueError(
"If mpi_tasks is not set then nodes and ntasks_per_node must be set instead"
)
if mpi_tasks is None:
mpi_tasks = nodes * ntasks_per_node
# mpiexec is defined by the standard and very basic, you can only tell it
# how many MPI tasks to start
return "-np {}".format(mpi_tasks)
else:
raise NotImplementedError(
"MPI launcher {mpi_launcher} is not yet supported.".format(
mpi_launcher=mpi_launcher
)
)
if mpi_launcher is None:
raise ValueError("The kwarg mpi_launcher must be set!")
if not isinstance(executable, str):
ValueError(
"executable is interpreted as a simple basestring: %(executable)".format(
executable=executable
)
)
# Also check for the existence of the executable (unless we
# "return_wrapped_command")
if not which(executable) and not return_wrapped_command:
ValueError(
"The executable should be available in the users path and have execute "
"rights: please check %(executable)".format(executable=executable)
)
default_launcher_args = get_default_mpi_params(
mpi_launcher, mpi_tasks, nodes, cpus_per_task, ntasks_per_node
)
cmd = " ".join(
[
string
for string in [
pre_launcher_opts,
mpi_launcher,
default_launcher_args,
launcher_args,
executable,
exec_args,
]
if string
]
)
if return_wrapped_command:
result = cmd
else:
try:
proc = subprocess.Popen(
shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
out = proc.stdout.read()
err = proc.stderr.read()
except OSError as err:
raise OSError(
"OS error caused by constructed command: {cmd}\n\n{err}".format(
cmd=cmd, err=err
)
)
result = {"cmd": cmd, "out": out, "err": err}
return result
def shutdown_mpitask_worker():
from mpi4py import MPI
# Finalise MPI
MPI.Finalize()
# and then exit
exit()
def deserialize_and_execute(serialized_object):
# Ensure the serialized object is of the expected type
if isinstance(serialized_object, dict):
# Make sure it has the expected entries
if not ("header" in serialized_object and "frames" in serialized_object):
raise RuntimeError(
"serialized_object dict does not have expected keys [header, frames]"
)
else:
raise RuntimeError("Cannot deserialize without a serialized_object")
func = deserialize(serialized_object["header"], serialized_object["frames"])
if serialized_object.get("args_header"):
args = deserialize(
serialized_object["args_header"], serialized_object["args_frames"]
)
else:
args = []
if serialized_object.get("kwargs_header"):
kwargs = deserialize(
serialized_object["kwargs_header"], serialized_object["kwargs_frames"]
)
else:
kwargs = {}
# Free memory space used by (potentially large) serialised object
del serialized_object
# Execute the function and return
return func(*args, **kwargs)
def flush_and_abort(
msg="Flushing print buffer and aborting", comm=None, error_code=1, mpi_abort=True
):
import traceback
if comm is None:
from mpi4py import MPI
comm = MPI.COMM_WORLD
if error_code == 0:
print("To abort correctly, we need to use a non-zero error code")
error_code = 1
if mpi_abort:
print(msg)
traceback.print_stack()
sys.stdout.flush()
sys.stderr.flush()
comm.Abort(error_code)
sys.exit(error_code)
def verify_mpi_communicator(comm, mpi_abort=True):
# Check we have a valid communicator
try:
comm.Get_rank()
return True
except AttributeError:
flush_and_abort(
msg="Looks like you did not pass a valid MPI communicator, aborting "
"using global communicator",
mpi_abort=mpi_abort,
)
def mpi_deserialize_and_execute(serialized_object=None, root=0, comm=None):
if comm is None:
from mpi4py import MPI
comm = MPI.COMM_WORLD
# Check we have a valid communicator
verify_mpi_communicator(comm)
# We only handle the case where root has the object and is the one who returns
# something
if serialized_object:
rank = comm.Get_rank()
if rank != root:
flush_and_abort(
msg="Only root rank (%d) can contain a serialized object for this "
"call, my rank is %d...aborting!" % (root, rank),
comm=comm,
)
print("Root ({}) has received the task and is broadcasting".format(rank))
return_something = True
else:
return_something = False
serialized_object = comm.bcast(serialized_object, root=root)
result = deserialize_and_execute(serialized_object)
if return_something and result:
return result
def serialize_function_and_args(func, *args, **kwargs):
header, frames = serialize(func)
serialized_object = {"header": header, "frames": frames}
if args:
args_header, args_frames = serialize(args)
serialized_object.update(
{"args_header": args_header, "args_frames": args_frames}
)
if kwargs:
kwargs_header, kwargs_frames = serialize(kwargs)
serialized_object.update(
{"kwargs_header": kwargs_header, "kwargs_frames": kwargs_frames}
)
return serialized_object
|
{"/jobqueue_features/functions.py": ["/jobqueue_features/clusters_controller.py"], "/examples/mpi_tasks_srun.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py"], "/jobqueue_features/tests/test_cluster.py": ["/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/clusters_controller.py"], "/examples/mpi_tasks_mpiexec.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/functions.py"], "/jobqueue_features/decorators.py": ["/jobqueue_features/clusters_controller.py", "/jobqueue_features/mpi_wrapper.py"], "/examples/forked_mpi_task_srun.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/functions.py"]}
|
5,473
|
AdamWlodarczyk/jobqueue_features
|
refs/heads/master
|
/jobqueue_features/clusters_controller.py
|
from typing import Tuple, Dict, Callable # noqa
import atexit
from dask.distributed import Client, LocalCluster
from .clusters import ClusterType # noqa
from .custom_exceptions import ClusterException
_DEFAULT = "default"
class ClusterController(object):
"""Controller keeps collection of clusters and clients so it can
provide these for decorators to submitting tasks."""
default_cluster = LocalCluster # type: Callable[..., ClusterType]
def __init__(self):
# type: () -> None
self._clusters = {_DEFAULT: None} # type: Dict[str, ClusterType]
self._clients = {_DEFAULT: None} # type: Dict[str, Client]
atexit.register(self._close)
def get_cluster(self, id_=None):
# type: (str) -> Tuple[ClusterType, Client]
cluster = self._clusters.get(id_ or _DEFAULT)
if cluster is None:
raise ClusterException('No cluster "{}" set!'.format(id_))
client = self._clients.get(id_ or _DEFAULT)
if client is None:
raise ClusterException('No client for cluster "{}" set!'.format(id_))
return cluster, client
def add_cluster(self, id_=None, cluster=None):
# type: (str, ClusterType) -> Tuple[ClusterType, Client]
if hasattr(cluster, "name"):
if id_ is None:
id_ = cluster.name
else:
assert id_ == cluster.name
return self._make_cluster(id_=id_ or _DEFAULT, cluster=cluster)
def delete_cluster(self, id_):
# type: (str) -> None
self._close_client(id_=id_)
self._close_cluster(id_=id_)
def _make_cluster(self, id_, cluster=None):
# type: (str, ClusterType) -> Tuple[ClusterType, Client]
if id_ != _DEFAULT and id_ in self._clusters:
raise ClusterException('Cluster "{}" already exists!'.format(id_))
self._clusters[id_] = cluster or self._make_default_cluster(name=id_)
self._make_client(id_=id_)
return self._clusters[id_], self._clients[id_]
def _make_default_cluster(self, name):
kwargs = {}
if self.default_cluster is not LocalCluster:
kwargs["name"] = name
else:
kwargs["processes"] = False
return self.default_cluster(**kwargs)
def _make_client(self, id_):
# type: (str) -> None
cluster = self._clusters[id_]
if hasattr(cluster, "client"):
client = cluster.client
else:
client = Client(cluster)
self._clients[id_] = client
def _close(self):
# type: () -> None
self._close_clients()
self._close_clusters()
def _close_cluster(self, id_):
# type: (str) -> None
cluster = self._clusters.pop(id_, None)
if cluster and type(cluster) is not LocalCluster:
cluster.close()
def _close_clusters(self):
# type: () -> None
for id_ in list(self._clusters.keys()):
self._close_cluster(id_)
self._clusters = {_DEFAULT: None}
def _close_client(self, id_):
# type: (str) -> None
client = self._clients.get(id_)
if client:
client.close()
def _close_clients(self):
# type: () -> None
for id_ in list(self._clients.keys()):
self._close_client(id_)
self._clients = {_DEFAULT: None}
clusters_controller_singleton = ClusterController()
|
{"/jobqueue_features/functions.py": ["/jobqueue_features/clusters_controller.py"], "/examples/mpi_tasks_srun.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py"], "/jobqueue_features/tests/test_cluster.py": ["/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/clusters_controller.py"], "/examples/mpi_tasks_mpiexec.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/functions.py"], "/jobqueue_features/decorators.py": ["/jobqueue_features/clusters_controller.py", "/jobqueue_features/mpi_wrapper.py"], "/examples/forked_mpi_task_srun.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/functions.py"]}
|
5,474
|
AdamWlodarczyk/jobqueue_features
|
refs/heads/master
|
/examples/forked_mpi_task_srun.py
|
from __future__ import print_function
import os
from dask.distributed import LocalCluster
from jobqueue_features.clusters import CustomSLURMCluster
from jobqueue_features.decorators import on_cluster, mpi_task
from jobqueue_features.mpi_wrapper import mpi_wrap
from jobqueue_features.functions import set_default_cluster
# import logging
# logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
# set_default_cluster(LocalCluster)
set_default_cluster(CustomSLURMCluster)
custom_cluster = CustomSLURMCluster(
name="mpiCluster", walltime="00:04:00", nodes=2, mpi_mode=True, fork_mpi=True
)
@on_cluster(cluster=custom_cluster, cluster_id="mpiCluster")
@mpi_task(cluster_id="mpiCluster")
def mpi_wrap_task(**kwargs):
return mpi_wrap(**kwargs)
# @on_cluster() # LocalCluster
def main():
script_path = os.path.join(os.path.dirname(__file__), "resources", "helloworld.py")
t = mpi_wrap_task(executable="python", exec_args=script_path)
print(t.result()["out"])
print(t.result()["err"])
if __name__ == "__main__":
main()
|
{"/jobqueue_features/functions.py": ["/jobqueue_features/clusters_controller.py"], "/examples/mpi_tasks_srun.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py"], "/jobqueue_features/tests/test_cluster.py": ["/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/clusters_controller.py"], "/examples/mpi_tasks_mpiexec.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/functions.py"], "/jobqueue_features/decorators.py": ["/jobqueue_features/clusters_controller.py", "/jobqueue_features/mpi_wrapper.py"], "/examples/forked_mpi_task_srun.py": ["/jobqueue_features/decorators.py", "/jobqueue_features/mpi_wrapper.py", "/jobqueue_features/functions.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.