def generar_img(temp: str): if temp != "" and temp is not None: from graphviz import Source s = Source(temp, filename="src\\Reports\\tree_report", format="png") s.view()
import os from stanfordcorenlp import StanfordCoreNLP from graphviz import Source # make sure nltk can find stanford-parser # please check your stanford-parser version from brew output (in my case 3.6.0) os.environ['CLASSPATH'] = r'/usr/local/Cellar/stanford-parser/3.6.0/libexec' sentence = 'The brown fox is quick and he is jumping over the lazy dog' sdp = StanfordCoreNLP() result = list(sdp.raw_parse(sentence)) dep_tree_dot_repr = [parse for parse in result][0].to_dot() source = Source(dep_tree_dot_repr, filename="dep_tree", format="png") source.view()
def visualise_recipe(self): """ Visualing recipe using plantUML Install it using brew install plantuml """ dc_directory = self.dlg.lineEdit.text() dc_recipe = self.track_recipe_choice() file = '{0}/src/main/resources/executions/examples/{1}'.format(dc_directory,dc_recipe) try: # Check if graphviz is installed if platform.system() == 'Windows': graphviz_path = None # Look in both Program Files and Program Files x86 for i in os.listdir('C:\\Program Files'): if 'Graphviz' in i: graphviz_path = 'C:\\Program Files\\' + i + '\\bin' else: pass if graphviz_path != None: pass else: for j in os.listdir('C:\\Program Files (x86)'): if 'Graphviz' in j: graphviz_path = 'C:\\Program Files (x86)\\' + i + '\\bin' else: pass # ERROR cannot find graphviz installation if graphviz_path == None: graphviz_path = QFileDialog.getExistingDirectory( self.dlg, "Select graphviz path", expanduser("~"), QFileDialog.ShowDirsOnly ) # Add missing PATHs for windows current_execs = os.environ['PATH'] if not 'graphviz' in current_execs: os.environ['PATH'] += ';' + graphviz_path # check graphviz for Mac OSX elif platform.system() == 'Darwin': for i in os.listdir('/usr/local/Cellar/'): if 'graphviz' in i: graphviz_path = '/usr/local/Cellar/' + i + '/' + os.listdir('/usr/local/Cellar/'+ i)[0] + \ '/' + 'bin' print graphviz_path else: pass if graphviz_path == None: graphviz_path = QFileDialog.getExistingDirectory( self.dlg, "Select graphviz path", expanduser("~"), QFileDialog.ShowDirsOnly ) # Add missing PATHs for windows current_execs = os.environ['PATH'] if not 'graphviz' in current_execs: os.environ['PATH'] += ':' + graphviz_path else: self.iface.messageBar().pushMessage("Error", "We currently support only Windows and MacOSX", level=QgsMessageBar.CRITICAL) from graphviz import Digraph from graphviz import Source with open(file) as f: content = f.readlines() jsn = '' for i in content: if '//' in i: pass else: jsn = jsn+i.replace("/n",'') f = json.loads(jsn) c, r = self.traverse(f, None) dot = Digraph() dot.attr('node', shape='box') for i in c: dot.node(i['clsNameFullReference'], label ='''<<table border="0"> <tr> <td>{0}</td> </tr> <hr/> <tr><td><FONT COLOR="red" POINT-SIZE="16.0">Properties</FONT></td></tr> {1} <hr/> <tr><td><FONT COLOR="red" POINT-SIZE="16.0">Objects</FONT></td></tr> {2} </table>>'''.format(i['clsName'], ['<tr><td>'+j+'</td></tr>' for j in i['clsProperties']], ['<tr><td>'+k+'</td></tr>' for k in i['clsObjects']])) for j in r: dot.edge(j.split('-->')[0].split(" ")[0].replace('"',""),j.split('-->')[-1].split(" ")[-1].replace('"',"")) s = Source(dot, filename=expanduser("~") + "/"+"test.gv", format="png") s.view() except ImportError, e: self.iface.messageBar().pushMessage("Error", "You need to install graphviz to visualise the recipe. Please refer to installation instructions", level=QgsMessageBar.CRITICAL)
def func_graph_gen(final_dict, interfaceneeded): #Installing the requirements for graphviz #var= os.system("sudo pip install graphviz") #print "\n----------------------------------------------------------------------------" #print "Please complete the installation of Xcode Dev Tools (if prompted) via the GUI and rerun this script" print "Status:" var1= os.system("xcode-select --install") print "----------------------------------------------------------------------------" var= os.system("brew install graphviz") #os.system('tput reset') #This is used to clear the screen ...similar to Ctrl+L in bash if len(final_dict)>20: graph_string=''' digraph finite_state_machine { size="8,5" node [shape = box]; rankdir="LR" ''' if len(final_dict)<=20: graph_string=''' digraph finite_state_machine { size="8,5" node [shape = box]; ''' #The below block is for handling '-' and '.' being present in DUT name for i in xrange(0,len(final_dict)): if '-' in final_dict[i]['neighborDevice'] or '-' in final_dict[i]['myDevice'] or '.' in final_dict[i]['neighborDevice'] or '.' in final_dict[i]['myDevice']: if '-' in final_dict[i]['neighborDevice'] or '.' in final_dict[i]['neighborDevice']: new_str=string.replace(final_dict[i]['neighborDevice'], '-', '_') final_dict[i]['neighborDevice']=new_str if '-' in final_dict[i]['myDevice'] or '.' in final_dict[i]['myDevice']: new_str=string.replace(final_dict[i]['myDevice'], '-', '_') final_dict[i]['myDevice']=new_str #The below block is for converting the topology to graphviz format for i in xrange(0,len(final_dict)): if interfaceneeded=='yes': tempvar=final_dict[i]['neighborDevice'] + ' -> ' + final_dict[i]['myDevice'] + ' [ label = "' + final_dict[i]['neighborPort'] + '---' + final_dict[i]['port'] + '" ]' else: tempvar=final_dict[i]['neighborDevice'] + ' -> ' + final_dict[i]['myDevice'] graph_string=graph_string+tempvar+'\n' graph_string=graph_string+'}' #print graph_string print "----------------------------------------------------------------------------" print "Your topology in .PDF and a editable .GV formats has been generated on the current directory" #print "There is both a readily-available pdf file as well as a .gv file which can be imported to graphing tools like OmniGraffle for further editing(get license for Omnigraffle from helpdesk..:/\n" print "If your device names contains either '.' or '-', it will be replaced by '_' to avoid conflict with other packages" try: s = Source(graph_string, filename="Topology.gv", format="pdf") s.view() except Exception as e: print e print"\n ---------------------------------------------------------------------------------------------------------------------- " print "[ERROR] Looks like we encountered an error. We'll see if installing a package fixes it. Please provide your mac password if prompted" print"---------------------------------------------------------------------------------------------------------------------- " var=os.system('''/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"''') var= os.system("brew install graphviz") os.system('tput reset') #This is used to clear the screen ...similar to Ctrl+L in bash s = Source(graph_string, filename="Topology.gv", format="pdf") s.view() try: installationcheckcmd="ls /Applications/ | grep -i OmniGraffle" returned_value = subprocess.call(installationcheckcmd, shell=True) if returned_value==1: #That means OmniGraffle is NOT present print "----------------------------------------------------------------------------" print "The PDF file has been generated in current directory! " #Instead of OmniGraffle not installed message elif returned_value==0: #That means OmniGraffle is present print "----------------------------------------------------------------------------" print "If you have Omnigraffle installed, choose 'Hierarchial' for getting the Topology in editable format." subprocess.call( ["/usr/bin/open", "-W", "-n", "-a", "/Applications/OmniGraffle.app","Topology.gv"] ) except: print "Finished!" sys.exit(1)
def main(): estimator = DecisionTreeClassifier(max_leaf_nodes=3, random_state=0) estimator.fit(X_train, y_train) # Properties from the estimator n_nodes = estimator.tree_.node_count # including decision nodes children_left = estimator.tree_.children_left # id of the left child of the node # id of the right child of the node children_right = estimator.tree_.children_right feature = estimator.tree_.feature threshold = estimator.tree_.threshold # traverse the tree node_depth = np.zeros(n_nodes, dtype=np.int64) is_leaves = np.zeros(n_nodes, dtype=bool) stack = [(0, -1)] # seed is the root node id and its parent depth while len(stack) > 0: node_id, parent_depth = stack.pop() node_depth[node_id] = parent_depth + 1 # If we have a test node if children_left[node_id] != children_right[node_id]: stack.append((children_left[node_id], parent_depth + 1)) stack.append((children_right[node_id], parent_depth + 1)) else: is_leaves[node_id] = True print("The binary tree structure has {} nodes and " "has the following tree structure:".format(n_nodes)) for i in range(n_nodes): if is_leaves[i]: print("{}node={} leaf node.".format(node_depth[i] * "\t", i)) else: print( "{}node={} test node: go to node {} if X[:, {}] <= {:.2f} else to " "node {}.".format( node_depth[i] * "\t", i, children_left[i], feature[i], threshold[i], children_right[i], )) node_indicator = estimator.decision_path(X_test) # Similarly, we can also have the leaves ids reached by each sample. leave_id = estimator.apply(X_test) # Now, it's possible to get the tests that were used to predict a sample or # a group of samples. First, let's make it for the sample. sample_id = 0 node_index = node_indicator.indices[ node_indicator.indptr[sample_id]:node_indicator.indptr[sample_id + 1]] # Each row holds the prediction value of each node output_value = estimator.tree_.value print(output_value) print('Rules used to predict sample {} with feature: {}: '.format( sample_id, ', '.join([str(feature) for feature in X_test[0]]))) for node_id in node_index: if leave_id[sample_id] == node_id: continue threshold_sign = ">" if (X_test[sample_id, feature[node_id]] <= threshold[node_id]): threshold_sign = "<=" print( "decision id node {} : (X_test[{}, {}] = {:.2f} {} {:.2f})".format( node_id, sample_id, feature[node_id], X_test[sample_id, feature[node_id]], threshold_sign, threshold[node_id])) # Plotting graph dot = export_graphviz(estimator, feature_names=feature_names, class_names=class_names, rounded=True, proportion=False, precision=2, filled=True) graph = Source(dot) graph.view() print('debug line')
def automaticGraphGenerator(dictionaryOfConnections, intfInfo): # This part below checks the number of DUTs and connections and based on it, it creates containers for the graphviz code if len(dictionaryOfConnections) > 20: graph_string = ''' digraph finite_state_machine { size="8,5" node [shape = box]; rankdir="LR" ''' if len(dictionaryOfConnections) <= 20: graph_string = ''' digraph finite_state_machine { size="8,5" node [shape = box]; ''' #The below block is for handling '-' and '.' being present in DUT name since it causes error in graphviz for i in range(0, len(dictionaryOfConnections)): if '-' in dictionaryOfConnections[i][ 'neighbor'] or '-' in dictionaryOfConnections[i][ 'myDevice'] or '.' in dictionaryOfConnections[i][ 'neighbor'] or '.' in dictionaryOfConnections[i][ 'myDevice']: if '-' in dictionaryOfConnections[i][ 'neighbor'] or '.' in dictionaryOfConnections[i][ 'neighbor']: new_str = string.replace( dictionaryOfConnections[i]['neighbor'], '-', '_') dictionaryOfConnections[i]['neighbor'] = new_str if '-' in dictionaryOfConnections[i][ 'myDevice'] or '.' in dictionaryOfConnections[i][ 'myDevice']: new_str = string.replace( dictionaryOfConnections[i]['myDevice'], '-', '_') dictionaryOfConnections[i]['myDevice'] = new_str #The below block is for converting the topology to graphviz format. Adding the connection details to the graphviz container created above for i in range(0, len(dictionaryOfConnections)): if intfInfo: tempvar = dictionaryOfConnections[i][ 'neighbor'] + ' -> ' + dictionaryOfConnections[i][ 'myDevice'] + ' [ label = "' + dictionaryOfConnections[i][ 'neighbor-port'] + '<------>' + dictionaryOfConnections[ i]['port'] + '" ]' #The below else block is for case when user chose not to include interface labels in topology else: tempvar = dictionaryOfConnections[i][ 'neighbor'] + ' -> ' + dictionaryOfConnections[i]['myDevice'] graph_string = graph_string + tempvar + '\n' graph_string = graph_string + '}' logging.info( "----------------------------------------------------------------------------" ) logging.info( "[MESSAGE] If your device names contains either '.' or '-', it will be replaced by '_' to avoid conflict with other packages\n \n" ) logging.info("> Completed:") # The below try-except block is for handling errors in graphviz installation due to all the above dependencies on Mac (linux doesn't have much), I try to install brew and then 'brew install graphviz' since brew (unlike apt-get) is not installed by default. try: s = Source(graph_string, filename="Topology.gv", format="pdf") s.view() #Send Email with the script sendEmailSwatExtension() #The below except block is used to install Xcode-Cli tools, brew and graphviz since Mac requires additional dependencies (if not present already) except Exception as e: logging.info( "\n ---------------------------------------------------------------------------------------------------------------------- " ) logging.info("[ERROR] Looks like we encountered an error. ERROR is:") logging.info(e) logging.info( " We'll see if installing a few packages fixes it. Please provide your device (Mac/server) password if prompted." ) logging.info( "---------------------------------------------------------------------------------------------------------------------- " ) #Installing Xcode command-line tools for Mac var1 = os.system("xcode-select --install") #Installing Brew var = os.system( '''/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"''' ) #Installing Graphviz using brew var = os.system("brew install graphviz") #This is used to clear the screen ...similar to Ctrl+L in bash os.system('tput reset') s = Source(graph_string, filename="Topology.gv", format="pdf") s.view() #Send Email with the script sendEmailSwatExtension() #The below code block if for opening the editable .gv file using Omnigraffle if it is installed on the user's Mac. Else, skip and print 'Script Complete' try: installationcheckcmd = "ls /Applications/ | grep -i OmniGraffle" returned_value = subprocess.call(installationcheckcmd, shell=True) if returned_value == 1: #That means OmniGraffle is NOT present logging.info( "\n [MESSAGE] * The PDF file (graphic topology) and txt file (text) have been generated in current directory! " ) #Instead of OmniGraffle not installed message abort("* Script Completed!") elif returned_value == 0: #That means OmniGraffle is present logging.info( "\t * The PDF file (graphic topology) and txt file (text) have been generated in current directory. Also, OmniGraffle has been opened to edit the GV file (graphic topology). Please choose 'Hierarchial' in OmniGraffle to edit it." ) subprocess.call([ "/usr/bin/open", "-W", "-n", "-a", "/Applications/OmniGraffle.app", "Topology.gv" ]) except: abort("* Script Complete!")
x = df[['Pos', 'OBP', 'AVG?', 'OPS', 'SLG', 'RBI']] y = df['2017Si.S'] # split train & test x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3) # standard scaler sc = preprocessing.StandardScaler() sc.fit(x) x_train_nor = sc.transform(x_train) x_test_nor = sc.transform(x_test) # create decision tree decision_tree = tree.DecisionTreeClassifier(criterion='gini', max_depth=3) decision_tree_clf = decision_tree.fit(x_train_nor, y_train) # show the decision tree by graphic (need install graphviz package) decision_tree_dot = tree.export_graphviz(decision_tree_clf, out_file=None, feature_names=x.columns) decision_tree_source = Source(decision_tree_dot, filename='decision_tree') decision_tree_source.view() # predicted y_tree_test_predicted = decision_tree_clf.predict(x_test_nor) # show the score tree_accuracy = metrics.accuracy_score(y_test, y_tree_test_predicted) print('tree_accuracy:', tree_accuracy)
return thisnode ############################################################################# X, y = make_data(m=200, n=10, make_identical_observations_consistent=False, balanced=True, seed=True) tree = Tree(metric='entropy').fit(X, y) ypred = tree.predict(X) acc = np.equal(y, ypred).mean() print("accuracy =", acc, "\tnumber of nodes =", tree._nodes_counter) #graphviz string = tree.graph try: from graphviz import Source except: print("Unable to import graphviz") else: graph = Source(string, filename="image", format="png") graph.view() from sklearn.tree import DecisionTreeClassifier md = DecisionTreeClassifier().fit(X, y) acc = md.score(X, y) print("sklearn acc", acc)
############################################################# # File Name: 2.py # Autohor: Hui Chen (c) 2020 # Mail: [email protected] # Create Time: 2020/03/16-21:14:17 ############################################################# #!/usr/bin/env python #-*- coding:utf8 -*- from graphviz import Source src = Source( 'digraph "the holy hand grenade" { rankdir=LR; 1 -> 2 -> 3 -> lob }') src.view()
D -> Menu [style=dotted, label="<requires>"]; PlanetOrbits -> Menu [style=dotted, label="<requires>"]; D -> TopCamera; D -> EarthCamera; D -> E; D -> F; F -> KeyboardControl [style=dotted, label="<requires>"]; Axes -> Menu [style=dotted, label="<requires>"]; StarField -> Menu [style=dotted, label="<requires>"]; A -> G; A -> H; } """ # model = Source(source, filename="feature_model", format="png") model.view() # feature_model_solar2 # CameraView [style=dotted]; # A [label="Reading planet data", style=dotted]; # B [label="Ability to toggle features"]; # C [label="Single camera view"]; # D [label="Multiple camera views", style=dotted]; # E [label="Camera moving in a pattern"]; # F [label="Camera moving from user input"]; # G [label="Reading from file"]; # H [label="Reading from command line"]; # SolarSystem -> KeyboardControl; # SolarSystem -> A [style=bold]; # SolarSystem -> PlanetAnimation;
import sys from graphviz import Source f = open("./cache/" + sys.argv[1], "r") text = f.read() f.close() a = Source(text, filename=sys.argv[1], directory="./cache/") a.view()
path_to_models_jar='E:/stanford/stanford-parser-full-2015-04-20/stanford-parser-3.5.2-models.jar') result = list(sdp.raw_parse(sentence)) result[0] [item for item in result[0].triples()] dep_tree = [parse.tree() for parse in result][0] print dep_tree dep_tree.draw() # generation of annotated dependency tree shown in Figure 3-4 from graphviz import Source dep_tree_dot_repr = [parse for parse in result][0].to_dot() source = Source(dep_tree_dot_repr, filename="dep_tree", format="png") source.view() import nltk tokens = nltk.word_tokenize(sentence) dependency_rules = """ 'fox' -> 'The' | 'brown' 'quick' -> 'fox' | 'is' | 'and' | 'jumping' 'jumping' -> 'he' | 'is' | 'dog' 'dog' -> 'over' | 'the' | 'lazy' """ dependency_grammar = nltk.grammar.DependencyGrammar.fromstring(dependency_rules) print dependency_grammar dp = nltk.ProjectiveDependencyParser(dependency_grammar)
def generate(self): self.visit_(self.tree) content = ''.join(self.dot_header + self.dot_body + self.dot_footer) # print(content) dot = Source(content, 'ast', format='png') dot.view(cleanup=True)
def func_graph_withchoice(final_dict,interfaceneeded): #Installing the requirements for graphviz #var= os.system("sudo pip install graphviz") #print "\n----------------------------------------------------------------------------" #print "Please complete the installation of Xcode Dev Tools (if prompted) via the GUI and rerun this script" print "Status:" var1= os.system("xcode-select --install") print "----------------------------------------------------------------------------" var= os.system("brew install graphviz") #os.system('tput reset') #This is used to clear the screen ...similar to Ctrl+L in bash if len(final_dict)>20: graph_string=''' digraph finite_state_machine { splines=true; node [shape = circle]; node [fontsize=7]; rankdir="LR" ''' if len(final_dict)<=20: graph_string=''' digraph finite_state_machine { splines=true; node [shape = circle]; node [fontsize=7]; ''' nooflevels=raw_input("Please enter the number of levels in your topology. Eg) Leaf-Spine is 2 levels and Leaf-Spine-Superspine is 3 levels. (Enter a integer:) ") alreadyadded=[] dictoflevels={} for i in xrange(1,(int(nooflevels)+1)): dictoflevels[i]=[] #print dictoflevels try: for i in xrange(0,len(final_dict)): if final_dict[i]['neighborDevice']==final_dict[i]['myDevice']: if final_dict[i]['neighborDevice'] not in alreadyadded: alreadyadded.append(final_dict[i]['neighborDevice']) value=raw_input ("Enter the level/hierarchy in range of 1 to "+nooflevels+" (with 1 being lowest) of "+final_dict[i]['neighborDevice'] +": ") dictoflevels[int(value)].append(final_dict[i]['neighborDevice']) else: if final_dict[i]['neighborDevice'] not in alreadyadded: alreadyadded.append(final_dict[i]['neighborDevice']) value=raw_input ("Enter the level/hierarchy in range of 1 to "+nooflevels+" (with 1 being lowest) of "+final_dict[i]['neighborDevice'] +": ") dictoflevels[int(value)].append(final_dict[i]['neighborDevice']) if final_dict[i]['myDevice'] not in alreadyadded: if 'Ixia' not in final_dict[i]['myDevice']: alreadyadded.append(final_dict[i]['myDevice']) value=raw_input ("Enter the level/hierarchy in range of 1 to "+nooflevels+" (with 1 being lowest) of "+final_dict[i]['myDevice'] +": ") dictoflevels[int(value)].append(final_dict[i]['myDevice']) #print alreadyadded except KeyError as e: print 'The entered value is outside the range of total levels. Please rerun again...' sys.exit(1) #print dictoflevels #The below block is for handling '-' and '.' being present in DUT name for i in xrange(0,len(final_dict)): if '-' in final_dict[i]['neighborDevice'] or '-' in final_dict[i]['myDevice'] or '.' in final_dict[i]['neighborDevice'] or '.' in final_dict[i]['myDevice']: if '-' in final_dict[i]['neighborDevice'] or '.' in final_dict[i]['neighborDevice']: if '-' in final_dict[i]['neighborDevice']: new_str=string.replace(final_dict[i]['neighborDevice'], '-', '_') if '.' in final_dict[i]['neighborDevice']: new_str=string.replace(final_dict[i]['neighborDevice'], '.', '_') final_dict[i]['neighborDevice']=new_str if '-' in final_dict[i]['myDevice'] or '.' in final_dict[i]['myDevice']: if '-' in final_dict[i]['myDevice']: new_str=string.replace(final_dict[i]['myDevice'], '-', '_') if '.' in final_dict[i]['myDevice']: new_str=string.replace(final_dict[i]['myDevice'], '.', '_') final_dict[i]['myDevice']=new_str for j in reversed(xrange(1,(int(nooflevels)+1))): graph_string=graph_string+"\n\nsubgraph level"+str(j) +" {" if j==1: graph_string=graph_string+''' rank=max; node[style=filled, shape=box,color=green, fontsize=8]; ''' elif j==2: graph_string=graph_string+''' rank=same; node[style=filled, shape=box,color=red, fontsize=8]; ''' else: graph_string=graph_string+''' rank=min; node[style=filled, shape=box,color=yellow, fontsize=8]; ''' #Adding the devices to each level for k in xrange(0,len(dictoflevels[j])): #Handling '-' or '.' present in the name if '-' in dictoflevels[j][k] or '.' in dictoflevels[j][k]: if '-' in dictoflevels[j][k]: new_str=string.replace(dictoflevels[j][k], '-', '_') dictoflevels[j][k]=new_str if '.' in dictoflevels[j][k]: new_str=string.replace(dictoflevels[j][k], '.', '_') dictoflevels[j][k]=new_str graph_string=graph_string+dictoflevels[j][k]+";\n" graph_string=graph_string+"}" #print graph_string #The below is generic connector code graph_string=graph_string+''' subgraph connector{ ''' #The below block is for converting the topology to graphviz format for i in xrange(0,len(final_dict)): if interfaceneeded=='yes': tempvar=final_dict[i]['neighborDevice'] + ' -> ' + final_dict[i]['myDevice'] + ' [ label = "' + final_dict[i]['neighborPort'] + '---' + final_dict[i]['port'] + '",labelfontsize=0.5 ]' else: tempvar=final_dict[i]['neighborDevice'] + ' -> ' + final_dict[i]['myDevice'] graph_string=graph_string+tempvar+'\n' graph_string=graph_string+'}}' #print graph_string print "----------------------------------------------------------------------------" print "Your topology in .PDF and a editable .GV formats has been generated on the current directory" #print "There is both a readily-available pdf file as well as a .gv file which can be imported to graphing tools like OmniGraffle for further editing(get license for Omnigraffle from helpdesk..:/\n" print "If your device names contains either '.' or '-', it will be replaced by '_' to avoid conflict with other packages" print "\n----------------------------------------------------------------------------" print "Important NOTE: If you get a blank file as output, please verify your choice for device levels. Your choice may have given impossible to comprehend/design for our tool" try: s = Source(graph_string, filename="Topology.gv", format="pdf") s.view() except: print"\n ---------------------------------------------------------------------------------------------------------------------- " print "[ERROR] Looks like we encountered an error. We'll see if installing a package fixes it. Please provide your mac password if prompted" print"---------------------------------------------------------------------------------------------------------------------- " var=os.system('''/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"''') var= os.system("brew install graphviz") os.system('tput reset') #This is used to clear the screen ...similar to Ctrl+L in bash s = Source(graph_string, filename="Topology.gv", format="pdf") s.view() try: installationcheckcmd="ls /Applications/ | grep -i OmniGraffle" returned_value = subprocess.call(installationcheckcmd, shell=True) if returned_value==1: #That means OmniGraffle is NOT present print "----------------------------------------------------------------------------" print "The PDF file has been generated in current directory! " #Instead of OmniGraffle not installed message elif returned_value==0: #That means OmniGraffle is present print "----------------------------------------------------------------------------" print "If you have Omnigraffle installed, choose 'Hierarchial' for getting the Topology in editable format." subprocess.call( ["/usr/bin/open", "-W", "-n", "-a", "/Applications/OmniGraffle.app","Topology.gv"] ) except: print "Finished!" sys.exit(1)
code = """digraph G { n1[shape=record,label="{{0x603010 size:0x20}}"] n2[shape=box,label="{{0x603010 size:0x20}|{0x603030 size:0x190}}"] n3[shape=box,label="{{0x603010 size:0x20}|{0x603030 size:0x190}|{0x6031c0 size:0x20}}"] n4[shape=record,label="{{0x603010 size:0x20}|{0x603030 size:0x190}|{0x6031c0 size:0x20}|{0x6031e0 size:0x10}}"] n5[shape=record,label="{{0x603010 size:0x20}|{0x603030 size:0x190}|{0x6031c0 size:0x20}}"] n6[shape=record,label="{{0x603010 size:0x20}|{0x603030 size:0x190}}"] n7[shape=record,label="{{0x603010 size:0x20}}"] n8[shape=none, label=<<table border="0" cellborder="1" cellspacing="0" cellpadding="4"> <tr><td bgcolor="lightgrey"><font color="red">0x603010 size:0x20</font></td></tr> <tr><td>0x603030 size:0x20</td></tr> </table>>] n9[shape=none, label=<<table border="0" cellborder="1" cellspacing="0" cellpadding="4"> <tr><td bgcolor="lightgrey"><font color="red">0x603010 size:0x20</font></td></tr> <tr><td>0x603030 size:0x20</td></tr> </table>>] n10[shape=box, label=< <br/> 0x6031b0|<font face='cairo' color='#EACE00'>00</font><font face='cairo' color='#EACE00'>00</font><font face='cairo' color='#EACE00'>00</font><font color='#EACE00'>00</font><font color='#EACE00'>00</font><font color='#EACE00'>00</font><font color='#EACE00'>01</font><font color='#EACE00'>90</font> <font color='#EACE00'>00</font><font color='#EACE00'>00</font><font color='#EACE00'>00</font><font color='#EACE00'>00</font><font color='#EACE00'>00</font><font color='#EACE00'>00</font><font color='#EACE00'>00</font><font color='#EACE00'>20</font><br/>0x6031c0| <font color='#EACE00'>00</font><font color='#EACE00'>00</font><font color='#EACE00'>00</font><font color='#EACE00'>00</font><font color='#EACE00'>00</font><font color='#EACE00'>60</font><font color='#EACE00'>31</font><font color='#EACE00'>e0</font> <font color='#EACE00'>00</font><font color='#EACE00'>00</font><font color='#EACE00'>00</font><font color='#EACE00'>00</font><font color='#EACE00'>00</font><font color='#EACE00'>00</font><font color='#EACE00'>00</font><font color='#EACE00'>08</font><br/>0x6031d0| 00000000000000<font color='red'>00</font> 0000000000000021<br/>>] n1->n2[label="Malloc called with size 0x190, returns addr 0x603030"] {rank = same; n2->n8[style=dotted dir=none]} n2->n3[label="Malloc called with size 0x20, returns addr 0x6031c0"] {rank = same; n3->n9} n3->n4[label="Malloc called with size 0x10, returns addr 0x6031e0"] n4->n5[label="Free called to free 0x6031e0 with size 0x20"] n5->n6[label="Free called to free 0x6031c0 with size 0x20"] n6->n7[label="Free called to free 0x603030 with size 0x190"] }""" t = Source(code) t.view()
def automaticGraphGenerator(dictionaryOfConnections, intfInfo): print "[MESSAGE] Ignore on Linux. On macOS, ignore unless prompted for Xcode tools installation:" print "----------------------------------------------------------------------------" var1 = os.system("xcode-select --install") var = os.system("brew install graphviz") print "----------------------------------------------------------------------------" os.system('tput reset' ) #This is used to clear the screen ...similar to Ctrl+L in bash if len(dictionaryOfConnections) > 20: graph_string = ''' digraph finite_state_machine { size="8,5" node [shape = box]; rankdir="LR" ''' if len(dictionaryOfConnections) <= 20: graph_string = ''' digraph finite_state_machine { size="8,5" node [shape = box]; ''' #The below block is for handling '-' and '.' being present in DUT name for i in xrange(0, len(dictionaryOfConnections)): if '-' in dictionaryOfConnections[i][ 'neighborDevice'] or '-' in dictionaryOfConnections[i][ 'myDevice'] or '.' in dictionaryOfConnections[i][ 'neighborDevice'] or '.' in dictionaryOfConnections[i][ 'myDevice']: if '-' in dictionaryOfConnections[i][ 'neighborDevice'] or '.' in dictionaryOfConnections[i][ 'neighborDevice']: new_str = string.replace( dictionaryOfConnections[i]['neighborDevice'], '-', '_') dictionaryOfConnections[i]['neighborDevice'] = new_str if '-' in dictionaryOfConnections[i][ 'myDevice'] or '.' in dictionaryOfConnections[i][ 'myDevice']: new_str = string.replace( dictionaryOfConnections[i]['myDevice'], '-', '_') dictionaryOfConnections[i]['myDevice'] = new_str #The below block is for converting the topology to graphviz format for i in xrange(0, len(dictionaryOfConnections)): if intfInfo == 'yes': tempvar = dictionaryOfConnections[i][ 'neighborDevice'] + ' -> ' + dictionaryOfConnections[i][ 'myDevice'] + ' [ label = "' + dictionaryOfConnections[i][ 'neighborPort'] + '<------>' + dictionaryOfConnections[ i]['port'] + '" ]' else: tempvar = dictionaryOfConnections[i][ 'neighborDevice'] + ' -> ' + dictionaryOfConnections[i][ 'myDevice'] graph_string = graph_string + tempvar + '\n' graph_string = graph_string + '}' #print graph_string print "----------------------------------------------------------------------------" print "[MESSAGE] If your device names contains either '.' or '-', it will be replaced by '_' to avoid conflict with other packages\n \n" print "> Completed Successfully: " #print "There is both a readily-available pdf file as well as a .gv file which can be imported to graphing tools like OmniGraffle for further editing(get license for Omnigraffle from helpdesk..:/\n" try: s = Source(graph_string, filename="Topology.gv", format="pdf") s.view() #Send Email with the script sendEmailSwatExtension() except Exception as e: print e print "\n ---------------------------------------------------------------------------------------------------------------------- " print "[ERROR] Looks like we encountered an error. We'll see if installing a package fixes it. Please provide your mac password if prompted" print "---------------------------------------------------------------------------------------------------------------------- " var = os.system( '''/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"''' ) var = os.system("brew install graphviz") os.system( 'tput reset' ) #This is used to clear the screen ...similar to Ctrl+L in bash s = Source(graph_string, filename="Topology.gv", format="pdf") s.view() #Send Email with the script sendEmailSwatExtension() try: installationcheckcmd = "ls /Applications/ | grep -i OmniGraffle" returned_value = subprocess.call(installationcheckcmd, shell=True) if returned_value == 1: #That means OmniGraffle is NOT present print "\n [MESSAGE] * The PDF file (graphic topology) and txt file (text) have been generated in current directory! " #Instead of OmniGraffle not installed message print "* Script Completed!" elif returned_value == 0: #That means OmniGraffle is present print "\t * The PDF file (graphic topology) and txt file (text) have been generated in current directory. Also, OmniGraffle has been opened to edit the GV file (graphic topology). Please choose 'Hierarchial' in OmniGraffle to edit it." subprocess.call([ "/usr/bin/open", "-W", "-n", "-a", "/Applications/OmniGraffle.app", "Topology.gv" ]) except: print "* Script Complete!" sys.exit(1)
builder = DiagramBuilder() controller = builder.AddSystem(BabySystem()) integrator = builder.AddSystem(Integrator(1)) builder.Connect(controller.get_output_port(), integrator.get_input_port()) # builder.Connect(integrator) diagram = builder.Build() context = diagram.CreateDefaultContext() simulator = Simulator(diagram) # integrator.GetMyContextFromRoot(simulator.get_mutable_context()).get_mutable_continuous_state_vector().SetFromVector(np.array([2.3])) g = Source(diagram.GetGraphvizString()) g.view() # print(context) int_context = integrator.GetMyContextFromRoot(simulator.get_mutable_context()) print(int_context) simulator.Initialize() # simulator.set_target_realtime_rate(1.0) simulator.AdvanceTo(5.0) print(int_context) print("Default context?: ", context) # print(context)
def graphGeneratorwithLeafSpine(dictionaryOfConnections, intfInfo): print "[MESSAGE] Ignore on Linux. On macOS, ignore unless prompted for Xcode tools installation:" print "----------------------------------------------------------------------------" var1 = os.system("xcode-select --install") var = os.system("brew install graphviz") print "----------------------------------------------------------------------------" os.system('tput reset' ) #This is used to clear the screen ...similar to Ctrl+L in bash if len(dictionaryOfConnections) > 20: graph_string = ''' digraph finite_state_machine { node [shape = box]; rankdir="LR" ''' if len(dictionaryOfConnections) <= 20: graph_string = ''' digraph finite_state_machine { node [shape = box]; ''' nooflevels = raw_input( "Please enter the number of levels in your topology. Eg) Leaf-Spine is 2 levels and Leaf-Spine-Superspine is 3 levels. (Enter a integer:) " ) alreadyadded = [] dictoflevels = {} for i in xrange(1, (int(nooflevels) + 1)): dictoflevels[i] = [] #print dictoflevels try: for i in xrange(0, len(dictionaryOfConnections)): if dictionaryOfConnections[i][ 'neighborDevice'] == dictionaryOfConnections[i][ 'myDevice']: if dictionaryOfConnections[i][ 'neighborDevice'] not in alreadyadded: alreadyadded.append( dictionaryOfConnections[i]['neighborDevice']) value = raw_input( "Enter the level/hierarchy in range of 1 to " + nooflevels + " (with 1 being lowest) of " + dictionaryOfConnections[i]['neighborDevice'] + ": ") dictoflevels[int(value)].append( dictionaryOfConnections[i]['neighborDevice']) else: if dictionaryOfConnections[i][ 'neighborDevice'] not in alreadyadded: alreadyadded.append( dictionaryOfConnections[i]['neighborDevice']) value = raw_input( "Enter the level/hierarchy in range of 1 to " + nooflevels + " (with 1 being lowest) of " + dictionaryOfConnections[i]['neighborDevice'] + ": ") dictoflevels[int(value)].append( dictionaryOfConnections[i]['neighborDevice']) if dictionaryOfConnections[i]['myDevice'] not in alreadyadded: alreadyadded.append(dictionaryOfConnections[i]['myDevice']) value = raw_input( "Enter the level/hierarchy in range of 1 to " + nooflevels + " (with 1 being lowest) of " + dictionaryOfConnections[i]['myDevice'] + ": ") dictoflevels[int(value)].append( dictionaryOfConnections[i]['myDevice']) #print alreadyadded except KeyError as e: print '[ERROR] The entered value is outside the range of total levels. Please rerun again...' print '* Script Complete' sys.exit(1) #print dictoflevels #The below block is for handling '-' and '.' being present in DUT name for i in xrange(0, len(dictionaryOfConnections)): if '-' in dictionaryOfConnections[i][ 'neighborDevice'] or '-' in dictionaryOfConnections[i][ 'myDevice'] or '.' in dictionaryOfConnections[i][ 'neighborDevice'] or '.' in dictionaryOfConnections[i][ 'myDevice']: if '-' in dictionaryOfConnections[i][ 'neighborDevice'] or '.' in dictionaryOfConnections[i][ 'neighborDevice']: if '-' in dictionaryOfConnections[i]['neighborDevice']: new_str = string.replace( dictionaryOfConnections[i]['neighborDevice'], '-', '_') if '.' in dictionaryOfConnections[i]['neighborDevice']: new_str = string.replace( dictionaryOfConnections[i]['neighborDevice'], '.', '_') dictionaryOfConnections[i]['neighborDevice'] = new_str if '-' in dictionaryOfConnections[i][ 'myDevice'] or '.' in dictionaryOfConnections[i][ 'myDevice']: if '-' in dictionaryOfConnections[i]['myDevice']: new_str = string.replace( dictionaryOfConnections[i]['myDevice'], '-', '_') if '.' in dictionaryOfConnections[i]['myDevice']: new_str = string.replace( dictionaryOfConnections[i]['myDevice'], '.', '_') dictionaryOfConnections[i]['myDevice'] = new_str for j in reversed(xrange(1, (int(nooflevels) + 1))): graph_string = graph_string + "\n\nsubgraph level" + str(j) + " {" if j == 1: graph_string = graph_string + ''' rank=max; node[style=filled, shape=box,color=green, fontsize=8]; ''' elif j == 2: if int(nooflevels) == 2: graph_string = graph_string + ''' rank=min; node[style=filled, shape=box,color=red, fontsize=8]; ''' else: graph_string = graph_string + ''' rank=same; node[style=filled, shape=box,color=red, fontsize=8]; ''' else: graph_string = graph_string + ''' rank=min; node[style=filled, shape=box,color=yellow, fontsize=8]; ''' #Adding the devices to each level for k in xrange(0, len(dictoflevels[j])): #Handling '-' or '.' present in the name if '-' in dictoflevels[j][k] or '.' in dictoflevels[j][k]: if '-' in dictoflevels[j][k]: new_str = string.replace(dictoflevels[j][k], '-', '_') dictoflevels[j][k] = new_str if '.' in dictoflevels[j][k]: new_str = string.replace(dictoflevels[j][k], '.', '_') dictoflevels[j][k] = new_str graph_string = graph_string + dictoflevels[j][k] + ";\n" graph_string = graph_string + "}" #print graph_string #The below is generic connector code graph_string = graph_string + ''' subgraph connector{ ''' #The below block is for converting the topology to graphviz format for i in xrange(0, len(dictionaryOfConnections)): if intfInfo == 'yes': tempvar = dictionaryOfConnections[i][ 'neighborDevice'] + ' -> ' + dictionaryOfConnections[i][ 'myDevice'] + ' [ label = "' + dictionaryOfConnections[i][ 'neighborPort'] + '<------>' + dictionaryOfConnections[ i]['port'] + '",labelfontsize=0.5 ]' else: tempvar = dictionaryOfConnections[i][ 'neighborDevice'] + ' -> ' + dictionaryOfConnections[i][ 'myDevice'] graph_string = graph_string + tempvar + '\n' graph_string = graph_string + '}}' #print graph_string print "----------------------------------------------------------------------------" print "[MESSAGE] If your device names contains either '.' or '-', it will be replaced by '_' to avoid conflict with other packages" print "[MESSAGE] If you get a blank file as output, please verify your includeIxiaPorts for device levels. Your includeIxiaPorts may have given impossible to comprehend/design for our tool \n \n" print "> Completed successfully: \n" #print "There is both a readily-available pdf file as well as a .gv file which can be imported to graphing tools like OmniGraffle for further editing(get license for Omnigraffle from helpdesk..:/\n" try: s = Source(graph_string, filename="Topology.gv", format="pdf") s.view() #Send Email with the script sendEmailSwatExtension() except: print "\n ---------------------------------------------------------------------------------------------------------------------- " print "[ERROR] Looks like we encountered an error. We'll see if installing a package fixes it. Please provide your mac password if prompted" print "---------------------------------------------------------------------------------------------------------------------- " var = os.system( '''/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"''' ) var = os.system("brew install graphviz") os.system( 'tput reset' ) #This is used to clear the screen ...similar to Ctrl+L in bash s = Source(graph_string, filename="Topology.gv", format="pdf") s.view() #Send Email with the script sendEmailSwatExtension() try: installationcheckcmd = "ls /Applications/ | grep -i OmniGraffle" returned_value = subprocess.call(installationcheckcmd, shell=True) if returned_value == 1: #That means OmniGraffle is NOT present print "[MESSAGE] The PDF file (graphic topology) and txt file (text) have been generated in current directory! " #Instead of OmniGraffle not installed message print "* Script Completed! " elif returned_value == 0: #That means OmniGraffle is present print "\t * The PDF file (graphic topology) and txt file (text) have been generated in current directory. Also, OmniGraffle has been opened to edit the GV file (graphic topology). Please choose 'Hierarchial' in OmniGraffle to edit it." subprocess.call([ "/usr/bin/open", "-W", "-n", "-a", "/Applications/OmniGraffle.app", "Topology.gv" ]) except: print "* Script Complete!" sys.exit(1)
def graphGeneratorwithLeafSpine(dictionaryOfConnections, intfInfo): # This part below checks the number of DUTs and connections and based on it, it creates containers for the graphviz code if len(dictionaryOfConnections) > 20: graph_string = ''' digraph finite_state_machine { node [shape = box]; rankdir="LR" ''' if len(dictionaryOfConnections) <= 20: graph_string = ''' digraph finite_state_machine { node [shape = box]; ''' nooflevels = input( "Please enter the number of levels in your topology. Eg) Leaf-Spine is 2 levels and Leaf-Spine-Superspine is 3 levels. (Enter a integer:) " ) alreadyadded = [] dictoflevels = {} #The below block is used for getting the levels of DUTs (.ie. whether leaf/spine/super-spine/...) from user for i in range(1, (int(nooflevels) + 1)): dictoflevels[i] = [] try: for i in range(0, len(dictionaryOfConnections)): if dictionaryOfConnections[i][ 'neighbor'] == dictionaryOfConnections[i]['myDevice']: if dictionaryOfConnections[i]['neighbor'] not in alreadyadded: alreadyadded.append(dictionaryOfConnections[i]['neighbor']) value = input( "Enter the level/hierarchy in range of 1 to " + nooflevels + " (with 1 being lowest) of " + dictionaryOfConnections[i]['neighbor'] + ": ") dictoflevels[int(value)].append( dictionaryOfConnections[i]['neighbor']) else: if dictionaryOfConnections[i]['neighbor'] not in alreadyadded: alreadyadded.append(dictionaryOfConnections[i]['neighbor']) value = input( "Enter the level/hierarchy in range of 1 to " + nooflevels + " (with 1 being lowest) of " + dictionaryOfConnections[i]['neighbor'] + ": ") dictoflevels[int(value)].append( dictionaryOfConnections[i]['neighbor']) if dictionaryOfConnections[i]['myDevice'] not in alreadyadded: alreadyadded.append(dictionaryOfConnections[i]['myDevice']) value = input( "Enter the level/hierarchy in range of 1 to " + nooflevels + " (with 1 being lowest) of " + dictionaryOfConnections[i]['myDevice'] + ": ") dictoflevels[int(value)].append( dictionaryOfConnections[i]['myDevice']) except KeyError as e: logging.info( '[ERROR] The entered value is outside the range of total levels. Please rerun again...' ) abort('* Script Complete') #The below block is for handling '-' and '.' being present in DUT name since it causes error in graphviz for i in range(0, len(dictionaryOfConnections)): if '-' in dictionaryOfConnections[i][ 'neighbor'] or '-' in dictionaryOfConnections[i][ 'myDevice'] or '.' in dictionaryOfConnections[i][ 'neighbor'] or '.' in dictionaryOfConnections[i][ 'myDevice']: if '-' in dictionaryOfConnections[i][ 'neighbor'] or '.' in dictionaryOfConnections[i][ 'neighbor']: if '-' in dictionaryOfConnections[i]['neighbor']: new_str = string.replace( dictionaryOfConnections[i]['neighbor'], '-', '_') if '.' in dictionaryOfConnections[i]['neighbor']: new_str = string.replace( dictionaryOfConnections[i]['neighbor'], '.', '_') dictionaryOfConnections[i]['neighbor'] = new_str if '-' in dictionaryOfConnections[i][ 'myDevice'] or '.' in dictionaryOfConnections[i][ 'myDevice']: if '-' in dictionaryOfConnections[i]['myDevice']: new_str = string.replace( dictionaryOfConnections[i]['myDevice'], '-', '_') if '.' in dictionaryOfConnections[i]['myDevice']: new_str = string.replace( dictionaryOfConnections[i]['myDevice'], '.', '_') dictionaryOfConnections[i]['myDevice'] = new_str #The below block is for creating containers in Dot language for all the levels for j in reversed(range(1, (int(nooflevels) + 1))): graph_string = graph_string + "\n\nsubgraph level" + str(j) + " {" if j == 1: graph_string = graph_string + ''' rank=max; node[style=filled, shape=box,color=green, fontsize=8]; ''' elif j == 2: if int(nooflevels) == 2: graph_string = graph_string + ''' rank=min; node[style=filled, shape=box,color=red, fontsize=8]; ''' else: graph_string = graph_string + ''' rank=same; node[style=filled, shape=box,color=red, fontsize=8]; ''' else: graph_string = graph_string + ''' rank=min; node[style=filled, shape=box,color=yellow, fontsize=8]; ''' #Adding the devices to each level created above for k in range(0, len(dictoflevels[j])): #Handling '-' or '.' present in the name if '-' in dictoflevels[j][k] or '.' in dictoflevels[j][k]: if '-' in dictoflevels[j][k]: new_str = string.replace(dictoflevels[j][k], '-', '_') dictoflevels[j][k] = new_str if '.' in dictoflevels[j][k]: new_str = string.replace(dictoflevels[j][k], '.', '_') dictoflevels[j][k] = new_str graph_string = graph_string + dictoflevels[j][k] + ";\n" graph_string = graph_string + "}" #The below block is used for adding the connections to DUTs for graph generation graph_string = graph_string + ''' subgraph connector{ ''' #The below loop is for converting the topology to graphviz format. Adding the connection details to the graphviz container created above for i in range(0, len(dictionaryOfConnections)): if intfInfo: tempvar = dictionaryOfConnections[i][ 'neighbor'] + ' -> ' + dictionaryOfConnections[i][ 'myDevice'] + ' [ label = "' + dictionaryOfConnections[i][ 'neighbor-port'] + '<------>' + dictionaryOfConnections[ i]['port'] + '",labelfontsize=0.5 ]' #The below else block is for case when user chose not to include interface labels in topology else: tempvar = dictionaryOfConnections[i][ 'neighbor'] + ' -> ' + dictionaryOfConnections[i]['myDevice'] graph_string = graph_string + tempvar + '\n' graph_string = graph_string + '}}' logging.info( "----------------------------------------------------------------------------" ) logging.info( "[MESSAGE] If your device names contains either '.' or '-', it will be replaced by '_' to avoid conflict with other packages" ) logging.info( "[MESSAGE] If you get a blank file as output, please verify your choice for device levels. Your choice may have given impossible to comprehend/design for our tool \n \n" ) logging.info("> Completed: \n") # The below try-except block is for handling errors in graphviz installation due to all the above dependencies on Mac (linux doesn't have much), I try to install brew and then 'brew install graphviz' since brew (unlike apt-get) is not installed by default. try: s = Source(graph_string, filename="Topology.gv", format="pdf") s.view() #Send Email with the script sendEmailSwatExtension() #The below except block is used to install Xcode-Cli tools, brew and graphviz since Mac requires additional dependencies (if not present already) except Exception as e: logging.info( "\n ---------------------------------------------------------------------------------------------------------------------- " ) logging.info("[ERROR] Looks like we encountered an error. ERROR is:") logging.info(e) logging.info( " We'll see if installing a few packages fixes it. Please provide your device (Mac/server) password if prompted." ) logging.info( "---------------------------------------------------------------------------------------------------------------------- " ) #Installing Xcode command-line tools for Mac var1 = os.system("xcode-select --install") #Installing Brew var = os.system( '''/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"''' ) #Installing Graphviz using brew var = os.system("brew install graphviz") #This is used to clear the screen ...similar to Ctrl+L in bash os.system('tput reset') s = Source(graph_string, filename="Topology.gv", format="pdf") s.view() #Send Email with the script sendEmailSwatExtension() #The below code block if for opening the editable .gv file using Omnigraffle if it is installed on the user's Mac. Else, skip and print 'Script Complete' try: installationcheckcmd = "ls /Applications/ | grep -i OmniGraffle" returned_value = subprocess.call(installationcheckcmd, shell=True) if returned_value == 1: #That means OmniGraffle is NOT present logging.info( "[MESSAGE] The PDF file (graphic topology) and txt file (text) have been generated in current directory! " ) #Instead of OmniGraffle not installed message abort("* Script Completed! ") elif returned_value == 0: #That means OmniGraffle is present logging.info( "\t * The PDF file (graphic topology) and txt file (text) have been generated in current directory. Also, OmniGraffle has been opened to edit the GV file (graphic topology). Please choose 'Hierarchial' in OmniGraffle to edit it." ) subprocess.call([ "/usr/bin/open", "-W", "-n", "-a", "/Applications/OmniGraffle.app", "Topology.gv" ]) except: abort("* Script Complete!")
def graph(self): self.visit(None, self.ast) s = Source(self.dot.source, filename='graph', format='png') return s.view()
import os import sys from graphviz import Source os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/' path = sys.argv[1] fileEnding = sys.argv[2] file = open(path, 'r') #READING DOT FILE text = file.read() s = Source(text, filename=path, format=fileEnding) s.view() file.close()
temp += "tabla2 [label=<\n" temp += "<table>\n" temp += "<tr>\n" for y in range(n3): for x in range(n2): if (pot[y][x] != n5 * n2 + n4): temp += "\t<td bgcolor=\"blue\">(" + str( cont2) + ")" + str(pot[y][x]) + "</td>\n" else: temp += "\t<td bgcolor=\"yellow\">(" + str( cont2) + ")" + str(pot[y][x]) + "</td>\n" cont2 = cont2 + 1 temp += "</tr>\n" temp += "</table> >,]; }" sp = Source(temp, filename="mapeo por filas", format="png") sp.view() elif n1 == 2: cont = 0 print(".: Ingrese el tamaño del arreglo:.") n2 = int(input("Ingrese X: ")) n3 = int(input("Ingrese Y: ")) pot = CreaMatriz(n3, n2) print(".: Ingrese las posicion a linealizar:.") n4 = int(input("Ingrese X: ")) n5 = int(input("Ingrese Y: ")) print("Resultado= Posicion " + str(n4 * n3 + n5)) temp = "digraph G{\n" temp += "label=\"Matriz\";\n" temp += "node [shape=record, color=blue]\n"