# CUDA for Engineers: 2D Grids and Interactive Graphics

• Print
This chapter is from the book

## Application: Stability

To drive home the idea of using the flashlight app as a template for creating more interesting and useful apps, let’s do exactly that. Here we build on flashlight to create an app that analyzes the stability of a linear oscillator, and then we extend the app to handle general single degree of freedom (1DoF) systems, including the van der Pol oscillator, which has more interesting behavior.

The linear oscillator arises from models of a mechanical mass-spring-damper system, an electrical RLC circuit, and the behavior of just about any 1DoF system in the vicinity of an equilibrium point. The mathematical model consists of a single second-order ordinary differential equation (ODE) that can be written in its simplest form (with suitable choice of time unit) as x” + 2bx’ + x = 0, where x is the displacement from the equilibrium position, b is the damping constant, and the primes indicate time derivatives. To put things in a handy form for finding solutions, we convert to a system of two first-order ODEs by introducing the velocity y as a new variable and writing the first-order ODEs that give the rate of change of x and y:

As a bit of foreshadowing, everything we do from here generalizes to a wide variety of 1DoF oscillators by just plugging other expressions in for f(x, y, t, ...) on the right-hand side of the y-equation. While we can write analytical solutions for the linear oscillator, here we focus on numerical solutions using finite difference methods that apply to the more general case. Finite difference methods compute values at discrete multiples of the time step dt (so we introduce tk = k * dt, xk = x(tk), and yk = y(tk) as the relevant variables) and replace exact derivatives by difference approximations; that is, x′ → (xk+1xk) / dt, y′ → (yk+1yk) / dt. Here we apply the simplest finite difference approach, the explicit Euler method, by substituting the finite difference expressions for the derivatives and solving for the new values at the end of the time step, xk+1 and yk+1, in terms of the previous values at the beginning of a time step, xk and yk, to obtain:

We can then choose an initial state {xo, yo} and compute the state of the system at successive time steps.

We’ve just described a method for computing a solution (a sequence of states) arising from a single initial state, and the solution method is completely serial: Entries in the sequence of states are computed one after another.

However, stability depends not on the solution for one initial state but on the solutions for all initial states. For a stable equilibrium, all nearby initial states produce solutions that approach (or at least don’t get further from) the equilibrium. Finding a solution that grows away from the equilibrium indicates instability. For more information on dynamics and stability, see 7,8.

It is this collective-behavior aspect that makes stability testing such a good candidate for parallelization: By launching a computational grid with initial states densely sampling the neighborhood of the equilibrium, we can test the solutions arising from the surrounding initial states. We’ll see that we can compute hundreds of thousands of solutions in parallel and, with CUDA/OpenGL interop, see and interact with the results in real time.

In particular, we’ll choose a grid of initial states that regularly sample a rectangle centered on the equilibrium. We’ll compute the corresponding solutions and assign shading values based on the fractional change in distance, dist_r (for distance ratio) from the equilibrium during the simulation. To display the results, we’ll assign each pixel a red channel value proportional to the distance ratio (and clipped to [0, 255]) and a blue channel value proportional to the inverse distance ratio (and clipped). Initial states producing solutions that are attracted to the equilibrium (and suggest stability) are dominated by blue, while initial states that produce solutions being repelled from the equilibrium are dominated by red, and the attracting/repelling transition is indicated by equal parts of blue and red; that is, purple.

The result shown in the graphics window will then consist of the equilibrium (at the intersection of the horizontal x-axis and the vertical y-axis shown using the green channel) on a field of red, blue, or purple pixels. Figure 4.3 previews a result from the stability application with both attracting and repelling regions.

We now have a plan for producing a stability image for a single system, but we will also introduce interactions so we can observe how the stability image changes for different parameter values or for different systems.

With the plan for the kernel and the interactions in mind, we are ready to look at the code. As promised, the major changes from the flashlight app involve a new kernel function (and a few supporting functions), as shown in Listing 4.10, and new interactivity specifications, as shown in Listing 4.11.

#### Listing 4.10 stability/kernel.cu

