def loadFromFiles(self, reactions_file, metabs_file, matrix_file): reaction_ids, reactions = read_file_rm(reactions_file) metab_ids, _ = read_file_rm(metabs_file) matrix = read_file_mat(matrix_file) gmr = MyGraph() for metab in metab_ids: gmr.add_node(metab) for reaction in reaction_ids: gmr.add_node(reaction) for index_metabolite, index_reaction, coeficient_value in matrix: metab_id = metab_ids[index_metabolite] reaction_id = reaction_ids[index_reaction] reaction_rev = reactions[reaction_id][0] if coeficient_value > 0 or reaction_rev < 0: gmr.add_edge(reaction_id, metab_id) if coeficient_value < 0 or reaction_rev < 0: gmr.add_edge(metab_id, reaction_id) if self.net_type == 'metabolite-reaction': self.g = gmr.g else: self.g = {}
def __init__(self, frags, reps=True): MyGraph.__init__(self, {}) if reps: self.create_overlap_graph_with_reps(frags) else: self.create_overlap_graph(frags) self.reps = reps
def teste8():### reac-comp dic_reac=teste6() gr=MyGraph() for k, v in dic_reac.items(): for r, m in dic_reac.items(): if v[len(v)-2] == "->": if v[len(v)-1]==m[0]: sv="".join(v) sm="".join(m) gr.addEdge(k, sv) gr.addEdge(sv, r) gr.addEdge(r, sm) else: s=str(v[len(v)-3])+"+"+str(v[len(v)-1]) try: s2=str(m[0])+"+"+str(m[2]) if s == s2: sv="".join(v) sm="".join(m) gr.addEdge(k, sv) gr.addEdge(sv, r) gr.addEdge(r, sm) except IndexError: pass return gr.printGraph()
def __init__(self, network_type = "metabolite-reaction", split_rev = False): #split_rev diz se apresenta reações reversiveis ou não MyGraph.__init__(self, {}) self.net_type = network_type #pode ser metabolite reaction, metabolitee reaction self.node_types = {} if network_type == "metabolite-reaction": # se for metabolite reaction vou ter nodes de metabolite e de reaction no grafo self.node_types["metabolite"] = [] self.node_types["reaction"] = [] self.split_rev = split_rev
def __init__(self, network_type="metabolite-reaction", split_rev=False): MyGraph.__init__(self, {}) self.net_type = network_type self.node_types = {} if network_type == "metabolite-reaction": self.node_types["metabolite"] = [] self.node_types["reaction"] = [] self.split_rev = split_rev
def create_graph (seqs, dist_cut): '''Construction of the graph considering the sequences preveously selected''' sm = SubstMatrix() sm.read_submat_file("blosum62.mat", "\t") alseq = PairwiseAlignment(sm, -8) up = UPGMA(seqs, alseq) graph=MyGraph() for i in range(up.matdist.num_rows()): for j in range(0,i): if up.matdist[i][j] < dist_cut: graph.add_edge(i,j) graph.add_edge(j,i) return graph
def __init__(self, network_type="metabolite-reaction", split_rev=False): #split_rev-> indica se as reações são ou não reversíveis, isto é, se nos mostra as reações reversiveis através do grafo #Indica se se consideram as reações reversíveis como duas reações distintas, uma para cada direção (True) ou não (False) #Tipo de rede-> é o que lhe passarmos MyGraph.__init__( self, {} ) #Construtor da classe MyGraph - cria o self.graph (podia pôr-se self.graph = {}) self.net_type = network_type #Tipo de rede self.node_types = {} #Tipos de nós if network_type == "metabolite-reaction": self.node_types["metabolite"] = [] #Tipo de nó - metabolitos self.node_types["reaction"] = [] #Tipo de nó - reações self.split_rev = split_rev #flag
def __init__(self): super().__init__() self.class_1_construction = MyClassConstructor(self, 100, 200, 'color: blue', 1) self.class_0_construction = MyClassConstructor(self, 100, 100, 'color: red', 0) self.graph = MyGraph(self) self.graph_button = QPushButton('Create graph', self) self.Heavside_Button = CustomButton(self, "Heavside", 0) self.Sigmoid_Button = CustomButton(self, "Sigmoid", 1) self.ReLu_Button = CustomButton(self, "ReLu", 2) self.leaky_ReLu_Button = CustomButton(self, "leaky_ReLu", 3) self.current_button = self.Heavside_Button self.init_ui()
def perg1(metab,reac,bounds,mat): print("\nPergunta 1\n") gmr = MyGraph({}) for m in metab: gmr.add_node(m) for r in reac: gmr.add_node(r) for e in mat: met_index = int(e[0]) met_id = metab[met_index] reac_index = int(e[1]) reac_id = reac[reac_index] reac_rev = float(bounds[reac_id][0]) sign = float(e[2]) if sign > 0 or reac_rev < 0: gmr.add_edge(reac_id,met_id) if sign < 0 or reac_rev < 0: gmr.add_edge(met_id, reac_id) print("\nGrafo concluído\n--------------------------") return gmr
def __init__(self, network_type="metabolite-reaction", split_rev=False): #split_rev-> diz se representa reações reversiveis ou não, ou seja, se nos mostra as reações reversiveis atraves do grafo #indica se se consideram as reações reversíveis como duas reações distintas, uma para cada direção (True) ou não (False) #Tipo de rede-> é o que lhe passarmos MyGraph.__init__( self, {} ) #chamar o construtor da classe MyGraph (classe maior) -> estamos a chama-lo com o dicionario vazio para construir o grafo self.net_type = network_type #tipo de rede: “metabolite-reaction”, “reaction”, “metabolite” self.node_types = { } ##guarda dicionário indicando listas de nós de cada tipo (no caso de ser uma rede “metabolite-reaction” – grafo bipartido) if network_type == "metabolite-reaction": #se for do tipo metabolito-reacao self.node_types["metabolite"] = [ ] #estou a dizer que tenho nós deste tipo dentro da network self.node_types["reaction"] = [ ] #estou a dizer que tenho nós deste tipo dentro da network self.split_rev = split_rev
def get_orthology_graph( t,seedname,phyid ): """Return graph representing orthology relationships from the tree.""" #get evol_events evolEvents,seednode=get_evolEvents( t,phyid,seedname ) if not evolEvents: return #create orthologs graph ortho_graph=MyGraph( t.get_leaf_names() ) #non-directed graph #populate it with orthologs for e in filter( lambda x: x.etype=='S',evolEvents ): #seednode.get_my_evol_events() ): for o1 in e.out_seqs: for o2 in e.in_seqs: ortho_graph.add_line( o1,o2 ) return ortho_graph
def get_orthology_graph(t, seedname, phyid): """Return graph representing orthology relationships from the tree.""" #get evol_events evolEvents, seednode = get_evolEvents(t, phyid, seedname) if not evolEvents: return #create orthologs graph ortho_graph = MyGraph(t.get_leaf_names()) #non-directed graph #populate it with orthologs for e in filter(lambda x: x.etype == 'S', evolEvents): #seednode.get_my_evol_events() ): for o1 in e.out_seqs: for o2 in e.in_seqs: ortho_graph.add_line(o1, o2) return ortho_graph
def populate_orthology_graph( t,seedname,phyid,species_list ): #get seed orthologs orthologs=get_orthologs( t,seedname,phyid,species_list ) if not orthologs: return [],None #create orthologs graph ortho_graph=MyGraph( orthologs ) #non-directed graph #populate it with orthologs for orth in orthologs: if orth==seedname: continue ortho_graph.add_line( seedname, orth ) #mark all orthologs of given ortholog in the graph for orth_in in get_orthologs( t,orth,phyid,species_list ): if orth_in in orthologs: ortho_graph.add_line( orth, orth_in ) return orthologs,ortho_graph
def teste3(): dic_reac=teste2() gr=MyGraph() for reac in dic_reac: comp=dic_reac[reac] c=0 if comp[c+1]=="+": try: comp[c+5]=="+" s2=str(comp[c+4])+"+"+str(comp[c+6]) s3=str(comp[c])+"+"+str(comp[c+2]) gr.addEdge(s3,s2) except IndexError: s=str(comp[c])+"+"+str(comp[c+2]) gr.addEdge(s,comp[c+4]) elif comp[c+1]=="->": try: comp[c+3]=="+" s=str(comp[c+2])+"+"+str(comp[c+4]) gr.addEdge(comp[c],s) except IndexError: gr.addEdge(comp[c],comp[c+2]) return gr.printGraph()
def teste7():### reac-reac dic_reac=teste6() gr=MyGraph() for k, v in dic_reac.items(): for r, m in dic_reac.items(): if v[len(v)-2] == "->": if v[len(v)-1]==m[0]: gr.addEdge(k, r) else: s=str(v[len(v)-3])+"+"+str(v[len(v)-1]) try: s2=str(m[0])+"+"+str(m[2]) if s == s2: gr.addEdge(k, r) except IndexError: pass return gr.printGraph()
def graphGenerate(self): try: numbersOfTop = int(self.numbersOfTopInput.text()) valueOfArc = int(self.valueOfArcInput.text()) myGraph = MyGraph() myGraph.addRandomTopsAndArcs(numbersOfTop, valueOfArc) current_milli_time = lambda: int(round(time.time() * 1000)) timeOd = current_milli_time() path = myGraph.hamiltonCycle() timeDo = current_milli_time() time1 = (timeDo - timeOd) * 0.001 timeOd = current_milli_time() pathP = myGraph.hamiltonCycleAllPath( ) #aby wyłączyć algorytm dokładny zakomentować linijkę timeDo = current_milli_time() time2 = (timeDo - timeOd) * 0.001 self.neighborhoodList.setText("<b>Lista sąsiedztwa:</b> <br>%s" % myGraph) self.cycleP.setText( "<b>Wartość cyklu (dokładny):</b> %d<br>%s" % (pathP.getValue(), pathP)) #aby wyłączyć algorytm dokładny zakomentować linijkę self.cycle.setText("<b>Wartość cyklu:</b> %d<br>%s" % (path.getValue(), path)) self.timeP.setText("<b>Czas dokładny:</b> %s [s]" % time2) self.time.setText("<b>Czas:</b> %s [s]" % time1) graphPlot = GraphPlot() graphPlot.drawGraphPlot( myGraph, pathP) #aby wyłączyć algorytm dokładny zakomentować linijkę #graphPlot.drawGraphPlot(myGraph, path) #aby wyłączyć algorytm dokładny ODKOMENTOWAć linijkę self.close() except ValueError: QMessageBox.warning(self, "Błąd", "Błędne dane", QMessageBox.Ok)
def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(1600, 900) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.centralwidget) self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.lay_left = QtWidgets.QVBoxLayout() self.lay_left.setObjectName("lay_left") self.PdTable = QtWidgets.QTableWidget(self.centralwidget) self.PdTable.setObjectName("PdTable") self.PdTable.setColumnCount(0) self.PdTable.setRowCount(0) self.lay_left.addWidget(self.PdTable) self.lay_left_descr = QtWidgets.QHBoxLayout() self.lay_left_descr.setObjectName("lay_left_descr") self.lay_labels_spins = QtWidgets.QVBoxLayout() self.lay_labels_spins.setObjectName("lay_labels_spins") self.lay_T = QtWidgets.QHBoxLayout() self.lay_T.setObjectName("lay_T") self.label_T = QtWidgets.QLabel(self.centralwidget) self.label_T.setObjectName("label_T") self.lay_T.addWidget(self.label_T) self.doubleSpinBox_T = QtWidgets.QDoubleSpinBox(self.centralwidget) self.doubleSpinBox_T.setObjectName("doubleSpinBox_T") self.lay_T.addWidget(self.doubleSpinBox_T) self.lay_labels_spins.addLayout(self.lay_T) self.lay_n = QtWidgets.QHBoxLayout() self.lay_n.setObjectName("lay_n") self.label_n = QtWidgets.QLabel(self.centralwidget) self.label_n.setObjectName("label_n") self.lay_n.addWidget(self.label_n) self.spinBox_n = QtWidgets.QSpinBox(self.centralwidget) self.spinBox_n.setObjectName("spinBox_n") self.lay_n.addWidget(self.spinBox_n) self.lay_labels_spins.addLayout(self.lay_n) self.lay_m = QtWidgets.QHBoxLayout() self.lay_m.setObjectName("lay_m") self.label_m = QtWidgets.QLabel(self.centralwidget) self.label_m.setObjectName("label_m") self.lay_m.addWidget(self.label_m) self.spinBox_m = QtWidgets.QSpinBox(self.centralwidget) self.spinBox_m.setObjectName("spinBox_m") self.lay_m.addWidget(self.spinBox_m) self.lay_labels_spins.addLayout(self.lay_m) self.lay_left_descr.addLayout(self.lay_labels_spins) self.lay_left.addLayout(self.lay_left_descr) self.horizontalLayout_2.addLayout(self.lay_left) self.lay_right = QtWidgets.QVBoxLayout() self.lay_right.setObjectName("lay_right") self.MplGraph = MyGraph(self.centralwidget) self.MplGraph.setObjectName("MplGraph") self.lay_right.addWidget(self.MplGraph) self.lay_buttons = QtWidgets.QHBoxLayout() self.lay_buttons.setObjectName("lay_buttons") self.checkBox_lays = QtWidgets.QCheckBox(self.centralwidget) self.checkBox_lays.setObjectName("checkBox_lays") self.lay_buttons.addWidget(self.checkBox_lays) self.pushButton_task = QtWidgets.QPushButton(self.centralwidget) self.pushButton_task.setObjectName("pushButton_task") self.lay_buttons.addWidget(self.pushButton_task) self.pushButton_descr = QtWidgets.QPushButton(self.centralwidget) self.pushButton_descr.setObjectName("pushButton_descr") self.lay_buttons.addWidget(self.pushButton_descr) self.lay_right.addLayout(self.lay_buttons) self.horizontalLayout_2.addLayout(self.lay_right) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 1600, 21)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow)
def __init__(self, networktype='metabolite-reaction', graph={}): MyGraph.__init__(self, graph) self.net_type = networktype
#Date: 11/11/2016 #Class: CS4310 #Assignment: Assignment 7 #Author(s): Alex Dekau from MyGraph import MyGraph graph = MyGraph() # Verticies graph.new_vertex("A") #0 graph.new_vertex("B") #1 graph.new_vertex("C") #2 #Edges-Undirected graph.new_edge(0, 1) #0 graph.new_edge(0, 1, True) #1 graph.new_edge(1, 2) #2 graph.new_edge(2, 1, True) #3 graph.new_edge(2, 2) #4 print "Memory Addresses" print graph.list_vertices() print "A Adjacency" print graph.vertex(0).aV print "B Adjacency" print graph.vertex(1).aV print "C Adjacency" print graph.vertex(2).aV
def __init__(self, frags): MyGraph.__init__(self, {}) self.create_deBruijn_graph(frags)
#Date: 11/11/2016 #Class: CS4310 #Assignment: Assignment 7 #Author(s): Alex Dekau from MyGraph import MyGraph graph = MyGraph() # Verticies graph.new_vertex("A") #0 graph.new_vertex("B") #1 graph.new_vertex("C") #2 #Edges-Undirected graph.new_edge(0, 1) #0 graph.new_edge(0, 1, True) #1 graph.new_edge(1, 2) #2 graph.new_edge(2, 1, True) #3 graph.new_edge(2, 2) #4 print "Vertex A incoming" print graph.V[0].Ei print "Vertex A outgoing" print graph.V[0].Eo print "Vertex B incoming" print graph.V[1].Ei print "Vertex B outgoing" print graph.V[1].Eo print "Vertex C incoming" print graph.V[2].Ei
def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(1600, 750) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget) self.horizontalLayout.setObjectName("horizontalLayout") self.vlayout_left = QtWidgets.QVBoxLayout() self.vlayout_left.setObjectName("vlayout_left") self.PdTable = QtWidgets.QTableWidget(self.centralwidget) self.PdTable.setObjectName("PdTable") self.PdTable.setColumnCount(0) self.PdTable.setRowCount(0) self.vlayout_left.addWidget(self.PdTable) self.hlayout_params = QtWidgets.QHBoxLayout() self.hlayout_params.setObjectName("hlayout_params") self.hlayout_n = QtWidgets.QHBoxLayout() self.hlayout_n.setObjectName("hlayout_n") self.label_n = QtWidgets.QLabel(self.centralwidget) self.label_n.setObjectName("label_n") self.hlayout_n.addWidget(self.label_n) self.spinBox_n = QtWidgets.QSpinBox(self.centralwidget) self.spinBox_n.setObjectName("spinBox_n") self.hlayout_n.addWidget(self.spinBox_n) self.hlayout_params.addLayout(self.hlayout_n) self.hlayout_h = QtWidgets.QHBoxLayout() self.hlayout_h.setObjectName("hlayout_h") self.label_h = QtWidgets.QLabel(self.centralwidget) self.label_h.setObjectName("label_h") self.hlayout_h.addWidget(self.label_h) self.doubleSpinBox_h = QtWidgets.QDoubleSpinBox(self.centralwidget) self.doubleSpinBox_h.setObjectName("doubleSpinBox_h") self.hlayout_h.addWidget(self.doubleSpinBox_h) self.hlayout_params.addLayout(self.hlayout_h) self.hlayout_eps = QtWidgets.QHBoxLayout() self.hlayout_eps.setObjectName("hlayout_eps") self.label_eps = QtWidgets.QLabel(self.centralwidget) self.label_eps.setObjectName("label_eps") self.hlayout_eps.addWidget(self.label_eps) self.doubleSpinBox_eps = QtWidgets.QDoubleSpinBox(self.centralwidget) self.doubleSpinBox_eps.setObjectName("doubleSpinBox_eps") self.hlayout_eps.addWidget(self.doubleSpinBox_eps) self.hlayout_params.addLayout(self.hlayout_eps) self.vlayout_left.addLayout(self.hlayout_params) self.hlayout_but = QtWidgets.QHBoxLayout() self.hlayout_but.setObjectName("hlayout_but") self.button_numeric = QtWidgets.QPushButton(self.centralwidget) self.button_numeric.setObjectName("button_numeric") self.hlayout_but.addWidget(self.button_numeric) self.button_eps = QtWidgets.QPushButton(self.centralwidget) self.button_eps.setObjectName("button_eps") self.hlayout_but.addWidget(self.button_eps) self.button_exact = QtWidgets.QPushButton(self.centralwidget) self.button_exact.setObjectName("button_exact") self.hlayout_but.addWidget(self.button_exact) self.button_numeric_exact = QtWidgets.QPushButton(self.centralwidget) self.button_numeric_exact.setObjectName("button_numeric_exact") self.hlayout_but.addWidget(self.button_numeric_exact) self.vlayout_left.addLayout(self.hlayout_but) self.horizontalLayout.addLayout(self.vlayout_left) self.vlayout_right = QtWidgets.QVBoxLayout() self.vlayout_right.setObjectName("vlayout_right") self.verticalLayout_ = QtWidgets.QVBoxLayout() self.verticalLayout_.setObjectName("verticalLayout_") self.MplGraph = MyGraph(self.centralwidget) self.MplGraph.setObjectName("MplGraph") self.verticalLayout_.addWidget(self.MplGraph) self.vlayout_right.addLayout(self.verticalLayout_) self.lay_r = QtWidgets.QVBoxLayout() self.lay_r.setObjectName("lay_r") self.lay_rr = QtWidgets.QHBoxLayout() self.lay_rr.setObjectName("lay_rr") self.button_descr = QtWidgets.QPushButton(self.centralwidget) self.button_descr.setObjectName("button_descr") self.lay_rr.addWidget(self.button_descr) self.checkBox_lp = QtWidgets.QCheckBox(self.centralwidget) self.checkBox_lp.setObjectName("checkBox_lp") self.lay_rr.addWidget(self.checkBox_lp) self.lay_r.addLayout(self.lay_rr) self.hlayout_res = QtWidgets.QHBoxLayout() self.hlayout_res.setObjectName("hlayout_res") self.label_nres = QtWidgets.QLabel(self.centralwidget) self.label_nres.setObjectName("label_nres") self.hlayout_res.addWidget(self.label_nres) self.label_u0 = QtWidgets.QLabel(self.centralwidget) self.label_u0.setObjectName("label_u0") self.hlayout_res.addWidget(self.label_u0) self.label_hres = QtWidgets.QLabel(self.centralwidget) self.label_hres.setObjectName("label_hres") self.hlayout_res.addWidget(self.label_hres) self.lay_r.addLayout(self.hlayout_res) self.vlayout_right.addLayout(self.lay_r) self.horizontalLayout.addLayout(self.vlayout_right) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 1600, 21)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow)
#Date: 11/11/2016 #Class: CS4310 #Assignment: Assignment 7 #Author(s): Alex Dekau from MyGraph import MyGraph graph = MyGraph() # Verticies graph.new_vertex("A") #0 graph.new_vertex("B") #1 graph.new_vertex("C") #2 #Edges-Undirected graph.new_edge(0, 1) #0 graph.new_edge(0, 1, True) #1 graph.new_edge(1, 2) #2 graph.new_edge(2, 1, True) #3 graph.new_edge(2, 2) #4 print "Is 1 directed? (true)" print graph.is_directed(1) print "Is 2 directed? (false)" print graph.is_directed(2) print "In degree A (1)" print graph.in_degree(0) print "In degree B (4)" print graph.in_degree(1) print "In degree C (2)"
#Date: 11/11/2016 #Class: CS4310 #Assignment: Assignment 7 #Author(s): Alex Dekau from MyGraph import MyGraph graph = MyGraph("Assignment 7") HNL = graph.new_vertex("HNL") LAX = graph.new_vertex("LAX") SFO = graph.new_vertex("SFO") ORD = graph.new_vertex("ORD") DFW = graph.new_vertex("DFW") LGA = graph.new_vertex("LGA") PVD = graph.new_vertex("PVD") MIA = graph.new_vertex("MIA") HNL_LAX = graph.new_edge(HNL, LAX, value=2555) LAX_SFO = graph.new_edge(LAX, SFO, value=337) LAX_DFW = graph.new_edge(LAX, DFW, value=1233) LAX_ORD = graph.new_edge(LAX, ORD, True, value=1743) SFO_ORD = graph.new_edge(SFO, ORD, value=1843) ORD_PVD = graph.new_edge(ORD, PVD, value=849) ORD_DFW = graph.new_edge(ORD, DFW, value=802) DFW_LGA = graph.new_edge(DFW, LGA, value=1387) DFW_MIA = graph.new_edge(DFW, MIA, value=1120) LGA_MIA = graph.new_edge(LGA, MIA, value=1099) PVD_LGA = graph.new_edge(PVD, LGA, True, value=142) PVD_MIA = graph.new_edge(PVD, MIA, value=1205)
def __init__(self, frags): MyGraph.__init__(self, {}) self.create_overlap_graph(frags)
def __init__(self, modules, organism="hsa"): MyGraph.__init__(self,{}) self.gr=MyGraph() self.modules=modules self.s = KEGG() self.s.organism = organism # H**o sapiens as default
def updateHashtagGraph(timeStamp, hashTags, tweetGraph, tweetsIn60Sec, timeStampIn60Sec, maxTimeStamp): """ This function updates hashtag graph with new tweets. A hashtag graph contains hashtags from tweets within last 60 seconds. Any tweet before 60 seconds is purged. There are following conditions that need to be checked before the graph is updated: 1. If incoming tweet appears in order of time. 2. If incoming tweet is out of order of time. :param timeStamp: timestamp of incoming tweet :param hashTags: list of hashtags in incoming tweet :param tweetGraph: dictionary of hashtags and number of tweets that formed the edges between hashtags :param tweetsIn60Sec: dictionary of tweets in 60 seconds window with timestamp as key :param timeStampIn60Sec: list of timestamps in 60 seconds window :param maxTimeStamp: timestamp of latest tweet :return: tweetGraph - updated graph with edges representing tweets within 60seconds tweetsIn60Sec - updated dictionary of tweets in 60 seconds window timeStampIn60Sec - updated list of timestamps in 60 seconds window maxTimeStamp - timestamp of latest tweet. """ graph = MyGraph(tweetGraph) # create Graph object # Step 1: check incoming tweet: # ------------------------------ # Condition 1: If tweet arrives in Order if timeStamp >= maxTimeStamp: # Check if new timeStamp is already in list - timeStampIn60Sec if timeStamp != maxTimeStamp: # append if not in 60 second list timeStampIn60Sec.append(timeStamp) # update maxTimeStamp maxTimeStamp = timeStamp # If timestamp already in tweets60Sec. if timeStamp in tweetsIn60Sec: # append incoming hashtags at given time tweetsIn60Sec[timeStamp].append(hashTags) else: # add the new hashtag at given time tweetsIn60Sec[timeStamp] = [hashTags] # Update the Hashtag graph: # Step 2: Add edge to tweetGraph only if there are 2 or more hashtags # ----------------------------------------------------------------------- if len(hashTags) > 2: tweetGraph = addGraphEdge(hashTags, tweetGraph) # Step 3: Delete edge from tweetGraph for tweets that are more than 60 seconds old. # ------------------------------------------------------------------------------------- while maxTimeStamp - timeStampIn60Sec[0] > 60: tweetGraph = deleteGraphEdge(hashTags=hashTags, tweetGraph=tweetGraph, timeStampIn60Sec=timeStampIn60Sec, tweetsIn60Sec=tweetsIn60Sec) tweetsIn60Sec.pop(timeStampIn60Sec[0]) timeStampIn60Sec.pop(0) # Condition 2: If tweet does not arrive in order: else: # Check if the tweet is in last 60 Seconds if maxTimeStamp - timeStamp <= 60: # Check if timestamp is in list of timestamps if timeStamp not in timeStampIn60Sec: timeStampIn60Sec.append(timeStamp) # Check if timeStamp already in tweet60Sec if timeStamp in tweetsIn60Sec: tweetsIn60Sec[timeStamp].append(hashTags) else: tweetsIn60Sec[timeStamp] = [hashTags] # Update the Hashtag graph: # Step 2: Add edge to tweetGraph only if there are 2 or more hashtags if len(hashTags) > 2: tweetGraph = addGraphEdge(hashTags, tweetGraph) # Check if the tweet is older than 60 Seconds - Do Nothing else: pass return tweetGraph, sorted(timeStampIn60Sec), tweetsIn60Sec, maxTimeStamp
def encodeData(sess, model, data_fetcher, graphs, placeholders, use_emb, use_code, inverted_index, id2emb, id2code): encode_batchsize = FLAGS.ecd_batchsize total_graph_num = len(graphs) thres = np.zeros(FLAGS.hash_code_len) all_codes = [] all_embs = [] for i in range(0, total_graph_num, encode_batchsize): end = i + encode_batchsize if end > total_graph_num: end = total_graph_num idx_list = list(range(i, end)) # padding to fit placeholders' shapes while (len(idx_list) < encode_batchsize): idx_list.append(0) # Create wrapper graphs wrp_graphs = [] for j in idx_list: mg = MyGraph(graphs[j], data_fetcher.max_label) wrp_graphs.append(mg) features = sp.vstack([g.sparse_node_inputs for g in wrp_graphs]) features = data_fetcher._sparse_to_tuple(features) laplacians = sp.block_diag([g.laplacian for g in wrp_graphs]) laplacians = data_fetcher._sparse_to_tuple(laplacians) sizes = [g.nxgraph.number_of_nodes() for g in wrp_graphs] data_fetcher.batch_node_num = sum(sizes) feed_dict = dict() #nfn = data_fetcher.get_node_feature_dim() feed_dict.update({placeholders['dropout']: 0}) feed_dict.update({placeholders['features']: features}) feed_dict.update({placeholders['support']: laplacians}) # feed_dict.update({placeholders['num_features_nonzero']: [data_fetcher.batch_node_num]}) feed_dict.update({placeholders['graph_sizes']: sizes}) feed_dict.update({placeholders['thres']: thres}) if use_code and use_emb: codes, embs = sess.run([model.codes, model.ecd_embeddings], feed_dict=feed_dict) codes = list(codes) codes = codes[0:end - i] all_codes = all_codes + codes embs = list(embs) embs = embs[0:end - i] all_embs = all_embs + embs elif use_code and use_emb == False: codes = sess.run(model.codes, feed_dict=feed_dict) codes = list(codes) codes = codes[0:end - i] all_codes = all_codes + codes all_embs = all_codes elif use_code == False and use_emb: embs = sess.run(model.ecd_embeddings, feed_dict=feed_dict) embs = list(embs) embs = embs[0:end - i] all_embs = all_embs + embs all_codes = all_embs else: raise RuntimeError('use_code and use_emb cannot both be False') for i, pair in enumerate(zip(all_codes, all_embs)): code = pair[0] emb = pair[1] tuple_code = tuple(code) gid = graphs[i].graph['gid'] if use_emb and use_code: inverted_index.setdefault(tuple_code, []) inverted_index[tuple_code].append((gid, emb)) if use_code and use_emb == False: inverted_index.setdefault(tuple_code, []) inverted_index[tuple_code].append((gid, None)) if use_emb: id2emb[gid] = emb if use_code: id2code[gid] = code
class MainWindow(QWidget): def __init__(self): super().__init__() self.class_1_construction = MyClassConstructor(self, 100, 200, 'color: blue', 1) self.class_0_construction = MyClassConstructor(self, 100, 100, 'color: red', 0) self.graph = MyGraph(self) self.graph_button = QPushButton('Create graph', self) self.Heavside_Button = CustomButton(self, "Heavside", 0) self.Sigmoid_Button = CustomButton(self, "Sigmoid", 1) self.ReLu_Button = CustomButton(self, "ReLu", 2) self.leaky_ReLu_Button = CustomButton(self, "leaky_ReLu", 3) self.current_button = self.Heavside_Button self.init_ui() def init_ui(self): self.setWindowTitle("GUI") self.setFixedSize(800, 600) self.init_graph(200, 250) self.init_button() self.init_radio_buttons() def init_radio_buttons(self): self.Heavside_Button.setChecked(True) self.Heavside_Button.toggled.connect(self.OnClicked) self.Sigmoid_Button.toggled.connect(self.OnClicked) self.ReLu_Button.toggled.connect(self.OnClicked) self.leaky_ReLu_Button.toggled.connect(self.OnClicked) def init_graph(self, x_val, y_val): self.graph.move(x_val, y_val) self.graph.setVisible(False) def OnClicked(self): # print("button clicked") if self.sender().isChecked(): self.current_button = self.sender() # print("button changed") # print("Current button value = ", self.current_button.act_func_index) def slider_value_changed(self, value): self.slider_update.emit(value) self.slider_label.setText("Value of a: " + str(value)) self.slider_label.adjustSize() # self.reset_graph(False) # self.draw_graph() def init_button(self): self.graph_button.resize(100, 50) self.graph_button.move(600, 350) QToolTip.setFont(QFont('Times', 13)) self.graph_button.setToolTip('Click to show/recreate graph!') self.graph_button.clicked.connect(lambda: self.redraw_graph()) def redraw_graph(self): # self.graph.setVisible(False) # self.gather_data_and_create X, Y = self.construct_data() self.graph.set_x_data(X) self.graph.set_y_data(Y) self.graph.plot(self.current_button.act_func_index) # self.graph.setVisible(True) def construct_data(self): zero_data = ( int(self.class_0_construction.samples_slider.text_field.text()), int(self.class_0_construction.modes_slider.text_field.text())) one_data = ( int(self.class_1_construction.samples_slider.text_field.text()), int(self.class_1_construction.modes_slider.text_field.text())) number_samples_per_class = [ zero_data[0] * zero_data[1], one_data[0] * one_data[1] ] total_samples = number_samples_per_class[0] + number_samples_per_class[ 1] Y = np.zeros(shape=(total_samples, )) X = np.zeros(shape=(total_samples, 2)) X, Y = self.construct_arrays(0, zero_data, X, Y, 0) X, Y = self.construct_arrays(zero_data[0] * zero_data[1], one_data, X, Y, 1) return X, Y def construct_arrays(self, start_index, data, x, y, class_label): mu_range = 8 for i in range(data[1]): mu = [ random.uniform(-mu_range, mu_range), random.uniform(-mu_range, mu_range) ] xi = np.random.randn(data[0], 2) + mu yi = np.ones(shape=(data[0], )) * class_label x[start_index:start_index + data[0], :] = xi y[start_index:start_index + data[0]] = yi start_index += data[0] return x, y
def convert_graph(options, closureClass = None) : """ Entry point for external scripts (CGI or command line) to parse an RDF file(s), possibly execute OWL and/or RDFS closures, and serialize back the result in some format. Note that this entry point can be used requiring no entailement at all. Because both the input and the output format for the package can be RDF/XML or Turtle, such usage would simply mean a format conversion. If OWL 2 RL processing is required, that also means that the owl:imports statements are interpreted. Ie, ontologies can be spread over several files. Note, however, that the output of the process would then include all imported ontologies, too. @param options: object with specific attributes, namely: - options.sources: list of uris or file names for the source data; for each one if the name ends with 'ttl', it is considered to be turtle, RDF/XML otherwise (this can be overwritten by the options.iformat, though) - options.text: direct Turtle encoding of a graph as a text string (useful, eg, for a CGI call using a text field) - options.owlClosure: can be yes or no - options.rdfsClosure: can be yes or no - options.owlExtras: can be yes or no; whether the extra rules beyond OWL 2 RL are used or not. - options.axioms: whether relevant axiomatic triples are added before chaining (can be a boolean, or the strings "yes" or "no") - options.daxioms: further datatype axiomatic triples are added to the output (can be a boolean, or the strings "yes" or "no") - options.format: output format, can be "turtle" or "rdfxml" - options.iformat: input format, can be "turtle", "rdfxml", or "auto". "auto" means that the suffix of the file is considered: '.ttl' is for turtle, rdfxml otherwise - options.trimming: whether the extension to OWLRL should also includ trimming @param closureClass: explicit class reference. If set, this overrides the various different other options to be used as an extension. """ def __convert_to_turtle(graph) : """Using a non-rdflib Turtle Serializer""" return graph.serialize(format="turtle") def __convert_to_json(graph) : """Using a JSON-LD Serializer""" return graph.serialize(format="json") def __convert_to_XML(graph) : """Using a non-rdflib RDF/XML Serializer""" retval = "" try : retval = graph.serialize(format="pretty-xml") except : # there are cases when the pretty serialization goes wild, eg, when a blank node is used as a class name # as a fall back the ugly but safer simple xml serialization is used retval = graph.serialize(format="xml") return retval def __modify_request_header() : """Older versions of RDFlib, though they added an accept header, did not include anything for turtle. This is taken care of here.""" if rdflib.__version__ < "3.0.0" : from rdflib.URLInputSource import headers # The xhtml+xml probably refers to the ability of distill RDFa, though the current RDFLib distribution # is fairly poor on that one... acceptHeader = "application/rdf+xml, text/turtle, text/n3, application/xml;q=0.8, application/xhtml+xml;q=0.5" headers['Accept'] = acceptHeader else : # Unfortunately, there is no clean way of doing that in rdflib 3.0, which knows only n3... pass def __check_yes_or_true(opt) : return opt == True or opt == "yes" or opt == "Yes" or opt == "True" or opt == "true" import warnings warnings.filterwarnings("ignore") if len(options.sources) == 0 and (options.text == None or len(options.text.strip()) == 0) : raise Exception("No graph specified either via a URI or text") __modify_request_header() graph = Graph() # Just to be sure that this attribute does not create issues with older versions of the service... # the try statement should be removed, eventually... iformat = AUTO try : iformat = options.iformat except : # exception can be raised if that attribute is not used at all, true for older versions pass # similar measure with the possible usage of the 'source' options try : if options.source != None : options.sources.append(options.source) except : # exception can be raised if that attribute is not used at all, true for newer versions pass # Get the sources first. Note that a possible error is filtered out, namely to process the same file twice. This is done # by turning the intput arguments into a set... for inp in set(options.sources) : __parse_input(iformat, inp, graph) # add the possible extra text (ie, the text input on the HTML page) if options.text != None : graph.parse(StringIO.StringIO(options.text),format="n3") # Get all the options right owlClosure = __check_yes_or_true(options.owlClosure) rdfsClosure = __check_yes_or_true(options.rdfsClosure) owlExtras = __check_yes_or_true(options.owlExtras) try : trimming = __check_yes_or_true(options.trimming) except : trimming = False axioms = __check_yes_or_true(options.axioms) daxioms = __check_yes_or_true(options.daxioms) if owlClosure : interpret_owl_imports(iformat, graph) # adds to the 'beauty' of the output graph.bind("owl","http://www.w3.org/2002/07/owl#") graph.bind("xsd","http://www.w3.org/2001/XMLSchema#") #@@@@ some smarter choice should be used later to decide what the closure class is!!! That should # also control the import management. Eg, if the superclass includes OWL... if closureClass is not None : closure_class = closureClass else : closure_class = return_closure_class(owlClosure, rdfsClosure, owlExtras, trimming) DeductiveClosure(closure_class, improved_datatypes = True, rdfs_closure = rdfsClosure, axiomatic_triples = axioms, datatype_axioms = daxioms).expand(graph) if options.format == TURTLE : return __convert_to_turtle(graph) elif options.format == JSON : return __convert_to_json(graph) else : return __convert_to_XML(graph)
def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(1600, 900) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.centralwidget) self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.lay_table = QtWidgets.QVBoxLayout() self.lay_table.setObjectName("lay_table") self.PdTable = QtWidgets.QTableWidget(self.centralwidget) self.PdTable.setObjectName("PdTable") self.PdTable.setColumnCount(0) self.PdTable.setRowCount(0) self.lay_table.addWidget(self.PdTable) self.lay_buts = QtWidgets.QHBoxLayout() self.lay_buts.setObjectName("lay_buts") self.but_call = QtWidgets.QPushButton(self.centralwidget) self.but_call.setObjectName("but_call") self.lay_buts.addWidget(self.but_call) self.but_descr = QtWidgets.QPushButton(self.centralwidget) self.but_descr.setObjectName("but_descr") self.lay_buts.addWidget(self.but_descr) self.lay_table.addLayout(self.lay_buts) self.horizontalLayout_2.addLayout(self.lay_table) self.lay_graph = QtWidgets.QVBoxLayout() self.lay_graph.setObjectName("lay_graph") self.MplGraph = MyGraph(self.centralwidget) self.MplGraph.setObjectName("MplGraph") self.lay_graph.addWidget(self.MplGraph) self.vlayout_left_right = QtWidgets.QHBoxLayout() self.vlayout_left_right.setObjectName("vlayout_left_right") self.vlayout_left = QtWidgets.QVBoxLayout() self.vlayout_left.setObjectName("vlayout_left") self.label_params_enter = QtWidgets.QLabel(self.centralwidget) self.label_params_enter.setObjectName("label_params_enter") self.vlayout_left.addWidget(self.label_params_enter) self.lay_top = QtWidgets.QVBoxLayout() self.lay_top.setObjectName("lay_top") self.label_top = QtWidgets.QLabel(self.centralwidget) self.label_top.setObjectName("label_top") self.lay_top.addWidget(self.label_top) self.lay_L = QtWidgets.QHBoxLayout() self.lay_L.setObjectName("lay_L") self.label_L = QtWidgets.QLabel(self.centralwidget) self.label_L.setObjectName("label_L") self.lay_L.addWidget(self.label_L) self.doubleSpinBox_L = QtWidgets.QDoubleSpinBox(self.centralwidget) self.doubleSpinBox_L.setObjectName("doubleSpinBox_L") self.lay_L.addWidget(self.doubleSpinBox_L) self.lay_top.addLayout(self.lay_L) self.lay_R = QtWidgets.QHBoxLayout() self.lay_R.setObjectName("lay_R") self.label_R = QtWidgets.QLabel(self.centralwidget) self.label_R.setObjectName("label_R") self.lay_R.addWidget(self.label_R) self.doubleSpinBox_R = QtWidgets.QDoubleSpinBox(self.centralwidget) self.doubleSpinBox_R.setObjectName("doubleSpinBox_R") self.lay_R.addWidget(self.doubleSpinBox_R) self.lay_top.addLayout(self.lay_R) self.lay_I0 = QtWidgets.QHBoxLayout() self.lay_I0.setObjectName("lay_I0") self.label_I0 = QtWidgets.QLabel(self.centralwidget) self.label_I0.setObjectName("label_I0") self.lay_I0.addWidget(self.label_I0) self.doubleSpinBox_I0 = QtWidgets.QDoubleSpinBox(self.centralwidget) self.doubleSpinBox_I0.setObjectName("doubleSpinBox_I0") self.lay_I0.addWidget(self.doubleSpinBox_I0) self.lay_top.addLayout(self.lay_I0) self.vlayout_left.addLayout(self.lay_top) self.lay_center = QtWidgets.QVBoxLayout() self.lay_center.setObjectName("lay_center") self.label_center = QtWidgets.QLabel(self.centralwidget) self.label_center.setObjectName("label_center") self.lay_center.addWidget(self.label_center) self.lay_E0 = QtWidgets.QHBoxLayout() self.lay_E0.setObjectName("lay_E0") self.label_E0 = QtWidgets.QLabel(self.centralwidget) self.label_E0.setObjectName("label_E0") self.lay_E0.addWidget(self.label_E0) self.doubleSpinBox_E0 = QtWidgets.QDoubleSpinBox(self.centralwidget) self.doubleSpinBox_E0.setObjectName("doubleSpinBox_E0") self.lay_E0.addWidget(self.doubleSpinBox_E0) self.lay_center.addLayout(self.lay_E0) self.lay_w = QtWidgets.QHBoxLayout() self.lay_w.setObjectName("lay_w") self.label_w = QtWidgets.QLabel(self.centralwidget) self.label_w.setObjectName("label_w") self.lay_w.addWidget(self.label_w) self.doubleSpinBox_w = QtWidgets.QDoubleSpinBox(self.centralwidget) self.doubleSpinBox_w.setObjectName("doubleSpinBox_w") self.lay_w.addWidget(self.doubleSpinBox_w) self.lay_center.addLayout(self.lay_w) self.vlayout_left.addLayout(self.lay_center) self.lay_bottom = QtWidgets.QVBoxLayout() self.lay_bottom.setObjectName("lay_bottom") self.label_bottom = QtWidgets.QLabel(self.centralwidget) self.label_bottom.setObjectName("label_bottom") self.lay_bottom.addWidget(self.label_bottom) self.lay_V = QtWidgets.QHBoxLayout() self.lay_V.setObjectName("lay_V") self.label_V = QtWidgets.QLabel(self.centralwidget) self.label_V.setObjectName("label_V") self.lay_V.addWidget(self.label_V) self.doubleSpinBox_V = QtWidgets.QDoubleSpinBox(self.centralwidget) self.doubleSpinBox_V.setObjectName("doubleSpinBox_V") self.lay_V.addWidget(self.doubleSpinBox_V) self.lay_bottom.addLayout(self.lay_V) self.vlayout_left.addLayout(self.lay_bottom) self.vlayout_left_right.addLayout(self.vlayout_left) self.vlayout_right = QtWidgets.QVBoxLayout() self.vlayout_right.setObjectName("vlayout_right") self.label_params_enter2 = QtWidgets.QLabel(self.centralwidget) self.label_params_enter2.setObjectName("label_params_enter2") self.vlayout_right.addWidget(self.label_params_enter2) self.lay_h0 = QtWidgets.QHBoxLayout() self.lay_h0.setObjectName("lay_h0") self.label_h0 = QtWidgets.QLabel(self.centralwidget) self.label_h0.setObjectName("label_h0") self.lay_h0.addWidget(self.label_h0) self.doubleSpinBox_h0 = QtWidgets.QDoubleSpinBox(self.centralwidget) self.doubleSpinBox_h0.setObjectName("doubleSpinBox_h0") self.lay_h0.addWidget(self.doubleSpinBox_h0) self.vlayout_right.addLayout(self.lay_h0) self.lay_n = QtWidgets.QHBoxLayout() self.lay_n.setObjectName("lay_n") self.label_n = QtWidgets.QLabel(self.centralwidget) self.label_n.setObjectName("label_n") self.lay_n.addWidget(self.label_n) self.spinBox_n = QtWidgets.QSpinBox(self.centralwidget) self.spinBox_n.setObjectName("spinBox_n") self.lay_n.addWidget(self.spinBox_n) self.vlayout_right.addLayout(self.lay_n) self.lay_eps = QtWidgets.QHBoxLayout() self.lay_eps.setObjectName("lay_eps") self.label_eps = QtWidgets.QLabel(self.centralwidget) self.label_eps.setObjectName("label_eps") self.lay_eps.addWidget(self.label_eps) self.doubleSpinBox_eps = QtWidgets.QDoubleSpinBox(self.centralwidget) self.doubleSpinBox_eps.setObjectName("doubleSpinBox_eps") self.lay_eps.addWidget(self.doubleSpinBox_eps) self.vlayout_right.addLayout(self.lay_eps) self.lay_xmax = QtWidgets.QHBoxLayout() self.lay_xmax.setObjectName("lay_xmax") self.label_xmax = QtWidgets.QLabel(self.centralwidget) self.label_xmax.setObjectName("label_xmax") self.lay_xmax.addWidget(self.label_xmax) self.doubleSpinBox_xmax = QtWidgets.QDoubleSpinBox(self.centralwidget) self.doubleSpinBox_xmax.setObjectName("doubleSpinBox_xmax") self.lay_xmax.addWidget(self.doubleSpinBox_xmax) self.vlayout_right.addLayout(self.lay_xmax) self.lay_xeps = QtWidgets.QHBoxLayout() self.lay_xeps.setObjectName("lay_xeps") self.label_xeps = QtWidgets.QLabel(self.centralwidget) self.label_xeps.setObjectName("label_xeps") self.lay_xeps.addWidget(self.label_xeps) self.doubleSpinBox_xeps = QtWidgets.QDoubleSpinBox(self.centralwidget) self.doubleSpinBox_xeps.setObjectName("doubleSpinBox_xeps") self.lay_xeps.addWidget(self.doubleSpinBox_xeps) self.vlayout_right.addLayout(self.lay_xeps) self.vlayout_left_right.addLayout(self.vlayout_right) self.lay_graph.addLayout(self.vlayout_left_right) self.horizontalLayout_2.addLayout(self.lay_graph) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 1600, 21)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow)