SlideShare una empresa de Scribd logo
1 de 36
Descargar para leer sin conexión
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




                                            NetworkX Tutorial

                                                   Evan Rosen


                                               October 6, 2011




Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




          1 Installation

          2 Basic Classes

          3 Generating Graphs

          4 Analyzing Graphs

          5 Save/Load

          6 Plotting (Matplotlib)




Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Local Installation


                install manually from
                http://pypi.python.org/pypi/networkx
                or use built-in python package manager, easy install
                $ easy install networkx
                or use macports
                $ sudo port install py27-networkx
                use pip (replacement for easy install)
                $ sudo pip install networkx
                or use debian package manager
                $ sudo apt-get install python-networkx


Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Cluster Setup



                networkx is already installed on the corn cluster
                Only works for python version 2.6, 2.7
                However default mapping of command ’python’ is to version
                2.4
                Just type ‘python2.6’ instead or make an alias in your shell
                configuration




Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Basic Example



          >>> import networkx as nx
          >>> G = nx . Graph ()
          >>> G . add_node ( " spam " )
          >>> G . add_edge (1 ,2)
          >>> print ( G . nodes () )
          [1 , 2 , ’ spam ’]
          >>> print ( G . edges () )
          [(1 , 2) ]




Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Graph Types

                Graph : Undirected simple (allows self loops)
                DiGraph : Directed simple (allows self loops)
                MultiGraph : Undirected with parallel edges
                MultiDiGraph : Directed with parallel edges
                can convert to undirected: g.to undirected()
                can convert to directed: g.to directed()
          To construct, use standard python syntax:
          >>>      g    =   nx . Graph ()
          >>>      d    =   nx . DiGraph ()
          >>>      m    =   nx . MultiGraph ()
          >>>      h    =   nx . MultiDiGraph ()

Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Adding Nodes

                add nodes from() takes any iterable collection and any
                object

          >>> g = nx . Graph ()
          >>> g . add_node ( ’a ’)
          >>> g . add_nodes_from ( [ ‘ b ’ ,‘c ’ ,‘d ’ ])
          >>> g . add_nodes_from ( ’ xyz ’)
          >>> h = nx . path_graph (5)
          >>> g . add_nodes_from ( h )
          >>> g . nodes ()
          [0 ,1 , ‘ c ’ ,‘b ’ ,4 , ‘ d ’ ,2 ,3 ,5 , ‘ x ’ ,‘y ’ ,‘z ’]


Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Adding Edges


                Adding an edge between nodes that don’t exist will
                automatically add those nodes
                add nodes from() takes any iterable collection and any type
                (anything that has a iter () method)

          >>> g = nx . Graph ( [( ‘ a ’ ,‘b ’) ,( ‘ b ’ ,‘c ’) ,( ‘ c ’
             ,‘a ’) ] )
          >>> g . add_edge ( ’a ’ , ’d ’)
          >>> g . add_edges_from ([( ‘ d ’ , ‘c ’) , ( ‘ d ’ , ‘b ’)
             ])



