Python (PGX) Interpreter

Python (PGX) paragraphs start with %python-pgx and allows you to use the available PyPGX APIs.

See the Python API Reference for more information on PyPGX APIs.

Tip:

You can hover over the bottom part of a notebook paragraph and click the python_icon Add Python-PGX Paragraph icon to open a Python (PGX) paragraph instantly in the notebook.

The following variables are built-in for easier PGX interaction when using a Python paragraph:

  • session: the PgxSession object bound to your user. You can access all graphs currently loaded into memory via the session object. Note that sessions time out after a while of not being used. A new session will be created when you log back in to the notebook; thus, the underlying session ID is not always the same.

  • instance: the ServerInstance pointing to the PGX server.

  • visual_query: a helper object to convert PGQL queries into visualizable output.

  • analyst: a helper object providing access to all built-in graph analytics such as PageRank and Betweenness Centrality.

The following import is available by default on all Python (PGX) paragraphs:

import pypgx

Also, the Python (PGX) interpreter supports the following Python libraries. However, you must import these modules in order to use them in a Python (PGX) paragraph.

  • NumPy
  • scikit-learn
  • oracledb
  • Matplotlib
  • pandas
  • SciPy
  • requests
  • openpyxl

The following is an example of a Python (PGX) paragraph which runs a built-in algorithm to counts the number of triangles inside a graph:

%python-pgx
# Reference in-memory graphs by name
graph = session.get_graph("FIRST_GRAPH")
# Running an algorithm to determine the number of triangles in a graph
analyst.count_triangles(graph, True)

You can also define new helper classes/functions inside Python paragraphs. For example:

%python-pgx
import math
# Define helper classes/functions
class Functions:
    def haversine (lat1, lon1, lat2, lon2):
       delta_lon = (lon2 - lon1) * math.pi/180
       delta_lat = (lat2 - lat1) * math.pi/180
       a = math.pow(math.sin(delta_lat/2),2) + math.cos(lat1 * math.pi/180) * math.cos(lat2 * math.pi / 180) * math.pow(math.sin(delta_lon / 2), 2)
       c = 2 * math.asin(math.sqrt(a))
       r = 6371 #  Radius of the Earth in kilometers. Use 3956 for miles
       return c * r
Functions.haversine(30.26, 97.74, 48.13, 11.58)

Internally, the Python (PGX) interpreter operates on the same PGX session as the Java (PGX) interpreter. So, any analysis results computed in Java (PGX) paragraphs are available for querying in subsequent Python (PGX) paragraphs.

The following example show the PageRank values computed on a graph in a Java (PGX) paragraph. The pagerank property on the graph is then queried in the subsequent Python (PGX) paragraph.

%java-pgx
var g = session.getGraph("MY_FIRST_GRAPH")
session.createAnalyst().pagerank(g)
%python-pgx
session.execute_pgql("SELECT x.pagerank FROM MATCH (x) ON MY_FIRST_GRAPH").print()