Did you know that it’s simple to use some truly excellent Python libraries to boost your Delphi app development on Windows? These libraries are very easy to use and produce wonderful ways to produce graphs and network visualization.
Adding Python to your Delphi code toolbox can enhance your app development by bringing in new capabilities that allow you to provide innovative and powerful solutions to your app’s users, combining the best of Python with the supreme low-code and unparalleled power of native Windows development that Delphi provides.
Are you looking for how to build a GUI for graph and network visualization library?
You can create, manipulate, and study the structure, dynamics, and functions of complex networks with NetworkX on Delphi. This article will demonstrate how to create a Delphi GUI app dedicated to the NetworkX library.
Watch this video by Jim McKeeth for a thorough explanation of why you can love both Delphi and Python at the same time:
Get to know with Embarcadero Python Ecosystem
Before we dive in more into the NetworkX4D GUI prototype, let’s get to know first about Embarcadero Python Ecosystem:
And here are the Embarcadero Python Ecosystem licenses:
Which you can know more about them from the following webinars by Jim McKeeth:
What do we mean by graphs and network visualization?
In mathematics, and more specifically in graph theory, a graph is a structure consisting of a set of objects, some of which are “related.”
The objects correspond to mathematical abstractions known as vertices (also known as nodes or points), and each pair of related vertices is known as an edge (also called a link or line).
A graph is typically represented diagrammatically as a set of dots or circles for the vertices, joined by lines or curves for the edges. Graphs are one of the topics covered by discrete mathematics.
Graphs are the fundamental subject of graph theory. J. J. Sylvester coined the term “graph” in this context in 1878, referring to a direct relationship between mathematics and chemical structure (what he called chemico-graphical image).
Networks are all around us, and they are extremely important in our lives. Communication networks, social media networks, biological networks, and so on are all examples of networks.
Here are to name of a few examples of graphs and network visualizations:
The World’s social networks shown as a network graph
A protein interaction network
Coauthorship network of 2014 breaking news articles
What is the NetworkX graphs and network visualization Library?
NetworkX is a Python package for creating, manipulating, and studying complex networks’ structure, dynamics, and functions.
- tools for studying the structure and dynamics of social, biological, and infrastructure networks;
- a standard programming interface and graph implementation suitable for a wide range of applications;
- a rapid development environment for collaborative, multidisciplinary projects;
- an interface to existing numerical algorithms and code written in C, C++, and FORTRAN; and
- the ability to work with large nonstandard data sets without difficulty.
You can use NetworkX to load and save networks in standard and nonstandard data formats, generate many different types of random and classic networks, analyze network structure, build network models, design new network algorithms, draw networks, and much more.
What are the prerequisites for the NetworkX Library?
You will need Graphviz and PyGraphviz for some advanced graph and network layout and visualizations. We recommend you to install them with conda or Anaconda Distribution, instead of regular Python, due to some complexities and conflicts you will face if you install them in regular Python distribution.
Prerequisites 1: Graphviz
You can easily install Graphviz with this conda install command:
conda install –c anaconda graphviz
Excerpt of conda install progress for graphviz:
Prerequisites 2: PyGraphviz
You can easily install PyGraphviz with this conda install command:
conda install –c conda–forge pygraphviz
Excerpt of conda install progress for pygraphviz:
How do I get and install the NetworkX Library?
You can easily install NetworkX with pip:
Or, you can install it with conda install to avoid complexities and conflicts between required libraries, as we tell you in the previous section:
conda install –c anaconda networkx
How do I install Python4Delphi?
How do I build a Delphi GUI for the NetworkX graphs and network visualization library?
Our project’s user interface structure is as follows:
Here is the list of Components used in the NetworkX4D demo app:
Memo1.Lines.LoadFromFile(ExtractFilePath(ParamStr(0)) + ‘networkxApp.py’);
You can change the “networkxApp.py” with any NetworkX script you want, or you can load your NetworkX scripts at runtime, by clicking the “Load script…” like we will show you in the next Demo Sections.
How to create graphs and network visualization using NetworkX in a Delphi app?
This post will walk you through the process of integrating Python NetworkX into a Delphi-created Windows app. As a bonus, we will show you five use cases.
Highly recommended practice:
1. This GUI was created by modifying Python4Delphi Demo34, which allows us to change the Python version in the runtime (this will save you from the seemingly complicated dll issues).
2. Add “Jpeg” to the top of our UnitNetworkX4D.pas code’s Uses-list. We must do so because Delphi will not understand the JPG format otherwise. It should work with this change.
After that, the above modification should look like this:
We can also load JPG images into our TImage.
3. Set up the following paths in your Environment Variable:
Set up the following paths if you’re using the Anaconda Python distribution:
4. To show plotting results, you must use Matplotlib outside of the “normal” command-line process. To do this, add the following lines to all of your Python code:
import matplotlib.pyplot as plt
We strongly advise you to name your image output as “networkxPlot.jpg” in order for it to load automatically on your GUI after you click the “Show plot” button.
5. Set MaskFPUExceptions(True); to the UnitNetworkX4D.pas file to avoid Delphi raising an exception when floating operations result in +/- infinity (e.g. division by zero), which is caused by incompatibility with a number of Python libraries such as NumPy, SciPy, pandas, and Matplotlib.
One of the best features of this NetworkX4D Demo GUI is that you can choose your preferred Python version, which is interchangeable.
6. As we’ve already tested this GUI for regular Python and Anaconda Python distribution, this NetworkX4D GUI works better for Anaconda Python distribution. The required Graphviz and PyGraphviz packages would throw some complicated errors and conflicts when we try to install them on the regular Python distribution
7. Then, click the “Execute” button to run the very basic example of NetworkX to draw a simple graph (the Python code is already called inside the UnitNetworkX4D.pas file), and then click the “Show plot” button to display the figure. Here is the output:
Example 1 of graphs and network visualization: Simple graph
This example is similar to the most basic NetworkXD we have mentioned earlier. This example would draw a simple graph with a manual layout.
Here is the default example embedded on the NetworkX4D GUI:
This basic/default example basically loads and executes the embedded networkxApp.py script.
Example 2 of graphs and network visualization: Degree analysis
This example demonstrates how to visualize the degree distribution of nodes using two common techniques: A degree-rank plot and a degree histogram.
In this example, a random Graph with 100 nodes is generated. The degree of each node is calculated, and a figure is generated that shows three things:
1. The connected component subgraph
2. the Graph’s degree-rank plot, and
3. The degree histogram
To try this example, load the demo02_degreeAnalysis.py at runtime by clicking the “Load script…” button, and then “Execute”. Here is the output:
Example 3 of graphs and network visualization: Employ the PyGraphviz layout – Atlas of all connected graphs with up to 6 nodes
In the third example, we will visualize the atlas of all connected graphs with up to 6 nodes.
This example uses Graphviz via PyGraphviz.
The image should show 142 graphs. We don’t plot the empty graph or the single node graph (142 is the sum of values 2 to n=6 in sequence. Source: oeis.org/A001349).
Load the demo03_atlasOfAllConnectedGraphsUpTo6Nodes.py at runtime by clicking the “Load script…” button, and then “Execute”, to get the output as shown above.
Example 4 of graphs and network visualization: Employ the Graphviz and PyGraphviz layout – Draw a circular tree
A circular tree, radial tree, or radial map is a method of displaying a tree structure (e.g., a tree data structure) in a radial fashion (expands outwards).
It is one of several methods for visually displaying a tree, with examples dating back to the early 20th century. Circular tree is a type of information graphic in use.
Load the demo04_circularTree.py at runtime by clicking the “Load script…” button, and then “Execute”, to get the output as shown above.
Example 5 of graphs and network visualization: Solve a real AI problem – This is how to solve the traveling salesman problem
The traveling salesman problem is a very popular technology interview question because it requires the person answering it to understand some subtle difficulties that occur in real-life real-world situations. In this example, we will show how to use NetworkX4D to solve the traveling salesman problem. It will draw the solution to the traveling salesman problem and print out the route taken by the traveler.
The traveling salesman problem (TSP) is an algorithmic problem in which the goal is to find the shortest path between a set of points and locations that must be visited. The cities that a salesperson might visit are represented by the points in the problem statement. The salesman’s goal is to keep travel expenses and distance traveled to a minimum.
TSP, which focuses on optimization, is frequently used in computer science to find the most efficient route for data to travel between different nodes.
The function used to generate the solution is christofides, which calculates the route of the nodes that the traveler must take to minimize the total cost given a set of nodes.
The Christofides algorithm, also known as the Christofides-Serdyukov algorithm, is a method for finding approximate solutions to the traveling salesman problem when the distances form a metric space (they are symmetric and obey the triangle inequality). It is named after Nicos Christofides and Anatoliy I. Serdyukov, who discovered it independently in 1976. It is an approximation algorithm that ensures that its solutions are within 3/2 of the optimal solution length.
Here is the result of our demonstration:
Load the demo05_travelingSalesmanProblem.py at runtime by clicking the “Load script…” button, and then “Execute”, to get the output as shown above. The output not only draws the path taken by the salesman, but also prints out the route of the traveler.
Such a powerful graph and network visualization tool, right?
Visit this repository for complete source code.
Are you ready to try these NetworkX4D graphs and network visualization demos?
Congratulations, now you have learned a lot about NetworkX: A powerful graph and network visualization library, and how you can use Delphi to create a simple yet powerful GUI for it! We have learned a few examples and use cases, and now you can explore them to boost your productivity in creating your own graph and network visualization apps.
For a more Pythonic point of view, you can refer to this article:
and if you are looking for other powerful data visualization libraries, please read this article:
Download a free trial of RAD Studio Delphi today and try out these examples for yourself.
References & further readings
Books & papers
Bratanic, T. (2021). Graphs and network science: An introduction. Manning Publications.
Goodrich, M. T., & Tamassia, R. (2015). Algorithm design and applications (p. 349). Hoboken: Wiley.
Gross, J. L., & Yellen, J. (2004). Handbook of graph theory. CRC Press. Boca Raton.
J. J. Sylvester (February 7, 1878). Chemistry and algebra. Nature, 17: 284
Trudeau, R. J. (2013). Introduction to graph theory. Courier Corporation.
Why not try out these graphs and network visualization examples for yourself? Download a free trial of RAD Studio Delphi and start coding today!