Evan Rosen
NetworkX Tutorial
Outline      Installation     Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Adding Node and Edge attributes
                Every node and edge is associated with a dictionary from
                attribute keys to values
                Type indifferent, just needs to be hashable
                            i.e. can’t use list, must use tuple
                            >>> G = nx . Graph ()
                            >>> G . add_node ([1 ,2])
                            Traceback ( most recent call last ) :
                            File " < stdin > " , line 1 , in < module >
                            File " / usr / lib / pymodules / python2 .7/
                               networkx / classes / graph . py " , line 377 ,
                               in add_node
                                if n not in self . adj :
                            TypeError : unhashable type : ’ list ’

                No consistency among attribute dicts enforced by NetworkX
Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Node attributes



                Can add node attributes as optional arguments along with
                most add methods

          >>> g = nx . Graph ()
          >>> g . add_node (1 , name = ‘ Obrian ’)
          >>> g . add_nodes_from ([2] , name = ‘ Quintana ’ ])
          >>> g [1][ ‘ name ’]
          ‘ Obrian ’




Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Edge attributes

                Can add edge attributes as optional arguments along with
                most add methods

          >>> g . add_edge (1 , 2 , w =4.7 )
          >>> g . add_edges_from ([(3 ,4) ,(4 ,5) ] , w =3.0)
          >>> g . add_edges_from ([(1 ,2 ,{ ‘ val ’ :2.0}) ])
          # adds third value in tuple as ‘ weight ’ attr
          >>> g . ad d _w ei g h t e d _ e d g e s _ f r o m ([(6 ,7 ,3.0) ])
          >>> g . get_edge_data (3 ,4)
          { ‘ w ’ : 3.0}
          >>> g . add_edge (5 ,6)
          >>> g [5][6]
          {}

Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Simple Properties
                Number of nodes :
                >>> len ( g )
                >>> g . number_of_nodes ()
                >>> g . order ()

                Number of Edges
                >>> g . number_of_edges ()

                Check node membership
                >>> g . has_node (1)

                Check edge presence
                >>> g . has_edge (1)

Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Neighbors
                Iterating over edges
                can be useful for efficiency
          >>> G = nx . Graph ()
          >>> G . add_path ([0 ,1 ,2 ,3])
          >>> [ e for e in G . edges_iter () ]
          [(0 , 1) , (1 , 2) , (2 , 3) ]
          >>> [( n , nbrs ) for n , nbrs in G . adjacency_iter
              () ]
          [(0 , {1: {}}) , (1 , {0: {} , 2: {}}) , (2 , {1:
              {} , 3: {}}) , (3 , {2: {}}) ]
          >>> G [1][2][ ’ new_attr ’] = 5
          >>> G [1][2][ ’ new_attr ’]
          5

Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Degrees


            >>> G . degree (0)
          1
          >>> G . degree ([0 ,1])
          {0: 1 , 1: 2}
          >>> G . degree ()
          {1: 1 , 2: 2 , 3: 2 , 4: 1}
          >>> G . degree () . values () # useful for degree
              dist
          [1 , 2 , 2 , 1]




Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Simple Graph Generators
                located in networkx.generators.classic module
                Complete Graph
                nx . complete_graph (5)

                Chain
                nx . path_graph (5)

                Bipartite
                nx . c om p l e te _ b i p a r t i t e _ g r a p h ( n1 , n2 )

                Arbitrary Dimensional Lattice (nodes are tuples of ints)
                nx . grid_graph ([10 ,10 ,10 ,10]) # 4D , 100^4
                     nodes

Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Random Graph Generators

                located in module networkx.generators.random graphs
                Preferential Attachment
                nx . ba raba si_ a l b e r t _ g r a p h (n , m )

                Gn,p
                nx . gnp_random_graph (n , p )


                nx . gnm_random_graph (n , m )


                nx . watts_str o g a t z _ g r a p h (n , k , p }


Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Stochastic Graph Generators



                located in module networkx.generators.stochastic
                Configuration Model / Rewired
                deg sequence is a list of integers representing the degree for
                each node. Does not eliminate self loops
                c onfiguratio n _ mo d e l ( deg_sequence )




Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Algorithms Package (networkx.algorithms)

               bipartite                                              flow (package)
               block                                                  isolates
               boundary                                               isomorphism (package)
               centrality (package)                                   link analysis (package)
               clique                                                 matching
               cluster                                                mixing
               components (package)                                   mst
               core                                                   operators
               cycles                                                 shortest paths (package)
               dag                                                    smetric
               distance measures
Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Use the Python Help Viewer

          >>> import networkx as nx
          >>> help ( nx . algorithms )

                pops up an instance of ‘less’ (the pager utility)




Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




A Few Useful Functions

                As subgraphs
                nx . c o n n e c t e d _ c o m p o n e n t _ s u b g r a p h s ( G )

                Operations on Graph
                nx . union (G , H ) , intersection (G , H ) ,
                     complement ( G )

                k-cores
                nx . find_cores ( G )



Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




A Few More
                shortest path
                nx . shortest_path (G ,s , t )
                nx . b et we en ne s s _ c e n t r a l i t y ( G )

                clustering
                nx . average_c lu st er in g ( G )

                >>> G = nx . complete_graph (5)
                >>> nx . clustering ( G )
                {0: 1.0 , 1: 1.0 , 2: 1.0 , 3: 1.0 , 4: 1.0}

                diameter
                nx . diameter ( G )

Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Edge List Text File

          nx . read_edgelist ( ‘ elist ’ , comment = ‘# ’ ,
               delimiter = ‘ t ’)
          nx . write_edgelist (G , path )
          >>> G . edges ()
          [( u ‘1 ’ , u ‘3 ’) , (u ‘1 ’ , u ‘2 ’) , (u ‘3 ’ , u ‘2 ’) ]
          >>> G . add_edge (u ‘1 ’ ,u ‘3 ’)
          >>> nx . save_edgelist (G , ’ elist_new ’ , data =
               False )


      # edge list file                                          # new edge list file
      1       2                                                 1       2
      3       2                                                 3       2
                                                                3       1

Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Importing Other Graph Formats


                GML
                Pickle
                GraphML
                YAML
                Pajek
                GEXF
                LEDA
                SparseGraph6
                GIS Shapefile


Evan Rosen
NetworkX Tutorial
Outline      Installation     Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Matplotlib

                A python package which emulates matlab functionality
                            Well documented at
                            http://matplotlib.sourceforge.net/contents.html
                Interfaces nicely with NetworkX
                Depends on Numpy which provides multidimensional array
                support:
                            http://numpy.scipy.org/
                We only really need it for plotting

          >>> import matplotlib . pyplot as plt
          >>> plt . plot ( range (10) , range (10) )


Evan Rosen
NetworkX Tutorial
Outline      Installation     Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Backend

                Need to specify a backend
                This is the program which is responsible for either displaying
                or writing the plots to file
                does not change matplotlib plotting tools
                options include
                            ‘MacOSX’ interactive plot tool for mac OS X
                            ‘GTKAgg’ cross-platform interactive plot tool
                            ‘PDF’ A “renderer” in PDF format
                            ‘PS’ A “renderer” in PostScript format
                For more info, see: http://matplotlib.sourceforge.net/
                faq/installing_faq.html#what-is-a-backend
                renderers are useful for working on clusters because they don’t
                require a windowing system
Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Configuring Backend

                can be set within the script itself:
                import matplotlib
                matplotlib . use ( ‘ PDF ’)
                import matplotlib . pyplot as plt
                # need to do these steps in this order

                can be set in the matplotlib config file:
                /.matplotlib/matplotlibrc
                ...
                backend                       : MacOSX
                ...


Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs        Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Basic Graph Drawing (with matplotlib)

          import networkx as nx
          import matplotlib . pyplot as plt
          >>> G = nx . path_graph (10)
          >>> nx . draw ( G )
          >>> plt . savefig ( " path_graph . pdf " )

                consult package nx.drawing for more options
                                                         7   6
                                                     8           5
                                                 9
                                                                       4


                                                                           3


                                                                               2


                                                                               1

                                                                               0




Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Basic Data Plotting

          def get_phase_curve ( n ) :
              ps = np . arange (0.001 ,0.1 ,0.005)
              cs = []
              for p in ps :
                  G = nx . gnp_random_graph (n , p )
                  c = nx . c o n n e c t e d _ c o m p o n e n t _ s u b g r a p h s
                      ( G ) [0]. order ()
                  cs . append ( float ( c ) /100)
              return cs

           plt . plot ( ps , get_phase_curve (100) )
           plt . savefig ( ‘ phase . pdf ’)


Evan Rosen
NetworkX Tutorial
Outline      Installation    Basic Classes      Generating Graphs   Analyzing Graphs    Save/Load   Plotting (Matplotlib)




Phase Change Plot

                            1.0


                            0.8


                            0.6


                            0.4


                            0.2


                            0.0
                             0.00            0.02        0.04       0.06         0.08        0.10


Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes    Generating Graphs           Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Plotting Multiple Series on Same Axes
                Let’s add another curve
          plt . clf ()
          ps = np . arange (0.001 ,0.1 ,0.005)
          plt . plot ( ps , get_phase_curve ( ps ,100) )
          plt . plot ( ps , get_phase_curve ( ps ,200) )
          plt . savefig ( ’ phase_100_200 . pdf ’)

                                            1.0


                                            0.8


                                            0.6


                                            0.4


                                            0.2


                                            0.0
                                             0.00   0.02   0.04   0.06       0.08   0.10


Evan Rosen
NetworkX Tutorial
Outline      Installation     Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Plotting Basics

                matplotlib has an internal structure much like matlab
                good resource:
                            matplotlib.sourceforge.net/users/artists.html
                several objects involved in every plot
                     figure top level container for all plot elements
                        axes a specific set of axes (as in a subplot)
                        axis a specific axis (x or y)

          >>>      fig = plt . figure ()
          >>>      ax = fig . add_subplot (1 ,1 ,1)
          >>>      h = ax . plot ( range (10) , range (10) )
          >>>      plt . show ()

Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs     Analyzing Graphs      Save/Load   Plotting (Matplotlib)




Log Plots
          ps , cs = get_phase_curve (100)
          plt . loglog ( ps , cs ) # also see semilog
          plt . savefig ( ‘ phase_log_log . pdf ’)


                                   100




                                  10-1




                                  10-2 -3
                                     10                    10-2                      10-1

Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Legends


                each call to plt.plot returns a handle object for the series
                of type matplotlib.lines.Line2D
                to add a legend, call use method
                plt.legend([handles],[labels])
                can control placement with keyword argument
                loc=[1,. . .,10] (uppper left, lower left, ...)

          h_100 = plt . plot ( ps , get_phase_curve (100) )
          h_200 = plt . plot ( ps , get_phase_curve (200) )
          plt . legend ([ h_100 , h_200 ] ,[ ‘ n =100 ’ ,‘n =200 ’ ])



Evan Rosen
NetworkX Tutorial
Outline      Installation    Basic Classes      Generating Graphs   Analyzing Graphs    Save/Load   Plotting (Matplotlib)




Legends

                            1.0
                                                                                        n=100
                                                                                        n=200
                            0.8


                            0.6


                            0.4


                            0.2


                            0.0
                             0.00            0.02        0.04       0.06         0.08        0.10


Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Legends
                Can use Latex:
                plt . legend ([ h_100 , h_200 ] ,[ ’ $$ n =100 $$ ’ , ’
                    $$ n =200 $$ ’ ])




Evan Rosen
NetworkX Tutorial
Outline      Installation   Basic Classes   Generating Graphs   Analyzing Graphs   Save/Load   Plotting (Matplotlib)




Resources
                NetworkX Docs
                http://networkx.lanl.gov/tutorial/index.html
                NetworkX Tutorial
                http://networkx.lanl.gov/contents.html
                Matplotlib Docs
                http://matplotlib.sourceforge.net/contents.html
                Matplotlib Tutorial
                http://matplotlib.sourceforge.net/users/pyplot_
                tutorial.html
                Numpy Docs
                http://numpy.scipy.org/
                MacPorts
                http://macports.org
Evan Rosen
NetworkX Tutorial

Más contenido relacionado

La actualidad más candente

Computational Learning Theory
Computational Learning TheoryComputational Learning Theory
Computational Learning Theorybutest
 
Generative adversarial networks
Generative adversarial networksGenerative adversarial networks
Generative adversarial networks남주 김
 