``````  1 #include "kernel.h"
2 #define TX 32
3 #define TY 32
4 #define LEN 5.f
5 #define TIME_STEP 0.005f
6 #define FINAL_TIME 10.f
7
8 // scale coordinates onto [-LEN, LEN]
9 __device__
10 float scale(int i, int w) { return 2*LEN*(((1.f*i)/w) - 0.5f); }
11
12 // function for right-hand side of y-equation
13 __device__
14 float f(float x, float y, float param, float sys) {
15   if (sys == 1) return x - 2*param*y; // negative stiffness
16   if (sys == 2) return -x + param*(1 - x*x)*y; //van der Pol
17   else return -x - 2*param*y;
18 }
19
20 // explicit Euler solver
21 __device__
22 float2 euler(float x, float y, float dt, float tFinal,
23              float param, float sys) {
24   float dx = 0.f, dy = 0.f;
25   for (float t = 0; t < tFinal; t += dt) {
26     dx = dt*y;
27     dy = dt*f(x, y, param, sys);
28     x += dx;
29     y += dy;
30   }
31   return make_float2(x, y);
32 }
33
34 __device__
35 unsigned char clip(float x){ return x > 255 ? 255 : (x < 0 ? 0 : x); }
36
37 // kernel function to compute decay and shading
38 __global__
39 void stabImageKernel(uchar4 *d_out, int w, int h, float p, int s) {
40   const int c = blockIdx.x*blockDim.x + threadIdx.x;
41   const int r = blockIdx.y*blockDim.y + threadIdx.y;
42   if ((c >= w) || (r >= h)) return; // Check if within image bounds
43   const int i = c + r*w; // 1D indexing
44   const float x0 = scale(c, w);
45   const float y0 = scale(r, h);
46   const float dist_0 = sqrt(x0*x0 + y0*y0);
47   const float2 pos = euler(x0, y0, TIME_STEP, FINAL_TIME, p, s);
48   const float dist_f = sqrt(pos.x*pos.x + pos.y*pos.y);
49   // assign colors based on distance from origin
50   const float dist_r = dist_f/dist_0;
51   d_out[i].x = clip(dist_r*255); // red ~ growth
52   d_out[i].y = ((c == w/2) || (r == h/2)) ? 255 : 0; // axes
53   d_out[i].z = clip((1/dist_r)*255); // blue ~ 1/growth
54   d_out[i].w = 255;
55 }
56
57 void kernelLauncher(uchar4 *d_out, int w, int h, float p, int s) {
58   const dim3 blockSize(TX, TY);
59   const dim3 gridSize = dim3((w + TX - 1)/TX, (h + TY - 1)/TY);
60   stabImageKernel<<<gridSize, blockSize>>>(d_out, w, h, p, s);
61 }``````

Here is a brief description of the code in kernel.cu. Lines 1–6 include kernel.h and define constant values for thread counts, the spatial scale factor, and the time step and time interval for the simulation. Lines 8–35 define new device functions that will be called by the kernel:

• scale() scales the pixel values onto the coordinate range [-LEN, LEN].
• f() gives the rate of change of the velocity. If you are interested in studying other 1DoF oscillators, you can edit this to correspond to your system of interest. In the sample code, three different versions are included corresponding to different values of the variable sys.

• The default version with sys = 0 is the damped linear oscillator discussed above.
• Setting sys = 1 corresponds to a linear oscillator with negative effective stiffness (which may seem odd at first, but that is exactly the case near the inverted position of a pendulum).
• Setting sys = 2 corresponds to a personal favorite, the van der Pol oscillator, which has a nonlinear damping term.
• euler() performs the simulation for a given initial state and returns a float2 value corresponding to the location of the trajectory at the end of the simulation interval. (Note that the float2 type allows us to bundle the position and velocity together into a single entity. The alternative approach, passing a pointer to memory allocated to store multiple values as we do to handle larger sets of output from kernel functions, is not needed in this case.)

