def find_percent_decrease(experiment, month, wavelength, date=None): csvs = get_csvs(path_arr=['processed', month, wavelength, date]) cf.go_offline() emit_data = [] for csv in csvs: headers = experiment_variables.get_header(wavelength, csv.stem) df1 = pd.read_csv(str(csv), names=headers, index_col=0) df1 = df1[1:] df1 = df1.apply(pd.to_numeric, errors='ignore') decreases = experiment_variables.determine_decrease( wavelength, df1, csv.stem) print('Calculating % diff for {} at {} nm'.format( csv.stem, wavelength)) flavonoid = csv.stem emit = { 'flavonoid': csv.stem, 'control': decreases['control'], 'experiment': decreases['experiment'], 'percent decrease': decreases['percent'] } emit_data.append(emit) df2 = pd.DataFrame( emit_data, columns=['flavonoid', 'control', 'experiment', 'percent decrease']) control_experiment = graph.graph(df2, kind='bar', barmode='group', x='flavonoid', y=['control', 'experiment'], yTitle='%', xTitle='Flavanoid', title='% Decrease', asFigure=True) percent_dec_graph = graph.graph(df2, kind='bar', barmode='group', x='flavonoid', y='percent decrease', yTitle='%', xTitle='Flavanoid', title='% Decrease', asFigure=True) df2 = df2.set_index('flavonoid') csv_file = '{}.csv'.format(wavelength) control_exp_html = 'control_exp_{}.html'.format(wavelength) percent_dec_html = 'precent_decrease_{}.html'.format(wavelength) print('Creating bar graph...') analysis_path = Output() \ .make_path(['analysis', 'decrease', experiment]) \ .output_csv(df2, csv_file) \ .output_html(control_experiment, control_exp_html) \ .output_html(percent_dec_graph, percent_dec_html)
def computorv1(string, param=0): params(param) exit_error.status = False split_eq = parser(string) if (exit_error.status == True): return reduced_eq = reduce(split_eq) print_eq(reduced_eq, "Reduced form:\t") degree = reduced_eq[0][0] print "Polynomial degree: %g" % degree if (degree > 2): print( "The polynomial degree is strictly greater than 2, I can't solve.") else: (x1, x2) = solve(reduced_eq, degree) if x1 is not None and x2 is not None: if params.graph: import graph formula = "" for i, s in enumerate(reduced_eq): formula += ("+" if (s[1] > 0 and i > 0) else "") + "%g" % s[1] + \ ("*x" if s[0] > 0 else "") + ("**%g" % s[0] if s[0] > 1 else "") x1 -= 10 x2 += 10 graph.graph(formula, int(round(x1)), int(round(x2))) return
def rank_and_freq(self, count_noun: list) -> None: ''' 単語の頻度を降順で並べたものに順位をつける。 ''' # 順位 rank_num = 1 # ループ総回数のカウンター counter = 1 # 最小値 min_num = 1000000 # グラフで使うための縦軸・横軸のリストをセット rank_list = [] freq_list = [] # 名詞と出現回数を全部出力 for key, count in count_noun.most_common(): # 単語の出現回数が同じ場合、順位を同率にしておく # if min_num == count: # print( "{0}位 {1} : {2}".format( rank_num, key, str(count) ) ) # print(str(count)) rank_list.append(rank_num) freq_list.append(count) # 出現回数が異なる場合は、裏でループ回数を数えていたnumから値を受け取り順位を更新 # elif min_num > count: min_num = count rank_num = counter # print( "{0}位 {1} : {2}".format( rank_num, key, str(count) ) ) # print(str(count)) rank_list.append(rank_num) freq_list.append(count) counter += 1 graph.graph(rank_list, freq_list, self.__text_file_path)
def menu(): # the user is asked to enter each of the settings, # settings are stored in placeholder variables and sent to the database if choice == 1: user_too_low_temp = int( input("Enter in Fahrenheit the Temperature deemed too low: ")) user_just_right_temp = int( input("Enter in Fahrenheit the Temperature deemed just right: ")) user_too_high_temp = int( input("Enter in Fahrenheit the Temperature deemed too high: ")) user_humidity_limit = int( input("Enter the humidity limit without the % symbol: ")) user_light_threshold = int(input("Enter the light threshold value: ")) Database.send_settings_to_firebase(user_too_low_temp, user_just_right_temp, user_too_high_temp, user_humidity_limit, user_light_threshold) print("Your settings have been configured\n") print("The system will now run") elif choice == 2: # runs the function which displays the graph of temperature and humidity print("Here is your Graph!") graph.graph() else: # Any integer inputs other than values 1-2 print an error message raw_input("Wrong option selection. Enter any key to try again..")
def menu2(companydata, companylist, comindex): utils.cls() print("=" * 26, "You selected", "=" * 26) print((companylist.iloc[int(comindex)])) loop = True while loop: print("\n" + "=" * 25 + "Stock Options" + "=" * 25) print("\nSelect options (1-6):") print("1. Summary") print("2. Graph") print("3. Historical Data") print("4. Future Prediction") print("5. Go back to previous menu") print("6. Exit") option = input( "\nYour option: ").lstrip() if option == '1': summary(companydata) elif option == '2': graph(companylist, comindex), elif option == '3': historicaldata(companydata), elif option == '4': prediction(companydata), elif option == '5': menu() elif option == '6': print("\nThanks for coming. Please visit again ...\n") loop = False exit() else: print("\nWrong option. Try again ...")
def main(): args = sys.argv[1:] if len(args) < 1: logging.warning('Usage: python <filename> <function> <parameters..>') elif args[0] == 'init': init() elif args[0] == 'add': data_to_copy_path = args[1] add(data_to_copy_path) elif args[0] == 'commit': message = args[1] commit(message) elif args[0] == 'status': status() elif args[0] == 'checkout': commit_id = args[1] checkout(commit_id) elif args[0] == 'graph': graph() elif args[0] == 'branch': branch_name = args[1] branch(branch_name) elif args[0] == 'merge': branch_name = args[1] merge()
def quadratic(eq, x): eqn = eq abc = [0, 0, 0] term(eq, abc) c = abc[0] b = abc[1] a = abc[2] determinant = b * b - 4 * a * c res = "" # condition for real and different roots if (determinant > 0): # sqrt() function returns square root root1 = (-b + (determinant**.5)) / (2 * a) root2 = (-b - (determinant**.5)) / (2 * a) addpts([root1, root2], [0, 0]) res = f"\t\t{x} = ({round(root1,2)},{round(root2,2)})\n" #condition for real and equal roots elif (determinant == 0): root1 = root2 = -b / (2 * a) addpts([root1], [0]) res = f"\t\t {x} = {root1}\n" # if roots are not real else: realPart = -b / (2 * a) imaginaryPart = (-determinant)**.5 / (2 * a) root1 = root2 = -b / (2 * a) res = f"\t\t{x} =( {round(realPart,2)}+i{round(imaginaryPart,2)} , {round(realPart,2)}-i{round(imaginaryPart,2)})\n" xpts = np.linspace(-2 - min(root1, root2), 2 + max(root1, root2), 1000) ypts = [list(map(lambda x: a * x**2 + b * x + c, xpts))] graph(xpts, ypts, [eqn], "Quadratic Equations") return res
def play_pooo(): """Active le robot-joueur """ global MATCHES logging.info('Entering play_pooo fonction from {} module...'.format(inspect.currentframe().f_back.f_code.co_filename)) logging.getLogger().setLevel(logging.WARNING) Mafenetre = Tk() Canevas = Canvas(Mafenetre, width = 500, height =500, bg ='white') Canevas.pack(padx =5, pady =5) while True: # On récupère et parse le nouvel état reçu. new_state = poooc.state_on_update() new_state = protocol.parse_message(new_state) if not new_state: continue # Si le match est en cours, on le met à jour puis on récupère la # stratégie à adopter qu'on encode et envoie. matchid = new_state['matchid'] if matchid in MATCHES: if new_state['type'] in ('gameover', 'endofgame'): del MATCHES[matchid] elif new_state['type'] == 'state': current_match = MATCHES[matchid] current_match.update(new_state) orders = current_match.compute_strategy() for order in orders: order = protocol.encode_order(UUID, order) poooc.order(order) graph.graph(Canevas,current_match) Mafenetre.update()
def test(localIP, file='shrimp.avi', config='vegas', port='9999', type='', show=True, remake=False): # Get local and remote node names local_node = socket.gethostname() remote_node = name() print "The local machine is: " + local_node print "The remote machine is: " + remote_node # Start server on a separate thread locally t = ThreadRunServer(config, port, remake) t.start() # Start client on the remote machine start_client(localIP, file, port, remake) # Wait for the transaction to finish t.join() # Get the log_name generated by ctcp and make it into an absolute path log_name= q.get() path = os.path.abspath(os.path.join(os.path.dirname(__file__), log_name)) "Fab: show is " + str(show) # Graph the log graph.graph(path, keyword=type, local_node=local_node, remote_node=remote_node, showGraph=show)
def testAddEmptyGraph(self): gr1 = graph.graph() gr1.generate(25, 100) gr1c = copy.copy(gr1) gr2 = graph.graph() gr1.add_graph(gr2) self.assertTrue(gr1.nodes() == gr1c.nodes()) self.assertTrue(gr1.edges() == gr1c.edges())
def main(): n = int(input("\n\tNumber to calculate firts n-Cubes: ")) # cube ( n ): Return the _sum of the first 'n' cubes, the computational time # of the algorithm and a list of the sum of nth cubes. _sum, count, cubelist = cube(n) print("\n\tThe sum of the first ", n, " cubes is: C ( ", n, " ) = ", _sum, "\n") graph(_sum, count, cubelist, n)
def main(): n = -1 while (n <= 0): n = int(input("\n\tFibonacci Number to Calculate: ")) # fibonacci ( n ): Return the fibonacci number, the counter that takes to # find that number, and a list of the fibonacci numbers before 'fibo'. fibo, count, f = fibonacci(n) print("\n\tFibonacci ( ", n, " ): ", fibo, "\n") graph(count, fibo, f, n)
def testAddGraph(self): gr1 = graph.graph() gr1.generate(25, 100) gr2 = graph.graph() gr2.generate(40, 200) gr1.add_graph(gr2) for each in gr2.nodes(): self.assertTrue(each in gr1) for each in gr2.edges(): self.assertTrue(each in gr1.edges())
def main(): parser = argparse.ArgumentParser() parser.add_argument("--subfolder", required=True, type=str, help="Folder data is in") parser.add_argument("--start_range", type=int, help="Start timestamp of zoom region") parser.add_argument("--end_range", type=int, help="End timestamp of zoom region") args = parser.parse_args() results = parse(args.subfolder) colors = ["red", "blue"] labels = ["Number of VCPUs", "Number of Running Jobs"] graph.graph(args.subfolder, results, colors, labels, args.start_range, args.end_range)
def main(): parameters = [] n = int(input("\n\tNumber to calculate firts n-Cubes: ")) # cube ( n ): Return a list of tuples with the sum of the numbers to the # power '3' and the Computational Time of the Algorithm [ ( C ( n ), T ( n ) ) ]. for i in range(1, n + 1): parameters.append(cube(i, 0)) print("\n\tCubesum ( ", n, " ): ", parameters[len(parameters) - 1][0], "\n") graph(parameters[len(parameters) - 1], parameters, n)
def main ( ): menu ( ) for i in range ( len ( gb.n ) + 1 ): m, gb.time = gb.n [ :i ], 0 quicksort ( m, 0, len ( m ) - 1 ) gb.parameters.append ( ( len ( m ), gb.time ) ) print ( "\n\tSorted list: ", m, "\n" ) print ( "\n\tQuicksort Parameters: ", gb.parameters ) print ( "\n\tPartition Parameters: ", gb._parameters ) graph ( )
def main(): n, parameters = -1, [] while (n <= 0): n = int(input("\n\tFibonacci Number to Calculate: ")) # fibonacci ( n ): Return a list of tuples with the Fibonacci numbers # and the Computational Time of the Algorithm [ ( F ( n ), T ( n ) ) ]. for i in range(1, n + 1): parameters.append(fibonacci(i, 0)) print("\n\tFibonacci ( ", n, " ): ", parameters[len(parameters) - 1][0], "\n") graph(parameters[len(parameters) - 1], parameters, n)
def ask(): # Introduces current time as a variable now = datetime.datetime.now() # Asks for wanted stock print("Which stock would you like to check? (Keep it simple)") a = input() # Lines 55 - 58 sends the information from symbol2.symbol2(), sends it to # stocks.getPriceHistory() to be used for graphing information, which then returns # back and is sent to graph.graph(). stockAndName = symbol2(a) print("") graphData = getPriceHistory(stockAndName, now) graph(graphData)
def main(**args): # Read log projectRoot = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) logFilename = os.path.join(projectRoot, 'experiments', args['experimentName'], '%s.log' % args['experimentName']) dfs = read_log(logFilename) # Create plot plotFile = os.path.join(projectRoot, 'experiments', args['experimentName'], '%s.svg' % args['experimentName']) graph(dfs, args['experimentName'], plotFile)
def main(): random_seeds = np.random.randint(2320602665, size=cpu_count()) pool = Pool(processes=cpu_count()) results = pool.map(compute, random_seeds) for parameters, backup in results: print("Do graph.") graph(results=backup, parameters=parameters, root_folder=path.expanduser("~/Desktop/MoneyBootstrapping"), root_name="MB")
def linear(eq, x): eqn = eq f0 = "" f1 = "" g0 = "" g1 = "" k = 0 for i in range(len(eq)): if (eq[i] == '='): k = 1 break if (not k): eq += '=0' i = 0 while eq[i] != '=': if (eq[i] != x): f0 += eq[i] f1 += eq[i] else: if ((eq[i - 1]).isdigit() and i != 0): f0 += '*' f1 += '*' k += 1 f0 += '0' f1 += '1' k += 1 i += 1 i += 1 while i < len(eq): if (eq[i] != x): g0 += eq[i] g1 += eq[i] else: if (isdigit(eq[i - 1])): g0 += '*' g1 += '*' k += 1 g0 += '0' g1 += '1' k += 1 i += 1 num = (arithEq(f0) - arithEq(g0)) den = (arithEq(f0) - arithEq(g0) - arithEq(f1) + arithEq(g1)) res = round(num / den, 2) xpts = np.linspace(-10, 10, 1000) ypts = list(np.array(res * np.ones(len(xpts)))) if (x == 'x' or x == 'X'): graph(ypts, [xpts], [eqn], "Linear Equations") if (x == 'y' or x == 'Y'): graph(xpts, [ypts], [eqn], "Linear Equations") return f"\t\t{x} = {res}\n"
def main(): args = parse_arguments() train = Train(args.data_file, args.iteration, args.learning_rate, args.precision) if args.square: train.train_with_least_square() else: train.normalize_data() train.train(args.animation) if args.animation: animation_lr(train.data, train.history_gradient) if args.graph: graph(train.data, train.theta_0, train.theta_1) train.dump_theta_values()
def main(): parser = argparse.ArgumentParser() parser.add_argument("--bucket", type=str, required=True, help="Log bucket") parser.add_argument("--subfolder", type=str, required=True, help="Subfolder to download results in") parser.add_argument("--parameters", type=str, required=True, help="Location of JSON parameter file") parser.add_argument("--start_range", type=int, help="Start timestamp of zoom region") parser.add_argument("--pending", default=False, action="store_true") parser.add_argument("--end_range", type=int, help="End timestamp of zoom region") parser.add_argument("--increment", type=int, required=True) parser.add_argument("--max_y", type=int) parser.add_argument("--download", default=False, action="store_true", help="Download the data") parser.add_argument("--legend", default=False, action="store_true") parser.add_argument("--old", default=False, action="store_true", help="Old save format") args = parser.parse_args() params = json.loads(open(args.parameters).read()) if args.download: download(args.subfolder, args.bucket, params) [lambda_ranges, task_ranges, pending_tasks] = process(args.subfolder, params, args.old) if args.pending: colors = ['#003300', '#ff3300', '#883300'] labels = [ "Number of VCPUs", "Number of Running Jobs", "Number of Total Jobs" ] else: colors = ['#003300', '#ff3300'] #, '#883300'] labels = ["Number of VCPUs", "Number of Running Jobs"] #, "Number of Total Jobs"] pending_tasks = None print(args.increment) graph.graph(args.subfolder, [lambda_ranges, task_ranges], colors, pending_tasks, labels, args.start_range, args.end_range, args.max_y, args.increment, args.legend)
def test_add_spanning_tree(self): gr = graph() st = {0: None, 1: 0, 2:0, 3: 1, 4: 2, 5: 3} gr.add_spanning_tree(st) for each in st: self.assertTrue((each, st[each]) in gr.edges() or (each, st[each]) == (0, None)) self.assertTrue((st[each], each) in gr.edges() or (each, st[each]) == (0, None))
def test_cutsets(self): # this is the big one. # total number of f-cutsets in a given graph = (len(g.nodes())-1) # start with a non-directed graph g = pygraph.graph() # add some nodes. g.add_nodes(range(1,11)) # add some edges for each in range(1,10): g.add_edge(each,each+1) # find all cutsets that divide the graph into 2 graphs. # the third parameter is set to the max number of cuts to return # in this case, we know that there are at most 9 cuts, # (because of the 9 edges) gsets = cutsets(g,2,len(g.edges())/2) self.assertTrue(len(gsets)==len(g.edges())/2) # this only holds for pygraph.graph (not pygraph.digraph) self.assertTrue(len(gsets)==len(g.nodes())-1) # directed graph test. g2 = pygraph.digraph() g2.add_nodes(range(1,11)) for each in range(1,10): g2.add_edge(each,each+1) self.assertTrue(countGraphs(makeCut([1,2],g2)) == 2) g2sets = cutsets(g2,2) self.assertTrue(len(g2sets)==len(g.nodes())-1)
def test_complete_graph(self): gr = graph() gr.add_nodes(range(10)) gr.complete() for i in range(10): for j in range(10): self.assertTrue((i, j) in gr.edges() or i == j)
def main(): config = ConfigParser.SafeConfigParser() config.read('/opt/raumServiceDeamon/src/deamon.cfg') dataPool = {'security': {'motion': False, 'door': False, 'motion_C': "CLOSED"}, 'weather': {'out': 0.0, 'rain': False, 'in': 0.0}} checkRRD(config) signal.signal(signal.SIGINT, kill_signal_handler) signal.signal(signal.SIGTERM, kill_signal_handler) #fillDummyData(dataPool) # DEBUG t = UploadDeamon(config, dataPool) t.start() tem = temperatur(config, dataPool) tem.start() sec = security(config, dataPool, t) sec.start() gra = graph(config) gra.start() global ser ser = service(dataPool) ser.start()
def calculate_single(_id): # 转发树(全树与子树计算) g = graph(_id) whole_g = g['whole'] sub_g = g['sub'] whole_g_graph = whole_g['graph'] whole_g_stats = whole_g['stats'] whole_g_reposts = whole_g['reposts'] if sub_g['ori']:#转发微博 sub_g_graph = sub_g['graph'] sub_g_stats = sub_g['stats'] sub_g_reposts = sub_g['reposts'] save_weibo_tree(str(_id), whole_g_graph, whole_g_stats, sub_g_graph, sub_g_stats) calculate_single_whole(whole_g_reposts, whole_g['ori'], sub_g['ori']) calculate_single_sub(sub_g_reposts, sub_g['ori']) else:#原创微博 sub_g_graph = whole_g['graph'] sub_g_stats = whole_g['stats'] sub_g_reposts = whole_g['reposts'] save_weibo_tree(str(_id), whole_g_graph, whole_g_stats, whole_g_graph, whole_g_stats) calculate_single_whole(whole_g_reposts, whole_g['ori'], whole_g['ori']) calculate_single_sub(whole_g_reposts, whole_g['ori']) return 'Done'
def test_constructor(): test = g.graph_node('test') assert test.name == 'test' assert test.edge_list == [] test = g.graph('graph') assert test.name == 'graph' assert test.node_dict == {}
def main(): cfg = readConfig(gcfg( )) cseed = 0 if cfg[GRAPH][SEED] == 'random': cseed = seed( ) else: cseed = float(cfg[GRAPH][SEED]) random.seed(cseed) lg = log( cfg, cseed, gcfg( ) ) best = False for i in range( int(cfg[MAIN][TOTAL_RUNS]) ): puz=graph(conf=cfg, quiet=True) if i == 0: renderHead(cfg) nbest = runner.manSeq( puz, cfg, lg, i ) if best == False or nsgabetter(nbest, best): #lg.newBest( nbest ) if best != False: best.delete( ) best = nbest else: nbest.delete( ) print( "" ) lg.best(best) lg.wrapUp(best)
def testSanityGraph(self): G = graph.graph() G.generate(100, 500) st, lo = G.breadth_first_search() for each in G: if (st[each] != None): assert lo.index(each) > lo.index(st[each])
def computeMST(G): S = set() # contains seen vertices num_vertices = G.num_vertices min_weight = [float('inf')] * num_vertices previous = [None] * num_vertices mst = graph() # initialize the MST Q = [(min_weight[0], 0)] Qset = set([0]) heapq.heapify(Q) while Q: weight, u = heapq.heappop(Q) if u in S: continue S.add(u) # Add u and its smallet edge to MST mst.add_vertex(u) if weight == float('inf') else mst.add_edge( u, previous[u], weight) u = G.get_vertex(u) for v in u.get_connections(): if v.id not in S: if u.get_weight(v) < min_weight[v.id]: min_weight[v.id] = u.get_weight(v) previous[v.id] = u.id heapq.heappush(Q, (min_weight[v.id], v.id)) # return the sum of the weights of the MST and the MST return sum(min_weight[1:]), mst
def make_graph_2partial(f): g = graph() for i, c in enumerate(f): for v in c: g.add_edge('c{}'.format(i), 'v{}'.format(int(math.fabs(v))), int(v / math.fabs(v))) return g
def test_find_cycle(self): g = pygraph.graph() g.add_nodes(range(1,11)) for each in range(1,10): g.add_edge(each,each+1) g.add_edge(1,10) g2 = copy.deepcopy(g) # also, try one with another edge thrown in there g2.add_edge(2,5) cycles = find_cycle(g) cycles2 = find_cycle(g2) #print "g = ", g #print cycles reducedCycles = set() for each in cycles: reducedCycles.add(frozenset(each)) trulyReducedCycles = frozenset(reducedCycles) # there should only be one cycle self.assertTrue(len(trulyReducedCycles)==1) reducedCycles2 = set() for each in cycles2: reducedCycles2.add(frozenset(each)) trulyReducedCycles2 = frozenset(reducedCycles2) self.assertTrue(len(trulyReducedCycles2)==3)
def open(self): print "New client connected" self.clients.add(self) #print self.clients self.graph = graph.graph() #create a graph instance for this client self.write_message("You are connected, waiting for graph... ")
def test_has_node(): test = g.graph('graph') test.add_node('node1') test.add_node('node2') assert test.has_node('node1') assert test.has_node('node2') assert not test.has_node('node3')
def test_graph_equality_labels(self): """ Graph equality test. This one checks node equality. """ gr = graph() gr.add_nodes([0,1,2]) gr.add_edge((0,1), label="l1") gr.add_edge((1,2), label="l2") gr2 = deepcopy(gr) gr3 = deepcopy(gr) gr3.del_edge((0,1)) gr3.add_edge((0,1)) gr4 = deepcopy(gr) gr4.del_edge((0,1)) gr4.add_edge((0,1), label="l3") assert gr == gr2 assert gr2 == gr assert gr != gr3 assert gr3 != gr assert gr != gr4 assert gr4 != gr
def __init__(self,vid,monitorname): self.g=graph.graph('neighbor.txt') self.vid=vid self.monitorname=monitorname self.monitorsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.monitorsocket.connect((self.monitorname, 40000)) self.neighbors={} self.host_to_key={} self.hellotimestamp=datetime.datetime.now() self.failure_dtc_timestamp=datetime.datetime.now() self.broad_latency_timestamp=datetime.datetime.now() self.sendingSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.receivingSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.receivingSock.bind((myHostName, 40001)) self.helloseq=0 self.metricseq=0 self.neighborstimestamp={} self.latency={} self.file=open('overlay.log','a') self.distance=[] self.prev=[] self.joinevent='' self.downevent='' self.tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.tcpSocket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) self.tcpSocket.bind((myHostName, 40000)) #bind to localhost self.tcpSocket.listen(20) self.bootstrap=False self.datatimestamp=datetime.datetime.now()
def test_graph_equality_attributes(self): """ Graph equality test. This one checks node equality. """ gr = graph() gr.add_nodes([0,1,2]) gr.add_edge((0,1)) gr.add_node_attribute(1, ('a','x')) gr.add_node_attribute(2, ('b','y')) gr.add_edge_attribute((0,1), ('c','z')) gr2 = deepcopy(gr) gr3 = deepcopy(gr) gr3.del_edge((0,1)) gr3.add_edge((0,1)) gr4 = deepcopy(gr) gr4.del_edge((0,1)) gr4.add_edge((0,1)) gr4.add_edge_attribute((0,1), ('d','k')) gr5 = deepcopy(gr) gr5.del_node(2) gr5.add_node(2) gr5.add_node_attribute(0, ('d','k')) assert gr == gr2 assert gr2 == gr assert gr != gr3 assert gr3 != gr assert gr != gr4 assert gr4 != gr assert gr != gr5 assert gr5 != gr
def graph_fce(): err=0 try: mini=float(min_obsah.get()) except: min_obsah.set("Error") err=1 return try: maxi=float(man_obsah.get()) except: man_obsah.set("Error") err=1 return try: if mini>=maxi: man_obsah.set("Error") min_obsah.set("Error") err=1 return except: pass expand=int(exp.get()) if graph.graph(expand,mini,maxi,input_obsah.get())==0: img = ImageTk.PhotoImage(Image.open("./img/pix.png")) else: img = ImageTk.PhotoImage(Image.open("./img/err.png")) panel.configure(image = img) panel.image = img root.update()
def graph_1(): g = { 's': { 'b': 10, 'd': 10 }, 'b': { 'c': 9 }, 'c': { 'e': 6, 't': 10 }, 'd': { 'b': 2, 'c': 8, 'e': 4 }, 'e': { 't': 10 }, 't': dict() } G = graph.graph(g) return G
def sinusoid_graph(): "generate sine graph" pylon_graph = graph.graph() points = sinusoid(ORIGIN, [LENGTH,0,0], WIDTH, LENGTH) print "points" ids = pylon_graph.add_nodes(points, "curve", True) return pylon_graph
def __init__( self, gen, **args ): self.graph = graph.graph( ) self.graph.copy( gen.puz ) # This will be our the inverse of our level on the table self.fit=-1 # Our level self.level=-1 #our old fit for caching self.oldFit = -1 #We store our metrics in here for easy usage #these are our MOEA constraints self.moeaf = [] #Who we dominate goes here, references to them self.dominates = [] #Who dominates us goes here, references self.domee = [] # Birth Generation self.birth=gen.num # Bad sol self.bad = False # Generation of origin self.gen = gen if 'mate' in args: self.breed( args['mate'][0], args['mate'][1] )
def main(): beg_file = "/home/hadoop/dataset_sssp/beg.txt" csr_file = "/home/hadoop/dataset_sssp/csr.txt" weight_file = "/home/hadoop/dataset_sssp/weight.txt" g = graph.graph(beg_file, csr_file,weight_file) bfs_sa(0,g) return 0
def separateGraphs(g): # given a graph g with non-connected components, return each component separately. # there's countGraphs(g) number of graphs to find in g. graphs = [] #dict = pygraph.accessibility.connected_components(g) #len(list(frozenset(dict.values()))) thedict = pygraph.accessibility.connected_components(g) # there's len(frozenset(thedict.keys())) number of graphs to be returned. for each in list(frozenset(thedict.values())): if type(g) == type(pygraph.graph): g2 = pygraph.graph() if type(g) == type(pygraph.digraph): g2 = pygraph.digraph() else: print "ERROR: unknown graph type.\n" return for node in thedict.keys(): if thedict[node] == each: g2.add_node(node) # also, add the edges corresponding to this node in this component for edge in g.edges(): if edge[0] == node or edge[1] == node: g2.add_edge(edge[0],edge[1]) graphs.append(g2) return graphs
def graph_2(): L = ['a', 'b', 'c', 'd', 'e'] R = ['f', 'g', 'h', 'i'] g = { 'a': { 'f': 1 }, 'b': { 'f': 1, 'h': 1 }, 'c': { 'g': 1, 'h': 1, 'i': 1 }, 'd': { 'h': 1 }, 'e': { 'h': 1, 'i': 1 }, 'f': dict(), 'g': dict(), 'h': dict(), 'i': dict(), 't': dict() } G = graph.graph(g) return G, L, R
def kruskals(graphs): cost_matrix = [[-1 for i in range(0,graphs.vertices)] for j in range(0,graphs.vertices)] mst = graph(graphs.vertices,cost_matrix) heap = Heap() for i in range(0,graphs.vertices): for j in range(0,len(graphs.adj[i])): if graphs.cost_matrix[i][graphs.adj[i][j]-1] >0: heap.insert(i+1,graphs.adj[i][j],graphs.cost_matrix[i][graphs.adj[i][j]-1]) edgesadd=0 left = graphs.vertices mfset = Mfset(left) while(edgesadd<graphs.vertices-1): minimum = heap.pop_min() set1 = mfset.find(minimum[1]) set2 = mfset.find(minimum[0]) if set1 == set2: if set1 == 0: mfset.insertnew(minimum[1]) mfset.insert(minimum[0],mfset.nosets) mst.add_edge(minimum[1],minimum[0]) mst.cost_matrix[minimum[1]-1][minimum[0]-1]=graphs.cost_matrix[minimum[1]-1][minimum[0]-1] mst.cost_matrix[minimum[0]-1][minimum[1]-1]=graphs.cost_matrix[minimum[0]-1][minimum[1]-1] edgesadd=edgesadd+1 else: # print(mfset.setarray) continue else: if set1 ==0: mfset.insert(minimum[1],set2) mst.add_edge(minimum[1],minimum[0]) mst.cost_matrix[minimum[1]-1][minimum[0]-1]=graphs.cost_matrix[minimum[1]-1][minimum[0]-1] mst.cost_matrix[minimum[0]-1][minimum[1]-1]=graphs.cost_matrix[minimum[0]-1][minimum[1]-1] edgesadd = edgesadd+1 elif set2 == 0: mst.add_edge(minimum[1],minimum[0]) mst.cost_matrix[minimum[1]-1][minimum[0]-1]=graphs.cost_matrix[minimum[1]-1][minimum[0]-1] mst.cost_matrix[minimum[0]-1][minimum[1]-1]=graphs.cost_matrix[minimum[0]-1][minimum[1]-1] mfset.insert(minimum[0],set1) edgesadd = edgesadd+1 else: mst.add_edge(minimum[1],minimum[0]) mst.cost_matrix[minimum[1]-1][minimum[0]-1]=graphs.cost_matrix[minimum[1]-1][minimum[0]-1] mst.cost_matrix[minimum[0]-1][minimum[1]-1]=graphs.cost_matrix[minimum[0]-1][minimum[1]-1] mfset.merge(set1,set2) edgesadd = edgesadd+1 # print(mfset.setarray) return mst
def main(): print("") g = graph() g.read_from_file("graph_Fig_22.3.tsv") g.print_graph() g.bfs("s") g.print_path("w", "u")
def test_add_empty_graph(self): gr1 = testlib.new_graph() gr1c = copy(gr1) gr2 = graph() gr1.add_graph(gr2) self.assertTrue(gr1.nodes() == gr1c.nodes()) self.assertTrue(gr1.edges() == gr1c.edges())
def testReadGraphDot(self): dot = ['graph graphname {', '1;', '2;', '3;', '4;', '5;', '1 -- 2;', '3 -- 2;', '4 -- 5;', '1 -- 5;', '4 -- 2;', '5 -- 3;', '}', ''] dot = "\n".join(dot) gr = graph.graph() gr.read(dot, 'dot') self._check_nodes(gr, dot) self._check_edges(gr, dot)
def test_makeCut(self): # blah? # start with a non-directed graph. g = pygraph.graph() # add some nodes g.add_nodes(range(1,11)) # add some edges for each in range(1,10): g.add_edge(each,each+1) # make a single cut gcut1 = makeCut([1,2],g) # should be two less edges because both (1,2) and (2,1) should have been removed. self.assertTrue(len(gcut1.edges()) == len(g.edges())-2) gcut2 = makeCut(([1,2],[3,4]),g) self.assertTrue(len(gcut2.edges()) == len(g.edges())-4) gcut3 = makeCut(([1,2],[3,4],[4,5]),g) self.assertTrue(len(gcut3.edges()) == len(g.edges())-6) # directed graph test g2 = pygraph.digraph() # add some nodes g2.add_nodes(range(1,11)) # add some edges for each in range(1,10): g2.add_edge(each,each+1) # make a single cut g2cut1 = makeCut([1,2],g2) self.assertTrue(len(g2cut1.edges()) == len(g2.edges())-1) # make two cuts g2cut2 = makeCut(([1,2],[2,3]),g2) self.assertTrue(len(g2cut2.edges()) == len(g2.edges())-2)
def sinusoid_graph(): "generate sine graph" pylon_graph = graph.graph() points = sinusoid(ORIGIN, [LENGTH, 0, 0], WIDTH, LENGTH) print "points" ids = pylon_graph.add_nodes(points, "curve", True) return pylon_graph
def __init__(self, mask, start=None, end=None, length=None): """ 从图片mask(二维0-1 ndarray)生成迷宫,图像需连续,0为透明 一个像素代表迷宫中一个格子 start、end都是tuple(row,col)坐标,默认为最上左角、最下右角 """ self.mask = mask self.maskrows, self.maskcols = self.maskshape = mask.shape[:2] self.length = length or 2 * (self.maskrows + self.maskcols) # 每个像素的id self.idmz = idmz = gh.to_id_image(mask, transOld=0, transNew=-1) # 相邻像素的对儿 self.nepairs = gh.neiPairsOf(idmz, trans=-1, shift=gh.shift_neonespadding) # 对应的图 self.G = G = graph(self.nepairs) # print(idmz[start],idmz[end]) # print(G.search(idmz[start],idmz[end])) self.start_id = min(G.vertices) if start is None else idmz[start] self.end_id = max(G.vertices) if end is None else idmz[end] self.start_coord, self.end_coord = gh.toCoords( [self.start_id, self.end_id], self.maskshape) # G的最小生成树 self.T = T = spanningTree_path_len(G, self.start_id, self.end_id, self.length) # 迷宫的矩阵表示,M.shape = (self.maskrows, self.maskcols, 4) self.M = MOfT(T, self.maskshape)
def main(): oveja = {} gr=generate_graph(oveja) #gr.generate_cannibal() #gr.generate_sheep() gr.generate_sheep() with open('oveja.json') as file: data =json.load(file) t=data['graph'] s=data['estado_inicial'] u=data['estado_aceptacion'] g=graph(t,s,u) copyg=g aux=gr.call_return_path(copyg,copyg.graph[0]) print('CAMINO') for h in gr.path: print('--',h,'\n') aux=gr.return_path_pos(copyg) print(aux) print(aux[0][1]) gui=GUI(g,gr) gui.window()
def server(): s = socket(AF_INET, SOCK_STREAM) s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) s.bind(('',9000)) s.listen(5) f.print_log('listening...') while True: client, address = s.accept() f.print_log("sensor server: got connection from %s port %d\n" % (address[0], address[1])) client.send("Connected\n") data = client.recv(1024) while(len(data) >0): if "stop" in data: print("stop incoming") close() f.close_file() client.close() data='' g = graph('/root/sensor/data/','/root/sensor/stylesheets/', f.file_prefix) g.saveTData() break else: if(len(data)>0): f.file_prefix = data f.open_file("data/"+data) start() data = client.recv(1024)
def star_graph(): """Playing with the star function""" pylon_graph = graph.graph() idx = pylon_graph.add_unique_node(ORIGIN, "base") star_list = pylon_graph.add_star_to_node(idx, 6) pylon_graph.connect_nodes(star_list) pylon_graph.save_graph("star") return pylon_graph
def test_edges(): test = g.graph('graph') test.add_edge('node1','node2') test.add_edge('node1','node3') test.add_edge('node2','node3') assert test.edges() == set([frozenset(['node1','node2']), frozenset(['node1','node3']), frozenset(['node2','node3'])])
def test_depth_first_traversal(): test = g.graph('graph') test.add_edge('node1','node2') test.add_edge('node1','node5') test.add_edge('node2','node3') test.add_edge('node2','node4') test.add_edge('node4','node6') test.depth_first_traversal('node1') assert test.path == ['node1','node2','node3','node4','node6','node5'] test = g.graph('graph1') test.add_edge('node1','node2') test.add_edge('node1','node5') test.add_edge('node2','node3') test.add_edge('node2','node4') test.add_edge('node4','node6') test.depth_first_traversal('node4') assert test.path == ['node4','node2','node1','node5','node3','node6']