AI 7 | Constraint Satisfaction Problem
AI 7 | Constraint Satisfaction ProblemAI 7 | Constraint Satisfaction Problem
AI 7 | Constraint Satisfaction ProblemMohammad Imam Hossain
 
Generative Adversarial Networks
Generative Adversarial NetworksGenerative Adversarial Networks
Generative Adversarial NetworksMustafa Yagmur
 
Generative adversarial networks
Generative adversarial networksGenerative adversarial networks
Generative adversarial networksYunjey Choi
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)PyData
 
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...Edureka!
 
Deep Learning With Neural Networks
Deep Learning With Neural NetworksDeep Learning With Neural Networks
Deep Learning With Neural NetworksAniket Maurya
 
Autoencoders
AutoencodersAutoencoders
AutoencodersCloudxLab
 
Deep Learning - Convolutional Neural Networks
Deep Learning - Convolutional Neural NetworksDeep Learning - Convolutional Neural Networks
Deep Learning - Convolutional Neural NetworksChristian Perone
 
Convolutional Neural Networks
Convolutional Neural NetworksConvolutional Neural Networks
Convolutional Neural NetworksAshray Bhandare
 
Graph Neural Network - Introduction
Graph Neural Network - IntroductionGraph Neural Network - Introduction
Graph Neural Network - IntroductionJungwon Kim
 
Decision tree in artificial intelligence
Decision tree in artificial intelligenceDecision tree in artificial intelligence
Decision tree in artificial intelligenceMdAlAmin187
 
A Fast and Dirty Intro to NetworkX (and D3)
A Fast and Dirty Intro to NetworkX (and D3)A Fast and Dirty Intro to NetworkX (and D3)
A Fast and Dirty Intro to NetworkX (and D3)Lynn Cherny
 

La actualidad más candente (20)

Computational Learning Theory
Computational Learning TheoryComputational Learning Theory
Computational Learning Theory
 
Generative adversarial networks
Generative adversarial networksGenerative adversarial networks
Generative adversarial networks
 
Vgg
VggVgg
Vgg
 
Python for Data Science
Python for Data SciencePython for Data Science
Python for Data Science
 
AI 7 | Constraint Satisfaction Problem
AI 7 | Constraint Satisfaction ProblemAI 7 | Constraint Satisfaction Problem
AI 7 | Constraint Satisfaction Problem
 
Python numbers
Python numbersPython numbers
Python numbers
 
Generative Adversarial Networks
Generative Adversarial NetworksGenerative Adversarial Networks
Generative Adversarial Networks
 
Generative adversarial networks
Generative adversarial networksGenerative adversarial networks
Generative adversarial networks
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
 
Hill climbing algorithm
Hill climbing algorithmHill climbing algorithm
Hill climbing algorithm
 
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
 
Deep Learning With Neural Networks
Deep Learning With Neural NetworksDeep Learning With Neural Networks
Deep Learning With Neural Networks
 
Cnn
CnnCnn
Cnn
 
Deep learning
Deep learningDeep learning
Deep learning
 
Autoencoders
AutoencodersAutoencoders
Autoencoders
 
Deep Learning - Convolutional Neural Networks
Deep Learning - Convolutional Neural NetworksDeep Learning - Convolutional Neural Networks
Deep Learning - Convolutional Neural Networks
 
Convolutional Neural Networks
Convolutional Neural NetworksConvolutional Neural Networks
Convolutional Neural Networks
 
Graph Neural Network - Introduction
Graph Neural Network - IntroductionGraph Neural Network - Introduction
Graph Neural Network - Introduction
 
Decision tree in artificial intelligence
Decision tree in artificial intelligenceDecision tree in artificial intelligence
Decision tree in artificial intelligence
 
A Fast and Dirty Intro to NetworkX (and D3)
A Fast and Dirty Intro to NetworkX (and D3)A Fast and Dirty Intro to NetworkX (and D3)
A Fast and Dirty Intro to NetworkX (and D3)
 

Destacado

Nx basics 2014 unfnished
Nx basics 2014 unfnishedNx basics 2014 unfnished
Nx basics 2014 unfnishedMiguele Davila
 
123 d design-tutorial-de
123 d design-tutorial-de123 d design-tutorial-de
123 d design-tutorial-dePascal Müller
 
3D-Printing Basics - 3D-Druck Grundlagen - rioprinto.com
3D-Printing Basics - 3D-Druck Grundlagen - rioprinto.com3D-Printing Basics - 3D-Druck Grundlagen - rioprinto.com
3D-Printing Basics - 3D-Druck Grundlagen - rioprinto.comrioprinto
 
Manual cam completo unigraphics(en español)
Manual cam completo unigraphics(en español)Manual cam completo unigraphics(en español)
Manual cam completo unigraphics(en español)errmanue
 
3D-DAY in Friedrichshafen
3D-DAY in Friedrichshafen3D-DAY in Friedrichshafen
3D-DAY in FriedrichshafenGeorg Eck
 

Destacado (7)

Nx basics 2014 unfnished
Nx basics 2014 unfnishedNx basics 2014 unfnished
Nx basics 2014 unfnished
 
Ab cdari
Ab cdariAb cdari
Ab cdari
 