Lines 34–35 define the same clip() function that we used in the flashlight app, and the definition of the new kernel, stabImageKernel(), starts on line 38. Note that arguments have been added for the damping parameter value, p, and the system specifier, s. The index computation and bounds checking in lines 40–43 is exactly as in distanceKernel() from the flashlight app. On lines 44–45 we introduce {x0, y0} as the scaled float coordinate values (which range from –LEN to LEN) corresponding to the pixel location and compute the initial distance, dist_0, from the equilibrium point at the origin. Line 47 calls euler() to perform the simulation with fixed time increment TIME_STEP over an interval of duration FINAL_TIME and return pos, the state the simulated trajectory has reached at the end of the simulation. Line 50 compares the final distance from the origin and to the initial distance. Lines 51–54 assign shading values based on the distance comparison with blue indicating decay toward equilibrium (a.k.a. a vote in favor of stability) and red indicating growth away from equilibrium (which vetoes other votes for stability). Line 52 uses the green channel to show the horizontal x-axis and the vertical y-axis which intersect at the equilibrium point.

Lines 57–61 define the revised wrapper function kernelLauncher() with the correct list of arguments and name of the kernel to be launched.

#### Listing 4.11 stability/interactions.h

``````  1 #ifndef INTERACTIONS_H
2 #define INTERACTIONS_H
3 #define W 600
4 #define H 600
5 #define DELTA_P 0.1f
6 #define TITLE_STRING "Stability"
7 int sys = 0;
8 float param = 0.1f;
9 void keyboard(unsigned char key, int x, int y) {
10   if (key == 27)  exit(0);
11   if (key == '0') sys = 0;
12   if (key == '1') sys = 1;
13   if (key == '2') sys = 2;
14   glutPostRedisplay();
15 }
16
17 void handleSpecialKeypress(int key, int x, int y) {
18   if (key == GLUT_KEY_DOWN) param -= DELTA_P;
19   if (key == GLUT_KEY_UP)   param += DELTA_P;
20   glutPostRedisplay();
21 }
22
23 // no mouse interactions implemented for this app
24 void mouseMove(int x, int y) { return; }
25 void mouseDrag(int x, int y) { return; }
26
27 void printInstructions() {
28   printf("Stability visualizer\n");
29   printf("Use number keys to select system:\n");
30   printf("\t0: linear oscillator: positive stiffness\n");
31   printf("\t1: linear oscillator: negative stiffness\n");
32   printf("\t2: van der Pol oscillator: nonlinear damping\n");
33   printf("up/down arrow keys adjust parameter value\n\n");
34   printf("Choose the van der Pol (sys=2)\n");
35   printf("Keep up arrow key depressed and watch the show.\n");
36 }
37
38 #endif``````

The description of the alterations to interactions.h, as shown in Listing 4.11, is also straightforward. To the #define statements that set the width W and height H of the image, we add DELTA_P for the size of parameter value increments. Lines 7–8 initialize variables for the system identifier sys and the parameter value param, which is for adjusting the damping value.

There are a few keyboard interactions: Pressing Esc exits the app; pressing number key 0, 1, or 2 selects the system to simulate; and the up arrow and down arrow keys decrease or increase the damping parameter value by DELTA_P. There are no planned mouse interactions, so mouseMove() and mouseDrag() simply return without doing anything.

Finally, there are a couple details to take care of in other files:

• kernel.h contains the prototype for kernelLauncher(), so the first line of the function definition from kernel.cu should be copied and pasted (with a colon terminator) in place of the old prototype in flashlight/kernel.h.
• A couple small changes are also needed in main.cpp:

• The argument list for the kernelLauncher() call in render() has changed, and that call needs to be changed to match the syntax of the revised kernel.
• render() is also an appropriate place for specifying information to be displayed in the title bar of the graphics window. For example, the sample code displays an application name (“Stability”) followed by the values of param and sys. Listing 4.12 shows the updated version of render() with the title bar information and updated kernel launch call.

#### Listing 4.12 Updated render() function for stability/main.cpp

