def fromComStruc(self, fname): com_node_dict = {} nodeidx_set = set() with open(fname) as ins: for line in ins: node_str, com_idx = line.strip().split() com_idx = int(com_idx) if com_idx not in com_node_dict: com_node_dict[com_idx] = [node_str] else: com_node_dict[com_idx].append(node_str) if len(com_node_dict) == 0: return self._com_list = [None] * (max(com_node_dict.keys())+1) for com_idx, nodestr_list in com_node_dict.items(): com = Community(com_idx) self._com_list[com_idx] = com for node_str in nodestr_list: assert self._hasNodeName(node_str) node_idx, node = self._getNodeIdx(node_str) nodeidx_set.add(node_idx) node.setCom(com_idx) com.addNode(node) for node in self._node_list: if node._id not in nodeidx_set: com = Community(self._com_num) self._com_list.append(com) node.setCom(com._id) com.addNode(node)
def choose_block(): Community.get_all_blocks() street, number = view.get_block_data() block = Community.find_block(street, number) if block: block_controller.block_menu(block) else: view.print_error_message()
def add_new_block(community): street, number = view.get_block_data() if not is_block_exist(street, number): block = Block(street, number) Community.add_blocks(block) community.save_to_file() else: view.print_block_exist()
def __init__(self, master=None): super().__init__(master) self.pack() self.createWidgets() self.selectedFamily = None self.selectedPerson = None self.lastInspected = None self.viewMode = "inspect" self.comparePerson = None self.community = Community() self.updateWidgets()
def __init__(self, deck, players, blindtimer, rules, bigblindonly=False): self.__deck = deck self.__players = players self.__blinds = blindtimer.getblinds() self.__blindtimer = blindtimer self.__pots = [Pot(players, 0)] self.__community = Community() self.__rules = rules self.__bigblindonly = bigblindonly self.__currentplayer = None self.__nextplayeractions = () self.__firsttoact = None self.__lasttoact = None self.__winners = [] self.__round = self.NOT_SET
def initSim(): global MAX_TIME G = nx.DiGraph() available_active = NUM_USERS # number of active users not in a community yet GRAPH_INFORM = False # False if there exists at least one community with an informed person # create sample communities for i in range(NUM_USERS): # if all users have been put in a community, break from graphinitialization if available_active <= 0: break pop = rd.randint(2, COMM_MAX) if i != NUM_USERS else available_active if int(math.log(pop)) > MAX_TIME: MAX_TIME = int(math.log(pop)) available_active -= pop # if available_active <= 0 after updating, this community is the last and must have informed people # determines whether community has an informed person if available_active <= 0 and not GRAPH_INFORM: hasInformed = True else: hasInformed = rd.random() < INFORMED_COMM_RATIO if hasInformed: GRAPH_INFORM = True c = Community(G, i, pop, hasInformed) G.add_node(c) commList = list(G.nodes()) for comm in commList: for otherComm in commList: if comm != otherComm: G.add_edge( comm, otherComm, weight=rd.random()) # weight = probability of impulse sent return G
def overlap_score(self, com1, com2): cmn_node = self.commonNode(com1._id, com2._id) com = Community(-1) for node_idx in cmn_node: com.addNode(self._node_list[node_idx]) node_frac = 1.*com._node_num/min(com1._node_num, com2._node_num) link_frac = 1.*com._ein/min(com1._ein, com2._ein) if min(com1._ein, com2._ein) > 0 else 0 return node_frac+link_frac
def makeGraphFromDict(name, dict): """ Updates this graph to be equal to a dictionary representation of a graph. Essentially a secondary constructor using a dict :param dict: Dictionary representation of a graph :return: Graph object that is equivalent to dict """ graph = Graph(name) communities = [] nodes = [] for nodeID, nodeValues in dict.items(): c = Community(nodeValues[1]) n = Node(nodeID) if n not in nodes: nodes.append(n) for node in nodes: if node == n: n = node for neighborID, arcWeight in nodeValues[0].items(): n2 = Node(neighborID) if n2 not in nodes: nodes.append(n2) for node in nodes: if node == n2: n2 = node e = Edge(n, n2, arcWeight) if e not in graph.getEdges(): graph.addEdge(e) n.addConnection(e) n2.addConnection(e) if c not in communities: communities.append(c) for comm in communities: if c == comm: c = comm c.addMemberNode(n) for node in nodes: graph.addNode(node) for c in communities: graph.addCommunity(c) return graph
def __init__(self, graph): self.graph = graph self.modularity = 0 communities = list() for n in graph.nodes(): graph.node[n]['cid'] = len(communities) community = Community(len(communities), n) communities.append(community) self.communities = communities
def runSim(): time = 0 G = initSim() commList = list(G.nodes()) for time in range(1, MAX_TIME + 1): for comm in commList: comm.informedRatio = comm.calcPopInform(time) / comm.pop if comm.informedRatio > 0: for otherComm in commList: # if the community 'comm' randomly chooses to send an impulse to community 'otherComm' if otherComm != comm and rd.random( ) < Community.getProbImpulse(G, comm, otherComm): comm.updateImpulse(otherComm) Community.updateProbImpulse(G, comm, otherComm) Community.decayProbImpulse(G, comm, otherComm) if isFinished(G): break print("time:", time) return G
def _checkNewCom(self, node_set): if len(node_set) >= COM_MIN_SIZE: new_com = Community(self._com_num) for node_idx in node_set: new_com.addNode(self._node_list[node_idx]) if self._satisComCond(new_com): for node_idx in node_set: self._node_list[node_idx].addCom(new_com._id) self._com_list.append(new_com) return new_com return None
def Test(): f = open("C:/Users/CBD_20/Desktop/community/Community_c++/graph.bin","rb") size = struct.unpack('i', f.read(4)) g = Graph() for i in range(0, size[0]): #print "degree: %d"%(struct.unpack('l', f.read(8))[0]) i print "size: %d"%(size[0]) for i in range(0, size[0]): start = struct.unpack('l', f.read(4)) end = struct.unpack('l', f.read(4)) g.addEdge(i, start[0], end[0], 1) #print "edge: %d -> %d"%(start[0], end[0]) f.close() print "node size:%d"%(g.nodeSize()) comm = Community(g, 0.5, 5, 5) comm.oneLevel() comm.printCommunity()
def _sepSingNode(self, node): ori_com = self._com_list[node._com] if len(ori_com._node) == 1: return new_com = Community(self._com_num) self._com_list.append(new_com) new_com.addNode(node) node.setCom(new_com._id) ori_com.delNode(node._id) if ori_com._empty: self._com_list[ori_com._id] = None
def create_instances_from_data(cls, filename): data = cls.import_from_csv(filename) for row in data: if row[1] == '' and row[2] == '' and row[3] == '': wojewodztwo = Voivodeship(row[4], row[0]) elif row[2] == "" and row[3] == "": powiat = County(row[4], row[1], row[5]) else: gmina = Community(row[4], row[2], row[5], row[1])
def _sepSingComByEdgev2(self, node1_str, node2_str): node1_idx, node1 = self._getNodeIdx(node1_str) node2_idx, node2 = self._getNodeIdx(node2_str) assert node1._com == node2._com, 'Seperate community by inter-edge' com = self._com_list[node1._com] # find 'quasi-clique's and singleton nodes in original community node1_set = set() node2_set = set() onode_set = set() for node_idx, node in com._node.items(): if node_idx == node1_idx or node_idx in node1._nb: if node_idx in node2._nb: onode_set.add(node_idx) else: node1_set.add(node_idx) elif node_idx == node2_idx or node_idx in node2._nb: node2_set.add(node_idx) else: onode_set.add(node_idx) new_com1 = Community(self._com_num) self._com_list.append(new_com1) for node_idx in node2_set: node = self._node_list[node_idx] node.setCom(new_com1._id) new_com1.addNode(node) com.delNode(node._id) for node_idx in onode_set: new_com = Community(self._com_num) self._com_list.append(new_com) node = self._node_list[node_idx] node.setCom(new_com._id) new_com.addNode(node) com.delNode(node._id) # detect best community of singleton nodes in onode_set for node_idx in onode_set: self._detBestCom(self._node_list[node_idx]) # detect best community of 'quasi-clique' in node1_set self._detBestComofNodeSet(node1_set, com._id) # detect best community of 'quasi-clique' in node2_set self._detBestComofNodeSet(node2_set, new_com1._id)
def runCapVsRomTests(self): community = Community() f1 = Family() community.addFamily(f1) with open("data.csv", "w", newline="") as csvFile: writer = csv.writer(csvFile) writer.writerow(["Cap", "Rom"]) for i in range(10000): f1.generatePerson(None, age=80, gender="male") f1.generatePerson(None, age=80, gender="female") val1 = f1.getPerson(0).calculateCap(f1.getPerson(1)) val2 = f1.getPerson(1).calculateCap(f1.getPerson(0)) val3 = f1.getPerson(0).calculateRomanticInterest(f1.getPerson(1)) val4 = f1.getPerson(1).calculateRomanticInterest(f1.getPerson(0)) writer.writerow([val1, val3]) writer.writerow([val2, val4]) f1.removePersonByIndex(1) f1.removePersonByIndex(0)
def _addEdgeAdjustv2(self, node1, node2): if node1._com == node2._com: return deltaq1 = self._delta_q(node1._id, node2._com) deltaq2 = self._delta_q(node2._id, node1._com) com1 = self._com_list[node1._com] com2 = self._com_list[node2._com] if deltaq1 < 0 and deltaq2 < 0: return # elif abs(deltaq1-deltaq2) < 1e-6: elif deltaq1 == deltaq2: new_com = Community(self._com_num) self._com_list.append(new_com) new_com.addNode(node1) new_com.addNode(node2) com1.delNode(node1._id) com2.delNode(node2._id) node1.setCom(new_com._id) node2.setCom(new_com._id) if com1._empty: self._com_list[com1._id] = None else: self._refineCom(node1, com1._id, new_com._id) if com2._empty: self._com_list[com2._id] = None else: self._refineCom(node2, com2._id, new_com._id) else: if deltaq1 < deltaq2: dst_com = com1 src_node = node2 src_com = com2 # elif deltaq2 > 0 and (deltaq1 < 0 or abs(deltaq1) < 1e-6): # elif deltaq1 < deltaq2: elif deltaq2 < deltaq1: dst_com = com2 src_node = node1 src_com = com1 src_com.delNode(src_node._id) dst_com.addNode(src_node) src_node.setCom(dst_com._id) if src_com._empty: self._com_list[src_com._id] = None else: """ for nnode_idx in src_node._nb.keys(): self._detBestCom(self._node_list[nnode_idx]) """ self._refineCom(src_node, src_com._id, dst_com._id)
def main_menu(): csv_path = 'community.csv' community = Community.create_from_csv(csv_path) view.welcome_screen(community.name) user_choice = '' while user_choice != '0': view.print_main_menu() user_choice = view.get_user_input() if user_choice == '1': Community.get_all_blocks() elif user_choice == '2': choose_block() elif user_choice == '3': add_new_block(community) elif user_choice == '4': # TODO find address by owner pass view.print_exit_message()
def _sepSingComByEdgev3(self, node1_str, node2_str): node1_idx, node1 = self._getNodeIdx(node1_str) node2_idx, node2 = self._getNodeIdx(node2_str) assert node1._com == node2._com, 'Seperate community by inter-edge' com = self._com_list[node1._com] node_list = com._node.keys() for node_idx in node_list: new_com = Community(self._com_num) self._com_list.append(new_com) node = self._node_list[node_idx] node.setCom(new_com._id) new_com.addNode(node) com.delNode(node._id) if com._empty: self._com_list[com._id] = None for node_idx in node_list: self._detBestCom(self._node_list[node_idx])
def addNode(self, new_node_str, new_node_w, edge_dict): new_nodeidx, new_node = self._getNodeIdx(new_node_str) new_node.setW(new_node_w) com = Community(self._com_num) self._com_list.append(com) com.addNode(new_node) new_node.setCom(com._id) nnodeidx_list = [] for nnode_str, weight in edge_dict.items(): nnode_idx, nnode = self._getNodeIdx(nnode_str) weight *= new_node_w * nnode._w new_node.addNB(nnode_idx, weight) nnode.addNB(new_node._id, weight) nnodeidx_list.append(nnode_idx) self._m += weight if abs(self._m) < 1e-6: return self._addNodeAdjust(new_node)
def addNode(self, new_node_str, edge_dict): new_nodeidx, new_node = self._getNodeIdx(new_node_str) com = Community(self._com_num) self._com_list.append(com) com.addNode(new_node) new_node.setCom(com._id) nnodeidx_list = [] for nnode_str, weight in edge_dict.items(): nnode_idx, nnode = self._getNodeIdx(nnode_str) new_node.addNB(nnode_idx, weight) nnode.addNB(new_node._id, weight) nnodeidx_list.append(nnode_idx) self._m += weight if abs(self._m) < 1e-6: return for nnode_idx in nnodeidx_list: self._detBestCom(self._node_list[nnode_idx]) self._detBestCom(self._node_list[new_nodeidx])
def addNode(self, new_node_str, new_node_w, edge_dict): assert not self._hasNodeName( new_node_str), 'node %s already exist' % new_node_str new_nodeidx, new_node = self._getNodeIdx(new_node_str) new_node.setW(new_node_w) com = Community(self._com_num) self._com_list.append(com) com.addNode(new_node) new_node.setCom(com._id) nnodeidx_list = [] for nnode_str, weight in edge_dict.items(): nnode_idx, nnode = self._getNodeIdx(nnode_str) # print 'addNode', weight, new_node_w, nnode_w weight *= new_node_w * nnode._w new_node.addNB(nnode_idx, weight) nnode.addNB(new_node._id, weight) nnodeidx_list.append(nnode_idx) self._m += weight if abs(self._m) < 1e-6: return for nnode_idx in nnodeidx_list: self._detBestCom(self._node_list[nnode_idx]) self._detBestCom(self._node_list[new_nodeidx])
def __init__(self, comm_row, comm_column, populations, initial_infections, comm_size=500): # constants self.FPS = 60 self.CONTAGIOUS_RADIUS = 15 self.CONTAGIOUS_RATE = 1 self.LEAST_INFECTED_TIME = 3 self.CURE_RATE = 0.07 self.CURE_RATE_PER_FRAME = 1 - pow(1 - self.CURE_RATE, 1/self.FPS) self.DEAD_RATE = 0.03 self.DEAD_RATE_PER_FRAME = 1 - pow(1 - self.DEAD_RATE, 1/self.FPS) self.SCAN_PER_FRAME = 3 # objects self.comm_row = comm_row self.comm_column = comm_column self.communities = [Community(self, size=comm_size, population=populations[i], initial_infection=initial_infections[i]) for i in range(comm_row*comm_column)] self.hospital = Hospital() # people variable self.people = [] self.data = []
class Application(Frame): def __init__(self, master=None): super().__init__(master) self.pack() self.createWidgets() self.selectedFamily = None self.selectedPerson = None self.lastInspected = None self.viewMode = "inspect" self.comparePerson = None self.community = Community() self.updateWidgets() def createWidgets(self): ''' Creates widgets. Hell awaits you. ''' self.btnFrame = Frame() self.btnFrame.pack(fill=X) self.passTimeBtn = Button(self.btnFrame, text="Pass time", command=self.passTime) self.passTimeBtn.grid(row=0, column=0, sticky=E + W) self.saveBtn = Button(self.btnFrame, text="Save", command=self.save) self.saveBtn.grid(row=0, column=1, sticky=E + W) self.loadBtn = Button(self.btnFrame, text="Load", command=self.load) self.loadBtn.grid(row=0, column=2, sticky=E + W) self.exitBtn = Button(self.btnFrame, text="Exit", command=root.destroy) self.exitBtn.grid(row=0, column=3, sticky=E + W) self.mayorListBtn = Button(self.btnFrame, text="Mayor list", command=self.mayorListWindow) self.mayorListBtn.grid(row=0, column=4, sticky=E + W) self.mayorListBtn = Button(self.btnFrame, text="Library", command=self.libraryWindow) self.mayorListBtn.grid(row=0, column=5, sticky=E + W) self.dateLabel = Label(self.btnFrame, text="") self.dateLabel.grid(row=0, column=6, sticky=E + W, padx=10) self.inspectBtn = Button(self.btnFrame, text="Inspect", command=self.onInspectBtnClick) self.inspectBtn.grid(row=0, column=7, sticky=E + W) self.compareBtn = Button(self.btnFrame, text="Compare", command=self.onCompareBtnClick) self.compareBtn.grid(row=0, column=8, sticky=E + W) self.restFrame = Frame() self.restFrame.pack(fill=X) self.restFrame.grid_columnconfigure(0, minsize=5, weight=0) self.restFrame.grid_columnconfigure(1, minsize=5, weight=0) self.restFrame.grid_columnconfigure(2, minsize=5, weight=1) self.familiesLabel = Label(self.restFrame, text="Families") self.familiesLabel.grid(row=0, column=0, sticky=W) self.familiesList = Listbox(self.restFrame, exportselection=False) self.familiesList.grid(row=1, column=0, sticky=E + W, padx=5) self.familiesList.bind('<<ListboxSelect>>', self.onFamiliesLbChange) self.peopleLabel = Label(self.restFrame, text="People") self.peopleLabel.grid(row=0, column=1, sticky=W) self.peopleList = Listbox(self.restFrame, exportselection=False) self.peopleList.grid(row=1, column=1, sticky=E + W, padx=5) self.peopleList.bind('<<ListboxSelect>>', self.onPeopleLbChange) self.personInfoLabel = Label(self.restFrame, text="Inspector") self.personInfoLabel.grid(row=0, column=2, sticky=W) self.personInfo = Frame(self.restFrame, borderwidth=2, relief=GROOVE) self.personInfo.grid(row=1, column=2, rowspan=3, sticky=N + E + W + S, padx=5) self.personInfoText = Label(self.personInfo, text="", anchor=W, justify=LEFT) self.personInfoText.config(wraplength=350) self.personInfoText.pack(fill=X) self.personEvents = Text(self.personInfo, height=10, state=DISABLED) self.personEvents.pack(fill=X, padx=5, pady=5, side=BOTTOM) self.personEventsLabel = Label(self.personInfo, text="Events") self.personEventsLabel.pack(anchor=W, side=BOTTOM) self.inspectorBtnFrame = Frame(self.personInfo) self.inspectorBtnFrame.pack(anchor=W, side=BOTTOM, padx=5) self.fatherBtn = Button(self.inspectorBtnFrame, text="Father", command=self.blank) self.fatherBtn.grid(row=0, column=0, sticky=W + E) self.fatherBtn.bind('<Button-1>', self.onRelativeButtonClick) self.motherBtn = Button(self.inspectorBtnFrame, text="Mother", command=self.blank) self.motherBtn.grid(row=0, column=1, sticky=W + E) self.motherBtn.bind('<Button-1>', self.onRelativeButtonClick) self.partnerBtn = Button(self.inspectorBtnFrame, text="Partner", command=self.blank) self.partnerBtn.grid(row=0, column=2, sticky=W + E) self.partnerBtn.bind('<Button-1>', self.onRelativeButtonClick) self.familyTreeBtn = Button(self.inspectorBtnFrame, text="Family Tree", command=self.familyTreeWindow) self.familyTreeBtn.grid(row=0, column=3, sticky=W + E) self.eventsLabel = Label(self.restFrame, text="Events") self.eventsLabel.grid(row=2, column=0, sticky=W) self.eventLog = Text(self.restFrame, width=50, height=19, state=DISABLED) self.eventLog.grid(row=3, column=0, columnspan=2, sticky=N + E + W + S, padx=5) def updateWidgets(self): self.dateLabel.config(text=self.community.dateToString()) self.familiesList.delete(0, END) for f in self.community.families: self.familiesList.insert(END, f.familyName) self.familiesList.insert(END, "[Graveyard]") # Set previous selection if self.selectedFamily is not None: self.familiesList.selection_set(self.selectedFamily) self.updatePeopleList() self.updateMainEventLog() self.updateInspectorButtons() if self.viewMode == "inspect": if self.lastInspected == "family": self.inspectFamily() elif self.lastInspected == "person": self.inspectPerson() else: self.personInfoText.config(text="Select a family to begin") elif self.viewMode == "compare": if self.comparePerson is None: self.writeToInspector("Select a person to compare") if self.viewMode == "inspect": self.compareBtn.config(relief=RAISED, state=NORMAL) self.inspectBtn.config(relief=SUNKEN, state=DISABLED) elif self.viewMode == "compare": self.compareBtn.config(relief=SUNKEN, state=DISABLED) self.inspectBtn.config(relief=RAISED, state=NORMAL) def updatePeopleList(self): self.peopleList.delete(0, END) if self.selectedFamily is not None: if self.selectedFamily < len(self.community.families): f = self.community.getFamilyByIndex(self.selectedFamily) for p in f.people: self.peopleList.insert(END, p.firstName()) else: graveyard = self.community.graveyard() for p in graveyard: self.peopleList.insert(END, p.printableFullName()) if self.selectedFamily is not None and self.selectedPerson is not None: self.peopleList.selection_set(self.selectedPerson) def updateInspectorButtons(self): partner = self.partnerBtn father = self.fatherBtn mother = self.motherBtn tree = self.familyTreeBtn partner.config(state=DISABLED) father.config(state=DISABLED) mother.config(state=DISABLED) tree.config(state=DISABLED) if self.selectedPerson is not None: p = self.getSelectedPerson() if p: if p.partner is not None: partner.config(state=NORMAL) if p.father(): father.config(state=NORMAL) if p.mother(): mother.config(state=NORMAL) tree.config(state=NORMAL) def inspectFamily(self): self.lastInspected = "family" if self.selectedFamily < len(self.community.families): f = self.community.getFamilyByIndex(self.selectedFamily) self.writeToInspector(f.inspect()) self.writeInspectorEvents(f.eventLog) else: self.writeToInspector( "== The GRAVEYARD ==\n" + "The graveyard holds the memories of all souls that have passed through the community." ) self.writeInspectorEvents("") def inspectPerson(self): self.lastInspected = "person" if self.selectedPerson is not None: self.updateInspectorButtons() p = self.getSelectedPerson() if p: self.writeToInspector(p.inspect()) self.writeInspectorEvents(p.eventLog) else: self.writeToInspector("Select a family to begin") self.writeInspectorEvents([]) def comparePeople(self): # TODO compare p1 = self.comparePerson p2 = self.getSelectedPerson() self.writeToInspector(p1.compareTo(p2)) def updateMainEventLog(self): self.eventLog.config(state=NORMAL) self.eventLog.delete(1.0, END) for e in self.community.eventLog: self.eventLog.insert(END, e + "\n") self.eventLog.see(END) self.eventLog.config(state=DISABLED) def onFamiliesLbChange(self, evt): if len(self.familiesList.curselection()) > 0: ind = int(self.familiesList.curselection()[0]) self.selectedFamily = ind self.selectedPerson = None self.updatePeopleList() self.updateInspectorButtons() if self.viewMode == "inspect": self.inspectFamily() elif self.viewMode == "compare": None def onPeopleLbChange(self, evt): if len(self.peopleList.curselection()) > 0: ind = int(self.peopleList.curselection()[0]) self.selectedPerson = ind if self.viewMode == "inspect": self.inspectPerson() elif self.viewMode == "compare": self.comparePeople() def onInspectBtnClick(self): self.viewMode = "inspect" self.comparePerson = None self.updateWidgets() def onCompareBtnClick(self): if self.selectedPerson is not None and self.lastInspected == "person": self.viewMode = "compare" self.comparePerson = self.getSelectedPerson() self.writeToInspector("Select a person to compare to {}".format( self.comparePerson.firstName())) self.writeInspectorEvents([]) # clear events panel self.updateWidgets() def onRelativeButtonClick(self, evt): p = self.getSelectedPerson() wgt = evt.widget if p: gyard = self.community.graveyard() if wgt == self.fatherBtn and p.father(): father = p.father() if father in gyard: self.selectedFamily = len(self.community.families) self.selectedPerson = gyard.index(father) else: self.selectedFamily = self.community.families.index( father.family) self.selectedPerson = father.family.people.index(father) elif wgt == self.motherBtn and p.mother(): mother = p.mother() if mother in gyard: self.selectedFamily = len(self.community.families) self.selectedPerson = gyard.index(mother) else: self.selectedFamily = self.community.families.index( mother.family) self.selectedPerson = mother.family.people.index(mother) elif wgt == self.partnerBtn and p.partner is not None: partner = p.partner if partner in gyard: self.selectedFamily = len(self.community.families) self.selectedPerson = gyard.index(partner) else: self.selectedFamily = self.community.families.index( partner.family) self.selectedPerson = partner.family.people.index(partner) self.updateWidgets() def writeToInspector(self, s): self.personInfoText.config(text=s) def writeInspectorEvents(self, events): self.personEvents.config(state=NORMAL) self.personEvents.delete(1.0, END) for e in events: self.personEvents.insert(END, e + "\n") self.personEvents.see(END) self.personEvents.config(state=DISABLED) def getSelectedPerson(self): if self.selectedFamily is not None and self.selectedPerson is not None: if self.selectedFamily < len(self.community.families): f = self.community.getFamilyByIndex(self.selectedFamily) p = f.getPerson(self.selectedPerson) return p else: # graveyard is selected graveyard = self.community.graveyard() if self.selectedPerson < len(graveyard): p = graveyard[self.selectedPerson] return p return False def passTime(self): self.community.passTime() self.updateWidgets() def save(self): cwd = os.path.dirname(os.path.realpath(__file__)) filename = filedialog.asksaveasfilename( initialdir=cwd, title="Select file", filetypes=(("Community save file", "*.cmu"), ("all files", "*.*"))) if filename: with open(filename, "wb") as file: try: pickle.dump(self.community, file) except Exception as e: print("An error occurred: {}".format(e)) def load(self): cwd = os.path.dirname(os.path.realpath(__file__)) filename = filedialog.askopenfilename( initialdir=cwd, title="Select file", filetypes=(("Community save file", "*.cmu"), ("all files", "*.*"))) if filename: with open(filename, "rb") as file: try: tempCom = pickle.load(file) if isinstance(tempCom, Community): self.community = tempCom self.updateWidgets() else: raise Exception( "Could not decode community from save file") except Exception as e: print("An error occurred: {}".format(e)) def familyTreeWindow(self): w = Toplevel(self) w.geometry("600x400") w.resizable(0, 0) w.wm_attributes("-topmost", 1) w.grab_set() w.main = FamilyTree(w, self.getSelectedPerson()) w.main.pack(fill=BOTH) def mayorListWindow(self): w = Toplevel(self) w.geometry("600x600") w.resizable(0, 0) w.wm_attributes("-topmost", 1) w.grab_set() w.main = MayorList(w, community=self.community) w.main.pack(fill=BOTH) def libraryWindow(self): w = Toplevel(self) w.geometry("600x600") w.resizable(0, 0) w.wm_attributes("-topmost", 1) w.grab_set() w.main = Library(w, community=self.community) w.main.pack(fill=BOTH) def blank(self): 'Placeholder function' None
from community import Community import csv my_logger = logging.getLogger('Collibra') i = 0 f = open('community list.txt', 'r+') row = csv.reader(f, delimiter=',') listOfAcceptedCommunities = list() listOfRejecteCommunities = list() for line in row: tempTuple = tuple() i = i + 1 name = line[0].strip() description = line[1].strip() parentName = line[2].strip() if Community.communityFind(name).statusCode == 1: if not parentName or Community.communityFind( parentName).statusCode == 0: c1 = Community(name, desc=description, parent=parentName) c1.postCommunity() c2 = Community.communityFind(name) tempTuple = (name, c2.uri, c2.rid) listOfAcceptedCommunities.append(tempTuple) else: tempTuple = (name, 'No', 'No') listOfRejecteCommunities.append(tempTuple) else: tempTuple = (name, 'Yes', 'NA') listOfRejecteCommunities.append(tempTuple) for iTemp in listOfAcceptedCommunities:
def phaseTwo(graph): """ Consolidates communities toa single supernode, and adds edges to that node based on sum of weights between nodes from those communities. Nodes will have self-edges with a weight equal to the number of edges between nodes in the community as described in the paper. :param graph: A graph object :return: A version of input graph corresponding to phase two of the blondel algorithm. """ newNodes = {} newEdges = set() newCommunities = [] # Create all supernodes, one per community for community in graph.getCommunities(): id = community.getID() node = Node(id) id = community.getID() c = Community(id) c.addMemberNode(node) newNodes[id] = node newCommunities.append(c) # Create all edges between supernodes # Outer for loop will correspond to a supernode for community in graph.getCommunities(): # This dictionary will store communityID as the key (these are same as supernode nodeID) # and a numerical value representing the weight between two supernodes newEdgeDict = {} # This for loop corresponds to the edges between each supernode for node in community.getMemberNodes(): neighborList = node.getNeighborCommunities() # This loop calculates the weight of each new edge for edge in node.getConnections(): otherNode = edge.getOtherNode(node) nCommID = otherNode.getCommunity().getID() if node == otherNode: newEdgeDict[nCommID] = newEdgeDict.get( nCommID, 0) + edge.getWeight() elif nCommID == node.getCommunity().getID(): newEdgeDict[nCommID] = newEdgeDict.get( nCommID, 0) + edge.getWeight() / 2 else: newEdgeDict[nCommID] = newEdgeDict.get( nCommID, 0) + edge.getWeight() for key, weight in newEdgeDict.items(): n1 = newNodes[community.getID()] n2 = newNodes[key] e1 = Edge(n1, n2, weight) e2 = Edge(n2, n1, weight) if e1 not in newEdges and e2 not in newEdges: n1.addConnection(e1) n2.addConnection(e1) newEdges.add(e1) for nodeID, node in newNodes.items(): node.computeSumEdgeWeights() for community in newCommunities: community.computeInCommunityWeight() p2graph = Graph(graph.getName(), nodes=newNodes, edges=newEdges, communities=newCommunities) return p2graph
def run(self): c = Community() f1 = Family(c) f2 = Family(c) c.addFamily(f1) c.addFamily(f2) c.removeFamily(f2) f2 = c.newFamily() f1ByInd = c.getFamilyByIndex(0) p1 = Person([None, None], gender="male", family=f1) p2 = Person([None, None], gender="female", family=f1) p1.partner = p2 p2.partner = p1 p1.marryPartner() f1.addPerson(p1) f1.addPerson(p2) p3 = f1.generatePerson([p1, p2]) p3ByInd = f1.getPerson(2) p1.addChild(p3) p2.addChild(p3) p4 = f1.generatePerson([p1, p2]) f1.removePerson(p4) f1.addPerson(p4) f1.removePersonByIndex(3) p5 = Person([None, None], gender="male", family=f1) p6 = Person([None, None], gender="female", family=f1) p5.partner = p6 p6.partner = p5 p5.updateRapport(p6, -0.5) p5.breakUp() p5.calculateCap(p6) p5.likes(p6) p5.calculateRomanticInterest(p6) p5.romanticallyLikes(p6) p1.isRelative(p3) p1.firstName() p1.surname() p1.printableFullName() p1.setFirstName("test") p1.setSurname("test") p1.regenerateFirstName() p1.rapportStatus(p2) p1.friends() p1.countFriends() p1.getMood() p1.oneWordMood() p1.moodReasons() p1.father() p1.mother() p1.baseMood() p1.addModifier(2) p1.emotionality() p1.politicalOrientation() p1.sociopathy() p1.isChild() p1.getAttr("o") p1.explainCap(p2) p1.ageToString() p1.attributesToString() p1.attributesAsDescription() p1.otherAttributesAsDescription() p1.getLastInteractions(5) p1.compareTo(p2) p1.logKeyEvent("test") p1.inspect() p1.die() c.log("test message") f1.log("test message") allPeople = c.allPeople() c.passTime() c.graveyard()
from community import Community import matplotlib.pyplot as plt import matplotlib.animation as animation POPULATION_SIZE = 100 STARTING_INFECTED = 1 TRANSMISSION_RATE = 0.3 TRANSMISSION_RADIUS = 2 GRID_SIZE = 10 INFECTION_TIME = 14 fig = plt.figure() ax1 = fig.add_subplot(1, 2, 1) ax2 = fig.add_subplot(1, 2, 2) community = Community(POPULATION_SIZE, STARTING_INFECTED, TRANSMISSION_RATE, TRANSMISSION_RADIUS, GRID_SIZE, INFECTION_TIME) def main(): ani = animation.FuncAnimation(fig, simulate, frames=35, repeat=False) # noqa F841 plt.show() def simulate(i): ax1.clear() ax1.stackplot(range(i + 2), [community.counts[key] for key in community.counts], labels=[key for key in community.counts]) ax1.legend() for key in community.counts:
def localTest(): f = open("../Community_latest/graph.bin","rb") size = struct.unpack('i', f.read(4)) g = Graph() for i in range(0, size[0]): #print "degree: %d"%(struct.unpack('l', f.read(8))[0]) i print "size: %d"%(size[0]) for i in range(0, size[0]): start = struct.unpack('l', f.read(8)) end = struct.unpack('l', f.read(8)) g.addEdge(i, start[0], end[0], 1) #print "edge: %d -> %d"%(start[0], end[0]) f.close() print "node size:%d"%(g.nodeSize()) #g.printGraph() comm = Community(g, 0.5, 5, 5) comm.oneLevel() comm.printCommunity() csvReader = csv.reader(file(sys.argv[1],'rb'), csv.excel_tab) i = 0 g = Graph() for line in csvReader: edgeArr = line g.addEdge(i, edgeArr[0], edgeArr[1], 1.0) i+=1 #g.printGraph() comm = Community(g, 0.01, 10, 2) comm.initCommunity() comm.startCluster() #comm.oneLevel() print "cluster size:%d"%(comm.clusterSize()) comm.printCommunity() print "--------------------------------"
class Hand: # poker hand PREFLOP = 0 FLOP = 1 TURN = 2 RIVER = 3 SHOWDOWN = 4 NOT_SET = -1 __STATE_TEXT = { PREFLOP: 'pre-flop', FLOP: 'flop', TURN: 'turn', RIVER: 'river', SHOWDOWN: 'showdown', NOT_SET: 'not set' } def __init__(self, deck, players, blindtimer, rules, bigblindonly=False): self.__deck = deck self.__players = players self.__blinds = blindtimer.getblinds() self.__blindtimer = blindtimer self.__pots = [Pot(players, 0)] self.__community = Community() self.__rules = rules self.__bigblindonly = bigblindonly self.__currentplayer = None self.__nextplayeractions = () self.__firsttoact = None self.__lasttoact = None self.__winners = [] self.__round = self.NOT_SET def __setstate(self, round): self.__round = round self.__currentplayer = None if self.__round > self.PREFLOP: self.__updatepot() for player in self.__players: player.clearbet() if self.__round == self.PREFLOP: if self.__bigblindonly: self.__players[0].bigblind(self.__blinds[1]) else: self.__players[0].smallblind(self.__blinds[0]) self.__players[1].bigblind(self.__blinds[1]) self.__currentbet = self.__blinds[1] else: self.__currentbet = 0 # determine the first to act in each round def __getfirstactor(self): if self.__round == self.PREFLOP: starting_point = 0 # first to act is to the left of big blind for i, player in enumerate(self.__players): if player.isbigblind(): starting_point = i + 1 if starting_point >= len(self.__players): starting_point = 0 break else: # first to act is to the left of the dealer starting_point = 0 player = self.__players[starting_point] player_found = True player_index = starting_point while player.can_act() == False: player_index = player_index + 1 if player_index >= len(self.__players): player_index = 0 if player_index == starting_point: # been round once and back to the start player_found = False break player = self.__players[player_index] if player_found: return player else: return None def __updatepot(self): # No pots? What are you doing here? if len(self.__pots) == 0: return players = self.__pots[-1].getplayers()[:] # Find everyone who's all in allins = [] for player in players: if player.isallin(): allins.append((player.gettotalbet(), player.name(), player)) allins.sort(key=lambda player: player[0]) # Remove the biggest all-in as they're still in if len(allins) > 1 and allins[-1][0] > allins[-2][0]: allins[-1][2].reducebet(allins[-1][0] - allins[-2][0]) allins[-1][2].notallin() self.__pots[-1].subtractvalue(allins[-1][0] - allins[-2][0]) del (allins[-1]) # fill the current pot and create a new side pot/pots last_allin = 0 allin_count = 0 for allin in allins: allin_count = allin_count + 1 if allin[0] > last_allin: # not already processed this all in bet for player in players: if allin[0] > player.gettotalbet(): self.__pots[-1].addvalue(player.gettotalbet()) player.addedtopot(player.gettotalbet()) else: self.__pots[-1].addvalue(allin[0]) player.addedtopot(allin[0]) last_allin = allin[0] players.remove(allin[2]) self.__pots.append(Pot(players, 0)) # fill the main pot or side pot for remaining players for player in players: if player.gettotalbet() == 0: continue self.__pots[-1].addvalue(player.gettotalbet()) player.addedtopot(player.gettotalbet()) def getsmallblind(self): return self.__blinds[0] def getbigblind(self): return self.__blinds[1] def getstate(self): return self.__round def getstatetext(self): return self.__STATE_TEXT[self.__round] def getfirsttoact(self): return self.__firsttoact def getlasttoact(self): return self.__lasttoact def getwinners(self): return self.__winners def nexttobet(self): if self.getstate() == self.SHOWDOWN: return (None, None) if self.playersinhand() <= 1: return (None, None) if self.__nextplayeractions: # make repeat calls idempotent return (self.__currentplayer, self.__nextplayeractions) if self.__currentplayer == None: if self.__firsttoact != None and self.__firsttoact.can_act( ) == True: nextplayer = self.__firsttoact self.__currentplayer = self.__firsttoact else: nextplayer = None self.__currentplayer = None return (None, None) else: first_player = self.__players.index(self.__firsttoact) player_index = self.__players.index(self.__currentplayer) + 1 if player_index >= len(self.__players): player_index = 0 nextplayer = self.__players[player_index] # get the next player to bet while nextplayer.can_act() == False: if player_index == first_player: # gone back around and not found anyone to act nextplayer = None break player_index = player_index + 1 if player_index >= len(self.__players): player_index = 0 nextplayer = self.__players[player_index] if nextplayer == None or nextplayer.isactive( ) == False: # can't find an active player self.__currentplayer = None return (None, None) # been all the way around and back to the start if nextplayer.name() == self.__firsttoact.name(): self.__currentplayer = None self.__nextplayeractions = () return (None, None) # determine the actions allowed if nextplayer.gettotalbet() < self.__currentbet: self.__nextplayeractions = ('bet', 'fold') else: self.__nextplayeractions = ('check', 'bet', 'fold') self.__currentplayer = nextplayer return (nextplayer, self.__nextplayeractions) def currentbet(self): return self.__currentbet def act(self, player, action, amount=0): try: if player == None \ or self.__players.index(player) < 0 \ or player.name() != self.__currentplayer.name(): raise GameException('Player not allowed') # unexpected player except ValueError: raise GameException('Player not allowed') all_in = False if action == 'call': # shortcut call action action = 'bet' amount = self.__currentbet - player.gettotalbet() if amount < 0: raise GameException('Call not allowed') elif action == 'raise': # shortcut raise action if player.gettotalbet() > self.getsmallblind() \ and self.__currentbet > self.getbigblind() \ and self.__currentbet < (2 * self.getbigblind()): raise GameException( "Cannot re-raise as previous bet was not full raise") action = 'bet' amount = amount - player.gettotalbet() if amount <= 0: raise GameException('Negative raise not allowed') elif action == 'all-in': # shortcut all-in action all_in = True action = 'bet' amount = player.getchips() if action not in self.__nextplayeractions: raise GameException('Action not allowed') if action == 'check': pass elif action == 'bet': if amount > player.getchips(): raise GameException("Can't bet more than your stack") newcurrentbet = player.gettotalbet() + amount if newcurrentbet == self.__currentbet: pass # just a call elif amount < self.__blinds[1] and not all_in: raise GameException("Bet minimum is big blind") if newcurrentbet > self.__currentbet: self.__firsttoact = player #re-open the betting if there's a raise player.makebet(amount) if player.gettotalbet() > self.__currentbet: self.__currentbet = player.gettotalbet() if player.getchips() == 0: player.allin() elif action == 'fold': player.fold() else: pass self.__lasttoact = player self.__nextplayeractions = () def getcurrentplayer(self): return self.__currentplayer def getcurrentpotvalue(self): return self.__pots[-1].getvalue() def getpots(self): return self.__pots def getplayers(self): return self.__players def deal(self): for i in range(0, 2): for player in self.__players: player.deal(self.__deck.card()) self.__setstate(self.PREFLOP) self.__firsttoact = self.__getfirstactor() def playersinhand(self): playercount = 0 for player in self.__players: if player.isactive(): playercount = playercount + 1 return playercount def flop(self): if self.__round != self.PREFLOP: raise GameException('Hand not ready for a flop') if self.playersinhand() < 2: raise GameOverException('Hand is won already') for i in range(0, 3): self.__community.addcard(self.__deck.card()) self.__setstate(self.FLOP) self.__firsttoact = self.__getfirstactor() def burnandturn(self): self.__deck.card() # burn one self.__community.addcard(self.__deck.card()) # turn one def turn(self): if self.__round != self.FLOP: raise GameException('Hand not ready for a turn') if self.playersinhand() < 2: raise GameOverException('Hand is won already') self.__setstate(self.TURN) self.burnandturn() self.__firsttoact = self.__getfirstactor() def river(self): if self.__round != self.TURN: raise GameException('Hand not ready for a river') if self.playersinhand() < 2: raise GameOverException('Hand is won already') self.__setstate(self.RIVER) self.burnandturn() self.__firsttoact = self.__getfirstactor() def getcommmunity(self): return self.__community def setcommunity(self, cardlist): self.__community.setcards(cardlist) def showdown(self): self.__setstate(self.SHOWDOWN) for pot in self.__pots: if pot.getvalue() == 0: continue winners = [] for player in pot.getplayers(): if player.isactive() == False: continue player.makehand(self.__community, self.__rules) if winners and player.getplayerhand().getranking( ) > winners[0].getplayerhand().getranking( ): # pick the biggest ranking winners = [player] elif winners and player.getplayerhand().getranking( ) < winners[0].getplayerhand().getranking(): pass else: winners.append(player) if len(winners) > 1: # equal rank, look for high card dedup = [] i = 0 highvalue = 0 # look at each card in the hand to work out who has highest kicker while i < 5: for winner in winners: cards = winner.getplayerhand().gethand() if cards[i].points() > highvalue: dedup = [] dedup.append(winner) highvalue = cards[i].points() elif cards[i].points() == highvalue: dedup.append(winner) winners = dedup[:] if len(winners) == 1: break dedup = [] highvalue = 0 i = i + 1 pot.setwinners(winners) self.__paywinners() self.__winners = [] for pot in self.__pots: self.__winners = self.__winners + pot.getwinners() return self.__winners def __paywinners(self): for pot in self.__pots[:]: if pot.getvalue() <= 0: self.__pots.remove(pot) for pot in self.__pots: if len(pot.getwinners()) == 0: continue the_pot = pot.getvalue() while the_pot > 0: for winner in pot.getwinners(): pot.payout(winner.name(), 1) winner.addchips(1) the_pot = the_pot - 1 if the_pot < 1: break
def is_block_exist(street, number): if Community.find_block(street, number): return True else: return False
g = Graph() for i in range(0, size[0]): #print "degree: %d"%(struct.unpack('l', f.read(8))[0]) i print "size: %d"%(size[0]) for i in range(0, size[0]): start = struct.unpack('l', f.read(4)) end = struct.unpack('l', f.read(4)) g.addEdge(i, start[0], end[0], 1) #print "edge: %d -> %d"%(start[0], end[0]) f.close() print "node size:%d"%(g.nodeSize()) comm = Community(g, 0.5, 5, 5) comm.oneLevel() comm.printCommunity() if (__name__ == "__main__"): csvReader = csv.reader(file(sys.argv[1],'rb'), csv.excel_tab) i = 0 g = Graph() for line in csvReader: edgeArr = line g.addEdge(i, edgeArr[0], edgeArr[1], 1.0) i+=1 comm = Community(g, 0.01, 10, 3) comm.startCluster()