def task_3(sequence_length, phase_filtering): polyharmonic_sequence = generate_polyharmonic_sequence(sequence_length) direct_transformer = DirectFourierTransformer(polyharmonic_sequence) amplitude_spectrum = direct_transformer.get_amplitude_spectrum() phase_spectrum = [ x if amplitude_spectrum[i] > phase_filtering else 0 for i, x in enumerate(direct_transformer.get_phase_spectrum()) ] restored_sequence = InverseFourierTransformer( amplitude_spectrum, phase_spectrum).restore_polyharmonic(True) restored_sequence_without_phases \ = InverseFourierTransformer(amplitude_spectrum, phase_spectrum).restore_polyharmonic(False) drawer = GraphDrawer() drawer.add_plot( Graph(range(sequence_length), polyharmonic_sequence, "Original sequence")) drawer.add_stem( Graph(range(sequence_length), amplitude_spectrum, "Amplitude spectrum")) drawer.add_stem( Graph(range(sequence_length), phase_spectrum, "Phase spectrum")) drawer.add_plot( Graph(range(sequence_length), restored_sequence, "Restored sequence")) drawer.add_plot( Graph(range(sequence_length), restored_sequence_without_phases, "Restored sequence w/o phase spectrum")) drawer.draw() drawer.show()
def assessment_page(): """ This is the assessment category page. This method is used to generate the graphs and talbes that display on the page. """ graph = Graph() # assessment_count = graph.assessment_count() # assessment_avgtone = graph.assessment_avgtone() maine_html_table = graph.table_generator("main_nummen_assessment", "assessment") student_html_table = graph.table_generator("student_nummen_assessment", "assessment") US_html_table = graph.table_generator("US_nummen_assessment", "assessment") FL_html_table = graph.table_generator("FL_nummen_assessment", "assessment") return render_template( 'assessment.html', maine_html_table=maine_html_table, student_html_table=student_html_table, US_html_table=US_html_table, FL_html_table=FL_html_table, # assessment_avgtone=assessment_avgtone, # assessment_count=assessment_count )
def curri_page(): """ This is the curriculum category page. This method is used to generate the graphs and tables that display on this page. """ # The Graph class is instantiated and assigned to the graph variable. graph = Graph() CA_distplot = graph.curri_distplot("ca_avgtone_curri_topstates", "California") TX_distplot = graph.curri_distplot("tx_avgtone_curri_topstates", "Texas") MA_distplot = graph.curri_distplot("ma_avgtone_curri_topstates", "Massachusetts") NY_distplot = graph.curri_distplot("ny_avgtone_curri_topstates", "New York") CA_html_table = graph.table_generator("ca_curri_topstates", "curriculum") TX_html_table = graph.table_generator("tx_curri_topstates", "curriculum") MA_html_table = graph.table_generator("ma_curri_topstates", "curriculum") NY_html_table = graph.table_generator("ny_curri_topstates", "curriculum") return render_template('curriculum.html', CA_distplot=CA_distplot, TX_distplot=TX_distplot, MA_distplot=MA_distplot, NY_distplot=NY_distplot, CA_html_table=CA_html_table, TX_html_table=TX_html_table, MA_html_table=MA_html_table, NY_html_table=NY_html_table)
def charter_schools_page(): """ This is the charter school category page. This method is used to generate the graphs and tables that display on the page. """ graph = Graph() # This line can be used to generate the avgtone/nummention line plot again if needed. # I left it commented out because there are a lot of data points and it takes a long time # to load. # lineplot_url = graph.charter_lineplot() top10_us_url = graph.buzzwords_graph("keyword_count") # I used the highest number of mentions from 2014-2015 to create this table top_20_20142015 = graph.table_generator("charter_schools_20142015", "charter-school") # I used the lowest number of mentions from 2014-2015 to create this table top_20_20152016 = graph.table_generator("charter_schools_20152016", "charter-school") # I used the lowest number of mentions from 2014-2015 to create this table top_20_2017pres = graph.table_generator("charter_schools_2017pres", "charter-school") return render_template( 'charter-schools.html', top10_us_url=top10_us_url, # lineplot_url=lineplot_url, top_20_20142015=top_20_20142015, top_20_20152016=top_20_20152016, top_20_2017pres=top_20_2017pres)
def explore_reccursively( self, word: str, max_depth: int = 2, current_depth=1, _previous_graph=None, ) -> Graph: """Search for terms reccursively from the website Args: word (str): the word max_depth (int): the deepth of the reccursion Returns: a Graph object with the words that were looked up """ logging.debug( f"Exploring with word '{word}' current depth is '{current_depth}'") if not isinstance(max_depth, int): raise TypeError( f"max_depth type should be int not '{type(max_depth)}'") if not _previous_graph: # initializing the Graph for the 1st time graph = Graph() # adding the root source graph.add_root_word(word) else: graph = _previous_graph if current_depth - 1 == max_depth: # reccursion ends return graph else: new_words = [w for w in self._get_results_from_website(word) if w] logging.info(f"{len(new_words)} found") for n_word in new_words: if self.unidecode_word: n_word = unidecode(n_word.lower()) else: n_word = n_word.lower() if n_word in graph: logging.debug( f"n_word is already in the graph -> skipping it") continue graph.add_word(n_word, current_depth, "synonym", word, comesFrom=self.website) graph = self.explore_reccursively( n_word, current_depth=current_depth + 1, max_depth=max_depth, _previous_graph=graph, ) return graph
def roadsAndLibraries(n, c_lib, c_road, cities): # Complete this function if not n: return 0 if c_lib <= c_road: return n * c_lib graph = Graph() # for _n in range(n): # graph.addVertex(Vertex(str(_n+1))) for edge in cities: try: graph.addVertex(Vertex(str(edge[0]))) except KeyError: pass try: graph.addVertex(Vertex(str(edge[1]))) except KeyError: pass graph.createEdge(str(edge[0]), str(edge[1])) print graph.degree subgraphs = graph.listSubGraphs() print subgraphs libraries = len(subgraphs) + (n - graph.degree) roads = 0 for g in subgraphs: roads += len(g) - 1 return (libraries * c_lib) + (roads * c_road)
def run(data): servers = Graph(data, Transformer, " - ", ": ", oriented=True) res = {} out = "" for node in servers.nodes: if not out: out = node best = float("inf") for neighbour in servers.nodes[node].neighbours(): if neighbour in res.keys(): continue path, cost = servers.dijkstra(node, neighbour) if cost < best: best = cost res[node] = path total = 0 to_unpack = len(res) while to_unpack: key = out[-1] direction = res[key].pop() total += servers.vertex_cost(key, direction) out = out + " - " + direction to_unpack -= 1 print(out + ": " + str(total))
def test_graph_creation(): login, passwd = get_login_password() from vkwrapper import Vk from graphs import Graph v = Vk(cache=FileCache(), login=login, password=passwd) g = Graph(v, "238696131")
def run(data): data_lower = [] data_upper = [] for line in data: if line[0].istitle(): data_upper.append(line) else: data_lower.append(line) lower_towns = Graph(data_lower, Town, " -> ") upper_towns = Graph(data_upper, Town, " -> ") new_routes, to_delete = fuse(lower_towns.nodes, upper_towns.nodes) print_routes(new_routes) print("----") print_routes(to_delete)
def test_breadth_first(): g = Graph() v1 = g.add_node('Pandora') v2 = g.add_node('Mordor') g.add_nondirectional_edge(v1, v2, 110) expected = ['Pandora', 'Mordor'] actual = g.breadth_first(v1) assert expected == actual
def test_get_nodes(): graph = Graph() graph.add_node('coffee') graph.add_node('muffin') Vertex('loner') expected = 2 actual = len(graph.get_nodes()) assert actual == expected
def setUp(self): n6 = Node(6) n5 = Node(5, [n6]) n4 = Node(4, [n6]) n3 = Node(3, [n4, n5]) n2 = Node(2, [n4]) n1 = Node(1, [n2, n3]) self.g = Graph([n1, n2, n3, n4, n5, n6])
def test_add_edge_effect_with_weight(): graph = Graph() end = graph.add_node('coffee') start = graph.add_node('muffin') graph.add_edge(start, end, 44) expected = (end, 44) actual = graph._adjacency_list[start][0] assert actual == expected
def run(data): people = Graph(data, Person, " - ") groups = people.get_groups_a2() # hax groups groups = hax_one_member_grp(people.nodes, groups) for group in sorted(groups): print(", ".join(g for g in group))
def test_add_edge_interloper_start(): graph = Graph() start = Vertex('start') end = graph.add_node('end') with pytest.raises(KeyError): graph.add_edge(start, end)
def knightsGraph(board_size=8): g = Graph() for row in range(board_size): for col in range(board_size): currPos = getNormalizedPos(row, col, board_size) newPos = getPossiblePositions(row, col, board_size) for pos in newPos: g.addEdge(currPos, pos) return g
def test_graph_duplicating_edges(): login, passwd = get_login_password() from vkwrapper import Vk from graphs import Graph v = Vk(cache=FileCache(), login=login, password=passwd) g = Graph(v, "238696131") assert g.g.is_simple() == True
def test_get_neighbors(): graph = Graph() end = graph.add_node('coffee') start = graph.add_node('muffin') graph.add_edge(start, end, 44) neighbors = graph.get_neighbors(start) assert len(neighbors) == 1 assert neighbors[0][0].value == 'coffee' assert isinstance(neighbors[0][0], Vertex) assert neighbors[0][1] == 44
def allMoves(bdSize): ktGraph = Graph() for row in range(bdSize): for col in range(bdSize): nodeId = posToNodeId(row, col, bdSize) newPositions = genAllMoves(row, col, bdSize) for e in newPositions: nid = posToNodeId(e[0], e[1], bdSize) ktGraph.addEdge(nodeId, nid) return ktGraph
def test_graph_get_community_labels(): login, passwd = get_login_password() from vkwrapper import Vk from graphs import Graph v = Vk(cache=FileCache(), login=login, password=passwd) g = Graph(v, "238696131") g.get_community_labels()
def read_edge_list_graph(infile): """Parse an edge-list formatted graph from `infile`.""" num_vertices = int(infile.readline()) graph = Graph(range(num_vertices)) for line in infile: source, target = line.split(' ') graph.add_edge(int(source), int(target)) return graph
def test__graph_get_community_labels_sparse_graph(): login, passwd = get_login_password() from vkwrapper import Vk from graphs import Graph v = Vk(cache=FileCache(), login=login, password=passwd) g = Graph(v, "148907612") g.get_community_labels()
def test_it_can_topo_sort_a_graph(self): n5 = Node(105) n3 = Node(103, [n5]) n4 = Node(104) n2 = Node(102, [n3, n4, n5]) n1 = Node(101, [n2, n4]) g = Graph([n1, n2, n3, n4, n5]) topoSorted = g.topo_sort() r = g.min_path(topoSorted) self.assertEqual(r, [1, 2, 3, 4, 5])
def erdos_renyi(n, p): g = Graph() for i in xrange(n): g.add_node(DiscreteVariable([0, 1], name=str(i))) for i, j in itertools.product(xrange(n), xrange(n)): if random.random() < p: g.add_edge(g.get_node_by_name(str(i)), g.get_node_by_name(str(j))) return g
def setUp(self): """Test case set up.""" routes = [ ('Mumbai', 'Paris'), ('Mumbai', 'Dubai'), ('Paris', 'Dubai'), ('Paris', 'New York'), ('Dubai', 'New York'), ('New York', 'Toronto'), ] self.graph = Graph(routes)
def knight_graph(board_size): # Build the graph graph = Graph() for row in range(board_size): for col in range(board_size): node_id = pos_to_node_id(row, col, board_size) new_positions = generate_legal_moves(row, col, board_size) for e in new_positions: nid = pos_to_node_id(e[0], e[1], board_size) graph.add_edge(node_id, nid) return graph
def makeGrid(x, y): nV = x * y g = Graph(nV) for j in xrange(1, y + 1): linBeg = (j - 1) * x + 1 for i in xrange(x): if (i < (x - 1)): g.addE(linBeg + i, linBeg + i + 1) if (j != y): g.addE(linBeg + i, linBeg + i + x) return g
def knightGraph(bdSize): ktGraph = Graph() for row in range(bdSize): for col in range(bdSize): #import pdb; pdb.set_trace() nodeId = posToNodeId(row, col, bdSize) newPositions = genLegalMoves(row, col, bdSize) for e in newPositions: nid = posToNodeId(e[0], e[1], bdSize) ktGraph.addEdge(nodeId, nid) # import pdb; pdb.set_trace() return ktGraph
def run(data): compound1 = Graph([data[0]], Component, "-") compound2 = Graph([data[1]], Component, "-") print("* |U1| = |U2|: " + str(subtask0(compound1, compound2)).lower()) print("* |H1| = |H2|: " + str(subtask1(compound1, compound2)).lower()) print( "* Jsou-li u, v sousední uzly, pak i (u), (v) jsou sousední uzly: " + str(subtask2(compound1, compound2)).lower() ) print( "* Grafy mají stejnou posloupnost stupňů uzlů: " + str(subtask3(compound1, compound2)).lower() ) print("* Pak pro každý uzel v z U platí") print( "\t– stupeň uzlu v je roven stupni uzlu φ(v): " + str(subtask4(compound1, compound2)).lower() ) print( "\t– množina stupňů sousedů uzlu v je rovna množině stupňů " "sousedů uzlu φ(v): " + str(subtask5(compound1, compound2)).lower() ) print("* Pak pro každý sled platí") print( "\t– obraz sledu je opět sled: " + str(subtask6(compound1, compound2)).lower() ) print( "\t– obraz tahu je opět tah: " + str(subtask7(compound1, compound2)).lower() ) print( "\t– obraz cesty je opět cesta: " + str(subtask8(compound1, compound2)).lower() ) print( "\t– délka sledu zůstává zachována: " + str(subtask9(compound1, compound2)).lower() )
def task_5(sequence_length, phase_filtering, low, high): polyharmonic_sequence = generate_polyharmonic_sequence(sequence_length) direct_transformer = DirectFourierTransformer(polyharmonic_sequence) amplitude_spectrum = direct_transformer.get_amplitude_spectrum() phase_spectrum = [ x if amplitude_spectrum[i] > phase_filtering else 0 for i, x in enumerate(direct_transformer.get_phase_spectrum()) ] filtered = filter_spectrum(Spectrum(amplitude_spectrum, phase_spectrum), low, high) restored = InverseFourierTransformer( filtered.amplitude, filtered.phase).restore_polyharmonic() drawer = GraphDrawer() drawer.add_plot( Graph(range(sequence_length), polyharmonic_sequence, "Original sequence")) drawer.add_stem( Graph(range(sequence_length), amplitude_spectrum, "Amplitude spectrum")) drawer.add_stem( Graph(range(sequence_length), phase_spectrum, "Phase spectrum")) drawer.add_stem( Graph(range(sequence_length), filtered.amplitude, "Filtered amplitude")) drawer.add_stem( Graph(range(sequence_length), filtered.phase, "Filtered phase")) drawer.add_plot( Graph(range(sequence_length), restored, "Restored filtered")) drawer.draw() drawer.show()