``````  1 void render() {
2   uchar4 *d_out = 0;
3   cudaGraphicsMapResources(1, &cuda_pbo_resource, 0);
4   cudaGraphicsResourceGetMappedPointer((void **)&d_out, NULL,
5                                        cuda_pbo_resource);
6   kernelLauncher(d_out, W, H, param, sys);
7   cudaGraphicsUnmapResources(1, &cuda_pbo_resource, 0);
8   // update contents of the title bar
9   char title[64];
10   sprintf(title, "Stability: param = %.1f, sys = %d", param, sys);
11   glutSetWindowTitle(title);
12 }``````

### Running the Stability Visualizer

Now that we’ve toured the relevant code, it is time to test out the app. In Linux, the Makefile for building this project is the same as the Makefile for the flashlight app that was provided in Listing 4.9. In Visual Studio, the included library files and the project settings are the same as described in flashlight. When you build and run the application, two windows should open: the usual command window showing a brief summary of supported user inputs and a graphics window showing the stability results. The default settings specify the linear oscillator with positive damping, which you can verify from the title bar that displays Stability: param = 0.1, sys = 0, as shown in Figure 4.4(a). Since all solutions of an unforced, damped linear oscillator are attracted toward the equilibrium, the graphics window should show the coordinate axes on a dark field, indicating stability. Next you might test the down arrow key. A single press reduces the damping value from 0.1 to 0.0 (which you should be able to verify in the title bar), and you should see the field changes from dark to moderately bright, as shown in Figure 4.4(b). The linear oscillator with zero damping is neutrally stable (with sinusoidal oscillations that remain near, but do not approach, the equilibrium). The explicit Euler ODE solver happens to produce small errors that systematically favor repulsion from the origin, but the color scheme correctly indicates that all initial states lead to solutions that roughly maintain their distance from the equilibrium. Another press of the down arrow key changes the damping parameter value to −0.1, and the bright field shown in Figure 4.4(c) legitimately indicates instability.

Now press the 1 key to set sys = 1 corresponding to a system with negative effective stiffness, and increase the damping value. You should now see the axes on a bright field with a dark sector (and moderately bright transition regions), as shown in Figure 4.5. In this case, some solutions are approaching the equilibrium, but almost all initial conditions lead to solutions that grow away from the equilibrium, which is unstable.

Setting the damping param = 0.0 and sys = 2 brings us to the final case in the example, the van der Pol oscillator. With param = 0.0, this system is identical to the undamped linear oscillator, so we again see the equilibrium in a moderately bright field. What happens when you press the up arrow key to make the damping positive? The equilibrium is surrounded by a bright region, so nearby initial states produce solutions that are repelled and the equilibrium is unstable. However, the outer region is dark, so initial states further out produce solutions that are attracted inwards. There is no other equilibrium point to go to, so where do all these solutions end up? It turns out that there is a closed, attracting loop near the shading transition corresponding to a stable period motion or “limit cycle” (Figure 4.6).

Note that the results of this type of numerical stability analysis should be considered as advisory. The ODE solver is approximate, and we only test a few hundred thousand initial states, so it is highly likely but not guaranteed that we did not miss something.

Before we are done, you might want to press and hold the up arrow key and watch the hundreds of thousands of pixels in the stability visualization change in real time. This is something you are not likely to be able to do without the power of parallel computing.

• 🔖 Save To Your Account

### InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

## Overview

Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

## Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

### Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

### Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

### Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

### Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

### Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

### Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

## Other Collection and Use of Information

### Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

### Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

### Do Not Track

This site currently does not respond to Do Not Track signals.

## Security

Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

## Children

This site is not directed to children under the age of 13.

## Marketing

Pearson may send or direct marketing communications to users, provided that

• Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
• Such marketing is consistent with applicable law and Pearson's legal obligations.
• Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
• Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

## Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

## Choice/Opt-out

Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

## Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

## Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

## Sharing and Disclosure

Pearson may disclose personal information, as follows:

• As required by law.
• With the consent of the individual (or their parent, if the individual is a minor)
• In response to a subpoena, court order or legal process, to the extent permitted or required by law
• To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
• In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
• To investigate or address actual or suspected fraud or other illegal activities
• To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
• To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
• To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

## Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020