Do you want to build a GUI App with Scientific Computation capabilities using Python Script Writer? This post will help you understand how to use SciPy Python Library using Python4Delphi in the Delphi/C++ application. SciPy is a collection of mathematical algorithms and convenience functions built on the NumPy extension of Python.
SciPy is organized into sub-packages covering different scientific computing domains such as cluster, special, integrate, optimize, interpolate, linalg etc.
Python for Delphi (P4D) is a set of free components that wrap up the Python DLL into Delphi and Lazarus (FPC). They let you easily execute Python scripts, create new Python modules and new Python types. You can use Python4Delphi in a number of different ways such as:
- Create a Windows GUI around your existing Python app.
- Add Python scripting to your Delphi Windows apps.
- Add parallel processing to your Python apps through Delphi threads.
- Enhance your speed-sensitive Python apps with functions from Delphi for more speed.
Table of Contents
What are the prerequisites for using SciPy and Delphi?
- If not python and Python4Delphi is not installed on your machine, Check this how to run a simple python script in Delphi application using Python4Delphi sample app
- Open windows open command prompt, and type pip install -U SciPy to install SciPy. For more info for Installing Python Modules check here
- First, run the Demo1 project for executing Python script in Python for Delphi. Then load the SciPy sample script in the Memo1 field and press the Execute Script button to see the result. On Clicking Execute Button the script strings are executed using the below code. Go to GitHub to download the Demo1 source.
1 2 3 4 |
procedure TForm1.Button1Click(Sender: TObject); begin PythonEngine1.ExecStrings( Memo1.Lines ); end; |
What does the example of using the Scipy Python Library look like?
Here are the Scipy Python Library sample script details. It covers some of the SciPy sub packages functions such as Bessel, Integration, Interpolation, and optimization.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
import numpy as np from scipy import special def drumhead_height(n, k, distance, angle, t): kth_zero = special.jn_zeros(n, k)[-1] return np.cos(t) * np.cos(n*angle) * special.jn(n, distance*kth_zero) theta = np.r_[0:2*np.pi:50j] radius = np.r_[0:1:50j] x = np.array([r * np.cos(theta) for r in radius]) y = np.array([r * np.sin(theta) for r in radius]) z = np.array([drumhead_height(1, 1, r, theta, 0.5) for r in radius]) #show in the matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm fig = plt.figure() ax = Axes3D(fig, rect=(0, 0.05, 0.95, 0.95)) ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap='RdBu_r', vmin=-0.5, vmax=0.5) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_xticks(np.arange(-1, 1.1, 0.5)) ax.set_yticks(np.arange(-1, 1.1, 0.5)) ax.set_zlabel('Z') plt.show() #Integration import scipy.integrate as integrate import scipy.special as special result = integrate.quad(lambda x: special.jv(2.5,x), 0, 4.5) print(result) #Optimization from scipy.optimize import minimize def rosen(x): """The Rosenbrock function""" return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0) x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2]) res = minimize(rosen, x0, method='nelder-mead', options={'xatol': 1e-8, 'disp': True}) print(res.x) #interpolation from scipy.interpolate import interp1d x = np.linspace(0, 10, num=11, endpoint=True) y = np.cos(-x**2/9.0) f = interp1d(x, y) f2 = interp1d(x, y, kind='cubic') xnew = np.linspace(0, 10, num=41, endpoint=True) import matplotlib.pyplot as plt plt.plot(x, y, 'o', xnew, f(xnew), '-', xnew, f2(xnew), '--') plt.legend(['data', 'linear', 'cubic'], loc='best') plt.show() |
What does the SciPy.Special subpackage do?
- The main feature of the
scipy.special
package is the definition of numerous special functions of mathematical physics. Available functions include airy, elliptic, bessel, gamma, beta, hypergeometric, parabolic cylinder, mathieu, spheroidal wave, struve, and kelvin. - Bessel functions are a family of solutions to Bessel’s differential equation with real or complex order alpha. These functions arise in wave propagation problems, such as the vibrational modes of a thin drum head. Here is an example of a circular drum head anchored at the edge:
What is the SciPy.Integrate Subpackage?
- The
scipy.integrate
sub-package provides several integration techniques including an ordinary differential equation integrator. - The function quad is provided to integrate a function of one variable between two points. For example, to integrate a bessel function
jv(2.5, x)
along the interval [0,4.5].This could be computed usingquad
and the result as shown in Memo output.
What is the SciPy.Optimize subpackage and what does it do?
- The
scipy.optimize
package provides several commonly used optimization algorithms. To demonstrate the minimization function, consider the problem of minimizing the Rosenbrock function of N variables: The minimum value of this function is 0 which is achieved when xi=1. - The
minimize
routine is used with the Nelder-Mead simplex algorithm (selected through themethod
parameter) and the result as shown in Memo output.
What is the function of the SciPy.Interpolate subpackage?
- The
interp1d
class inscipy.interpolate
is a convenient method to create a function based on fixed data points, which can be evaluated anywhere within the domain defined by the given data using linear interpolation. This example demonstrates its use, for linear and cubic spline interpolation:
Note: Samples used for demonstration were picked from here with only the difference of printing the outputs. You can check the APIs and some more samples from the same place.
You have read the quick overview of SciPy library, download this library from here and use user-friendly scientific computation functions in your applications. Check out Python4Delphi and easily build Python GUIs for Windows using Delphi.