def solve_graph(graph, name): """ Runs a planarity test on a predefined graph. Args: graph (networkx.Graph): Input graph name (str): The name of the graph Returns: planarity (bool): Planarity of the graph """ # graph_nodes = len(graph.nodes()) # graph_edges = len(graph.edges()) # FouldsRobinsonPlanarity.find_planarity(G) # TarjanHopcroftPlanarity.find_planarity(graph) planar, bad_graph = KuratowskiPlanarity.find_planarity(graph) print "Graph %s is planar: %s" % ( name, planar, ) GraphUtils.draw_graph(graph, name, bad_graph) return planar
def get(self): # Grab initial graph initialGraph = graph_tool.load_graph(io.StringIO(graphData), fmt='graphml') graph = initialGraph # Add in graphincludes graphIncludes = self.get_argument('graphIncludes', default=None) if graphIncludes: includes = graphIncludes.split('|') #### Turn this into a for-loop, with appropriately named exist queries?? if 'repo' in includes: addData = exist.buildGraphML('repo' + '.xql') addGraph = graph_tool.load_graph(io.StringIO(addData), fmt='graphml') print('\n\n#####################\n JOINING REPO GRAPH\n#######################') graph = GraphUtils.join_graphs(graph, addGraph) # Add in search terms searchString = self.get_argument('searchTerm', default=None) if searchString: searchTerms = searchString.split('|') for st in searchTerms: addData = exist.buildGraphML('searchTerm.xql?searchString=' + st) print('\n\n#####################\n JOINING ST', st, 'GRAPH\n#######################') addGraph = graph_tool.load_graph(io.StringIO(addData), fmt='graphml') graph = GraphUtils.join_graphs(graph, addGraph) layout = yield executor.submit(self.get_layout, graph) ########### self.write(GraphUtils.graph_to_linkurious_json(graph, layout)) self.finish()
def __init__(self, graph, nodeType, alphas=[0.01]): self.graph = graph self.type = self.graph.getStringProperty('type') self.name = self.graph.getStringProperty('name') self.plainOneModeGraph = self.graph.getSuperGraph().addSubGraph( 'plainOneMode_country') self.substrateType = nodeType self.strength = self.plainOneModeGraph.getDoubleProperty( 'Neal strength') self.nbCatalysts = 0 for node in self.graph.getNodes(): if self.type[node] != self.substrateType: self.nbCatalysts += 1 self.alphas = alphas for node in self.graph.getNodes(): if self.type[node] == self.substrateType: self.plainOneModeGraph.addNode(node) self.neighborSets = {} self.probabilities = {} self.utils = GraphUtils()
def createGraphProcess(functions, domain, gRange): # Format the expressions so they are ready to be graphed funcArg = [GraphUtils.formatExpression(f) for f in functions] funcArg = GraphUtils.replaceCalls(funcArg) funcArg = [GraphUtils.nestFunctions(e[1], funcArg[:e[0]] + funcArg[e[0] + 1:]) for e in enumerate(funcArg)] # Open the graphing subprocess return subprocess.Popen(["python", sys.path[1] + "/Graphing.py", str(len(funcArg))] + funcArg + [domain,gRange])
def get_and_plot_ads_revenue_data(fan_id, fan_token, from_time, to_time): revenue_data = get_fan_and_admob_revenue_data(fan_id, fan_token, from_time, to_time) # we got all the necessary data. We will plot the data into a time series graph now. GraphUtils.plot_time_series(revenue_data[0], revenue_data[1:4], "Date", "Revenue", ["FAN", "Admob", "Total"], "$", "Network", "Pi Music Player Ads Revenue")
def add_van_node(self): van_pos = (self.ride_data.van_vertex["x"], self.ride_data.van_vertex["y"]) GraphUtils.add_node(self.graph, "van", van_pos, "van", grid_graph=None, on_grid=True)
def testPlanar(self): # Generate K(4) graph p_graph = GraphGenerator.make_planar_graph() # Test graph planar, bad_graph = KuratowskiPlanarity.find_planarity(p_graph) GraphUtils.draw_graph(p_graph, "planar_test", bad_graph) # print "Test on planar graph:", 'PASS' if planar else 'FAIL' self.assertTrue(planar) # True means graph is planar
def testK5(self): # Generate K(5) graph k5 = GraphGenerator.make_k5_graph() # Test graph planar, bad_graph = KuratowskiPlanarity.find_planarity(k5) GraphUtils.draw_graph(k5, "K5", bad_graph) # print "Test on K(5):", 'FAIL' if planar else 'PASS' self.assertFalse(planar) # False means K(5) subgraph was found
def testK33(self): # Generate K(3, 3) graph k33 = GraphGenerator.make_k33_graph() # Test graph planar, bad_graph = KuratowskiPlanarity.find_planarity(k33) GraphUtils.draw_graph(k33, "K33", bad_graph) # print "Test on K(3, 3):", 'FAIL' if planar else 'PASS' self.assertFalse(planar) # False means K(3, 3) subgraph was found
def __usonic_log(self, tweet_id, span=HOUR): now = datetime.datetime.now() if span == DAY: from_time = now - datetime.timedelta(days=1) axis_span = 120 else: from_time = now - datetime.timedelta(hours=1) axis_span = 10 db = USonicDB() log = db.select_between(from_time, now) Gu.create_usonic_graph(log, USONIC_GRAPH_TEMP, axis_span=axis_span) message = USONIC_LOG_FMT.format(span) self.tweet.update_with_media(USONIC_GRAPH_TEMP, message, tweet_id)
def add_rides_to_graph(self, rides): for ride in rides: pu = GraphUtils.add_main_node(self.graph, ride.pickup.name, ride.pickup.pos, "pickup", self.ride_data) do = GraphUtils.add_main_node(self.graph, ride.dropoff.name, ride.dropoff.pos, "dropoff", self.ride_data) self.do_nodes.append(do[0]) self.pu_nodes.append(pu[0]) self.w_nodes.extend(pu[1:]) self.w_nodes.extend(do[1:]) self.add_edges_for_print(ride)
def __init__(self, outdir="./", outfile="yields.txt", integer_precision=False): self.columns = [] self.rows = [] self.column_names = [] self.row_names = [] self.gu = GraphUtils() # self.out_dir = outdir self.out_file = outfile self.integer_precision = integer_precision
def __dht_log(self, tweet_id, span=DAY): now = datetime.datetime.now() if span == DAY: from_time = now - datetime.timedelta(days=1) axis_span = 120 elif span == WEEK: from_time = now - datetime.timedelta(days=7) axis_span = 1000 else: from_time = now - datetime.timedelta(hours=1) axis_span = 10 db = DHTDB() log = db.select_between(from_time, now) Gu.create_dht_graph(log, DHT_GRAPH_TEMP, axis_span=axis_span) message = DHT_LOG_FMT.format(span) self.tweet.update_with_media(DHT_GRAPH_TEMP, message, tweet_id)
def equationChanged(stuff, var, resultString, resultLabel, num): global fList def updateResults(rng): formatted = map(lambda frame: GraphUtils.formatExpression(frame[6].get()), fList[rng[0]: rng[1]]) replaced = GraphUtils.replaceCalls(formatted) for i in range(len(replaced)): replaced[i] = GraphUtils.nestFunctions(replaced[i], replaced[:i] + replaced[i + 1:]) for i in range(len(replaced)): frame = fList[i + rng[0]] eq = replaced[i] # Calculate the result of the entered equation result = MathCalc.readEquation(GraphUtils.removeDependant(eq)) resultType = type(result) types = [int, long, float] # Display the result of calculation below the text box if resultType in types: frame[7].set("= " + str(result)) frame[3].grid(columnspan=1000) else: frame[3].grid_forget() if GraphUtils.defineFunctions([var.get()] + map(lambda frame: frame[6].get(), fList)): updateResults([0, len(fList)]) else: index = int(num.get()[:-1]) - 1 updateResults([index, index + 1])
def add_drop_off_node(self, nn, rides, sh_path_lens, grid_g): cur_node_dict = self.graph.nodes[nn] ride_num = int(nn[2]) ride = rides[ride_num - 1] new_nodes = GraphUtils.add_main_node(self.graph, ride.dropoff.name, ride.dropoff.pos, "dropoff", self.ride_data, grid_graph=grid_g.graph, on_grid=False) # adds the "detour" attribute to the node attributes dictionary self.graph.nodes[ ride.dropoff.name]["detour"] = -sh_path_lens[ride.pickup.name] # Creates weighted edges for the new nodes with the exist nodes for new_node in new_nodes: for node in self.graph.nodes: if all([ node not in self.graph.node[new_node]["wnode"], node != "van" ]): self.graph.add_edge(new_node, node, weight=nx.shortest_path_length( grid_g.graph, new_node, node))
def computeBendPoints(pixels, keypixels, vectorpoints): temp_key_pixels = copy.deepcopy(keypixels) bend_pixels = [] for i in keypixels: x = GraphUtils.vectorSearch(np.array(i), np.array(keypixels), pixels, is_start=True, vector_points=vectorpoints) if x is not None and len(x) != 0: # print(x) i1 = x[0][0] i2 = x[1][0] j1 = x[0][1] j2 = x[1][1] _cos = (i1 * i2 + j1 * j2) / (np.sqrt(i1**2 + j1**2) * np.sqrt(i2**2 + j2**2)) tmp = np.arccos(float(_cos)) angle = np.rad2deg(tmp) # print(angle) if angle >= 120: temp_key_pixels.remove(i) bend_pixels.append(i) keypixels = temp_key_pixels return bend_pixels
def __init__(self, multiGraph, M, damp=.8, sieve=3, top=5, eiglim=1.6, wlcf=lambda x,y,z: x): self.rankdata = [] self.remaining = range(len(multiGraph)) self.prevRemaining = range(len(multiGraph)) self.nowins = [] self.M = M self.damp = damp self.sieve = sieve self.top = top self.eiglim = eiglim self.wlcf = wlcf for i in range(len(M)): for j in range(len(M)): self.M[i, j] = self.M[i, j]**.5 for i in multiGraph: if not multiGraph[i]: self.nowins.append(i) self.remaining.remove(i) self.count = len(self.remaining) currM = self.M[np.ix_(self.remaining, self.remaining)] self.prevM = self.M eigval = max(abs(np.linalg.eig(currM)[0])) if not eigval or eigval < eiglim: eigval = eiglim escale = damp*eigval**(-1) K = gu.KRank(currM, escale, 50) rankdata = sorted(zip(range(len(currM)), K), key=lambda v: v[1]) self.currank = [(self.remaining[i], j) for i, j in rankdata]
def random_walk(graph, startVector, r=0.4): """ This method can be called from anywhere (such as validation scripts) and does whatever it needs to do to produce a properly formatted output, using only the given parameters. @param graph: a networkx graph object containing the entire PPI network @param startVector: a numpy array that contains the weighted start probabilities for each protein in the network @returns: a nested list of tuples, in sorted order of probability, where each item contains the name of a gene, and its respective probability as determined by the algorithm """ print("INITIALIZING RANDOM WALK") maxIterations = 500 normThreshold = 10**(-6) print("creating matrix") matrix = compute_if_not_cached(create_normalized_matrix, graph, fileName=graph.name) probabilityVector = random_walk_matrix(matrix, startVector, r, maxIterations, normThreshold) # format probabilityVector into usable output print("formatting output") return GraphUtils.format_output(graph, probabilityVector)
def run_algs(self, policies, n_experiments=None, time_horizon=None): for n_nodes, budget in zip(self.n_nodes, self.budgets): network = ut.create_network(n_nodes, self.n_features) print('\nBudget: ' + str(budget)) print('Number of nodes: ' + str(n_nodes)) env = None if self.alg_type == 'unknown': print('Time Horizon: ', str(time_horizon)) print('Number of experiments: ', str(n_experiments)) env = SocialEnvironment(network.copy()) for e in network.edges.values(): e['prob'] = None for mc_iterations in self.mc_iterations: print('Montecarlo iterations: ' + str(mc_iterations)) if self.alg_type == 'known': self.learners = SimplePolicies(network, mc_iterations, bandit=False) self.learners.execute(budget, policies) self.plot_results() else: self.learners = SocialBanditPolicies( network, budget, mc_iterations, env) self.learners.execute(n_experiments, time_horizon, policies) self.plot_results()
def __init__(self, inputpath='', inputfile='', output=None, standards=None, observable=None, purity=None): try: Defaults.__init__(self, standards=standards) except RuntimeError: print "Error: cannot initialize defaults class..." self.__outputpath = inputpath self.__filename = os.path.join(inputpath, inputfile) self.__output = output self.__standards = standards self.__observable = observable self.__purity = purity # self.__analysis = standards.analysis self.__luminosity = standards.luminosity self.__gu = GraphUtils() self.__fm = Format(standards) self.__histo_list = [] self.__analysis_ready = self.analyze_file() self.__visual_ready = self.visualize() self.__final_ready = self.finalize()
def xmlizeFiles(self, directory, fileType): # stat table contains triples of (time, file, stat) statTable = [] fields = self.request().fields() for f in findSysFiles(directory): s = os.stat(os.path.join(basicPathName, directory, f)) md5sum = self.readMd5Sum(directory, f) statTable.append((s[stat.ST_MTIME], f, s, md5sum)) # sort first by reverse time, then by name statTable.sort(lambda a,b: cmp(b[0], a[0]) or FormUtils.alphanumericCompare(a[1], b[1])) result = self.doc.createElement(directory) for sysMtime, eachFile, fileStat, md5Sum in statTable: sysBytes = fileStat[stat.ST_SIZE] sysTimeStr = time.strftime('%Y/%m/%d %H:%M', time.localtime(sysMtime)) fileEl = self.doc.createElement('file') fileEl.setAttribute('name', eachFile) fileEl.setAttribute( 'href', '/mgmt/download?f=%s&type=%s' % (eachFile, fileType)) # bytes are for column sorting fileEl.setAttribute('bytes', '%d' % sysBytes) fileEl.setAttribute('sizeStr', GraphUtils.scale( sysBytes, GraphUtils.SCALER_HUNDREDS_OF_BYTES)) # timestamp is for column sorting fileEl.setAttribute('timestamp', '%d' % sysMtime) fileEl.setAttribute('timestring', sysTimeStr) fileEl.setAttribute('md5sum', '%s' % md5Sum) result.appendChild(fileEl) self.doc.documentElement.appendChild(result) self.writeXmlDoc()
def inputExpression(): while 1: while 1: print "\nPlease enter expression to evaluate [OR] q to return to the main menu" expression = raw_input(">> ").strip() if not expression: continue break if expression.lower() == "q": return None formatted = GraphUtils.formatExpression(expression) if not GraphUtils.validateFunction(formatted): print "The expression entered has unmatched brackets.\nPlease try again.\n" continue return expression
def create_normalized_matrix(ppiGraph): """ Generates normalized adjacency matrix. @param ppiGraph: a networkx graph containing the entire PPI network @returns: a numpy array that contains the normalized adjacency matrix """ return np.asarray( GraphUtils.normalize_adjacency_matrix(nx.to_numpy_matrix(ppiGraph)))
def calc_data(self): self.M = gu.MG_to_M(self.multiGraph) data = gu.MG_to_G(self.multiGraph) self.G = data[0] self.D = data[1] self.A = gu.G_to_A(self.G) self.DA = np.matrix([[0 for col in self.M] for col in self.M]) for i in self.D: for j in self.D[i]: self.DA[i, j] = 1 self.W = self.A + (.5)*self.DA # TODO: implement a function to scale results from 0 to 1 self.partition = gu.SCC(self.G) self.inCycle = gu.record_cycles(self.G, self.partition) self.isBelow = gu.record_isBelow(self.G, self.inCycle) self.stronglyBelow = gu.record_stronglyBelow(self.G, self.isBelow, self.inCycle)
def updateResults(rng): formatted = map(lambda frame: GraphUtils.formatExpression(frame[6].get()), fList[rng[0]: rng[1]]) replaced = GraphUtils.replaceCalls(formatted) for i in range(len(replaced)): replaced[i] = GraphUtils.nestFunctions(replaced[i], replaced[:i] + replaced[i + 1:]) for i in range(len(replaced)): frame = fList[i + rng[0]] eq = replaced[i] # Calculate the result of the entered equation result = MathCalc.readEquation(GraphUtils.removeDependant(eq)) resultType = type(result) types = [int, long, float] # Display the result of calculation below the text box if resultType in types: frame[7].set("= " + str(result)) frame[3].grid(columnspan=1000) else: frame[3].grid_forget()
def reduce(self): while len(self.currank) > self.top: self.rankdata.append(self.currank) #find point of change after cutoff point n = max(1, len(self.currank)/self.sieve) while self.currank[n] == self.currank[n+1]: n += 1 for i in [i for i,j in self.currank[:n]]: self.remaining.remove(i) currM = self.M[np.ix_(self.remaining, self.remaining)] eigval = max(abs(np.linalg.eig(currM)[0])) if not eigval or eigval < self.eiglim: eigval = self.eiglim escale = self.damp*eigval**(-1) # used for scaling losses in wlcf lscale = float(self.count - len(self.remaining))/self.count K = gu.KRank(currM, escale, 50) KL = gu.KRank(currM, escale, 50, direction=0) D = [self.wlcf(i, j, lscale) for i, j in zip(K, KL)] drankdata = sorted(zip(range(len(currM)), D), key=lambda v: v[1]) self.currank = [(self.remaining[i], j) for i, j in drankdata] self.prevM = currM self.prevRemain = self.remaining # I don't understand why I need to make this check # If I don't, rankdata somehow gets the last currank appended twice if self.rankdata[-1] != self.currank: self.rankdata.append(self.currank)
def main(): """ Entry point into the program. """ num_nodes = 20 # Use binomial coefficient to find algorithm runtime (algorithm is O(n choose 6 + n choose 5)) # K33 check complexity complexity_k33 = math.factorial(num_nodes) / ( math.factorial(6) * math.factorial(num_nodes - 6)) # K5 check complexity complexity_k5 = math.factorial(num_nodes) / (math.factorial(5) * math.factorial(num_nodes - 5)) # Overall complexity formatted with commas complexity = GraphUtils.format_commas(complexity_k5 + complexity_k33) print "[kuratowski] Iterations (worst case) for %s nodes: %s" % ( num_nodes, complexity, ) # Random graph, usually nonplanar solve_random_graph(num_nodes, 0.7, "graph1") # Graph is likely to be nonplanar # Random graph, usually planar solve_random_graph(8, 0.4, "graph2") # Graph is usually planar # K(3, 3) graph k33 = GraphGenerator.make_k33_graph() solve_graph(k33, "k33") # K(5) graph k5 = GraphGenerator.make_k5_graph() solve_graph(k5, "k5") # Guaranteed planar graph planar_graph = GraphGenerator.make_planar_graph() solve_graph(planar_graph, "planar_graph") # Display each graph (blocking command, run last) plt.show()
def approximation(edges, vectors, i, P_list, S_list, O_list): O = edges[i][0] S = edges[i][-1] OM = vectors[i] OS = (S[0] - O[0], S[1] - O[1]) c = np.sqrt((O[0] - S[0])**2 + (O[1] - S[1])**2) length = GraphUtils.fullLen(edges[i]) cos_alpha = (OM[0] * OS[0] + OM[1] * OS[1]) / ( np.sqrt(OM[0]**2 + OM[1]**2) * np.sqrt(OS[0]**2 + OS[1]**2)) if cos_alpha != 1: a = (c**2 - length**2) / (2 * (c * cos_alpha - length)) cos_beta = OM[0] / np.sqrt(OM[0]**2 + OM[1]**2) sin_beta = np.sqrt(1 - cos_beta**2) delta_x = a * cos_beta delta_y = a * sin_beta P = O[0] + delta_x, O[1] + delta_y OP = P[0] - O[0], P[1] - O[1] # С ОТРАЖЕНИЕМ if (OS[0] * OM[1] - OS[1] * OM[0]) * (OS[0] * OP[1] - OS[1] * OP[0]) >= 0: P_list.append(P) S_list.append(S) O_list.append(O) else: S_list.append(S) O_list.append(O) # TODO: отражение точки относительно отрезка temp_line = Line(0, xy1=O, xy2=S) A, B, C = temp_line.A, temp_line.B, temp_line.C first_matrix = np.array([[A, B], [B, -A]], dtype=np.float32) second_vector = np.array([-C, B * P[0] - A * P[1]], dtype=np.float32) x1, y1 = np.linalg.solve(first_matrix, second_vector) P = (2 * x1 - P[0], 2 * y1 - P[1]) P_list.append(P) else: P_list.append(edges[i][len(edges[i]) // 2]) O_list.append(O) S_list.append(S)
def calc_data(self): self.M = gu.MG_to_M(self.multiGraph) data = gu.MG_to_G(self.multiGraph) self.G = data[0] self.D = data[1] self.A = gu.G_to_A(self.G) self.DA = np.matrix([[0 for col in self.M] for col in self.M]) for i in self.D: for j in self.D[i]: self.DA[i, j] = 1 self.W = self.A + (.5) * self.DA # TODO: implement a function to scale results from 0 to 1 self.partition = gu.SCC(self.G) self.inCycle = gu.record_cycles(self.G, self.partition) self.isBelow = gu.record_isBelow(self.G, self.inCycle) self.stronglyBelow = gu.record_stronglyBelow(self.G, self.isBelow, self.inCycle)
def __init__(self, graph, nodeType, alphas = [0.01]): self.graph = graph self.type = self.graph.getStringProperty('type') self.name = self.graph.getStringProperty('name') self.plainOneModeGraph = self.graph.getSuperGraph().addSubGraph('plainOneMode_country') self.substrateType = nodeType self.strength = self.plainOneModeGraph.getDoubleProperty('Neal strength') self.nbCatalysts = 0 for node in self.graph.getNodes(): if self.type[node] != self.substrateType: self.nbCatalysts += 1 self.alphas = alphas for node in self.graph.getNodes(): if self.type[node] == self.substrateType: self.plainOneModeGraph.addNode(node) self.neighborSets = {} self.probabilities = {} self.utils = GraphUtils()
def final_graph_plotting(self, path, rides): self.add_rides_to_graph(rides) self.add_van_node() path_edge_list = GraphUtils.get_edge_list_from_path(path) plt.figure(figsize=(15, 15)) self.set_nodes_and_edge_colors() nx.draw(self.graph, self.positions, node_size=15, node_color=self.node_colors, edge_color=self.edge_colors) nx.draw_networkx_nodes(self.graph, self.positions, self.w_nodes, node_size=40, node_color='y') nx.draw_networkx_nodes(self.graph, self.positions, self.pu_nodes, node_size=40, node_color='r') nx.draw_networkx_nodes(self.graph, self.positions, self.do_nodes, node_size=40, node_color='b') nx.draw_networkx_nodes(self.graph, self.positions, ["van"], node_size=40, node_color='g') nx.draw_networkx_edges(self.graph, self.positions, path_edge_list, width=2, edge_color='red') plt.show()
def load_nodes(self, gridG, rides, van_vertex, for_final_plot=False): van_pos = (van_vertex["x"], van_vertex["y"]) GraphUtils.add_node(self.graph, "van", van_pos, "van", grid_graph=gridG.graph, on_grid=False) for ride in rides: GraphUtils.add_main_node(self.graph, ride.pickup.name, ride.pickup.pos, "pickup", self.ride_data, grid_graph=gridG.graph, on_grid=False) if for_final_plot: GraphUtils.add_main_node(self.graph, ride.dropoff.name, ride.dropoff.pos, "dropoff", self.ride_data, grid_graph=gridG.graph, on_grid=False) self.graph.add_edge(ride.pickup.name, ride.dropoff.name, color="green") else: for i, j in itertools.combinations(self.graph.nodes, 2): if i == "van" or j == "van" or j not in self.graph.node[i][ "wnode"]: self.graph.add_edge(i, j, weight=nx.shortest_path_length( gridG.graph, self.graph.node[i]["position"], self.graph.node[j]["position"]))
class OneModeProjection(object): ''' this class implements Z. Neal's technique for computing a one mode projection of a bipartite network we agree to distinguish nodes by assinging them a type stored in a string property for convenience we call nodes either substrates or catalysts to distinguish these two types substrates are those nodes of the indicated type ''' def __init__(self, graph, nodeType, alphas = [0.01]): self.graph = graph self.type = self.graph.getStringProperty('type') self.name = self.graph.getStringProperty('name') self.plainOneModeGraph = self.graph.getSuperGraph().addSubGraph('plainOneMode_country') self.substrateType = nodeType self.strength = self.plainOneModeGraph.getDoubleProperty('Neal strength') self.nbCatalysts = 0 for node in self.graph.getNodes(): if self.type[node] != self.substrateType: self.nbCatalysts += 1 self.alphas = alphas for node in self.graph.getNodes(): if self.type[node] == self.substrateType: self.plainOneModeGraph.addNode(node) self.neighborSets = {} self.probabilities = {} self.utils = GraphUtils() def computeNeighborSets(self): for node in self.graph.getNodes(): if self.type[node] == self.substrateType: neighbors = [] for neigh in self.graph.getInOutNodes(node): neighbors.append(neigh.id) self.neighborSets[node.id] = frozenset(neighbors) def probability(self, P1, P2, C): E = self.nbCatalysts p = 1.0 p *= binomial(E, C) p *= binomial(E - C, P1 - C) p *= binomial(E - P1, P2 - C) p /= binomial(E, P1) p /= binomial(E, P2) return p def cumulProbability(self, P1, P2, C): s = 0.0 for c in range(C+1): s += self.probability(P1, P2, c) return s def inverseCPF(self, P1, P2, alpha): ''' (CPF stands for cumulatice probability function) determine C such that the probability that P1 and P2 share C common neighbors or less is at least alpha ''' C = min(P1, P2) + 1 cumulProb = 0.0 while cumulProb < alpha: C -= 1 cumulProb += self.probability(P1, P2, C) return C + 1 def induceEdge(self, node1, node2): try: set1 = self.neighborSets[node1.id] except KeyError: print node1, self.type[node1], self.name[node1] P1 = len(set1) set2 = self.neighborSets[node2.id] P2 = len(set2) intersection = set1.intersection(set2) C = len(intersection) for i in range(len(self.alphas)): alpha = self.alphas[i] oneModeGraph = self.oneModeGraphs[i] if C >= self.inverseCPF(P1, P2, alpha): edge = self.utils.findEdge(node1, node2, oneModeGraph) #print edge if edge == None: edge = oneModeGraph.addEdge(node1, node2) self.strength[edge] = self.cumulProbability(P1, P2, C) label = '(' + str(node1.id) + ', ' + str(node2.id) + ', ' + str(self.inverseCPF(P1, P2, alpha)) + ')' self.invCPFProperty[edge] = label def plainProjection(self): ''' take all pairs of distance-2 neighbors of type A (connected through a type B common neighbor) induce an edge between nodes in a unimode (type A) graph ''' visited = set() queue = Queue() ''' find a node of proper type ''' for node in self.sandBoxGraph.getNodes(): if self.type[node] == self.substrateType: queue.put(node) break nbProcessedEdges = 0 while not queue.empty(): node1 = queue.get() visited.add(node1.id) if len(visited) % 10 == 0: print 'processed ' + str(len(visited)) + ' substrate nodes' for node in self.sandBoxGraph.getInOutNodes(node1): for node2 in self.sandBoxGraph.getInOutNodes(node): if node2.id not in visited: queue.put(node2) edge = self.utils.findEdge(node1, node2, self.plainOneModeGraph) if edge == None: edge = self.plainOneModeGraph.addEdge(node1, node2) nbProcessedEdges += 1 def computeEdgeStrength(self, node1, node2): set1 = self.neighborSets[node1.id] P1 = len(set1) set2 = self.neighborSets[node2.id] P2 = len(set2) intersection = set1.intersection(set2) C = len(intersection) strength = 0 for k in range(C+1): strength += self.probability(P1, P2, k) return strength def projectNeal(self, alphas): ''' this is Zachary Neal's trick take all pairs of distance-2 neighbors of type A (connected through a type B common neighbor) if number of common neighbors (of type B) is at lest equal to inverseCPF(alpha) induce an edge between nodes in a unimode (type A) graph ''' visited = set() queue = Queue() ''' find a node of proper type ''' for node in self.sandBoxGraph.getNodes(): if self.type[node] == self.substrateType: queue.put(node) break nbProcessedEdges = 0 while not queue.empty(): substrate1 = queue.get() visited.add(substrate1.id) if len(visited) % 10 == 0: print 'processed ' + str(len(visited)) + ' substrate nodes' for catalyst in self.sandBoxGraph.getInOutNodes(substrate1): for substrate2 in self.sandBoxGraph.getInOutNodes(catalyst): if substrate2.id not in visited: queue.put(substrate2) self.induceEdge(substrate1, substrate2, alpha) nbProcessedEdges += 1 def efficientProject(self): ''' parse all nodes of type 'not substrate' for each, grab their neighbors (they are of type 'substrate') build a clique (add all missing edges, as some might already be there) ''' denom = self.graph.numberOfNodes() - self.plainOneModeGraph.numberOfNodes() numer = 0 percentProcessedNodes = 0.0 for node in self.graph.getNodes(): if self.type[node] != self.substrateType: numer += 1 for neigh1 in self.graph.getInOutNodes(node): for neigh2 in self.graph.getInOutNodes(node): if neigh1.id != neigh2.id: edge = self.utils.findEdge(neigh1, neigh2, self.plainOneModeGraph) if edge == None: edge = self.plainOneModeGraph.addEdge(neigh1, neigh2) self.strength[edge] = self.computeEdgeStrength(neigh1, neigh2) newPercentProcessedNodes = round(float(numer)/denom * 100) if newPercentProcessedNodes > percentProcessedNodes: percentProcessedNodes = newPercentProcessedNodes print 'Processed ', percentProcessedNodes, '% nodes, (', numer, ' non substrate) nodes' def efficientNealProject(self): for i in range(len(self.alphas)): alpha = self.alphas[i] print ' Computing Neal projection' + str(alpha) nodeSet = set() self.plainOneModeGraph.getBooleanProperty('select') for edge in self.plainOneModeGraph.getEdges(): node1 = self.plainOneModeGraph.source(edge) set1 = self.neighborSets[node1.id] P1 = len(set1) node2 = self.plainOneModeGraph.target(edge) set2 = self.neighborSets[node2.id] P2 = len(set2) intersection = set1.intersection(set2) C = len(intersection) if C >= self.inverseCPF(P1, P2, alpha): nodeSet.add(node1) nodeSet.add(node2) subGraph = self.plainOneModeGraph.inducedSubGraph(nodeSet) subGraph.setName('plainOneMode_country_' + str(alpha)) print ' Finished - Computing Neal projection' + str(alpha)
class Yields(object): def __init__(self, outdir="./", outfile="yields.txt", integer_precision=False): self.columns = [] self.rows = [] self.column_names = [] self.row_names = [] self.gu = GraphUtils() # self.out_dir = outdir self.out_file = outfile self.integer_precision = integer_precision def __ncol(self): return len(self.column_names) + 1 def __get_latex_table_top(self): column_names = self.column_names column_names.append("Ratio") ncolumns = "l" * (self.__ncol()) titles = " & ".join(column_names) multicolumn = "" for i in xrange(1, self.__ncol() + 1): multicolumn += "{#%i}" % i return """\\begin{table} \\renewcommand{\\arraystretch}{1.3} \\begin{center} \\begin{tabular}{%s}\hline Sample & %s \\\ \hline \hline \n""" % (ncolumns, titles) def __get_latex_table_bottom(self): caption = ", ".join(self.column_names) label = "_".join(self.column_names) return """\hline \end{tabular} \end{center} \caption{%s yields.} \label{tb:yields_%s} \end{table}\n\n""" % (caption, label) def add_column(self, icolumn=None): if icolumn: self.columns.append(icolumn) self.column_names.append(icolumn.name) def add_row(self, irow=None): if irow: self.rows.append(irow) self.row_names.append(irow.name) def store(self): #upper table outbuffer = self.__get_latex_table_top() #organize columns ref_column = self.columns[0] total_prefit = 0 total_postfit = 0 error_prefit2 = 0 error_postfit2 = 0 for sample, histo in ref_column.column.items(): #prefit error = ROOT.Double() area = histo.IntegralAndError(-1, -1, error, "") if self.integer_precision: outbuffer += "%-*s & %-*i $\pm$ %-*i" % ( 15, sample, 15, int(area), 15, int(error)) else: outbuffer += "%-*s & %-*.4f $\pm$ %-*.4f" % (15, sample, 15, area, 15, error) total_prefit += area error_prefit2 += error**2 #postfit for icolumn in self.columns: if icolumn.name == ref_column.name: continue for isample, ihisto in icolumn.column.items(): if isample == sample: ierror = ROOT.Double() iarea = ihisto.IntegralAndError(-1, -1, ierror, "") if self.integer_precision: outbuffer += " & %-*i $\pm$ %-*i" % ( 15, int(iarea), 15, int(ierror)) else: outbuffer += " & %-*.4f $\pm$ %-*.4f" % ( 15, iarea, 15, ierror) #ratio ratio_val = iarea / area ratio_err = ratio_val * math.sqrt( math.pow(ierror / iarea, 2) + math.pow(error / area, 2)) outbuffer += " & %-*.2f $\pm$ %-*.2f" % (15, ratio_val, 15, ratio_err) total_postfit += iarea error_postfit2 += ierror**2 outbuffer += "\\\\ \n" # error_prefit = math.sqrt(error_prefit2) error_postfit = math.sqrt(error_postfit2) total_ratio_val = total_postfit / total_prefit total_ratio_error = total_ratio_val * math.sqrt( math.pow(error_prefit / total_prefit, 2) + math.pow(error_postfit / total_postfit, 2)) outbuffer += "\hline \n" outbuffer += "%-*s & %-*.4f $\pm$ %-*.4f" % ( 15, "Total", 15, total_prefit, 15, error_prefit) outbuffer += " & %-*.4f $\pm$ %-*.4f" % (15, total_postfit, 15, error_postfit) outbuffer += " & %-*.2f $\pm$ %-*.2f" % (15, total_ratio_val, 15, total_ratio_error) outbuffer += "\\\\ \n" outbuffer += "\hline \n" #organize rows for irow in self.rows: content, error_low, error_high = self.gu.area_and_poissonian_errors( irow.graph) outbuffer += "%-*s & \multicolumn{%i}{c}{$%i^{+%i}_{-%i}$} & \\\\ \n" % ( 15, irow.name, self.__ncol() - 2, content, error_high, error_low) total_ratio_prefit = content / total_prefit total_error_prefit_high = total_ratio_prefit * math.sqrt( math.pow(error_prefit / total_prefit, 2) + math.pow(error_high / content, 2)) total_error_prefit_low = total_ratio_prefit * math.sqrt( math.pow(error_prefit / total_prefit, 2) + math.pow(error_low / content, 2)) total_ratio_postfit = content / total_postfit total_error_postfit_high = total_ratio_postfit * math.sqrt( math.pow(error_postfit / total_postfit, 2) + math.pow(error_high / content, 2)) total_error_postfit_low = total_ratio_postfit * math.sqrt( math.pow(error_postfit / total_postfit, 2) + math.pow(error_low / content, 2)) outbuffer += "\hline \n" outbuffer += "%-*s" % (15, irow.name + "/Total") outbuffer += " & $%.4f^{+%.4f}_{-%.4f}$" % ( total_ratio_prefit, total_error_prefit_high, total_error_prefit_low) outbuffer += " & $%.4f^{+%.4f}_{+%.4f}$" % ( total_ratio_postfit, total_error_postfit_high, total_error_postfit_low) outbuffer += " & " outbuffer += "\\\\ \n" outbuffer += "\hline \n" #bottom table outbuffer += self.__get_latex_table_bottom() + "\n" fname = os.path.join(self.out_dir, self.out_file) f = open(fname, "w") f.write(outbuffer) f.close() msg.info("Yields::store", "Result is stored in '%s'" % (fname))
def page_rank(graph, startVector, priorBias, beta=BETA): return GraphUtils.format_output( graph, rank_genes(graph, startVector, priorBias, beta))
def compute_matrix(graph): return np.asarray( GraphUtils.normalize_adjacency_matrix(nx.to_numpy_matrix(graph)))
def simplefitter_3D_NoFormDataValidation(): formTextData = request.form['textdata'] formEquation = request.form['equation'] formFittingTarget = request.form['target'] if formEquation == 'Linear': equation = pyeq2.Models_3D.Polynomial.Linear(formFittingTarget) elif formEquation == 'FullQuadratic': equation = pyeq2.Models_3D.Polynomial.FullQuadratic(formFittingTarget) elif formEquation == 'FullCubic': equation = pyeq2.Models_3D.Polynomial.FullCubic(formFittingTarget) elif formEquation == 'MonkeySaddleA': equation = pyeq2.Models_3D.Miscellaneous.MonkeySaddleA( formFittingTarget) elif formEquation == 'GaussianCurvatureOfWhitneysUmbrellaA': equation = pyeq2.Models_3D.Miscellaneous.GaussianCurvatureOfWhitneysUmbrellaA( formFittingTarget) elif formEquation == 'NIST_NelsonAutolog': equation = pyeq2.Models_3D.NIST.NIST_NelsonAutolog(formFittingTarget) elif formEquation == 'CustomPolynomialOne': # X order 3, Y order 1 in this example - passed as integers equation = pyeq2.Models_3D.Polynomial.UserSelectablePolynomial( formFittingTarget, "Default", 3, 1) # the name of the data here is from the form # check for functions requiring non-zero nor non-negative data such as 1/x, etc. try: pyeq2.dataConvertorService().ConvertAndSortColumnarASCII( formTextData, equation, False) except: return equation.reasonWhyDataRejected # check for number of coefficients > number of data points to be fitted coeffCount = len(equation.GetCoefficientDesignators()) dataCount = len(equation.dataCache.allDataCacheDictionary['DependentData']) if coeffCount > dataCount: return "This equation requires a minimum of " + repr( coeffCount) + " data points, you supplied " + repr(dataCount) + "." equation.Solve() equation.CalculateModelErrors(equation.solvedCoefficients, equation.dataCache.allDataCacheDictionary) equation.CalculateCoefficientAndFitStatistics() # save fit statistics to a text file fitStatisticsFilePath = "static/fitstatistics_3D.txt" # simplefitter_3D TextUtils.SaveCoefficientAndFitStatistics(fitStatisticsFilePath, equation) # save source code to a single text file, all available languages sourceCodeFilePath = "static/sourcecode_3D.html" # simplefitter_3D TextUtils.SaveSourceCode(sourceCodeFilePath, equation) # create graphs graphFilePath_Surface = "static/surface.png" # surface plot graphFilePath_Contour = "static/contour.png" # contour plot surfaceTitle = "Example Surface Plot" contourTitle = "Example Contour Plot" xAxisLabel = "X data" yAxisLabel = "Y data" zAxisLabel = "Z data" GraphUtils.SurfaceAndContourPlots(graphFilePath_Surface, graphFilePath_Contour, equation, surfaceTitle, contourTitle, xAxisLabel, yAxisLabel, zAxisLabel) absErrorPlotFilePath = "static/abs_error_3D.png" # simplefitter_3D title = "Absolute Error For An HTML FORM Model" GraphUtils.SaveAbsErrorScatterPlot(absErrorPlotFilePath, equation, title, zAxisLabel) absErrorHistFilePath = "static/abs_error_hist_3D.png" # simplefitter_3D title = "Absolute Error" GraphUtils.SaveDataHistogram(absErrorHistFilePath, equation.modelAbsoluteError, title) if equation.dataCache.DependentDataContainsZeroFlag != 1: perErrorPlotFilePath = "static/per_error_3D.png" # simplefitter_3D title = "Percent Error For An HTML FORM Model" GraphUtils.SavePercentErrorScatterPlot(perErrorPlotFilePath, equation, title, zAxisLabel) perErrorHistFilePath = "static/per_error_hist_3D.png" # simplefitter_3D title = "Percent Error" GraphUtils.SaveDataHistogram(perErrorHistFilePath, equation.modelPercentError, title) # generate HTML htmlToReturn = '' htmlToReturn += equation.GetDisplayName() + '<br><br>\n' htmlToReturn += equation.GetDisplayHTML() + '<br><br>\n' htmlToReturn += '<a href="' + fitStatisticsFilePath + '">Link to parameter and fit statistics</a><br><br>\n' htmlToReturn += '<a href="' + sourceCodeFilePath + '">Link to source code, all available languages</a><br><br>\n' htmlToReturn += '<img src="' + graphFilePath_Surface + '"><br><br>\n' htmlToReturn += '<img src="' + graphFilePath_Contour + '"><br><br>\n' htmlToReturn += '<img src="' + absErrorPlotFilePath + '"><br><br>\n' htmlToReturn += '<img src="' + absErrorHistFilePath + '"><br><br>\n' if equation.dataCache.DependentDataContainsZeroFlag != 1: htmlToReturn += '<img src="' + perErrorPlotFilePath + '"><br><br>\n' htmlToReturn += '<img src="' + perErrorHistFilePath + '"><br><br>\n' return '<html><body>' + htmlToReturn + '</body></html>'
def simplefitter_2D_NoFormDataValidation(): formTextData = request.form['textdata'] formEquation = request.form['equation'] formFittingTarget = request.form['target'] if formEquation == 'Linear': equation = pyeq2.Models_2D.Polynomial.Linear(formFittingTarget) elif formEquation == 'Quadratic': equation = pyeq2.Models_2D.Polynomial.Quadratic(formFittingTarget) elif formEquation == 'Cubic': equation = pyeq2.Models_2D.Polynomial.Cubic(formFittingTarget) elif formEquation == 'WitchA': equation = pyeq2.Models_2D.Miscellaneous.WitchOfAgnesiA( formFittingTarget) elif formEquation == 'VanDeemter': equation = pyeq2.Models_2D.Engineering.VanDeemterChromatography( formFittingTarget) elif formEquation == 'GammaRayDegreesB': equation = pyeq2.Models_2D.LegendrePolynomial.GammaRayAngularDistributionDegreesB( formFittingTarget) elif formEquation == 'ExponentialWithOffset': equation = pyeq2.Models_2D.Exponential.Exponential( formFittingTarget, 'Offset') # the name of the data here is from the form # check for functions requiring non-zero nor non-negative data such as 1/x, etc. try: pyeq2.dataConvertorService().ConvertAndSortColumnarASCII( formTextData, equation, False) except: return equation.reasonWhyDataRejected # check for number of coefficients > number of data points to be fitted coeffCount = len(equation.GetCoefficientDesignators()) dataCount = len(equation.dataCache.allDataCacheDictionary['DependentData']) if coeffCount > dataCount: return "This equation requires a minimum of " + repr( coeffCount) + " data points, you supplied " + repr(dataCount) + "." equation.Solve() equation.CalculateModelErrors(equation.solvedCoefficients, equation.dataCache.allDataCacheDictionary) equation.CalculateCoefficientAndFitStatistics() # save fit statistics to a text file fitStatisticsFilePath = "static/fitstatistics_2D.txt" # simplefitter_2D TextUtils.SaveCoefficientAndFitStatistics(fitStatisticsFilePath, equation) # save source code to a single text file, all available languages sourceCodeFilePath = "static/sourcecode_2D.html" # simplefitter_2D TextUtils.SaveSourceCode(sourceCodeFilePath, equation) # create graph graphFilePath = "static/model_and_scatterplot_2D.png" # simplefitter_2D title = "Example Of An HTML FORM Model" xAxisLabel = "X data" yAxisLabel = "Y data" GraphUtils.SaveModelScatterConfidence(graphFilePath, equation, title, xAxisLabel, yAxisLabel) absErrorPlotFilePath = "static/abs_error_2D.png" # simplefitter_2D title = "Absolute Error For An HTML FORM Model" GraphUtils.SaveAbsErrorScatterPlot(absErrorPlotFilePath, equation, title, yAxisLabel) absErrorHistFilePath = "static/abs_error_hist_2D.png" # simplefitter_2D title = "Absolute Error" GraphUtils.SaveDataHistogram(absErrorHistFilePath, equation.modelAbsoluteError, title) if equation.dataCache.DependentDataContainsZeroFlag != 1: percentErrorPlotFilePath = "static/per_error_2D.png" # simplefitter_2D title = "Percent Error For An HTML FORM Model" GraphUtils.SavePercentErrorScatterPlot(percentErrorPlotFilePath, equation, title, yAxisLabel) perErrorHistFilePath = "static/per_error_hist_2D.png" # simplefitter_2D title = "Percent Error" GraphUtils.SaveDataHistogram(perErrorHistFilePath, equation.modelPercentError, title) # generate HTML htmlToReturn = '' htmlToReturn += equation.GetDisplayName() + '<br><br>\n' htmlToReturn += equation.GetDisplayHTML() + '<br><br>\n' htmlToReturn += '<a href="' + fitStatisticsFilePath + '">Link to parameter and fit statistics</a><br><br>\n' htmlToReturn += '<a href="' + sourceCodeFilePath + '">Link to source code, all available languages</a><br><br>\n' htmlToReturn += '<img src="' + graphFilePath + '"> <br>\n' htmlToReturn += '<img src="' + absErrorPlotFilePath + '"><br>\n' htmlToReturn += '<img src="' + absErrorHistFilePath + '"><br>\n' if equation.dataCache.DependentDataContainsZeroFlag != 1: htmlToReturn += '<img src="' + percentErrorPlotFilePath + '"><br><br>\n' htmlToReturn += '<img src="' + perErrorHistFilePath + '"><br><br>\n' return '<html><body>' + htmlToReturn + '</body></html>'
def textInterface(): # Get user input for expression def inputExpression(): while 1: while 1: print "\nPlease enter expression to evaluate [OR] q to return to the main menu" expression = raw_input(">> ").strip() if not expression: continue break if expression.lower() == "q": return None formatted = GraphUtils.formatExpression(expression) if not GraphUtils.validateFunction(formatted): print "The expression entered has unmatched brackets.\nPlease try again.\n" continue return expression # Menu options options = ["Evaluate an expression", "Set domain and range", "View a function in text", "View a function in the graph window", "Perform calculations from a text file", "Exit the program"] domain, rnge = [-10, 10], [-7.5, 7.5] # Pattern to match floats floatPattern = r"(\-|\+)?[0-9]+(\.[0-9]*)?" currentDom, currentRange = "%s,%s" % (str(domain[0]), str(domain[1])), "%s,%s" % (str(rnge[0]), str(rnge[1])) graphProcess = None running = True while running: # Display options to the user print "What would you like to do?" for i, option in enumerate(options): print " %d. %s" % (i + 1, option) choice = raw_input(">> ").strip() if choice == "1": expression = inputExpression() if expression == None: continue formatted = GraphUtils.formatExpression(expression) result = MathCalc.readEquation(formatted) if result == None: print "\nSorry the expression was not evaluated successfully.\n" else: print "\nResult: %s\n" % str(result) elif choice == "2": # Display the current domain and range to user print "\nCurrent domain and range:" print "%s <= x <= %s %s <= y <= %s\n" % (str(domain[0]), str(domain[1]), str(rnge[0]), str(rnge[1])) # Domain entry while 1: print "Please input the domain [OR] nothing to not alter it" print "Format: 'lowerX,upperX'" inp = raw_input(">> ").strip() if not inp: break # Match the user entered domain match = re.search(r"(%s) *\, *(%s)" % (floatPattern, floatPattern), inp) if match == None: print "Invalid input please try again.\n" continue domain = map(lambda s: float(s.strip()), match.group().split(",")) currentDom = "%s,%s" % (str(domain[0]), str(domain[1])) break print # Range entry while 1: print "Please input the range [OR] nothing to not alter it" print "Format: 'lowerY,upperY'" inp = raw_input(">> ").strip() if not inp: break # Match the user entered range match = re.search(r"(%s) *\, *(%s)" % (floatPattern, floatPattern), inp) if match == None: print "Invalid input please try again.\n" continue rnge = map(lambda s: float(s.strip()), match.group().split(",")) currentRange = "%s,%s" % (str(rnge[0]), str(rnge[1])) break print elif choice == "3": expression = inputExpression() if not expression: continue # Format the entered expression and draw the text graph expression = GraphUtils.formatExpression(expression) Graphing.commandLineDraw(expression, domain, rnge) elif choice == "4": expression = inputExpression() if expression == None: continue if graphProcess != None: if graphProcess.poll() == None: # Terminate previous graphing process graphProcess.terminate() graphProcess = createGraphProcess([expression], currentDom, currentRange) else: graphProcess = createGraphProcess([expression], currentDom, currentRange) else: graphProcess = createGraphProcess([expression], currentDom, currentRange) print elif choice == "5": print while 1: print "Please input the path to the file [OR] q to return to the main menu" inp = raw_input(">> ") if inp.lower() == "q": break try: fileContents = CLineReadFile.readFile(inp) except: print "Sorry", inp, "cannot be found or opened.\n" continue expressions = CLineReadFile.parseContents(fileContents) results = CLineReadFile.evalExpressions(expressions) # Display results print "============Results============" CLineReadFile.printResults(results) break print elif choice == "6": print "Goodbye!" running = False
def logFiles(self): fields = self.request().fields() baseName = fields.get('logPrefix', '') + 'messages' msgFileSeq = logDownload.findMessageFiles(baseName) result = self.doc.createElement('logfiles') if baseName in msgFileSeq: plainSize = os.stat('/var/log/' + baseName)[stat.ST_SIZE] plainSize = '(%s)' % \ GraphUtils.scale(plainSize, GraphUtils.SCALER_TENTHS_OF_BYTES, precision=1) fileEl = self.doc.createElement('file') fileEl.setAttribute('logName', 'Current Log') fileEl.setAttribute('uncompressedTitle', 'Download the current log as plain text') fileEl.setAttribute( 'uncompressedHref', '/mgmt/download?f=%s&type=plainlog' % baseName) fileEl.setAttribute('compressedTitle', '') fileEl.setAttribute('compressedHref', '') fileEl.setAttribute('plainSize', plainSize) result.appendChild(fileEl) msgFileSeq.remove(baseName) downloads = [] for num in [mf.split('.')[1] for mf in msgFileSeq]: if num not in downloads: downloads.append(num) downloads.sort(FormUtils.alphanumericCompare) downloads = [(num, '%s.%s' % (baseName, num), '%s.%s.gz' % (baseName, num)) for num in downloads] downloads = [(num, plain in msgFileSeq and plain or compressed, compressed in msgFileSeq and compressed or '') for num, plain, compressed in downloads] for num, plain, compressed in downloads: fileEl = self.doc.createElement('file') fileEl.setAttribute('logName', 'Archived log # ' + num) fileEl.setAttribute('uncompressedTitle', 'Download archived log # %s as plain text' % num) plainSize = '' if plain.endswith('.gz'): fileEl.setAttribute('uncompressedHref', '/mgmt/download?f=%s&type=gunzippedlog' % plain) else: fileEl.setAttribute('uncompressedHref', '/mgmt/download?f=%s&type=plainlog' % plain) plainSize = os.stat('/var/log/' + plain)[stat.ST_SIZE] plainSize = '(%s)' % \ GraphUtils.scale(plainSize, GraphUtils.SCALER_TENTHS_OF_BYTES, precision=1) compressedSize = '' if compressed: fileEl.setAttribute('compressedTitle', 'Download archived log # %s in gzip format' % num) fileEl.setAttribute('compressedHref', '/mgmt/download?f=%s&type=gzippedlog' % compressed) compressedSize = os.stat('/var/log/' + compressed)[stat.ST_SIZE] compressedSize = '(%s)' % \ GraphUtils.scale(compressedSize, GraphUtils.SCALER_TENTHS_OF_BYTES, precision=1) else: fileEl.setAttribute('compressedTitle', '') fileEl.setAttribute('compressedHref', '') fileEl.setAttribute('plainSize', plainSize) fileEl.setAttribute('compressedSize', compressedSize) result.appendChild(fileEl) self.doc.documentElement.appendChild(result) self.writeXmlDoc()
import networkx as nx import GraphUtils import bellMan, Djikstra gConf = GraphUtils.GraphUtils() # graphWhereDjikstraFails = {0: [(1, -1), (2, -2)], 1: [(2, 3), (3, 2), (4, 2)], 2: [], 3: [(2, -5), (1, 1)], 4: [(3, 3)]} graph = { 0: [(1, -1), (2, -2)], 1: [(2, 3), (3, 2), (4, 2)], 2: [], 3: [(2, 5), (1, 1)], 4: [(3, 3)] } labels = {0: "Hospital", 1: "Work", 2: "Shop", 3: "Grocery Store", 4: "Home"} source = 0 def djikstra(gConf, graph, G, labels, pos, source): try: # Calculating shortest distances and shortest path # from source node to every node path = Djikstra.driver(graph, source) # Creating graph from the above obtained path djiGraph, labels, eLabels = gConf.createGraphFromPath(G, path, labels) # Displaying the above created graph gConf.displayGraph(G=djiGraph, name="djikstraPath.jpeg", labels=labels, eLabels=eLabels, pos=pos) except ValueError:
def find_planarity(G): """ Searches *graph* for any subgraphs isomorphic to K(3, 3) or K(5). Complexity: O((n choose 6) + (n choose 5)) Args: graph (networkx.Graph): The graph to be searched Returns: bool, networkx.Graph: Planarity of the graph and either None or the detected Kuratowski graph """ planar = True offending_subgraph = None # Optimization step: # Remove nodes from graph with edge count > 1 and assign to new graph (don't alter original) outdeg = G.degree() to_keep = [n for n in outdeg if outdeg[n] > 1] graph = G.subgraph(to_keep) num_nodes = len(graph.nodes()) it = 0 k33 = GraphGenerator.make_k33_graph() k5 = GraphGenerator.make_k5_graph() if num_nodes > 5: # Test if graph contains a K(3, 3) subgraph. for subgraph_nodes in itertools.combinations(graph.nodes(), 6): it += 1 subgraph = graph.subgraph(subgraph_nodes) # If the subgraph is bipartite, get each set if bipartite.is_bipartite(graph): # subgraph? set1, set2 = bipartite.sets(graph) # subgraph? # If one set in a 6-node bipartite graph has 3 nodes, then the other # set has 3 nodes, making it a K(3, 3) graph. if len(set1) == 3: planar = False offending_subgraph = subgraph # Test for isomorphism if nx.is_isomorphic(subgraph, k33): planar = False offending_subgraph = subgraph if planar and num_nodes > 4: # Test if graph contains a K(5) subgraph. for subgraph_nodes in itertools.combinations(graph.nodes(), 5): it += 1 subgraph = graph.subgraph(subgraph_nodes) # If the graph is complete, it's a K(5) graph if GraphUtils.check_completeness(subgraph): planar = False offending_subgraph = subgraph # Test isomorphism if nx.is_isomorphic(subgraph, k5): planar = False offending_subgraph = subgraph print "Iterations (actual):", GraphUtils.format_commas(it) return planar, offending_subgraph
def set_nodes_and_edge_colors(self): [self.node_colors, self.positions, self.edge_colors] = GraphUtils.set_nodes_and_edge_colors(self.graph)