123 d design-tutorial-de
123 d design-tutorial-de123 d design-tutorial-de
123 d design-tutorial-de
 
3D-Printing Basics - 3D-Druck Grundlagen - rioprinto.com
3D-Printing Basics - 3D-Druck Grundlagen - rioprinto.com3D-Printing Basics - 3D-Druck Grundlagen - rioprinto.com
3D-Printing Basics - 3D-Druck Grundlagen - rioprinto.com
 
NX Tutorial
NX TutorialNX Tutorial
NX Tutorial
 
Manual cam completo unigraphics(en español)
Manual cam completo unigraphics(en español)Manual cam completo unigraphics(en español)
Manual cam completo unigraphics(en español)
 
3D-DAY in Friedrichshafen
3D-DAY in Friedrichshafen3D-DAY in Friedrichshafen
3D-DAY in Friedrichshafen
 

Similar a Nx tutorial basics

Towards Safe Automated Refactoring of Imperative Deep Learning Programs to Gr...
Towards Safe Automated Refactoring of Imperative Deep Learning Programs to Gr...Towards Safe Automated Refactoring of Imperative Deep Learning Programs to Gr...
Towards Safe Automated Refactoring of Imperative Deep Learning Programs to Gr...Raffi Khatchadourian
 
PPT ON MACHINE LEARNING by Ragini Ratre
PPT ON MACHINE LEARNING by Ragini RatrePPT ON MACHINE LEARNING by Ragini Ratre
PPT ON MACHINE LEARNING by Ragini RatreRaginiRatre
 
Overview of Chainer and Its Features
Overview of Chainer and Its FeaturesOverview of Chainer and Its Features
Overview of Chainer and Its FeaturesSeiya Tokui
 
A gentle introduction to functional programming through music and clojure
A gentle introduction to functional programming through music and clojureA gentle introduction to functional programming through music and clojure
A gentle introduction to functional programming through music and clojurePaul Lam
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnArnaud Joly
 
(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_iNico Ludwig
 
Deep Learning and TensorFlow
Deep Learning and TensorFlowDeep Learning and TensorFlow
Deep Learning and TensorFlowOswald Campesato
 
Python for R developers and data scientists
Python for R developers and data scientistsPython for R developers and data scientists
Python for R developers and data scientistsLambda Tree
 
Introduction to Deep Learning and Tensorflow
Introduction to Deep Learning and TensorflowIntroduction to Deep Learning and Tensorflow
Introduction to Deep Learning and TensorflowOswald Campesato
 
Using R on Netezza
Using R on NetezzaUsing R on Netezza
Using R on NetezzaAjay Ohri
 
NVIDIA HPC ソフトウエア斜め読み
NVIDIA HPC ソフトウエア斜め読みNVIDIA HPC ソフトウエア斜め読み
NVIDIA HPC ソフトウエア斜め読みNVIDIA Japan
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Raffi Khatchadourian
 
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...David Walker
 
Reproducible Computational Research in R
Reproducible Computational Research in RReproducible Computational Research in R
Reproducible Computational Research in RSamuel Bosch
 
RDataMining slides-r-programming
RDataMining slides-r-programmingRDataMining slides-r-programming
RDataMining slides-r-programmingYanchang Zhao
 

Similar a Nx tutorial basics (20)

Towards Safe Automated Refactoring of Imperative Deep Learning Programs to Gr...
Towards Safe Automated Refactoring of Imperative Deep Learning Programs to Gr...Towards Safe Automated Refactoring of Imperative Deep Learning Programs to Gr...
Towards Safe Automated Refactoring of Imperative Deep Learning Programs to Gr...
 
PPT ON MACHINE LEARNING by Ragini Ratre
PPT ON MACHINE LEARNING by Ragini RatrePPT ON MACHINE LEARNING by Ragini Ratre
PPT ON MACHINE LEARNING by Ragini Ratre
 
Overview of Chainer and Its Features
Overview of Chainer and Its FeaturesOverview of Chainer and Its Features
Overview of Chainer and Its Features
 
Deep Learning for Computer Vision: Software Frameworks (UPC 2016)
Deep Learning for Computer Vision: Software Frameworks (UPC 2016)Deep Learning for Computer Vision: Software Frameworks (UPC 2016)
Deep Learning for Computer Vision: Software Frameworks (UPC 2016)
 
A gentle introduction to functional programming through music and clojure
A gentle introduction to functional programming through music and clojureA gentle introduction to functional programming through music and clojure
A gentle introduction to functional programming through music and clojure
 
NvFX GTC 2013
NvFX GTC 2013NvFX GTC 2013
NvFX GTC 2013
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
 
(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i
 
Deep Learning and TensorFlow
Deep Learning and TensorFlowDeep Learning and TensorFlow
Deep Learning and TensorFlow
 
Python for R developers and data scientists
Python for R developers and data scientistsPython for R developers and data scientists
Python for R developers and data scientists
 
PMED Undergraduate Workshop - R Tutorial for PMED Undegraduate Workshop - Xi...
PMED Undergraduate Workshop - R Tutorial for PMED Undegraduate Workshop  - Xi...PMED Undergraduate Workshop - R Tutorial for PMED Undegraduate Workshop  - Xi...
PMED Undergraduate Workshop - R Tutorial for PMED Undegraduate Workshop - Xi...
 
Introduction to Deep Learning and Tensorflow
Introduction to Deep Learning and TensorflowIntroduction to Deep Learning and Tensorflow
Introduction to Deep Learning and Tensorflow
 
Using R on Netezza
Using R on NetezzaUsing R on Netezza
Using R on Netezza
 
NVIDIA HPC ソフトウエア斜め読み
NVIDIA HPC ソフトウエア斜め読みNVIDIA HPC ソフトウエア斜め読み
NVIDIA HPC ソフトウエア斜め読み
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
 
Cascalog internal dsl_preso
Cascalog internal dsl_presoCascalog internal dsl_preso
Cascalog internal dsl_preso
 
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...
 
Reproducible Computational Research in R
Reproducible Computational Research in RReproducible Computational Research in R
Reproducible Computational Research in R
 
RDataMining slides-r-programming
RDataMining slides-r-programmingRDataMining slides-r-programming
RDataMining slides-r-programming
 

Último

"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 

Último (20)

"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 

Nx tutorial basics

  • 1. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) NetworkX Tutorial Evan Rosen October 6, 2011 Evan Rosen NetworkX Tutorial
  • 2. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) 1 Installation 2 Basic Classes 3 Generating Graphs 4 Analyzing Graphs 5 Save/Load 6 Plotting (Matplotlib) Evan Rosen NetworkX Tutorial
  • 3. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Local Installation install manually from http://pypi.python.org/pypi/networkx or use built-in python package manager, easy install $ easy install networkx or use macports $ sudo port install py27-networkx use pip (replacement for easy install) $ sudo pip install networkx or use debian package manager $ sudo apt-get install python-networkx Evan Rosen NetworkX Tutorial
  • 4. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Cluster Setup networkx is already installed on the corn cluster Only works for python version 2.6, 2.7 However default mapping of command ’python’ is to version 2.4 Just type ‘python2.6’ instead or make an alias in your shell configuration Evan Rosen NetworkX Tutorial
  • 5. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Basic Example >>> import networkx as nx >>> G = nx . Graph () >>> G . add_node ( " spam " ) >>> G . add_edge (1 ,2) >>> print ( G . nodes () ) [1 , 2 , ’ spam ’] >>> print ( G . edges () ) [(1 , 2) ] Evan Rosen NetworkX Tutorial
  • 6. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Graph Types Graph : Undirected simple (allows self loops) DiGraph : Directed simple (allows self loops) MultiGraph : Undirected with parallel edges MultiDiGraph : Directed with parallel edges can convert to undirected: g.to undirected() can convert to directed: g.to directed() To construct, use standard python syntax: >>> g = nx . Graph () >>> d = nx . DiGraph () >>> m = nx . MultiGraph () >>> h = nx . MultiDiGraph () Evan Rosen NetworkX Tutorial
  • 7. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Adding Nodes add nodes from() takes any iterable collection and any object >>> g = nx . Graph () >>> g . add_node ( ’a ’) >>> g . add_nodes_from ( [ ‘ b ’ ,‘c ’ ,‘d ’ ]) >>> g . add_nodes_from ( ’ xyz ’) >>> h = nx . path_graph (5) >>> g . add_nodes_from ( h ) >>> g . nodes () [0 ,1 , ‘ c ’ ,‘b ’ ,4 , ‘ d ’ ,2 ,3 ,5 , ‘ x ’ ,‘y ’ ,‘z ’] Evan Rosen NetworkX Tutorial
  • 8. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Adding Edges Adding an edge between nodes that don’t exist will automatically add those nodes add nodes from() takes any iterable collection and any type (anything that has a iter () method) >>> g = nx . Graph ( [( ‘ a ’ ,‘b ’) ,( ‘ b ’ ,‘c ’) ,( ‘ c ’ ,‘a ’) ] ) >>> g . add_edge ( ’a ’ , ’d ’) >>> g . add_edges_from ([( ‘ d ’ , ‘c ’) , ( ‘ d ’ , ‘b ’) ]) Evan Rosen NetworkX Tutorial
  • 9. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Adding Node and Edge attributes Every node and edge is associated with a dictionary from attribute keys to values Type indifferent, just needs to be hashable i.e. can’t use list, must use tuple >>> G = nx . Graph () >>> G . add_node ([1 ,2]) Traceback ( most recent call last ) : File " < stdin > " , line 1 , in < module > File " / usr / lib / pymodules / python2 .7/ networkx / classes / graph . py " , line 377 , in add_node if n not in self . adj : TypeError : unhashable type : ’ list ’ No consistency among attribute dicts enforced by NetworkX Evan Rosen NetworkX Tutorial
  • 10. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Node attributes Can add node attributes as optional arguments along with most add methods >>> g = nx . Graph () >>> g . add_node (1 , name = ‘ Obrian ’) >>> g . add_nodes_from ([2] , name = ‘ Quintana ’ ]) >>> g [1][ ‘ name ’] ‘ Obrian ’ Evan Rosen NetworkX Tutorial
  • 11. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Edge attributes Can add edge attributes as optional arguments along with most add methods >>> g . add_edge (1 , 2 , w =4.7 ) >>> g . add_edges_from ([(3 ,4) ,(4 ,5) ] , w =3.0) >>> g . add_edges_from ([(1 ,2 ,{ ‘ val ’ :2.0}) ]) # adds third value in tuple as ‘ weight ’ attr >>> g . ad d _w ei g h t e d _ e d g e s _ f r o m ([(6 ,7 ,3.0) ]) >>> g . get_edge_data (3 ,4) { ‘ w ’ : 3.0} >>> g . add_edge (5 ,6) >>> g [5][6] {} Evan Rosen NetworkX Tutorial
  • 12. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Simple Properties Number of nodes : >>> len ( g ) >>> g . number_of_nodes () >>> g . order () Number of Edges >>> g . number_of_edges () Check node membership >>> g . has_node (1) Check edge presence >>> g . has_edge (1) Evan Rosen NetworkX Tutorial
  • 13. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Neighbors Iterating over edges can be useful for efficiency >>> G = nx . Graph () >>> G . add_path ([0 ,1 ,2 ,3]) >>> [ e for e in G . edges_iter () ] [(0 , 1) , (1 , 2) , (2 , 3) ] >>> [( n , nbrs ) for n , nbrs in G . adjacency_iter () ] [(0 , {1: {}}) , (1 , {0: {} , 2: {}}) , (2 , {1: {} , 3: {}}) , (3 , {2: {}}) ] >>> G [1][2][ ’ new_attr ’] = 5 >>> G [1][2][ ’ new_attr ’] 5 Evan Rosen NetworkX Tutorial
  • 14. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Degrees >>> G . degree (0) 1 >>> G . degree ([0 ,1]) {0: 1 , 1: 2} >>> G . degree () {1: 1 , 2: 2 , 3: 2 , 4: 1} >>> G . degree () . values () # useful for degree dist [1 , 2 , 2 , 1] Evan Rosen NetworkX Tutorial
  • 15. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Simple Graph Generators located in networkx.generators.classic module Complete Graph nx . complete_graph (5) Chain nx . path_graph (5) Bipartite nx . c om p l e te _ b i p a r t i t e _ g r a p h ( n1 , n2 ) Arbitrary Dimensional Lattice (nodes are tuples of ints) nx . grid_graph ([10 ,10 ,10 ,10]) # 4D , 100^4 nodes Evan Rosen NetworkX Tutorial
  • 16. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Random Graph Generators located in module networkx.generators.random graphs Preferential Attachment nx . ba raba si_ a l b e r t _ g r a p h (n , m ) Gn,p nx . gnp_random_graph (n , p ) nx . gnm_random_graph (n , m ) nx . watts_str o g a t z _ g r a p h (n , k , p } Evan Rosen NetworkX Tutorial
  • 17. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Stochastic Graph Generators located in module networkx.generators.stochastic Configuration Model / Rewired deg sequence is a list of integers representing the degree for each node. Does not eliminate self loops c onfiguratio n _ mo d e l ( deg_sequence ) Evan Rosen NetworkX Tutorial
  • 18. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Algorithms Package (networkx.algorithms) bipartite flow (package) block isolates boundary isomorphism (package) centrality (package) link analysis (package) clique matching cluster mixing components (package) mst core operators cycles shortest paths (package) dag smetric distance measures Evan Rosen NetworkX Tutorial
  • 19. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Use the Python Help Viewer >>> import networkx as nx >>> help ( nx . algorithms ) pops up an instance of ‘less’ (the pager utility) Evan Rosen NetworkX Tutorial
  • 20. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) A Few Useful Functions As subgraphs nx . c o n n e c t e d _ c o m p o n e n t _ s u b g r a p h s ( G ) Operations on Graph nx . union (G , H ) , intersection (G , H ) , complement ( G ) k-cores nx . find_cores ( G ) Evan Rosen NetworkX Tutorial
  • 21. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) A Few More shortest path nx . shortest_path (G ,s , t ) nx . b et we en ne s s _ c e n t r a l i t y ( G ) clustering nx . average_c lu st er in g ( G ) >>> G = nx . complete_graph (5) >>> nx . clustering ( G ) {0: 1.0 , 1: 1.0 , 2: 1.0 , 3: 1.0 , 4: 1.0} diameter nx . diameter ( G ) Evan Rosen NetworkX Tutorial
  • 22. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Edge List Text File nx . read_edgelist ( ‘ elist ’ , comment = ‘# ’ , delimiter = ‘ t ’) nx . write_edgelist (G , path ) >>> G . edges () [( u ‘1 ’ , u ‘3 ’) , (u ‘1 ’ , u ‘2 ’) , (u ‘3 ’ , u ‘2 ’) ] >>> G . add_edge (u ‘1 ’ ,u ‘3 ’) >>> nx . save_edgelist (G , ’ elist_new ’ , data = False ) # edge list file # new edge list file 1 2 1 2 3 2 3 2 3 1 Evan Rosen NetworkX Tutorial
  • 23. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Importing Other Graph Formats GML Pickle GraphML YAML Pajek GEXF LEDA SparseGraph6 GIS Shapefile Evan Rosen NetworkX Tutorial
  • 24. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Matplotlib A python package which emulates matlab functionality Well documented at http://matplotlib.sourceforge.net/contents.html Interfaces nicely with NetworkX Depends on Numpy which provides multidimensional array support: http://numpy.scipy.org/ We only really need it for plotting >>> import matplotlib . pyplot as plt >>> plt . plot ( range (10) , range (10) ) Evan Rosen NetworkX Tutorial
  • 25. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Backend Need to specify a backend This is the program which is responsible for either displaying or writing the plots to file does not change matplotlib plotting tools options include ‘MacOSX’ interactive plot tool for mac OS X ‘GTKAgg’ cross-platform interactive plot tool ‘PDF’ A “renderer” in PDF format ‘PS’ A “renderer” in PostScript format For more info, see: http://matplotlib.sourceforge.net/ faq/installing_faq.html#what-is-a-backend renderers are useful for working on clusters because they don’t require a windowing system Evan Rosen NetworkX Tutorial
  • 26. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Configuring Backend can be set within the script itself: import matplotlib matplotlib . use ( ‘ PDF ’) import matplotlib . pyplot as plt # need to do these steps in this order can be set in the matplotlib config file: /.matplotlib/matplotlibrc ... backend : MacOSX ... Evan Rosen NetworkX Tutorial
  • 27. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Basic Graph Drawing (with matplotlib) import networkx as nx import matplotlib . pyplot as plt >>> G = nx . path_graph (10) >>> nx . draw ( G ) >>> plt . savefig ( " path_graph . pdf " ) consult package nx.drawing for more options 7 6 8 5 9 4 3 2 1 0 Evan Rosen NetworkX Tutorial
  • 28. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Basic Data Plotting def get_phase_curve ( n ) : ps = np . arange (0.001 ,0.1 ,0.005) cs = [] for p in ps : G = nx . gnp_random_graph (n , p ) c = nx . c o n n e c t e d _ c o m p o n e n t _ s u b g r a p h s ( G ) [0]. order () cs . append ( float ( c ) /100) return cs plt . plot ( ps , get_phase_curve (100) ) plt . savefig ( ‘ phase . pdf ’) Evan Rosen NetworkX Tutorial
  • 29. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Phase Change Plot 1.0 0.8 0.6 0.4 0.2 0.0 0.00 0.02 0.04 0.06 0.08 0.10 Evan Rosen NetworkX Tutorial
  • 30. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Plotting Multiple Series on Same Axes Let’s add another curve plt . clf () ps = np . arange (0.001 ,0.1 ,0.005) plt . plot ( ps , get_phase_curve ( ps ,100) ) plt . plot ( ps , get_phase_curve ( ps ,200) ) plt . savefig ( ’ phase_100_200 . pdf ’) 1.0 0.8 0.6 0.4 0.2 0.0 0.00 0.02 0.04 0.06 0.08 0.10 Evan Rosen NetworkX Tutorial
  • 31. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Plotting Basics matplotlib has an internal structure much like matlab good resource: matplotlib.sourceforge.net/users/artists.html several objects involved in every plot figure top level container for all plot elements axes a specific set of axes (as in a subplot) axis a specific axis (x or y) >>> fig = plt . figure () >>> ax = fig . add_subplot (1 ,1 ,1) >>> h = ax . plot ( range (10) , range (10) ) >>> plt . show () Evan Rosen NetworkX Tutorial
  • 32. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Log Plots ps , cs = get_phase_curve (100) plt . loglog ( ps , cs ) # also see semilog plt . savefig ( ‘ phase_log_log . pdf ’) 100 10-1 10-2 -3 10 10-2 10-1 Evan Rosen NetworkX Tutorial
  • 33. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Legends each call to plt.plot returns a handle object for the series of type matplotlib.lines.Line2D to add a legend, call use method plt.legend([handles],[labels]) can control placement with keyword argument loc=[1,. . .,10] (uppper left, lower left, ...) h_100 = plt . plot ( ps , get_phase_curve (100) ) h_200 = plt . plot ( ps , get_phase_curve (200) ) plt . legend ([ h_100 , h_200 ] ,[ ‘ n =100 ’ ,‘n =200 ’ ]) Evan Rosen NetworkX Tutorial
  • 34. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Legends 1.0 n=100 n=200 0.8 0.6 0.4 0.2 0.0 0.00 0.02 0.04 0.06 0.08 0.10 Evan Rosen NetworkX Tutorial
  • 35. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Legends Can use Latex: plt . legend ([ h_100 , h_200 ] ,[ ’ $$ n =100 $$ ’ , ’ $$ n =200 $$ ’ ]) Evan Rosen NetworkX Tutorial
  • 36. Outline Installation Basic Classes Generating Graphs Analyzing Graphs Save/Load Plotting (Matplotlib) Resources NetworkX Docs http://networkx.lanl.gov/tutorial/index.html NetworkX Tutorial http://networkx.lanl.gov/contents.html Matplotlib Docs http://matplotlib.sourceforge.net/contents.html Matplotlib Tutorial http://matplotlib.sourceforge.net/users/pyplot_ tutorial.html Numpy Docs http://numpy.scipy.org/ MacPorts http://macports.org Evan Rosen NetworkX Tutorial